Running Two AI Agents on One Machine: Isolation, Routing, and Governance

    Two AI agents can share the same language model yet behave very differently: one may favor explanations over action, while another keeps executing until it exhausts its budget. This article outlines a single-machine architecture that combines a shared model gateway with isolated runtimes, task-based routing, explicit permissions, execution budgets, and centralized observability. It explains how to separate planning from execution without mixing sessions, exposing credentials, or losing control of long-running tasks.

    Running Two AI Agents on One Machine: Isolation, Routing, and Governance

    1. Why the Same Model Can Produce Two Behavioral Extremes

    Teams often evaluate or deploy several AI agents at once. Even when those agents call the same large language model, their behavior can differ significantly:

    • Explanation-oriented agents repeatedly emphasize environmental limitations, sandbox restrictions, or insufficient permissions. They tend to propose solutions rather than execute them, leaving users to push tasks beyond plausible descriptions.
    • Long-running execution agents keep calling tools and breaking work into subtasks. Once started, they may continue until they time out or are interrupted externally.

    These differences can look like differences in model capability. More often, however, they reflect differences in the agent runtime: system prompts, available tools, permission boundaries, loop controls, timeout policies, acceptance criteria, context management, and human approval mechanisms.

    Running both agents against the same model, with different entry points available as needed, is therefore a practical engineering approach. A shared model gateway, isolated runtimes, and unified governance can turn contrasting behavior into capabilities that are schedulable, observable, and bounded.

    This article does not compare specific products. It addresses a general deployment problem: how to run multiple agents on one machine, share a model service, isolate sessions and workspaces, and apply different execution policies to different tasks.

    2. Architecture: One Model Gateway, Multiple Agent Runtimes

    The recommended architecture has four main layers, supported by shared infrastructure:

    1. User entry points
    2. Browser interface Mobile messaging
    3. | |
    4. v v
    5. Channel adapters
    6. Session mapping, identity verification, message formatting
    7. | |
    8. v v
    9. Agent runtimes
    10. Agent A: planning/advisory Agent B: execution/verification
    11. Separate process, port, Separate process, port,
    12. and workspace and workspace
    13. \ /
    14. \ /
    15. v v
    16. Shared model gateway
    17. Authentication, quotas, routing, auditing, timeout control
    18. |
    19. v
    20. Model inference service
    21. Shared governance and infrastructure
    22. Tool sandboxes, object storage, logs, monitoring and alerts,
    23. approval workflows, secret management

    The goal is not simply to install two applications. The architecture should meet five requirements:

    1. Unified model access: Both agents use the same gateway, avoiding separate credentials, inconsistent billing records, and fragmented audit logs.
    2. Runtime isolation: Agents do not share global dependencies, temporary directories, ports, or session context.
    3. Distinct behavior profiles: Role prompts, tool permissions, timeout budgets, and acceptance criteria separate planning and explanation from execution and verification.
    4. Centralized governance: Logs, approvals, metrics, credentials, and resource limits are managed consistently.
    5. Multiple entry points: Browser interfaces, mobile messaging, command-line tools, and other channels remain independent of the underlying agent implementation.

    The key distinction is simple: sharing a model does not mean sharing a session; running on one machine does not mean running without isolation; and two entry points do not require two disconnected systems.

    3. Implementing Single-Machine Coexistence

    3.1 Isolate Processes, Ports, and Workspaces

    Run the agents as separate processes, listening on different local ports and using separate working and log directories. If one agent fails during an upgrade, accumulates excessive context, or gets stuck on a task, the other should remain usable.

    The following configuration illustrates the separation:

    1. agents:
    2. - name: planner
    3. entry: browser
    4. workdir: /srv/agents/planner
    5. port: 18081
    6. model_ref: shared-gateway
    7. profile: consultative
    8. max_runtime: 15m
    9. default_permission: read-only
    10. - name: executor
    11. entry: mobile-message
    12. workdir: /srv/agents/executor
    13. port: 18082
    14. model_ref: shared-gateway
    15. profile: action-oriented
    16. max_runtime: 25m
    17. default_permission: workspace-write
    18. model_gateway:
    19. endpoint: http://127.0.0.1:19000/v1
    20. audit_log: /var/log/agents/model-calls.log
    21. per_agent_quota: true

    These values are illustrative rather than universal requirements. The underlying principles are:

    • Give each agent a separate working directory to prevent concurrent writes to the same temporary files.
    • Use separate session databases or namespaces to prevent context leakage.
    • Assign fixed, monitored ports to avoid conflicts after restarts.
    • Keep configuration under version control, including changes to role prompts and tool inventories.
    • Include agent identifiers in logs so model requests and tool actions can be attributed correctly.

    3.2 Use a Shared Model Gateway

    Storing model credentials separately in each agent creates three problems: credential proliferation, costs that are difficult to audit, and inconsistent model versions. A lightweight model gateway provides a more manageable boundary. All agents access the model through that gateway.

    At a minimum, the gateway should:

    • Record agent identifiers, session identifiers, model requests, and timestamps in audit logs.
    • Enforce rate limits and budgets by agent or user.
    • Keep model versions consistent to reduce untracked behavioral drift.
    • Propagate timeout and cancellation signals to both the model service and the agent.
    • Redact sensitive fields.
    • Allow task-specific parameter choices while keeping changes traceable.

    Illustrative pseudocode:

    1. handle_model_request(request):
    2. agent = authenticate(request.agent_id)
    3. quota = check_quota(agent, request.user_id)
    4. if not quota.allowed:
    5. return error("quota exceeded")
    6. sanitized = redact_secrets(request.messages)
    7. trace = create_trace(agent.id, request.session_id)
    8. log_request(trace, sanitized, request.tool_schema_version)
    9. response = forward_to_model(
    10. messages=sanitized,
    11. model_alias=request.model_alias,
    12. timeout=request.timeout,
    13. stop_condition=request.stop_condition
    14. )
    15. log_response(trace, response)
    16. return response

    The gateway is more than a request proxy. It turns model calls into governed events. When multiple agents share one model, this makes it possible to identify which role initiated a request, through which channel, for which task, with what budget consumption and outcome.

    3.3 Separate Sessions and Memory

    When two entry points serve the same user, it may seem natural to share memory because both agents use the same model. That assumption needs care. Sharing a knowledge base can be appropriate; sharing raw session context should be much more restricted.

    Use a session key with multiple dimensions:

    1. agent_id : channel : user_id : thread_id

    For example:

    1. planner:browser:user-001:thread-42
    2. executor:mobile:user-001:thread-17

    This separation ensures that:

    • A browser planning session is not automatically inherited by a mobile execution session.
    • Tool-call histories remain distinct.
    • Agents can retrieve from a shared knowledge base while filtering results by permission.
    • A user-requested handoff follows an explicit process, such as creating a task summary and acceptance checklist before transferring work.

    The appropriate unit of shared memory is a structured artifact, not an unfiltered conversation. Useful handoff artifacts include the task description, constraints, completed actions, supporting evidence, unresolved questions, and acceptance results.

    3.4 Route Tasks Across Multiple Channels

    Browser and mobile interfaces serve different interaction needs. A browser is suitable for long-form content, file diffs, logs, and interactive approvals. Mobile messaging is better suited to quick task initiation, concise updates, and simple confirmations.

    A practical default mapping is:

    Entry point Primary use Suggested default role Output requirements
    Browser interface Design discussions, code reviews, long-task orchestration Planning/advisory Decision summaries, file diffs, and approval items
    Mobile messaging Quick questions, execution updates, status notifications Execution/verification Short summaries, suggested next steps, and exception alerts
    Command line or local scripts Automated verification and batch processing Execution Machine-readable results, exit codes, and log paths

    These defaults should not become rigid boundaries. A shared router can select an agent based on task intent and current context, regardless of the entry point.

    For example, an incomplete request can first go to the planning agent for clarification. Once acceptance criteria are established, the execution agent can take over.

    1. function dispatch(channel, user, message):
    2. profile = route_by_intent(message, channel)
    3. session = session_store.get_or_create(profile.agent_id, channel, user)
    4. task = supervisor.prepare(profile, session, message)
    5. if task.needs_clarification:
    6. return ask_user(task.questions)
    7. if task.risk_level == high:
    8. return request_approval(task.plan)
    9. return supervisor.run(task)

    4. Governing the Two Behavioral Extremes

    4.1 For Agents That Explain but Do Not Act: Require Capabilities and Evidence

    A conservative agent may repeatedly claim that its sandbox prevents execution. Common causes include:

    • System prompts emphasize restrictions without explaining permitted operations.
    • The tool inventory does not describe concrete capabilities, forcing the model to guess.
    • Network, filesystem, or command permissions are genuinely restricted, but errors are not returned to the model.
    • Missing acceptance criteria allow explanatory text to substitute for execution.
    • The agent cannot determine the current working directory, project, or environment state.

    Telling the agent to “be more proactive” is not enough. Define a capability inventory and an execution contract:

    1. Capability inventory: Provide structured information about readable and writable directories, permitted network access, available tools, and restrictions.
    2. Preflight checks: At task start, inspect the working directory, dependencies, permissions, and test entry points, then report the results.
    3. Evidence of failure: If the agent says it cannot execute, require the relevant tool call, error message, and attempted alternatives. An unsupported claim of inability is not a valid conclusion.
    4. Output contract: Require consistent fields for completed actions, verification evidence, unfinished work, and the next request.
    5. Small, verifiable steps: Break large tasks into steps that produce inspectable artifacts rather than a single long explanation.

    An example output contract:

    1. Status: Complete / Partially complete / Blocked
    2. Completed actions:
    3. - Action 1 and result summary
    4. - Action 2 and result summary
    5. Evidence:
    6. - File paths, log excerpts, test results, or command exit status
    7. Incomplete items:
    8. - Specific reasons and required permissions
    9. Suggested next steps:
    10. - No more than three

    4.2 For Agents That Keep Executing: Add Budgets, Checkpoints, and Stop Conditions

    An action-oriented agent can become trapped in an extended loop of decomposition, modification, and retries. Common causes include:

    • No explicit definition of completion.
    • Unlimited retries after tool failures.
    • Self-generated subtasks that drift away from the original goal.
    • Continuous execution without intermediate acceptance checks.
    • No limits on steps, elapsed time, or retries.

    Use both hard and soft budgets:

    • Hard budgets: Maximum runtime, tool calls, model calls, retries, and file-write volume.
    • Soft budgets: Periodic progress summaries, self-checks after a set number of steps, and instructions to save a checkpoint as limits approach.

    A supervisory loop might look like this:

    1. for step in 1..max_steps:
    2. remaining_time = deadline - now()
    3. if remaining_time <= reserve_time:
    4. return checkpoint_and_summarize()
    5. action = model.propose(session, tools, remaining_budget)
    6. if action.type == "final":
    7. return verify_and_finish(action)
    8. if action.requires_approval:
    9. approval = wait_for_human(action)
    10. if approval.rejected:
    11. log_and_stop(reason="human rejected")
    12. result = sandbox.execute(action, timeout=per_tool_timeout)
    13. trace.record(step, action, result)
    14. if no_progress(last_n_steps):
    15. return checkpoint_and_ask_for_guidance()
    16. return checkpoint_and_summarize(reason="budget exhausted")

    No-progress detection is especially important. If repeated tool calls produce no meaningful changes, new files, passing tests, or new information, the agent should stop and return a checkpoint rather than continue consuming its budget.

    5. Security Boundaries: A Sandbox Is Not Sufficient

    Running multiple agents on one machine does not automatically reduce risk. More entry points and tools can expand the attack surface.

    At a minimum, apply these controls:

    1. Least privilege: Make the planning agent read-only by default. Limit the execution agent’s writes to its designated workspace. Require human approval for high-risk actions such as deleting, overwriting, committing, or deploying.
    2. Workspace isolation: Use separate agent directories and make shared directories read-only. Use locks or a task queue when concurrent writes are necessary.
    3. Network egress controls: Specify which agents can access external networks and which are restricted to the internal model gateway and artifact storage. Treat content from unknown sources as untrusted.
    4. Credential isolation: Keep secrets in the model gateway or a secret-management component, not in prompts or agent workspaces. Provide access to external capabilities through controlled proxies.
    5. Supply-chain controls: Review tool extensions, scripts, and prompt templates. Do not dynamically load them from unverified locations.
    6. Auditing and replay: Record model calls, tool calls, approval decisions, file changes, and final outputs so sessions can be reconstructed when necessary.
    7. Resource limits: Bound CPU, memory, disk usage, concurrency, and runtime so one agent cannot overwhelm the host.

    An agent’s natural-language claim that it is “running in a sandbox” is not a security boundary. Enforcement must come from process isolation, permissions, network policies, and approval workflows. The agent’s explanation is only supporting information.

    6. Observability: Measure Complementarity Instead of Relying on Impressions

    Whether two agents actually complement each other should be validated with metrics. Track task completion, human intervention, timeout risk, and output quality.

    An example event:

    1. {
    2. "agent_id": "executor",
    3. "session_id": "user-001:mobile:thread-17",
    4. "task_type": "code-change",
    5. "step": 7,
    6. "tool": "workspace.write",
    7. "decision": "needs_approval",
    8. "duration_ms": 842,
    9. "status": "blocked",
    10. "budget_left": {
    11. "steps": 13,
    12. "seconds": 620
    13. }
    14. }

    Useful metrics include:

    • First-attempt and eventual task completion rates.
    • Average number of human interventions.
    • Tool calls and model calls per task.
    • Timeout, no-progress stop, and human cancellation rates.
    • Retry success rates after failures.
    • Average duration and cost.
    • Approval rates for high-risk operations and reasons for rejection.
    • The proportion of conclusions unsupported by evidence.

    As data accumulates, adjust role assignments by task type. The planning agent may be better suited to requirements clarification, option comparison, and risk analysis. The execution agent may be better suited to fixing tests, batch refactoring, and scripted verification.

    The agents can also participate in a three-stage workflow—plan, execute, review—rather than requiring the user to switch between them manually.

    7. Deployment and Operations

    For a single-machine deployment, use the following startup sequence:

    1. Start the model gateway and validate its configuration.
    2. Start shared logging, artifact storage, and monitoring collection.
    3. Start the planning-agent runtime.
    4. Start the execution-agent runtime.
    5. Start the browser interface and mobile messaging adapter.
    6. Run smoke tests covering model calls, read-only tool access, workspace writes, timeout termination, approval rejection, and log persistence.

    If cloud resources are used to extend the deployment, use general infrastructure categories: a container platform for agent runtimes, object storage for task artifacts, centralized logging for audit records, and monitoring and alerts for timeout rates and resource utilization.

    Where Baidu AI Cloud’s container, object storage, logging, or monitoring capabilities are selected, apply the same shared-gateway and least-privilege principles. Do not expose cloud credentials directly to agent runtimes.

    Operations should also address three details:

    • Version tracking: Record versions of the model gateway, role prompts, tool inventories, and channel adapters separately so behavioral drift can be traced to a change.
    • Independent upgrades: Upgrade one agent, observe its metrics, and then upgrade the other. Simultaneous updates are unnecessary.
    • Fault isolation: A stalled or timed-out execution agent should not disable the planning agent. A mobile-channel failure should not affect the browser interface.

    8. Common Mistakes and How to Avoid Them

    Mistake Consequence Mitigation
    Both agents share a working directory File conflicts and accidental overwrites Separate workspaces; make shared artifacts read-only
    Both entry points use the same session key Context contamination and cross-session leakage Separate sessions by agent, channel, user, and thread
    Behavior is constrained only by prompts Unreliable enforcement Use tool permissions, timeouts, budgets, and approvals
    Model credentials are stored in each agent’s configuration Credential proliferation and unauditable costs Centralize access through a model gateway
    Tasks have no completion criteria Execution loops and timeouts Establish an acceptance checklist before execution
    Work ends when the agent says it cannot proceed Stalled tasks Require error evidence and attempted alternatives
    Only final answers are logged Failures cannot be reconstructed Record tool calls, approvals, and checkpoints
    Entry points are permanently bound to roles Users must choose the agent themselves Add intent-based routing

    9. Conclusion: Assign Each Behavior a Clear Role

    Running two agents on one machine is technically straightforward. The harder problem is letting them share model capabilities without sharing risks, share knowledge without contaminating sessions, and behave differently while remaining subject to the same governance.

    A practical design can be summarized in six principles:

    • One model gateway: Centralize credentials, quotas, auditing, and model versions.
    • Two isolated runtimes: Separate processes, ports, workspaces, and session namespaces.
    • Multiple entry points: Treat browser and mobile interfaces as channels, not as fixed risk policies.
    • Separate planning from execution: Clarify acceptance criteria before allowing write operations.
    • Require both budgets and evidence: Prevent inaction as well as unbounded action.
    • Enforce security and observability independently: Sandboxes, approvals, logs, and metrics must not depend on the model’s own description of its behavior.

    With these boundaries in place, running both agents becomes more than a compromise between two user experiences. It creates a controlled workflow: use the planning role for discussion, the execution role for progress, and centralized approval and auditing for high-risk actions.

    The result is not merely a more compliant or more persistent agent. It is an engineering system that selects behavior according to task risk, execution cost, and delivery criteria.