Files
orca/src/cli/execution-host-flag.ts
T
Neil 9d1dfc314f fix(cli): resolve host names across both kinds, and stop ssh: answering empty (#15449)
* fix(cli): resolve host names across both kinds, and stop ssh: answering empty

`--host ssh:<id>` was never validated. An unknown target filtered to nothing and
returned ok:true with an empty list — the same silent wrong-machine answer that
unknown `runtime:` ids gave before they were rejected. And because SSH target
ids are machine-generated (`ssh-<timestamp>-<random>`) while the name anyone
actually knows is the label, this fired on the ordinary spelling rather than a
rare typo: every human-typed SSH name missed.

The two kinds of remote machine are also reached on different axes. A paired
Orca server is a connection (`--environment <name>`); an SSH target is a machine
the connected host reaches (`--host ssh:<id>`). A caller only knows "the machine
called X", so naming X on the wrong axis was the common failure and produced
either an empty answer or a dead-end "unknown environment".

Now: `ssh:` resolves labels as well as ids and rejects an unknown target with the
known ones listed; `runtime:` accepts the environment name as well as its id,
matching --environment, and canonicalizes to the id so stored host ids still
compare; and when a name misses on one axis but exists on the other, the error
says which and gives the exact flag. Candidates ride along in error.data so an
agent can recover without parsing prose.

`orca host list` is the discovery surface that was missing entirely — nothing in
the CLI listed SSH targets, so a caller told to use one had nowhere to look. It
prints this machine, the SSH targets registered on the connected host, and the
paired servers, each with the selector to use.

* fix(cli): give --environment the same cross-kind hint, and validate the ssh host on setup-create

Two gaps a follow-up survey found in the first pass.

`--environment openclaw` still dead-ended with a bare "Unknown environment"
while an SSH target by that name sat right there — the inverse of the case just
fixed, and the direction the report actually hit. The store's own error cannot
carry the hint: translateStoreError forwards code and message and drops data. So
the selector is resolved before the client is built, where the payload survives.
Only the explicit flag is asserted eagerly; an ambient ORCA_ENVIRONMENT stays
lazy, because failing local-only commands over stale background config would be
a regression.

`project setup-create` records independent metadata and, unlike the other setup
paths, is not covered by the runtime's ssh rejection — so an unknown target
persisted a row pointing at a machine that does not exist. It now resolves the
host. `local` and `runtime:` still pass through untouched: this is also the
provisioning path, where a runtime host legitimately may not exist yet when its
metadata is written.

`setup-existing-folder` and `setup-clone` deliberately keep the unresolved id.
The runtime rejects every ssh host for those operations regardless of whether it
exists, so resolving first would answer "no such target" and imply the command
would have worked with the right id.

* fix(cli): refuse an ambiguous host name instead of resolving the first match

Name lookup took the first match while the environment store itself refuses an
ambiguous name rather than guessing. That put the guess back, in the selector
whose entire purpose is to stop a command reaching a machine the caller did not
choose — and it applied to both spellings: two SSH targets sharing a label, and
two paired servers sharing a name.

Both now resolve to nothing and report every candidate with its id, so the
caller picks. An exact id still resolves past a colliding name, since an id is
never ambiguous.

Also pins the property that makes accepting a name safe at all: `runtime:<id>`
is a persisted token that lands in ProjectHostSetup.hostId and is embedded in
generated setup ids, so the name is canonicalized to the id before anything
downstream sees it. A test now asserts a name never reaches the wire.

* fix(cli): fall back to the older ssh listing so an old host is not read as having no targets

Hosts predating ssh.listTargetSummaries still answer ssh.listTargets, and both
are served by the same summariser. Swallowing the method_not_found made such a
host indistinguishable from one with no SSH targets registered, which would
reject a target id that is valid there — a new-client/old-host regression on a
path that previously passed the id through unvalidated.
2026-08-19 17:20:21 -07:00

208 lines
8.4 KiB
TypeScript

import {
LOCAL_EXECUTION_HOST_ID,
normalizeExecutionHostId,
parseExecutionHostId,
toSshExecutionHostId,
type ParsedExecutionHost
} from '../shared/execution-host'
import {
ambiguousEnvironments,
crossKindNextSteps,
findEnvironmentByName,
resolveSshHostTargetId,
type SshTargetSummary
} from './host-selector-alternatives'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
export type HostFlagRoutingSelection = {
// Why: SSH targets live in the running Orca host, not on disk, so enumerating them needs a
// client. Injected as a thunk so the lookup only happens on the error path we are explaining.
listSshTargets: () => Promise<SshTargetSummary[]>
pairingCode: string | null
// Why: an ambient ORCA_ENVIRONMENT counts as a selection too, so carry the label to
// name the real source in the conflict message.
environmentSelector: { value: string; label: string } | null
}
export function parseHostFlag(
flags: Map<string, string | boolean>
): ParsedExecutionHost | undefined {
if (!flags.has('host')) {
return undefined
}
const raw = flags.get('host')
if (typeof raw !== 'string' || raw.length === 0) {
throw new RuntimeClientError('invalid_argument', 'Missing value for --host')
}
const parsed = parseExecutionHostId(raw)
if (!parsed) {
throw new RuntimeClientError(
'invalid_argument',
`Invalid --host value: ${raw}. Expected local, ssh:<target-id>, or runtime:<environment-id>.`
)
}
return parsed
}
// Why: `runtime:<environment-id>` ids are minted by this machine's pairing store, so they
// only name a machine relative to it. Filtering or mutating the locally connected runtime
// with one answers for the wrong host, and an id that matches nothing is indistinguishable
// from a real host with no rows — so resolve the id here and send the command to it.
export async function resolveHostFlagEnvironmentId(
flags: Map<string, string | boolean>,
selection: HostFlagRoutingSelection
): Promise<string | null> {
const host = parseHostFlag(flags)
if (host?.kind !== 'runtime') {
return null
}
const [{ listEnvironments, resolveEnvironment }, { getDefaultUserDataPath }] = await Promise.all([
import('./runtime/environments.js'),
import('./runtime-client.js')
])
const userDataPath = getDefaultUserDataPath()
const known = listEnvironments(userDataPath)
// Why: --environment has always taken a name or an id, and the name is what people and agents
// actually know. Requiring the raw uuid here made the obvious spelling fail; accept either and
// canonicalize to the id so stored host ids still compare correctly downstream.
const environment = findEnvironmentByName(
known.map((candidate) => ({ id: candidate.id, name: candidate.name })),
host.environmentId
)
if (!environment) {
// Why: `runtime:<id>` is a host id that also appears in stored rows, so it resolves by id
// only — unlike --environment, which also accepts a name. Say so, and hand back the ids an
// agent can retry with instead of making it scrape the sentence.
const environments = known.map((candidate) => ({ id: candidate.id, name: candidate.name }))
assertEnvironmentNameUnambiguous(environments, host.environmentId, `--host ${host.id}`)
const sshTargets = await selection.listSshTargets()
throw new RuntimeClientError(
'invalid_argument',
`Unknown Orca server in --host ${host.id}: no paired Orca server is named or has id ${host.environmentId}.`,
{
knownEnvironments: environments,
knownSshTargets: sshTargets,
nextSteps: [
...crossKindNextSteps(host.environmentId, { environments, sshTargets }, 'environment'),
'Run `orca environment list` to see paired Orca servers.',
'Use --host local to target this machine.'
]
}
)
}
if (selection.pairingCode) {
throw new RuntimeClientError(
'invalid_argument',
`--host ${host.id} already selects a paired Orca server; use either --host runtime:<id> or --pairing-code, not both.`
)
}
if (selection.environmentSelector) {
const selected = resolveEnvironment(userDataPath, selection.environmentSelector.value)
if (selected.id !== environment.id) {
throw new RuntimeClientError(
'invalid_argument',
`--host ${host.id} and ${selection.environmentSelector.label} ${selection.environmentSelector.value} name different Orca servers.`
)
}
}
return environment.id
}
// Why: a runtime stamps its own setups `local` when they were made on the box and
// `runtime:<id>` when a paired client made them. Once --host routed the command to that
// runtime both spellings mean the same machine, so a host filter has to accept both.
export function hostFilterMatchesHostId(
filter: ParsedExecutionHost,
candidateHostId: string | null | undefined
): boolean {
const candidate = normalizeExecutionHostId(candidateHostId)
if (candidate === filter.id) {
return true
}
return filter.kind === 'runtime' && candidate === LOCAL_EXECUTION_HOST_ID
}
// Why: `ssh:` reaches a machine the connected runtime owns, so it can only be checked against
// that runtime — unlike `runtime:`, which is resolved from this machine's pairing store before a
// client exists. Callers that act on a --host value run this so an unknown target fails loudly
// instead of quietly filtering to nothing.
export async function resolveHostFlagTarget(
flags: Map<string, string | boolean>,
client: RuntimeClient
): Promise<ParsedExecutionHost | undefined> {
const host = parseHostFlag(flags)
if (host?.kind !== 'ssh') {
return host
}
const [{ listEnvironments }, { getDefaultUserDataPath }] = await Promise.all([
import('./runtime/environments.js'),
import('./runtime-client.js')
])
const environments = listEnvironments(getDefaultUserDataPath()).map((candidate) => ({
id: candidate.id,
name: candidate.name
}))
const targetId = await resolveSshHostTargetId(client, host.targetId, environments)
return parseExecutionHostId(toSshExecutionHostId(targetId)) ?? host
}
// Why: the store refuses an ambiguous environment name rather than guessing which server was
// meant. Resolving one here would put the guess back, in the flag whose whole purpose is to stop
// a command reaching a machine the caller did not choose.
function assertEnvironmentNameUnambiguous(
environments: readonly { id: string; name: string }[],
name: string,
flag: string
): void {
const ambiguous = ambiguousEnvironments(environments, name)
if (ambiguous.length === 0) {
return
}
throw new RuntimeClientError(
'invalid_argument',
`Ambiguous Orca server in ${flag}: ${ambiguous.length} paired servers are named ${name}. Use the environment id.`,
{
knownEnvironments: ambiguous,
nextSteps: ambiguous.map(
(candidate) => `Use --host runtime:${candidate.id} for the server named ${candidate.name}.`
)
}
)
}
// Why: the inverse of the --host case. `--environment openclaw` failed with a bare "Unknown
// environment", when openclaw is very often an SSH target — a different axis, not a typo. The
// store's own error cannot carry the hint (translateStoreError forwards code and message only,
// dropping data), so resolve the selector here where the payload survives.
export async function assertEnvironmentSelectorResolvable(
selector: string,
listSshTargetsForSuggestion: () => Promise<SshTargetSummary[]>
): Promise<void> {
const [{ listEnvironments }, { getDefaultUserDataPath }] = await Promise.all([
import('./runtime/environments.js'),
import('./runtime-client.js')
])
const environments = listEnvironments(getDefaultUserDataPath()).map((candidate) => ({
id: candidate.id,
name: candidate.name
}))
if (findEnvironmentByName(environments, selector)) {
return
}
assertEnvironmentNameUnambiguous(environments, selector, `--environment ${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}.`,
{
knownEnvironments: 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.'
]
}
)
}