feat(cli): name the Orca that owns a workspace 'server'

orca server ... replaces orca environment ... and orca host name; --server and
--parent-server replace --environment and --parent-environment. Old spellings
stay accepted as input only: help, suggestions, errors and printed commands use
the new names, and giving both spellings different values is invalid_argument.
--host is still parsed but leaves help; orca host list/rm are hidden.

Listings name each row's owning server (server: / server=) from data already
returned, mapping a stored owner to a saved-server name only from this
computer's own store, and print server=unknown instead of guessing local. The
ports footer and search hits drop host=. CLI-built JSON uses server keys
(server, address.server, parent.server, unknown-server, servers, knownServers,
status target kind server). create/set print the same parent line as ps.
This commit is contained in:
Jinwoo-H
2026-11-09 02:12:19 -05:00
parent f36751f79f
commit c46a06032e
169 changed files with 1574 additions and 995 deletions
+2 -2
View File
@@ -491,7 +491,7 @@ or a development plugin's key when you run it inside that folder; installed plug
The result adds `replay: true` and `scenario`, `errors` lists what the render reported, and an
unknown name fails and lists the panel's scenarios. A replay is a still frame: controls whose
value Orca owns start from the tree's props, images show their placeholder, it takes no `--act`,
it works only on this machine (no `--environment`), and it needs Orca's window hidden or
it works only on this machine (no `--server`), and it needs Orca's window hidden or
minimized because the preview is drawn inside it. It writes
`.orca/shots/<plugin-key>-<panel>.<scenario>.png` in the plugin folder unless you pass `--out`.
@@ -543,7 +543,7 @@ sidebar it skips the shot and says so once (`shot_skipped`), and resumes when th
Both need the Orca desktop app with a workspace showing; `orca serve` has no window and refuses
them. A shot never changes the view, so while Orca shows Settings or another full page it fails
with `no_workspace`. With `--environment`, the PNG (at most 5 MiB) comes back to the machine
with `no_workspace`. With `--server`, the PNG (at most 5 MiB) comes back to the machine
that ran the command.
To keep a folder loaded without a terminal, use Settings instead:
+3 -3
View File
@@ -66,14 +66,14 @@ orca automations create \
--prompt "Triage open issues" \
--provider claude \
--project <projectId> \
--host <host> \
--server <server> \
--disabled \
--json
```
`--project` takes the project id or the display name from `orca project list`. `--host` takes `local`, `ssh:<target-id>`, `runtime:<environment-id>`, or the bare name from `orca host list`, and it can be omitted entirely when the project is set up on only one host — Orca uses that one. When the project is set up on several, the error names each host and the flag to select it.
`--project` takes the project id or the display name from `orca project list`. `--server` runs the command on that server and uses its own setup of the project; omit it to stay on this computer. When the project has setups for several servers here and no `--server` is given, the error names each setup and the server that owns it.
Use `--project-host-setup <id>` when you already have a setup id. Optional `--source-context '<json>'` pins task/provider data to a host/account (pass `null` on edit to clear).
Use `--project-host-setup <id>` when you already have a setup id. Optional `--source-context '<json>'` pins task/provider data to a server/account (pass `null` on edit to clear).
## Manage automations across hosts
+1 -1
View File
@@ -11,7 +11,7 @@ Use it when you need ownership, completion tracking, or a DAG. For one-off promp
<Callout title="Experimental">
Enable orchestration under Settings → Experimental before using these commands. The CLI talks to
the running Orca runtime, so `orca status --json` should succeed first.
the running Orca server, so `orca status --json` should succeed first.
</Callout>
<Callout title="Legacy commands retired">
+16 -24
View File
@@ -5,7 +5,7 @@ description: Commands, selectors, and agent-friendly patterns for driving Orca f
import { Callout } from '@/components/docs/prose'
The `orca` CLI talks to a running Orca runtime. Use it when a shell script or agent needs to inspect worktrees, launch terminals, open files, automate the built-in browser, or report progress back into Orca.
The `orca` CLI talks to a running Orca server. Use it when a shell script or agent needs to inspect worktrees, launch terminals, open files, automate the built-in browser, or report progress back into Orca.
## Verify the runtime
@@ -53,27 +53,19 @@ orca worktree show --worktree branch:feature-name --json
orca worktree show --worktree issue:123 --json
```
`active` and `current` resolve to the enclosing Orca-managed worktree from the shell's current directory or terminal context. Use explicit selectors in scripts that may run outside the target worktree. For remote runtimes, prefer full server-side selectors such as `id:<repoId>::<absolute-worktree-path>` or `path:<absolute-server-path>` because the local shell's current directory may not exist on the runtime host.
`active` and `current` resolve to the enclosing Orca-managed worktree from the shell's current directory or terminal context. Use explicit selectors in scripts that may run outside the target worktree. With `--server`, prefer full server-side selectors such as `id:<repoId>::<absolute-worktree-path>` or `path:<absolute-server-path>` because the local shell's current directory may not exist on that server.
## Choose a host
## Choose a server
List every machine the current Orca host can target and the selector for each one:
Every command runs on one Orca server. Without a flag it is `local`, the Orca on this computer. Pass `--server <id>` to run on a saved [Remote Orca Server](/docs/remote-servers), or `--server local` to stay on this computer even when `ORCA_ENVIRONMENT` sets a default. List the saved servers and the selector for each one:
```bash
orca host list --json
orca server list --json
```
The result includes this machine, its registered [SSH targets](/docs/ssh), and paired [Remote Orca Servers](/docs/remote-servers). Use `--host local` for this machine, `--host ssh:<target-id>` for an SSH target, and `--environment <server-name>` for a paired server. SSH rows include the detected remote platform (`linux`, `darwin`, or `win32`) after the target connects; older or disconnected targets report `platform unknown`. They also include `connected` and, when known, the SSH lifecycle `connectionStatus`. If you put a machine name on the wrong selector, Orca reports the matching machine and the flag to use instead of returning an empty result.
`server list` reads this computer's pairing store and never contacts a server. Ask one server for its status with `orca status --server <id> --json`. A server set up over [SSH](/docs/ssh) is a saved server like any other; SSH connections themselves are managed in Settings.
`--host` also takes the bare name shown in the `name` column, on either axis — `--host trader-local` reaches the same machine as `--host ssh:ssh-1783599077486-fyasux`. Names resolve only when they are unique: a name held by two SSH targets, by two paired servers, or by one of each is refused, and the error hands back the id form for each candidate — `--host ssh:<target-id>` for an SSH target and `--host runtime:<environment-id>` for a paired server. Use those to settle it, since `--environment <server-name>` cannot separate two servers sharing a name.
Remove a saved SSH target with the id `orca host list` prints:
```bash
orca host rm --host ssh:<target-id> --json
```
It removes the target the same way Settings does, so the passive `~/.ssh/config` import does not add the alias back on the next launch. It takes only the `ssh:<target-id>` form, not the bare name, because it deletes data. It refuses `--host local`, paired servers (use `orca environment rm`), and an id this Orca host does not have.
Listings name the server that owns each row: `server:` in `worktree ps` and `worktree show`, and `server=` in `worktree list`, `terminal list`, `project setups` and orchestration worker lines. `server=unknown (...)` means Orca cannot verify the owner from here, so don't treat that row's paths as files on this computer.
## Runtime commands
@@ -99,7 +91,7 @@ orca repo search-refs --repo id:<repoId> --query main --limit 10 --json
Set the repo base ref before creating lots of worktrees so new tasks branch from the right place by default.
`repo add` defaults to `--kind git`. Use `--kind folder` to open an ordinary directory, including a repo-tool root containing separate Git repositories, as a folder workspace without Git worktrees or source control. With `--environment`, use an absolute path on that Orca server.
`repo add` defaults to `--kind git`. Use `--kind folder` to open an ordinary directory, including a repo-tool root containing separate Git repositories, as a folder workspace without Git worktrees or source control. With `--server`, use an absolute path on that Orca server.
## Worktrees
@@ -209,7 +201,7 @@ Omit `--terminal` to target the active terminal in the current worktree. Read be
Close stops the process as part of removing the terminal. Use `--terminal <handle>` for one
terminal, or `--worktree <selector> --all` to durably close every terminal in exactly that
workspace, including its saved layouts and agent-resume records. Use workspace Sleep when those
terminals should resume later. If the execution host cannot confirm that every PTY stopped, bulk
terminals should resume later. If the server cannot confirm that every PTY stopped, bulk
close returns a failing `unverifiable` result rather than claiming the processes exited.
`terminal stop` remains only for compatibility with older tooling.
@@ -218,7 +210,7 @@ close returns a failing `unverifiable` result rather than claiming the processes
handle, run `orca terminal list --json` and reacquire the handle.
</Callout>
`terminal list` reports each terminal's `executionHostId` when Orca can verify it, plus a result-level `hostScope` with covered and omitted host IDs. Treat a missing host identity or scope as **unverifiable**, not local. A missing terminal is evidence that it exited only when its execution host is listed in `hostScope.hostIds`.
`terminal list` reports each terminal's `executionHostId` when Orca can verify it, plus a result-level `hostScope` with covered and omitted host IDs. Treat a missing host identity or scope as **unverifiable**, not local; text output prints it as `server=unknown`. A missing terminal is evidence that it exited only when its host is listed in `hostScope.hostIds`.
By default, `terminal read` returns the accumulated output stream with terminal escapes stripped. Programs that redraw lines can therefore appear as stacked fragments. Use `--screen` when you need the currently rendered frame; the response's `source` identifies `stream`, `screen`, or `screen-unavailable`. Screen reads have no history to page, so `--screen` and `--cursor` are mutually exclusive.
@@ -231,7 +223,7 @@ orca chat rename --session <sessionId> --name "Release notes" --json
orca chat rename --name "Migrate auth"
```
Renames a chat tab, the same as renaming it by hand. `--session` takes the `sessionId` that `orca agent launch` prints. Run inside a chat, it defaults to that chat; with `--environment` it is required.
Renames a chat tab, the same as renaming it by hand. `--session` takes the `sessionId` that `orca agent launch` prints. Run inside a chat, it defaults to that chat; with `--server` it is required.
## Files
@@ -384,7 +376,7 @@ orca skills install --all --dry-run
orca skills update --all
```
`install` / `update` run Orca's own skill installer on the machine that runs them, the same planner the app's **Update skills** uses. They do not contact the Orca runtime or need `npx`. See [Orca skills](/docs/cli/skills#keep-skills-up-to-date).
`install` / `update` run Orca's own skill installer on the machine that runs them, the same planner the app's **Update skills** uses. They do not contact an Orca server or need `npx`. See [Orca skills](/docs/cli/skills#keep-skills-up-to-date).
## Account (host-local runtime)
@@ -442,12 +434,12 @@ orca automations create --name "Daily review" --trigger daily --time 09:00 --pro
orca automations run <automationId> --json
```
Remote runtime environments:
Saved servers:
```bash
orca environment add --name work-laptop --pairing-code "orca://pair?code=..." --json
orca environment list --json
orca environment rm --environment <selector> --json
orca server add --name work-laptop --pairing-code "orca://pair?code=..." --json
orca server list --json
orca server rm --server <id> --json
```
Agent status hooks:
+1 -1
View File
@@ -25,7 +25,7 @@ Orca won't add a second target for a machine already in Orca. When it imports `~
The import reads `Host` blocks only. It adds each concrete alias of a `Host` line and skips patterns with `*`, `?`, or `!`. A `Match` block adds no target: a `Match` line ends the `Host` block above it, and the import ignores its lines until the next `Host` line. A tool that writes its own SSH config blocks can use `Match originalhost <name>` instead of `Host <name>` to keep a machine out of the import. Orca expands `Include` files in place before it parses, so a `Host` block in an included file is imported even when the `Include` line is inside a `Match` block.
When you remove a target that came from `~/.ssh/config` (in Settings, or with `orca host rm`), the passive import (on launch, **Sync ~/.ssh/config**, or **Add all**) does not add its alias back. **Restore removed hosts…** in Settings → SSH brings it back.
When you remove a target that came from `~/.ssh/config` (in Settings), the passive import (on launch, **Sync ~/.ssh/config**, or **Add all**) does not add its alias back. **Restore removed hosts…** in Settings → SSH brings it back.
## Host key verification
+1 -1
View File
@@ -86,7 +86,7 @@ Use `ORCA linear list-issues` when MCP-compatible filters or cursor pagination a
- Omitting `--limit` returns every match and reports `result.meta.limit` as `null`, so filter before listing a large workspace. `--limit <n>` caps the read.
- When a cap held results back, `--json` sets `result.truncated` and `result.meta.hasMore`; human output prints `truncated: showing N`. Check `truncated` before reporting a count, then page with `--cursor` until it is false.
- A `--cursor` is bound to the workspace and the Orca runtime that issued it. `--workspace all` cannot page, and a raw Linear cursor still needs a concrete `--workspace`.
- A `--cursor` is bound to the workspace and the Orca server that issued it. `--workspace all` cannot page, and a raw Linear cursor still needs a concrete `--workspace`.
- `--priority` is `0=none`, `1=urgent`, `2=high`, `3=medium`, `4=low`. Issue JSON carries `priorityLabel` in the CLI setter vocabulary; project JSON keeps Linear's title-case label.
- `ORCA linear search`, `ORCA linear list`, and `ORCA linear project list` cap at their own `--limit` and set `result.truncated` the same way.
+17 -16
View File
@@ -46,7 +46,7 @@ For a requested model or effort, such as `gpt-6-astra high`, add `--model` and `
ORCA worktree create --name <task-name> --no-parent --agent codex --model gpt-6-astra --effort high --prompt "<task brief>" --json
```
Read what started from `result.launch`: `outcome.kind` is `structured` (a chat) or `terminal`, `outcome.handle` is the agent handle, `receipt.detail` says why, and `prompt.outcome` says whether the brief arrived. An Orca host older than this returns the terminal handle in `result.agentTerminalHandle` and refuses `--model`/`--effort`.
Read what started from `result.launch`: `outcome.kind` is `structured` (a chat) or `terminal`, `outcome.handle` is the agent handle, `receipt.detail` says why, and `prompt.outcome` says whether the brief arrived. An Orca server older than this returns the terminal handle in `result.agentTerminalHandle` and refuses `--model`/`--effort`.
For a fresh agent in a worktree that already exists, use `agent launch`, which takes the same `--prompt`, `--model` and `--effort`:
@@ -64,7 +64,7 @@ ORCA terminal send --terminal <handle> --text "<task brief>" --enter --json
`worktree create --agent` (new checkout) and `agent launch` (existing worktree) are how to start an agent. They go through Orca's agent launch, the same one the app's new-agent tab uses: the user's Chat | CLI choice for that agent decides whether it opens as a chat or a terminal, and the result reports which (`outcome.kind`) and why (`receipt.detail`). When a chat is not possible, such as for an agent without chat support, the launch starts a terminal and the receipt says so. `--surface chat|terminal` picks one for that launch instead of the setting; pass it only when the user asked for a chat or a terminal. `--surface chat` is refused when Orca can establish before starting anything that the agent cannot open as a chat. If support cannot be checked, the launch can fall back to a terminal. If chat becomes unavailable only after a new workspace is created, Orca keeps that workspace, its setup and default tabs, then opens a terminal; the receipt explains the fallback. `terminal create` makes a terminal for shells and commands.
If a launch reply is lost, use the returned `operationId` to re-issue the exact same command from the same directory against the same execution host with `--retry-launch <operationId>`. Keep that ID on every retry: the host replays the accepted launch instead of starting another agent or submitting the brief twice. Do not retry as a fresh launch. If replay says the outcome is unknown or expired, or an older host gives no replay ID, inspect the workspace and agent without sending input before deciding whether another launch is needed. A host that cannot safely carry prompts or honor background/focus requests is refused before launch; update Orca on that execution host.
If a launch reply is lost, use the returned `operationId` to re-issue the exact same command from the same directory against the same server with `--retry-launch <operationId>`. Keep that ID on every retry: the server replays the accepted launch instead of starting another agent or submitting the brief twice. Do not retry as a fresh launch. If replay says the outcome is unknown or expired, or an older server gives no replay ID, inspect the workspace and agent without sending input before deciding whether another launch is needed. A server that cannot safely carry prompts or honor background/focus requests is refused before launch; update Orca on that server.
## Worktrees
@@ -72,7 +72,7 @@ An Orca worktree is Orca's tracked view of a repo checkout, its metadata, termin
Its id is a two-part address, `<repoId>::<worktreePath>`, such as `repo-123::/Users/me/orca/fix-login`. Copy the whole `id` field from `ORCA worktree create --json` or `ORCA worktree list --json`. `repo-123` alone names only the repo.
For local creation, omit `--repo` and `--project` to stay in the caller's project. Use `--parent-worktree active` for a child of the current workspace. Project selection and parent selection are separate: a native folder parent supplies lineage, not a Git destination, so pass an explicit Git target when creating from a folder outside any managed checkout. Otherwise, pass `--repo` or `--project` only when deliberately creating in another project, or when Orca asks you to disambiguate. Outside any Orca-managed project, pass an explicit target. With a paired server, discover and use that server's exact target instead of the local cwd.
For local creation, omit `--repo` and `--project` to stay in the caller's project. Use `--parent-worktree active` for a child of the current workspace. Project selection and parent selection are separate: a native folder parent supplies lineage, not a Git destination, so pass an explicit Git target when creating from a folder outside any managed checkout. Otherwise, pass `--repo` or `--project` only when deliberately creating in another project, or when Orca asks you to disambiguate. Outside any Orca-managed project, pass an explicit target. With `--server`, discover and use that server's exact target instead of the local cwd.
If several Orca workspaces share the checkout and no caller identity selects one, workspace-specific commands ask you to choose an exact selector. Inspect a listed workspace with `ORCA worktree show --worktree <exact-selector> --json`, then use the command’s workspace target flag. For an implicit-create refusal, use `ORCA worktree list --limit 10000 --json` with the same server and host selection; match path and host, increasing --limit if truncated. Pass `--parent-worktree <exact-selector>` or deliberately use `--no-parent` on a fresh request without --retry-launch. Retrying the refused ID returns its original explanation. Pass each exact selector as one argument quoted for your shell. Native folder choices are shown in the local error; exact show inspection is supported, while native folders are not enumerated by worktree list. Implicit creation checks this only when the host actually uses the directory’s parent context; older hosts retain their existing implicit-parent behavior.
@@ -120,9 +120,9 @@ ORCA worktree set --worktree active --pr null --gitlab-mr null --json
ORCA worktree rm --worktree id:<repoId>::<worktreePath> --force --json
```
`repo add` defaults to Git. Use `--kind folder` for an ordinary directory or a parent of separate Git repositories; worktrees attached to a folder workspace appear in its Source Control panel, one section each. With `--environment`, pass an absolute path on that server.
`repo add` defaults to Git. Use `--kind folder` for an ordinary directory or a parent of separate Git repositories; worktrees attached to a folder workspace appear in its Source Control panel, one section each. With `--server`, pass an absolute path on that server.
Ports: `ORCA ports --json` lists the listening ports Orca tied to the current workspace (`--worktree <selector>` for another one, `--all` for every listener on that workspace's host). Each row has `port`, `pid`, `processName`, `connectHost`, `protocol`, and `kind` (`workspace`, `container`, or `external`). Only `workspace` rows have `owner` (with `owner.confidence`: `cwd` or `command`) and, when the dev server printed one in an Orca terminal, `advertisedUrl`. Use this to find a dev server's port instead of running `lsof` yourself. If `unavailableReason` is set, the scan could not run on that host. Native folder workspaces need `--all`, because Orca does not tie ports to them. SSH workspaces opened directly from this app report `unavailableReason` for now; a workspace on a managed Orca server is scanned on that server.
Ports: `ORCA ports --json` lists the listening ports Orca tied to the current workspace (`--worktree <selector>` for another one, `--all` for every listener on that workspace's server). Each row has `port`, `pid`, `processName`, `connectHost`, `protocol`, and `kind` (`workspace`, `container`, or `external`). Only `workspace` rows have `owner` (with `owner.confidence`: `cwd` or `command`) and, when the dev server printed one in an Orca terminal, `advertisedUrl`. Use this to find a dev server's port instead of running `lsof` yourself. If `unavailableReason` is set, the scan could not run on that server. Native folder workspaces need `--all`, because Orca does not tie ports to them. SSH workspaces opened directly from this app report `unavailableReason` for now; a workspace on a managed Orca server is scanned on that server.
Use `repo set --external-worktree-visibility show` to show a repo's non-Orca worktrees.
`hide` hides them; `inherit` clears the repo override and follows the global default.
@@ -134,11 +134,12 @@ Selectors:
- `folder:<folderId>` names a folder workspace, for commands that take one (`worktree activate` doesn't yet). On a folder workspace, `worktree set` changes `--display-name`, `--comment`, `--workspace-status` and `--unread`/`--read` (links go through `reference add`), and `worktree rm` makes Orca forget it while the folder stays on disk. `path:` and `name:` also match folder workspaces, so `--worktree path:<folderPath>` reaches the folder; `branch:`, `issue:` and `identity:` match worktrees only. `ORCA worktree ps --json` lists folder workspaces; `worktree list` does not.
- Older Orca versions match `path:` and `name:` against worktrees only, and may pick a worktree at the folder's path. If a folder is meant, pass `folder:<folderId>`.
- When several workspaces match, the error usually lists each choice's kind, host, path and exact selector; pass one of those. If it lists none, find the row with `ORCA worktree ps --json` (if `truncated`, repeat with `--limit <totalCount>`) and pass `identity:<identity.key>`, `folder:<folderId>`, or `id:<worktreeId>` when no other row has that id. A folder id that two folder workspaces share can't be selected; the error says how to repair it.
- For a workspace in another environment, add `--environment <id>` to the command, as with any other selector.
- For a workspace on another server, add `--server <id>` to the command, as with any other selector.
- The full id is the exact `<repo-id>::<path>` value returned by `ORCA worktree create --json` or `ORCA worktree list --json`; a bare repo id is not a worktree id.
- `active` / `current` for the Orca workspace enclosing the shell cwd, worktree or folder workspace: the innermost one wins, so a worktree nested inside a folder workspace is picked over the folder; at equal depth this terminal's own workspace wins, otherwise the error lists the choices. Pass `folder:<folderId>` to get the folder itself. `worktree rm` refuses `current`/`active` and needs an explicit selector; its error prints the one `current` resolves to. `current` resolves on this machine's Orca, so it is refused with `--environment <id>` or `--pairing-code`; use an explicit selector from that environment instead (`--environment local` keeps it on this machine even when `ORCA_ENVIRONMENT` is set).
- `--environment` selects which Orca receives the command (`local` is this machine's own Orca); `host` is that Orca's stored location metadata. Never derive an environment from `host`.
- `worktree ps` and `worktree show` give each workspace an `address` (text: an `address:` line). Copy `address.line` as is, keeping its `--environment`, or pass `address.environment` and `address.worktree` as `--environment` and `--worktree`. If `address` is null, follow `addressUnavailable` (`one-off-connection`, `unverifiable-row` or `duplicate-folder-id`) and never construct a route yourself. `parent` names the parent's environment when it is known; with `state: unknown-environment` there is no route to it from here.
- `active` / `current` for the Orca workspace enclosing the shell cwd, worktree or folder workspace: the innermost one wins, so a worktree nested inside a folder workspace is picked over the folder; at equal depth this terminal's own workspace wins, otherwise the error lists the choices. Pass `folder:<folderId>` to get the folder itself. `worktree rm` refuses `current`/`active` and needs an explicit selector; its error prints the one `current` resolves to. `current` resolves on the Orca on this computer, so it is refused with `--server <id>` or `--pairing-code`; use an explicit selector from that server instead (`--server local` keeps it on this computer even when `ORCA_ENVIRONMENT` is set).
- `--server` selects which Orca server receives the command: `local` is the Orca on this computer, any other value is a saved server's id or name (`ORCA server list`).
- A row's `server` (text: `server:` in `ps`/`show`, `server=` in `worktree list`, `terminal list`, `project setups` and worker lines) is the server that owns it. `server=unknown (...)` means Orca cannot verify the owner from here; it never guesses `local`, so don't treat that row's paths as files on this computer. JSON `hostId` is raw stored data; never build a route from it.
- `worktree ps` and `worktree show` give each workspace an `address` (text: an `address:` line): the server that answered plus a selector it accepts, which can differ from the owning `server`. Copy `address.line` as is, or pass `address.server` and `address.worktree` as `--server` and `--worktree`. If `address` is null, follow `addressUnavailable` (`one-off-connection`, `unverifiable-row` or `duplicate-folder-id`) and never construct a route yourself. `parent.server` names the parent's server when it is known; with `parent.state: unknown-server` there is no route to it from here.
- For `worktree create --parent-worktree`, folder/worktree parent context keys are also valid: `folder:<folderId>`, `worktree:<repoId>::<worktreePath>`, `id:folder:<folderId>`, `id:worktree:<repoId>::<worktreePath>`. `worktree set --parent-worktree` also takes the folder keys, `folder:<folderId>` or `id:folder:<folderId>`. On both, `path:` and `name:` record a folder workspace parent when they match one.
Lineage rules:
@@ -147,9 +148,9 @@ Lineage rules:
- Use `--parent-worktree active` when the child worktree relationship should be explicit.
- Use `--parent-worktree folder:<folderId>` or `--parent-worktree worktree:<repoId>::<worktreePath>` when a folder or worktree parent context should be explicit.
- Use `--no-parent` only when the new work is independent.
- A parent can be in a different project from its child, such as `worktree create --repo id:<otherRepoId> --name related-task --parent-worktree id:<parentRepoId>::<parentPath>`. A worktree parent and child must use the same execution host (local machine, SSH target, or paired server).
- `--parent-worktree` is looked up in the child's environment. For a parent in another environment, add `--parent-environment <local|environment-id>`: to reuse a workspace from `ps`/`show` as a parent, pass its `address.environment` as `--parent-environment` and its `address.worktree` as `--parent-worktree`. Orca never searches other environments; a parent missing there is an error. `active`/`current` always mean this machine's own workspace, so they take only `--parent-environment local`.
- An address with `--environment local` means the Orca that printed it, because `local` is always the machine running the command; don't hand an address to another machine to run. To link workspaces across environments, run the command from the Orca that has both paired, such as `--environment <server> --worktree <selector> --parent-worktree current`.
- A parent can be in a different project from its child, such as `worktree create --repo id:<otherRepoId> --name related-task --parent-worktree id:<parentRepoId>::<parentPath>`. A parent can also be on another server: name it with `--parent-server`. The child's server must support parents on other servers; an older one refuses before changing anything.
- `--parent-worktree` is looked up on the child's server. For a parent on another server, add `--parent-server <local|server-id>`: to reuse a workspace from `ps`/`show` as a parent, pass its `address.server` as `--parent-server` and its `address.worktree` as `--parent-worktree`. Orca never searches other servers; a parent missing there is an error. `active`/`current` always mean a workspace on this computer, so they take only `--parent-server local`.
- An address with `--server local` means the Orca that printed it, because `local` is always the computer running the command; don't hand an address to another computer to run. To link workspaces across servers, run the command from the Orca that has both saved, such as `--server <server> --worktree <selector> --parent-worktree current`.
- To move an existing worktree under a different parent, or make it top-level, use `worktree set` with `--parent-worktree <selector>` or `--no-parent`.
- `--no-parent` only controls Orca lineage; it does not choose the Git base. For independent top-level work, omit `--base-branch` so Orca uses the repo default base, or explicitly pass the repo default base. Never base it on the current feature branch unless the user asks for stacked work or "branch from current".
@@ -248,13 +249,13 @@ Terminal rules:
- `--terminal` is optional for most commands; omitted means the active terminal in the current worktree.
- Use `terminal close --terminal <handle>` to close one terminal. Use `terminal close --worktree <selector> --all` to stop every terminal process in exactly that workspace and durably remove its terminal tabs, layouts, and agent-resume records.
- A bulk close fails when the execution host cannot confirm every PTY stopped. Treat that as `unverifiable`; do not report the processes as exited or retry against another host.
- A bulk close fails when the server cannot confirm every PTY stopped. Treat that as `unverifiable`; do not report the processes as exited or retry against another server.
- Use workspace Sleep, not close, when the terminals and agent sessions should resume later. `terminal stop` is legacy compatibility plumbing and should not be used in new agent workflows.
- `terminal list --json` omits `visualLayouts` to keep the common agent payload bounded. Add `--include-visual-layouts` only when tab and pane topology is required.
- A chat tab has no terminal handle, so `terminal rename` cannot rename it. Use `ORCA chat rename --session <sessionId> --name "New Name" --json` with the `sessionId` `agent launch` printed; inside a chat, omit `--session` to rename that chat.
- `terminal create --title` and `terminal rename` set the tab title, which `terminal list` reports under `visualLayouts`. `terminal set-pane-title` sets one pane's title, reported as `terminals[].paneTitle`. `terminals[].title` may be the tab title or the running program's own title, which agents repaint constantly, so never match on it to re-find a terminal.
- `terminals[].agentIdentity`, when present, is only the agent type (e.g. `codex`), not a session identity, so two Codex panes share it. To find a specific agent's terminal, join `worktree ps --json` `agents[].paneKey` (`<tabId>:<leafId>`) to the `tabId` and `leafId` of a `terminal list` row to get its handle.
- A paired server has no window. `terminal switch --environment <name>` moves the desktop app on this machine to that server's terminal, and reports `navigated: false` when no desktop here shows that server.
- A server reached with `--server` has no window. `terminal switch --server <id>` moves the desktop app on this computer to that server's terminal, and reports `navigated: false` when no desktop here shows that server.
- Use `terminal read` before `terminal send` unless the next input is obvious.
- `terminal read` returns accumulated output with escape sequences stripped, not the rendered screen, so anything that repaints (shells, progress bars, TUIs) reads as stacked fragments. Use `--screen` whenever the answer depends on what the terminal actually shows.
- `--screen` and `--cursor` are mutually exclusive: a screen read is the current frame and has no history to page.
@@ -325,7 +326,7 @@ a plugin. To design, write and debug a plugin end to end, invoke the `orca-plugi
## Agent Session Search
`ORCA search` runs a full-text search over the agent sessions indexed on one Orca host: this machine, or the paired server named by `--environment` or `--pairing-code`. There is no all-computers search.
`ORCA search` runs a full-text search over the agent sessions indexed on one Orca server: the Orca on this computer, or the server named by `--server` or `--pairing-code`. There is no all-servers search.
Common commands:
@@ -335,7 +336,7 @@ ORCA search "resolveTerminalPath" --scope conversation --json
ORCA search "blank restore" --agent codex --since 2026-09-01T00:00:00Z --json
ORCA search "blank restore" --path /abs/worktree --sort newest --limit 50 --json
ORCA search "blank restore" --cursor <cursor> --json
ORCA search "blank restore" --environment <environmentId> --json
ORCA search "blank restore" --server <serverId> --json
ORCA search "blank restore" --fresh --debug --json
ORCA search --index-status --json
```
+6 -6
View File
@@ -52,7 +52,7 @@ Exit codes: `0` ok, `1` error, `2` `plugin_invalid`, `3` `approval_required` or
(see `docs/reference/plugin-declarative-ui.md`, "Testing"). Both run the plugin's code
unsandboxed on this machine: use them only on code you trust.
4. `plugin dev load <dir>` adds the folder to Settings → Plugins → Development folders on the
Orca host and loads it. Orca reloads it, and restarts its worker, when its files change; run
Orca server and loads it. Orca reloads it, and restarts its worker, when its files change; run
`plugin dev reload <dir>` if a change was missed. `plugin restart <plugin-key>` stops a
worker so its next command or event reruns its startup code. `plugin logs` shows what a worker printed and a panel's or editor's
console errors, warnings and uncaught exceptions as `[frame] <file>:<line> <message>`.
@@ -92,13 +92,13 @@ Exit codes: `0` ok, `1` error, `2` `plugin_invalid`, `3` `approval_required` or
Both need the desktop app with a workspace showing and never raise the window.
6. `plugin dev unload <dir>` when done.
Paths are on the machine that runs Orca. With `--environment <server>`, pass an absolute path
Paths are on the machine that runs Orca. With `--server <server>`, pass an absolute path
on that server. From an SSH or WSL shell that forwards `orca` to another machine, the authoring
and dev commands refuse; work on the Orca host instead.
and dev commands refuse; work on the Orca server instead.
`plugin_system_disabled` means plugins are off on that host. Ask the user to click "Turn on
plugins" in Settings → Plugins, or on a host with no window (`orca serve`) to run
`plugin system on` with the same `--environment`. It approves nothing; only plugins approved
`plugin system on` with the same `--server`. It approves nothing; only plugins approved
earlier start.
## Install, update and remove
@@ -110,7 +110,7 @@ earlier start.
- `owner/repo` or `owner/repo@v1.2.0` on GitHub,
- any `https://` or `ssh://` Git URL or `git@host:owner/repo.git`, with `#ref` for a version,
- a GitHub or GitLab release, tag or tree page URL (`.../releases/tag/v1.2.0`, `.../-/tree/main`),
- a plugin folder (a path on the Orca host).
- a plugin folder (a path on the Orca server).
With no version, Orca installs the newest version tag (`vX.Y.Z`), else the default branch, and
always pins the exact commit. The result names the version, commit, publisher and repository.
@@ -137,7 +137,7 @@ returns `approval_required` with a `cat1-…` fingerprint for that exact URL and
## Private repositories
Git runs on the Orca host (the `--environment` server when given) with that machine's own Git
Git runs on the Orca server (the `--server` one when given) with that machine's own Git
credentials and never prompts. Nothing to pass to `orca`; set up Git there once:
- HTTPS on GitHub: `gh auth login` then `gh auth setup-git`. GitLab: `glab auth login`. Elsewhere:
+1 -1
View File
@@ -30,7 +30,7 @@ device with `emulator_unsupported`. `tap`, `type`, `gesture`, `button`, `rotate`
tree on Android, a serve-sim node tree on iOS.
Camera and sensor injection are not wrapped; Android virtual-scene is out of scope. Commands
drive the SDK and devices on the host that runs the Orca runtime, including a headless
drive the SDK and devices on the computer that runs the Orca server, including a headless
`orca serve` or SSH host.
## Prerequisites
+1 -1
View File
@@ -24,7 +24,7 @@ unvalidated with the active device injected.
device with `emulator_unsupported`. `tap`, `type`, `gesture`, `button`, `rotate`, `ax`, and
`exec` work on both backends.
Commands drive devices on the host that runs the Orca runtime. Simulators need that host to
Commands drive devices on the computer that runs the Orca server. Simulators need that computer to
be a Mac, so a Linux `orca serve` or SSH host can drive only Android devices.
## Prerequisites
+1 -1
View File
@@ -142,7 +142,7 @@ Confirm `ORCA status --json` unless already checked this turn, then read the iss
## Connections and verified reads
Configure credentials in Orca Settings. `ORCA jira connection --json` lists saved site IDs; it does not test access or agent MCP authentication. These commands use credentials on the selected execution host, including SSH hosts. Update that host if the CLI reports `incompatible_runtime`.
Configure credentials in Orca Settings. `ORCA jira connection --json` lists saved site IDs; it does not test access or agent MCP authentication. These commands use credentials on the selected server, including servers on SSH hosts. Update that host if the CLI reports `incompatible_runtime`.
A successful empty list means the Jira read completed; API, permission and network errors remain errors. Jira keys are case-insensitive; full browse URLs are accepted wherever an issue key is required. Use `--body-file <path>` for multiline descriptions and comments, or `--body-file -` for stdin.
+1 -1
View File
@@ -83,7 +83,7 @@ Use `ORCA linear list-issues` when MCP-compatible filters or cursor pagination a
- Omitting `--limit` returns every match and reports `result.meta.limit` as `null`, so filter before listing a large workspace. `--limit <n>` caps the read.
- When a cap held results back, `--json` sets `result.truncated` and `result.meta.hasMore`; human output prints `truncated: showing N`. Check `truncated` before reporting a count, then page with `--cursor` until it is false.
- A `--cursor` is bound to the workspace and the Orca runtime that issued it. `--workspace all` cannot page, and a raw Linear cursor still needs a concrete `--workspace`.
- A `--cursor` is bound to the workspace and the Orca server that issued it. `--workspace all` cannot page, and a raw Linear cursor still needs a concrete `--workspace`.
- `--priority` is `0=none`, `1=urgent`, `2=high`, `3=medium`, `4=low`. Issue JSON carries `priorityLabel` in the CLI setter vocabulary; project JSON keeps Linear's title-case label.
- `ORCA linear search`, `ORCA linear list`, and `ORCA linear project list` cap at their own `--limit` and set `result.truncated` the same way.
+1 -1
View File
@@ -18,7 +18,7 @@ Pass `--json` to every `ORCA plugin` command and branch on `error.code`, not on
- **Your files:** a new folder, ideally its own Git repository, with `orca-plugin.json` at its
root, made by `ORCA plugin create` (never overwrites). Paths are on the machine that runs Orca;
with `--environment` pass an absolute path on that server.
with `--server` pass an absolute path on that server.
- **Types:** `ORCA plugin types <dir>` (also run by `dev watch`) writes `.orca/types/` for every
surface; the plugin's `tsconfig.json` extends `./.orca/types/tsconfig.json`. Never edit `.orca/`.
- **Ground truth:** the references below match this Orca. Read them instead of guessing.
@@ -11,12 +11,12 @@
- `ORCA plugin validate <dir|orca-plugin.json|orca-catalog.json> [--json]`: Check a plugin folder, manifest or catalog the way Orca will load it
- `ORCA plugin inspect <dir> [--json]`: Show what a plugin folder contributes, the access it asks for, and its content hash
- `ORCA plugin release-entry <dir> [--json]`: Print the catalog release entry for a plugin folder's committed HEAD
- `ORCA plugin list [--json]`: List plugins on the Orca host with their status and access level
- `ORCA plugin list [--json]`: List plugins on the Orca server with their status and access level
- `ORCA plugin logs <plugin-key> [--json]`: Print the recent log lines of a plugin
- `ORCA plugin enable <plugin-key> [--approve <fingerprint>] [--json]`: Enable a plugin; code and capabilities need --approve
- `ORCA plugin disable <plugin-key> [--json]`: Disable a plugin
- `ORCA plugin system on [--json]`: Turn plugins on for the Orca host
- `ORCA plugin system off [--json]`: Turn plugins off for the Orca host
- `ORCA plugin system on [--json]`: Turn plugins on for the Orca server
- `ORCA plugin system off [--json]`: Turn plugins off for the Orca server
- `ORCA plugin restart <plugin-key> [--json]`: Stop a plugin's worker so its next command or event starts it fresh
- `ORCA plugin dev watch <dir> [--check] [--shot <out-dir> [--shot-panel <id>]] [--approve <fingerprint>] [--json]`: Load a plugin folder, then stream its logs and reloads until Ctrl-C
- `ORCA plugin dev load <dir> [--approve <fingerprint>] [--json]`: Load a plugin folder into Orca as a development plugin
@@ -67,7 +67,7 @@ re-checks changed commands and shortcuts), `ORCA plugin dev unload <dir>`.
a dev plugin, run inside its folder. The result adds `replay: true` and `scenario`, and
`errors` has what the render reported; an unknown name fails and lists the scenarios. Limits:
a still frame (host-owned control values start from the tree's props), images show their
placeholder, no `--act`, local only (no `--environment`), and Orca's window must be hidden
placeholder, no `--act`, local only (no `--server`), and Orca's window must be hidden
or minimized. Default file `.orca/shots/<plugin-key>-<panel>.<scenario>.png`.
- `ORCA plugin open <plugin-key> [--panel <id> | --editor <file>]` shows the panel in the right
sidebar, or a file in the plugin's custom editor. Neither raises the window. `--editor` opens the
+1 -1
View File
@@ -50,7 +50,7 @@ ORCA orchestration worker-start --spec "<task>" --worktree current --agent codex
in any state: a working worker gets it when its current turn ends; a finished
or closed one gets it as a follow-up Task and reports with `worker_done`. The
receipt says which.
Except on a paired server: a finished worker there refuses `send`, so start
Except on another server: a finished worker there refuses `send`, so start
new work there with `worker-start --on <server>` (load
`references/placement-and-remote.md` first).
@@ -18,10 +18,10 @@ when requesting a child of the current workspace.
ORCA orchestration worker-start --task <task_id> --worktree new-child --agent codex --setup run
# On a connected server; the Run stays on yours.
ORCA orchestration worker-start --task <task_id> --on <environment> --worktree new-top-level --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run
ORCA orchestration worker-start --task <task_id> --on <server> --worktree new-top-level --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run
# On a connected server, nested under your workspace in the sidebar.
ORCA orchestration worker-start --task <task_id> --on <environment> --worktree new-child --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run
ORCA orchestration worker-start --task <task_id> --on <server> --worktree new-child --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run
```
With `--on`, both `new-child` and `new-top-level` need `--repo` naming a
+2 -1
View File
@@ -1,5 +1,6 @@
import type { CommandSpec } from './args'
import { effectiveAllowedFlags } from './args'
import { INPUT_ONLY_FLAGS } from './command-spec'
const SCHEMA_VERSION = 1
@@ -36,7 +37,7 @@ export function buildAgentContext(specs: CommandSpec[]): AgentContextSchema {
summary: spec.summary,
usage: spec.usage,
// Include globals and conditional flags so discovery matches validation.
flags: effectiveAllowedFlags(spec),
flags: effectiveAllowedFlags(spec).filter((flag) => !INPUT_ONLY_FLAGS.has(flag)),
positionalArgs: spec.positionalArgs ?? [],
...(spec.variadicPositional ? { variadicPositional: true } : {}),
...(spec.repeatableFlags ? { repeatableFlags: spec.repeatableFlags } : {}),
+3 -3
View File
@@ -59,12 +59,12 @@ export async function withCliAgentLaunchRecovery<T>(
: undefined
const nextSteps = recovery.operationId
? [
`Re-issue the exact same command from the same directory against the same execution host with --retry-launch ${recovery.operationId}. Keep that ID on every retry; never retry as a fresh launch.`,
`Re-issue the exact same command from the same directory against the same server with --retry-launch ${recovery.operationId}. Keep that ID on every retry; never retry as a fresh launch.`,
'If replay reports an unknown or expired outcome, inspect the workspace and agent without sending input before deciding what to do.'
]
: [
'Do not repeat the launch: this older host cannot prove whether it started the agent or sent the prompt.',
'Inspect worktree list and terminal list on the execution host, then read the agent without sending input. Confirm the outcome before deliberately starting another agent.'
'Do not repeat the launch: this older server cannot prove whether it started the agent or sent the prompt.',
'Inspect worktree list and terminal list on the server, then read the agent without sending input. Confirm the outcome before deliberately starting another agent.'
]
// Replace transport restart-and-retry advice: the accepted launch may still be running.
throw new RuntimeClientError(
+5 -5
View File
@@ -75,7 +75,7 @@ export function readCliAgentLaunch(
model: getOptionalStringFlag(flags, 'model'),
effort: getOptionalStringFlag(flags, 'effort'),
createsWorktree: target.createsWorktree,
// The execution host verifies an OpenCode model itself before it starts one.
// The server verifies an OpenCode model itself before it starts one.
openCodeModelLaunchSupported: true
})
if ('refusal' in checked) {
@@ -107,7 +107,7 @@ export function hasLaunchModelFlags(flags: Flags): boolean {
// An older host strips `surface` and follows its own setting, so an explicit pick never reaches it.
export const SURFACE_UNSUPPORTED_MESSAGE =
'This Orca host cannot start an agent as a chat or a terminal on request. Update Orca on the execution host, or omit --surface.'
'This Orca server cannot start an agent as a chat or a terminal on request. Update Orca on that server, or omit --surface.'
export async function getAgentLaunchCapabilities(
client: RuntimeClient
@@ -128,13 +128,13 @@ export async function callAgentLaunch(
if (launch.operationId && !replaySupported) {
throw new RuntimeClientError(
'agent_session_operation_unknown',
'This host cannot replay the earlier launch. Return to the original execution host; do not retry without --retry-launch.'
'This server cannot replay the earlier launch. Return to the server that started it; do not retry without --retry-launch.'
)
}
if (launch.prompt && !capabilities.includes(AGENT_LAUNCH_PROMPT_CARRY_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host cannot safely carry launch prompts. Update Orca on the execution host.'
'This Orca server cannot safely carry launch prompts. Update Orca on that server.'
)
}
if (launch.surface && !capabilities.includes(AGENT_LAUNCH_SURFACE_RUNTIME_CAPABILITY)) {
@@ -143,7 +143,7 @@ export async function callAgentLaunch(
if (!capabilities.includes(AGENT_LAUNCH_LOCAL_PRESENTATION_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host cannot honor CLI launch focus or background behavior. Update Orca on the execution host.'
'This Orca server cannot honor CLI launch focus or background behavior. Update Orca on that server.'
)
}
const operationId = replaySupported
+2 -7
View File
@@ -46,12 +46,7 @@ describe('terminal safety', () => {
{ updatedAt: '2026-09-12\u001b[31mT18:04:11.000Z' },
'Claude 2026-09-12T18:04:11.000Z'
],
[
'executionHostId',
{ executionHostId: 'ssh:\u001b]0;pwned\u0007build-01' },
'host=ssh:build-01'
],
['title', { title: 'resize\u001b[2Jrace' }, ' resizerace host='],
['title', { title: 'resize\u001b[2Jrace' }, ' resizerace\n'],
[
'evidence snippet',
{ evidence: { ...localHit.evidence!, snippet: 'a\u001b[1mb' } },
@@ -125,7 +120,7 @@ describe('terminal safety', () => {
]
})
)
expect(text).toContain('Claude 2026-09-12T18:04:11.000Z wrapped title host=ssh:build-01')
expect(text).toContain('Claude 2026-09-12T18:04:11.000Z wrapped title\n')
expect(text).toContain(' assistant: first second')
})
})
+8 -10
View File
@@ -18,12 +18,10 @@ function oneLine(value: string): string {
}
function formatHit(hit: AiVaultSearchHit): string {
const host = oneLine(hit.executionHostId ?? '')
const header = [
aiVaultAgentLabel(hit.agent),
oneLine(hit.updatedAt ?? '') || 'unknown time',
oneLine(hit.title) || '(untitled)',
...(host ? [`host=${host}`] : [])
oneLine(hit.title) || '(untitled)'
].join(' ')
const evidence = hit.evidence
? ` ${hit.evidence.role}: ${oneLine(hit.evidence.snippet)}`
@@ -65,21 +63,21 @@ function formatUnavailable(
reason: 'disabled' | 'not-ready' | 'no-service' | 'scope-unknown' | 'unsupported-agent'
): string {
if (reason === 'disabled') {
return 'Session search is off on this host.'
return 'Session search is off on this server.'
}
if (reason === 'unsupported-agent') {
return 'This host does not support history search for the selected agent. Update Orca on that host or select another agent.'
return 'This server does not support history search for the selected agent. Update Orca on that server or select another agent.'
}
// Only hand-built requests can select an unknown identity; the CLI scopes by path.
if (reason === 'scope-unknown') {
return 'This host does not know the workspace or project that search was scoped to.'
return 'This server does not know the workspace or project that search was scoped to.'
}
if (reason === 'not-ready') {
return 'Session search is not ready on this host yet. Try again once its index has started.'
return 'Session search is not ready on this server yet. Try again once its index has started.'
}
return [
'This host runs no session search service.',
'An Orca host older than session search answers the same way; update it and try again.'
'This server runs no session search service.',
'An Orca server older than session search answers the same way; update it and try again.'
].join('\n')
}
@@ -92,7 +90,7 @@ function formatResults(response: SessionSearchResults): string {
...(response.page.hasMore && cursor
? [`more pages: re-run with --cursor ${cursor}`]
: response.page.hasMore
? ['more pages exist, but this host issued no cursor for them']
? ['more pages exist, but this server issued no cursor for them']
: []),
...formatTruncation(response.truncated)
]
+4 -4
View File
@@ -224,21 +224,21 @@ describe('validateCommandAndFlags', () => {
'demo',
'--pairing-code',
'remote-runtime',
'--environment',
'server',
'--server',
'build-box',
'--json'
])
expect(() => validateCommandAndFlags(specs, parsed)).not.toThrow()
})
it.each(['environment', 'pairing-code'])('rejects --%s without a value', (flag) => {
it.each(['server', 'pairing-code'])('rejects --%s without a value', (flag) => {
const parsed = parseArgs([`--${flag}`, 'demo'], [['demo']])
expect(() => validateCommandAndFlags(specs, parsed)).toThrow(`Flag --${flag} requires a value.`)
})
it.each(['environment', 'pairing-code'])('rejects an empty --%s= value', (flag) => {
it.each(['server', 'pairing-code'])('rejects an empty --%s= value', (flag) => {
const parsed = parseArgs(['demo', `--${flag}=`])
expect(() => validateCommandAndFlags(specs, parsed)).toThrow(`Flag --${flag} requires a value.`)
+80 -6
View File
@@ -1,8 +1,9 @@
import { RuntimeClientError } from './runtime/types'
import { unknownCommandData, unknownFlagData } from './command-suggestion'
import { specPaths, type CommandSpec } from './command-spec'
import { INPUT_ONLY_FLAGS, specPaths, type CommandSpec } from './command-spec'
import {
CLI_BOOLEAN_FLAGS,
CLI_FLAG_ALIASES,
CLI_GLOBAL_FLAGS,
CLI_GLOBAL_VALUE_FLAGS,
findCliCommandIndex
@@ -15,6 +16,8 @@ export type ParsedArgs = {
commandPath: string[]
flags: Map<string, string | boolean>
positionalFlagConflicts?: string[]
/** Canonical flags given under both spellings with different values. */
flagAliasConflicts?: { flag: string; alias: string }[]
}
export const GLOBAL_FLAGS = CLI_GLOBAL_FLAGS
@@ -171,11 +174,71 @@ export function isCommandGroup(specs: CommandSpec[], commandPath: string[]): boo
)
}
export function normalizeCommandPositionals(specs: CommandSpec[], parsed: ParsedArgs): ParsedArgs {
/** Raw argv with old flag spellings renamed, so commands rebuilt from argv print only canonical flags. */
export function canonicalizeLegacyFlagArgv(argv: readonly string[]): string[] {
const end = argv.indexOf('--')
return argv.map((token, index) => {
if ((end !== -1 && index >= end) || !token.startsWith('--')) {
return token
}
const [name, ...value] = token.slice(2).split('=')
const canonical = CLI_FLAG_ALIASES[name]
return canonical === undefined ? token : [`--${canonical}`, ...value].join('=')
})
}
/** Renames old flag spellings so every later reader sees only canonical flags. */
function canonicalizeFlagAliases(parsed: ParsedArgs): ParsedArgs {
if (!Object.keys(CLI_FLAG_ALIASES).some((alias) => parsed.flags.has(alias))) {
return parsed
}
const flags = new Map<string, string | boolean>()
const conflicts: { flag: string; alias: string }[] = []
for (const [name, value] of parsed.flags) {
const canonical = CLI_FLAG_ALIASES[name]
if (canonical === undefined) {
flags.set(name, value)
} else if (!parsed.flags.has(canonical)) {
flags.set(canonical, value)
} else if (parsed.flags.get(canonical) !== value) {
conflicts.push({ flag: canonical, alias: name })
}
}
return {
...parsed,
flags,
...(conflicts.length > 0 ? { flagAliasConflicts: conflicts } : {})
}
}
/** A group typed under an alias (`orca environment`) names the canonical group (`orca server`). */
function canonicalizeGroupAlias(specs: CommandSpec[], parsed: ParsedArgs): ParsedArgs {
const path = parsed.commandPath
if (path.length === 0 || isCanonicalPrefix(specs, path)) {
return parsed
}
for (const spec of specs) {
for (const alias of [...(spec.aliases ?? []), ...(spec.legacyAliases ?? [])]) {
if (alias.length > path.length && matches(alias.slice(0, path.length), path)) {
return { ...parsed, commandPath: spec.path.slice(0, path.length) }
}
}
}
return parsed
}
function isCanonicalPrefix(specs: CommandSpec[], path: string[]): boolean {
return specs.some(
(spec) => spec.path.length >= path.length && matches(spec.path.slice(0, path.length), path)
)
}
export function normalizeCommandPositionals(specs: CommandSpec[], input: ParsedArgs): ParsedArgs {
const parsed = canonicalizeFlagAliases(input)
for (const spec of specs) {
const positionalArgs = spec.positionalArgs ?? []
// Alias-only paths still need canonicalization without positional arguments.
if (positionalArgs.length === 0 && !spec.aliases) {
if (positionalArgs.length === 0 && !spec.aliases && !spec.legacyAliases) {
continue
}
for (const base of specPaths(spec)) {
@@ -203,10 +266,10 @@ export function normalizeCommandPositionals(specs: CommandSpec[], parsed: Parsed
setFlagValue(flags, name, value, new Set(spec.repeatableFlags ?? []))
}
})
return { commandPath: spec.path, flags, positionalFlagConflicts }
return { ...parsed, commandPath: spec.path, flags, positionalFlagConflicts }
}
}
return parsed
return canonicalizeGroupAlias(specs, parsed)
}
export function findCommandSpec(
@@ -243,6 +306,14 @@ export function validateCommandAndFlags(specs: CommandSpec[], parsed: ParsedArgs
)
}
const aliasConflict = parsed.flagAliasConflicts?.[0]
if (aliasConflict) {
throw new RuntimeClientError(
'invalid_argument',
`--${aliasConflict.flag} and --${aliasConflict.alias} name different values; pass only --${aliasConflict.flag}.`
)
}
const pageAllowed = supportsBrowserPageFlag(spec)
const repeatable = new Set([...REPEATABLE_STRING_FLAGS, ...(spec.repeatableFlags ?? [])])
for (const [flag, value] of parsed.flags) {
@@ -254,7 +325,10 @@ export function validateCommandAndFlags(specs: CommandSpec[], parsed: ParsedArgs
throw new RuntimeClientError(
'invalid_argument',
`Unknown flag --${flag} for command: ${spec.path.join(' ')}`,
unknownFlagData(flag, effectiveAllowedFlags(spec))
unknownFlagData(
flag,
effectiveAllowedFlags(spec).filter((name) => !INPUT_ONLY_FLAGS.has(name))
)
)
}
if (repeatable.has(flag) && !BOOLEAN_FLAGS.has(flag) && typeof value !== 'string') {
+1 -1
View File
@@ -14,7 +14,7 @@ import { listEnvironments } from '../shared/remote-runtime/host-store/runtime-en
import { RuntimeClient } from './runtime-client'
import { fetchSshTargetSummaries } from './host-selector-alternatives'
/** Empty selectors mean the execution host cannot change. */
/** Empty selectors mean the server cannot change. */
export type AutomationDestinationTarget = { repo?: string; workspace?: string }
async function resolveTargetRepo(
+32 -20
View File
@@ -8,6 +8,7 @@ import { getAutomationLegacyRepoId } from '../shared/automations/history/automat
import { formatAutomationPrecheckTimeout } from '../shared/automations/launch/automation-precheck'
import { formatAutomationSchedule } from '../shared/automations/scheduling/automation-schedules'
import { quoteCliCommandArgument } from './shell-command-quote'
import { serverLabel, type WorkspaceServer } from './row-owner-server'
export type AutomationListPayload = {
automations: Automation[]
@@ -21,24 +22,26 @@ export type AutomationShowPayload = {
owner?: AutomationOwnerPrecondition
}
const ORPHAN_HOST_LABEL = 'orphan (no host can run this automation)'
function formatOwnerSelector(selector: AutomationOwnerPrecondition['selector']): string {
/** `self` is the answering server; an SSH owner is not proven to be an Orca server, so it is not named. */
function formatOwnerServer(
selector: AutomationOwnerPrecondition['selector'] | AutomationListItem['selector'],
answering: WorkspaceServer | undefined,
orphanIssue: string
): string {
if (selector.kind === 'ssh') {
return `ssh:${selector.targetId} (generation ${selector.targetGeneration})`
return `unknown (SSH connection ssh:${selector.targetId}, generation ${selector.targetGeneration})`
}
return selector.kind === 'orphan' ? ORPHAN_HOST_LABEL : 'self'
if (selector.kind === 'orphan') {
return `none (orphan: ${orphanIssue})`
}
return answering ? serverLabel(answering) : 'self'
}
function formatListItemSelector(item: AutomationListItem): string {
const selector = item.selector
if (selector.kind === 'ssh') {
return `ssh:${selector.targetId} (generation ${selector.targetGeneration})`
}
return selector.kind === 'orphan' ? `orphan — ${selector.issue}` : 'self'
}
export function formatAutomationList(result: AutomationListPayload): string {
/** `answering` is the server that answered, which owns its `self` automations. */
export function formatAutomationList(
result: AutomationListPayload,
answering?: WorkspaceServer
): string {
if (result.automations.length === 0) {
return 'No automations found.'
}
@@ -47,13 +50,18 @@ export function formatAutomationList(result: AutomationListPayload): string {
.map((automation) => {
const status = automation.enabled ? 'enabled' : 'disabled'
const item = hosts.get(automation.id)
const host = item ? `\nhost: ${formatListItemSelector(item)}` : ''
return `${automation.id} ${automation.name} ${automation.agentId} ${status}\n${formatAutomationSchedule(automation.rrule)} next: ${new Date(automation.nextRunAt).toISOString()}${host}`
const server = item
? `\nserver: ${formatOwnerServer(item.selector, answering, item.selector.kind === 'orphan' ? item.selector.issue : '')}`
: ''
return `${automation.id} ${automation.name} ${automation.agentId} ${status}\n${formatAutomationSchedule(automation.rrule)} next: ${new Date(automation.nextRunAt).toISOString()}${server}`
})
.join('\n\n')
}
export function formatAutomationShow(result: AutomationShowPayload): string {
export function formatAutomationShow(
result: AutomationShowPayload,
answering?: WorkspaceServer
): string {
const automation = result.automation
const runContext = automation.runContext ?? null
const projectLines = runContext
@@ -92,7 +100,11 @@ export function formatAutomationShow(result: AutomationShowPayload): string {
`baseBranch: ${automation.baseBranch ?? 'null'}`,
`reuseSession: ${automation.reuseSession}`,
`target: ${automation.executionTargetType}:${automation.executionTargetId}`,
...(result.owner ? [`host: ${formatOwnerSelector(result.owner.selector)}`] : []),
...(result.owner
? [
`server: ${formatOwnerServer(result.owner.selector, answering, 'no server can run this automation')}`
]
: []),
`prompt: ${automation.prompt}`
].join('\n')
}
@@ -141,11 +153,11 @@ function formatAutomationRunFollowUp(
!target.environment.startsWith('--') &&
(process.platform !== 'win32' || /^[a-zA-Z0-9._:/@ -]+$/.test(target.environment))
if (target.environment && safeEnvironment) {
command.push('--environment', quoteCliCommandArgument(target.environment))
command.push('--server', quoteCliCommandArgument(target.environment))
}
const prefix =
target.preserveConnectionSettings || (target.environment && !safeEnvironment)
? 'Follow up on the same host and profile (preserve your connection/profile settings)'
? 'Follow up on the same server and profile (preserve your connection/profile settings)'
: 'Follow up'
return `${prefix}: ${command.join(' ')}`
}
@@ -9,20 +9,20 @@ export type AutomationOwnerConflictRecovery = { nextSteps: readonly string[] }
const RECOVERY: Record<string, readonly string[]> = {
[AUTOMATION_OWNER_CONFLICT_CODES.ownerChanged]: [
'The automation moved to a different host between the read and the write.',
'Run the command again; it captures the current host on each attempt.'
'The automation moved to a different owner between the read and the write.',
'Run the command again; it captures the current owner on each attempt.'
],
[AUTOMATION_OWNER_CONFLICT_CODES.targetRemoved]: [
'This automation is pinned to an SSH host that is no longer registered, so it cannot run and retrying will not change that.',
'Re-add that SSH host, or delete the automation with `orca automations remove --id <id>`.'
],
[AUTOMATION_OWNER_CONFLICT_CODES.fencingRequired]: [
'The host accepted the request but did not report which host owns the automation, so the CLI had no owner to send.',
'Update Orca on the host, then run the command again.'
'The server accepted the request but did not report who owns the automation, so the CLI had no owner to send.',
'Update Orca on the server, then run the command again.'
],
[AUTOMATION_OWNER_CONFLICT_CODES.invalidDestination]: [
'The host this command targets is not registered on the authority that stores the automation.',
'Run `orca automations show --id <id>` to see where it lives, then target a host that authority knows.'
'The owner this command targets is not registered on the server that stores the automation.',
'Run `orca automations show --id <id>` to see where it lives, then target an owner that server knows.'
]
}
+1 -1
View File
@@ -40,7 +40,7 @@ async function getEnforceableExpectUrl(
if (!status.result.capabilities?.includes(BROWSER_EXPECT_URL_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca runtime cannot check --expect-url yet. Update Orca on it or drop the flag.'
'This Orca server cannot check --expect-url yet. Update Orca on it or drop the flag.'
)
}
return expectUrl
+1 -1
View File
@@ -15,7 +15,7 @@ async function assertBrowserIdentitySupported({ client }: HandlerContext): Promi
if (!status.result.capabilities?.includes(BROWSER_IDENTITY_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'The running Orca runtime does not support browser identity management. Update or restart Orca and try again.'
'The running Orca server does not support browser identity management. Update or restart Orca and try again.'
)
}
}
+36 -35
View File
@@ -127,7 +127,7 @@ const LINEAR_TICKETS_MARKDOWN = [
"",
"- Omitting `--limit` returns every match and reports `result.meta.limit` as `null`, so filter before listing a large workspace. `--limit <n>` caps the read.",
"- When a cap held results back, `--json` sets `result.truncated` and `result.meta.hasMore`; human output prints `truncated: showing N`. Check `truncated` before reporting a count, then page with `--cursor` until it is false.",
"- A `--cursor` is bound to the workspace and the Orca runtime that issued it. `--workspace all` cannot page, and a raw Linear cursor still needs a concrete `--workspace`.",
"- A `--cursor` is bound to the workspace and the Orca server that issued it. `--workspace all` cannot page, and a raw Linear cursor still needs a concrete `--workspace`.",
"- `--priority` is `0=none`, `1=urgent`, `2=high`, `3=medium`, `4=low`. Issue JSON carries `priorityLabel` in the CLI setter vocabulary; project JSON keeps Linear's title-case label.",
"- `ORCA linear search`, `ORCA linear list`, and `ORCA linear project list` cap at their own `--limit` and set `result.truncated` the same way.",
"",
@@ -274,7 +274,7 @@ const ORCA_CLI_MARKDOWN = [
"ORCA worktree create --name <task-name> --no-parent --agent codex --model gpt-6-astra --effort high --prompt \"<task brief>\" --json",
"```",
"",
"Read what started from `result.launch`: `outcome.kind` is `structured` (a chat) or `terminal`, `outcome.handle` is the agent handle, `receipt.detail` says why, and `prompt.outcome` says whether the brief arrived. An Orca host older than this returns the terminal handle in `result.agentTerminalHandle` and refuses `--model`/`--effort`.",
"Read what started from `result.launch`: `outcome.kind` is `structured` (a chat) or `terminal`, `outcome.handle` is the agent handle, `receipt.detail` says why, and `prompt.outcome` says whether the brief arrived. An Orca server older than this returns the terminal handle in `result.agentTerminalHandle` and refuses `--model`/`--effort`.",
"",
"For a fresh agent in a worktree that already exists, use `agent launch`, which takes the same `--prompt`, `--model` and `--effort`:",
"",
@@ -292,7 +292,7 @@ const ORCA_CLI_MARKDOWN = [
"",
"`worktree create --agent` (new checkout) and `agent launch` (existing worktree) are how to start an agent. They go through Orca's agent launch, the same one the app's new-agent tab uses: the user's Chat | CLI choice for that agent decides whether it opens as a chat or a terminal, and the result reports which (`outcome.kind`) and why (`receipt.detail`). When a chat is not possible, such as for an agent without chat support, the launch starts a terminal and the receipt says so. `--surface chat|terminal` picks one for that launch instead of the setting; pass it only when the user asked for a chat or a terminal. `--surface chat` is refused when Orca can establish before starting anything that the agent cannot open as a chat. If support cannot be checked, the launch can fall back to a terminal. If chat becomes unavailable only after a new workspace is created, Orca keeps that workspace, its setup and default tabs, then opens a terminal; the receipt explains the fallback. `terminal create` makes a terminal for shells and commands.",
"",
"If a launch reply is lost, use the returned `operationId` to re-issue the exact same command from the same directory against the same execution host with `--retry-launch <operationId>`. Keep that ID on every retry: the host replays the accepted launch instead of starting another agent or submitting the brief twice. Do not retry as a fresh launch. If replay says the outcome is unknown or expired, or an older host gives no replay ID, inspect the workspace and agent without sending input before deciding whether another launch is needed. A host that cannot safely carry prompts or honor background/focus requests is refused before launch; update Orca on that execution host.",
"If a launch reply is lost, use the returned `operationId` to re-issue the exact same command from the same directory against the same server with `--retry-launch <operationId>`. Keep that ID on every retry: the server replays the accepted launch instead of starting another agent or submitting the brief twice. Do not retry as a fresh launch. If replay says the outcome is unknown or expired, or an older server gives no replay ID, inspect the workspace and agent without sending input before deciding whether another launch is needed. A server that cannot safely carry prompts or honor background/focus requests is refused before launch; update Orca on that server.",
"",
"## Worktrees",
"",
@@ -300,7 +300,7 @@ const ORCA_CLI_MARKDOWN = [
"",
"Its id is a two-part address, `<repoId>::<worktreePath>`, such as `repo-123::/Users/me/orca/fix-login`. Copy the whole `id` field from `ORCA worktree create --json` or `ORCA worktree list --json`. `repo-123` alone names only the repo.",
"",
"For local creation, omit `--repo` and `--project` to stay in the caller's project. Use `--parent-worktree active` for a child of the current workspace. Project selection and parent selection are separate: a native folder parent supplies lineage, not a Git destination, so pass an explicit Git target when creating from a folder outside any managed checkout. Otherwise, pass `--repo` or `--project` only when deliberately creating in another project, or when Orca asks you to disambiguate. Outside any Orca-managed project, pass an explicit target. With a paired server, discover and use that server's exact target instead of the local cwd.",
"For local creation, omit `--repo` and `--project` to stay in the caller's project. Use `--parent-worktree active` for a child of the current workspace. Project selection and parent selection are separate: a native folder parent supplies lineage, not a Git destination, so pass an explicit Git target when creating from a folder outside any managed checkout. Otherwise, pass `--repo` or `--project` only when deliberately creating in another project, or when Orca asks you to disambiguate. Outside any Orca-managed project, pass an explicit target. With `--server`, discover and use that server's exact target instead of the local cwd.",
"",
"If several Orca workspaces share the checkout and no caller identity selects one, workspace-specific commands ask you to choose an exact selector. Inspect a listed workspace with `ORCA worktree show --worktree <exact-selector> --json`, then use the command’s workspace target flag. For an implicit-create refusal, use `ORCA worktree list --limit 10000 --json` with the same server and host selection; match path and host, increasing --limit if truncated. Pass `--parent-worktree <exact-selector>` or deliberately use `--no-parent` on a fresh request without --retry-launch. Retrying the refused ID returns its original explanation. Pass each exact selector as one argument quoted for your shell. Native folder choices are shown in the local error; exact show inspection is supported, while native folders are not enumerated by worktree list. Implicit creation checks this only when the host actually uses the directory’s parent context; older hosts retain their existing implicit-parent behavior.",
"",
@@ -348,9 +348,9 @@ const ORCA_CLI_MARKDOWN = [
"ORCA worktree rm --worktree id:<repoId>::<worktreePath> --force --json",
"```",
"",
"`repo add` defaults to Git. Use `--kind folder` for an ordinary directory or a parent of separate Git repositories; worktrees attached to a folder workspace appear in its Source Control panel, one section each. With `--environment`, pass an absolute path on that server.",
"`repo add` defaults to Git. Use `--kind folder` for an ordinary directory or a parent of separate Git repositories; worktrees attached to a folder workspace appear in its Source Control panel, one section each. With `--server`, pass an absolute path on that server.",
"",
"Ports: `ORCA ports --json` lists the listening ports Orca tied to the current workspace (`--worktree <selector>` for another one, `--all` for every listener on that workspace's host). Each row has `port`, `pid`, `processName`, `connectHost`, `protocol`, and `kind` (`workspace`, `container`, or `external`). Only `workspace` rows have `owner` (with `owner.confidence`: `cwd` or `command`) and, when the dev server printed one in an Orca terminal, `advertisedUrl`. Use this to find a dev server's port instead of running `lsof` yourself. If `unavailableReason` is set, the scan could not run on that host. Native folder workspaces need `--all`, because Orca does not tie ports to them. SSH workspaces opened directly from this app report `unavailableReason` for now; a workspace on a managed Orca server is scanned on that server.",
"Ports: `ORCA ports --json` lists the listening ports Orca tied to the current workspace (`--worktree <selector>` for another one, `--all` for every listener on that workspace's server). Each row has `port`, `pid`, `processName`, `connectHost`, `protocol`, and `kind` (`workspace`, `container`, or `external`). Only `workspace` rows have `owner` (with `owner.confidence`: `cwd` or `command`) and, when the dev server printed one in an Orca terminal, `advertisedUrl`. Use this to find a dev server's port instead of running `lsof` yourself. If `unavailableReason` is set, the scan could not run on that server. Native folder workspaces need `--all`, because Orca does not tie ports to them. SSH workspaces opened directly from this app report `unavailableReason` for now; a workspace on a managed Orca server is scanned on that server.",
"",
"Use `repo set --external-worktree-visibility show` to show a repo's non-Orca worktrees.",
"`hide` hides them; `inherit` clears the repo override and follows the global default.",
@@ -362,11 +362,12 @@ const ORCA_CLI_MARKDOWN = [
"- `folder:<folderId>` names a folder workspace, for commands that take one (`worktree activate` doesn't yet). On a folder workspace, `worktree set` changes `--display-name`, `--comment`, `--workspace-status` and `--unread`/`--read` (links go through `reference add`), and `worktree rm` makes Orca forget it while the folder stays on disk. `path:` and `name:` also match folder workspaces, so `--worktree path:<folderPath>` reaches the folder; `branch:`, `issue:` and `identity:` match worktrees only. `ORCA worktree ps --json` lists folder workspaces; `worktree list` does not.",
"- Older Orca versions match `path:` and `name:` against worktrees only, and may pick a worktree at the folder's path. If a folder is meant, pass `folder:<folderId>`.",
"- When several workspaces match, the error usually lists each choice's kind, host, path and exact selector; pass one of those. If it lists none, find the row with `ORCA worktree ps --json` (if `truncated`, repeat with `--limit <totalCount>`) and pass `identity:<identity.key>`, `folder:<folderId>`, or `id:<worktreeId>` when no other row has that id. A folder id that two folder workspaces share can't be selected; the error says how to repair it.",
"- For a workspace in another environment, add `--environment <id>` to the command, as with any other selector.",
"- For a workspace on another server, add `--server <id>` to the command, as with any other selector.",
"- The full id is the exact `<repo-id>::<path>` value returned by `ORCA worktree create --json` or `ORCA worktree list --json`; a bare repo id is not a worktree id.",
"- `active` / `current` for the Orca workspace enclosing the shell cwd, worktree or folder workspace: the innermost one wins, so a worktree nested inside a folder workspace is picked over the folder; at equal depth this terminal's own workspace wins, otherwise the error lists the choices. Pass `folder:<folderId>` to get the folder itself. `worktree rm` refuses `current`/`active` and needs an explicit selector; its error prints the one `current` resolves to. `current` resolves on this machine's Orca, so it is refused with `--environment <id>` or `--pairing-code`; use an explicit selector from that environment instead (`--environment local` keeps it on this machine even when `ORCA_ENVIRONMENT` is set).",
"- `--environment` selects which Orca receives the command (`local` is this machine's own Orca); `host` is that Orca's stored location metadata. Never derive an environment from `host`.",
"- `worktree ps` and `worktree show` give each workspace an `address` (text: an `address:` line). Copy `address.line` as is, keeping its `--environment`, or pass `address.environment` and `address.worktree` as `--environment` and `--worktree`. If `address` is null, follow `addressUnavailable` (`one-off-connection`, `unverifiable-row` or `duplicate-folder-id`) and never construct a route yourself. `parent` names the parent's environment when it is known; with `state: unknown-environment` there is no route to it from here.",
"- `active` / `current` for the Orca workspace enclosing the shell cwd, worktree or folder workspace: the innermost one wins, so a worktree nested inside a folder workspace is picked over the folder; at equal depth this terminal's own workspace wins, otherwise the error lists the choices. Pass `folder:<folderId>` to get the folder itself. `worktree rm` refuses `current`/`active` and needs an explicit selector; its error prints the one `current` resolves to. `current` resolves on the Orca on this computer, so it is refused with `--server <id>` or `--pairing-code`; use an explicit selector from that server instead (`--server local` keeps it on this computer even when `ORCA_ENVIRONMENT` is set).",
"- `--server` selects which Orca server receives the command: `local` is the Orca on this computer, any other value is a saved server's id or name (`ORCA server list`).",
"- A row's `server` (text: `server:` in `ps`/`show`, `server=` in `worktree list`, `terminal list`, `project setups` and worker lines) is the server that owns it. `server=unknown (...)` means Orca cannot verify the owner from here; it never guesses `local`, so don't treat that row's paths as files on this computer. JSON `hostId` is raw stored data; never build a route from it.",
"- `worktree ps` and `worktree show` give each workspace an `address` (text: an `address:` line): the server that answered plus a selector it accepts, which can differ from the owning `server`. Copy `address.line` as is, or pass `address.server` and `address.worktree` as `--server` and `--worktree`. If `address` is null, follow `addressUnavailable` (`one-off-connection`, `unverifiable-row` or `duplicate-folder-id`) and never construct a route yourself. `parent.server` names the parent's server when it is known; with `parent.state: unknown-server` there is no route to it from here.",
"- For `worktree create --parent-worktree`, folder/worktree parent context keys are also valid: `folder:<folderId>`, `worktree:<repoId>::<worktreePath>`, `id:folder:<folderId>`, `id:worktree:<repoId>::<worktreePath>`. `worktree set --parent-worktree` also takes the folder keys, `folder:<folderId>` or `id:folder:<folderId>`. On both, `path:` and `name:` record a folder workspace parent when they match one.",
"",
"Lineage rules:",
@@ -375,9 +376,9 @@ const ORCA_CLI_MARKDOWN = [
"- Use `--parent-worktree active` when the child worktree relationship should be explicit.",
"- Use `--parent-worktree folder:<folderId>` or `--parent-worktree worktree:<repoId>::<worktreePath>` when a folder or worktree parent context should be explicit.",
"- Use `--no-parent` only when the new work is independent.",
"- A parent can be in a different project from its child, such as `worktree create --repo id:<otherRepoId> --name related-task --parent-worktree id:<parentRepoId>::<parentPath>`. A worktree parent and child must use the same execution host (local machine, SSH target, or paired server).",
"- `--parent-worktree` is looked up in the child's environment. For a parent in another environment, add `--parent-environment <local|environment-id>`: to reuse a workspace from `ps`/`show` as a parent, pass its `address.environment` as `--parent-environment` and its `address.worktree` as `--parent-worktree`. Orca never searches other environments; a parent missing there is an error. `active`/`current` always mean this machine's own workspace, so they take only `--parent-environment local`.",
"- An address with `--environment local` means the Orca that printed it, because `local` is always the machine running the command; don't hand an address to another machine to run. To link workspaces across environments, run the command from the Orca that has both paired, such as `--environment <server> --worktree <selector> --parent-worktree current`.",
"- A parent can be in a different project from its child, such as `worktree create --repo id:<otherRepoId> --name related-task --parent-worktree id:<parentRepoId>::<parentPath>`. A parent can also be on another server: name it with `--parent-server`. The child's server must support parents on other servers; an older one refuses before changing anything.",
"- `--parent-worktree` is looked up on the child's server. For a parent on another server, add `--parent-server <local|server-id>`: to reuse a workspace from `ps`/`show` as a parent, pass its `address.server` as `--parent-server` and its `address.worktree` as `--parent-worktree`. Orca never searches other servers; a parent missing there is an error. `active`/`current` always mean a workspace on this computer, so they take only `--parent-server local`.",
"- An address with `--server local` means the Orca that printed it, because `local` is always the computer running the command; don't hand an address to another computer to run. To link workspaces across servers, run the command from the Orca that has both saved, such as `--server <server> --worktree <selector> --parent-worktree current`.",
"- To move an existing worktree under a different parent, or make it top-level, use `worktree set` with `--parent-worktree <selector>` or `--no-parent`.",
"- `--no-parent` only controls Orca lineage; it does not choose the Git base. For independent top-level work, omit `--base-branch` so Orca uses the repo default base, or explicitly pass the repo default base. Never base it on the current feature branch unless the user asks for stacked work or \"branch from current\".",
"",
@@ -476,13 +477,13 @@ const ORCA_CLI_MARKDOWN = [
"",
"- `--terminal` is optional for most commands; omitted means the active terminal in the current worktree.",
"- Use `terminal close --terminal <handle>` to close one terminal. Use `terminal close --worktree <selector> --all` to stop every terminal process in exactly that workspace and durably remove its terminal tabs, layouts, and agent-resume records.",
"- A bulk close fails when the execution host cannot confirm every PTY stopped. Treat that as `unverifiable`; do not report the processes as exited or retry against another host.",
"- A bulk close fails when the server cannot confirm every PTY stopped. Treat that as `unverifiable`; do not report the processes as exited or retry against another server.",
"- Use workspace Sleep, not close, when the terminals and agent sessions should resume later. `terminal stop` is legacy compatibility plumbing and should not be used in new agent workflows.",
"- `terminal list --json` omits `visualLayouts` to keep the common agent payload bounded. Add `--include-visual-layouts` only when tab and pane topology is required.",
"- A chat tab has no terminal handle, so `terminal rename` cannot rename it. Use `ORCA chat rename --session <sessionId> --name \"New Name\" --json` with the `sessionId` `agent launch` printed; inside a chat, omit `--session` to rename that chat.",
"- `terminal create --title` and `terminal rename` set the tab title, which `terminal list` reports under `visualLayouts`. `terminal set-pane-title` sets one pane's title, reported as `terminals[].paneTitle`. `terminals[].title` may be the tab title or the running program's own title, which agents repaint constantly, so never match on it to re-find a terminal.",
"- `terminals[].agentIdentity`, when present, is only the agent type (e.g. `codex`), not a session identity, so two Codex panes share it. To find a specific agent's terminal, join `worktree ps --json` `agents[].paneKey` (`<tabId>:<leafId>`) to the `tabId` and `leafId` of a `terminal list` row to get its handle.",
"- A paired server has no window. `terminal switch --environment <name>` moves the desktop app on this machine to that server's terminal, and reports `navigated: false` when no desktop here shows that server.",
"- A server reached with `--server` has no window. `terminal switch --server <id>` moves the desktop app on this computer to that server's terminal, and reports `navigated: false` when no desktop here shows that server.",
"- Use `terminal read` before `terminal send` unless the next input is obvious.",
"- `terminal read` returns accumulated output with escape sequences stripped, not the rendered screen, so anything that repaints (shells, progress bars, TUIs) reads as stacked fragments. Use `--screen` whenever the answer depends on what the terminal actually shows.",
"- `--screen` and `--cursor` are mutually exclusive: a screen read is the current frame and has no history to page.",
@@ -553,7 +554,7 @@ const ORCA_CLI_MARKDOWN = [
"",
"## Agent Session Search",
"",
"`ORCA search` runs a full-text search over the agent sessions indexed on one Orca host: this machine, or the paired server named by `--environment` or `--pairing-code`. There is no all-computers search.",
"`ORCA search` runs a full-text search over the agent sessions indexed on one Orca server: the Orca on this computer, or the server named by `--server` or `--pairing-code`. There is no all-servers search.",
"",
"Common commands:",
"",
@@ -563,7 +564,7 @@ const ORCA_CLI_MARKDOWN = [
"ORCA search \"blank restore\" --agent codex --since 2026-09-01T00:00:00Z --json",
"ORCA search \"blank restore\" --path /abs/worktree --sort newest --limit 50 --json",
"ORCA search \"blank restore\" --cursor <cursor> --json",
"ORCA search \"blank restore\" --environment <environmentId> --json",
"ORCA search \"blank restore\" --server <serverId> --json",
"ORCA search \"blank restore\" --fresh --debug --json",
"ORCA search --index-status --json",
"```",
@@ -818,7 +819,7 @@ const ORCA_CLI_PLUGINS_REFERENCE_MARKDOWN = [
" (see `docs/reference/plugin-declarative-ui.md`, \"Testing\"). Both run the plugin's code",
" unsandboxed on this machine: use them only on code you trust.",
"4. `plugin dev load <dir>` adds the folder to Settings → Plugins → Development folders on the",
" Orca host and loads it. Orca reloads it, and restarts its worker, when its files change; run",
" Orca server and loads it. Orca reloads it, and restarts its worker, when its files change; run",
" `plugin dev reload <dir>` if a change was missed. `plugin restart <plugin-key>` stops a",
" worker so its next command or event reruns its startup code. `plugin logs` shows what a worker printed and a panel's or editor's",
" console errors, warnings and uncaught exceptions as `[frame] <file>:<line> <message>`.",
@@ -858,13 +859,13 @@ const ORCA_CLI_PLUGINS_REFERENCE_MARKDOWN = [
" Both need the desktop app with a workspace showing and never raise the window.",
"6. `plugin dev unload <dir>` when done.",
"",
"Paths are on the machine that runs Orca. With `--environment <server>`, pass an absolute path",
"Paths are on the machine that runs Orca. With `--server <server>`, pass an absolute path",
"on that server. From an SSH or WSL shell that forwards `orca` to another machine, the authoring",
"and dev commands refuse; work on the Orca host instead.",
"and dev commands refuse; work on the Orca server instead.",
"",
"`plugin_system_disabled` means plugins are off on that host. Ask the user to click \"Turn on",
"plugins\" in Settings → Plugins, or on a host with no window (`orca serve`) to run",
"`plugin system on` with the same `--environment`. It approves nothing; only plugins approved",
"`plugin system on` with the same `--server`. It approves nothing; only plugins approved",
"earlier start.",
"",
"## Install, update and remove",
@@ -876,7 +877,7 @@ const ORCA_CLI_PLUGINS_REFERENCE_MARKDOWN = [
"- `owner/repo` or `owner/repo@v1.2.0` on GitHub,",
"- any `https://` or `ssh://` Git URL or `git@host:owner/repo.git`, with `#ref` for a version,",
"- a GitHub or GitLab release, tag or tree page URL (`.../releases/tag/v1.2.0`, `.../-/tree/main`),",
"- a plugin folder (a path on the Orca host).",
"- a plugin folder (a path on the Orca server).",
"",
"With no version, Orca installs the newest version tag (`vX.Y.Z`), else the default branch, and",
"always pins the exact commit. The result names the version, commit, publisher and repository.",
@@ -903,7 +904,7 @@ const ORCA_CLI_PLUGINS_REFERENCE_MARKDOWN = [
"",
"## Private repositories",
"",
"Git runs on the Orca host (the `--environment` server when given) with that machine's own Git",
"Git runs on the Orca server (the `--server` one when given) with that machine's own Git",
"credentials and never prompts. Nothing to pass to `orca`; set up Git there once:",
"",
"- HTTPS on GitHub: `gh auth login` then `gh auth setup-git`. GitLab: `glab auth login`. Elsewhere:",
@@ -1224,7 +1225,7 @@ const ORCA_EMULATOR_MARKDOWN = [
"device with `emulator_unsupported`. `tap`, `type`, `gesture`, `button`, `rotate`, `ax`, and",
"`exec` work on both backends.",
"",
"Commands drive devices on the host that runs the Orca runtime. Simulators need that host to",
"Commands drive devices on the computer that runs the Orca server. Simulators need that computer to",
"be a Mac, so a Linux `orca serve` or SSH host can drive only Android devices.",
"",
"## Prerequisites",
@@ -1345,7 +1346,7 @@ const ORCA_EMULATOR_ANDROID_MARKDOWN = [
"tree on Android, a serve-sim node tree on iOS.",
"",
"Camera and sensor injection are not wrapped; Android virtual-scene is out of scope. Commands",
"drive the SDK and devices on the host that runs the Orca runtime, including a headless",
"drive the SDK and devices on the computer that runs the Orca server, including a headless",
"`orca serve` or SSH host.",
"",
"## Prerequisites",
@@ -1580,7 +1581,7 @@ const ORCA_JIRA_MARKDOWN = [
"",
"## Connections and verified reads",
"",
"Configure credentials in Orca Settings. `ORCA jira connection --json` lists saved site IDs; it does not test access or agent MCP authentication. These commands use credentials on the selected execution host, including SSH hosts. Update that host if the CLI reports `incompatible_runtime`.",
"Configure credentials in Orca Settings. `ORCA jira connection --json` lists saved site IDs; it does not test access or agent MCP authentication. These commands use credentials on the selected server, including servers on SSH hosts. Update that host if the CLI reports `incompatible_runtime`.",
"",
"A successful empty list means the Jira read completed; API, permission and network errors remain errors. Jira keys are case-insensitive; full browse URLs are accepted wherever an issue key is required. Use `--body-file <path>` for multiline descriptions and comments, or `--body-file -` for stdin.",
"",
@@ -1683,7 +1684,7 @@ const ORCA_LINEAR_MARKDOWN = [
"",
"- Omitting `--limit` returns every match and reports `result.meta.limit` as `null`, so filter before listing a large workspace. `--limit <n>` caps the read.",
"- When a cap held results back, `--json` sets `result.truncated` and `result.meta.hasMore`; human output prints `truncated: showing N`. Check `truncated` before reporting a count, then page with `--cursor` until it is false.",
"- A `--cursor` is bound to the workspace and the Orca runtime that issued it. `--workspace all` cannot page, and a raw Linear cursor still needs a concrete `--workspace`.",
"- A `--cursor` is bound to the workspace and the Orca server that issued it. `--workspace all` cannot page, and a raw Linear cursor still needs a concrete `--workspace`.",
"- `--priority` is `0=none`, `1=urgent`, `2=high`, `3=medium`, `4=low`. Issue JSON carries `priorityLabel` in the CLI setter vocabulary; project JSON keeps Linear's title-case label.",
"- `ORCA linear search`, `ORCA linear list`, and `ORCA linear project list` cap at their own `--limit` and set `result.truncated` the same way.",
"",
@@ -2685,7 +2686,7 @@ const ORCA_PLUGIN_AUTHORING_MARKDOWN = [
"",
"- **Your files:** a new folder, ideally its own Git repository, with `orca-plugin.json` at its",
" root, made by `ORCA plugin create` (never overwrites). Paths are on the machine that runs Orca;",
" with `--environment` pass an absolute path on that server.",
" with `--server` pass an absolute path on that server.",
"- **Types:** `ORCA plugin types <dir>` (also run by `dev watch`) writes `.orca/types/` for every",
" surface; the plugin's `tsconfig.json` extends `./.orca/types/tsconfig.json`. Never edit `.orca/`.",
"- **Ground truth:** the references below match this Orca. Read them instead of guessing.",
@@ -2816,12 +2817,12 @@ const ORCA_PLUGIN_AUTHORING_CLI_REFERENCE_MARKDOWN = [
"- `ORCA plugin validate <dir|orca-plugin.json|orca-catalog.json> [--json]`: Check a plugin folder, manifest or catalog the way Orca will load it",
"- `ORCA plugin inspect <dir> [--json]`: Show what a plugin folder contributes, the access it asks for, and its content hash",
"- `ORCA plugin release-entry <dir> [--json]`: Print the catalog release entry for a plugin folder's committed HEAD",
"- `ORCA plugin list [--json]`: List plugins on the Orca host with their status and access level",
"- `ORCA plugin list [--json]`: List plugins on the Orca server with their status and access level",
"- `ORCA plugin logs <plugin-key> [--json]`: Print the recent log lines of a plugin",
"- `ORCA plugin enable <plugin-key> [--approve <fingerprint>] [--json]`: Enable a plugin; code and capabilities need --approve",
"- `ORCA plugin disable <plugin-key> [--json]`: Disable a plugin",
"- `ORCA plugin system on [--json]`: Turn plugins on for the Orca host",
"- `ORCA plugin system off [--json]`: Turn plugins off for the Orca host",
"- `ORCA plugin system on [--json]`: Turn plugins on for the Orca server",
"- `ORCA plugin system off [--json]`: Turn plugins off for the Orca server",
"- `ORCA plugin restart <plugin-key> [--json]`: Stop a plugin's worker so its next command or event starts it fresh",
"- `ORCA plugin dev watch <dir> [--check] [--shot <out-dir> [--shot-panel <id>]] [--approve <fingerprint>] [--json]`: Load a plugin folder, then stream its logs and reloads until Ctrl-C",
"- `ORCA plugin dev load <dir> [--approve <fingerprint>] [--json]`: Load a plugin folder into Orca as a development plugin",
@@ -3728,7 +3729,7 @@ const ORCA_PLUGIN_AUTHORING_WORKFLOW_REFERENCE_MARKDOWN = [
" a dev plugin, run inside its folder. The result adds `replay: true` and `scenario`, and",
" `errors` has what the render reported; an unknown name fails and lists the scenarios. Limits:",
" a still frame (host-owned control values start from the tree's props), images show their",
" placeholder, no `--act`, local only (no `--environment`), and Orca's window must be hidden",
" placeholder, no `--act`, local only (no `--server`), and Orca's window must be hidden",
" or minimized. Default file `.orca/shots/<plugin-key>-<panel>.<scenario>.png`.",
"- `ORCA plugin open <plugin-key> [--panel <id> | --editor <file>]` shows the panel in the right",
" sidebar, or a file in the plugin's custom editor. Neither raises the window. `--editor` opens the",
@@ -3973,7 +3974,7 @@ const ORCHESTRATION_MARKDOWN = [
" in any state: a working worker gets it when its current turn ends; a finished",
" or closed one gets it as a follow-up Task and reports with `worker_done`. The",
" receipt says which.",
" Except on a paired server: a finished worker there refuses `send`, so start",
" Except on another server: a finished worker there refuses `send`, so start",
" new work there with `worker-start --on <server>` (load",
" `references/placement-and-remote.md` first).",
"",
@@ -4116,10 +4117,10 @@ const ORCHESTRATION_PLACEMENT_AND_REMOTE_REFERENCE_MARKDOWN = [
"ORCA orchestration worker-start --task <task_id> --worktree new-child --agent codex --setup run",
"",
"# On a connected server; the Run stays on yours.",
"ORCA orchestration worker-start --task <task_id> --on <environment> --worktree new-top-level --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run",
"ORCA orchestration worker-start --task <task_id> --on <server> --worktree new-top-level --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run",
"",
"# On a connected server, nested under your workspace in the sidebar.",
"ORCA orchestration worker-start --task <task_id> --on <environment> --worktree new-child --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run",
"ORCA orchestration worker-start --task <task_id> --on <server> --worktree new-child --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run",
"```",
"",
"With `--on`, both `new-child` and `new-top-level` need `--repo` naming a",
+1 -1
View File
@@ -178,7 +178,7 @@ export function selectEnclosingWorktreeSelectionOnHost(
'Inspect a chosen workspace with `orca worktree show --worktree <selector> --json`.',
purpose === 'current'
? 'Use the intended action’s target flag to select that workspace; current has no replacement target flag.'
: `Pass ${flag} <selector> on your original invocation${purpose === 'ports' ? '; native folders require --all for a host-wide scan' : ''}.`,
: `Pass ${flag} <selector> on your original invocation${purpose === 'ports' ? '; native folders require --all for a server-wide scan' : ''}.`,
'Pass the exact selector as one argument quoted for your shell.'
]
}
+2 -2
View File
@@ -16,7 +16,7 @@ export type CliErrorContext = {
worktreeSelector?: string
/** The runtime error omits the original --repo selector. */
repoSelector?: string
/** True when --environment, --pairing-code, --host runtime:, or their env vars chose a server. */
/** True when --server, --pairing-code, --host runtime:, or their env vars chose a server. */
remoteServerSelected?: boolean
/** Concise orchestration failures: compact JSON plus one `error: <code>: <message>` stderr line. */
conciseOrchestration?: boolean
@@ -25,7 +25,7 @@ export type CliErrorContext = {
type ContextRecovery = { nextSteps: readonly string[] } & Record<string, unknown>
const STALE_HANDLE_SERVER_HINT =
'Terminal handles belong to the Orca server that issued them. If this handle came from a paired server (for example `orca terminal list --environment <server>`), pass the same --environment <server> to this command.'
'Terminal handles belong to the Orca server that issued them. If this handle came from another server (for example `orca terminal list --server <server>`), pass the same --server <server> to this command.'
function contextRecovery(error: unknown, context: CliErrorContext): ContextRecovery | undefined {
const code = cliErrorCode(error)
+8 -8
View File
@@ -46,16 +46,16 @@ const COMMAND_SCOPED_FLAG_HELP: Record<string, Record<string, string>> = {
id: '--id <id> Plugin id (default: the folder name)',
name: '--name <display name> Plugin name shown in Orca'
},
'environment update': {
'server update': {
force: '--force Restart over running terminals instead of deferring the update'
},
'environment recover': {
'server recover': {
'accept-changed-state':
'--accept-changed-state Restore the prelaunch snapshot over state a rejected build changed',
yes: '--yes Confirm discarding what the rejected build changed'
},
'environment stop': {
yes: '--yes Confirm stopping the server and unlinking it from this machine'
'server stop': {
yes: '--yes Confirm stopping the server and unlinking it from this computer'
},
'file open': {
line: '--line <n> Cursor line (1-based)',
@@ -82,18 +82,18 @@ const COMMAND_SCOPED_FLAG_HELP: Record<string, Record<string, string>> = {
search: {
query: '--query <text> Search text; also accepted as the positional argument',
scope: '--scope <corpus> conversation (user and assistant turns) or all (default)',
fresh: '--fresh Wait up to 5s for the host to reconcile its index first',
fresh: '--fresh Wait up to 5s for the server to reconcile its index first',
limit: '--limit <n> Hits per page (default 20, maximum 100)',
cursor: '--cursor <cursor> Opaque cursor printed by the previous page of this search',
agent: '--agent <id> Restrict to one agent; repeat for several',
path: '--path <path> Restrict to an execution-host path; repeat for several',
path: '--path <path> Restrict to a path on the server; repeat for several',
since: '--since <iso> Only sessions updated at or after this ISO 8601 timestamp',
sort: '--sort <order> relevance (default) or newest',
debug: '--debug Include the planner route the host used',
debug: '--debug Include the planner route the server used',
'index-status': '--index-status Report the index instead of searching'
},
ports: {
all: '--all List every listener on the workspace host, not just this workspace'
all: '--all List every listener on the workspace server, not just this workspace'
},
snapshot: {
interactive:
+6 -1
View File
@@ -1,6 +1,8 @@
export type CommandSpec = {
path: string[]
aliases?: string[][]
/** Old spellings: accepted as input, canonicalized to `path`, and never shown. */
legacyAliases?: string[][]
argumentMode?: 'parsed' | 'passthrough'
// Prevent typo recovery from suggesting destructive actions for unrelated commands.
destructive?: boolean
@@ -22,6 +24,9 @@ export type CommandSpec = {
export type IdentityFlag = 'from' | 'terminal'
/** Still parsed for old scripts, but never offered in help or typo recovery. */
export const INPUT_ONLY_FLAGS: ReadonlySet<string> = new Set(['host'])
export function specPaths(spec: CommandSpec): string[][] {
return spec.aliases ? [spec.path, ...spec.aliases] : [spec.path]
return [spec.path, ...(spec.aliases ?? []), ...(spec.legacyAliases ?? [])]
}
@@ -22,7 +22,7 @@ const blocked = [
['orchestration worker-reuse', 'orchestration worker-release'],
['tab clues', 'tab close'],
['linear relation move', 'linear relation remove'],
['environment rollbook', 'environment rollback']
['environment rollbook', 'server rollback']
]
const recovery = [
@@ -34,8 +34,8 @@ const recovery = [
['orchestration worker-releasee', 'orchestration worker-release'],
['tab clos', 'tab close'],
['tab clone', 'tab close'],
['environment rollbac', 'environment rollback'],
['environment remov', 'environment rm'],
['environment rollbac', 'server rollback'],
['environment remov', 'server rm'],
['artifacts delet', 'artifacts delete'],
['worktree remov', 'worktree remove'],
['worktree delet', 'worktree delete'],
@@ -62,16 +62,16 @@ describe('live destructive command recovery', () => {
expect(data.nextSteps.join(' ')).toContain(`orca ${expected}`)
})
it('retains the complete legitimate environment removal ranking', () => {
it('suggests only canonical server commands for a typo in the old spelling', () => {
expect(suggestCommands(COMMAND_SPECS, ['environment', 'remov'])).toEqual([
'environment recover',
'environment rm'
'server recover',
'server rm'
])
})
it('keeps every declared alias accepted and normalized to its canonical command', () => {
for (const spec of COMMAND_SPECS) {
for (const path of [spec.path, ...(spec.aliases ?? [])]) {
for (const path of [spec.path, ...(spec.aliases ?? []), ...(spec.legacyAliases ?? [])]) {
expect(findCommandSpec(COMMAND_SPECS, path)).toBe(spec)
const parsed = normalizeCommandPositionals(COMMAND_SPECS, parseArgs(path))
expect(parsed.commandPath).toEqual(spec.path)
+21 -8
View File
@@ -69,24 +69,37 @@ export function suggestCommands(specs: CommandSpec[], commandPath: string[]): st
) {
continue
}
const candidates = specPaths(spec).map((path) =>
commandPath.length === 1 ? path.slice(0, 1) : path
)
for (const candidate of candidates) {
const canonical = (commandPath.length === 1 ? spec.path.slice(0, 1) : spec.path).join(' ')
const legacy = new Set((spec.legacyAliases ?? []).map((path) => path.join(' ')))
for (const path of specPaths(spec)) {
const candidate = commandPath.length === 1 ? path.slice(0, 1) : path
if (candidate.length !== commandPath.length) {
continue
}
const joined = candidate.join(' ')
// Legacy spellings are input only: match on them, but suggest the canonical path.
const label = legacy.has(path.join(' ')) ? canonical : joined
if (seen.has(joined)) {
continue
}
seen.add(joined)
if (Math.abs(input.length - joined.length) <= SUGGESTION_THRESHOLD) {
scored.push({ label: joined, distance: levenshtein(input, joined) })
scored.push({ label, distance: levenshtein(input, joined) })
}
}
}
return rankByDistance(scored)
return rankByDistance(bestPerLabel(scored))
}
// A legacy alias and its canonical path can share a label; keep the closer match.
function bestPerLabel(
scored: { label: string; distance: number }[]
): { label: string; distance: number }[] {
const best = new Map<string, number>()
for (const { label, distance } of scored) {
best.set(label, Math.min(distance, best.get(label) ?? distance))
}
return [...best].map(([label, distance]) => ({ label, distance }))
}
// A positional terminal handle lands in the command path; point at the flag form instead.
@@ -101,7 +114,7 @@ function terminalFlagSuggestion(specs: CommandSpec[], commandPath: string[]): st
!candidate.hidden && specPaths(candidate).some((path) => path.join(' ') === parent)
)
return spec?.allowedFlags.includes('terminal') && spec.identityFlagRoles?.terminal !== 'caller'
? [`${parent} --terminal <handle>`]
? [`${spec.path.join(' ')} --terminal <handle>`]
: []
}
@@ -123,7 +136,7 @@ export type FlagErrorData = {
}
// Recover renamed flags only when the typed flag is rejected and its synonym is accepted.
const FLAG_SYNONYMS: Readonly<Record<string, string>> = { from: 'terminal' }
const FLAG_SYNONYMS: Readonly<Record<string, string>> = { from: 'terminal', host: 'server' }
function suggestFlags(flag: string, validFlags: string[]): string[] {
const synonym = FLAG_SYNONYMS[flag]
-1
View File
@@ -166,7 +166,6 @@ describe('a folder workspace whose host is unknown', () => {
expect(() => select(rows, '/tmp/hub/notes')).toThrow(
expect.objectContaining({
code: 'selector_ambiguous',
message: expect.stringContaining("can't tell which host owns the folder workspace"),
data: expect.objectContaining({
nextSteps: expect.arrayContaining([
'Pass --worktree folder:hub to target the folder workspace itself.'
+36 -40
View File
@@ -15,6 +15,7 @@ import {
LOCAL_HOST_LIST_NAME,
normalizeTypedName,
resolveSshHostTargetId,
sshConnectionStep,
stripWrappingQuotes,
type EnvironmentSummary,
type SshTargetSummary
@@ -59,13 +60,13 @@ export function parseHostFlag(flags: Map<string, string | boolean>): HostFlagSel
if (!alias || alias.startsWith('ssh:') || alias.startsWith('runtime:')) {
throw new RuntimeClientError(
'invalid_argument',
`Invalid --host value: ${raw}. Expected local, ssh:<target-id>, runtime:<environment-id>, or a host name from \`orca host list\`.`
`Invalid --host value: ${raw}. To run on another server, use --server <id>; \`orca server list\` prints each id.`
)
}
return { kind: 'alias', alias }
}
// Pairing IDs are local to this machine; route to the paired host before applying its filters.
// Pairing IDs are local to this computer; route to the saved server before applying its filters.
export async function resolveHostFlagEnvironmentId(
flags: Map<string, string | boolean>,
selection: HostFlagRoutingSelection
@@ -91,25 +92,25 @@ export async function resolveHostFlagEnvironmentId(
if (host.kind === 'alias' && (selection.environmentSelector || selection.pairingCode)) {
return null
}
// Accept environment names but canonicalize them to IDs for stored-host comparisons.
// Accept server names but canonicalize them to IDs for stored-host comparisons.
const environment = findEnvironmentByName(environments, wanted)
if (!environment) {
assertEnvironmentNameUnambiguous(environments, wanted, flagSpelling)
// A missing server alias may still name the local machine or one of its SSH targets.
// A missing server alias may still name this computer or one of its SSH targets.
if (host.kind === 'alias') {
return null
}
const sshTargets = await selection.listSshTargets()
throw new RuntimeClientError(
'invalid_argument',
`Unknown Orca server in ${flagSpelling}: no paired Orca server is named or has id ${wanted}.`,
`Unknown server in ${flagSpelling}: no saved server has that id or name.`,
{
knownEnvironments: environments,
knownServers: environments,
knownSshTargets: sshTargets,
nextSteps: [
...crossKindNextSteps(wanted, { environments, sshTargets }, 'environment'),
'Run `orca environment list` to see paired Orca servers.',
'Use --host local to target this machine.'
...crossKindNextSteps(wanted, { environments, sshTargets }, 'server'),
'Run `orca server list` to see saved servers.',
'Use --server local for the Orca on this computer.'
]
}
)
@@ -118,12 +119,12 @@ export async function resolveHostFlagEnvironmentId(
if (isLocalHostListName(host.alias)) {
throw new RuntimeClientError(
'invalid_argument',
`Ambiguous --host ${host.alias}: it names both this machine and a paired Orca server.`,
`Ambiguous --host ${host.alias}: it names both this computer and a saved server.`,
{
knownEnvironments: [environment],
knownServers: [environment],
nextSteps: [
'Use --host local for this machine.',
`Use --host runtime:${environment.id} for the paired Orca server named ${environment.name}.`
'Use --server local for the Orca on this computer.',
`Use --server ${environment.id} for the saved server named ${environment.name}.`
]
}
)
@@ -133,7 +134,7 @@ export async function resolveHostFlagEnvironmentId(
if (selection.pairingCode) {
throw new RuntimeClientError(
'invalid_argument',
`${flagSpelling} already selects a paired Orca server; use either --host runtime:<id> or --pairing-code, not both.`
`${flagSpelling} already selects a saved server; use either --server <id> or --pairing-code, not both.`
)
}
if (selection.environmentSelector) {
@@ -144,14 +145,14 @@ export async function resolveHostFlagEnvironmentId(
if (selected?.id !== environment.id) {
throw new RuntimeClientError(
'invalid_argument',
`${flagSpelling} and ${selection.environmentSelector.label} ${selection.environmentSelector.value} name different Orca servers.`
`${flagSpelling} and ${selection.environmentSelector.label} ${selection.environmentSelector.value} name different servers; pass only --server.`
)
}
}
return environment.id
}
// An alias naming both a paired server and an SSH target must not choose either silently.
// An alias naming both a saved server and an SSH target must not choose either silently.
async function assertAliasNamesOneHost(
alias: string,
environment: EnvironmentSummary,
@@ -163,11 +164,11 @@ async function assertAliasNamesOneHost(
} catch {
throw new RuntimeClientError(
'invalid_argument',
`Cannot verify --host ${alias}: it names a paired Orca server, but this machine's SSH targets could not be read to rule out one with the same name.`,
`Cannot verify --host ${alias}: it names a saved server, but this computer's SSH connections could not be read to rule out one with the same name.`,
{
knownEnvironments: [environment],
knownServers: [environment],
nextSteps: [
`Use --host runtime:${environment.id} for the paired Orca server named ${environment.name}.`
`Use --server ${environment.id} for the saved server named ${environment.name}.`
]
}
)
@@ -182,15 +183,13 @@ async function assertAliasNamesOneHost(
conflicts.length === 1 ? 'an SSH target' : `${conflicts.length} SSH targets sharing that label`
throw new RuntimeClientError(
'invalid_argument',
`Ambiguous --host ${alias}: it names both a paired Orca server and ${sshCount} on this machine.`,
`Ambiguous --host ${alias}: it names both a saved server and ${sshCount} on this computer.`,
{
knownEnvironments: [environment],
knownServers: [environment],
knownSshTargets: conflicts,
nextSteps: [
`Use --host runtime:${environment.id} for the paired Orca server named ${environment.name}.`,
...conflicts.map(
(target) => `Use --host ssh:${target.id} for the SSH target labeled ${target.label}.`
)
`Use --server ${environment.id} for the saved server named ${environment.name}.`,
sshConnectionStep(alias)
]
}
)
@@ -208,7 +207,7 @@ export function hostFilterMatchesHostId(
return filter.kind === 'runtime' && candidate === LOCAL_EXECUTION_HOST_ID
}
// Validate SSH IDs against the connected runtime, not this machine's pairing store.
// Validate SSH IDs against the connected server, not this computer's pairing store.
export async function resolveHostFlagTarget(
flags: Map<string, string | boolean>,
client: RuntimeClient
@@ -255,20 +254,17 @@ async function resolveLocalHostListName(
if (clashing.length > 0) {
throw new RuntimeClientError(
'invalid_argument',
`Ambiguous --host ${alias}: it names both this machine and an SSH target.`,
`Ambiguous --host ${alias}: it names both this computer and an SSH connection.`,
{
knownSshTargets: clashing,
nextSteps: [
'Use --host local for this machine.',
...clashing.map((target) => `Use --host ssh:${target.id} for ${target.label}.`)
]
nextSteps: ['Use --server local for the Orca on this computer.', sshConnectionStep(alias)]
}
)
}
return { kind: 'local', id: LOCAL_EXECUTION_HOST_ID }
}
// Preserve the store's refusal to guess between duplicate environment names.
// Preserve the store's refusal to guess between duplicate server names.
function assertEnvironmentNameUnambiguous(
environments: readonly { id: string; name: string }[],
name: string,
@@ -280,11 +276,11 @@ function assertEnvironmentNameUnambiguous(
}
throw new RuntimeClientError(
'invalid_argument',
`Ambiguous Orca server in ${flag}: ${ambiguous.length} paired servers are named ${name}. Use the environment id.`,
`Ambiguous server in ${flag}: ${ambiguous.length} saved servers are named ${name}. Use the server id.`,
{
knownEnvironments: ambiguous,
knownServers: ambiguous,
nextSteps: ambiguous.map(
(candidate) => `Use --host runtime:${candidate.id} for the server named ${candidate.name}.`
(candidate) => `Use --server ${candidate.id} for the server named ${candidate.name}.`
)
}
)
@@ -308,17 +304,17 @@ export async function resolveEnvironmentSelectorForStore(
if (found) {
return found.id === selector || found.name === selector ? selector : found.id
}
assertEnvironmentNameUnambiguous(environments, selector, `--environment ${selector}`)
assertEnvironmentNameUnambiguous(environments, selector, `--server ${selector}`)
const sshTargets = await listSshTargetsForSuggestion()
throw new RuntimeClientError(
'invalid_argument',
`Unknown Orca server in --environment ${selector}: no paired Orca server is named or has id ${selector}.`,
`Unknown server in --server ${selector}: no saved server has that id or name.`,
{
knownEnvironments: environments,
knownServers: environments,
knownSshTargets: sshTargets,
nextSteps: [
...crossKindNextSteps(selector, { environments, sshTargets }, 'environment'),
'Run `orca host list` to see every machine you can target and the flag for each.'
...crossKindNextSteps(selector, { environments, sshTargets }, 'server'),
'Run `orca server list` to see saved servers, or use --server local for the Orca on this computer.'
]
}
)
+5 -5
View File
@@ -13,10 +13,10 @@ export const FLAG_HELP_TEXT: Record<string, string> = {
direction:
'--direction <dir> Direction: up|down|left|right for scroll, horizontal|vertical for split',
'display-name': '--display-name <name> Override the Orca display name',
environment:
"--environment <selector> Run against a saved paired Orca server (id or name), or `local` for this machine's own Orca over ORCA_ENVIRONMENT/ORCA_PAIRING_CODE; terminal handles belong to the server that issued them",
server:
"--server <server> The Orca server to run on: `local` for the Orca on this computer, or a saved server's id or name (`orca server list`). Terminal handles belong to the server that issued them",
'pairing-code':
'--pairing-code <code> Run against a remote Orca server using an orca://pair?... code',
'--pairing-code <code> Connect once to an Orca server with an orca://pair?... code',
'element-index': '--element-index <n> Element index from get-app-state',
title: '--title <text> Custom title for the terminal tab (omit to reset)',
enter: '--enter Append Enter after sending text',
@@ -61,8 +61,8 @@ export const FLAG_HELP_TEXT: Record<string, string> = {
pages: '--pages <n> Number of scroll pages',
'parent-worktree':
'--parent-worktree <selector> Parent worktree selector such as identity:<identity>, id:<repo-id>::<path>, folder:<id>, name:<displayName>, branch:<branch>, issue:<number>, path:<path>, or active/current',
'parent-environment':
"--parent-environment <environment> Environment holding --parent-worktree: local, or a saved environment id or name (default: the worktree's own)",
'parent-server':
"--parent-server <server> The server holding --parent-worktree: `local` or a saved server's id or name (default: the worktree's own server)",
path: '--path <path> Path argument for the command',
pr: '--pr <number|null> Linked GitHub pull request number; null clears on set',
prompt: '--prompt <text> Prompt text for agent-backed commands',
+17 -12
View File
@@ -45,8 +45,8 @@ export {
} from './automation-format'
export type { AutomationListPayload, AutomationShowPayload } from './automation-format'
export {
formatEnvironment,
formatEnvironmentList,
formatSavedServer,
formatSavedServerList,
formatMemorySnapshot,
formatRepoList,
formatRepoRefs,
@@ -69,7 +69,7 @@ export function printResult<TResult>(
}
export type HostListEntry = {
kind: 'local' | 'ssh' | 'environment'
kind: 'local' | 'ssh' | 'server'
name: string
id: string
selector: string
@@ -84,7 +84,7 @@ export function formatHostList(result: { hosts: HostListEntry[] }): string {
const kindLabel: Record<HostListEntry['kind'], string> = {
local: 'local',
ssh: 'ssh target',
environment: 'orca server'
server: 'orca server'
}
return result.hosts
.map(
@@ -94,7 +94,7 @@ export function formatHostList(result: { hosts: HostListEntry[] }): string {
.join('\n')
}
/** What one runtime calls itself; `machineName` is absent when the runtime predates the field. */
/** What one server calls itself; `machineName` is absent when the server predates the field. */
export type HostNameResult = {
machineName?: string
platform?: string
@@ -118,22 +118,27 @@ function formatHostConnection(host: HostListEntry): string {
export function formatCliStatus(status: CliStatusResult): string {
return [
...(status.target && status.target.kind === 'environment'
? [`target: environment ${status.target.environment}`]
: []),
...(status.target ? [`server: ${formatStatusTarget(status.target)}`] : []),
`appRunning: ${status.app.running}`,
`pid: ${status.app.pid ?? 'none'}`,
`desktopWindowStatus: ${status.app.desktopWindowStatus ?? 'unknown'}`,
`runtimeState: ${status.runtime.state}`,
`runtimeReachable: ${status.runtime.reachable}`,
`runtimeConnectionState: ${status.runtime.connectionState ?? 'unknown'}`,
`runtimeId: ${status.runtime.runtimeId ?? 'none'}`,
`state: ${status.runtime.state}`,
`reachable: ${status.runtime.reachable}`,
`connection: ${status.runtime.connectionState ?? 'unknown'}`,
`instance: ${status.runtime.runtimeId ?? 'none'}`,
`graphState: ${status.graph.state}`,
...(status.runtime.degradations ?? []).map((degradation) => `degraded: ${degradation.message}`),
...(status.caller === undefined ? [] : [`orcaSessionId: ${formatStatusCaller(status.caller)}`])
].join('\n')
}
function formatStatusTarget(target: NonNullable<CliStatusResult['target']>): string {
if (target.kind === 'local') {
return 'local'
}
return target.server === 'pairing-code' ? 'one-off connection' : target.server
}
function formatStatusCaller(caller: CliStatusCaller): string {
if ('refusal' in caller) {
return `none (refused: ${caller.refusal.code})`
+1 -1
View File
@@ -161,7 +161,7 @@ function antigravityAccounts(ctx: HandlerContext): ProviderAccounts {
if (!(await supportsAntigravityAccounts(ctx))) {
throw new RuntimeClientError(
'incompatible_runtime',
'Update or restart this Orca host to manage Antigravity accounts.'
'Update or restart this Orca server to manage Antigravity accounts.'
)
}
return client.call<AntigravityAccountState>('accounts.antigravityList', target)
+1 -1
View File
@@ -234,7 +234,7 @@ async function assertAccountImportSupported(
if (!status.result.capabilities?.includes(capability)) {
throw new RuntimeClientError(
'incompatible_runtime',
'The running Orca runtime is too old to add accounts from the CLI. Update or restart Orca and try again.'
'The running Orca server is too old to add accounts from the CLI. Update or restart Orca and try again.'
)
}
}
+2 -2
View File
@@ -32,12 +32,12 @@ export const AGENT_LAUNCH_HANDLERS: Record<string, CommandHandler> = {
if (launch.operationId) {
throw new RuntimeClientError(
'agent_session_operation_unknown',
'This host cannot replay the earlier launch. Return to the original execution host; do not retry without --retry-launch.'
'This server cannot replay the earlier launch. Return to the server that started it; do not retry without --retry-launch.'
)
}
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host cannot start agents from the CLI. Update Orca on the execution host.'
'This Orca server cannot start agents from the CLI. Update Orca on that server.'
)
}
const result = await callAgentLaunch(
+1 -1
View File
@@ -11,7 +11,7 @@ import type { RuntimeClient } from '../runtime-client'
import { RuntimeClientError } from '../runtime-client'
const SETUP_CHOICE_HOST_UPDATE_REQUIRED =
"This host's Orca is too old for --setup on automations. Update Orca on that host, or run the command without --setup."
"This host's Orca is too old for --setup on automations. Update Orca on that server, or run the command without --setup."
// Older runtimes silently strip these fields and would run without the requested arguments or setup choice.
export async function assertAutomationFieldsSupported(
+6 -5
View File
@@ -1,3 +1,4 @@
import { describeClientServer } from '../row-owner-server'
import type {
Automation,
AutomationCreateInput,
@@ -159,13 +160,13 @@ function buildAutomationRunContextFromSetup(setup: ProjectHostSetup): WorkspaceR
export const AUTOMATION_HANDLERS: Record<string, CommandHandler> = {
'automations list': async ({ client, json }) => {
const result = await client.call<{ automations: Automation[] }>('automation.list')
printResult(result, json, formatAutomationList)
printResult(result, json, (value) => formatAutomationList(value, describeClientServer(client)))
},
'automations show': async ({ flags, client, json }) => {
const result = await client.call<AutomationShowPayload>('automation.show', {
id: getRequiredStringFlag(flags, 'id')
})
printResult(result, json, formatAutomationShow)
printResult(result, json, (value) => formatAutomationShow(value, describeClientServer(client)))
},
'automations create': async ({ flags, client, cwd, json }) => {
const setupDecision = getAutomationSetupFlag(flags)
@@ -204,7 +205,7 @@ export const AUTOMATION_HANDLERS: Record<string, CommandHandler> = {
await assertAutomationFieldsSupported(writer, create)
}
const result = await writer.call<{ automation: Automation }>('automation.create', params)
printResult(result, json, formatAutomationShow)
printResult(result, json, (value) => formatAutomationShow(value, describeClientServer(client)))
},
'automations edit': async ({ flags, client, cwd, json }) => {
const setupDecision = getAutomationSetupFlag(flags)
@@ -251,7 +252,7 @@ export const AUTOMATION_HANDLERS: Record<string, CommandHandler> = {
...(setupDecision && !updates.workspaceMode ? { expectedWorkspaceMode: 'new_per_run' } : {}),
updates
})
printResult(result, json, formatAutomationShow)
printResult(result, json, (value) => formatAutomationShow(value, describeClientServer(client)))
},
'automations remove': async ({ flags, client, json }) => {
const id = getRequiredStringFlag(flags, 'id')
@@ -269,7 +270,7 @@ export const AUTOMATION_HANDLERS: Record<string, CommandHandler> = {
id,
...(expectedOwner ? { expectedOwner } : {})
})
const environment = getOptionalStringFlag(flags, 'environment') ?? process.env.ORCA_ENVIRONMENT
const environment = getOptionalStringFlag(flags, 'server') ?? process.env.ORCA_ENVIRONMENT
const preserveConnectionSettings = Boolean(
(client.isRemote && !environment) || process.env.ORCA_USER_DATA_PATH
)
@@ -179,7 +179,7 @@ export function createSkillMutationHandler(verb: SkillMutationVerb): CommandHand
throw new RuntimeClientError(
'invalid_environment',
`orca skills ${verb} writes to the machine that runs it, but this shell forwards ` +
`orca to the Orca host. Run the same orca skills ${verb} command on the machine ` +
`orca to the Orca server. Run the same orca skills ${verb} command on the machine ` +
"you want it on, where it can detect that host's agents."
)
}
+1 -1
View File
@@ -50,7 +50,7 @@ function explainRenameRefusal(error: unknown, sessionId: string): unknown {
) {
return new RuntimeClientError(
'incompatible_runtime',
'This Orca host cannot rename chats from the CLI. Update Orca on that host, or check that it has chats turned on.'
'This Orca server cannot rename chats from the CLI. Update Orca on that server, or check that it has chats turned on.'
)
}
return error
+1 -1
View File
@@ -25,7 +25,7 @@ describe('orca connector', () => {
it('names the update instead of surfacing method_not_found from an older host', async () => {
await expect(
callConnector(refusingClient('method_not_found'), 'connector.send', {})
).rejects.toThrow('Update Orca on the host')
).rejects.toMatchObject({ code: 'incompatible_runtime' })
})
it('claims a start only for a definite answer', () => {
+1 -1
View File
@@ -42,7 +42,7 @@ export async function callConnector<TResult>(
if (error instanceof RuntimeClientError && error.code === 'method_not_found') {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host has no connectors. Update Orca on the host and try again.'
'This Orca server has no connectors. Update Orca on the server and try again.'
)
}
throw error
+1 -1
View File
@@ -23,7 +23,7 @@ export async function assertDataAccountsSupported(ctx: HandlerContext): Promise<
if (!status.result.capabilities?.includes(DATA_ACCOUNT_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'Update or restart this Orca host to manage OpenCode and Devin accounts.'
'Update or restart this Orca server to manage OpenCode and Devin accounts.'
)
}
}
+38 -42
View File
@@ -1,7 +1,7 @@
import type { CommandHandler } from '../dispatch'
import {
formatEnvironment,
formatEnvironmentList,
formatSavedServer,
formatSavedServerList,
formatHostList,
formatHostName,
printResult,
@@ -34,10 +34,11 @@ import {
} from '../runtime/environments'
import { exchangeCliPairingCode } from '../runtime/environment-pairing-exchange'
import { refuseReservedEnvironmentName } from '../local-environment-selector'
import { quoteCliCommandArgument } from '../shell-command-quote'
import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store'
export const ENVIRONMENT_HANDLERS: Record<string, CommandHandler> = {
'host name': async ({ client, flags, json }) => {
'server name': async ({ client, flags, json }) => {
const requestedName = flags.get('name')
if (requestedName !== undefined && typeof requestedName !== 'string') {
throw new RuntimeClientError('invalid_argument', 'Missing value for --name')
@@ -48,37 +49,36 @@ export const ENVIRONMENT_HANDLERS: Record<string, CommandHandler> = {
if (current.result.machineName === undefined) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca runtime does not support machine names. Update Orca on that host and try again.'
'This Orca server does not support machine names. Update Orca on that server and try again.'
)
}
await client.call('settings.update', { machineName: requestedName })
}
// A blank override restores the detected name; read it from the runtime after writing.
// A blank override restores the detected name; read it from the server after writing.
const status = await client.call<RuntimeStatus>('status.get')
printResult({ ...status, result: describeRuntimeHost(status.result) }, json, formatHostName)
},
'environment add': async ({ flags, json }) => {
'server add': async ({ flags, json }) => {
const name = getRequiredStringFlag(flags, 'name')
refuseReservedEnvironmentName(name)
const pairingCode = await exchangeCliPairingCode(getRequiredStringFlag(flags, 'pairing-code'))
const environment = redactRuntimeEnvironment(
const server = redactRuntimeEnvironment(
addEnvironmentFromPairingCode(getDefaultUserDataPath(), {
name,
pairingCode
})
)
printResult(
localSuccess({ environment }),
localSuccess({ server }),
json,
(result: EnvironmentAddResult) =>
`Saved environment ${result.environment.name} (${result.environment.id}).`
(result: EnvironmentAddResult) => `Saved server ${result.server.name} (${result.server.id}).`
)
},
'host list': async ({ client, flags, json }) => {
rejectLocalPairingStoreRetargeting(
flags,
'`orca host list`. It answers from this machine\u2019s own pairing store, so a routed answer would name servers paired with a different machine.',
'Run `orca host list` on that machine to see the SSH targets registered there.'
'`orca host list`. It answers from this computer\u2019s own pairing store, so a routed answer would name servers saved on a different computer.',
'Run `orca host list` on that computer to see the SSH connections registered there.'
)
const sshTargets = (await listSshTargets(client)).map((target) => ({
kind: 'ssh' as const,
@@ -91,11 +91,11 @@ export const ENVIRONMENT_HANDLERS: Record<string, CommandHandler> = {
}))
// Read the local pairing store without dialing every server, so listing works offline.
const localStatus = await readLocalHostDescriptor(client)
const environments = listEnvironments(getDefaultUserDataPath()).map((environment) => ({
kind: 'environment' as const,
name: environment.name,
id: environment.id,
selector: `--environment ${environment.name}`
const servers = listEnvironments(getDefaultUserDataPath()).map((server) => ({
kind: 'server' as const,
name: server.name,
id: server.id,
selector: `--server ${quoteCliCommandArgument(server.id)}`
}))
const hosts = [
{
@@ -107,15 +107,15 @@ export const ENVIRONMENT_HANDLERS: Record<string, CommandHandler> = {
platform: localStatus.platform ?? process.platform
},
...sshTargets,
...environments
...servers
]
printResult(localSuccess({ hosts }), json, formatHostList)
},
'host rm': async ({ client, flags, json }) => {
rejectLocalPairingStoreRetargeting(
flags,
'`orca host rm`. It removes an SSH target from this machine\u2019s own Orca runtime, the same one `orca host list` reads.',
'Run `orca host rm` on that machine to remove an SSH target registered there.'
'`orca host rm`. It removes an SSH connection from the Orca on this computer, the same one `orca host list` reads.',
'Run `orca host rm` on that computer to remove an SSH connection registered there.'
)
const targetId = requireSshHostFlag(flags)
// Unlike listSshTargets, this keeps runtime_unavailable instead of reporting an unknown target.
@@ -124,7 +124,7 @@ export const ENVIRONMENT_HANDLERS: Record<string, CommandHandler> = {
if (!target) {
throw new RuntimeClientError(
'invalid_argument',
`Unknown SSH target in --host ssh:${targetId}: this Orca host has no SSH target with that id.`,
`Unknown SSH target in --host ssh:${targetId}: the Orca on this computer has no SSH target with that id.`,
{
knownSshTargets: targets,
nextSteps: ['Run `orca host list` to see each SSH target and its --host ssh:<id> flag.']
@@ -141,32 +141,28 @@ export const ENVIRONMENT_HANDLERS: Record<string, CommandHandler> = {
`Removed SSH target ${result.removed.name} (${result.removed.id}).`
)
},
'environment list': async ({ flags, json }) => {
'server list': async ({ flags, json }) => {
rejectLocalPairingStoreRetargeting(
flags,
'`orca environment list`. Paired servers are stored on this machine, so there is no other host to ask.',
'Run `orca environment list` on that machine to see the servers paired with it.'
'`orca server list`. Saved servers are stored on this computer, so no other server could answer.',
'Run `orca server list` on that computer to see the servers saved there.'
)
const environments = listEnvironments(getDefaultUserDataPath()).map(redactRuntimeEnvironment)
printResult(localSuccess({ environments }), json, formatEnvironmentList)
const servers = listEnvironments(getDefaultUserDataPath()).map(redactRuntimeEnvironment)
printResult(localSuccess({ servers }), json, formatSavedServerList)
},
'environment show': async ({ flags, json }) => {
const selector = getRequiredStringFlag(flags, 'environment')
const environment = redactRuntimeEnvironment(
resolveEnvironment(getDefaultUserDataPath(), selector)
)
printResult(localSuccess({ environment }), json, ({ environment: value }) =>
formatEnvironment(value)
)
'server show': async ({ flags, json }) => {
const selector = getRequiredStringFlag(flags, 'server')
const server = redactRuntimeEnvironment(resolveEnvironment(getDefaultUserDataPath(), selector))
printResult(localSuccess({ server }), json, ({ server: value }) => formatSavedServer(value))
},
'environment rm': async ({ flags, json }) => {
const selector = getRequiredStringFlag(flags, 'environment')
'server rm': async ({ flags, json }) => {
const selector = getRequiredStringFlag(flags, 'server')
const removed = redactRuntimeEnvironment(removeEnvironment(getDefaultUserDataPath(), selector))
printResult(
localSuccess({ removed }),
json,
(result: EnvironmentRemoveResult) =>
`Removed environment ${result.removed.name} (${result.removed.id}).`
`Removed server ${result.removed.name} (${result.removed.id}).`
)
}
}
@@ -178,7 +174,7 @@ function describeRuntimeHost(status: RuntimeStatus): HostNameResult {
}
}
/** The local row of `host list` still prints when this machine's runtime is not running. */
/** The local row of `host list` still prints when the Orca on this computer is not running. */
async function readLocalHostDescriptor(client: RuntimeClient): Promise<HostNameResult> {
try {
return describeRuntimeHost((await client.call<RuntimeStatus>('status.get')).result)
@@ -187,14 +183,14 @@ async function readLocalHostDescriptor(client: RuntimeClient): Promise<HostNameR
}
}
// Both listings read the local pairing store; reject flags that imply a different runtime.
// Both listings read the local pairing store; reject flags that imply a different server.
function rejectLocalPairingStoreRetargeting(
flags: Map<string, string | boolean>,
suffix: string,
crossHostNextStep: string
): void {
rejectRemoteSelectionFlags(flags, suffix, {
nextSteps: [crossHostNextStep, 'Drop the flag to answer for this machine.']
nextSteps: [crossHostNextStep, 'Drop the flag to answer for this computer.']
})
}
@@ -209,9 +205,9 @@ function requireSshHostFlag(flags: Map<string, string | boolean>): string {
const named = host.kind === 'alias' ? host.alias : host.id
const nextStep =
host.kind === 'runtime'
? 'A paired Orca server is removed with `orca environment rm --environment <name>`.'
? 'A saved server is removed with `orca server rm --server <id>`.'
: host.kind === 'local' || normalizeTypedName(named) === LOCAL_HOST_LIST_NAME
? 'This machine is always listed and cannot be removed.'
? 'This computer is always listed and cannot be removed.'
: 'Pass the SSH target id as --host ssh:<target-id>; `orca host list` prints it.'
throw new RuntimeClientError(
'invalid_argument',
@@ -11,6 +11,7 @@ import { formatWorktreeShow, printResult } from '../format'
import { getOptionalStringFlag, getOptionalStringFlagAllowingEmpty } from '../flags'
import { RuntimeClientError, type RuntimeClient, type RuntimeRpcSuccess } from '../runtime-client'
import { getWorktreeReadFlags } from './worktree-unread-flag'
import { annotateMutationResult } from './worktree-address-annotation'
type Flags = Map<string, string | boolean>
@@ -65,7 +66,11 @@ export async function setIfFolderWorkspace(
if (folderId === undefined) {
return false
}
printResult(await setFolderWorkspace(client, flags, folderId), json, formatWorktreeShow)
const { response } = await annotateMutationResult(
client,
await setFolderWorkspace(client, flags, folderId)
)
printResult(response, json, formatWorktreeShow)
return true
}
+3 -2
View File
@@ -1,4 +1,5 @@
import type { OrcadManagedRuntimeStatus } from '../../shared/orcad-managed-runtime'
import { quoteCliCommandArgument } from '../shell-command-quote'
function count(value: number | null): string {
return value === null ? 'unverifiable' : String(value)
@@ -12,7 +13,7 @@ export function formatManagedServerStatus(status: OrcadManagedRuntimeStatus): st
]
if (status.recovery) {
lines.push(
`Interrupted ${status.recovery.operation} of ${status.recovery.version} (${status.recovery.phase}); run \`orca environment recover\`.`
`Interrupted ${status.recovery.operation} of ${status.recovery.version} (${status.recovery.phase}); run \`orca server recover --server ${quoteCliCommandArgument(status.environmentId)}\`.`
)
}
if (status.migration) {
@@ -25,7 +26,7 @@ export function formatManagedServerStatus(status: OrcadManagedRuntimeStatus): st
}
if (status.availableUpdate) {
lines.push(
`Update available: ${status.availableUpdate}; run \`orca environment update --environment ${status.environmentId}\`.`
`Update available: ${status.availableUpdate}; run \`orca server update --server ${quoteCliCommandArgument(status.environmentId)}\`.`
)
}
return lines.join('\n')
+4 -3
View File
@@ -1,8 +1,9 @@
// Updates can close this connection mid-call; report the outcome from status after the runtime returns.
// Updates can close this connection mid-call; report the outcome from status after the server returns.
import type { OrcadManagedRuntimeStatus } from '../../shared/orcad-managed-runtime'
import type { HandlerContext } from '../dispatch'
import { printResult } from '../format'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
import { quoteCliCommandArgument } from '../shell-command-quote'
const STATUS_ATTEMPTS = 15
const STATUS_RETRY_MS = 2_000
@@ -24,7 +25,7 @@ export async function reportAfterClosedConnection(
if (status.recovery) {
throw new RuntimeClientError(
'managed_server_interrupted',
`The ${status.recovery.operation} of ${status.recovery.version} was interrupted. Run \`orca environment recover\`.`,
`The ${status.recovery.operation} of ${status.recovery.version} was interrupted. Run \`orca server recover --server ${quoteCliCommandArgument(selector.selector)}\`.`,
status
)
}
@@ -41,6 +42,6 @@ export async function reportAfterClosedConnection(
}
throw new RuntimeClientError(
'managed_server_in_progress',
'The connection closed while the server restarted, and it has not answered since. Check `orca environment status`.'
`The connection closed while the server restarted, and it has not answered since. Check \`orca server status --server ${quoteCliCommandArgument(selector.selector)}\`.`
)
}
+19 -17
View File
@@ -16,9 +16,10 @@ import { printResult } from '../format'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
import { formatManagedServerStatus } from './managed-server-format'
import { reportAfterClosedConnection } from './managed-server-reconnect'
import { quoteCliCommandArgument } from '../shell-command-quote'
const UNSUPPORTED_MESSAGE =
'This Orca runtime cannot manage servers over SSH. Run this on the computer whose Orca desktop app deployed the server, after updating Orca there.'
'This Orca server cannot manage servers over SSH. Run this on the computer whose Orca desktop app deployed the server, after updating Orca there.'
// Windows promotion and readiness waits can take ten minutes; allow headroom on slow hosts.
export const MANAGED_SERVER_ACTION_TIMEOUT_MS = 20 * 60_000
@@ -48,11 +49,11 @@ async function callManagedServer<TResult>(
if (error instanceof RuntimeClientError && error.code === 'method_not_found') {
throw unsupported()
}
// The runtime continues the action after this client times out.
// The desktop continues the action after this client times out.
if (!readOnly && error instanceof RuntimeClientError && error.code === 'runtime_timeout') {
throw new RuntimeClientError(
'managed_server_in_progress',
'Stopped waiting, but the desktop may still be running this action. Check `orca environment status` before retrying.'
`Stopped waiting, but the desktop may still be running this action. Check \`orca server status --server ${quoteCliCommandArgument(String(params.selector))}\` before retrying.`
)
}
throw error
@@ -77,7 +78,7 @@ async function callExpectingRestart<TResult>(
}
function selectorOf(context: HandlerContext): { selector: string } {
return { selector: getRequiredStringFlag(context.flags, 'environment') }
return { selector: getRequiredStringFlag(context.flags, 'server') }
}
type Outcome = { outcome: string; code?: string; reason?: string }
@@ -111,7 +112,7 @@ function isSettled<TResult extends Outcome, TSettled extends TResult['outcome']>
}
export const MANAGED_SERVER_HANDLERS: Record<string, CommandHandler> = {
'environment status': async (context) => {
'server status': async (context) => {
const response = await callManagedServer<OrcadManagedRuntimeStatus>(
context,
'managedServer.status',
@@ -119,7 +120,7 @@ export const MANAGED_SERVER_HANDLERS: Record<string, CommandHandler> = {
)
printResult(response, context.json, formatManagedServerStatus)
},
'environment update': async (context) => {
'server update': async (context) => {
const params = { ...selectorOf(context), force: context.flags.get('force') === true }
const response = await callExpectingRestart<OrcadManagedDeployResult>(
context,
@@ -135,7 +136,7 @@ export const MANAGED_SERVER_HANDLERS: Record<string, CommandHandler> = {
: `Updated ${result.environment.name} to ${result.activeVersion}.`
)
},
'environment rollback': async (context) => {
'server rollback': async (context) => {
const response = await callExpectingRestart<OrcadManagedRollbackResult>(
context,
'managedServer.rollback',
@@ -151,7 +152,7 @@ export const MANAGED_SERVER_HANDLERS: Record<string, CommandHandler> = {
(result) => `Rolled ${result.environment.name} back to ${result.activeVersion}.`
)
},
'environment recover': async (context) => {
'server recover': async (context) => {
const params = selectorOf(context)
const acceptChangedState = context.flags.get('accept-changed-state') === true
if (acceptChangedState && context.flags.get('yes') !== true) {
@@ -179,12 +180,12 @@ export const MANAGED_SERVER_HANDLERS: Record<string, CommandHandler> = {
: null
)
},
'environment stop': async (context) => {
'server stop': async (context) => {
const params = selectorOf(context)
if (context.flags.get('yes') !== true) {
throw new RuntimeClientError(
'confirmation_required',
`Stopping ${params.selector} ends its terminals and unlinks it from this machine. Re-run with --yes to confirm.`
`Stopping ${params.selector} ends its terminals and unlinks it from this computer. Re-run with --yes to confirm.`
)
}
const response = await callManagedServer<OrcadManagedStopResult>(
@@ -197,15 +198,15 @@ export const MANAGED_SERVER_HANDLERS: Record<string, CommandHandler> = {
context.json,
['unlinked'],
() =>
`Stopped ${params.selector}, unlinked it from this machine and disconnected its SSH host.`
`Stopped ${params.selector}, unlinked it from this computer and disconnected its SSH host.`
)
},
'environment forget': async (context) => {
'server forget': async (context) => {
const params = selectorOf(context)
if (context.flags.get('yes') !== true) {
throw new RuntimeClientError(
'confirmation_required',
`Forgetting ${params.selector} unlinks it from this machine without stopping it on its host. Re-run with --yes to confirm.`
`Forgetting ${params.selector} unlinks it from this computer without stopping it on its host. Re-run with --yes to confirm.`
)
}
const response = await callManagedServer<OrcadManagedForgetResult>(
@@ -218,21 +219,22 @@ export const MANAGED_SERVER_HANDLERS: Record<string, CommandHandler> = {
context.json,
['forgotten'],
() =>
`Unlinked ${params.selector} from this machine and disconnected its SSH host. The host was not contacted, so orcad may still be running there; connect the host to set its server up again.`
`Unlinked ${params.selector} from this computer and disconnected its SSH host. The host was not contacted, so orcad may still be running there; connect the host to set its server up again.`
)
},
'environment cancel-stop': async (context) => {
'server cancel-stop': async (context) => {
const params = selectorOf(context)
const response = await callManagedServer<OrcadManagedCancelStopResult>(
context,
'managedServer.cancelStop',
selectorOf(context)
params
)
report(response, context.json, ['canceled', 'already-stopped', 'none'], (result) => {
switch (result.outcome) {
case 'canceled':
return `Stop withdrawn; the server keeps serving ${result.activeVersion}.`
case 'already-stopped':
return 'orcad had already exited. Run `orca environment stop --yes` to unlink it.'
return `orcad had already exited. Run \`orca server stop --server ${quoteCliCommandArgument(params.selector)} --yes\` to unlink it.`
case 'none':
return 'No stop is pending.'
}
@@ -248,7 +248,7 @@ describe('orchestration agent views', () => {
expect(stdout).toBe(
'scope.run=run_1 scope.source=flag\n' +
'dispatchId=ctx_1 taskId=task_1 state=running liveness=live terminal=term_agent terminalState=active workspace=wt_1::/repo host=local attention=input next="orca-dev orchestration worker-stop --dispatch ctx_1"'
'dispatchId=ctx_1 taskId=task_1 state=running liveness=live terminal=term_agent terminalState=active workspace=wt_1::/repo server=local attention=input next="orca-dev orchestration worker-stop --dispatch ctx_1"'
)
})
@@ -66,7 +66,7 @@ export function formatRemovedWorkListing(
): string {
if (!removed) {
// Also shown when a host could not read its record; run-show omits the field either way.
return 'No record of removed work is available from this Orca host.'
return 'No record of removed work is available from this Orca server.'
}
const entries = removed.entries ?? []
if (entries.length === 0) {
@@ -1,4 +1,5 @@
import { renderOrchestrationArgv, type OrchestrationAgentView } from './agent-view'
import { formatOwner, ownerOfWorkerHost, type OwnerContext } from '../../row-owner-server'
import type { WorkerListRunScope } from './worker-list-run-scope'
import { isActionableOrchestrationFleetAttention } from '../../../shared/orchestration/fleet/orchestration-fleet-attention'
import { formatPrCommentRelativeTime } from '../../../shared/source-control/review-comments/pr-comment-time'
@@ -7,7 +8,7 @@ type WorkerProjection = {
runId?: string
outcome?: string | null
provider?: { id: string; model: string | null } | null
host: { id: string }
host: { kind?: 'local' | 'remote'; id: string }
workspace?: { id: string } | null
stage: { activity: string }
liveness: { verdict: string; detail?: string }
@@ -132,7 +133,7 @@ type WorkerListRow = {
terminal?: string
terminalState?: string
workspace?: string
host?: string
server?: string
attention?: string[]
autoReleaseAt?: string
next?: string
@@ -147,7 +148,10 @@ type WorkerListFields = {
type ScopedWorkerList = WorkerListResult & { scope: WorkerListRunScope }
export const WORKER_LIST_VIEW: OrchestrationAgentView<ScopedWorkerList, WorkerListFields> = {
/** `owners` names each worker's server from the home coordinator's own store; nothing is dialed. */
export const workerListView = (
owners: OwnerContext
): OrchestrationAgentView<ScopedWorkerList, WorkerListFields> => ({
fields: (value) => ({
workers: value.workers.map((worker) => {
const projection = worker.projection
@@ -167,7 +171,7 @@ export const WORKER_LIST_VIEW: OrchestrationAgentView<ScopedWorkerList, WorkerLi
terminalState: worker.terminalState ?? undefined,
// Older runtimes send no projection; the terminal resource row still names both.
workspace: projection?.workspace?.id ?? worker.resource?.worktreeId ?? undefined,
host: projection?.host.id,
server: workerServer(projection?.host, owners),
attention: actionableAttention(projection),
autoReleaseAt: projection?.autoReleaseAt ?? worker.resource?.autoReleaseAt ?? undefined,
next: projection
@@ -189,6 +193,13 @@ export const WORKER_LIST_VIEW: OrchestrationAgentView<ScopedWorkerList, WorkerLi
}
: undefined
}
})
function workerServer(
host: WorkerProjection['host'] | undefined,
owners: OwnerContext
): string | undefined {
return host ? formatOwner(ownerOfWorkerHost(host, owners)) : undefined
}
// Older runtimes send no projection and cannot close finished workers on their own.
@@ -34,7 +34,7 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record<string, CommandHandler>
) {
throw new RuntimeClientError(
'incompatible_runtime',
'The connected Orca runtime does not support worker model or effort overrides. Update or restart Orca and try again.'
'The connected Orca server does not support worker model or effort overrides. Update or restart Orca and try again.'
)
}
}
@@ -1,7 +1,8 @@
import type { CommandHandler } from '../../dispatch'
import { printResult } from '../../format'
import { printOrchestrationResult } from './agent-view'
import { WORKER_LIST_VIEW, type WorkerListResult } from './worker-agent-views'
import { workerListView, type WorkerListResult } from './worker-agent-views'
import { formatOwnerToken, ownerOfWorkerHost, readOwnerContext } from '../../row-owner-server'
import {
formatHelperStops,
WORKER_RELEASE_VIEW,
@@ -139,18 +140,19 @@ export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record<string, CommandHandl
if (requiresCurrentListSemantics && !result.result.page) {
throw new RuntimeClientError(
'incompatible_runtime',
'The connected Orca runtime did not prove support for the requested worker-list flags, so no inventory was printed. Update the connected Orca runtime and retry.'
'The connected Orca server did not prove support for the requested worker-list flags, so no inventory was printed. Update the connected Orca server and retry.'
)
}
if (!flags.has('full')) {
printOrchestrationResult(
{ ...result, result: { ...result.result, scope } },
json,
WORKER_LIST_VIEW
workerListView(readOwnerContext(client))
)
return
}
printResult({ ...result, result: { ...result.result, scope } }, json, (value) => {
const owners = readOwnerContext(client)
const rows =
value.workers.length === 0
? 'No workers found.'
@@ -165,7 +167,7 @@ export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record<string, CommandHandl
const liveness = projection?.liveness.verdict
const attention = projection?.attention?.categories.join(',') || 'none'
const details = projection
? `/${stage}] attention=${attention} liveness=${liveness} provider=${provider} host=${projection.host.id} workspace=${workspace}`
? `/${stage}] attention=${attention} liveness=${liveness} provider=${provider} ${formatOwnerToken(ownerOfWorkerHost(projection.host, owners))} workspace=${workspace}`
: `]`
const next = projection
? ` next=${projection.nextAction.argv.join(' ') || 'none'}`
+2 -2
View File
@@ -44,7 +44,7 @@ describe('orca plugin dev watch', () => {
'--approve',
'ap1-old',
'--json',
'--environment',
'--server',
'box'
]
const call = vi
@@ -65,7 +65,7 @@ describe('orca plugin dev watch', () => {
dir: '/work/notes',
approve: 'ap1-new',
json: true,
environment: 'box'
server: 'box'
})
})
+2 -2
View File
@@ -125,11 +125,11 @@ function bindShotHost(
export function bindPluginDevWatchHost(ctx: HandlerContext, path: string): PluginDevWatchHost {
const approve = ctx.flags.get('approve')
const check = ctx.flags.get('check') === true
// Why local only: the check renders the folder's code on this machine, not on the Orca host.
// Why local only: the check renders the folder's code on this machine, not on the Orca server.
if (check && ctx.client.isRemote) {
throw new RuntimeClientError(
'invalid_argument',
'--check renders the plugin on this machine, so it needs a local folder; drop --environment or --check.'
'--check renders the plugin on this machine, so it needs a local folder; drop --server or --check.'
)
}
const shotFlag = ctx.flags.get('shot')
+1 -1
View File
@@ -62,7 +62,7 @@ function looksLikePath(value: string): boolean {
)
}
/** Sorts what the caller typed into a catalog id, a Git source or a folder on the Orca host. */
/** Sorts what the caller typed into a catalog id, a Git source or a folder on the Orca server. */
export function classifyPluginInstallSource(ctx: HandlerContext, value: string): InstallSpec {
const ref = stringFlag(ctx, 'ref')
const catalog = stringFlag(ctx, 'catalog')
+4 -4
View File
@@ -46,8 +46,8 @@ export function translatePluginRpcError(
if (code === 'method_not_found') {
return new RuntimeClientError(
'runtime_unsupported',
`The Orca host this command reached is too old for \`${method}\`.`,
{ nextSteps: ['Update Orca on that host, then run the command again.'] }
`The Orca server this command reached is too old for \`${method}\`.`,
{ nextSteps: ['Update Orca on that server, then run the command again.'] }
)
}
const fingerprint = approvalFingerprintOf(data)
@@ -85,12 +85,12 @@ export async function callPlugins<T>(
}
}
/** Development folders are paths on the Orca host, which may not be this machine. */
/** Development folders are paths on the Orca server, which may not be this machine. */
export function resolveHostPluginPath(ctx: HandlerContext, value: string): string {
if (process.env.ORCA_CLI_CWD) {
throw new RuntimeClientError(
'invalid_environment',
'This shell forwards orca to an Orca host on another machine, which cannot read this folder. Run the command on the machine that runs Orca, or pass --environment for an Orca server that has the folder.'
'This shell forwards orca to an Orca server on another machine, which cannot read this folder. Run the command on the machine that runs Orca, or pass --server for an Orca server that has the folder.'
)
}
if (isAbsolute(value)) {
+1 -1
View File
@@ -45,7 +45,7 @@ function requireLocal(ctx: HandlerContext): void {
if (process.env.ORCA_CLI_CWD || ctx.client.isRemote) {
throw refuse(
'invalid_environment',
"shot --scenario runs the plugin's code on this machine and shows it in the Orca on this machine, so it does not reach another host. Run it where Orca and the plugin folder are, without --environment."
"shot --scenario runs the plugin's code on this machine and shows it in the Orca on this machine, so it does not reach another host. Run it where Orca and the plugin folder are, without --server."
)
}
}
+2 -2
View File
@@ -79,12 +79,12 @@ export function defaultPluginShotPath(dir: string, pluginKey: string, panelId: s
return join(dir, `${pluginKey}-${panelId}.png`)
}
/** The PNG lands on the machine that runs the CLI, also with --environment. */
/** The PNG lands on the machine that runs the CLI, also with --server. */
export function resolveLocalShotPath(ctx: HandlerContext, value: string): string {
if (process.env.ORCA_CLI_CWD) {
throw new RuntimeClientError(
'invalid_environment',
'orca plugin shot writes the PNG on the machine that runs it, but this shell forwards orca to the Orca host. Run it on the machine that should keep the image.'
'orca plugin shot writes the PNG on the machine that runs it, but this shell forwards orca to the Orca server. Run it on the machine that should keep the image.'
)
}
return isAbsolute(value) ? value : resolve(ctx.cwd, value)
+1 -1
View File
@@ -140,7 +140,7 @@ async function scanPortsOnWorkspaceHost(
if (error instanceof RuntimeClientError && error.code === 'method_not_found') {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca runtime cannot list workspace ports yet. Update Orca and try again.'
'This Orca server cannot list workspace ports yet. Update Orca and try again.'
)
}
throw error
+1 -1
View File
@@ -477,7 +477,7 @@ describe('profile-state CLI recovery', () => {
expect(existsSync(profile.databaseFile)).toBe(true)
expect(vi.mocked(console.log).mock.calls.at(-1)?.[0]).toContain(
'`--environment` does not retarget profile-state recovery'
'`--server` does not retarget profile-state recovery'
)
})
+12 -7
View File
@@ -10,7 +10,11 @@ import type {
ProjectHostSetupUpdateArgs,
ProjectHostSetupUpdateResult
} from '../../shared/project-types'
import { getSshTargetIdForExecutionHost, type ExecutionHostId } from '../../shared/execution-host'
import {
getSshTargetIdForExecutionHost,
LOCAL_EXECUTION_HOST_ID,
type ExecutionHostId
} from '../../shared/execution-host'
import type { RuntimeStatus } from '../../shared/runtime-types'
import { PROJECT_HOST_SETUP_HOST_TARGET_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
import type { CommandHandler, HandlerContext } from '../dispatch'
@@ -28,6 +32,7 @@ import {
parseHostFlag,
resolveHostFlagTarget
} from '../execution-host-flag'
import { readOwnerContext } from '../row-owner-server'
import { getOptionalRepoKind, getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { findProjectSetups, resolveProjectIdSelector } from '../project-selector'
import { resolveRepoPathArgument } from '../repo-path-arguments'
@@ -59,10 +64,7 @@ async function getResolvedHostId(
client: HandlerContext['client']
): Promise<ExecutionHostId> {
const host = await resolveHostFlagTarget(flags, client)
if (!host) {
throw new RuntimeClientError('invalid_argument', 'Missing required --host')
}
return host.id
return host?.id ?? LOCAL_EXECUTION_HOST_ID
}
// The runtime rejects SSH setup operations regardless of target existence; preserve that refusal.
@@ -71,8 +73,9 @@ async function getRequiredHostId(
client: HandlerContext['client']
): Promise<ExecutionHostId> {
const host = parseHostFlag(flags)
// Without --host the setup belongs to the server the command runs on.
if (!host) {
throw new RuntimeClientError('invalid_argument', 'Missing required --host')
return LOCAL_EXECUTION_HOST_ID
}
if (host.kind !== 'alias') {
return host.id
@@ -123,7 +126,9 @@ export const PROJECT_HANDLERS: Record<string, CommandHandler> = {
const setups = projectSetups.filter(
(setup) => hostFilter === undefined || hostFilterMatchesHostId(hostFilter, setup.hostId)
)
printResult({ ...result, result: { setups } }, json, formatProjectHostSetupList)
printResult({ ...result, result: { setups } }, json, (value) =>
formatProjectHostSetupList(value, readOwnerContext(client))
)
},
'project setup-existing-folder': async ({ flags, client, cwd, json }) => {
const rawPath = getRequiredStringFlag(flags, 'path')
+1 -1
View File
@@ -36,7 +36,7 @@ async function callReference<TResult>(
if (error instanceof RuntimeClientError && error.code === 'method_not_found') {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host does not support reference commands yet. Update Orca on the execution host.'
'This Orca server does not support reference commands yet. Update Orca on that server.'
)
}
throw error
+1 -1
View File
@@ -134,7 +134,7 @@ async function callShare(
if (error instanceof RuntimeRpcFailureError && error.code === 'method_not_found') {
throw new RuntimeClientError(
'update_required',
'The connected Orca runtime does not support agent skill sharing yet. Update Orca on that machine and try again.'
'The connected Orca server does not support agent skill sharing yet. Update Orca on that machine and try again.'
)
}
throw error
+1 -1
View File
@@ -74,7 +74,7 @@ export const terminalCloseHandler: CommandHandler = async ({ flags, client, cwd,
if (error instanceof RuntimeClientError && error.code === 'method_not_found') {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host does not support closing every terminal in a workspace yet. Update Orca on the host and try again.'
'This Orca server does not support closing every terminal in a workspace yet. Update Orca on the server and try again.'
)
}
throw error
+4 -4
View File
@@ -35,7 +35,7 @@ export const terminalSendHandler: CommandHandler = async ({ flags, client, cwd,
if (!status.result.runtime.reachable) {
throw new RuntimeClientError(
'runtime_unavailable',
'Orca could not verify prompt-delivery support, so no input was sent. Wait for the execution host to become reachable and retry.'
'Orca could not verify prompt-delivery support, so no input was sent. Wait for the server to become reachable and retry.'
)
}
promptDeliverySupported =
@@ -46,13 +46,13 @@ export const terminalSendHandler: CommandHandler = async ({ flags, client, cwd,
if (retryRequest && !promptDeliverySupported) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host cannot honor --retry-request and never recorded this request ID. This attempt sent no input, but an earlier prompt may have been delivered; inspect the terminal and do not resend unless you independently prove it was not delivered, because updating the host cannot make this specific retry idempotent.'
'This Orca server cannot honor --retry-request and never recorded this request ID. This attempt sent no input, but an earlier prompt may have been delivered; inspect the terminal and do not resend unless you independently prove it was not delivered, because updating the host cannot make this specific retry idempotent.'
)
}
if (waitSubmitMs && !promptDeliverySupported) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host does not support --wait-submit. No input was sent; update Orca on the execution host, or omit only --wait-submit for a legacy prompt whose delivery cannot be observed or retried safely.'
'This Orca server does not support --wait-submit. No input was sent; update Orca on the server, or omit only --wait-submit for a legacy prompt whose delivery cannot be observed or retried safely.'
)
}
const params = {
@@ -86,7 +86,7 @@ export const terminalSendHandler: CommandHandler = async ({ flags, client, cwd,
throw attachUnverifiedTerminalPromptRecovery(
new RuntimeClientError(
'incompatible_runtime',
'The Orca host changed after prompt-delivery support was verified and accepted input without returning a durable prompt receipt.'
'The Orca server changed after prompt-delivery support was verified and accepted input without returning a durable prompt receipt.'
)
)
}
+7 -6
View File
@@ -34,6 +34,7 @@ import {
type WithAnnotatedHostScope
} from '../omitted-host-scope-selectors'
import { RuntimeClientError } from '../runtime-client'
import { readOwnerContext } from '../row-owner-server'
import {
isSupportedWindowsShellOverride,
listSupportedWindowsShellOverrides
@@ -80,7 +81,7 @@ export const TERMINAL_HANDLERS: Record<string, CommandHandler> = {
}
)
await annotateOmittedHostScope(result.result)
printResult(result, json, formatTerminalList)
printResult(result, json, (value) => formatTerminalList(value, readOwnerContext(client)))
},
'terminal show': async ({ flags, client, cwd, json }) => {
const result = await client.call<{ terminal: RuntimeTerminalShow }>('terminal.show', {
@@ -115,7 +116,7 @@ export const TERMINAL_HANDLERS: Record<string, CommandHandler> = {
if (screen && result.result.terminal.source === undefined) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host does not support --screen reads, so it answered with accumulated output instead of the rendered screen. Update Orca on the host, or drop --screen to read accumulated output deliberately.'
'This Orca server does not support --screen reads, so it answered with accumulated output instead of the rendered screen. Update Orca on the server, or drop --screen to read accumulated output deliberately.'
)
}
printResult(result, json, formatTerminalRead)
@@ -186,7 +187,7 @@ export const TERMINAL_HANDLERS: Record<string, CommandHandler> = {
if (!status.result.runtime.reachable) {
throw new RuntimeClientError(
'runtime_unavailable',
'Orca could not verify --shell support on the execution host, so no terminal was created. Wait for the execution host to become reachable and retry.'
'Orca could not verify --shell support on the server, so no terminal was created. Wait for the server to become reachable and retry.'
)
}
if (
@@ -196,7 +197,7 @@ export const TERMINAL_HANDLERS: Record<string, CommandHandler> = {
) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host does not support --shell, and would silently create a terminal running its default shell instead. No terminal was created; update Orca on the execution host.'
'This Orca server does not support --shell, and would silently create a terminal running its default shell instead. No terminal was created; update Orca on the server.'
)
}
}
@@ -234,7 +235,7 @@ export const TERMINAL_HANDLERS: Record<string, CommandHandler> = {
if (!status.result.runtime.reachable) {
throw new RuntimeClientError(
'runtime_unavailable',
'Orca could not verify --retry-split support on the execution host, so nothing was split. Wait for the execution host to become reachable and retry.'
'Orca could not verify --retry-split support on the server, so nothing was split. Wait for the server to become reachable and retry.'
)
}
if (
@@ -243,7 +244,7 @@ export const TERMINAL_HANDLERS: Record<string, CommandHandler> = {
) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host does not support --retry-split and would split again. Nothing was split; check `orca terminal list --json` for the pane instead.'
'This Orca server does not support --retry-split and would split again. Nothing was split; check `orca terminal list --json` for the pane instead.'
)
}
}
@@ -1,6 +1,16 @@
import type { RuntimeWorktreePsSummary, RuntimeWorktreeRecord } from '../../shared/runtime-types'
import type { RuntimeClient } from '../runtime-client'
import { addressableOfPsRow, addressableOfShowRecord, annotateListing } from '../workspace-address'
import type {
CrossStoreWorkspaceLineage,
WorkspaceLineage,
WorktreeLineage
} from '../../shared/worktree/lineage-types'
import {
addressableOfPsRow,
addressableOfShowRecord,
annotateListing,
formatParentText
} from '../workspace-address'
import { callerOrcaClient } from './worktree-parent-fields'
/** Annotates `worktree ps` rows; the returned function applies them to any rows aligned by index. */
@@ -16,7 +26,7 @@ export async function annotatePsRows(
return (aligned) => aligned.map((row, index) => ({ ...row, ...annotations[index] }))
}
/** A `worktree show` record with its environment, address and parent. */
/** A `worktree show` record with its server, address and parent. */
export async function annotateShown<
Response extends { result: { worktree: RuntimeWorktreeRecord } }
>(client: RuntimeClient, response: Response): Promise<Response> {
@@ -28,3 +38,40 @@ export async function annotateShown<
result: { ...response.result, worktree: { ...response.result.worktree, ...annotation } }
}
}
type MutationResult = {
worktree: RuntimeWorktreeRecord
lineage?: WorktreeLineage | null
workspaceLineage?: WorkspaceLineage | null
crossStoreLineage?: CrossStoreWorkspaceLineage | null
}
/**
* A create/set result annotated the way `show` is, so its summary prints the same parent line as
* `ps`. Reporting only: an annotation failure keeps the unannotated result.
*/
export async function annotateMutationResult<Response extends { result: MutationResult }>(
client: RuntimeClient,
response: Response
): Promise<{ response: Response; parentText: string | null }> {
const { worktree, lineage, workspaceLineage, crossStoreLineage } = response.result
try {
const [annotation] = await annotateListing(client, () => callerOrcaClient(client), [
addressableOfShowRecord({
...worktree,
parentWorktreeId: worktree.parentWorktreeId ?? lineage?.parentWorktreeId ?? null,
workspaceLineage: worktree.workspaceLineage ?? workspaceLineage ?? null,
crossStoreLineage: worktree.crossStoreLineage ?? crossStoreLineage ?? null
})
])
return {
response: {
...response,
result: { ...response.result, worktree: { ...worktree, ...annotation } }
},
parentText: formatParentText(annotation)
}
} catch {
return { response, parentText: null }
}
}
@@ -1,4 +1,4 @@
// Use agent.launch for surface/model/effort; older hosts fall back to the create startup terminal.
// Use agent.launch for surface/model/effort; older servers fall back to the create startup terminal.
import type { AgentLaunchResult } from '../../shared/agent-launch/contracts/agent-launch-intent'
import {
@@ -17,6 +17,7 @@ import {
import { formatWorktreeShow, printResult } from '../format'
import { RuntimeClientError, type RuntimeClient } from '../runtime-client'
import { printLineageSummary } from './worktree-lineage-summary'
import { annotateMutationResult } from './worktree-address-annotation'
import { printHookWarning } from './worktree-removal-warnings'
import { withSetupDecisionRecovery } from './worktree-setup-decision-recovery'
import { withCliAgentLaunchRecovery } from '../agent-launch-recovery'
@@ -25,7 +26,7 @@ type WorktreeAgentLaunchResult = Pick<
RuntimeWorktreeCreateResult,
'lineage' | 'workspaceLineage' | 'crossStoreLineage'
> & {
/** Absent only when the host could not show the worktree it just created. */
/** Absent only when the server could not show the worktree it just created. */
worktree?: RuntimeWorktreeRecord
launch: AgentLaunchResult
}
@@ -47,13 +48,13 @@ export async function createWorktreeWithAgent(args: {
if (launch.operationId) {
throw new RuntimeClientError(
'agent_session_operation_unknown',
'This host cannot replay the earlier launch. Return to the original execution host; do not retry without --retry-launch.'
'This server cannot replay the earlier launch. Return to the server that started it; do not retry without --retry-launch.'
)
}
if (hasLaunchModelFlags(flags)) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host cannot start an agent on a chosen model or effort. Update Orca on the execution host, or omit --model and --effort.'
"This Orca server can't start an agent on a chosen model or effort. Update Orca on that server, or omit --model and --effort."
)
}
if (launch.surface) {
@@ -74,9 +75,10 @@ export async function createWorktreeWithAgent(args: {
}
)
)
printHookWarning(created.result, json)
printLineageSummary(created.result, json)
printResult(created, json, formatWorktreeShow)
const { response, parentText } = await annotateMutationResult(client, created)
printHookWarning(response.result, json)
printLineageSummary(response.result, json, parentText)
printResult(response, json, formatWorktreeShow)
return
}
const launched = await withSetupDecisionRecovery(
@@ -92,7 +94,11 @@ export async function createWorktreeWithAgent(args: {
),
launch.operationId !== undefined
)
const worktree = await showLaunchedWorktree(client, launched.result.worktreeId)
const shown = await showLaunchedWorktree(client, launched.result.worktreeId)
const annotated = shown
? await annotateMutationResult(client, { result: { worktree: shown } })
: undefined
const worktree = annotated?.response.result.worktree
const result: WorktreeAgentLaunchResult = {
...(worktree
? {
@@ -104,7 +110,7 @@ export async function createWorktreeWithAgent(args: {
: { lineage: null }),
launch: launched.result
}
printLineageSummary(result, json)
printLineageSummary(result, json, annotated?.parentText ?? null)
printResult({ ...launched, result }, json, (value) =>
[
...(value.worktree ? [formatWorktreeShow({ worktree: value.worktree })] : []),
+25 -21
View File
@@ -19,35 +19,42 @@ function getLineageSourceLabel(source: string): string {
}
}
/** The summary line for a parent saved in another Orca store. */
export function formatCrossStoreParentLine(
lineage: NonNullable<RuntimeWorktreeCreateResult['crossStoreLineage']>
/**
* The stderr parent summary for create/set: the `ps` parent text plus how the parent was captured.
* `parentText` comes from the result's annotation; without one, a cross-store parent's server is unknown.
*/
function parentSummaryText(
parentText: string | null,
fallback: string,
capture: { confidence: string; source: string }
): string {
return `parent: ${lineage.parent.workspaceKey} on another machine (${lineage.capture.confidence} from ${getLineageSourceLabel(lineage.capture.source)})`
}
export function formatFolderParentLine(
lineage: NonNullable<RuntimeWorktreeCreateResult['workspaceLineage']>
): string {
return `parent: ${lineage.parentWorkspaceKey} (folder workspace)`
return `parent: ${parentText ?? fallback} (${capture.confidence} from ${getLineageSourceLabel(capture.source)})`
}
/** The parent `worktree set` attached; same-store lineage fields stay null for both kinds. */
export function printSetParentLine(
worktree: RuntimeWorktreeRecord,
parentFields: { crossStoreParent?: unknown; parentWorktree?: string }
parentFields: { crossStoreParent?: unknown; parentWorktree?: string },
parentText: string | null
): void {
if (parentFields.crossStoreParent && worktree.crossStoreLineage) {
console.error(formatCrossStoreParentLine(worktree.crossStoreLineage))
const { parent, capture } = worktree.crossStoreLineage
console.error(parentSummaryText(parentText, crossStoreFallback(parent.workspaceKey), capture))
} else if (parentFields.parentWorktree && worktree.workspaceLineage) {
console.error(formatFolderParentLine(worktree.workspaceLineage))
const { parentWorkspaceKey, capture } = worktree.workspaceLineage
console.error(parentSummaryText(parentText, parentWorkspaceKey, capture))
}
}
function crossStoreFallback(workspaceKey: string): string {
return `${workspaceKey} server=unknown (no verified route here)`
}
export function printLineageSummary(
result: Pick<RuntimeWorktreeCreateResult, 'lineage' | 'workspaceLineage'> &
Partial<Pick<RuntimeWorktreeCreateResult, 'warnings' | 'crossStoreLineage'>>,
json: boolean
json: boolean,
parentText: string | null = null
): void {
if (json) {
return
@@ -56,21 +63,18 @@ export function printLineageSummary(
console.error(`warning: ${warning.message}`)
}
if (result.crossStoreLineage) {
console.error(formatCrossStoreParentLine(result.crossStoreLineage))
const { parent, capture } = result.crossStoreLineage
console.error(parentSummaryText(parentText, crossStoreFallback(parent.workspaceKey), capture))
return
}
if (result.workspaceLineage) {
const { parentWorkspaceKey, capture } = result.workspaceLineage
console.error(
`parent: ${parentWorkspaceKey} (${capture.confidence} from ${getLineageSourceLabel(capture.source)})`
)
console.error(parentSummaryText(parentText, parentWorkspaceKey, capture))
return
}
if (result.lineage) {
const { parentWorktreeId, capture } = result.lineage
console.error(
`parent: ${parentWorktreeId} (${capture.confidence} from ${getLineageSourceLabel(capture.source)})`
)
console.error(parentSummaryText(parentText, `id:${parentWorktreeId}`, capture))
return
}
console.error('parent: none')
+43 -43
View File
@@ -13,10 +13,10 @@ import { mayNameFolderWorkspace } from '../folder-workspace-selector'
import { isLocalEnvironmentSelector, LOCAL_ENVIRONMENT } from '../local-environment-selector'
import { RuntimeClient, RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
import { quoteCliCommandArgument } from '../shell-command-quote'
import { describeClientEnvironment, environmentLabel } from '../workspace-address'
import { describeClientServer, serverLabel } from '../row-owner-server'
import { attachCliErrorData } from './worktree-setup-decision-recovery'
/** The Orca a parent lives in: `local` or a saved environment's id. */
/** The server a parent lives on: `local` or a saved server's id. */
export type ParentEnvironment = { route: string; name: string }
const LOCAL: ParentEnvironment = { route: LOCAL_ENVIRONMENT, name: LOCAL_ENVIRONMENT }
@@ -36,43 +36,43 @@ function savedParentEnvironment(userDataPath: string, value: string): ParentEnvi
if (byName.length > 1) {
throw new RuntimeClientError(
'invalid_argument',
`--parent-environment ${value} is ambiguous: ${byName.length} saved environments have that name. Use the environment id.`,
{ nextSteps: byName.map((environment) => `--parent-environment ${environment.id}`) }
`--parent-server ${value} is ambiguous: ${byName.length} saved servers have that name. Use the server id.`,
{ nextSteps: byName.map((environment) => `--parent-server ${environment.id}`) }
)
}
throw new RuntimeClientError(
'environment_not_paired',
`--parent-environment ${value} is not a saved environment here, so its workspaces can't be reached from this machine.`,
'server_not_saved',
`--parent-server ${value} is not a saved server here, so its workspaces can't be reached from here.`,
{
environment: value,
knownEnvironments: saved.map(({ id, name }) => ({ id, name })),
server: value,
knownServers: saved.map(({ id, name }) => ({ id, name })),
nextSteps: [
'Pass local, or the id or name of a saved environment from `orca environment list`.',
'Pair it first with `orca environment add --name <name> --pairing-code <code>`.'
"Pass local, or a saved server's id or name from `orca server list`.",
'Save it first with `orca server add --name <name> --pairing-code <code>`.'
]
}
)
}
/**
* Which environment `--parent-worktree` names, when that differs from the child's. Undefined keeps
* same-environment parents. A caller-relative parent (active/current) is always on the caller's own
* Orca, so against another environment it is implicitly `local`.
* Which server `--parent-worktree` names, when that differs from the child's. Undefined keeps
* same-server parents. A caller-relative parent (active/current) is always on the caller's own
* Orca, so against another server it is implicitly `local`.
*/
export function resolveParentEnvironment(
flags: Map<string, string | boolean>,
client: RuntimeClient
): ParentEnvironment | undefined {
const parentSelector = getOptionalStringFlag(flags, 'parent-worktree')
const value = getOptionalStringFlag(flags, 'parent-environment')
if (flags.has('parent-environment')) {
const value = getOptionalStringFlag(flags, 'parent-server')
if (flags.has('parent-server')) {
if (value === undefined) {
throw new RuntimeClientError('invalid_argument', 'Missing required --parent-environment')
throw new RuntimeClientError('invalid_argument', 'Missing required --parent-server')
}
if (flags.get('no-parent') === true || !parentSelector) {
throw new RuntimeClientError(
'invalid_argument',
'--parent-environment says where --parent-worktree lives; pass it with --parent-worktree, not with --no-parent or alone.'
'--parent-server says which server holds --parent-worktree; pass it with --parent-worktree, not with --no-parent or alone.'
)
}
}
@@ -84,17 +84,17 @@ export function resolveParentEnvironment(
if (isCallerRelative(parentSelector) && named && named.route !== LOCAL_ENVIRONMENT) {
throw new RuntimeClientError(
'invalid_argument',
`--parent-worktree ${parentSelector} names the workspace containing this terminal or cwd, which is on this machine's own Orca, not ${named.name}.`,
`--parent-worktree ${parentSelector} names the workspace containing this terminal or cwd, which is on the Orca on this computer, not ${named.name}.`,
{
nextSteps: [
`Drop --parent-environment, or pass --parent-environment local.`,
`For a workspace in ${named.name}, list it with \`orca worktree ps --environment ${quoteCliCommandArgument(named.route)} --json\` and pass its address.worktree as --parent-worktree.`
'Drop --parent-server, or pass --parent-server local.',
`For a workspace on ${named.name}, list it with \`orca worktree ps --server ${quoteCliCommandArgument(named.route)} --json\` and pass its address.worktree as --parent-worktree.`
]
}
)
}
const parentEnvironment = named ?? (isCallerRelative(parentSelector) ? LOCAL : undefined)
return parentEnvironment && parentEnvironment.route !== describeClientEnvironment(client).id
return parentEnvironment && parentEnvironment.route !== describeClientServer(client).id
? parentEnvironment
: undefined
}
@@ -117,11 +117,11 @@ async function assertChildSavesCrossStoreParents(client: RuntimeClient): Promise
if (supportsCrossStoreLineage(status.capabilities)) {
return
}
const environment = describeClientEnvironment(client)
const server = describeClientServer(client)
throw new RuntimeClientError(
'incompatible_runtime',
`Update Orca in ${environmentLabel(environment)} to nest workspaces under a parent in another environment. Nothing was changed.`,
{ environment: environment.id, requires: WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY }
`Update Orca on ${serverLabel(server)} to nest workspaces under a parent on another server. Nothing was changed.`,
{ server: server.id, requires: WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY }
)
}
@@ -130,11 +130,11 @@ function unavailableError(error: unknown, environment: ParentEnvironment): unkno
return error
}
return new RuntimeClientError(
'environment_unavailable',
'server_unavailable',
`${environment.name} didn't answer, so the parent couldn't be checked. Nothing was changed. (${error.message})`,
{
environment: environment.route,
nextSteps: [`orca status --environment ${quoteCliCommandArgument(environment.route)} --json`]
server: environment.route,
nextSteps: [`orca status --server ${quoteCliCommandArgument(environment.route)} --json`]
}
)
}
@@ -145,7 +145,7 @@ function isParentLookupCode(code: string): code is ParentLookupCode {
return code === 'LINEAGE_PARENT_NOT_FOUND' || code === 'LINEAGE_PARENT_AMBIGUOUS'
}
/** The lineage code for a parent lookup's own error, as the runtime reports an explicit parent. */
/** The lineage code for a parent lookup's own error, as the server reports an explicit parent. */
function parentLookupCode(error: RuntimeClientError): ParentLookupCode | undefined {
if (isParentLookupCode(error.code)) {
return error.code
@@ -158,8 +158,8 @@ function parentLookupCode(error: RuntimeClientError): ParentLookupCode | undefin
}
/**
* Error data for a parent miss or ambiguity: the environment searched, and recovery that lists that
* environment. Inherited steps are dropped because they inspect the caller's default route.
* Error data for a parent miss or ambiguity: the server searched, and recovery that lists that
* server. Inherited steps are dropped because they inspect the caller's default route.
*/
function searchedEnvironmentData(
error: RuntimeClientError,
@@ -168,16 +168,16 @@ function searchedEnvironmentData(
extraSteps: readonly string[] = []
): Record<string, unknown> {
const list = environment.route
? `orca worktree ps --environment ${quoteCliCommandArgument(environment.route)} --json`
? `orca worktree ps --server ${quoteCliCommandArgument(environment.route)} --json`
: undefined
const listStep = list
? code === 'LINEAGE_PARENT_AMBIGUOUS'
? `Compare the choices with \`${list}\`, then pass one as --parent-worktree.`
: list
: 'This one-off connection has no listing route; save it with `orca environment add --name <name> --pairing-code <code>`, then run `orca worktree ps --environment <name> --json`.'
: 'This one-off connection has no listing route; save it with `orca server add --name <name> --pairing-code <code>`, then run `orca worktree ps --server <name> --json`.'
return {
...(error.data && typeof error.data === 'object' ? error.data : {}),
environment: environment.route,
server: environment.route,
nextSteps: [listStep, ...extraSteps]
}
}
@@ -192,14 +192,14 @@ function parentLookupError(error: unknown, environment: ParentEnvironment): unkn
}
const message =
code === 'LINEAGE_PARENT_NOT_FOUND'
? `No workspace in ${environment.name} matched the parent selector. Nothing was changed; no other environment was searched.`
: `${error.message} (in ${environment.name}; nothing was changed)`
? `No workspace on ${environment.name} matched the parent selector. Nothing was changed; no other server was searched.`
: `${error.message} (on ${environment.name}; nothing was changed)`
return new RuntimeClientError(code, message, searchedEnvironmentData(error, code, environment))
}
/**
* The verified ref a child saves for a parent in another environment, built as the app builds it:
* the parent store's own installationId plus the parent row's identity. No other environment is
* The verified ref a child saves for a parent on another server, built as the app builds it:
* the parent store's own installationId plus the parent row's identity. No other server is
* searched, and every check runs before the child is changed.
*/
export async function resolveCrossEnvironmentParent(
@@ -230,9 +230,9 @@ export async function resolveCrossEnvironmentParent(
if (!installationId) {
throw new RuntimeClientError(
'incompatible_runtime',
`Update Orca in ${environment.name} so workspaces in other environments can name it as a parent. Nothing was changed.`,
`Update Orca on ${environment.name} so workspaces on other servers can name it as a parent. Nothing was changed.`,
{
environment: environment.route,
server: environment.route,
requires: WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY
}
)
@@ -249,7 +249,7 @@ export async function resolveCrossEnvironmentParent(
}
}
/** Sends a create/set; a miss or ambiguity on its same-environment parent names where it looked
/** Sends a create/set; a miss or ambiguity on its same-server parent names where it looked
* and how to list it, and a miss says how to name a parent elsewhere. */
export async function callNamingParentEnvironment<
T,
@@ -274,16 +274,16 @@ export async function callNamingParentEnvironment<
throw error
}
const code = error.code
const environment = describeClientEnvironment(client)
const environment = describeClientServer(client)
throw attachCliErrorData(
error,
searchedEnvironmentData(
error,
code,
{ route: environment.id, name: environmentLabel(environment) },
{ route: environment.id, name: serverLabel(environment) },
code === 'LINEAGE_PARENT_NOT_FOUND'
? [
`Only ${environmentLabel(environment)} was searched for "${parentSelector}". For a parent in another environment, add --parent-environment <local|environment-id> (a row's address.environment from \`orca worktree ps --environment <id> --json\`).`
`Only ${serverLabel(environment)} was searched for "${parentSelector}". For a parent on another server, add --parent-server <local|server-id> (a row's address.server from \`orca worktree ps --server <id> --json\`).`
]
: []
)
+2 -2
View File
@@ -35,7 +35,7 @@ export async function requestWorktreeRemoval(
if (!parsed.success) {
throw new RuntimeClientError(
'invalid_runtime_response',
'The Orca host returned an invalid status response.'
'The Orca server returned an invalid status response.'
)
}
if (
@@ -44,7 +44,7 @@ export async function requestWorktreeRemoval(
return deleteBranch === undefined ? legacy : { ...legacy, deleteBranch }
}
console.error(
'warning: This Orca host is older and uses its existing branch policy. Keep-by-default and --delete-branch do not apply.'
'warning: This Orca server is older and uses its existing branch policy. Keep-by-default and --delete-branch do not apply.'
)
return legacy
},
+14 -7
View File
@@ -34,7 +34,12 @@ import { createWorktreeWithAgent } from './worktree-create-agent-launch'
import { printLineageSummary, printSetParentLine } from './worktree-lineage-summary'
import { resolveCreateParentFields, resolveSetParentFields } from './worktree-parent-fields'
import { callNamingParentEnvironment } from './worktree-parent-environment'
import { annotatePsRows, annotateShown } from './worktree-address-annotation'
import {
annotateMutationResult,
annotatePsRows,
annotateShown
} from './worktree-address-annotation'
import { readOwnerContext } from '../row-owner-server'
import { refuseCurrentForRemoval } from './worktree-removal-current-refusal'
import { projectWorktreePsTerminalVerdict } from '../worktree-ps-terminal-verdict'
import {
@@ -101,7 +106,7 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
}
)
await annotateOmittedHostScope(result.result)
printResult(result, json, formatWorktreeList)
printResult(result, json, (value) => formatWorktreeList(value, readOwnerContext(client)))
},
'worktree show': async ({ flags, client, cwd, json }) => {
const result = await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
@@ -204,11 +209,12 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
await createWorktreeWithAgent({ client, flags, create, launch: agentLaunch, json, rawArgs })
return
}
const result = await withSetupDecisionRecovery(
const created = await withSetupDecisionRecovery(
callNamingParentEnvironment<RuntimeWorktreeCreateResult>(client, 'worktree.create', create)
)
const { response: result, parentText } = await annotateMutationResult(client, created)
printHookWarning(result.result, json)
printLineageSummary(result.result, json)
printLineageSummary(result.result, json, parentText)
printResult(result, json, formatWorktreeShow)
},
'worktree set': async ({ flags, client, cwd, json }) => {
@@ -240,7 +246,7 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
...parentFields,
noParent: flags.get('no-parent') === true
})
const result = await withWorktreeSelectorRecovery(
const updated = await withWorktreeSelectorRecovery(
pending,
parentSelector
? [
@@ -249,11 +255,12 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
]
: []
)
const { response: result, parentText } = await annotateMutationResult(client, updated)
if (!json) {
for (const warning of result.result.warnings ?? []) {
console.error(`warning: ${warning.message}`)
}
printSetParentLine(result.result.worktree, parentFields)
printSetParentLine(result.result.worktree, parentFields, parentText)
}
printResult(result, json, formatWorktreeShow)
},
@@ -270,7 +277,7 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
if (!hostId) {
throw new RuntimeClientError(
'worktree_host_unresolved',
'Orca cannot tell which host owns this workspace. Refresh projects and try again.'
'Orca cannot tell which server owns this workspace. Refresh projects and try again.'
)
}
if (flags.get('allow-failed-archive-hook') === true && flags.get('run-hooks') !== true) {
+4 -3
View File
@@ -1,6 +1,7 @@
import type { CommandSpec } from './args'
import { findCommandSpec, isCommandGroup, matches, supportsBrowserPageFlag } from './args'
import { unknownCommandData } from './command-suggestion'
import { INPUT_ONLY_FLAGS } from './command-spec'
import { formatCommandScopedFlagHelp } from './command-scoped-flag-help'
import { FLAG_HELP_TEXT } from './flag-help-text'
import { ROOT_HELP_TEXT_PRIMARY } from './root-help-text-primary'
@@ -34,9 +35,9 @@ export function formatCommandHelp(spec: CommandSpec): string {
const displayedFlags =
spec.argumentMode === 'passthrough'
? []
: supportsBrowserPageFlag(spec)
? [...spec.allowedFlags, 'page']
: spec.allowedFlags
: (supportsBrowserPageFlag(spec) ? [...spec.allowedFlags, 'page'] : spec.allowedFlags).filter(
(flag) => !INPUT_ONLY_FLAGS.has(flag)
)
if (displayedFlags.length > 0) {
lines.push('', 'Options:')
+14 -14
View File
@@ -1,31 +1,31 @@
import type { HandlerGroup } from './handler-group-manifest'
// The machines Orca reaches: saved hosts and paired environments, the Orca servers it manages on
// them, and recipe VMs.
// The Orca servers this computer reaches: saved servers, the servers it manages over SSH, its SSH
// connections, and recipe VMs.
export const HOST_HANDLER_GROUPS: readonly HandlerGroup[] = [
{
name: 'environment',
keys: [
'host name',
'server name',
'host list',
'host rm',
'environment add',
'environment list',
'environment show',
'environment rm'
'server add',
'server list',
'server show',
'server rm'
],
load: async () => (await import('./handlers/environment.js')).ENVIRONMENT_HANDLERS
},
{
name: 'managed-server',
keys: [
'environment status',
'environment update',
'environment rollback',
'environment recover',
'environment stop',
'environment cancel-stop',
'environment forget'
'server status',
'server update',
'server rollback',
'server recover',
'server stop',
'server cancel-stop',
'server forget'
],
load: async () => (await import('./handlers/managed-server.js')).MANAGED_SERVER_HANDLERS
},
+14 -22
View File
@@ -48,18 +48,17 @@ describe('findEnvironmentByName', () => {
describe('crossKindNextSteps', () => {
const alternatives = { sshTargets: SSH_TARGETS, environments: ENVIRONMENTS }
it('points an SSH name at the SSH flag when a server was asked for', () => {
const steps = crossKindNextSteps('openclaw', alternatives, 'environment')
it('never offers an SSH connection as a place to run', () => {
const steps = crossKindNextSteps('openclaw', alternatives, 'server')
expect(steps.join('\n')).toContain('--host ssh:ssh-1755000000000-a1b2c3')
expect(steps.join('\n')).toContain('is an SSH target')
expect(steps.join('\n')).toContain('`orca server list`')
expect(steps.join('\n')).not.toContain('--host')
})
it('points a server name at --environment when an SSH target was asked for', () => {
it('points a server name at --server <id> when an SSH target was asked for', () => {
const steps = crossKindNextSteps('awin', alternatives, 'ssh')
expect(steps.join('\n')).toContain('--environment awin')
expect(steps.join('\n')).toContain('is a paired Orca server')
expect(steps.join('\n')).toContain('--server 03ef704c-b180-4b10-998d-e28fbd5de9a3')
})
it('says nothing when the name exists on neither axis', () => {
@@ -68,7 +67,7 @@ describe('crossKindNextSteps', () => {
it('does not suggest the axis that was already requested', () => {
expect(crossKindNextSteps('openclaw', alternatives, 'ssh')).toEqual([])
expect(crossKindNextSteps('awin', alternatives, 'environment')).toEqual([])
expect(crossKindNextSteps('awin', alternatives, 'server')).toEqual([])
})
})
@@ -94,19 +93,12 @@ describe('resolveSshHostTargetId', () => {
).rejects.toMatchObject({
code: 'invalid_argument',
data: {
nextSteps: expect.arrayContaining([expect.stringContaining('--environment awin')])
nextSteps: expect.arrayContaining([
expect.stringContaining('--server 03ef704c-b180-4b10-998d-e28fbd5de9a3')
])
}
})
})
it('says so plainly when the host has no SSH targets at all', async () => {
await expect(
resolveSshHostTargetId(clientReturning([]), 'openclaw', ENVIRONMENTS)
).rejects.toMatchObject({
code: 'invalid_argument',
data: { nextSteps: expect.arrayContaining(['This Orca host has no SSH targets registered.']) }
})
})
})
describe('listSshTargets', () => {
@@ -188,10 +180,10 @@ describe('ambiguous names never resolve silently', () => {
).rejects.toMatchObject({
code: 'invalid_argument',
data: {
nextSteps: expect.arrayContaining([
expect.stringContaining('ssh-1-a'),
expect.stringContaining('ssh-2-b')
])
knownSshTargets: [
expect.objectContaining({ id: 'ssh-1-a' }),
expect.objectContaining({ id: 'ssh-2-b' })
]
}
})
})
+15 -16
View File
@@ -72,23 +72,24 @@ export function ambiguousEnvironments(
return byName.length > 1 ? byName : []
}
/** SSH is how a server is set up, never a place to run; Orca does not guess which server it hosts. */
export function sshConnectionStep(name: string): string {
return `"${name}" is an SSH connection, not a server. If Orca runs a server there, it is in \`orca server list\`; otherwise set it up in Settings → SSH Hosts.`
}
export function crossKindNextSteps(
name: string,
alternatives: HostAlternatives,
requested: 'environment' | 'ssh'
requested: 'server' | 'ssh'
): string[] {
const steps: string[] = []
const ssh = findSshTargetByName(alternatives.sshTargets, name)
const environment = findEnvironmentByName(alternatives.environments, name)
const server = findEnvironmentByName(alternatives.environments, name)
if (requested !== 'ssh' && ssh) {
steps.push(
`"${name}" is an SSH target on this Orca host, not a paired server. Use --host ssh:${ssh.id}.`
)
steps.push(sshConnectionStep(name))
}
if (requested !== 'environment' && environment) {
steps.push(
`"${name}" is a paired Orca server, not an SSH target. Use --environment ${environment.name}.`
)
if (requested !== 'server' && server) {
steps.push(`"${name}" is a saved server, not an SSH connection. Use --server ${server.id}.`)
}
return steps
}
@@ -167,23 +168,21 @@ export async function resolveSshHostTargetId(
`Ambiguous SSH target in ${flagSpelling}: ${ambiguous.length} targets share that label. Use the target id.`,
{
knownSshTargets: ambiguous,
nextSteps: ambiguous.map((target) => `Use --host ssh:${target.id} for ${target.label}.`)
nextSteps: [sshConnectionStep(targetId)]
}
)
}
throw new RuntimeClientError(
'invalid_argument',
bareName
? `Unknown host in ${flagSpelling}: it is not this machine or a paired Orca server the command can use, and the connected Orca host has no SSH target named ${targetId}. Run \`orca host list\` to see every name.`
: `Unknown SSH target in ${flagSpelling}: this Orca host has no SSH target named or with id ${targetId}.`,
? `Unknown name in ${flagSpelling}: it is not this computer, a saved server, or an SSH connection of the answering server.`
: `Unknown SSH target in ${flagSpelling}: the answering Orca server has no SSH target named or with id ${targetId}.`,
{
knownSshTargets: targets,
knownEnvironments: environments,
knownServers: environments,
nextSteps: [
...crossKindNextSteps(targetId, { sshTargets: targets, environments }, 'ssh'),
...(targets.length > 0
? [`Known SSH targets: ${targets.map((target) => target.label).join(', ')}.`]
: ['This Orca host has no SSH targets registered.'])
'To run on another server, use --server <id>; `orca server list` prints each id.'
]
}
)
+2 -2
View File
@@ -56,7 +56,7 @@ describe('orca cli worktree awareness', () => {
spawnMock
})
it('lists saved environments even when ORCA_ENVIRONMENT is set', async () => {
it('lists saved servers under the old spelling even when ORCA_ENVIRONMENT is set', async () => {
process.env.ORCA_ENVIRONMENT = 'stale-env'
listEnvironmentsMock.mockReturnValue([addEnvironmentFromPairingCodeMock()])
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
@@ -68,7 +68,7 @@ describe('orca cli worktree awareness', () => {
expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toMatchObject({
ok: true,
result: {
environments: [
servers: [
{
id: 'env-1',
name: 'desk',
+38 -6
View File
@@ -90,7 +90,23 @@ describe('--environment local and workspace addresses', () => {
[['worktree', 'ps', '--pairing-code', 'orca://pair?code=x', '--environment', 'local']],
[['worktree', 'ps', '--host', 'runtime:srv-b', '--environment', 'local']],
[['environment', 'add', '--name', ' Local ', '--pairing-code', 'orca://pair?code=x']],
[['environment', 'stop', '--environment', 'local']]
[['environment', 'stop', '--environment', 'local']],
[['server', 'stop', '--server', 'local']],
[['worktree', 'ps', '--environment', 'srv-b', '--server', 'build-box']],
[
[
'worktree',
'create',
'--name',
'child',
'--parent-worktree',
'folder:hub-a',
'--parent-environment',
'local',
'--parent-server',
'srv-b'
]
]
])('refuses %j before any request', async (args) => {
listEnvironmentsMock.mockReturnValue(SAVED)
const { exitCode, output } = await run([...args, '--json'])
@@ -98,11 +114,27 @@ describe('--environment local and workspace addresses', () => {
expect(JSON.parse(output).error.code).toBe('invalid_argument')
expect(callMock).not.toHaveBeenCalled()
expect(addEnvironmentFromPairingCodeMock).not.toHaveBeenCalled()
if (args[0] === 'environment' && args[1] === 'stop') {
expect(output).toContain('--environment srv-old')
if (args[1] === 'stop') {
expect(output).toContain('--server srv-old')
}
})
it('accepts both spellings when they name the same server', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
callMock.mockResolvedValue(okFixture('ps', { worktrees: [], totalCount: 0, truncated: false }))
const { exitCode } = await run([
'worktree',
'ps',
'--environment',
'srv-b',
'--server',
'srv-b',
'--json'
])
expect(exitCode).toBeUndefined()
expect(runtimeClientConstructorMock).toHaveBeenLastCalledWith(undefined, 'srv-b')
})
it('refuses current against another environment with an inspection command', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const { exitCode, output } = await run([
@@ -114,7 +146,7 @@ describe('--environment local and workspace addresses', () => {
])
expect(exitCode).toBe(1)
expect(JSON.parse(output).error.data.nextSteps[0]).toContain(
'`orca worktree ps --environment srv-b --json`'
'`orca worktree ps --server srv-b --json`'
)
expect(callMock).not.toHaveBeenCalled()
})
@@ -146,7 +178,7 @@ describe('--environment local and workspace addresses', () => {
expect(exitCode).toBeUndefined()
expect(callMock).toHaveBeenCalledWith('worktree.show', { worktree: 'folder:hub-a' })
expect(JSON.parse(output).result.worktree.address.line).toBe(
'--environment local --worktree folder:hub-a'
'--server local --worktree folder:hub-a'
)
vi.unstubAllEnvs()
})
@@ -309,7 +341,7 @@ describe('worktree rm needs an explicit workspace', () => {
])
expect(exitCode).toBe(1)
expect(JSON.parse(output).error.data.nextSteps[0]).toContain(
'`orca worktree ps --environment srv-b --json`'
'`orca worktree ps --server srv-b --json`'
)
expect(callMock).not.toHaveBeenCalled()
})
@@ -141,8 +141,8 @@ describe('--parent-environment', () => {
expect(exitCode).toBe(1)
const error = JSON.parse(output).error
expect(error.code).toBe('LINEAGE_PARENT_NOT_FOUND')
expect(error.data.environment).toBe('srv-b')
expect(error.data.nextSteps.join('\n')).toContain('--parent-environment')
expect(error.data.server).toBe('srv-b')
expect(error.data.nextSteps.join('\n')).toContain('--parent-server')
expect(new Set(calls.map((call) => call.environment))).toEqual(new Set(['srv-b']))
})
@@ -198,10 +198,10 @@ describe('--parent-environment', () => {
'folder:hub-a'
]
const cases: [string, string, Answer][] = [
['srv-z', 'environment_not_paired', FOLDER_PARENT],
['srv-z', 'server_not_saved', FOLDER_PARENT],
[
'srv-c',
'environment_unavailable',
'server_unavailable',
({ environment }) =>
environment === 'srv-c'
? new RuntimeClientError('remote_runtime_unavailable', 'Could not connect.')
@@ -229,7 +229,7 @@ describe('--parent-environment', () => {
const { output } = await run(setOnB(parentEnvironment))
expect(JSON.parse(output).error.code, parentEnvironment).toBe(code)
expect(calls.filter((call) => MUTATIONS.has(call.method))).toEqual([])
if (code === 'environment_not_paired') {
if (code === 'server_not_saved') {
expect(calls).toEqual([])
}
}
@@ -269,13 +269,13 @@ describe('--parent-environment', () => {
const { output } = await run([...command, ...parent])
const error = JSON.parse(output).error
expect(error.code, command[1]).toBe('LINEAGE_PARENT_AMBIGUOUS')
expect(error.data.environment).toBe('srv-b')
expect(error.data.server).toBe('srv-b')
expect(error.data.candidates).toEqual([
{ selector: 'folder:one' },
{ selector: 'folder:two' }
])
expect(error.data.nextSteps).toEqual([
'Compare the choices with `orca worktree ps --environment srv-b --json`, then pass one as --parent-worktree.'
'Compare the choices with `orca worktree ps --server srv-b --json`, then pass one as --parent-worktree.'
])
}
})
+16 -10
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env node
import {
canonicalizeLegacyFlagArgv,
findCommandSpec,
isCommandGroup,
normalizeCommandPositionals,
@@ -97,6 +98,11 @@ export async function main(
return
}
const json = parsed.flags.has('json')
// Passthrough argv belongs to another program; everything else is echoed in canonical spelling.
const echoedArgv =
findCommandSpec(COMMAND_SPECS, parsed.commandPath)?.argumentMode === 'passthrough'
? argv
: canonicalizeLegacyFlagArgv(argv)
try {
// Report invalid commands before runtime lookup can mask them with connection errors.
@@ -107,27 +113,27 @@ export async function main(
const RuntimeClientClass = await loadRuntimeClientClass()
const ignoreRemoteSelection = ignoresRemoteSelection(parsed.commandPath)
const pairingCode = ignoreRemoteSelection ? null : parsed.flags.get('pairing-code')
const environmentSelector = ignoreRemoteSelection ? null : parsed.flags.get('environment')
const environmentSelector = ignoreRemoteSelection ? null : parsed.flags.get('server')
// An explicit local route suppresses ambient ORCA_ENVIRONMENT and pairing codes.
const explicitLocal = isLocalEnvironmentSelector(environmentSelector)
if (explicitLocal && typeof pairingCode === 'string') {
throw new RuntimeClientError(
'invalid_argument',
'Use either --pairing-code or --environment, not both.'
'Use either --pairing-code or --server, not both.'
)
}
// Eagerly resolve explicit --environment; stale ambient config must not break local-only commands.
// Eagerly resolve explicit --server; stale ambient config must not break local-only commands.
const listSshTargetsForSuggestion = async (): Promise<{ id: string; label: string }[]> =>
listSshTargets(new RuntimeClientClass(undefined, undefined, null, null))
const storeEnvironmentSelector =
typeof environmentSelector === 'string' && !explicitLocal
? await resolveEnvironmentSelectorForStore(environmentSelector, listSshTargetsForSuggestion)
: null
// Select the paired connection before constructing the client; reject conflicting environments.
// Select the saved connection before constructing the client; reject conflicting servers.
const hostEnvironmentId = ignoreRemoteSelection
? null
: await resolveHostFlagEnvironmentId(parsed.flags, {
// SSH targets belong to this machine, even when the missing name was a paired server.
// SSH targets belong to this computer, even when the missing name was a saved server.
listSshTargets: listSshTargetsForSuggestion,
verifySshTargets: async () =>
(
@@ -138,7 +144,7 @@ export async function main(
pairingCode: typeof pairingCode === 'string' ? pairingCode : null,
environmentSelector:
typeof environmentSelector === 'string'
? { value: environmentSelector, label: '--environment' }
? { value: environmentSelector, label: '--server' }
: process.env.ORCA_ENVIRONMENT
? { value: process.env.ORCA_ENVIRONMENT, label: 'ORCA_ENVIRONMENT' }
: null
@@ -164,13 +170,13 @@ export async function main(
remotePairingCode,
remoteEnvironment,
resolveOrchestrationCliExecutable(),
argv
echoedArgv
)
return client
},
cwd,
json,
rawArgs: argv
rawArgs: echoedArgv
})
} catch (error) {
const worktreeSelector = parsed.flags.get('worktree')
@@ -181,8 +187,8 @@ export async function main(
...(typeof worktreeSelector === 'string' ? { worktreeSelector } : {}),
...(typeof repoSelector === 'string' ? { repoSelector } : {}),
remoteServerSelected:
!isLocalEnvironmentSelector(parsed.flags.get('environment')) &&
(parsed.flags.has('environment') ||
!isLocalEnvironmentSelector(parsed.flags.get('server')) &&
(parsed.flags.has('server') ||
parsed.flags.has('pairing-code') ||
(typeof hostFlag === 'string' && hostFlag.startsWith('runtime:')) ||
Boolean(process.env.ORCA_ENVIRONMENT?.trim() || process.env.ORCA_PAIRING_CODE?.trim())),
+1 -1
View File
@@ -39,7 +39,7 @@ export async function resolveJiraTarget(
if (!runtime.result.capabilities?.includes(JIRA_AGENT_ACCESS_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'Update Orca on the execution host to use verified Jira commands.'
'Update Orca on that server to use verified Jira commands.'
)
}
const { result: status } = await context.client.call<JiraConnectionStatus>('jira.status')
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest'
import {
canonicalizeLegacyFlagArgv,
normalizeCommandPositionals,
parseArgs,
validateCommandAndFlags
} from './args'
import { unknownCommandData } from './command-suggestion'
import { ignoresRemoteSelection } from './remote-selection-scope'
import { COMMAND_SPECS } from './specs'
function normalize(argv: string[]) {
return normalizeCommandPositionals(COMMAND_SPECS, parseArgs(argv, undefined, COMMAND_SPECS))
}
describe('old server spellings are input only', () => {
it('routes the old command and flag to the same handler and flag as the new ones', () => {
const legacy = normalize(['environment', 'stop', '--environment', 'srv-b', '--yes'])
const current = normalize(['server', 'stop', '--server', 'srv-b', '--yes'])
expect(legacy.commandPath).toEqual(['server', 'stop'])
expect(Object.fromEntries(legacy.flags)).toEqual(Object.fromEntries(current.flags))
expect(normalize(['host', 'name']).commandPath).toEqual(['server', 'name'])
expect(normalize(['environment']).commandPath).toEqual(['server'])
})
it('accepts both spellings only when their values are equal', () => {
const same = normalize(['worktree', 'ps', '--environment', 'srv-b', '--server', 'srv-b'])
expect(() => validateCommandAndFlags(COMMAND_SPECS, same)).not.toThrow()
expect(same.flags.get('server')).toBe('srv-b')
for (const argv of [
['worktree', 'ps', '--environment', 'srv-a', '--server', 'srv-b'],
[
'worktree',
'set',
'--worktree',
'id:x',
'--parent-worktree',
'id:y',
'--parent-environment',
'local',
'--parent-server',
'srv-b'
]
]) {
expect(() => validateCommandAndFlags(COMMAND_SPECS, normalize(argv))).toThrow(
expect.objectContaining({ code: 'invalid_argument' })
)
}
})
it('suggests and echoes only the new names', () => {
const { suggestions } = unknownCommandData(COMMAND_SPECS, ['environment', 'stp'])
expect(suggestions).toContain('server stop')
expect(suggestions.filter((path) => !path.startsWith('server '))).toEqual([])
expect(
canonicalizeLegacyFlagArgv([
'plugin',
'list',
'--environment=box',
'--parent-environment',
'x'
])
).toEqual(['plugin', 'list', '--server=box', '--parent-server', 'x'])
})
it('routes `server name` but keeps saved-server management on this computer', () => {
expect(ignoresRemoteSelection(['server', 'name'])).toBe(false)
expect(ignoresRemoteSelection(['server', 'list'])).toBe(true)
})
})
+18 -13
View File
@@ -3,7 +3,7 @@ import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import { quoteCliCommandArgument } from './shell-command-quote'
/** `--environment local`: the caller's own Orca, even over an ambient ORCA_ENVIRONMENT or pairing code. */
/** `--server local`: the caller's own Orca, even over an ambient ORCA_ENVIRONMENT or pairing code. */
export const LOCAL_ENVIRONMENT = 'local'
export function isLocalEnvironmentSelector(value: unknown): value is string {
@@ -21,24 +21,29 @@ export async function savedEnvironmentNamedLocal(): Promise<{ id: string } | und
)
}
/** `orca environment …` takes --environment as a saved entry to act on; local is not one. */
/** `orca server …` management commands act on a saved entry named by --server; `server name` is routed. */
export function isServerManagementCommand(commandPath: readonly string[]): boolean {
return commandPath[0] === 'server' && commandPath[1] !== 'name'
}
/** Management commands take --server as a saved entry to act on; local is not one. */
export async function refuseLocalManagementSelector(
commandPath: readonly string[],
flags: Map<string, string | boolean>
): Promise<void> {
if (commandPath[0] !== 'environment' || !isLocalEnvironmentSelector(flags.get('environment'))) {
if (!isServerManagementCommand(commandPath) || !isLocalEnvironmentSelector(flags.get('server'))) {
return
}
const named = await savedEnvironmentNamedLocal()
throw new RuntimeClientError(
'invalid_argument',
`--environment local names this machine's own Orca, not a saved environment, so \`orca ${commandPath.join(' ')}\` cannot act on it.`,
`--server local is the Orca on this computer, not a saved server, so \`orca ${commandPath.join(' ')}\` can't act on it.`,
{
nextSteps: [
...(named
? [`A saved environment named local is reached by its id: --environment ${named.id}.`]
? [`A saved server named local is reached by its id: --server ${named.id}.`]
: []),
'Run `orca environment list` to see saved environments.'
'Run `orca server list` to see saved servers.'
]
}
)
@@ -48,7 +53,7 @@ export function refuseReservedEnvironmentName(name: string): void {
if (isLocalEnvironmentSelector(name)) {
throw new RuntimeClientError(
'invalid_argument',
'`local` is reserved: --environment local always means this machine’s own Orca. Save the environment under another name.'
'`local` is reserved: --server local always means the Orca on this computer. Save the server under another name.'
)
}
}
@@ -59,16 +64,16 @@ export function assertLocalCwdWorktreeSelector(selector: string, client: Runtime
return
}
// A paired CLI's cwd belongs to the client filesystem, so it cannot identify server worktrees.
const environment = client.environmentSelector
const server = client.environmentSelector
throw new RuntimeClientError(
'invalid_argument',
`${selector} is a local cwd shortcut and cannot be resolved against a remote runtime. Pass an explicit server-side worktree selector such as identity:<identity>, id:<repo-id>::<path>, folder:<id>, name:<displayName>, branch:<branch>, issue:<number>, or path:<absolute-server-path>.`,
`${selector} is a cwd shortcut and resolves only on the Orca on this computer. Pass an explicit server-side worktree selector such as identity:<identity>, id:<repo-id>::<path>, folder:<id>, name:<displayName>, branch:<branch>, issue:<number>, or path:<absolute-server-path>.`,
{
nextSteps: [
environment
? `List that environment's workspaces: \`orca worktree ps --environment ${quoteCliCommandArgument(environment)} --json\`, then copy a row's address.`
: 'Save this connection with `orca environment add --name <name> --pairing-code <code>`, then list its workspaces with `orca worktree ps --environment <name> --json`.',
`For this machine's own workspace, rerun with --environment local.`
server
? `List that server's workspaces: \`orca worktree ps --server ${quoteCliCommandArgument(server)} --json\`, then copy a row's address.`
: 'Save this connection with `orca server add --name <name> --pairing-code <code>`, then list its workspaces with `orca worktree ps --server <name> --json`.',
'For a workspace on this computer, rerun with --server local.'
]
}
)
+8 -7
View File
@@ -5,14 +5,15 @@ import {
} from '../shared/execution-host'
import type { RuntimeListingHostScope } from '../shared/runtime-listing-host-scope'
import { findEnvironmentByName } from './host-selector-alternatives'
import { quoteCliCommandArgument } from './shell-command-quote'
export type OmittedHostScopeSelector = {
hostId: ExecutionHostId
/** null means this machine has no selector for the omitted host. */
/** null means this computer has no selector for the omitted host. */
selector: string | null
}
/** omittedHostSelectors is added locally, never sent by the runtime. */
/** omittedHostSelectors is added locally, never sent by the server. */
export type ListingHostScopeWithSelectors = RuntimeListingHostScope & {
omittedHostSelectors?: OmittedHostScopeSelector[]
}
@@ -56,16 +57,16 @@ function resolveSelector(
): string | null {
if (host?.kind === 'runtime') {
const environment = findEnvironmentByName(environments, host.environmentId)
return environment ? `--environment ${environment.name}` : null
return environment ? `--server ${quoteCliCommandArgument(environment.id)}` : null
}
// Listings take no --host flag; local and SSH hosts are reached through the answering runtime.
// Listings take no --host flag; local and SSH hosts are reached through the answering server.
return null
}
/** An absent scope means coverage is unknown. */
export function formatListingHostScope(scope: ListingHostScopeWithSelectors | undefined): string {
if (!scope) {
return 'scope: unverifiable — this host does not report which hosts it lists'
return 'scope: unverifiable — this server does not report what it lists'
}
const covered = scope.hostIds.length > 0 ? scope.hostIds.join(', ') : 'none'
if (scope.omittedHostIds.length === 0) {
@@ -84,8 +85,8 @@ export function formatListingHostScope(scope: ListingHostScopeWithSelectors | un
}
const kind = parseExecutionHostId(hostId)?.kind
return kind === 'local' || kind === 'ssh'
? `${hostId} (reached through this runtime; no flag selects it)`
: `${hostId} (not selectable from this machine)`
? `${hostId} (reached through this server; no flag selects it)`
: `${hostId} (not reachable from here)`
})
return `scope: ${covered} — not covered: ${omitted.join(', ')}`
}
@@ -19,7 +19,7 @@ export function requirePluginPathArg(ctx: HandlerContext, flag: string): string
/**
* Authoring commands read and write the files of the machine that runs them. Why refuse a bridged
* shell: there the CLI runs on the Orca host, so the caller's paths would name the wrong machine.
* shell: there the CLI runs on the Orca server, so the caller's paths would name the wrong machine.
*/
export function resolveLocalPluginPath(
ctx: HandlerContext,
@@ -30,7 +30,7 @@ export function resolveLocalPluginPath(
if (process.env.ORCA_CLI_CWD) {
throw new RuntimeClientError(
'invalid_environment',
`orca plugin ${command} works on the files of the machine that runs it, but this shell forwards orca to the Orca host. Write and check the plugin files on this machine directly, or run the command on the Orca host.`
`orca plugin ${command} works on the files of the machine that runs it, but this shell forwards orca to the Orca server. Write and check the plugin files on this machine directly, or run the command on the Orca server.`
)
}
return isAbsolute(value) ? value : resolve(ctx.cwd, value)
@@ -18,7 +18,7 @@ import {
type PluginDevWatchShotHost
} from './plugin-dev-watch-shot'
/** What the loop asks of the Orca host; the handler binds it to RPC for one folder. */
/** What the loop asks of the Orca server; the handler binds it to RPC for one folder. */
export type PluginDevWatchHost = {
refreshTypes(): Promise<string[]>
/** `approvalFingerprint` overrides `--approve` once the person approved at the prompt. */
@@ -15,7 +15,7 @@ export type PluginDevWatchShot = {
pendingRequests?: number
}
/** What `--shot` asks of the Orca host; the handler binds it to RPC. */
/** What `--shot` asks of the Orca server; the handler binds it to RPC. */
export type PluginDevWatchShotHost = {
/** `--shot-panel`, else the plugin's first panel; null when it has none. Throws on an unknown id. */
panelOf(entry: PluginHostListEntry | null): string | null
+1 -1
View File
@@ -1,6 +1,6 @@
import type { HandlerGroup } from './handler-group-manifest'
// Authoring runs offline; runtime commands reach the Orca host. Split so authoring never loads the RPC graph.
// Authoring runs offline; runtime commands reach the Orca server. Split so authoring never loads the RPC graph.
export const PLUGIN_HANDLER_GROUPS: readonly HandlerGroup[] = [
{
name: 'plugin-authoring',
+3 -5
View File
@@ -47,14 +47,12 @@ export function formatPortsScan(
scan: WorkspacePortHostScanResult,
options: { showOwner: boolean }
): string {
const host = `host=${scan.executionHostId}`
if (scan.unavailableReason) {
return `Port scan unavailable: ${scan.unavailableReason}\n${host}`
return `Port scan unavailable: ${scan.unavailableReason}`
}
if (scan.ports.length === 0) {
return `No listening ports found.\n${host}`
return 'No listening ports found.'
}
const ambiguousNames = options.showOwner ? findAmbiguousOwnerNames(scan.ports) : null
const rows = scan.ports.map((port) => formatPortRow(port, ambiguousNames))
return `${rows.join('\n')}\n\n${host}`
return scan.ports.map((port) => formatPortRow(port, ambiguousNames)).join('\n')
}
+6 -2
View File
@@ -1,3 +1,4 @@
import { ownerTokenOf, type OwnerContext } from './row-owner-server'
import type {
Project,
ProjectHostSetup,
@@ -21,14 +22,17 @@ export function formatProjectList(result: { projects: Project[] }): string {
.join('\n')
}
export function formatProjectHostSetupList(result: { setups: ProjectHostSetup[] }): string {
export function formatProjectHostSetupList(
result: { setups: ProjectHostSetup[] },
owners?: OwnerContext
): string {
if (result.setups.length === 0) {
return 'No project host setups found.'
}
return result.setups
.map(
(setup) =>
`${setup.id} project:${setup.projectId} host:${setup.hostId} ${setup.setupState} ${setup.path}`
`${setup.id} project:${setup.projectId}${ownerTokenOf(setup.hostId, owners)} ${setup.setupState} ${setup.path}`
)
.join('\n')
}
+1 -1
View File
@@ -97,7 +97,7 @@ export async function assertReferenceWritesSupported(client: RuntimeClient): Pro
if (!status.result.capabilities?.includes(WORKTREE_LINKED_ITEMS_DELTA_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host cannot merge reference changes safely. Update Orca on the execution host.'
'This Orca server cannot merge reference changes safely. Update Orca on that server.'
)
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { RuntimeClientError } from './runtime/types'
// Local-only command families reject explicit runtime selectors rather than silently ignoring them.
export const REMOTE_SELECTION_FLAGS = ['environment', 'pairing-code'] as const
// Local-only command families reject explicit server selectors rather than silently ignoring them.
export const REMOTE_SELECTION_FLAGS = ['server', 'pairing-code'] as const
/** suffix completes "--<flag> does not retarget …" with the command's actual scope. */
export function rejectRemoteSelectionFlags(

Some files were not shown because too many files have changed in this diff Show More