diff --git a/docs/site/content/docs/cli/orchestration.mdx b/docs/site/content/docs/cli/orchestration.mdx index d83d27836cf..88355cb8c82 100644 --- a/docs/site/content/docs/cli/orchestration.mdx +++ b/docs/site/content/docs/cli/orchestration.mdx @@ -44,7 +44,7 @@ orca orchestration worker-start --task --worktree new-child --name bill orca orchestration worker-start --task --worktree current --agent claude --model --effort high --json ``` -`--agent` takes any Orca agent ID enabled on the worker server, for example `claude`, `codex`, `cursor`, `antigravity`, `muse`, `opencode`, or `opencode2`. `--model` accepts opaque provider model IDs for Claude, Codex, Cursor, Antigravity, and Muse (for example `--agent muse --model muse-spark-1.3`); other agents, including opencode, run the model from their own config. `--effort` requires `--model` and only applies when that agent/model supports the level. Neither flag can combine with `--terminal` (reuse an existing pane). Overrides apply to that launch only and show under `launch.requested` / `launch.effective` in the start receipt. Federated starts need a worker host that advertises launch-preference support. +`--agent` takes any Orca agent ID enabled on the worker server, for example `claude`, `codex`, `cursor`, `antigravity`, `muse`, `opencode`, or `opencode2`. `--model` accepts opaque provider model IDs for Claude, Codex, Cursor, Antigravity, and Muse (for example `--agent muse --model muse-spark-1.3`); OpenCode accepts a per-launch model only in an existing worktree, when the execution host verifies its CLI version and model availability; OpenCode effort remains unsupported. Other agents run the model from their own config. `--effort` requires `--model` and only applies when that agent/model supports the level. Neither flag can combine with `--terminal` (reuse an existing pane). Overrides apply to that launch only and show under `launch.requested` / `launch.effective` in the start receipt. Federated starts need a worker host that advertises launch-preference support. Wait for completions (process every message in a Delivery, then ack): diff --git a/skill-guides/orchestration/references/coordinator-loop.md b/skill-guides/orchestration/references/coordinator-loop.md index aec13667645..164f91e4548 100644 --- a/skill-guides/orchestration/references/coordinator-loop.md +++ b/skill-guides/orchestration/references/coordinator-loop.md @@ -31,9 +31,12 @@ ORCA orchestration worker-start --task --worktree current --agent clau ORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json ``` -Other agents, including `opencode`, reject `--model`; they run the model set in -their own config, so a coordinator wanting a same-model opencode worker relies -on that config. +OpenCode also accepts `--model` in an existing worktree when the execution host +verifies its CLI version and model availability. Creating a new worktree with an +OpenCode model override is unsupported; use `--worktree current` or an existing +worktree selector, or omit `--model`. OpenCode effort is unsupported. Omit the +model to inherit its configuration; unsupported or unknown hosts refuse the +override explicitly. `--effort` requires `--model`; neither option combines with `--terminal`. A connected worker server must advertise launch-preference support before Orca diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index cea9256e75d..f23fe070c1f 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -69,10 +69,10 @@ const ORCA_PER_WORKSPACE_ENV_WINDOWS_SCRIPTS_REFERENCE_MARKDOWN = "# Windows loc const ORCHESTRATION_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Coordinate supervised Orca workers: threaded messages, blocking ask/reply,\n task dispatch, worker_done/escalation waits, task DAGs, decision gates,\n coordinator loops, and decomposing work across agents. Use `orca-cli` for full\n ownership handoffs — \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", \"another worktree\" — unless asked to supervise, monitor, or coordinate\n a DAG, and for terminal control, lightweight terminal prompts, shell commands,\n Orca worktree management, and reading or waiting on terminals.\n---\n\n# Orca orchestration\n\nOrchestration is Orca's structured coordination layer. It records who owns work,\nwhich attempt is authoritative, and when supervised work has settled.\n\n## Outcome\n\n**Result:** every in-scope Task has one explicit outcome and every settled worker\nterminal has a next owner or cleanup decision. **Next consumer:** the user who\nrequested supervision. **Done:** all expected Dispatches have settled, every\ndelivered message was processed before acknowledgment, each settled worker was\nreused, explicitly retained, or released, and the turn ends only when the report\nto that user names, per Task, its outcome, the evidence behind it, and any\nunresolved blocker.\n\n**Safe failure:** preserve work and authority and report the state as unknown or\n`unverifiable`. Only positive proof of exit authorizes stop, abandon, or retry,\nand only an accepted settlement authorizes release. Every other observation,\nabsence included, is a checkpoint.\n\n## Classify the role\n\n| Current context | Role | Route |\n| ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------ |\n| The user explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use a decision gate, or manage ask/reply | Coordinator | Use the supervised loop below |\n| The current prompt contains a live injected preamble with Task and Dispatch IDs | Dispatched worker | Follow the preamble and the worker obligations below |\n| The user asks to hand off ownership or start another agent/worktree without supervision | Handoff owner | Use `orca-cli`; create no Run, Task, or Dispatch and do not monitor completion |\n| A message carries a legacy authority label | Compatibility operator | Load the legacy contract reference before any lifecycle mutation |\n| No live preamble and no explicit supervision | Ordinary terminal agent | Do not emit lifecycle messages; use `orca-cli` for terminal/worktree work |\n\nModel or effort selection does not make a handoff supervised. Never substitute a\nnon-Orca subagent tool when Orca orchestration provenance was requested.\n\n## Authority and safety floor\n\n- A Run is a durable namespace and coordinator inbox; it does not schedule or\n place workers. A Task is work. A Dispatch is one authoritative Task attempt.\n- Lifecycle authority comes from the active Dispatch, not a terminal title,\n copied ID, old database row, provider transcript, or visible pane.\n- Workers use the exact executable, handle, Task ID, and Dispatch ID in the live\n preamble, plus any other flag it carries. Never reconstruct, translate, or\n broaden those arguments.\n- After remote start, address the worker by Dispatch ID. The execution host owns\n process, filesystem, transcript, stop, and cleanup facts. Preserve the verdicts\n `live` / `unverifiable` / `exited`; contact loss is not process death.\n- Liveness is layered: `worker-list`'s `projection.liveness` is the fleet verdict\n for the agent; `worker-show`'s `observation.status` is PTY liveness only. A live\n terminal can still hold a dead or stuck agent.\n- Folder workspaces are valid; never require Git or assume a worktree.\n- Clients and remote servers update independently. Treat unknown optional fields\n as absent. A new stream operation requires advertised capability because old\n decoders may silently drop unknown opcodes. Never fall back to local execution\n when remote authority or capability is unproven.\n- Use the executable you used to run `skills get` for the entire run. In the\n examples below, replace `ORCA` with it; do not create a shell variable or run\n `ORCA` literally. If it fails, report that exact error instead of switching.\n- `ORCA status --json` shows your Orca session ID as `caller.orcaSessionId` when you have one.\n- A successful `orchestration send` proves durable enqueue; its wake or nudge is\n best-effort attention only and does not prove the recipient read or accepted it.\n\n## Worker obligations\n\nThe injected preamble is authoritative. A dispatched worker must:\n\n1. Do only the current Task and use the preamble's `ask` command for a blocking\n coordinator question. Never open a local question TUI the coordinator cannot\n answer. Resume the same message ID after an ask timeout.\n2. Send heartbeats only at the cadence in the preamble. A heartbeat proves\n liveness, not completion.\n3. Read coordinator follow-ups at each natural checkpoint — before starting a\n new file, after a test run — and once more immediately before `worker_done`:\n `ORCA orchestration check --terminal --json`.\n4. Send `worker_done` exactly once, from the dispatched terminal, with a\n three-sentence executive summary, both lifecycle IDs, and explicit\n `--outcome succeeded` or `--outcome failed`. Never encode failure only in prose.\n5. Append `--files-modified` and `--report-path` only with real values when\n applicable. After `worker_done`, end the dispatched turn and idle; do not poll\n or start new work.\n\nA direct user instruction after completion starts new user-owned work and takes\nprecedence over the idle rule. Do not reuse the settled lifecycle IDs.\n\n## Canonical supervised loop\n\nConfirm the runtime, bind one Run, and start the full independent wave before\nwaiting. `worker-start --spec` creates the Task and its attempt in one call:\n\n```text\nORCA status --json\nORCA orchestration run-create --objective \"\" --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent codex --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent claude --json\nORCA orchestration check --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nIf `worker-start` exits non-zero, do not relaunch. Read the receipt's\n`failedStage` and `residualResources`, then load\n`references/recovery-and-cleanup.md`.\n\nUse `task-create` plus `worker-start --task ` for planned fan-out with\ndependencies or a retry of a known Task. Use dependencies only for real ordering\nand prefer parallel waves over chains deeper than three or four steps; nested\nworkers obey the depth limit, and a new Run does not reset the caller's depth.\n\nA consuming `check` names its caller with `--terminal `, never `--from`;\nomit it inside the coordinator's own Orca terminal. It returns the bound Run's\noldest FIFO Delivery and replays that batch until acknowledged. Process every\nmessage: reply to questions, validate each `worker_done` against the expected\nactive Dispatch, and decide each settled terminal's next owner before the ack:\n\n```text\nORCA orchestration reply --id --body \"\" --json\nORCA orchestration worker-release --dispatch --json\nORCA orchestration check --ack --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nKeep waiting until every expected Dispatch settles. A timeout or empty result is\na checkpoint, not a failure. Do not stop, retry, release, or launch a duplicate\neditor without the positive proof `## Outcome` requires.\n\nAfter three consecutive empty waits, stop waiting blindly and enumerate with\n`ORCA orchestration worker-list --include-remote --json` (defaults to the bound\nRun; `--run ` overrides; the receipt's `scope` names which), acting on\neach row's `projection.attention` categories, `projection.attention.requiresAction`, and literal `projection.nextAction` argv.\nRows come newest first and page at 100: while `page.hasMore`, follow `page.nextCursor` with `--cursor `.\nA `none` `nextAction` has no argv to run: read `liveness.reason` and keep waiting\nwith `check --wait`. Absence never earns an argv; settlement and pending work still do.\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Then load `references/recovery-and-cleanup.md` and choose\n`worker-stop` or `worker-abandon` explicitly. `unverifiable` is absence,\nincluding when `worker-show` reports `agentWait` null. Absence never authorizes\nstop, abandon, retry, or release; keep waiting or inspect.\n\n`worker-start` is the normal path, composing placement, terminal readiness,\nprompt injection, and supervised resource ownership. `dispatch --inject` leaves\nan operator-created process unsupervised and is only for an expressiveness gap.\n\n## Task-spec contract\n\nEvery Task spec must be self-contained and name:\n\n- **Target:** the files, component, or environment in scope.\n- **Change:** the concrete result to produce.\n- **Constraints:** invariants, compatibility rules, and do-not-touch boundaries.\n- **Ownership:** what this worker may edit and any coordination boundary.\n- **Observable acceptance:** the test, output, or evidence that proves completion.\n\n## Completion accounting\n\nAfter an accepted success or failure report, immediately do exactly one:\n\n1. Reuse the same proven agent terminal for an immediate follow-up Dispatch.\n2. Record user-requested retention with `worker-retain`.\n3. Run `worker-release`.\n\nRelease is post-settlement cleanup, not cancellation. Only an accepted\nsettlement authorizes it; no other observation does. If release is uncertain,\nfollow its exact recovery receipt and never substitute `terminal close`.\n\nA valid `worker_done` settles the Task and Dispatch automatically; do not follow\nit with `task-update --status completed`. Enumerate the terminals still owing a\ndecision with `worker-list --run --terminal-state reclaimable --json`,\nand do not end the coordinator turn until it returns none.\n\n## Conditional references\n\nThis compact guide is sufficient for the normal local loop. At an action gate\nbelow, run `ORCA skills get orchestration --reference references/.md` and\nread only that document; `--references` lists the names. If the CLI rejects\n`--reference`, run `ORCA skills get orchestration --full` once instead: it\nreturns this exact kernel and every reference, so read only the named one. If an\nolder CLI rejects `--full`, keep this kernel's safety floor, use that command's\n`--help`, and never guess newer flags.\n\n| Action gate | Bundled reference |\n| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |\n| Expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` |\n| You are a dispatched worker and the live preamble does not answer your question, or `check` returned an error | `references/worker-contract.md` |\n| New worktree, exact workspace, SSH, WSL, or connected-server placement | `references/placement-and-remote.md` |\n| Inbox replay, follow-up messages, group addresses, or decision gates | `references/messaging-and-gates.md` |\n| Failed/stopped/unknown attempts, retry, stop, abandon, retain, or uncertain release | `references/recovery-and-cleanup.md` |\n| Custom argv or terminal topology that `worker-start` cannot express | `references/low-level-topology.md` |\n| Any legacy label, adopted Run, compatibility receipt, or takeover | `references/legacy-contract-migration.md` |\n\nRetired scheduler commands are not aliases for Run creation. Recovery commands\nmust provide their exact next action; follow it with the same selected executable.\n" // oxfmt-ignore -const ORCHESTRATION_FULL_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Coordinate supervised Orca workers: threaded messages, blocking ask/reply,\n task dispatch, worker_done/escalation waits, task DAGs, decision gates,\n coordinator loops, and decomposing work across agents. Use `orca-cli` for full\n ownership handoffs — \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", \"another worktree\" — unless asked to supervise, monitor, or coordinate\n a DAG, and for terminal control, lightweight terminal prompts, shell commands,\n Orca worktree management, and reading or waiting on terminals.\n---\n\n# Orca orchestration\n\nOrchestration is Orca's structured coordination layer. It records who owns work,\nwhich attempt is authoritative, and when supervised work has settled.\n\n## Outcome\n\n**Result:** every in-scope Task has one explicit outcome and every settled worker\nterminal has a next owner or cleanup decision. **Next consumer:** the user who\nrequested supervision. **Done:** all expected Dispatches have settled, every\ndelivered message was processed before acknowledgment, each settled worker was\nreused, explicitly retained, or released, and the turn ends only when the report\nto that user names, per Task, its outcome, the evidence behind it, and any\nunresolved blocker.\n\n**Safe failure:** preserve work and authority and report the state as unknown or\n`unverifiable`. Only positive proof of exit authorizes stop, abandon, or retry,\nand only an accepted settlement authorizes release. Every other observation,\nabsence included, is a checkpoint.\n\n## Classify the role\n\n| Current context | Role | Route |\n| ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------ |\n| The user explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use a decision gate, or manage ask/reply | Coordinator | Use the supervised loop below |\n| The current prompt contains a live injected preamble with Task and Dispatch IDs | Dispatched worker | Follow the preamble and the worker obligations below |\n| The user asks to hand off ownership or start another agent/worktree without supervision | Handoff owner | Use `orca-cli`; create no Run, Task, or Dispatch and do not monitor completion |\n| A message carries a legacy authority label | Compatibility operator | Load the legacy contract reference before any lifecycle mutation |\n| No live preamble and no explicit supervision | Ordinary terminal agent | Do not emit lifecycle messages; use `orca-cli` for terminal/worktree work |\n\nModel or effort selection does not make a handoff supervised. Never substitute a\nnon-Orca subagent tool when Orca orchestration provenance was requested.\n\n## Authority and safety floor\n\n- A Run is a durable namespace and coordinator inbox; it does not schedule or\n place workers. A Task is work. A Dispatch is one authoritative Task attempt.\n- Lifecycle authority comes from the active Dispatch, not a terminal title,\n copied ID, old database row, provider transcript, or visible pane.\n- Workers use the exact executable, handle, Task ID, and Dispatch ID in the live\n preamble, plus any other flag it carries. Never reconstruct, translate, or\n broaden those arguments.\n- After remote start, address the worker by Dispatch ID. The execution host owns\n process, filesystem, transcript, stop, and cleanup facts. Preserve the verdicts\n `live` / `unverifiable` / `exited`; contact loss is not process death.\n- Liveness is layered: `worker-list`'s `projection.liveness` is the fleet verdict\n for the agent; `worker-show`'s `observation.status` is PTY liveness only. A live\n terminal can still hold a dead or stuck agent.\n- Folder workspaces are valid; never require Git or assume a worktree.\n- Clients and remote servers update independently. Treat unknown optional fields\n as absent. A new stream operation requires advertised capability because old\n decoders may silently drop unknown opcodes. Never fall back to local execution\n when remote authority or capability is unproven.\n- Use the executable you used to run `skills get` for the entire run. In the\n examples below, replace `ORCA` with it; do not create a shell variable or run\n `ORCA` literally. If it fails, report that exact error instead of switching.\n- `ORCA status --json` shows your Orca session ID as `caller.orcaSessionId` when you have one.\n- A successful `orchestration send` proves durable enqueue; its wake or nudge is\n best-effort attention only and does not prove the recipient read or accepted it.\n\n## Worker obligations\n\nThe injected preamble is authoritative. A dispatched worker must:\n\n1. Do only the current Task and use the preamble's `ask` command for a blocking\n coordinator question. Never open a local question TUI the coordinator cannot\n answer. Resume the same message ID after an ask timeout.\n2. Send heartbeats only at the cadence in the preamble. A heartbeat proves\n liveness, not completion.\n3. Read coordinator follow-ups at each natural checkpoint — before starting a\n new file, after a test run — and once more immediately before `worker_done`:\n `ORCA orchestration check --terminal --json`.\n4. Send `worker_done` exactly once, from the dispatched terminal, with a\n three-sentence executive summary, both lifecycle IDs, and explicit\n `--outcome succeeded` or `--outcome failed`. Never encode failure only in prose.\n5. Append `--files-modified` and `--report-path` only with real values when\n applicable. After `worker_done`, end the dispatched turn and idle; do not poll\n or start new work.\n\nA direct user instruction after completion starts new user-owned work and takes\nprecedence over the idle rule. Do not reuse the settled lifecycle IDs.\n\n## Canonical supervised loop\n\nConfirm the runtime, bind one Run, and start the full independent wave before\nwaiting. `worker-start --spec` creates the Task and its attempt in one call:\n\n```text\nORCA status --json\nORCA orchestration run-create --objective \"\" --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent codex --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent claude --json\nORCA orchestration check --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nIf `worker-start` exits non-zero, do not relaunch. Read the receipt's\n`failedStage` and `residualResources`, then load\n`references/recovery-and-cleanup.md`.\n\nUse `task-create` plus `worker-start --task ` for planned fan-out with\ndependencies or a retry of a known Task. Use dependencies only for real ordering\nand prefer parallel waves over chains deeper than three or four steps; nested\nworkers obey the depth limit, and a new Run does not reset the caller's depth.\n\nA consuming `check` names its caller with `--terminal `, never `--from`;\nomit it inside the coordinator's own Orca terminal. It returns the bound Run's\noldest FIFO Delivery and replays that batch until acknowledged. Process every\nmessage: reply to questions, validate each `worker_done` against the expected\nactive Dispatch, and decide each settled terminal's next owner before the ack:\n\n```text\nORCA orchestration reply --id --body \"\" --json\nORCA orchestration worker-release --dispatch --json\nORCA orchestration check --ack --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nKeep waiting until every expected Dispatch settles. A timeout or empty result is\na checkpoint, not a failure. Do not stop, retry, release, or launch a duplicate\neditor without the positive proof `## Outcome` requires.\n\nAfter three consecutive empty waits, stop waiting blindly and enumerate with\n`ORCA orchestration worker-list --include-remote --json` (defaults to the bound\nRun; `--run ` overrides; the receipt's `scope` names which), acting on\neach row's `projection.attention` categories, `projection.attention.requiresAction`, and literal `projection.nextAction` argv.\nRows come newest first and page at 100: while `page.hasMore`, follow `page.nextCursor` with `--cursor `.\nA `none` `nextAction` has no argv to run: read `liveness.reason` and keep waiting\nwith `check --wait`. Absence never earns an argv; settlement and pending work still do.\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Then load `references/recovery-and-cleanup.md` and choose\n`worker-stop` or `worker-abandon` explicitly. `unverifiable` is absence,\nincluding when `worker-show` reports `agentWait` null. Absence never authorizes\nstop, abandon, retry, or release; keep waiting or inspect.\n\n`worker-start` is the normal path, composing placement, terminal readiness,\nprompt injection, and supervised resource ownership. `dispatch --inject` leaves\nan operator-created process unsupervised and is only for an expressiveness gap.\n\n## Task-spec contract\n\nEvery Task spec must be self-contained and name:\n\n- **Target:** the files, component, or environment in scope.\n- **Change:** the concrete result to produce.\n- **Constraints:** invariants, compatibility rules, and do-not-touch boundaries.\n- **Ownership:** what this worker may edit and any coordination boundary.\n- **Observable acceptance:** the test, output, or evidence that proves completion.\n\n## Completion accounting\n\nAfter an accepted success or failure report, immediately do exactly one:\n\n1. Reuse the same proven agent terminal for an immediate follow-up Dispatch.\n2. Record user-requested retention with `worker-retain`.\n3. Run `worker-release`.\n\nRelease is post-settlement cleanup, not cancellation. Only an accepted\nsettlement authorizes it; no other observation does. If release is uncertain,\nfollow its exact recovery receipt and never substitute `terminal close`.\n\nA valid `worker_done` settles the Task and Dispatch automatically; do not follow\nit with `task-update --status completed`. Enumerate the terminals still owing a\ndecision with `worker-list --run --terminal-state reclaimable --json`,\nand do not end the coordinator turn until it returns none.\n\n## Conditional references\n\nThis compact guide is sufficient for the normal local loop. At an action gate\nbelow, run `ORCA skills get orchestration --reference references/.md` and\nread only that document; `--references` lists the names. If the CLI rejects\n`--reference`, run `ORCA skills get orchestration --full` once instead: it\nreturns this exact kernel and every reference, so read only the named one. If an\nolder CLI rejects `--full`, keep this kernel's safety floor, use that command's\n`--help`, and never guess newer flags.\n\n| Action gate | Bundled reference |\n| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |\n| Expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` |\n| You are a dispatched worker and the live preamble does not answer your question, or `check` returned an error | `references/worker-contract.md` |\n| New worktree, exact workspace, SSH, WSL, or connected-server placement | `references/placement-and-remote.md` |\n| Inbox replay, follow-up messages, group addresses, or decision gates | `references/messaging-and-gates.md` |\n| Failed/stopped/unknown attempts, retry, stop, abandon, retain, or uncertain release | `references/recovery-and-cleanup.md` |\n| Custom argv or terminal topology that `worker-start` cannot express | `references/low-level-topology.md` |\n| Any legacy label, adopted Run, compatibility receipt, or takeover | `references/legacy-contract-migration.md` |\n\nRetired scheduler commands are not aliases for Run creation. Recovery commands\nmust provide their exact next action; follow it with the same selected executable.\n\n---\n\n# Bundled references\n\nThese references belong to the version-matched guide above. Read only the documents named by its action gates.\n\n\n\n# Coordinator loop\n\nLoad this reference for expanded DAG waves, per-invocation launch preferences,\nsame-terminal reuse, or review ownership. The compact guide remains the source\nof truth for the loop order and completion boundary.\n\n## Ready waves\n\nCreate independent Tasks before the first wait. Encode only real dependencies,\nthen use the ready view as external memory:\n\n```text\nORCA orchestration task-create --spec \"\" --deps --json\nORCA orchestration task-list --ready --brief --json\n```\n\n`--brief` collapses whitespace and caps echoed specs at 160 characters;\n`spec_truncated` identifies shortened rows. Omit it when full specs are needed or\nwhen an older CLI rejects the flag. A nested worker must respect\n`nested_worker_depth_exceeded`; creating another Run does not reset depth.\n\n## Launch preferences\n\nFor a fresh Claude, Codex, Cursor, Antigravity, or Muse terminal, `--model`\naccepts an opaque provider model ID. Pass it only when the user named a model;\notherwise omit it so the worker inherits the user's configured agent default.\nAdd `--effort` only when that model supports it:\n\n```text\nORCA orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\nORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json\n```\n\nOther agents, including `opencode`, reject `--model`; they run the model set in\ntheir own config, so a coordinator wanting a same-model opencode worker relies\non that config.\n\n`--effort` requires `--model`; neither option combines with `--terminal`. A\nconnected worker server must advertise launch-preference support before Orca\nforwards either field. Compare `launch.requested` with `launch.effective`; never\nclaim a model or effort from requested arguments alone.\n\n## Reuse after settlement\n\nChoose the terminal's next owner before acknowledging the Delivery. When the\nsame exact agent has immediate follow-up work, recover the proven handle and\ntransfer cleanup ownership to the new Dispatch:\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-start --task --terminal --json\n```\n\nOtherwise explicitly retain or release the settled worker. Do not leave it live\nonly to inspect output; archived output remains available through `worker-read`.\n\n## Review ownership\n\nA review-only `worker_done` authorizes synthesis of findings, not coordinator\nfile edits. Dispatch or hand off fixes unless the user explicitly assigned them\nto the coordinator. If the user's plan names a next owner, post-review fixes and\nPR preparation remain with that owner; the coordinator routes and synthesizes.\n\n\n\n# Legacy contract migration\n\nLoad this reference only for an authority label, adopted Run, compatibility or\nrecovery receipt, or explicit legacy takeover. A newly created attempt always\nuses the current grammar.\n\n## Authority labels\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported\n command printed with the message, using the same selected executable and\n arguments supplied by the original prompt.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded,\n at-least-once cutover replay. Process it idempotently and acknowledge only\n through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or\n lifecycle mutation.\n- An unlabeled current message uses the current guide and grammar.\n\nAn explicitly selected current Run, attested current binding, current Dispatch,\nor federated attachment takes precedence over legacy fallback. A retained\nadoption record alone does not grant mutation authority. If liveness, principal\nownership, capability, or the exact legacy contract is unproven, degrade to\nread-only inspection and never fall back to local execution.\n\nAdoption preserves the live agent process, PTY/session, terminal handle,\ntab/pane, worktree or folder workspace, Task, and Dispatch. It never restarts or\nreplaces the worker and never revives the retired scheduler. Loss of lifecycle\nauthority does not invalidate the existing process, assignment, or filesystem\nwork. Exact recovery may restore the same PTY once in its original inactive\nbackground tab; it must not spawn, write, signal, stop, switch, focus, split, or\ninject a terminal.\n\n## Compatibility recovery\n\nWhen a compatibility response returns structured next-step arguments, execute\nthose exact arguments with the same selected CLI executable. Do not translate\nfrom memory, broaden the recipient, or retry as a current mutation unless the\nreceipt explicitly authorizes it.\n\nA pending ask, reply, final Dispatch settlement, and consuming check have\ndurable recovery identities. Heartbeat and escalation remain at-least-once\nacross a manual contract-boundary retry. If an ask may already have been\nanswered, run the exact non-consuming recovery check printed by Orca before\ncreating any new question. Never guess among identical question threads.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The\ninitial command commits the question, prints its exact\n`ask --resume ` command, and exits with launcher status `75`. Run\nthat exact resume after the launcher or update boundary. For an attested WSL\nlaunch, preserve the printed `orca-ide` executable and distro route. Older WSL\nworkers without launch proof remain lifecycle read-only even while their\nterminal and filesystem work continue.\n\n## Read-only inspection and takeover\n\nRead-only inspection does not consume mail:\n\n```text\nORCA orchestration run-list --json\nORCA orchestration run-show --id run_legacy_local --json\nORCA orchestration run-show --id --json\nORCA orchestration task-list --run --json\nORCA orchestration inbox --full --json\nORCA orchestration check --terminal --peek --format --json\nORCA terminal read --terminal --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\n`run_legacy_local` is an empty audit tombstone after adoption. Find the ordinary\nRun whose objective is `Recovered orchestration work from a contract update`.\n\nOnly when the original coordinator is unavailable or cannot prove retained\nauthority may a new live coordinator take over from its own terminal:\n\n```text\nORCA orchestration run-use --id --takeover-legacy --json\nORCA orchestration check --run --json\n```\n\nTakeover binds the authenticated invoking terminal; `--from` cannot nominate\nanother coordinator. It fences only the old coordinator and moves pending mail\ninto current Run delivery. It preserves live workers, Tasks, Dispatches, processes, and files.\nNever take over while the original coordinator is actively coordinating.\n\nDo not launch a replacement editor merely because Orca updated or authority is\nunclear. Keep the original worker as the only editor until a stable handoff\npoint, then use a fresh current Dispatch in a conflict-free placement.\n\n\n\n# Low-level topology\n\nLoad this reference only when `worker-start` cannot express required custom argv\nor terminal topology. It is not the normal supervised loop and is never a full\nhandoff recipe.\n\n```text\nORCA terminal create --worktree active --title --command \"\" --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\nORCA orchestration dispatch --task --to --inject --json\n```\n\nWait for readiness only when startup could lose injected input. Prefer\nagent-first `worker-start` whenever its argv and topology are sufficient.\n\n`dispatch --inject` creates authoritative Task/Dispatch context but deliberately\nkeeps an operator-created process unsupervised: it creates no supervised worker\nresource row. `worker-show`, `worker-read`, and `worker-list` report the lane as\n`unsupervised`; `worker-stop` and `worker-abandon` do not close that process, and\nsettled retain/release take no process action.\n\nUse `worker-start --terminal ` when lifecycle ownership of an existing\nagent terminal is required. Never imply that low-level dispatch retroactively\nowns a process, never use it to route around the nested-depth limit, and never\nuse it for an ownership handoff.\n\n\n\n# Messaging and gates\n\nLoad this reference for inbox replay, attempt-specific guidance, group\naddresses, blocking questions, or coordinator-managed DAG decisions.\n\nA successful `send` proves durable enqueue. Wake and nudge are best-effort\nattention only: neither proves the recipient read the message, began a turn, or\naccepted steering.\n\n## Coordinator delivery loop\n\n`check` names its caller with `--terminal ` and is the only verb that\nrejects `--from`. Omit `--terminal` inside an Orca terminal, where Orca resolves\nthe caller; pass it explicitly from anywhere else, including a dispatched\nworker reading coordinator follow-ups.\n\nA consuming coordinator `check` returns the bound Run's oldest FIFO Delivery,\nup to 50 messages, and replays that exact batch until acknowledged. Process\nevery row and required terminal ownership decision before `--ack`. Type filters\ndecide when a waiter wakes; they do not authorize skipping older actionable\nmail. A Delivery therefore always carries the whole FIFO batch whatever its\ntypes, and a `check` without `--wait` hands that batch over unfiltered.\n`--peek` and `--all` are read-only inspection, not progress through the\ncoordinator inbox.\n\nAn empty wait or timeout is a checkpoint. Continue rolling waits until every\nexpected Dispatch settles. Heartbeat or visible activity means alive, not done.\n\n## Addresses\n\nUse a stable Dispatch address for attempt-specific coordinator guidance:\n\n```text\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nDo not substitute a remote terminal handle. Omit `--from` for ordinary\ncoordinator calls; a dispatched worker instead copies the exact `--from` and\nother arguments in its preamble. `check` is the exception: it identifies\nits caller with `--terminal`, never `--from`.\n\nGroup addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`,\n`@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`. Every group but\n`@worktree:` means the live Dispatches of the sender's own Run. Mail goes\nto each `dispatch:` mailbox, except a worker coordinating a child Run\nreceives it in that `run:` mailbox. A sender bound to no Run is refused;\n`--run` must match the group audience and never grants membership.\nA Run group excludes its owning coordinator; a worker raising a blocker sends\nto `run:`. A worker that created its own Run addresses that Run's workers,\nnot its siblings. `@worktree:` reaches matching workspace terminals,\nincluding coordinators. Use groups only for intentional fan-out status or\nquestions. `worker_done`, heartbeat, and other\nDispatch lifecycle messages never target groups.\n\n## Questions and gates\n\nA worker uses `ask`; its timeout leaves one durable question pending, which the\nworker resumes by message ID. The coordinator answers that message with `reply`.\n\nUse a gate only for a coordinator-owned Task-DAG decision:\n\n```text\nORCA orchestration gate-create --task --question \"\" --options --json\nORCA orchestration gate-resolve --id --resolution \"\" --json\nORCA orchestration gate-list --task --json\n```\n\nPass `json_array` using the quoting rules of the active shell; do not copy POSIX\nsingle-quote syntax into PowerShell or `cmd.exe`.\n\nDo not create a gate merely to answer a worker's `ask`.\n\n\n\n# Placement and remote execution\n\nLoad this reference before creating a new worktree or placing work through SSH,\nWSL, or another connected Orca server.\n\n## Placement choices\n\nA fresh worker means a fresh agent terminal, not a new Git worktree. Use the\ncurrent or an exact existing workspace by default. Create a worktree only when\nthe user requested one or a concrete checkout or filesystem conflict makes\nsharing unsafe.\n\n```text\n# Current workspace; setup is not rerun.\nORCA orchestration worker-start --task --worktree current --agent codex --json\n\n# Stacked child worktree.\nORCA orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n\n# Independent top-level worktree.\nORCA orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nCurrent and exact existing workspaces create a fresh terminal unless\n`--terminal` is explicit. Folder workspaces are first-class; do not invoke Git\nor require worktree lineage when the selected workspace is a folder.\n\nRegister a folder workspace through project setup. `repo add --path `\nrequires a valid Git repository and rejects a plain directory:\n\n```text\nORCA project setup-existing-folder --project --host --path --kind folder --json\n```\n\nThen place work on the returned workspace with an exact selector. A worktree\nselector needs the full `::` value Orca returned, passed as\n`id:`; a bare repo id is not a worktree id. `new-child` and\n`new-top-level` are worktree creation and do not apply to a folder.\n\nNew worktrees use agent-first creation and run setup by default. Preserve the\nrepository's startup policy: `start-immediately` can report setup as `running`,\nwhile `wait-for-setup` gates prompt delivery on success. Orca lineage, Git base,\nfilesystem isolation, coordination parentage, UI grouping, and execution host\nare separate decisions.\n\n## Connected servers\n\nThe Run and Tasks remain authoritative on the current server. `--on` selects\nonly the worker's execution server and appears only on `worker-start`:\n\n```text\nORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run --json\n```\n\nRemote `current` and `new-child` are invalid because they are ambiguous across\nservers. Use an exact discovered remote workspace, or `new-top-level` with an\nexact remote repository selector. After start, route every follow-up, read,\nstop, and cleanup by Dispatch ID; never repeat `--on` or substitute a remote\nterminal handle.\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\nORCA orchestration worker-list --run --include-remote --json\n```\n\n`worker-list` reads local fleet state only; enumerate remote workers with\n`--include-remote` or every one of them reads `unverifiable`. Scope every list\nwith `--run `: unscoped, it reports every Dispatch this runtime has\nrecorded, and the workers you are waiting on are lost in that history.\n\n## Execution-host and mixed-version floor\n\nThe execution host owns process, filesystem, transcript, stop, and cleanup\nfacts. Render only `live`, `unverifiable`, or `exited`. Connection loss, relay\nabsence, missing client inventory, or timeout yields `unverifiable`, never\nsynthetic exit and never a client-local substitute action.\n\nClients and servers update independently. Optional response fields may be\nabsent. Forward model/effort, transcript reads, cleanup, or another new remote\noperation only when the peer advertises the relevant capability; unknown stream\nopcodes can be silently dropped. A narrow unsupported response may degrade to a\ndocumented older path, but must not broaden the target or cross the execution\nboundary. Changing host-published content reaches old clients even without a\nwire-shape change, so preserve established semantics or negotiate the behavior.\n\nFor WSL, use the exact executable and arguments returned by Orca so the distro\nand packaged launcher remain bound. Do not translate a printed `orca-ide`\nrecovery command into a PATH-resolved local command.\n\n\n\n# Recovery and cleanup\n\nLoad this reference only after a failed/stopped/unknown attempt, explicit retry\ndecision, stop/abandon request, retention request, or uncertain release.\n\n| Proven state | Safe action |\n| ----------------------- | ------------------------------------------------------------------ |\n| `ready` or active | Keep waiting; optionally read bounded output |\n| `failed` or `stopped` | Start a replacement with `--retry-of`; repeat placement explicitly |\n| `outcome_unknown` | Inspect, then choose `worker-stop` or explicit `worker-abandon` |\n| Accepted `worker_done` | Reuse, retain, or release |\n| Remote contact lost | Preserve `unverifiable`; do not stop or retry from absence alone |\n| `unverifiable` liveness | Keep waiting or inspect; never stop, abandon, retry, or release |\n| Proven `exited` agent | Enumerate with `worker-list`; follow its `nextAction` |\n\n## Inspect before acting\n\n```text\nORCA orchestration worker-list --run --json\nORCA orchestration worker-list --run --include-remote --json\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\n```\n\n`worker-list` is the enumerating command and the authority on agent liveness:\neach row carries `projection.liveness`, `projection.attention.categories`,\n`projection.attention.requiresAction`, and a literal `projection.nextAction`\nargv to run. Always scope it with `--run `; an unscoped list reports\nevery Dispatch this runtime has ever recorded and buries the live ones.\n`worker-show`'s `observation.status` is PTY liveness only, so a `live` terminal\nwhose agent died at a trust prompt still reads `live` there.\n\nWhen the two disagree, the fleet verdict decides — unless the fleet row is\n`unverifiable` for a reason that names a gap on this client rather than a fact\nabout the worker. `missing_status`, `host_unavailable`, and\n`capability_unsupported` are such gaps: the first means this runtime holds no\nstatus row, the second that it could not ask the execution host at all, and the\nthird that a stale peer answered but lacks the fleet-snapshot capability.\nAgainst any of them, a `worker-show` verdict sourced from the execution host is\nthe better evidence and outranks the row. Only `host_unavailable` is contact\nloss; the other two mean the host was never asked or answered without the\ncapability.\n\nThis never promotes absence. `unverifiable` from either command still authorizes\nnothing — only a positive `live` or `exited` verdict does.\n\nA worker started with `--on ` reads `unverifiable` until you\nenumerate with `--include-remote`, which asks its execution host for the\nverdict. Rows come newest first and past 100 the response pages, so follow\n`page.nextCursor` with `--cursor ` until `page.hasMore` is false.\n\n## Stall needs positive evidence\n\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Only then choose `worker-stop` or `worker-abandon`.\n\n`unverifiable` is always absence — `missing_status`, `stale_status`,\n`restored_unconfirmed`, or a remote worker with no connection — and a null\n`agentWait` or an unchanged `worker-read` tail is that same absence seen again.\nAbsence never authorizes stop, abandon, retry, or release: keep waiting, or\ninspect until you hold one of the positive signals above. A `nextAction` that\nnames an inspecting command is asking for evidence, not for cleanup.\n\n`worker-read --source auto` uses a proven provider transcript when available and\notherwise returns bounded terminal output with a typed `fallbackReason`.\nContinue with its top-level cursor, which is pinned to that source. If Orca\nreports `source_changed`, restart without the old cursor. A bounded initial\ntranscript tail can return an EOF cursor that follows only newly appended records;\nread `contentComplete`, `clipping`, and `warnings` before assuming omitted older\nrecords are pageable. Never guess a provider session ID, transcript path, or\nremote terminal handle.\n\n## Was the mutation applied?\n\nWhen a mutation's response was lost and named no Dispatch, do not replay blind.\nEvery orchestration mutation accepts `--retry-request `, which reuses one\noperation identity so Orca can replay, join, or recover it instead of starting a\nduplicate. Ask what happened first:\n\n```text\nORCA orchestration request-show --request --json\n```\n\n`completed` means the mutation already took effect; read its recorded receipt\ninstead of rerunning. `pending` means the original mutation is still running or\nOrca restarted before recording its outcome; replay the original command with\n`--retry-request `. `absent` means this runtime holds no receipt\nunder your caller identity — that is not proof nothing happened, so inspect the\naffected Task, Dispatch, and terminal before deciding whether to retry.\n\nWhen a worker's terminal accepted input but the submit is unconfirmed, use\n`terminal send --wait-submit `: it observes the accepted prompt for that\nlong and, on timeout, returns the input-accepted receipt without resending.\n\n## Refused starts\n\n`dispatch` and `worker-start` refuse the following preflight cases with a stable\n`error.code`; read it before choosing a recovery, and treat `error.data.nextSteps`\nas the exact recovery text. Older hosts may omit `data`, so treat every field as\noptional.\n\n| Code | Meaning | Recovery |\n| -------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n| `task_not_found` | No Task with that id, or not in the bound Run (`data.taskId`, `data.runId`) | Check `task-list --json`; create the Task with `task-create` if it does not exist |\n| `task_not_startable` | Task cannot start now: not `ready`, or invalid `--retry-of` (`data.status`, `data.unmetDependencies`, `data.retryOf`) | Wait for running dependencies with `check --wait`; retry or unblock failed ones; inspect `dispatch-show` if already dispatched |\n| `inject_rejected` | `--inject` refused because no recognized agent runs in the target (`data.terminal`, `data.reason`) | Start a recognized agent there or pick another terminal; or dispatch without `--inject` and use `terminal send` |\n| `runtime_error` | Any other failure, including a target terminal that already owns an active Dispatch | Read the message, inspect state, and do not retry unchanged |\n\n## Retry, stop, and abandon\n\nRetry only a positively proven failed or stopped attempt. Name the failed Task\nwith `--task`, since `--spec` creates a new one. Placement is never silently\ninherited:\n\n```text\nORCA orchestration worker-start --task --retry-of --worktree --agent --json\n```\n\nAfter three consecutive failures for one Task, its dispatch context\ncircuit-breaks and the Task is failed. Do not route around that boundary with a\nnew Run or an unrelated Dispatch.\n\nFor `outcome_unknown`, inspect first, then make an explicit choice:\n\n```text\nORCA orchestration worker-stop --dispatch --json\nORCA orchestration worker-abandon --dispatch --json\n```\n\n`worker-stop` closes only the exact proven supervised agent terminal. It never\ndeletes the worktree, setup terminal, configured tabs, or unrelated processes.\n`worker-abandon` fences orchestration while accepting that resources may remain\nlive; it performs no remote, process, or filesystem action. When it settles a\nworker, it retains an owned terminal by the same rule as `worker-retain`, so Orca\nstops owing its release; a release already committed (`releasing`,\n`release_unknown`) is left as it is. An already-settled worker is left untouched.\n\nTo cancel a Task, settle its worker with `worker-stop` or `worker-abandon`, then\nrecord the reason. A cancelled Task is `failed`, so its dependents stay blocked\nuntil a `--retry-of` replacement completes it:\n\n```text\nORCA orchestration task-update --id --status failed --result cancelled --json\n```\n\n## Retain and release\n\n```text\nORCA orchestration worker-retain --dispatch --json\nORCA orchestration worker-release --dispatch --json\n```\n\nRetain only when the user explicitly wants the settled terminal kept live.\nRelease works after succeeded and failed reports, archives readable output, and\ncloses only the exact terminal owned by that settled Dispatch. Replays may call\nrelease again safely. Reused, pre-existing, setup, coordinator, active,\nuser-taken-over, and unproven terminals are retained.\n\nA `worker-start` that failed before its agent was ready still owns the terminal\nit created. Its receipt names `worker-release`, and `worker-list` reports that\nrow as `reclaimable`; release it there rather than closing the terminal by hand.\n\nNever release because of timeout, TUI idle, heartbeat, status, question,\nescalation, or stale/rejected completion. If the receipt says `release_pending`\nor `release_unknown`, follow its exact recovery action. Never substitute\n`terminal close`.\n\n`orchestration reset` is destructive recovery. Do not run it during active\ncoordination unless the user explicitly abandons that state.\n\n\n\n# Worker contract\n\nThe injected preamble is authoritative. Copy its command rather than\nreconstructing flags. In particular, preserve the exact executable, worker\nhandle, Task ID, and Dispatch ID, and keep any other flag it carries (an older\nOrca host adds `--dispatch-capability`).\n\n## Heartbeat\n\nSend heartbeats only at the cadence required by the live preamble. Skip them\nwhile blocked inside `ask` or `check --wait`; those calls are liveness signals.\n\n```text\nORCA orchestration send --from --type heartbeat --subject \"alive\" --task-id --dispatch-id --phase \"\"\n```\n\nUse typed lifecycle flags, not a hand-written JSON payload. A heartbeat proves\nliveness, never completion.\n\n## Ask and resume\n\nUse Orca `ask` whenever the coordinator must answer. Never open a local question\nTUI the coordinator cannot answer.\n\n```text\nORCA orchestration ask --from --question \"\" --options \",\" --timeout-ms 600000\n\nORCA orchestration ask --from --resume --timeout-ms 600000\n```\n\nA timeout or disconnect leaves the original question pending. Resume its\nmessage ID; do not create a duplicate question.\n\n## Reading coordinator follow-ups\n\nThe coordinator steers a running worker with `send --to dispatch:`. That\nenqueue is durable but does not interrupt you, so nothing arrives unless you\nlook:\n\n```text\nORCA orchestration check --terminal --json\n```\n\nRun it at each natural checkpoint — before starting a new file, after a test\nrun — and once more immediately before `worker_done`, so a redirect or a\ncancellation lands before the Task settles. `check` names its caller with\n`--terminal`, never `--from`. Stop checking after `worker_done`.\n\nIf `check` returns `consumer_fenced`, this process no longer owns its Dispatch:\nthe Attempt was re-attached to another worker or settled without you. Stop, do\nnot send `worker_done`, and do not retry the check. An empty `check` never means\nyou were replaced; `consumer_fenced` is the only way you learn that.\nIf `send` or `ask` returns `consumer_fenced`, the command ran from another\nparty's terminal (a coordinator or another worker); run it from your own terminal.\n\n## Escalation\n\nEscalate only before completion and only when the coordinator must intervene:\n\n```text\nORCA orchestration send --from --type escalation --subject \"Blocked: \" --body \"
\" --task-id --dispatch-id \n```\n\n## Completion\n\nSend exactly one terminal report. `--body` is three sentences: what changed,\nwhat was found, and what remains. Use `--outcome failed` when the requested work\nis not complete; never hide failure in prose or silently exit.\n\nAppend `--files-modified` or `--report-path` only when applicable, using actual\npaths. Do not send documentation placeholders as metadata.\n\n```text\nORCA orchestration send --from --type worker_done --subject \"\" --body \"\" --task-id --dispatch-id --outcome succeeded\n```\n\nAfter `worker_done`, end the dispatched turn and idle. Do not poll, close your\nown terminal, or begin unrelated work. A later direct user instruction is new\nuser-owned work and must not reuse settled lifecycle IDs; a supervised follow-up\narrives with a fresh preamble and Task block.\n" +const ORCHESTRATION_FULL_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Coordinate supervised Orca workers: threaded messages, blocking ask/reply,\n task dispatch, worker_done/escalation waits, task DAGs, decision gates,\n coordinator loops, and decomposing work across agents. Use `orca-cli` for full\n ownership handoffs — \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", \"another worktree\" — unless asked to supervise, monitor, or coordinate\n a DAG, and for terminal control, lightweight terminal prompts, shell commands,\n Orca worktree management, and reading or waiting on terminals.\n---\n\n# Orca orchestration\n\nOrchestration is Orca's structured coordination layer. It records who owns work,\nwhich attempt is authoritative, and when supervised work has settled.\n\n## Outcome\n\n**Result:** every in-scope Task has one explicit outcome and every settled worker\nterminal has a next owner or cleanup decision. **Next consumer:** the user who\nrequested supervision. **Done:** all expected Dispatches have settled, every\ndelivered message was processed before acknowledgment, each settled worker was\nreused, explicitly retained, or released, and the turn ends only when the report\nto that user names, per Task, its outcome, the evidence behind it, and any\nunresolved blocker.\n\n**Safe failure:** preserve work and authority and report the state as unknown or\n`unverifiable`. Only positive proof of exit authorizes stop, abandon, or retry,\nand only an accepted settlement authorizes release. Every other observation,\nabsence included, is a checkpoint.\n\n## Classify the role\n\n| Current context | Role | Route |\n| ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------ |\n| The user explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use a decision gate, or manage ask/reply | Coordinator | Use the supervised loop below |\n| The current prompt contains a live injected preamble with Task and Dispatch IDs | Dispatched worker | Follow the preamble and the worker obligations below |\n| The user asks to hand off ownership or start another agent/worktree without supervision | Handoff owner | Use `orca-cli`; create no Run, Task, or Dispatch and do not monitor completion |\n| A message carries a legacy authority label | Compatibility operator | Load the legacy contract reference before any lifecycle mutation |\n| No live preamble and no explicit supervision | Ordinary terminal agent | Do not emit lifecycle messages; use `orca-cli` for terminal/worktree work |\n\nModel or effort selection does not make a handoff supervised. Never substitute a\nnon-Orca subagent tool when Orca orchestration provenance was requested.\n\n## Authority and safety floor\n\n- A Run is a durable namespace and coordinator inbox; it does not schedule or\n place workers. A Task is work. A Dispatch is one authoritative Task attempt.\n- Lifecycle authority comes from the active Dispatch, not a terminal title,\n copied ID, old database row, provider transcript, or visible pane.\n- Workers use the exact executable, handle, Task ID, and Dispatch ID in the live\n preamble, plus any other flag it carries. Never reconstruct, translate, or\n broaden those arguments.\n- After remote start, address the worker by Dispatch ID. The execution host owns\n process, filesystem, transcript, stop, and cleanup facts. Preserve the verdicts\n `live` / `unverifiable` / `exited`; contact loss is not process death.\n- Liveness is layered: `worker-list`'s `projection.liveness` is the fleet verdict\n for the agent; `worker-show`'s `observation.status` is PTY liveness only. A live\n terminal can still hold a dead or stuck agent.\n- Folder workspaces are valid; never require Git or assume a worktree.\n- Clients and remote servers update independently. Treat unknown optional fields\n as absent. A new stream operation requires advertised capability because old\n decoders may silently drop unknown opcodes. Never fall back to local execution\n when remote authority or capability is unproven.\n- Use the executable you used to run `skills get` for the entire run. In the\n examples below, replace `ORCA` with it; do not create a shell variable or run\n `ORCA` literally. If it fails, report that exact error instead of switching.\n- `ORCA status --json` shows your Orca session ID as `caller.orcaSessionId` when you have one.\n- A successful `orchestration send` proves durable enqueue; its wake or nudge is\n best-effort attention only and does not prove the recipient read or accepted it.\n\n## Worker obligations\n\nThe injected preamble is authoritative. A dispatched worker must:\n\n1. Do only the current Task and use the preamble's `ask` command for a blocking\n coordinator question. Never open a local question TUI the coordinator cannot\n answer. Resume the same message ID after an ask timeout.\n2. Send heartbeats only at the cadence in the preamble. A heartbeat proves\n liveness, not completion.\n3. Read coordinator follow-ups at each natural checkpoint — before starting a\n new file, after a test run — and once more immediately before `worker_done`:\n `ORCA orchestration check --terminal --json`.\n4. Send `worker_done` exactly once, from the dispatched terminal, with a\n three-sentence executive summary, both lifecycle IDs, and explicit\n `--outcome succeeded` or `--outcome failed`. Never encode failure only in prose.\n5. Append `--files-modified` and `--report-path` only with real values when\n applicable. After `worker_done`, end the dispatched turn and idle; do not poll\n or start new work.\n\nA direct user instruction after completion starts new user-owned work and takes\nprecedence over the idle rule. Do not reuse the settled lifecycle IDs.\n\n## Canonical supervised loop\n\nConfirm the runtime, bind one Run, and start the full independent wave before\nwaiting. `worker-start --spec` creates the Task and its attempt in one call:\n\n```text\nORCA status --json\nORCA orchestration run-create --objective \"\" --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent codex --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent claude --json\nORCA orchestration check --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nIf `worker-start` exits non-zero, do not relaunch. Read the receipt's\n`failedStage` and `residualResources`, then load\n`references/recovery-and-cleanup.md`.\n\nUse `task-create` plus `worker-start --task ` for planned fan-out with\ndependencies or a retry of a known Task. Use dependencies only for real ordering\nand prefer parallel waves over chains deeper than three or four steps; nested\nworkers obey the depth limit, and a new Run does not reset the caller's depth.\n\nA consuming `check` names its caller with `--terminal `, never `--from`;\nomit it inside the coordinator's own Orca terminal. It returns the bound Run's\noldest FIFO Delivery and replays that batch until acknowledged. Process every\nmessage: reply to questions, validate each `worker_done` against the expected\nactive Dispatch, and decide each settled terminal's next owner before the ack:\n\n```text\nORCA orchestration reply --id --body \"\" --json\nORCA orchestration worker-release --dispatch --json\nORCA orchestration check --ack --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nKeep waiting until every expected Dispatch settles. A timeout or empty result is\na checkpoint, not a failure. Do not stop, retry, release, or launch a duplicate\neditor without the positive proof `## Outcome` requires.\n\nAfter three consecutive empty waits, stop waiting blindly and enumerate with\n`ORCA orchestration worker-list --include-remote --json` (defaults to the bound\nRun; `--run ` overrides; the receipt's `scope` names which), acting on\neach row's `projection.attention` categories, `projection.attention.requiresAction`, and literal `projection.nextAction` argv.\nRows come newest first and page at 100: while `page.hasMore`, follow `page.nextCursor` with `--cursor `.\nA `none` `nextAction` has no argv to run: read `liveness.reason` and keep waiting\nwith `check --wait`. Absence never earns an argv; settlement and pending work still do.\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Then load `references/recovery-and-cleanup.md` and choose\n`worker-stop` or `worker-abandon` explicitly. `unverifiable` is absence,\nincluding when `worker-show` reports `agentWait` null. Absence never authorizes\nstop, abandon, retry, or release; keep waiting or inspect.\n\n`worker-start` is the normal path, composing placement, terminal readiness,\nprompt injection, and supervised resource ownership. `dispatch --inject` leaves\nan operator-created process unsupervised and is only for an expressiveness gap.\n\n## Task-spec contract\n\nEvery Task spec must be self-contained and name:\n\n- **Target:** the files, component, or environment in scope.\n- **Change:** the concrete result to produce.\n- **Constraints:** invariants, compatibility rules, and do-not-touch boundaries.\n- **Ownership:** what this worker may edit and any coordination boundary.\n- **Observable acceptance:** the test, output, or evidence that proves completion.\n\n## Completion accounting\n\nAfter an accepted success or failure report, immediately do exactly one:\n\n1. Reuse the same proven agent terminal for an immediate follow-up Dispatch.\n2. Record user-requested retention with `worker-retain`.\n3. Run `worker-release`.\n\nRelease is post-settlement cleanup, not cancellation. Only an accepted\nsettlement authorizes it; no other observation does. If release is uncertain,\nfollow its exact recovery receipt and never substitute `terminal close`.\n\nA valid `worker_done` settles the Task and Dispatch automatically; do not follow\nit with `task-update --status completed`. Enumerate the terminals still owing a\ndecision with `worker-list --run --terminal-state reclaimable --json`,\nand do not end the coordinator turn until it returns none.\n\n## Conditional references\n\nThis compact guide is sufficient for the normal local loop. At an action gate\nbelow, run `ORCA skills get orchestration --reference references/.md` and\nread only that document; `--references` lists the names. If the CLI rejects\n`--reference`, run `ORCA skills get orchestration --full` once instead: it\nreturns this exact kernel and every reference, so read only the named one. If an\nolder CLI rejects `--full`, keep this kernel's safety floor, use that command's\n`--help`, and never guess newer flags.\n\n| Action gate | Bundled reference |\n| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |\n| Expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` |\n| You are a dispatched worker and the live preamble does not answer your question, or `check` returned an error | `references/worker-contract.md` |\n| New worktree, exact workspace, SSH, WSL, or connected-server placement | `references/placement-and-remote.md` |\n| Inbox replay, follow-up messages, group addresses, or decision gates | `references/messaging-and-gates.md` |\n| Failed/stopped/unknown attempts, retry, stop, abandon, retain, or uncertain release | `references/recovery-and-cleanup.md` |\n| Custom argv or terminal topology that `worker-start` cannot express | `references/low-level-topology.md` |\n| Any legacy label, adopted Run, compatibility receipt, or takeover | `references/legacy-contract-migration.md` |\n\nRetired scheduler commands are not aliases for Run creation. Recovery commands\nmust provide their exact next action; follow it with the same selected executable.\n\n---\n\n# Bundled references\n\nThese references belong to the version-matched guide above. Read only the documents named by its action gates.\n\n\n\n# Coordinator loop\n\nLoad this reference for expanded DAG waves, per-invocation launch preferences,\nsame-terminal reuse, or review ownership. The compact guide remains the source\nof truth for the loop order and completion boundary.\n\n## Ready waves\n\nCreate independent Tasks before the first wait. Encode only real dependencies,\nthen use the ready view as external memory:\n\n```text\nORCA orchestration task-create --spec \"\" --deps --json\nORCA orchestration task-list --ready --brief --json\n```\n\n`--brief` collapses whitespace and caps echoed specs at 160 characters;\n`spec_truncated` identifies shortened rows. Omit it when full specs are needed or\nwhen an older CLI rejects the flag. A nested worker must respect\n`nested_worker_depth_exceeded`; creating another Run does not reset depth.\n\n## Launch preferences\n\nFor a fresh Claude, Codex, Cursor, Antigravity, or Muse terminal, `--model`\naccepts an opaque provider model ID. Pass it only when the user named a model;\notherwise omit it so the worker inherits the user's configured agent default.\nAdd `--effort` only when that model supports it:\n\n```text\nORCA orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\nORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json\n```\n\nOpenCode also accepts `--model` in an existing worktree when the execution host\nverifies its CLI version and model availability. Creating a new worktree with an\nOpenCode model override is unsupported; use `--worktree current` or an existing\nworktree selector, or omit `--model`. OpenCode effort is unsupported. Omit the\nmodel to inherit its configuration; unsupported or unknown hosts refuse the\noverride explicitly.\n\n`--effort` requires `--model`; neither option combines with `--terminal`. A\nconnected worker server must advertise launch-preference support before Orca\nforwards either field. Compare `launch.requested` with `launch.effective`; never\nclaim a model or effort from requested arguments alone.\n\n## Reuse after settlement\n\nChoose the terminal's next owner before acknowledging the Delivery. When the\nsame exact agent has immediate follow-up work, recover the proven handle and\ntransfer cleanup ownership to the new Dispatch:\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-start --task --terminal --json\n```\n\nOtherwise explicitly retain or release the settled worker. Do not leave it live\nonly to inspect output; archived output remains available through `worker-read`.\n\n## Review ownership\n\nA review-only `worker_done` authorizes synthesis of findings, not coordinator\nfile edits. Dispatch or hand off fixes unless the user explicitly assigned them\nto the coordinator. If the user's plan names a next owner, post-review fixes and\nPR preparation remain with that owner; the coordinator routes and synthesizes.\n\n\n\n# Legacy contract migration\n\nLoad this reference only for an authority label, adopted Run, compatibility or\nrecovery receipt, or explicit legacy takeover. A newly created attempt always\nuses the current grammar.\n\n## Authority labels\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported\n command printed with the message, using the same selected executable and\n arguments supplied by the original prompt.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded,\n at-least-once cutover replay. Process it idempotently and acknowledge only\n through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or\n lifecycle mutation.\n- An unlabeled current message uses the current guide and grammar.\n\nAn explicitly selected current Run, attested current binding, current Dispatch,\nor federated attachment takes precedence over legacy fallback. A retained\nadoption record alone does not grant mutation authority. If liveness, principal\nownership, capability, or the exact legacy contract is unproven, degrade to\nread-only inspection and never fall back to local execution.\n\nAdoption preserves the live agent process, PTY/session, terminal handle,\ntab/pane, worktree or folder workspace, Task, and Dispatch. It never restarts or\nreplaces the worker and never revives the retired scheduler. Loss of lifecycle\nauthority does not invalidate the existing process, assignment, or filesystem\nwork. Exact recovery may restore the same PTY once in its original inactive\nbackground tab; it must not spawn, write, signal, stop, switch, focus, split, or\ninject a terminal.\n\n## Compatibility recovery\n\nWhen a compatibility response returns structured next-step arguments, execute\nthose exact arguments with the same selected CLI executable. Do not translate\nfrom memory, broaden the recipient, or retry as a current mutation unless the\nreceipt explicitly authorizes it.\n\nA pending ask, reply, final Dispatch settlement, and consuming check have\ndurable recovery identities. Heartbeat and escalation remain at-least-once\nacross a manual contract-boundary retry. If an ask may already have been\nanswered, run the exact non-consuming recovery check printed by Orca before\ncreating any new question. Never guess among identical question threads.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The\ninitial command commits the question, prints its exact\n`ask --resume ` command, and exits with launcher status `75`. Run\nthat exact resume after the launcher or update boundary. For an attested WSL\nlaunch, preserve the printed `orca-ide` executable and distro route. Older WSL\nworkers without launch proof remain lifecycle read-only even while their\nterminal and filesystem work continue.\n\n## Read-only inspection and takeover\n\nRead-only inspection does not consume mail:\n\n```text\nORCA orchestration run-list --json\nORCA orchestration run-show --id run_legacy_local --json\nORCA orchestration run-show --id --json\nORCA orchestration task-list --run --json\nORCA orchestration inbox --full --json\nORCA orchestration check --terminal --peek --format --json\nORCA terminal read --terminal --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\n`run_legacy_local` is an empty audit tombstone after adoption. Find the ordinary\nRun whose objective is `Recovered orchestration work from a contract update`.\n\nOnly when the original coordinator is unavailable or cannot prove retained\nauthority may a new live coordinator take over from its own terminal:\n\n```text\nORCA orchestration run-use --id --takeover-legacy --json\nORCA orchestration check --run --json\n```\n\nTakeover binds the authenticated invoking terminal; `--from` cannot nominate\nanother coordinator. It fences only the old coordinator and moves pending mail\ninto current Run delivery. It preserves live workers, Tasks, Dispatches, processes, and files.\nNever take over while the original coordinator is actively coordinating.\n\nDo not launch a replacement editor merely because Orca updated or authority is\nunclear. Keep the original worker as the only editor until a stable handoff\npoint, then use a fresh current Dispatch in a conflict-free placement.\n\n\n\n# Low-level topology\n\nLoad this reference only when `worker-start` cannot express required custom argv\nor terminal topology. It is not the normal supervised loop and is never a full\nhandoff recipe.\n\n```text\nORCA terminal create --worktree active --title --command \"\" --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\nORCA orchestration dispatch --task --to --inject --json\n```\n\nWait for readiness only when startup could lose injected input. Prefer\nagent-first `worker-start` whenever its argv and topology are sufficient.\n\n`dispatch --inject` creates authoritative Task/Dispatch context but deliberately\nkeeps an operator-created process unsupervised: it creates no supervised worker\nresource row. `worker-show`, `worker-read`, and `worker-list` report the lane as\n`unsupervised`; `worker-stop` and `worker-abandon` do not close that process, and\nsettled retain/release take no process action.\n\nUse `worker-start --terminal ` when lifecycle ownership of an existing\nagent terminal is required. Never imply that low-level dispatch retroactively\nowns a process, never use it to route around the nested-depth limit, and never\nuse it for an ownership handoff.\n\n\n\n# Messaging and gates\n\nLoad this reference for inbox replay, attempt-specific guidance, group\naddresses, blocking questions, or coordinator-managed DAG decisions.\n\nA successful `send` proves durable enqueue. Wake and nudge are best-effort\nattention only: neither proves the recipient read the message, began a turn, or\naccepted steering.\n\n## Coordinator delivery loop\n\n`check` names its caller with `--terminal ` and is the only verb that\nrejects `--from`. Omit `--terminal` inside an Orca terminal, where Orca resolves\nthe caller; pass it explicitly from anywhere else, including a dispatched\nworker reading coordinator follow-ups.\n\nA consuming coordinator `check` returns the bound Run's oldest FIFO Delivery,\nup to 50 messages, and replays that exact batch until acknowledged. Process\nevery row and required terminal ownership decision before `--ack`. Type filters\ndecide when a waiter wakes; they do not authorize skipping older actionable\nmail. A Delivery therefore always carries the whole FIFO batch whatever its\ntypes, and a `check` without `--wait` hands that batch over unfiltered.\n`--peek` and `--all` are read-only inspection, not progress through the\ncoordinator inbox.\n\nAn empty wait or timeout is a checkpoint. Continue rolling waits until every\nexpected Dispatch settles. Heartbeat or visible activity means alive, not done.\n\n## Addresses\n\nUse a stable Dispatch address for attempt-specific coordinator guidance:\n\n```text\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nDo not substitute a remote terminal handle. Omit `--from` for ordinary\ncoordinator calls; a dispatched worker instead copies the exact `--from` and\nother arguments in its preamble. `check` is the exception: it identifies\nits caller with `--terminal`, never `--from`.\n\nGroup addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`,\n`@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`. Every group but\n`@worktree:` means the live Dispatches of the sender's own Run. Mail goes\nto each `dispatch:` mailbox, except a worker coordinating a child Run\nreceives it in that `run:` mailbox. A sender bound to no Run is refused;\n`--run` must match the group audience and never grants membership.\nA Run group excludes its owning coordinator; a worker raising a blocker sends\nto `run:`. A worker that created its own Run addresses that Run's workers,\nnot its siblings. `@worktree:` reaches matching workspace terminals,\nincluding coordinators. Use groups only for intentional fan-out status or\nquestions. `worker_done`, heartbeat, and other\nDispatch lifecycle messages never target groups.\n\n## Questions and gates\n\nA worker uses `ask`; its timeout leaves one durable question pending, which the\nworker resumes by message ID. The coordinator answers that message with `reply`.\n\nUse a gate only for a coordinator-owned Task-DAG decision:\n\n```text\nORCA orchestration gate-create --task --question \"\" --options --json\nORCA orchestration gate-resolve --id --resolution \"\" --json\nORCA orchestration gate-list --task --json\n```\n\nPass `json_array` using the quoting rules of the active shell; do not copy POSIX\nsingle-quote syntax into PowerShell or `cmd.exe`.\n\nDo not create a gate merely to answer a worker's `ask`.\n\n\n\n# Placement and remote execution\n\nLoad this reference before creating a new worktree or placing work through SSH,\nWSL, or another connected Orca server.\n\n## Placement choices\n\nA fresh worker means a fresh agent terminal, not a new Git worktree. Use the\ncurrent or an exact existing workspace by default. Create a worktree only when\nthe user requested one or a concrete checkout or filesystem conflict makes\nsharing unsafe.\n\n```text\n# Current workspace; setup is not rerun.\nORCA orchestration worker-start --task --worktree current --agent codex --json\n\n# Stacked child worktree.\nORCA orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n\n# Independent top-level worktree.\nORCA orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nCurrent and exact existing workspaces create a fresh terminal unless\n`--terminal` is explicit. Folder workspaces are first-class; do not invoke Git\nor require worktree lineage when the selected workspace is a folder.\n\nRegister a folder workspace through project setup. `repo add --path `\nrequires a valid Git repository and rejects a plain directory:\n\n```text\nORCA project setup-existing-folder --project --host --path --kind folder --json\n```\n\nThen place work on the returned workspace with an exact selector. A worktree\nselector needs the full `::` value Orca returned, passed as\n`id:`; a bare repo id is not a worktree id. `new-child` and\n`new-top-level` are worktree creation and do not apply to a folder.\n\nNew worktrees use agent-first creation and run setup by default. Preserve the\nrepository's startup policy: `start-immediately` can report setup as `running`,\nwhile `wait-for-setup` gates prompt delivery on success. Orca lineage, Git base,\nfilesystem isolation, coordination parentage, UI grouping, and execution host\nare separate decisions.\n\n## Connected servers\n\nThe Run and Tasks remain authoritative on the current server. `--on` selects\nonly the worker's execution server and appears only on `worker-start`:\n\n```text\nORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run --json\n```\n\nRemote `current` and `new-child` are invalid because they are ambiguous across\nservers. Use an exact discovered remote workspace, or `new-top-level` with an\nexact remote repository selector. After start, route every follow-up, read,\nstop, and cleanup by Dispatch ID; never repeat `--on` or substitute a remote\nterminal handle.\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\nORCA orchestration worker-list --run --include-remote --json\n```\n\n`worker-list` reads local fleet state only; enumerate remote workers with\n`--include-remote` or every one of them reads `unverifiable`. Scope every list\nwith `--run `: unscoped, it reports every Dispatch this runtime has\nrecorded, and the workers you are waiting on are lost in that history.\n\n## Execution-host and mixed-version floor\n\nThe execution host owns process, filesystem, transcript, stop, and cleanup\nfacts. Render only `live`, `unverifiable`, or `exited`. Connection loss, relay\nabsence, missing client inventory, or timeout yields `unverifiable`, never\nsynthetic exit and never a client-local substitute action.\n\nClients and servers update independently. Optional response fields may be\nabsent. Forward model/effort, transcript reads, cleanup, or another new remote\noperation only when the peer advertises the relevant capability; unknown stream\nopcodes can be silently dropped. A narrow unsupported response may degrade to a\ndocumented older path, but must not broaden the target or cross the execution\nboundary. Changing host-published content reaches old clients even without a\nwire-shape change, so preserve established semantics or negotiate the behavior.\n\nFor WSL, use the exact executable and arguments returned by Orca so the distro\nand packaged launcher remain bound. Do not translate a printed `orca-ide`\nrecovery command into a PATH-resolved local command.\n\n\n\n# Recovery and cleanup\n\nLoad this reference only after a failed/stopped/unknown attempt, explicit retry\ndecision, stop/abandon request, retention request, or uncertain release.\n\n| Proven state | Safe action |\n| ----------------------- | ------------------------------------------------------------------ |\n| `ready` or active | Keep waiting; optionally read bounded output |\n| `failed` or `stopped` | Start a replacement with `--retry-of`; repeat placement explicitly |\n| `outcome_unknown` | Inspect, then choose `worker-stop` or explicit `worker-abandon` |\n| Accepted `worker_done` | Reuse, retain, or release |\n| Remote contact lost | Preserve `unverifiable`; do not stop or retry from absence alone |\n| `unverifiable` liveness | Keep waiting or inspect; never stop, abandon, retry, or release |\n| Proven `exited` agent | Enumerate with `worker-list`; follow its `nextAction` |\n\n## Inspect before acting\n\n```text\nORCA orchestration worker-list --run --json\nORCA orchestration worker-list --run --include-remote --json\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\n```\n\n`worker-list` is the enumerating command and the authority on agent liveness:\neach row carries `projection.liveness`, `projection.attention.categories`,\n`projection.attention.requiresAction`, and a literal `projection.nextAction`\nargv to run. Always scope it with `--run `; an unscoped list reports\nevery Dispatch this runtime has ever recorded and buries the live ones.\n`worker-show`'s `observation.status` is PTY liveness only, so a `live` terminal\nwhose agent died at a trust prompt still reads `live` there.\n\nWhen the two disagree, the fleet verdict decides — unless the fleet row is\n`unverifiable` for a reason that names a gap on this client rather than a fact\nabout the worker. `missing_status`, `host_unavailable`, and\n`capability_unsupported` are such gaps: the first means this runtime holds no\nstatus row, the second that it could not ask the execution host at all, and the\nthird that a stale peer answered but lacks the fleet-snapshot capability.\nAgainst any of them, a `worker-show` verdict sourced from the execution host is\nthe better evidence and outranks the row. Only `host_unavailable` is contact\nloss; the other two mean the host was never asked or answered without the\ncapability.\n\nThis never promotes absence. `unverifiable` from either command still authorizes\nnothing — only a positive `live` or `exited` verdict does.\n\nA worker started with `--on ` reads `unverifiable` until you\nenumerate with `--include-remote`, which asks its execution host for the\nverdict. Rows come newest first and past 100 the response pages, so follow\n`page.nextCursor` with `--cursor ` until `page.hasMore` is false.\n\n## Stall needs positive evidence\n\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Only then choose `worker-stop` or `worker-abandon`.\n\n`unverifiable` is always absence — `missing_status`, `stale_status`,\n`restored_unconfirmed`, or a remote worker with no connection — and a null\n`agentWait` or an unchanged `worker-read` tail is that same absence seen again.\nAbsence never authorizes stop, abandon, retry, or release: keep waiting, or\ninspect until you hold one of the positive signals above. A `nextAction` that\nnames an inspecting command is asking for evidence, not for cleanup.\n\n`worker-read --source auto` uses a proven provider transcript when available and\notherwise returns bounded terminal output with a typed `fallbackReason`.\nContinue with its top-level cursor, which is pinned to that source. If Orca\nreports `source_changed`, restart without the old cursor. A bounded initial\ntranscript tail can return an EOF cursor that follows only newly appended records;\nread `contentComplete`, `clipping`, and `warnings` before assuming omitted older\nrecords are pageable. Never guess a provider session ID, transcript path, or\nremote terminal handle.\n\n## Was the mutation applied?\n\nWhen a mutation's response was lost and named no Dispatch, do not replay blind.\nEvery orchestration mutation accepts `--retry-request `, which reuses one\noperation identity so Orca can replay, join, or recover it instead of starting a\nduplicate. Ask what happened first:\n\n```text\nORCA orchestration request-show --request --json\n```\n\n`completed` means the mutation already took effect; read its recorded receipt\ninstead of rerunning. `pending` means the original mutation is still running or\nOrca restarted before recording its outcome; replay the original command with\n`--retry-request `. `absent` means this runtime holds no receipt\nunder your caller identity — that is not proof nothing happened, so inspect the\naffected Task, Dispatch, and terminal before deciding whether to retry.\n\nWhen a worker's terminal accepted input but the submit is unconfirmed, use\n`terminal send --wait-submit `: it observes the accepted prompt for that\nlong and, on timeout, returns the input-accepted receipt without resending.\n\n## Refused starts\n\n`dispatch` and `worker-start` refuse the following preflight cases with a stable\n`error.code`; read it before choosing a recovery, and treat `error.data.nextSteps`\nas the exact recovery text. Older hosts may omit `data`, so treat every field as\noptional.\n\n| Code | Meaning | Recovery |\n| -------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n| `task_not_found` | No Task with that id, or not in the bound Run (`data.taskId`, `data.runId`) | Check `task-list --json`; create the Task with `task-create` if it does not exist |\n| `task_not_startable` | Task cannot start now: not `ready`, or invalid `--retry-of` (`data.status`, `data.unmetDependencies`, `data.retryOf`) | Wait for running dependencies with `check --wait`; retry or unblock failed ones; inspect `dispatch-show` if already dispatched |\n| `inject_rejected` | `--inject` refused because no recognized agent runs in the target (`data.terminal`, `data.reason`) | Start a recognized agent there or pick another terminal; or dispatch without `--inject` and use `terminal send` |\n| `runtime_error` | Any other failure, including a target terminal that already owns an active Dispatch | Read the message, inspect state, and do not retry unchanged |\n\n## Retry, stop, and abandon\n\nRetry only a positively proven failed or stopped attempt. Name the failed Task\nwith `--task`, since `--spec` creates a new one. Placement is never silently\ninherited:\n\n```text\nORCA orchestration worker-start --task --retry-of --worktree --agent --json\n```\n\nAfter three consecutive failures for one Task, its dispatch context\ncircuit-breaks and the Task is failed. Do not route around that boundary with a\nnew Run or an unrelated Dispatch.\n\nFor `outcome_unknown`, inspect first, then make an explicit choice:\n\n```text\nORCA orchestration worker-stop --dispatch --json\nORCA orchestration worker-abandon --dispatch --json\n```\n\n`worker-stop` closes only the exact proven supervised agent terminal. It never\ndeletes the worktree, setup terminal, configured tabs, or unrelated processes.\n`worker-abandon` fences orchestration while accepting that resources may remain\nlive; it performs no remote, process, or filesystem action. When it settles a\nworker, it retains an owned terminal by the same rule as `worker-retain`, so Orca\nstops owing its release; a release already committed (`releasing`,\n`release_unknown`) is left as it is. An already-settled worker is left untouched.\n\nTo cancel a Task, settle its worker with `worker-stop` or `worker-abandon`, then\nrecord the reason. A cancelled Task is `failed`, so its dependents stay blocked\nuntil a `--retry-of` replacement completes it:\n\n```text\nORCA orchestration task-update --id --status failed --result cancelled --json\n```\n\n## Retain and release\n\n```text\nORCA orchestration worker-retain --dispatch --json\nORCA orchestration worker-release --dispatch --json\n```\n\nRetain only when the user explicitly wants the settled terminal kept live.\nRelease works after succeeded and failed reports, archives readable output, and\ncloses only the exact terminal owned by that settled Dispatch. Replays may call\nrelease again safely. Reused, pre-existing, setup, coordinator, active,\nuser-taken-over, and unproven terminals are retained.\n\nA `worker-start` that failed before its agent was ready still owns the terminal\nit created. Its receipt names `worker-release`, and `worker-list` reports that\nrow as `reclaimable`; release it there rather than closing the terminal by hand.\n\nNever release because of timeout, TUI idle, heartbeat, status, question,\nescalation, or stale/rejected completion. If the receipt says `release_pending`\nor `release_unknown`, follow its exact recovery action. Never substitute\n`terminal close`.\n\n`orchestration reset` is destructive recovery. Do not run it during active\ncoordination unless the user explicitly abandons that state.\n\n\n\n# Worker contract\n\nThe injected preamble is authoritative. Copy its command rather than\nreconstructing flags. In particular, preserve the exact executable, worker\nhandle, Task ID, and Dispatch ID, and keep any other flag it carries (an older\nOrca host adds `--dispatch-capability`).\n\n## Heartbeat\n\nSend heartbeats only at the cadence required by the live preamble. Skip them\nwhile blocked inside `ask` or `check --wait`; those calls are liveness signals.\n\n```text\nORCA orchestration send --from --type heartbeat --subject \"alive\" --task-id --dispatch-id --phase \"\"\n```\n\nUse typed lifecycle flags, not a hand-written JSON payload. A heartbeat proves\nliveness, never completion.\n\n## Ask and resume\n\nUse Orca `ask` whenever the coordinator must answer. Never open a local question\nTUI the coordinator cannot answer.\n\n```text\nORCA orchestration ask --from --question \"\" --options \",\" --timeout-ms 600000\n\nORCA orchestration ask --from --resume --timeout-ms 600000\n```\n\nA timeout or disconnect leaves the original question pending. Resume its\nmessage ID; do not create a duplicate question.\n\n## Reading coordinator follow-ups\n\nThe coordinator steers a running worker with `send --to dispatch:`. That\nenqueue is durable but does not interrupt you, so nothing arrives unless you\nlook:\n\n```text\nORCA orchestration check --terminal --json\n```\n\nRun it at each natural checkpoint — before starting a new file, after a test\nrun — and once more immediately before `worker_done`, so a redirect or a\ncancellation lands before the Task settles. `check` names its caller with\n`--terminal`, never `--from`. Stop checking after `worker_done`.\n\nIf `check` returns `consumer_fenced`, this process no longer owns its Dispatch:\nthe Attempt was re-attached to another worker or settled without you. Stop, do\nnot send `worker_done`, and do not retry the check. An empty `check` never means\nyou were replaced; `consumer_fenced` is the only way you learn that.\nIf `send` or `ask` returns `consumer_fenced`, the command ran from another\nparty's terminal (a coordinator or another worker); run it from your own terminal.\n\n## Escalation\n\nEscalate only before completion and only when the coordinator must intervene:\n\n```text\nORCA orchestration send --from --type escalation --subject \"Blocked: \" --body \"
\" --task-id --dispatch-id \n```\n\n## Completion\n\nSend exactly one terminal report. `--body` is three sentences: what changed,\nwhat was found, and what remains. Use `--outcome failed` when the requested work\nis not complete; never hide failure in prose or silently exit.\n\nAppend `--files-modified` or `--report-path` only when applicable, using actual\npaths. Do not send documentation placeholders as metadata.\n\n```text\nORCA orchestration send --from --type worker_done --subject \"\" --body \"\" --task-id --dispatch-id --outcome succeeded\n```\n\nAfter `worker_done`, end the dispatched turn and idle. Do not poll, close your\nown terminal, or begin unrelated work. A later direct user instruction is new\nuser-owned work and must not reuse settled lifecycle IDs; a supervised follow-up\narrives with a fresh preamble and Task block.\n" // oxfmt-ignore -const ORCHESTRATION_COORDINATOR_LOOP_REFERENCE_MARKDOWN = "# Coordinator loop\n\nLoad this reference for expanded DAG waves, per-invocation launch preferences,\nsame-terminal reuse, or review ownership. The compact guide remains the source\nof truth for the loop order and completion boundary.\n\n## Ready waves\n\nCreate independent Tasks before the first wait. Encode only real dependencies,\nthen use the ready view as external memory:\n\n```text\nORCA orchestration task-create --spec \"\" --deps --json\nORCA orchestration task-list --ready --brief --json\n```\n\n`--brief` collapses whitespace and caps echoed specs at 160 characters;\n`spec_truncated` identifies shortened rows. Omit it when full specs are needed or\nwhen an older CLI rejects the flag. A nested worker must respect\n`nested_worker_depth_exceeded`; creating another Run does not reset depth.\n\n## Launch preferences\n\nFor a fresh Claude, Codex, Cursor, Antigravity, or Muse terminal, `--model`\naccepts an opaque provider model ID. Pass it only when the user named a model;\notherwise omit it so the worker inherits the user's configured agent default.\nAdd `--effort` only when that model supports it:\n\n```text\nORCA orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\nORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json\n```\n\nOther agents, including `opencode`, reject `--model`; they run the model set in\ntheir own config, so a coordinator wanting a same-model opencode worker relies\non that config.\n\n`--effort` requires `--model`; neither option combines with `--terminal`. A\nconnected worker server must advertise launch-preference support before Orca\nforwards either field. Compare `launch.requested` with `launch.effective`; never\nclaim a model or effort from requested arguments alone.\n\n## Reuse after settlement\n\nChoose the terminal's next owner before acknowledging the Delivery. When the\nsame exact agent has immediate follow-up work, recover the proven handle and\ntransfer cleanup ownership to the new Dispatch:\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-start --task --terminal --json\n```\n\nOtherwise explicitly retain or release the settled worker. Do not leave it live\nonly to inspect output; archived output remains available through `worker-read`.\n\n## Review ownership\n\nA review-only `worker_done` authorizes synthesis of findings, not coordinator\nfile edits. Dispatch or hand off fixes unless the user explicitly assigned them\nto the coordinator. If the user's plan names a next owner, post-review fixes and\nPR preparation remain with that owner; the coordinator routes and synthesizes.\n" +const ORCHESTRATION_COORDINATOR_LOOP_REFERENCE_MARKDOWN = "# Coordinator loop\n\nLoad this reference for expanded DAG waves, per-invocation launch preferences,\nsame-terminal reuse, or review ownership. The compact guide remains the source\nof truth for the loop order and completion boundary.\n\n## Ready waves\n\nCreate independent Tasks before the first wait. Encode only real dependencies,\nthen use the ready view as external memory:\n\n```text\nORCA orchestration task-create --spec \"\" --deps --json\nORCA orchestration task-list --ready --brief --json\n```\n\n`--brief` collapses whitespace and caps echoed specs at 160 characters;\n`spec_truncated` identifies shortened rows. Omit it when full specs are needed or\nwhen an older CLI rejects the flag. A nested worker must respect\n`nested_worker_depth_exceeded`; creating another Run does not reset depth.\n\n## Launch preferences\n\nFor a fresh Claude, Codex, Cursor, Antigravity, or Muse terminal, `--model`\naccepts an opaque provider model ID. Pass it only when the user named a model;\notherwise omit it so the worker inherits the user's configured agent default.\nAdd `--effort` only when that model supports it:\n\n```text\nORCA orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\nORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json\n```\n\nOpenCode also accepts `--model` in an existing worktree when the execution host\nverifies its CLI version and model availability. Creating a new worktree with an\nOpenCode model override is unsupported; use `--worktree current` or an existing\nworktree selector, or omit `--model`. OpenCode effort is unsupported. Omit the\nmodel to inherit its configuration; unsupported or unknown hosts refuse the\noverride explicitly.\n\n`--effort` requires `--model`; neither option combines with `--terminal`. A\nconnected worker server must advertise launch-preference support before Orca\nforwards either field. Compare `launch.requested` with `launch.effective`; never\nclaim a model or effort from requested arguments alone.\n\n## Reuse after settlement\n\nChoose the terminal's next owner before acknowledging the Delivery. When the\nsame exact agent has immediate follow-up work, recover the proven handle and\ntransfer cleanup ownership to the new Dispatch:\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-start --task --terminal --json\n```\n\nOtherwise explicitly retain or release the settled worker. Do not leave it live\nonly to inspect output; archived output remains available through `worker-read`.\n\n## Review ownership\n\nA review-only `worker_done` authorizes synthesis of findings, not coordinator\nfile edits. Dispatch or hand off fixes unless the user explicitly assigned them\nto the coordinator. If the user's plan names a next owner, post-review fixes and\nPR preparation remain with that owner; the coordinator routes and synthesizes.\n" // oxfmt-ignore const ORCHESTRATION_LEGACY_CONTRACT_MIGRATION_REFERENCE_MARKDOWN = "# Legacy contract migration\n\nLoad this reference only for an authority label, adopted Run, compatibility or\nrecovery receipt, or explicit legacy takeover. A newly created attempt always\nuses the current grammar.\n\n## Authority labels\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported\n command printed with the message, using the same selected executable and\n arguments supplied by the original prompt.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded,\n at-least-once cutover replay. Process it idempotently and acknowledge only\n through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or\n lifecycle mutation.\n- An unlabeled current message uses the current guide and grammar.\n\nAn explicitly selected current Run, attested current binding, current Dispatch,\nor federated attachment takes precedence over legacy fallback. A retained\nadoption record alone does not grant mutation authority. If liveness, principal\nownership, capability, or the exact legacy contract is unproven, degrade to\nread-only inspection and never fall back to local execution.\n\nAdoption preserves the live agent process, PTY/session, terminal handle,\ntab/pane, worktree or folder workspace, Task, and Dispatch. It never restarts or\nreplaces the worker and never revives the retired scheduler. Loss of lifecycle\nauthority does not invalidate the existing process, assignment, or filesystem\nwork. Exact recovery may restore the same PTY once in its original inactive\nbackground tab; it must not spawn, write, signal, stop, switch, focus, split, or\ninject a terminal.\n\n## Compatibility recovery\n\nWhen a compatibility response returns structured next-step arguments, execute\nthose exact arguments with the same selected CLI executable. Do not translate\nfrom memory, broaden the recipient, or retry as a current mutation unless the\nreceipt explicitly authorizes it.\n\nA pending ask, reply, final Dispatch settlement, and consuming check have\ndurable recovery identities. Heartbeat and escalation remain at-least-once\nacross a manual contract-boundary retry. If an ask may already have been\nanswered, run the exact non-consuming recovery check printed by Orca before\ncreating any new question. Never guess among identical question threads.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The\ninitial command commits the question, prints its exact\n`ask --resume ` command, and exits with launcher status `75`. Run\nthat exact resume after the launcher or update boundary. For an attested WSL\nlaunch, preserve the printed `orca-ide` executable and distro route. Older WSL\nworkers without launch proof remain lifecycle read-only even while their\nterminal and filesystem work continue.\n\n## Read-only inspection and takeover\n\nRead-only inspection does not consume mail:\n\n```text\nORCA orchestration run-list --json\nORCA orchestration run-show --id run_legacy_local --json\nORCA orchestration run-show --id --json\nORCA orchestration task-list --run --json\nORCA orchestration inbox --full --json\nORCA orchestration check --terminal --peek --format --json\nORCA terminal read --terminal --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\n`run_legacy_local` is an empty audit tombstone after adoption. Find the ordinary\nRun whose objective is `Recovered orchestration work from a contract update`.\n\nOnly when the original coordinator is unavailable or cannot prove retained\nauthority may a new live coordinator take over from its own terminal:\n\n```text\nORCA orchestration run-use --id --takeover-legacy --json\nORCA orchestration check --run --json\n```\n\nTakeover binds the authenticated invoking terminal; `--from` cannot nominate\nanother coordinator. It fences only the old coordinator and moves pending mail\ninto current Run delivery. It preserves live workers, Tasks, Dispatches, processes, and files.\nNever take over while the original coordinator is actively coordinating.\n\nDo not launch a replacement editor merely because Orca updated or authority is\nunclear. Keep the original worker as the only editor until a stable handoff\npoint, then use a fresh current Dispatch in a conflict-free placement.\n" diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index a03bd6c8023..43674b9d757 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -36,7 +36,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'Current and existing worktrees never rerun setup; a fresh agent terminal is created unless --terminal is explicit.', 'When reusing --terminal, pass --worktree for that terminal; current means the coordinator worktree.', '--agent takes an Orca agent id enabled on the worker server, such as claude, codex, cursor, antigravity, muse, zcode, opencode, or opencode2.', - '--model supports Claude, Codex, Cursor, Antigravity, and Muse opaque provider model ids; --effort requires --model. OMP accepts --model only; --effort is unsupported. Neither can combine with --terminal. Other agents, including opencode and zcode, launch with the model from their own config.', + '--model supports Claude, Codex, Cursor, Antigravity, and Muse opaque provider model ids; --effort requires --model. OMP accepts --model only; --effort is unsupported. Neither can combine with --terminal. OpenCode model selection requires an existing worktree, a verified execution-host CLI, and an available model; effort is unsupported. Other agents, including zcode, launch with the model from their own config.', 'New worktrees use agent-first creation and default --setup to run. Repository start-immediately runs setup beside the agent; wait-for-setup gates agent readiness and task input.', 'Creation flags (--name, --repo, --base-branch, --display-name, --comment, --setup) are rejected for current/existing worktrees. Use exact --repo on the selected server; project/host convenience routing remains on worktree create.', "How the worker runs follows the user's own setting for new agent tabs; there is no flag for it and no caller needs to ask. A dispatch the setting cannot apply to still starts, so the placement, agent, and launch options passed here are always the ones honoured.", diff --git a/src/main/agent-launch/__fixtures__/host-agent-startup-call-sites.txt b/src/main/agent-launch/__fixtures__/host-agent-startup-call-sites.txt index de078fd731e..193c69c2765 100644 --- a/src/main/agent-launch/__fixtures__/host-agent-startup-call-sites.txt +++ b/src/main/agent-launch/__fixtures__/host-agent-startup-call-sites.txt @@ -2,9 +2,8 @@ # attributes a fresh agent the host builds; carries agentStartedTelemetry # resume continues an existing agent session; not a new start # mobile-followup the phone's session-tab launch; attribution is a separate follow-up -# The resolve-worktree-removal-target call also serves a bare typed command, which stays unattributed. -src/main/runtime/orca-runtime-create-agent-session.ts 2 attributes -src/main/runtime/orca-runtime-resolve-worktree-removal-target.ts 1 attributes +# The shared execution-host builder also serves bare commands; only fresh-agent callers supply attribution. +src/main/opencode/opencode-model-startup-plan.ts 2 attributes src/main/runtime/runtime-worktree-agent-startup.ts 3 attributes src/main/runtime/orca-runtime-get-agent-session-execution-namespace.ts 1 resume src/main/runtime/orca-runtime-resolve-mobile-session-terminal-command.ts 1 mobile-followup diff --git a/src/main/agent-launch/agent-launch-executor.ts b/src/main/agent-launch/agent-launch-executor.ts index 1d9bae4f45d..ac1511d1258 100644 --- a/src/main/agent-launch/agent-launch-executor.ts +++ b/src/main/agent-launch/agent-launch-executor.ts @@ -25,6 +25,7 @@ * is injected as a factory instead of branched on here. */ +import { assertOpenCodeModelLaunchPreferencesAbsent } from '../opencode/opencode-model-startup-plan' import { parsePaneKey } from '../../shared/stable-pane-id' import type { AgentLaunchIntent, @@ -76,6 +77,9 @@ export async function executeAgentLaunch( execution: AgentLaunchExecution ): Promise { const { intent, runtime } = execution + if (intent.reuseTerminal || intent.target.kind === 'create-worktree') { + assertOpenCodeModelLaunchPreferencesAbsent(intent.agent, intent.sessionOptions) + } const vocabulary = execution.vocabulary ?? DEFAULT_LAUNCH_VOCABULARY const settings = readAgentLaunchModeSettings(runtime) const preflight = decideAgentLaunchMode({ diff --git a/src/main/agent-launch/agent-launch-opencode-model.test.ts b/src/main/agent-launch/agent-launch-opencode-model.test.ts new file mode 100644 index 00000000000..39906f8c779 --- /dev/null +++ b/src/main/agent-launch/agent-launch-opencode-model.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it, vi } from 'vitest' +import type { AgentLaunchIntent } from '../../shared/agent-launch-intent' +import { executeAgentLaunch } from './agent-launch-executor' + +function harness() { + const readSettings = vi.fn(() => { + throw new Error('settings_not_needed_for_refusal') + }) + const createSupport = vi.fn(async () => { + throw new Error('support_not_needed_for_refusal') + }) + const createTerminal = vi.fn(async () => ({ handle: 'term_new' })) + const deliverPrompt = vi.fn(async () => true) + const createWorktree = vi.fn(async () => ({ + worktreeId: 'wt_new', + startupTerminalHandle: 'term_new' + })) + return { + readSettings, + createTerminal, + deliverPrompt, + createWorktree, + run: (intent: AgentLaunchIntent) => + executeAgentLaunch({ + intent, + runtime: { + getClientSettings: readSettings, + getStructuredAgentSessionCreateSupport: createSupport + }, + surfaces: { + createTerminalAgent: createTerminal, + createStructuredSession: async () => { + throw new Error('structured_not_expected') + }, + deliverTerminalPrompt: deliverPrompt + }, + workspaces: { createWorktree } + }) + } +} + +const reused: AgentLaunchIntent = { + agent: 'opencode', + target: { kind: 'existing', worktree: 'folder:private' }, + reuseTerminal: { handle: 'term_existing' }, + prompt: { text: 'Read only', delivery: 'submit' }, + sessionOptions: { model: 'private-proof/model-b' } +} +const creating: AgentLaunchIntent = { + ...reused, + reuseTerminal: undefined, + target: { kind: 'create-worktree', create: { repo: 'id:private', name: 'task' } } +} + +describe('OpenCode model preferences on unsupported launch placements', () => { + it.each([reused, creating])( + 'refuses before reading settings or creating or delivering', + async (intent) => { + const h = harness() + await expect(h.run(intent)).rejects.toMatchObject({ code: 'capability_unsupported' }) + expect(h.readSettings).not.toHaveBeenCalled() + expect(h.createTerminal).not.toHaveBeenCalled() + expect(h.createWorktree).not.toHaveBeenCalled() + expect(h.deliverPrompt).not.toHaveBeenCalled() + } + ) + + it('preserves prompt delivery to a reused terminal without model preferences', async () => { + const h = harness() + expect((await h.run({ ...reused, sessionOptions: undefined })).outcome).toEqual({ + kind: 'terminal', + handle: 'term_existing' + }) + expect(h.deliverPrompt).toHaveBeenCalledOnce() + expect(h.createWorktree).not.toHaveBeenCalled() + }) + + it('preserves ordinary worktree creation without model preferences', async () => { + const h = harness() + expect((await h.run({ ...creating, sessionOptions: undefined })).worktreeId).toBe('wt_new') + expect(h.createWorktree).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/opencode/opencode-model-availability.test.ts b/src/main/opencode/opencode-model-availability.test.ts new file mode 100644 index 00000000000..f8b3fdf552c --- /dev/null +++ b/src/main/opencode/opencode-model-availability.test.ts @@ -0,0 +1,105 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { runProcess } from '../../shared/child-process/run-process' +import { resolveCommandOnLocalPath } from '../ipc/command-path-resolver' +import { + probeOpenCodeModelAvailability, + resolveOpenCodeDirectModelExecutable +} from './opencode-model-availability' +vi.mock('../../shared/child-process/run-process', () => ({ runProcess: vi.fn() })) +vi.mock('../ipc/command-path-resolver', () => ({ resolveCommandOnLocalPath: vi.fn() })) +const options = { + command: '/private/opencode', + model: 'opencode/fledge-alpha-free', + cwd: '/tmp/project', + env: { OPENCODE_CONFIG_DIR: '/private/config', XDG_DATA_HOME: '/private/account' } +} +describe('OpenCode model catalog validation', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(resolveCommandOnLocalPath).mockResolvedValue('/resolved/opencode') + vi.mocked(runProcess).mockResolvedValue({ + code: 0, + timedOut: false, + stdout: 'opencode/fledge-alpha-free\nopencode/big-pickle\n', + stderr: '', + signal: null + }) + }) + it('checks exact catalog membership using the execution scope', async () => { + expect(await probeOpenCodeModelAvailability(options)).toBe(true) + expect(runProcess).toHaveBeenCalledWith( + expect.objectContaining({ + program: '/resolved/opencode', + args: ['models'], + cwd: options.cwd, + env: options.env + }) + ) + }) + it('resolves the default PATH executable before checking model availability', async () => { + expect(await resolveOpenCodeDirectModelExecutable({ ...options, command: 'opencode' })).toBe( + '/resolved/opencode' + ) + expect(resolveCommandOnLocalPath).toHaveBeenCalledWith('opencode', { + env: options.env, + cwd: options.cwd + }) + }) + it('rejects the real invalid selector that falls back to Big Pickle', async () => { + expect(await probeOpenCodeModelAvailability({ ...options, model: 'gpt-5-nano' })).toBe(false) + }) + it('does not accept substrings or verbose metadata', async () => { + expect(await probeOpenCodeModelAvailability({ ...options, model: 'fledge-alpha-free' })).toBe( + false + ) + }) + it('refuses timed out catalog probes even with matching partial output', async () => { + vi.mocked(runProcess).mockResolvedValue({ + code: 0, + timedOut: true, + stdout: options.model, + stderr: '', + signal: null + }) + expect(await probeOpenCodeModelAvailability(options)).toBe(false) + }) + it('refuses a truncated catalog even when its retained head contains the model', async () => { + vi.mocked(runProcess).mockResolvedValue({ + code: 0, + timedOut: false, + outputTruncated: true, + stdout: `${options.model}\n`, + stderr: '', + signal: null + }) + expect(await probeOpenCodeModelAvailability(options)).toBe(false) + }) + it('refuses the unterminated catalog shape captured from OpenCode 2.0.16', async () => { + vi.mocked(runProcess).mockResolvedValue({ + code: 0, + timedOut: false, + outputTruncated: false, + stdout: `${options.model}\npriv`, + stderr: '', + signal: null + }) + expect(await probeOpenCodeModelAvailability(options)).toBe(false) + }) + it.each(['\n', '\r\n'])('accepts a complete catalog with %j line endings', async (ending) => { + vi.mocked(runProcess).mockResolvedValue({ + code: 0, + timedOut: false, + outputTruncated: false, + stdout: `${options.model}${ending}`, + stderr: '', + signal: null + }) + expect(await probeOpenCodeModelAvailability(options)).toBe(true) + }) + it('refuses WSL until its exact guest launch environment is available', async () => { + expect(await probeOpenCodeModelAvailability({ ...options, wsl: { distro: 'Ubuntu' } })).toBe( + false + ) + expect(runProcess).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/opencode/opencode-model-availability.ts b/src/main/opencode/opencode-model-availability.ts new file mode 100644 index 00000000000..ce507de9969 --- /dev/null +++ b/src/main/opencode/opencode-model-availability.ts @@ -0,0 +1,59 @@ +import { resolveStartupShell, tokenizeStartupCommand } from '../../shared/tui-agent-startup-shell' +import { runProcess } from '../../shared/child-process/run-process' +import { resolveCommandOnLocalPath } from '../ipc/command-path-resolver' + +export async function resolveOpenCodeDirectModelExecutable(options: { + command: string | undefined + model: string + env: NodeJS.ProcessEnv + cwd?: string + wsl?: { distro?: string } +}): Promise { + // WSL needs the same guest account/profile environment as its actual launch. + if (options.wsl || !options.cwd) { + return null + } + const parsed = tokenizeStartupCommand( + options.command ?? '', + resolveStartupShell(process.platform) + ) + if ( + !parsed.ok || + parsed.tokens.length !== 1 || + parsed.spans.some((span) => span.divergesFromShell) + ) { + return null + } + return resolveCommandOnLocalPath(parsed.tokens[0], { + env: options.env, + cwd: options.cwd + }) +} + +export async function probeOpenCodeModelAvailability( + options: Parameters[0] +): Promise { + const executable = await resolveOpenCodeDirectModelExecutable(options) + if (!executable) { + return false + } + try { + const result = await runProcess({ + program: executable, + args: ['models'], + cwd: options.cwd, + env: options.env, + timeoutMs: 10_000, + maxOutputBytes: 1_048_576 + }) + return ( + result.code === 0 && + !result.timedOut && + !result.outputTruncated && + result.stdout.endsWith('\n') && + result.stdout.split(/\r?\n/).some((line) => line === options.model) + ) + } catch { + return false + } +} diff --git a/src/main/opencode/opencode-model-startup-plan.test.ts b/src/main/opencode/opencode-model-startup-plan.test.ts new file mode 100644 index 00000000000..0740bacfb0d --- /dev/null +++ b/src/main/opencode/opencode-model-startup-plan.test.ts @@ -0,0 +1,116 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { resolveAgentStartupPlanInputs } from '../../shared/agent-startup-plan-inputs' +import { probeOpenCodeLaunchCapabilities } from './opencode-launch-capabilities' +import { + probeOpenCodeModelAvailability, + resolveOpenCodeDirectModelExecutable +} from './opencode-model-availability' +import { buildExecutionHostAgentStartupPlan } from './opencode-model-startup-plan' + +vi.mock('../managed-data-accounts/launch-environment', () => ({ + applyManagedDataAccountEnvironment: vi.fn() +})) +vi.mock('./opencode-launch-capabilities', () => ({ probeOpenCodeLaunchCapabilities: vi.fn() })) +vi.mock('./opencode-model-availability', () => ({ + probeOpenCodeModelAvailability: vi.fn(), + resolveOpenCodeDirectModelExecutable: vi.fn() +})) + +function scope() { + return { + inputs: resolveAgentStartupPlanInputs({ + agent: 'opencode', + settings: { agentCmdOverrides: {} }, + platform: process.platform, + isRemote: false, + sessionOptions: { model: 'private-proof/model-b' } + }), + cwd: '/private/project', + prompt: 'Read only', + hostIdentity: 'host' + } +} + +describe('verified legacy execution-host model startup', () => { + beforeEach(() => { + vi.resetAllMocks() + vi.mocked(resolveOpenCodeDirectModelExecutable).mockResolvedValue('/resolved/opencode') + vi.mocked(probeOpenCodeModelAvailability).mockResolvedValue(true) + vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ + version: '1.18.30', + pluginApi: 'v1', + promptMode: 'submit' + }) + }) + + it.each(['1.18.30', '1.18.32'])( + 'verifies the default executable and exact model on %s', + async (version) => { + vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ + version, + pluginApi: 'v1', + promptMode: 'submit' + }) + const plan = await buildExecutionHostAgentStartupPlan(scope()) + expect(plan?.launchCommand).toContain('--model') + expect(resolveOpenCodeDirectModelExecutable).toHaveBeenCalledWith( + expect.objectContaining({ command: 'opencode' }) + ) + expect(probeOpenCodeModelAvailability).toHaveBeenCalledWith( + expect.objectContaining({ + command: 'opencode', + model: 'private-proof/model-b', + cwd: '/private/project' + }) + ) + } + ) + + it('refuses a missing model even when the CLI could silently use its default', async () => { + vi.mocked(probeOpenCodeModelAvailability).mockResolvedValue(false) + await expect(buildExecutionHostAgentStartupPlan(scope())).rejects.toMatchObject({ + code: 'capability_unsupported' + }) + }) + + it.each(['1.18.31', '2.0.16', '9.0.0'])( + 'refuses unverified legacy support for %s', + async (version) => { + vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ + version, + pluginApi: 'v1', + promptMode: 'submit' + }) + await expect(buildExecutionHostAgentStartupPlan(scope())).rejects.toMatchObject({ + code: 'capability_unsupported' + }) + expect(probeOpenCodeModelAvailability).not.toHaveBeenCalled() + } + ) + + it('refuses remote, WSL, and extra preferences before a local probe', async () => { + const options = scope() + options.inputs.isRemote = true + await expect(buildExecutionHostAgentStartupPlan(options)).rejects.toMatchObject({ + code: 'capability_unsupported' + }) + options.inputs.isRemote = false + await expect( + buildExecutionHostAgentStartupPlan({ ...options, isWsl: true }) + ).rejects.toMatchObject({ code: 'capability_unsupported' }) + options.inputs.sessionOptions = { model: 'private-proof/model-b', effort: 'high' } + await expect(buildExecutionHostAgentStartupPlan(options)).rejects.toMatchObject({ + code: 'capability_unsupported' + }) + expect(resolveOpenCodeDirectModelExecutable).not.toHaveBeenCalled() + }) + + it('preserves an ordinary launch without probing or overriding its own model', async () => { + const options = scope() + options.inputs.sessionOptions = undefined + expect((await buildExecutionHostAgentStartupPlan(options))?.launchCommand).not.toContain( + '--model' + ) + expect(probeOpenCodeLaunchCapabilities).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/opencode/opencode-model-startup-plan.ts b/src/main/opencode/opencode-model-startup-plan.ts new file mode 100644 index 00000000000..a520a6c5696 --- /dev/null +++ b/src/main/opencode/opencode-model-startup-plan.ts @@ -0,0 +1,125 @@ +import type { AgentStartupPlanInputs } from '../../shared/agent-startup-plan-inputs' +import { buildAgentDraftLaunchPlan, buildAgentStartupPlan } from '../../shared/tui-agent-startup' +import type { SleepingAgentLaunchConfig } from '../../shared/agent-session-resume' +import type { TuiAgent } from '../../shared/tui-agent' +import { isVerifiedOpenCodeLegacyModelVersion } from './opencode-model-version-policy' +import { getTuiAgentLaunchCommand, TUI_AGENT_CONFIG } from '../../shared/tui-agent-config' +import { applyManagedDataAccountEnvironment } from '../managed-data-accounts/launch-environment' +import { OrchestrationError } from '../runtime/orchestration/orchestration-error' +import { probeOpenCodeLaunchCapabilities } from './opencode-launch-capabilities' +import { + probeOpenCodeModelAvailability, + resolveOpenCodeDirectModelExecutable +} from './opencode-model-availability' + +type StartupScope = { + inputs: AgentStartupPlanInputs + cwd: string + isWsl?: boolean + hostIdentity?: string + signal?: AbortSignal +} + +function refuseModel(): never { + throw new OrchestrationError( + 'capability_unsupported', + 'The execution host cannot verify this OpenCode model launch.' + ) +} + +export async function prepareOpenCodeModelStartupInputs( + options: StartupScope +): Promise<{ inputs: AgentStartupPlanInputs; launchConfig?: SleepingAgentLaunchConfig }> { + const { inputs } = options + const model = inputs.sessionOptions?.model + if ( + inputs.agent !== 'opencode' || + !Object.values(inputs.sessionOptions ?? {}).some((value) => value !== undefined) + ) { + return { inputs } + } + if (typeof model !== 'string' || model.trim().length === 0) { + refuseModel() + } + if ( + Object.entries(inputs.sessionOptions ?? {}).some( + ([key, value]) => key !== 'model' && value !== undefined + ) || + inputs.isRemote || + options.isWsl || + inputs.platform !== process.platform || + options.signal?.aborted + ) { + refuseModel() + } + const command = + inputs.cmdOverrides.opencode || + getTuiAgentLaunchCommand(TUI_AGENT_CONFIG.opencode, inputs.platform) + const env: Record = {} + for (const [key, value] of Object.entries({ ...process.env, ...inputs.agentEnv })) { + if (value !== undefined) { + env[key] = value + } + } + applyManagedDataAccountEnvironment(env, { launchAgent: 'opencode' }) + const executable = await resolveOpenCodeDirectModelExecutable({ + command, + model, + cwd: options.cwd, + env + }) + if (!executable) { + refuseModel() + } + const capabilities = await probeOpenCodeLaunchCapabilities({ + command, + agent: 'opencode', + cwd: options.cwd, + env, + hostIdentity: options.hostIdentity + }) + if (isVerifiedOpenCodeLegacyModelVersion(capabilities?.version)) { + if (!(await probeOpenCodeModelAvailability({ command, model, cwd: options.cwd, env }))) { + refuseModel() + } + return { inputs } + } + refuseModel() +} + +export async function buildExecutionHostAgentStartupPlan( + options: StartupScope & { + prompt: string + promptDelivery?: 'auto-submit' | 'draft' + } +) { + const prepared = await prepareOpenCodeModelStartupInputs(options) + if (prepared.launchConfig && options.promptDelivery === 'draft') { + refuseModel() + } + const plan = + options.promptDelivery === 'draft' + ? buildAgentDraftLaunchPlan({ ...prepared.inputs, draft: options.prompt }) + : buildAgentStartupPlan({ + ...prepared.inputs, + prompt: options.prompt, + allowEmptyPromptLaunch: true + }) + if (plan && prepared.launchConfig) { + plan.launchConfig = prepared.launchConfig + plan.sessionOptions = { ...options.inputs.sessionOptions } + } + return plan +} + +export function assertOpenCodeModelLaunchPreferencesAbsent( + agent: TuiAgent | undefined, + preferences: Readonly> | undefined +): void { + if ( + agent === 'opencode' && + Object.values(preferences ?? {}).some((value) => value !== undefined) + ) { + refuseModel() + } +} diff --git a/src/main/opencode/opencode-model-version-policy.test.ts b/src/main/opencode/opencode-model-version-policy.test.ts new file mode 100644 index 00000000000..8c8c4f7247e --- /dev/null +++ b/src/main/opencode/opencode-model-version-policy.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest' +import { isVerifiedOpenCodeLegacyModelVersion } from './opencode-model-version-policy' + +describe('verified legacy OpenCode model versions', () => { + it.each(['1.18.30', '1.18.32'])('supports the verified model semantics of %s', (version) => { + expect(isVerifiedOpenCodeLegacyModelVersion(version)).toBe(true) + }) + + it.each([null, undefined, '1.18.29', '1.18.31', '1.18.33', '1.18.32-beta', '2.0.16'])( + 'keeps unverified version %s unsupported', + (version) => { + expect(isVerifiedOpenCodeLegacyModelVersion(version)).toBe(false) + } + ) +}) diff --git a/src/main/opencode/opencode-model-version-policy.ts b/src/main/opencode/opencode-model-version-policy.ts new file mode 100644 index 00000000000..e741a50f89e --- /dev/null +++ b/src/main/opencode/opencode-model-version-policy.ts @@ -0,0 +1,6 @@ +const VERIFIED_LEGACY_MODEL_VERSIONS = new Set(['1.18.30', '1.18.32']) + +export function isVerifiedOpenCodeLegacyModelVersion(version: string | null | undefined): boolean { + // Plugin API compatibility alone does not verify model selection or invalid-model behavior. + return typeof version === 'string' && VERIFIED_LEGACY_MODEL_VERSIONS.has(version) +} diff --git a/src/main/runtime/opencode-model-worktree-create.test.ts b/src/main/runtime/opencode-model-worktree-create.test.ts new file mode 100644 index 00000000000..078a5c5e5e3 --- /dev/null +++ b/src/main/runtime/opencode-model-worktree-create.test.ts @@ -0,0 +1,57 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const resolveRepo = vi.hoisted(() => vi.fn()) +vi.mock('./orca-runtime-get-worktree-terminal-provisioning-host', () => ({ + OrcaRuntimeWithGetWorktreeTerminalProvisioningHost: class { + store = { getSettings: () => ({ disabledTuiAgents: [] }) } + resolveRepoSelector = resolveRepo + } +})) +vi.mock('../workspace-create-telemetry', () => ({ + trackRuntimeWorkspaceCreate: ( + _request: unknown, + execute: (events: { begin: ReturnType }) => Promise + ) => execute({ begin: vi.fn() }) +})) +vi.mock('electron', () => ({ + app: { getPath: () => '/private/test', isPackaged: false }, + BrowserWindow: { fromId: vi.fn() }, + ipcMain: { on: vi.fn(), removeListener: vi.fn() } +})) + +import { OrcaRuntimeWithCreateManagedWorktree } from './orca-runtime-create-managed-worktree' + +describe('unverified OpenCode model worktree creation', () => { + beforeEach(() => { + resolveRepo.mockReset() + resolveRepo.mockRejectedValue(new Error('repo_read_before_model_refusal')) + }) + + it.each(['local-repo', 'folder-repo', 'ssh-repo'])( + 'refuses %s before resolving or creating its workspace', + async (repoSelector) => { + const runtime = new OrcaRuntimeWithCreateManagedWorktree() + await expect( + runtime.createManagedWorktree({ + repoSelector, + name: 'unverified-model', + startupAgent: 'opencode', + startupLaunchPreferences: { model: 'private-proof/model-b' } + }) + ).rejects.toMatchObject({ code: 'capability_unsupported' }) + expect(resolveRepo).not.toHaveBeenCalled() + } + ) + + it('preserves worktree creation without a model preference', async () => { + const runtime = new OrcaRuntimeWithCreateManagedWorktree() + await expect( + runtime.createManagedWorktree({ + repoSelector: 'local-repo', + name: 'ordinary', + startupAgent: 'opencode' + }) + ).rejects.toThrow('repo_read_before_model_refusal') + expect(resolveRepo).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/runtime/orca-runtime-create-agent-session.ts b/src/main/runtime/orca-runtime-create-agent-session.ts index 36e4d3f41a1..b2ba25b7d73 100644 --- a/src/main/runtime/orca-runtime-create-agent-session.ts +++ b/src/main/runtime/orca-runtime-create-agent-session.ts @@ -17,7 +17,7 @@ import { } from './orca-runtime-core' import { isTuiAgentEnabled } from '../../shared/tui-agent-selection' import { resolveAgentStartupPlanInputs } from '../../shared/agent-startup-plan-inputs' -import { buildAgentDraftLaunchPlan, buildAgentStartupPlan } from '../../shared/tui-agent-startup' +import { buildExecutionHostAgentStartupPlan } from '../opencode/opencode-model-startup-plan' import type { RuntimeTerminalCreate } from '../../shared/runtime-types' import type { AgentSessionCreateOperation, @@ -159,14 +159,14 @@ export class OrcaRuntimeWithCreateAgentSession extends OrcaRuntimeWithGetAgentSe ...(request.agentArgs !== undefined ? { agentArgs: request.agentArgs } : {}), sessionOptions: this.toAgentSessionOptions(request.launchPreferences) }) - const startup = - request.promptDelivery === 'draft' - ? buildAgentDraftLaunchPlan({ ...startupArgs, draft: request.prompt ?? '' }) - : buildAgentStartupPlan({ - ...startupArgs, - prompt: request.prompt ?? '', - allowEmptyPromptLaunch: true - }) + const startup = await buildExecutionHostAgentStartupPlan({ + inputs: startupArgs, + cwd: startupCwd ?? workspace.path, + prompt: request.prompt ?? '', + promptDelivery: request.promptDelivery, + hostIdentity: this.runtimeId, + signal: caller.signal + }) if (!startup) { throw new Error('agent_session_identity_required') } diff --git a/src/main/runtime/orca-runtime-create-managed-worktree.ts b/src/main/runtime/orca-runtime-create-managed-worktree.ts index 63e3a010772..5e8cf5e9d8a 100644 --- a/src/main/runtime/orca-runtime-create-managed-worktree.ts +++ b/src/main/runtime/orca-runtime-create-managed-worktree.ts @@ -13,15 +13,15 @@ import { prepareRuntimeLocalWorktreeSetup } from './runtime-local-worktree-setup import { invalidateAuthorizedRootsCacheForRepo } from '../ipc/filesystem-auth' import { startRuntimeLocalWorktreeTerminals } from './runtime-local-worktree-terminal-startup' import { trackRuntimeWorkspaceCreate } from '../workspace-create-telemetry' +import { assertOpenCodeModelLaunchPreferencesAbsent } from '../opencode/opencode-model-startup-plan' +import { resolveWorktreeCreateAgentStartup } from './runtime-worktree-agent-startup' import type { RuntimeWorkspaceCreateEvents } from '../workspace-create-telemetry' export class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWithGetWorktreeTerminalProvisioningHost { async createManagedWorktree( args: RuntimeManagedWorktreeCreateArgs ): Promise { - // Why a holder fired in `finally`: consuming a prepared checkout empties a pool slot, so a - // create that fails anywhere after that — include copy, push target, terminal startup — must - // still arm the replacement. On success it fires last, once the startup terminals are up. + // Re-arm a consumed checkout after terminal startup, including failed creates. const rearm: PreparationRearmHolder = { fire: () => {} } try { return await trackRuntimeWorkspaceCreate(args, (events) => @@ -41,6 +41,11 @@ export class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWithGetWork throw new Error('runtime_unavailable') } + assertOpenCodeModelLaunchPreferencesAbsent( + args.startupAgent ?? args.createdWithAgent, + args.startupLaunchPreferences + ) + const repo = await this.resolveRepoSelector(args.repoSelector) const createSettings = this.store.getSettings() const requestedAgent = args.startupAgent ?? args.createdWithAgent @@ -58,19 +63,9 @@ export class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWithGetWork ) { throw new Error('Selected agent is disabled. Choose an enabled agent before creating.') } - const agentStartup = - !args.startup && args.startupAgent - ? this.buildStartupForAgent( - repo, - args.startupAgent, - args.startupPrompt, - args.startupLaunchPreferences, - { - ...(args.startupAgentArgs !== undefined ? { agentArgs: args.startupAgentArgs } : {}), - ...(args.startupLaunchSource ? { launchSource: args.startupLaunchSource } : {}) - } - ) - : null + const agentStartup = resolveWorktreeCreateAgentStartup(args, (...inputs) => + this.buildStartupForAgent(repo, ...inputs) + ) const draftStartup = !args.startup && !agentStartup && args.startupDraft ? await this.buildStartupForDraft( @@ -88,10 +83,7 @@ export class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWithGetWork draftStartup?.agent ?? (requestedAgentEnabled ? requestedAgent : undefined)) const effectiveDraftPaste = args.startupDraftPaste ?? draftStartup?.draftPaste - // Resolve the execution host once, shared with the `worktrees:create` IPC entry point so the - // two cannot answer differently for the same repo. Reading the raw `connectionId` field routes - // an `executionHostId: 'ssh:*'`-only repo down the local path, which runs `git worktree add` on - // the client against a remote path. + // Match IPC routing: executionHostId-only SSH repos must not create locally. const createRoute = resolveWorktreeCreateRoute(repo) if (isFolderRepo(repo)) { // A folder workspace is a registration, not a filesystem create, so it is host-agnostic. diff --git a/src/main/runtime/orca-runtime-get-agent-session-execution-namespace.ts b/src/main/runtime/orca-runtime-get-agent-session-execution-namespace.ts index 7f968a6ba7d..8b03eebd650 100644 --- a/src/main/runtime/orca-runtime-get-agent-session-execution-namespace.ts +++ b/src/main/runtime/orca-runtime-get-agent-session-execution-namespace.ts @@ -13,6 +13,7 @@ import { canonicalizeAgentSessionIdentity } from './agent-session-claim-identity import { isTuiAgentEnabled } from '../../shared/tui-agent-selection' import { resolveLocalWindowsAgentStartupShell } from '../../shared/windows-terminal-shell' import { buildAgentResumeStartupPlan } from '../../shared/tui-agent-startup' +import { OrchestrationError } from './orchestration/orchestration-error' import { resolveTuiAgentLaunchArgs, resolveTuiAgentLaunchEnv @@ -93,6 +94,15 @@ export class OrcaRuntimeWithGetAgentSessionExecutionNamespace extends OrcaRuntim // Legacy renderer sleep records are migration evidence, not host authority. throw new Error('agent_session_resume_not_authorized') } + if ( + request.agent === 'opencode' && + Object.values(request.launchPreferences ?? {}).some((value) => value !== undefined) + ) { + throw new OrchestrationError( + 'capability_unsupported', + 'OpenCode resume preferences are not verified by this execution host.' + ) + } if (!this.store) { throw new Error('runtime_unavailable') } diff --git a/src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts b/src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts index 82969ecb1da..567cbe6896d 100644 --- a/src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts +++ b/src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts @@ -19,6 +19,11 @@ import { resolveLocalWindowsAgentStartupShell } from '../../shared/windows-termi import { resolveStartupShell, type AgentStartupShell } from '../../shared/tui-agent-startup-shell' import { isTuiAgent } from '../../shared/tui-agent-config' import { resolveConfiguredWorkerAgent } from './orchestration/configured-worker-agent-selector' +import { parseWslUncPath } from '../../shared/wsl-paths' +import { resolveLocalProjectRuntimeForRepo } from '../project-runtime-git-options' + +import { prepareOpenCodeModelStartupInputs } from '../opencode/opencode-model-startup-plan' +import { resolveAgentStartupPlanInputs } from '../../shared/agent-startup-plan-inputs' export class OrcaRuntimeWithGetTerminalInteractiveWait extends OrcaRuntimeWithAdoptTerminalOrphansFromInventory { async getTerminalInteractiveWait( @@ -223,6 +228,58 @@ export class OrcaRuntimeWithGetTerminalInteractiveWait extends OrcaRuntimeWithAd return this.resolveOrchestrationAgentLauncher(selector, platform, shell) } + async probeOrchestrationOpenCodeModelLaunchSupport(target: { + worktree?: string + model?: string + }): Promise { + if (!target.model || !target.worktree) { + return false + } + const workspace = await this.resolveTerminalWorkspaceLaunchScope(target.worktree) + const executionRepo = workspace?.repo + if ( + workspace?.connectionId || + (executionRepo?.executionHostId && executionRepo.executionHostId !== 'local') + ) { + return false + } + const store = this.requireStore() + const settings = store.getSettings() + const path = workspace?.path + const unc = path ? parseWslUncPath(path) : null + const projectRuntime = executionRepo + ? resolveLocalProjectRuntimeForRepo(store, executionRepo) + : null + if (projectRuntime?.status === 'repair-required') { + return false + } + const wsl = unc + ? { distro: unc.distro } + : projectRuntime?.runtime.kind === 'wsl' + ? { distro: projectRuntime.runtime.distro } + : undefined + if (!path) { + return false + } + try { + await prepareOpenCodeModelStartupInputs({ + inputs: resolveAgentStartupPlanInputs({ + agent: 'opencode', + settings, + platform: wsl ? 'linux' : process.platform, + isRemote: false, + sessionOptions: { model: target.model } + }), + cwd: path, + isWsl: Boolean(wsl), + hostIdentity: this.getRuntimeId() + }) + return true + } catch { + return false + } + } + validateOrchestrationAgentLauncher(agent: TuiAgent): void { const settings = this.store?.getSettings() if (!settings) { diff --git a/src/main/runtime/orca-runtime-resolve-worktree-removal-target.ts b/src/main/runtime/orca-runtime-resolve-worktree-removal-target.ts index 71b919bbf1b..3febb444395 100644 --- a/src/main/runtime/orca-runtime-resolve-worktree-removal-target.ts +++ b/src/main/runtime/orca-runtime-resolve-worktree-removal-target.ts @@ -25,7 +25,7 @@ import { terminalShellOverrideRefusal } from './terminal-shell-override-host-sup import { resolveTerminalStartupCwd } from '../../shared/terminal-startup-cwd' import { resolveLocalProjectRuntimeForWorktreeId } from '../local-project-runtime-resolution' import { resolveBareAgentLaunchCommand } from './runtime-agent-launch-resolution' -import { buildAgentStartupPlan } from '../../shared/tui-agent-startup' +import { buildExecutionHostAgentStartupPlan } from '../opencode/opencode-model-startup-plan' import { resolveAgentStartupPlanInputs } from '../../shared/agent-startup-plan-inputs' import { agentStartedTelemetry } from '../agent-launch/agent-started-telemetry' import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId } from '../../shared/execution-host' @@ -307,8 +307,8 @@ export class OrcaRuntimeWithResolveWorktreeRemovalTarget extends OrcaRuntimeWith return opts } - const startupPlan = buildAgentStartupPlan({ - ...resolveAgentStartupPlanInputs({ + const startupPlan = await buildExecutionHostAgentStartupPlan({ + inputs: resolveAgentStartupPlanInputs({ agent, settings, platform, @@ -319,7 +319,8 @@ export class OrcaRuntimeWithResolveWorktreeRemovalTarget extends OrcaRuntimeWith sessionOptions: this.toAgentSessionOptions(opts.launchPreferences) }), prompt: opts.startupPrompt ?? '', - allowEmptyPromptLaunch: true + cwd: resolveTerminalStartupCwd(workspace.path, opts.cwd) ?? workspace.path, + hostIdentity: this.runtimeId }) if (!startupPlan) { // Why: an explicit agent that yields no plan would otherwise spawn a bare diff --git a/src/main/runtime/orchestration-opencode-model-host.test.ts b/src/main/runtime/orchestration-opencode-model-host.test.ts new file mode 100644 index 00000000000..6d12025e232 --- /dev/null +++ b/src/main/runtime/orchestration-opencode-model-host.test.ts @@ -0,0 +1,98 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from './orca-runtime' +import { + probeOpenCodeModelAvailability, + resolveOpenCodeDirectModelExecutable +} from '../opencode/opencode-model-availability' +import { probeOpenCodeLaunchCapabilities } from '../opencode/opencode-launch-capabilities' +import { resolveLocalProjectRuntimeForRepo } from '../project-runtime-git-options' + +vi.mock('../opencode/opencode-launch-capabilities', () => ({ + probeOpenCodeLaunchCapabilities: vi.fn() +})) +vi.mock('../opencode/opencode-model-availability', () => ({ + probeOpenCodeModelAvailability: vi.fn(), + resolveOpenCodeDirectModelExecutable: vi.fn() +})) +vi.mock('../managed-data-accounts/launch-environment', () => ({ + applyManagedDataAccountEnvironment: vi.fn() +})) +vi.mock('../project-runtime-git-options', () => ({ resolveLocalProjectRuntimeForRepo: vi.fn() })) + +function host( + scope: { path: string; connectionId?: string; repo?: { executionHostId?: string } } = { + path: '/tmp/folder' + } +) { + return { + resolveTerminalWorkspaceLaunchScope: vi.fn(async () => scope), + resolveRepoSelector: vi.fn(async () => scope), + requireStore: () => ({ + getSettings: () => ({ + agentCmdOverrides: { opencode: '/tmp/private-opencode' }, + agentDefaultEnv: { opencode: { OPENCODE_CONFIG_DIR: '/tmp/private-config' } } + }) + }), + getRuntimeId: () => 'host-1' + } +} +function probe( + runtime: ReturnType, + target = { worktree: 'id:folder', model: 'opencode/fledge-alpha-free' } +) { + return OrcaRuntimeService.prototype.probeOrchestrationOpenCodeModelLaunchSupport.call( + runtime, + target + ) +} + +describe('OpenCode worker model execution host', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(probeOpenCodeModelAvailability).mockResolvedValue(true) + vi.mocked(resolveOpenCodeDirectModelExecutable).mockResolvedValue('/tmp/private-opencode') + vi.mocked(resolveLocalProjectRuntimeForRepo).mockReturnValue(undefined) + vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ + version: '1.18.30', + pluginApi: 'v1', + promptMode: 'submit' + }) + }) + it('probes a local folder with its configured command and environment', async () => { + expect(await probe(host())).toBe(true) + expect(probeOpenCodeLaunchCapabilities).toHaveBeenCalledWith( + expect.objectContaining({ + command: '/tmp/private-opencode', + cwd: '/tmp/folder', + hostIdentity: 'host-1', + env: expect.objectContaining({ OPENCODE_CONFIG_DIR: '/tmp/private-config' }) + }) + ) + }) + it('rejects an unknown selector rather than claiming the fallback model', async () => { + vi.mocked(probeOpenCodeModelAvailability).mockResolvedValue(false) + expect(await probe(host())).toBe(false) + }) + it.each(['v2', 'unknown'] as const)('refuses %s CLI model selection', async (pluginApi) => { + vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ + version: null, + pluginApi, + promptMode: 'unknown' + }) + expect(await probe(host())).toBe(false) + }) + it('never probes the client executable for an SSH workspace', async () => { + expect(await probe(host({ path: '/remote/folder', connectionId: 'ssh-1' }))).toBe(false) + expect(probeOpenCodeLaunchCapabilities).not.toHaveBeenCalled() + }) + it('never probes the client executable for a foreign execution host', async () => { + expect( + await probe(host({ path: '/remote/folder', repo: { executionHostId: 'remote-host' } })) + ).toBe(false) + expect(probeOpenCodeLaunchCapabilities).not.toHaveBeenCalled() + }) + it('refuses WSL without probing a different profile', async () => { + expect(await probe(host({ path: '\\\\wsl.localhost\\Ubuntu\\home\\repo' }))).toBe(false) + expect(probeOpenCodeLaunchCapabilities).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/rpc/methods/agent-launch-failure-code.ts b/src/main/runtime/rpc/methods/agent-launch-failure-code.ts index eac21c7c00e..bf3b4a2ceaa 100644 --- a/src/main/runtime/rpc/methods/agent-launch-failure-code.ts +++ b/src/main/runtime/rpc/methods/agent-launch-failure-code.ts @@ -1,3 +1,4 @@ +import { OrchestrationError } from '../../orchestration/orchestration-error' import type { AgentLaunchTarget } from '../../../../shared/agent-launch-intent' import { WorktreeCreateCollisionError, @@ -27,7 +28,8 @@ const LAUNCH_FAILURE_CODE_MAX_LENGTH = 128 * the entire store. */ export function agentLaunchFailureCode(error: unknown): string { - const code = error instanceof Error ? error.message : '' + const code = + error instanceof OrchestrationError ? error.code : error instanceof Error ? error.message : '' return code.length > 0 ? code.slice(0, LAUNCH_FAILURE_CODE_MAX_LENGTH) : 'agent_launch_failed' } diff --git a/src/main/runtime/rpc/methods/agent-launch-prestart-failure.test.ts b/src/main/runtime/rpc/methods/agent-launch-prestart-failure.test.ts index cfc14ec5504..43eac86e13e 100644 --- a/src/main/runtime/rpc/methods/agent-launch-prestart-failure.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch-prestart-failure.test.ts @@ -8,6 +8,7 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { computeAgentLaunchFingerprint } from '../../../../shared/agent-launch-operation' import type { AgentSessionRecordStore } from '../../agent-session-record-store' import { openTestAgentSessionRecordStore } from '../../agent-session-record-store-test-harness' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' @@ -32,7 +33,12 @@ const CREATE_LAUNCH = { target: { kind: 'create-worktree', create: { repo: 'id:repo-1', name: 'task' } } } const NO_LAUNCH_COMMAND = 'Could not build launch command for claude.' -type Launch = typeof EXISTING_LAUNCH | typeof CREATE_LAUNCH +type Launch = { + agent: string + target: { kind: string; worktree?: string; create?: Readonly> } + sessionOptions?: Readonly> + reuseTerminal?: { handle: string } +} /** The create throws; `afterDispatch` says whether the spawn request had already left. */ function failingCreate(runtime: AgentLaunchRuntimeStub, error: Error, afterDispatch: boolean) { @@ -169,4 +175,75 @@ describe('a launch whose terminal fails', () => { error: { code: 'agent_session_operation_unknown' } }) }) + it.each([ + { ...CREATE_LAUNCH, agent: 'opencode', sessionOptions: { model: 'private-proof/model-b' } }, + { + ...EXISTING_LAUNCH, + agent: 'opencode', + reuseTerminal: { handle: 'term_existing' }, + sessionOptions: { model: 'private-proof/model-b' } + } + ])('records and replays a model refusal before adapter effects', async (launch) => { + const first = runtimeStub({ settings: {} }) + expect(await replay(first, launch)).toMatchObject({ + ok: false, + error: { code: 'capability_unsupported' } + }) + expect(outcomeOf(OPERATION_ID)).toMatchObject({ + status: 'failed', + code: 'capability_unsupported' + }) + expect(first.showRepo).not.toHaveBeenCalled() + expect(first.createManagedWorktree).not.toHaveBeenCalled() + expect(first.createTerminal).not.toHaveBeenCalled() + const retry = runtimeStub({ settings: {} }) + expect(await replay(retry, launch)).toMatchObject({ + ok: false, + error: { code: 'capability_unsupported' } + }) + expect(retry.showTerminalWorkspaceLaunchScope).not.toHaveBeenCalled() + expect(retry.createManagedWorktree).not.toHaveBeenCalled() + }) + + it('preserves a successful recorded model launch even when its placement is now refused', async () => { + const launch = AGENT_LAUNCH_REPLAY.params.parse({ + ...CREATE_LAUNCH, + agent: 'opencode', + sessionOptions: { model: 'private-proof/model-b' }, + operationId: OPERATION_ID + }) + const callerKey = 'trusted-local:runtime' + await store.admitOperation({ + callerKey, + operationId: OPERATION_ID, + fingerprint: computeAgentLaunchFingerprint(launch), + now: Date.now() + }) + await store.claimOperation({ callerKey, operationId: OPERATION_ID }) + await store.recordOperationOutcome({ + callerKey, + operationId: OPERATION_ID, + outcome: { + status: 'succeeded', + sessionId: '', + launch: { + outcome: { kind: 'terminal', handle: 'term_historical' }, + worktreeId: 'wt_historical', + receipt: { + mode: 'terminal', + preferred: 'terminal', + reason: 'user_default', + detail: 'Previously recorded launch' + } + } + } + }) + const runtime = runtimeStub({ settings: {} }) + expect(await replay(runtime, launch)).toMatchObject({ + ok: true, + result: { outcome: { handle: 'term_historical' }, worktreeId: 'wt_historical' } + }) + expect(runtime.showRepo).not.toHaveBeenCalled() + expect(runtime.createManagedWorktree).not.toHaveBeenCalled() + }) }) diff --git a/src/main/runtime/rpc/methods/agent-launch.ts b/src/main/runtime/rpc/methods/agent-launch.ts index 1c7448e5ca2..574dfd1a30f 100644 --- a/src/main/runtime/rpc/methods/agent-launch.ts +++ b/src/main/runtime/rpc/methods/agent-launch.ts @@ -31,6 +31,7 @@ import { WorktreeCreateCollisionError, WORKTREE_CREATE_COLLISION_CODE } from '../../../../shared/new-workspace/worktree-create-collision' +import { assertOpenCodeModelLaunchPreferencesAbsent } from '../../../opencode/opencode-model-startup-plan' import { executeAgentLaunch } from '../../../agent-launch/agent-launch-executor' import { trackTerminalSpawnDispatch, @@ -137,6 +138,9 @@ async function resolveUnlaunchedIntent( params: AgentLaunchParams, runtime: OrcaRuntimeService ): Promise { + if (params.reuseTerminal || params.target.kind === 'create-worktree') { + assertOpenCodeModelLaunchPreferencesAbsent(params.agent, params.sessionOptions) + } const intent = await agentLaunchIntent(params, runtime) await validateReusedTerminal(intent, runtime) return intent @@ -237,7 +241,7 @@ async function executeReplaySafeAgentLaunch( ): Promise { const admission = await admitAgentLaunchOperation(context, params, fingerprint) if (admission.decision === 'refuse') { - throw new Error(admission.refusal.code) + throw Object.assign(new Error(admission.refusal.code), { code: admission.refusal.code }) } if (admission.decision === 'replay') { return admission.result diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation.ts index e88004ff89e..0d6bde6e104 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation.ts @@ -20,7 +20,7 @@ import { } from './federation-setup' import { FederationAttachStartParams } from './federation-start-schema' import { failFederatedAttachmentWithReceipt } from './federation-start-receipt' -import { prepareFederationConfiguredWorkerStart } from '../worker/worker-configured-agent-preflight' +import { prepareFederationWorkerLaunchOnHost } from '../worker/worker-opencode-model-preflight' import { isWorkerStartTimeoutWithinTimerLimit, resolveWorkerStartReadinessTimeoutMs @@ -54,7 +54,7 @@ export const ORCHESTRATION_FEDERATION_ATTACH_METHODS = [ ) } const createsWorktree = params.worktree === 'new-top-level' - const { agent, launch } = await prepareFederationConfiguredWorkerStart({ + const { agent, launch } = await prepareFederationWorkerLaunchOnHost({ params, createsWorktree, runtime diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts index c6d7ef96f68..c964c6f1e17 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts @@ -1,3 +1,4 @@ +import { probeWorkerOpenCodeModelLaunchSupport } from './worker-opencode-model-preflight' import { resolveWorkerConfiguredAgentParams } from './worker-configured-agent-preflight' import { waitForWorkerAgentReady } from '../../../../launched-agent-composer-readiness' import type { OrcaRuntimeService } from '../../../../orca-runtime' @@ -71,10 +72,25 @@ export async function startLocalWorker(args: { worktree: requestedWorktree === 'current' ? `id:${callerWorkspaceId}` : requestedWorktree } }) + let openCodeModelLaunchSupported = false + if (!createsWorktree && launchParams.agent === 'opencode' && launchParams.model) { + const callerWorkspaceId = await resolveDispatchCallerWorktreeId( + runtime, + params.from, + callerSession + ) + openCodeModelLaunchSupported = await probeWorkerOpenCodeModelLaunchSupport( + runtime, + launchParams, + { worktree: requestedWorktree === 'current' ? `id:${callerWorkspaceId}` : requestedWorktree } + ) + } + const { agent, launch } = prepareLocalWorkerStart({ params: launchParams, createsWorktree, - runtime + runtime, + openCodeModelLaunchSupported }) const coordinatorWorktreeId = await resolveDispatchCallerWorktreeId( diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.test.ts index 899a63c0683..481b96840a9 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.test.ts @@ -117,10 +117,48 @@ describe('orchestration worker launch preferences', () => { ).toThrow('does not support effort turbo') }) - it('refuses an opencode model because the opencode 2 TUI rejects --model', () => { + it('refuses an opencode model until the execution host verifies legacy TUI support', () => { expect(() => resolveWorkerLaunchPreferences({ agent: 'opencode', model: 'meta/muse-spark-1.3' }) - ).toThrow('does not support launch-time model selection') + ).toThrow('cannot verify launch-time model selection') + }) + + it('explains the existing-worktree requirement even if a new-worktree host is verified', () => { + expect(() => + resolveWorkerLaunchPreferences({ + agent: 'opencode', + model: 'opencode/fledge-alpha-free', + createsWorktree: true, + openCodeModelLaunchSupported: true + }) + ).toThrow('requires an existing worktree') + }) + + it('supports an opaque OpenCode model on a verified legacy host', () => { + expect( + resolveWorkerLaunchPreferences({ + agent: 'opencode', + model: 'zai-coding-plan/glm-5.3-flash', + openCodeModelLaunchSupported: true + }) + ).toEqual({ + preferences: { model: 'zai-coding-plan/glm-5.3-flash' }, + receipt: { + requested: { agent: 'opencode', model: 'zai-coding-plan/glm-5.3-flash', effort: null }, + effective: { agent: 'opencode', model: 'zai-coding-plan/glm-5.3-flash', effort: null } + } + }) + }) + + it('refuses an unverified OpenCode effort on a legacy host', () => { + expect(() => + resolveWorkerLaunchPreferences({ + agent: 'opencode', + model: 'opencode/fledge-alpha-free', + effort: 'high', + openCodeModelLaunchSupported: true + }) + ).toThrow('does not support effort high') }) it('does not invent an effort when only a model is requested', () => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.ts index d998d8e5e71..a5b12d7d46a 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.ts @@ -1,10 +1,12 @@ import type { AgentLaunchPreferences } from '../../../../../../shared/agent-session-host-authority' import { findCatalogModel, - findCatalogOption, - getAgentSessionOptionCatalog + findCatalogOption } from '../../../../../../shared/agent-session-option-catalog' -import { resolveAgentSessionOptionLaunch } from '../../../../../../shared/agent-session-option-launch' +import { + getAgentSessionOptionLaunchCatalog, + resolveAgentSessionOptionLaunch +} from '../../../../../../shared/agent-session-option-launch' import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../../../../../shared/protocol-version' import type { TuiAgent } from '../../../../../../shared/tui-agent' import { OrchestrationError } from '../../../../orchestration/orchestration-error' @@ -50,6 +52,8 @@ export function createPendingWorkerLaunchReceipt(args: { export function resolveWorkerLaunchPreferences(args: { agent: TuiAgent + openCodeModelLaunchSupported?: boolean + createsWorktree?: boolean model?: string effort?: string }): { @@ -66,7 +70,21 @@ export function resolveWorkerLaunchPreferences(args: { } } - const catalog = getAgentSessionOptionCatalog(args.agent) + if (args.agent === 'opencode' && args.createsWorktree) { + throw new OrchestrationError( + 'capability_unsupported', + 'OpenCode model selection requires an existing worktree. Use --worktree current or an existing worktree selector, or omit --model.' + ) + } + + if (args.agent === 'opencode' && args.openCodeModelLaunchSupported !== true) { + throw new OrchestrationError( + 'capability_unsupported', + 'This OpenCode TUI cannot verify launch-time model selection. Omit --model or use a supported OpenCode CLI.' + ) + } + + const catalog = getAgentSessionOptionLaunchCatalog(args.agent) if (!catalog?.supportsWorkerLaunchPreferences || !catalog.modelApply.launchArgs) { throw new OrchestrationError( 'invalid_argument', diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-opencode-model-preflight.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-opencode-model-preflight.ts new file mode 100644 index 00000000000..af0c4aa8db7 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-opencode-model-preflight.ts @@ -0,0 +1,36 @@ +import { + prepareFederationConfiguredWorkerStart, + resolveWorkerConfiguredAgentParams +} from './worker-configured-agent-preflight' +import type { prepareFederationAttachmentWorkerStart } from './worker-start-validation' +import type { OrcaRuntimeService } from '../../../../orca-runtime' + +export async function probeWorkerOpenCodeModelLaunchSupport( + runtime: OrcaRuntimeService, + params: { agent?: string; model?: string }, + target: { worktree?: string } +): Promise { + return Boolean( + params.model && + params.agent && + runtime.resolveOrchestrationAgentLauncher(params.agent) === 'opencode' && + (await runtime.probeOrchestrationOpenCodeModelLaunchSupport({ ...target, model: params.model })) + ) +} + +export async function prepareFederationWorkerLaunchOnHost( + args: Omit< + Parameters[0], + 'openCodeModelLaunchSupported' + > +) { + const params = await resolveWorkerConfiguredAgentParams(args.runtime, args.params, async () => + args.createsWorktree ? { repo: args.params.repo } : { worktree: args.params.worktree } + ) + const openCodeModelLaunchSupported = + !args.createsWorktree && + (await probeWorkerOpenCodeModelLaunchSupport(args.runtime, params, { + worktree: params.worktree + })) + return prepareFederationConfiguredWorkerStart({ ...args, params, openCodeModelLaunchSupported }) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts index 1f80eebcb34..b9e39abb859 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts @@ -52,6 +52,7 @@ export function prepareLocalWorkerStart(args: { params: WorkerStartInput createsWorktree: boolean runtime: OrcaRuntimeService + openCodeModelLaunchSupported?: boolean }): { agent: TuiAgent | undefined; launch: WorkerStartLaunch } { const { params, createsWorktree, runtime } = args assertWorkerLaunchPreferencesCreateTerminal(params) @@ -78,6 +79,8 @@ export function prepareLocalWorkerStart(args: { } return resolveWorkerStartAgent({ runtime, + openCodeModelLaunchSupported: args.openCodeModelLaunchSupported, + createsWorktree, terminal: params.terminal, agent: params.agent, model: params.model, @@ -90,6 +93,7 @@ export function prepareFederationAttachmentWorkerStart(args: { params: FederationAttachStartInput createsWorktree: boolean runtime: OrcaRuntimeService + openCodeModelLaunchSupported?: boolean }): { agent: TuiAgent | undefined; launch: WorkerStartLaunch } { const { params, createsWorktree, runtime } = args assertWorkerLaunchPreferencesCreateTerminal(params) @@ -122,6 +126,8 @@ export function prepareFederationAttachmentWorkerStart(args: { } return resolveWorkerStartAgent({ runtime, + openCodeModelLaunchSupported: args.openCodeModelLaunchSupported, + createsWorktree, terminal: params.terminal, agent: params.agent, model: params.model, @@ -133,6 +139,8 @@ export function prepareFederationAttachmentWorkerStart(args: { function resolveWorkerStartAgent(args: { runtime: OrcaRuntimeService + openCodeModelLaunchSupported?: boolean + createsWorktree: boolean terminal?: string agent?: string model?: string @@ -153,6 +161,8 @@ function resolveWorkerStartAgent(args: { agent, launch: resolveWorkerLaunchPreferences({ agent, + openCodeModelLaunchSupported: args.openCodeModelLaunchSupported, + createsWorktree: args.createsWorktree, model: args.model, effort: args.effort }) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts index fc7c1f3b26c..50fee27ac48 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts @@ -8,6 +8,8 @@ import { OrchestrationDb } from '../../../../orchestration/db' import { RpcDispatcher } from '../../../dispatcher' import type { RpcRequest } from '../../../core' import { ORCHESTRATION_METHODS } from '../../orchestration' +import { prepareFederationWorkerLaunchOnHost } from './worker-opencode-model-preflight' +import { FederationAttachStartParams } from '../federation/federation-start-schema' describe('orchestration new-worktree workers', () => { type CreateWorktreeResult = Awaited> @@ -189,6 +191,67 @@ describe('orchestration new-worktree workers', () => { }) }) + it.each(['new-child', 'new-top-level'])( + 'refuses an OpenCode model for %s without probing', + async (worktree) => { + mockCreatedWorktree() + const probe = vi + .spyOn(runtime, 'probeOrchestrationOpenCodeModelLaunchSupport') + .mockResolvedValue(true) + await expect( + startWorker({ + worktree, + repo: 'repo', + agent: 'opencode', + model: 'opencode/fledge-alpha-free' + }) + ).rejects.toMatchObject({ + code: 'capability_unsupported', + message: expect.stringContaining('requires an existing worktree') + }) + expect(probe).not.toHaveBeenCalled() + expect(runtime.createManagedWorktree).not.toHaveBeenCalled() + expect(runtime.createTerminal).not.toHaveBeenCalled() + expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() + } + ) + + it('refuses a federated new-worktree model before probing its repository', async () => { + const probe = vi + .spyOn(runtime, 'probeOrchestrationOpenCodeModelLaunchSupport') + .mockResolvedValue(true) + const params = FederationAttachStartParams.parse({ + dispatchId: 'ctx_new', + taskId: 'task_new', + taskSpec: 'No effects', + protocolVersion: 3, + worktree: 'new-top-level', + name: 'new-worker', + repo: 'repo', + agent: 'opencode', + model: 'opencode/fledge-alpha-free' + }) + await expect( + prepareFederationWorkerLaunchOnHost({ runtime, params, createsWorktree: true }) + ).rejects.toMatchObject({ + code: 'capability_unsupported', + message: expect.stringContaining('requires an existing worktree') + }) + expect(probe).not.toHaveBeenCalled() + expect(runtime.createTerminal).not.toHaveBeenCalled() + expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() + }) + + it('rejects an unsupported OpenCode model before creating a worker', async () => { + const create = vi.spyOn(runtime, 'createManagedWorktree') + vi.spyOn(runtime, 'probeOrchestrationOpenCodeModelLaunchSupport').mockResolvedValue(false) + await expect( + startWorker({ agent: 'opencode', model: 'opencode/fledge-alpha-free' }) + ).rejects.toMatchObject({ code: 'capability_unsupported' }) + expect(create).not.toHaveBeenCalled() + expect(runtime.createTerminal).not.toHaveBeenCalled() + }) + it('rejects a new worktree for a folder project before creating effects', async () => { vi.mocked(runtime.showRepo).mockResolvedValue({ id: 'repo', diff --git a/src/main/runtime/runtime-worktree-agent-startup.ts b/src/main/runtime/runtime-worktree-agent-startup.ts index a65f2527357..a57beb7efcd 100644 --- a/src/main/runtime/runtime-worktree-agent-startup.ts +++ b/src/main/runtime/runtime-worktree-agent-startup.ts @@ -14,6 +14,7 @@ import { detectRemoteAgents } from '../preflight/agent-detection' import type { RuntimeStore } from './runtime-store-contract' +import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' export type WorktreeStartupDraftPaste = { agent: TuiAgent; content: string } export type WorktreeStartupFollowup = { expectedProcess: string; prompt: string } @@ -173,3 +174,21 @@ export function buildWorktreeStartupForAgent( : {}) } } + +export function resolveWorktreeCreateAgentStartup( + args: RuntimeManagedWorktreeCreateArgs, + build: ( + agent: TuiAgent, + prompt: string | undefined, + preferences: AgentLaunchPreferences | undefined, + inputs: { agentArgs?: string | null; launchSource?: string } + ) => { agent: TuiAgent; startup: WorktreeStartupLaunch; followup?: WorktreeStartupFollowup } +) { + if (args.startup || !args.startupAgent) { + return null + } + return build(args.startupAgent, args.startupPrompt, args.startupLaunchPreferences, { + ...(args.startupAgentArgs !== undefined ? { agentArgs: args.startupAgentArgs } : {}), + ...(args.startupLaunchSource ? { launchSource: args.startupLaunchSource } : {}) + }) +} diff --git a/src/renderer/src/components/terminal-pane/ipc-pty-opencode-model.test.ts b/src/renderer/src/components/terminal-pane/ipc-pty-opencode-model.test.ts new file mode 100644 index 00000000000..631d965b91b --- /dev/null +++ b/src/renderer/src/components/terminal-pane/ipc-pty-opencode-model.test.ts @@ -0,0 +1,101 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { callRuntimeRpc } from '../../runtime/runtime-rpc-client' +import { spawnIpcPty } from './ipc-pty-spawn-request' +import type { IpcPtyTransportOptions } from './pty-transport-types' + +vi.mock('../../runtime/runtime-rpc-client', async () => ({ + callRuntimeRpc: vi.fn(), + RuntimeRpcCallError: (await import('../../runtime/runtime-rpc-result')).RuntimeRpcCallError +})) +const spawn = vi.fn(async () => ({ id: 'pty_host', isReattach: true })) +const options = (): IpcPtyTransportOptions => ({ + worktreeId: 'folder:private', + tabId: 'tab_private', + leafId: 'leaf_private', + launchAgent: 'opencode', + command: 'opencode --model private-proof/model-b', + agentPrompt: 'Read only', + agentPromptDelivery: 'auto-submit', + agentLaunchPreferences: { model: 'private-proof/model-b' } +}) +const connect = { url: 'ipc://private', callbacks: {}, cols: 80, rows: 24 } + +describe('local OpenCode model launch authority', () => { + beforeEach(() => { + vi.resetAllMocks() + vi.stubGlobal('window', { api: { pty: { spawn } } }) + spawn.mockResolvedValue({ id: 'pty_host', isReattach: true }) + vi.mocked(callRuntimeRpc).mockResolvedValue({ + terminal: { ptyId: 'pty_host' }, + disposition: 'created' + }) + }) + afterEach(() => vi.unstubAllGlobals()) + + it('sends preferences to the execution host and attaches only to its returned PTY', async () => { + const claimReplacedPtyId = vi.fn(() => 'pty_previous') + expect(await spawnIpcPty(options(), { ...connect, claimReplacedPtyId })).toMatchObject({ + id: 'pty_host' + }) + expect(callRuntimeRpc).toHaveBeenCalledWith( + { kind: 'local' }, + 'terminal.createAgentSession', + expect.objectContaining({ + agent: 'opencode', + launchPreferences: { model: 'private-proof/model-b' }, + prompt: 'Read only', + promptDelivery: 'auto-submit', + placement: { tabId: 'tab_private', leafId: 'leaf_private' } + }) + ) + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: 'pty_host', command: undefined }) + ) + expect(claimReplacedPtyId).not.toHaveBeenCalled() + }) + + it('preserves one operation ID across a lost reply and reconnect', async () => { + const transport = options() + vi.mocked(callRuntimeRpc).mockRejectedValueOnce(new Error('reply lost')) + await spawnIpcPty(transport, connect) + await spawnIpcPty(transport, connect) + const operationRequest = z.object({ clientOperationId: z.string() }) + const ids = vi + .mocked(callRuntimeRpc) + .mock.calls.map((call) => operationRequest.parse(call[2]).clientOperationId) + expect(ids).toHaveLength(3) + expect(new Set(ids).size).toBe(1) + expect(ids[0]).toMatch(/^\d{13}-[0-9a-f]{32}$/) + }) + + it('does not issue raw spawn or replacement effects after the host refuses', async () => { + vi.mocked(callRuntimeRpc).mockRejectedValue(new Error('capability_unsupported')) + const claimReplacedPtyId = vi.fn(() => 'pty_previous') + await expect(spawnIpcPty(options(), { ...connect, claimReplacedPtyId })).rejects.toThrow( + 'capability_unsupported' + ) + expect(spawn).not.toHaveBeenCalled() + expect(claimReplacedPtyId).not.toHaveBeenCalled() + }) + + it.each([ + { connectionId: 'ssh_private' }, + { resumeProviderSession: { key: 'session_id' as const, id: 'old' } } + ])('refuses unsupported placement before host or raw spawn', async (extra) => { + await expect(spawnIpcPty({ ...options(), ...extra }, connect)).rejects.toThrow( + 'capability_unsupported' + ) + expect(callRuntimeRpc).not.toHaveBeenCalled() + expect(spawn).not.toHaveBeenCalled() + }) + + it('preserves ordinary raw startup and captured-session attachment', async () => { + const ordinary = { ...options(), agentLaunchPreferences: undefined } + await spawnIpcPty(ordinary, connect) + expect(spawn).toHaveBeenCalledWith(expect.objectContaining({ command: ordinary.command })) + await spawnIpcPty(options(), connect, 'pty_existing') + expect(callRuntimeRpc).not.toHaveBeenCalled() + expect(spawn).toHaveBeenLastCalledWith(expect.objectContaining({ sessionId: 'pty_existing' })) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/ipc-pty-spawn-request.ts b/src/renderer/src/components/terminal-pane/ipc-pty-spawn-request.ts index ff69ba35a86..667865deb7e 100644 --- a/src/renderer/src/components/terminal-pane/ipc-pty-spawn-request.ts +++ b/src/renderer/src/components/terminal-pane/ipc-pty-spawn-request.ts @@ -1,6 +1,14 @@ import type { IpcPtyTransportOptions, PtyConnectResult, PtyTransport } from './pty-transport-types' +import type { RuntimeCreateAgentSessionResult } from '../../../../shared/agent-session-host-authority' +import { + createAgentSessionCreateOperation, + type AgentSessionCreateOperation +} from '../../runtime/agent-session-create-operation' +import { callRuntimeRpc } from '../../runtime/runtime-rpc-client' +import { toRuntimeTerminalWorktreeSelector } from '../../runtime/runtime-worktree-selector' type PtyConnectOptions = Parameters[0] +const modelLaunchOperations = new WeakMap() /** `incarnationId` names which lifetime of the returned id this spawn owns; absent when the * execution host predates the field. It is deliberately NOT on `PtyConnectResult` — only the @@ -15,6 +23,52 @@ export async function spawnIpcPty( connectOptions: PtyConnectOptions, admittedSessionId?: string ): Promise { + if ( + !admittedSessionId && + transportOptions.launchAgent === 'opencode' && + Object.values(transportOptions.agentLaunchPreferences ?? {}).some( + (value) => value !== undefined + ) + ) { + const { worktreeId, tabId, leafId, connectionId, resumeProviderSession } = transportOptions + if (!worktreeId || !tabId || !leafId || connectionId || resumeProviderSession) { + throw new Error('capability_unsupported') + } + let operation = modelLaunchOperations.get(transportOptions) + if (!operation) { + operation = createAgentSessionCreateOperation() + modelLaunchOperations.set(transportOptions, operation) + } + const created = await operation.run((clientOperationId) => + callRuntimeRpc( + { kind: 'local' }, + 'terminal.createAgentSession', + { + clientOperationId, + worktree: toRuntimeTerminalWorktreeSelector(worktreeId), + agent: 'opencode', + prompt: transportOptions.agentPrompt, + promptDelivery: transportOptions.agentPromptDelivery, + agentArgs: transportOptions.agentArgsOverride, + launchPreferences: transportOptions.agentLaunchPreferences, + startupCwd: transportOptions.cwd, + placement: { tabId, leafId }, + presentation: 'background', + ...(transportOptions.terminalKittyKeyboardProtocol === true + ? { terminalKittyKeyboardProtocol: true } + : {}) + } + ) + ) + if (!created.terminal.ptyId) { + throw new Error('agent_session_operation_unknown') + } + return spawnIpcPty( + { ...transportOptions, command: undefined, launchConfig: undefined }, + { ...connectOptions, command: undefined, launchConfig: undefined }, + created.terminal.ptyId + ) + } const { cwd, cwdFallback, diff --git a/src/shared/agent-session-option-catalog-opencode.test.ts b/src/shared/agent-session-option-catalog-opencode.test.ts new file mode 100644 index 00000000000..7162a1f6b22 --- /dev/null +++ b/src/shared/agent-session-option-catalog-opencode.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest' +import { getAgentSessionOptionCatalog } from './agent-session-option-catalog' +import { + removeOverriddenAgentSessionArgs, + resolveAgentSessionOptionLaunch +} from './agent-session-option-launch' + +describe('OpenCode launch options', () => { + it('does not expose worker-only launch options as an interactive session catalog', () => { + expect(getAgentSessionOptionCatalog('opencode')).toBeNull() + }) + + it('maps an opaque model id to the OpenCode --model flag', () => { + expect( + resolveAgentSessionOptionLaunch('opencode', { + model: 'zai-coding-plan/glm-5.3-flash' + }) + ).toEqual({ + args: ['--model', 'zai-coding-plan/glm-5.3-flash'], + appliedValues: { model: 'zai-coding-plan/glm-5.3-flash' } + }) + }) + + it('removes a configured model flag before applying a per-launch model', () => { + expect( + removeOverriddenAgentSessionArgs('opencode', { model: 'zai-coding-plan/glm-5.3-flash' }, [ + '--model', + 'opencode/global-default', + '--log-level', + 'DEBUG' + ]) + ).toEqual(['--log-level', 'DEBUG']) + }) + + it('keeps arguments after the terminator while removing every earlier model choice', () => { + expect( + removeOverriddenAgentSessionArgs('opencode', { model: 'private-proof/model-b' }, [ + '-mfirst', + '--model=second', + '--log-level', + 'DEBUG', + '--', + '--model', + 'trailing' + ]) + ).toEqual(['--log-level', 'DEBUG', '--', '--model', 'trailing']) + }) + + it('does not record the selected model when later free-form arguments override it', () => { + expect( + resolveAgentSessionOptionLaunch('opencode', { model: 'private-proof/model-b' }, [ + '-m', + 'private-proof/model-a' + ]) + ).toEqual({ args: ['--model', 'private-proof/model-b'], appliedValues: {} }) + }) + + it('records the selected model when model-like arguments follow the terminator', () => { + expect( + resolveAgentSessionOptionLaunch('opencode', { model: 'private-proof/model-b' }, [ + '--', + '--model', + 'private-proof/model-a' + ]) + ).toEqual({ + args: ['--model', 'private-proof/model-b'], + appliedValues: { model: 'private-proof/model-b' } + }) + }) +}) diff --git a/src/shared/agent-session-option-catalog-opencode.ts b/src/shared/agent-session-option-catalog-opencode.ts new file mode 100644 index 00000000000..bf7773b5d16 --- /dev/null +++ b/src/shared/agent-session-option-catalog-opencode.ts @@ -0,0 +1,14 @@ +import { removeAgentArgOption } from './agent-session-option-agent-args' +import type { AgentSessionOptionCatalog } from './agent-session-option-catalog-types' + +const MODEL_FLAGS = ['-m', '--model'] as const + +// Why: worker-start needs launch serialization without exposing a new Native Chat option surface. +export const OPENCODE_LAUNCH_OPTION_CATALOG: AgentSessionOptionCatalog = { + supportsWorkerLaunchPreferences: true, + models: [], + modelApply: { + launchArgs: (value) => ['--model', String(value)], + removeAgentArgs: (tokens) => removeAgentArgOption(tokens, MODEL_FLAGS) + } +} diff --git a/src/shared/agent-session-option-launch.ts b/src/shared/agent-session-option-launch.ts index e9c5b90181d..fb34a95cfa4 100644 --- a/src/shared/agent-session-option-launch.ts +++ b/src/shared/agent-session-option-launch.ts @@ -1,6 +1,10 @@ import type { AgentType } from './agent-status-types' import { findCatalogModel, getAgentSessionOptionCatalog } from './agent-session-option-catalog' -import type { CatalogOptionApply } from './agent-session-option-catalog-types' +import { OPENCODE_LAUNCH_OPTION_CATALOG } from './agent-session-option-catalog-opencode' +import type { + AgentSessionOptionCatalog, + CatalogOptionApply +} from './agent-session-option-catalog-types' import type { SessionOptionValue } from './native-chat-session-options' export type ResolvedSessionOptionLaunch = { @@ -13,12 +17,18 @@ function isOverriddenByAgentArgs(apply: CatalogOptionApply, tokens: readonly str return kept !== undefined && kept.length < tokens.length } +export function getAgentSessionOptionLaunchCatalog( + agent: AgentType +): AgentSessionOptionCatalog | null { + return agent === 'opencode' ? OPENCODE_LAUNCH_OPTION_CATALOG : getAgentSessionOptionCatalog(agent) +} + export function removeOverriddenAgentSessionArgs( agent: AgentType, values: Record | null | undefined, tokens: readonly string[] ): string[] { - const catalog = getAgentSessionOptionCatalog(agent) + const catalog = getAgentSessionOptionLaunchCatalog(agent) const modelId = typeof values?.model === 'string' ? values.model : null if (!catalog || !values || !modelId) { return [...tokens] @@ -40,7 +50,7 @@ export function resolveAgentSessionOptionLaunch( trailingAgentArgs: readonly string[] = [], includeCatalogDefaults = true ): ResolvedSessionOptionLaunch { - const catalog = getAgentSessionOptionCatalog(agent) + const catalog = getAgentSessionOptionLaunchCatalog(agent) const modelId = typeof values?.model === 'string' ? values.model : null if (!catalog || !values || !modelId) { return { args: [], appliedValues: {} } diff --git a/src/shared/tui-agent-startup-session-options.test.ts b/src/shared/tui-agent-startup-session-options.test.ts index c6d0f551226..174a1b172a2 100644 --- a/src/shared/tui-agent-startup-session-options.test.ts +++ b/src/shared/tui-agent-startup-session-options.test.ts @@ -89,6 +89,24 @@ describe('tui agent startup session options', () => { expect(plan?.sessionOptions).toEqual({ model: 'muse-spark-1.3', effort: 'xhigh' }) }) + it('keeps OpenCode agent arguments while replacing only the per-launch model', () => { + const plan = buildAgentStartupPlan({ + agent: 'opencode', + prompt: '', + cmdOverrides: {}, + platform: 'linux', + allowEmptyPromptLaunch: true, + sessionOptions: { model: 'zai-coding-plan/glm-5.3-flash' }, + sessionOptionsOverrideAgentArgs: true, + agentArgs: '--share --model opencode/global-default' + }) + expect(plan?.launchCommand).toBe("opencode '--share' '--model' 'zai-coding-plan/glm-5.3-flash'") + expect(plan?.launchConfig.agentCommand).toBe( + "opencode '--share' '--model' 'opencode/global-default'" + ) + expect(plan?.sessionOptions).toEqual({ model: 'zai-coding-plan/glm-5.3-flash' }) + }) + it('inserts worker preferences before an argument terminator', () => { const plan = buildAgentStartupPlan({ agent: 'codex',