fix(orchestration): preserve active workers across updates (#11271)

* fix(orchestration): preserve active workers across updates

* test(ssh): model absent legacy adoption

* test(orchestration): align compatibility contracts

* fix(windows): escape updater PowerShell booleans

* fix(windows): restore stock uninstall process check

* fix(orchestration): keep recovery off renderer startup barrier

* fix(orchestration): harden legacy recovery migration

* fix(orchestration): close recovery review gaps

* fix(orchestration): complete legacy worker cutover recovery

* fix(orchestration): preserve legacy workers across updates

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-07-29 20:25:44 -07:00
committed by Neil
co-authored by OrcaWin
parent 3240c26bce
commit 959e8d63b0
150 changed files with 19865 additions and 792 deletions
@@ -1,20 +1,47 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { randomUUID } from 'node:crypto'
import type * as NodeCrypto from 'node:crypto'
import { SshRelaySession } from './ssh-relay-session'
import { createMockDeps, mockDeploySuccess } from './ssh-relay-session-test-fixtures'
const { muxRequestMock } = vi.hoisted(() => ({ muxRequestMock: vi.fn() }))
type MockMuxInstance = {
requestHandlers: Map<string, (params: Record<string, unknown>) => Promise<unknown>>
}
const { muxRequestMock, muxInstancesRaw } = vi.hoisted(() => ({
muxRequestMock: vi.fn(),
muxInstancesRaw: [] as unknown[]
}))
const muxInstances = muxInstancesRaw as MockMuxInstance[]
vi.mock('./ssh-relay-deploy', () => ({ deployAndLaunchRelay: vi.fn() }))
vi.mock('./ssh-relay-deploy-helpers', () => ({ execCommand: vi.fn().mockResolvedValue('') }))
vi.mock('node:crypto', async (importOriginal) => {
const actual = await importOriginal<typeof NodeCrypto>()
return { ...actual, randomUUID: vi.fn() }
})
vi.mock('./ssh-remote-orca-cli', () => ({
runRemoteOrcaCli: vi.fn().mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' })
}))
vi.mock('./ssh-channel-multiplexer', () => ({
SshChannelMultiplexer: class MockSshChannelMultiplexer {
requestHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>()
notify = vi.fn()
request = muxRequestMock
onNotification = vi.fn().mockReturnValue(() => {})
onRequest = vi.fn().mockReturnValue(() => {})
onRequest = vi.fn(
(method: string, handler: (params: Record<string, unknown>) => Promise<unknown>) => {
this.requestHandlers.set(method, handler)
return () => this.requestHandlers.delete(method)
}
)
onDispose = vi.fn().mockReturnValue(() => {})
dispose = vi.fn()
isDisposed = vi.fn().mockReturnValue(false)
constructor() {
muxInstancesRaw.push(this)
}
}
}))
vi.mock('../agent-hooks/remote-managed-hook-installers', () => ({
@@ -98,13 +125,74 @@ function emitExitDuringAttach(payload: { id: string; code: number; incarnationId
describe('SshRelaySession reconnect incarnation ordering', () => {
beforeEach(() => {
vi.clearAllMocks()
muxInstances.splice(0)
delete process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS
muxRequestMock.mockReset()
muxRequestMock.mockResolvedValue([])
vi.mocked(randomUUID).mockReset()
vi.mocked(randomUUID).mockReturnValue('00000000-0000-4000-8000-000000000001')
mockDeploySuccess()
vi.mocked(getPtyIdsForConnection).mockReturnValue([])
})
it('keeps the winning reconnect incarnation when a stale health check resolves last', async () => {
const initialIncarnation = '00000000-0000-4000-8000-000000000001'
const winningIncarnation = '00000000-0000-4000-8000-000000000002'
const staleIncarnation = '00000000-0000-4000-8000-000000000003'
let resolveStaleHealthCheck!: (value: unknown) => void
const staleHealthCheck = new Promise((resolve) => {
resolveStaleHealthCheck = resolve
})
let resolveHomeCalls = 0
muxRequestMock.mockImplementation((method: string) => {
if (method !== 'session.resolveHome') {
return Promise.resolve([])
}
resolveHomeCalls += 1
return resolveHomeCalls === 2 ? staleHealthCheck : Promise.resolve('/')
})
vi.mocked(randomUUID)
.mockReturnValueOnce(initialIncarnation)
.mockReturnValueOnce(winningIncarnation)
.mockReturnValue(staleIncarnation)
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const runtime = {
registerOrchestrationCompatibilitySshAttachment: vi.fn(
(_targetId: string, connectionIncarnation: string) => ({
attachmentId: `attachment-${connectionIncarnation}`,
connectionIncarnation
})
),
releaseOrchestrationCompatibilitySshAttachment: vi.fn()
}
const session = new SshRelaySession(
'target-1',
getMainWindow,
mockStore,
mockPortForward,
runtime as never
)
await session.establish(mockConn)
const staleReconnect = session.reconnect(mockConn)
await vi.waitFor(() => expect(resolveHomeCalls).toBe(2))
await session.reconnect(mockConn)
expect(session.getState()).toBe('ready')
resolveStaleHealthCheck('/')
await staleReconnect
const winningCliHandler = muxInstances[2]?.requestHandlers.get('orca.cli')
expect(winningCliHandler).toBeDefined()
await winningCliHandler?.({ argv: ['status'], cwd: '/', env: {} })
expect(runtime.registerOrchestrationCompatibilitySshAttachment).toHaveBeenCalledWith(
'target-1',
winningIncarnation
)
expect(randomUUID).toHaveBeenCalledTimes(2)
})
it('restores and persists exact incarnation proof from reconnect attach', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const incarnationId = 'incarnation-reconnect'
+72 -11
View File
@@ -2,6 +2,7 @@
// Why: single authority for all relay lifecycle state per SSH target (previously scattered across module Maps/Sets with duplicated paths).
import type { BrowserWindow } from 'electron'
import { randomUUID } from 'node:crypto'
import { deployAndLaunchRelay } from './ssh-relay-deploy'
import { execCommand } from './ssh-relay-deploy-helpers'
import { isRelayVersionMismatchError } from './ssh-relay-version-mismatch-error'
@@ -65,6 +66,10 @@ import {
import type { Store } from '../persistence'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import { runRemoteOrcaCli } from './ssh-remote-orca-cli'
import {
acknowledgeRemoteOrcaCliPostOutput,
parseRemoteOrcaCliPostOutput
} from './ssh-remote-orchestration-post-output'
import { toSshExecutionHostId, type ExecutionHostId } from '../../shared/execution-host'
import { isTerminalLeafId, makePaneKey } from '../../shared/stable-pane-id'
import { isValidTerminalTabId } from '../../shared/terminal-tab-id'
@@ -151,6 +156,7 @@ export class SshRelaySession {
private remoteCliBridgeEnv: RemoteCliBridgeEnv | null = null
private forwardedReattachReplayByPty = new Map<string, ForwardedReplayFingerprint>()
private pendingPtyReattaches = new Map<string, PendingPtyReattach>()
private activeCompatibilityAttachmentIds = new Set<string>()
constructor(
readonly targetId: string,
@@ -278,8 +284,15 @@ export class SshRelaySession {
// Why: round-trip the relay before registering providers so a closed --connect bridge fails fast instead of leaving a 'ready' session on a dead mux.
await mux.request('session.resolveHome', { path: '~' })
if (!ownsAttempt()) {
if (!mux.isDisposed()) {
mux.dispose()
}
throw new Error('Session disposed during establish')
}
const connectionIncarnation = randomUUID()
const registered = await this.registerProviders(mux, ownsAttempt)
const registered = await this.registerProviders(mux, ownsAttempt, connectionIncarnation)
if (!registered) {
if (!mux.isDisposed()) {
mux.dispose()
@@ -387,8 +400,9 @@ export class SshRelaySession {
}
return
}
const connectionIncarnation = randomUUID()
const registered = await this.registerProviders(mux, ownsAttempt)
const registered = await this.registerProviders(mux, ownsAttempt, connectionIncarnation)
if (!registered) {
if (!mux.isDisposed()) {
mux.dispose()
@@ -499,7 +513,8 @@ export class SshRelaySession {
// Why: shared by establish() and reconnect() so both use the exact same registration sequence.
private async registerProviders(
mux: SshChannelMultiplexer,
shouldContinue?: () => boolean
shouldContinue: (() => boolean) | undefined,
connectionIncarnation: string
): Promise<boolean> {
await this.registerRelayRoots(mux)
if (shouldContinue && !shouldContinue()) {
@@ -530,7 +545,7 @@ export class SshRelaySession {
return false
}
this.wireUpRemoteOrcaCli(mux)
this.wireUpRemoteOrcaCli(mux, connectionIncarnation)
const ptyProvider = new SshPtyProvider(this.targetId, mux, this.remoteCliBridgeEnv ?? undefined)
registerSshPtyProvider(this.targetId, ptyProvider)
@@ -667,7 +682,7 @@ export class SshRelaySession {
}
}
private wireUpRemoteOrcaCli(mux: SshChannelMultiplexer): void {
private wireUpRemoteOrcaCli(mux: SshChannelMultiplexer, connectionIncarnation: string): void {
mux.onRequest('orca.cli', async (params) => {
if (!this.runtime) {
throw new Error('Orca runtime is unavailable')
@@ -687,12 +702,54 @@ export class SshRelaySession {
)
: {}
const stdin = typeof params.stdin === 'string' ? params.stdin : undefined
return await runRemoteOrcaCli(this.runtime, {
argv,
cwd,
env,
...(stdin !== undefined ? { stdin } : {})
})
const runtimeAuthority = this.runtime.registerOrchestrationCompatibilitySshAttachment(
this.targetId,
connectionIncarnation
)
this.activeCompatibilityAttachmentIds.add(runtimeAuthority.attachmentId)
try {
return await runRemoteOrcaCli(this.runtime, {
argv,
cwd,
env,
...(stdin !== undefined ? { stdin } : {}),
runtimeAuthority
})
} finally {
this.activeCompatibilityAttachmentIds.delete(runtimeAuthority.attachmentId)
this.runtime.releaseOrchestrationCompatibilitySshAttachment(runtimeAuthority.attachmentId)
}
})
mux.onRequest('orca.cli.postOutput', async (params) => {
if (!this.runtime) {
throw new Error('Orca runtime is unavailable')
}
const rawEnv = params.env
const env =
rawEnv && typeof rawEnv === 'object' && !Array.isArray(rawEnv)
? Object.fromEntries(
Object.entries(rawEnv).filter(
(entry): entry is [string, string] =>
typeof entry[0] === 'string' && typeof entry[1] === 'string'
)
)
: {}
const runtimeAuthority = this.runtime.registerOrchestrationCompatibilitySshAttachment(
this.targetId,
connectionIncarnation
)
this.activeCompatibilityAttachmentIds.add(runtimeAuthority.attachmentId)
try {
await acknowledgeRemoteOrcaCliPostOutput(this.runtime, {
postOutput: parseRemoteOrcaCliPostOutput(params.postOutput),
env,
runtimeAuthority
})
return { acknowledged: true }
} finally {
this.activeCompatibilityAttachmentIds.delete(runtimeAuthority.attachmentId)
this.runtime.releaseOrchestrationCompatibilitySshAttachment(runtimeAuthority.attachmentId)
}
})
}
@@ -826,6 +883,10 @@ export class SshRelaySession {
this.mux.dispose(reason)
}
this.mux = null
for (const attachmentId of this.activeCompatibilityAttachmentIds) {
this.runtime?.releaseOrchestrationCompatibilitySshAttachment(attachmentId)
}
this.activeCompatibilityAttachmentIds.clear()
if (reason === 'shutdown') {
clearPtyOwnershipForConnection(this.targetId)
@@ -22,6 +22,12 @@ import {
import { resolveOrchestrationAskClientTimeoutMs } from '../../shared/orchestration-ask-timeout'
import { remoteCliRequestTimeoutMs } from '../../relay/remote-cli-timeout'
import { MAX_TIMER_DELAY_MS } from '../../shared/timer-delay'
import {
ORCHESTRATION_COMPATIBILITY_ATTACHMENT_ENV,
ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV,
ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV,
ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV
} from '../../shared/orchestration-compatibility-evidence'
type FakeChild = EventEmitter & {
stdout: EventEmitter
@@ -65,7 +71,12 @@ describe('buildHostCliEnv', () => {
ORCA_TERMINAL_HANDLE: 'term_remote',
ORCA_WORKTREE_ID: 'repo::/home/alice/wt',
ORCA_PANE_KEY: 'pane-9',
ORCA_AGENT_LAUNCH_TOKEN: 'launch-secret',
ORCA_WORKSPACE_ID: 'ws-1',
[ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV]: 'wsl',
[ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV]: 'caller-host',
[ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV]: 'caller-incarnation',
[ORCHESTRATION_COMPATIBILITY_ATTACHMENT_ENV]: 'caller-attachment',
// Why: these are remote-machine paths and must not leak into the host
// subprocess (PATH would break host binary lookup; user-data would
// retarget the CLI at a different local instance).
@@ -73,13 +84,24 @@ describe('buildHostCliEnv', () => {
ORCA_USER_DATA_PATH: '/remote/user-data'
},
userDataPath: '/host/user-data',
remoteCwd: '/home/alice/wt/sub'
remoteCwd: '/home/alice/wt/sub',
runtimeAuthority: {
kind: 'ssh',
targetId: 'saved-target',
connectionIncarnation: 'connection-incarnation',
attachmentId: 'runtime-attachment'
}
})
expect(env.ORCA_TERMINAL_HANDLE).toBe('term_remote')
expect(env.ORCA_WORKTREE_ID).toBe('repo::/home/alice/wt')
expect(env.ORCA_PANE_KEY).toBe('pane-9')
expect(env.ORCA_AGENT_LAUNCH_TOKEN).toBe('launch-secret')
expect(env.ORCA_WORKSPACE_ID).toBe('ws-1')
expect(env[ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV]).toBe('ssh')
expect(env[ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV]).toBe('saved-target')
expect(env[ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV]).toBe('connection-incarnation')
expect(env[ORCHESTRATION_COMPATIBILITY_ATTACHMENT_ENV]).toBe('runtime-attachment')
expect(env.PATH).toBe('/host/bin')
expect(env.ORCA_USER_DATA_PATH).toBe('/host/user-data')
expect(env.ORCA_CLI_CWD).toBe('/home/alice/wt/sub')
@@ -17,20 +17,49 @@ import {
parsePositiveSafeIntegerNumericText,
parsePositiveSafeIntegerText
} from '../../shared/timer-delay'
import {
ORCHESTRATION_COMPATIBILITY_ATTACHMENT_ENV,
ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV,
ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV,
ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV
} from '../../shared/orchestration-compatibility-evidence'
export type SshCliRuntimeAuthority = {
kind: 'ssh'
targetId: string
connectionIncarnation: string
attachmentId: string
}
export type RemoteOrcaCliRequest = {
argv: string[]
cwd: string
env: Record<string, string>
stdin?: string
runtimeAuthority?: SshCliRuntimeAuthority
}
export type RemoteOrcaCliResult = {
stdout: string
stderr: string
exitCode: number
postOutput?: RemoteOrcaCliPostOutput
}
export type RemoteOrcaCliPostOutput =
| {
kind: 'legacy_check_ack'
terminal: string
messageIds: string[]
types?: string[]
}
| {
kind: 'legacy_question_ack'
terminal: string
questionId: string
answerMessageId: string
}
export type HostCliPassthroughOptions = {
execPath?: string
cliEntryPath?: string
@@ -54,6 +83,7 @@ const REMOTE_CONTEXT_ENV_VARS = [
'ORCA_TERMINAL_HANDLE',
'ORCA_WORKTREE_ID',
'ORCA_PANE_KEY',
'ORCA_AGENT_LAUNCH_TOKEN',
'ORCA_WORKSPACE_ID'
] as const
@@ -106,6 +136,7 @@ export function buildHostCliEnv(args: {
remoteEnv: Record<string, string>
userDataPath: string
remoteCwd: string
runtimeAuthority?: SshCliRuntimeAuthority
}): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...args.hostEnv }
for (const key of REMOTE_CONTEXT_ENV_VARS) {
@@ -127,6 +158,17 @@ export function buildHostCliEnv(args: {
env.ORCA_NODE_REPL_EXTERNAL_MODULE = args.hostEnv.NODE_REPL_EXTERNAL_MODULE ?? ''
delete env.NODE_OPTIONS
delete env.NODE_REPL_EXTERNAL_MODULE
delete env[ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV]
delete env[ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV]
delete env[ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV]
delete env[ORCHESTRATION_COMPATIBILITY_ATTACHMENT_ENV]
if (args.runtimeAuthority) {
env[ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV] = 'ssh'
env[ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV] = args.runtimeAuthority.targetId
env[ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV] =
args.runtimeAuthority.connectionIncarnation
env[ORCHESTRATION_COMPATIBILITY_ATTACHMENT_ENV] = args.runtimeAuthority.attachmentId
}
env.ELECTRON_RUN_AS_NODE = '1'
return env
}
@@ -177,7 +219,8 @@ export async function runHostOrcaCliPassthrough(
hostEnv,
remoteEnv: request.env,
userDataPath,
remoteCwd: request.cwd
remoteCwd: request.cwd,
runtimeAuthority: request.runtimeAuthority
})
return await new Promise<RemoteOrcaCliResult>((resolve, reject) => {
@@ -0,0 +1,40 @@
import type { RpcResponse } from '../runtime/rpc/core'
import type { ParsedRemoteCli } from './ssh-remote-cli-argument-error'
import type { RemoteOrcaCliResult } from './ssh-remote-cli-host-passthrough'
import { formatRemoteCli } from './ssh-remote-cli-format'
import {
formatRemoteOrchestrationAsk,
getRemoteCliExitCode
} from './ssh-remote-orchestration-ask-output'
import { formatRemoteOrchestrationCheck } from './ssh-remote-orchestration-check-output'
import { getRemoteCliPostOutput } from './ssh-remote-orchestration-post-output'
import { resolveRemoteCliHandle } from './ssh-remote-cli-args'
export function formatInProcessRemoteCliResult(
parsed: ParsedRemoteCli,
env: Record<string, string>,
response: RpcResponse,
json: boolean
): RemoteOrcaCliResult {
const command = parsed.commandPath.join(' ')
const formatted =
command === 'orchestration check'
? formatRemoteOrchestrationCheck(
response,
json,
resolveRemoteCliHandle(parsed.flags, env, 'terminal'),
parsed.flags.has('format')
)
: command === 'orchestration ask'
? formatRemoteOrchestrationAsk(response, json)
: json
? { stdout: `${JSON.stringify(response, null, 2)}\n`, stderr: '' }
: formatRemoteCli(response)
const postOutput = getRemoteCliPostOutput(parsed, env, response)
return {
stdout: formatted.stdout,
stderr: formatted.stderr,
exitCode: getRemoteCliExitCode(command, response),
...(postOutput ? { postOutput } : {})
}
}
+1 -1
View File
@@ -24,7 +24,6 @@ const LEGACY_FALLBACK_OPTIONS: HostCliPassthroughOptions = {
userDataPath: '/host/user-data',
entryExists: () => false
}
type FakeChild = EventEmitter & {
stdout: EventEmitter
stderr: EventEmitter
@@ -80,6 +79,7 @@ describe('runRemoteOrcaCli', () => {
}
}
}),
getLegacyAdoption: vi.fn(() => undefined),
getActiveDispatchForIdentity: vi.fn(() => undefined),
getCurrentRunForPane: vi.fn(() => undefined),
findActiveRemoteAttachmentForPane: vi.fn(() => undefined)
+99 -36
View File
@@ -1,10 +1,11 @@
import type { CliStatusResult, RuntimeStatus } from '../../shared/runtime-types'
import { randomUUID } from 'node:crypto'
import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope'
import { readOrchestrationCompatibilityEvidence } from '../../shared/orchestration-compatibility-evidence'
import { ORCHESTRATION_CONTRACT_VERSION } from '../../shared/protocol-version'
import { RpcDispatcher } from '../runtime/rpc/dispatcher'
import type { RpcResponse } from '../runtime/rpc/core'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import { formatRemoteCli } from './ssh-remote-cli-format'
import {
HostCliUnavailableError,
runHostOrcaCliPassthrough,
@@ -24,9 +25,9 @@ import { buildRemoteCliError } from './ssh-remote-cli-error-response'
import { getRemoteLinearHelp, tryDispatchRemoteLinearCli } from './ssh-remote-linear-cli'
import {
getRemoteOrchestrationPayload,
hasRemoteLifecycleRejection,
resolveRemoteOrchestrationSender
} from './ssh-remote-orchestration-send'
import { formatInProcessRemoteCliResult } from './ssh-remote-cli-in-process-result'
export type { RemoteOrcaCliRequest, RemoteOrcaCliResult } from './ssh-remote-cli-host-passthrough'
@@ -49,6 +50,7 @@ export async function runRemoteOrcaCli(
): Promise<RemoteOrcaCliResult> {
const parsed = parseRemoteCliArgs(request.argv)
const json = parsed.flags.has('json')
const command = parsed.commandPath.join(' ')
const interactiveMessage = HOST_INTERACTIVE_COMMANDS[parsed.commandPath[0] ?? '']
if (interactiveMessage) {
@@ -62,6 +64,17 @@ export async function runRemoteOrcaCli(
return { stdout: '', stderr: `${interactiveMessage}\n`, exitCode: 1 }
}
if (command === 'orchestration check' || command === 'orchestration ask') {
// Why: compatibility ACKs must wait until relay stdout is observable; a host CLI child can only flush into main's capture pipe.
return await runLegacyRemoteOrcaCli(
runtime,
request,
parsed,
json,
new HostCliUnavailableError('output-ordered orchestration bridge required')
)
}
let passthroughFailure: HostCliUnavailableError | null = null
try {
return await runHostOrcaCliPassthrough(request, passthroughOptions)
@@ -96,18 +109,10 @@ async function runLegacyRemoteOrcaCli(
parsed,
request.env,
request.stdin,
passthroughFailure.message
passthroughFailure.message,
request.runtimeAuthority
)
const formatted = json
? { stdout: `${JSON.stringify(response, null, 2)}\n`, stderr: '' }
: formatRemoteCli(response)
return {
stdout: formatted.stdout,
stderr: formatted.stderr,
// Why: the legacy SSH bridge bypasses the local CLI handler that turns
// a persisted lifecycle rejection into an unsuccessful command.
exitCode: response.ok && !hasRemoteLifecycleRejection(response.result) ? 0 : 1
}
return formatInProcessRemoteCliResult(parsed, request.env, response, json)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
const code =
@@ -134,9 +139,23 @@ async function dispatchRemoteCli(
parsed: ParsedRemoteCli,
env: Record<string, string>,
stdin: string | undefined,
passthroughFailureReason: string
passthroughFailureReason: string,
runtimeAuthority: RemoteOrcaCliRequest['runtimeAuthority']
): Promise<RpcResponse> {
const command = parsed.commandPath.join(' ')
const inheritedEvidence = readOrchestrationCompatibilityEvidence(env)
const orchestrationCompatibilityEvidence = runtimeAuthority
? { ...inheritedEvidence, host: runtimeAuthority }
: inheritedEvidence
const compatibilityEnvelope: RuntimeOrchestrationEnvelope = {
compatibilityInvocationId: randomUUID(),
orchestrationRequestId:
optionalRemoteCliString(parsed.flags, 'retry-request') ??
(command === 'orchestration check' || command === 'orchestration ask'
? randomUUID()
: undefined),
orchestrationCompatibilityEvidence
}
const linearResponse = await tryDispatchRemoteLinearCli(dispatcher, parsed, env, stdin)
if (linearResponse) {
return linearResponse
@@ -187,33 +206,74 @@ async function dispatchRemoteCli(
senderPaneKey: env.ORCA_PANE_KEY || undefined
},
{
orchestrationCapability: optionalRemoteCliString(parsed.flags, 'dispatch-capability'),
orchestrationRequestId: optionalRemoteCliString(parsed.flags, 'retry-request')
...compatibilityEnvelope,
orchestrationCapability: optionalRemoteCliString(parsed.flags, 'dispatch-capability')
}
)
}
case 'orchestration check':
return await call(dispatcher, 'orchestration.check', {
terminal: resolveRemoteCliHandle(parsed.flags, env, 'terminal'),
terminalPaneKey: parsed.flags.has('terminal') ? undefined : env.ORCA_PANE_KEY || undefined,
unread: parsed.flags.has('unread') ? true : undefined,
all: parsed.flags.has('all') ? true : undefined,
types: optionalRemoteCliString(parsed.flags, 'types'),
inject: parsed.flags.has('inject') ? true : undefined,
wait: parsed.flags.has('wait') ? true : undefined,
timeoutMs: optionalRemoteCliNumber(parsed.flags, 'timeout-ms')
})
return await call(
dispatcher,
'orchestration.check',
{
terminal: resolveRemoteCliHandle(parsed.flags, env, 'terminal'),
terminalPaneKey: parsed.flags.has('terminal')
? undefined
: env.ORCA_PANE_KEY || undefined,
unread: parsed.flags.has('unread') ? true : parsed.flags.has('peek') ? false : undefined,
peek: parsed.flags.has('peek') ? true : undefined,
all: parsed.flags.has('all') ? true : undefined,
types: optionalRemoteCliString(parsed.flags, 'types'),
format: parsed.flags.has('format') ? true : undefined,
inject: parsed.flags.has('inject') ? true : undefined,
compatibilityCliCommand: 'orca',
run: optionalRemoteCliString(parsed.flags, 'run'),
ack: optionalRemoteCliString(parsed.flags, 'ack'),
wait: parsed.flags.has('wait') ? true : undefined,
timeoutMs: optionalRemoteCliNumber(parsed.flags, 'timeout-ms')
},
compatibilityEnvelope
)
case 'orchestration ask':
return await call(
dispatcher,
'orchestration.ask',
{
to: optionalRemoteCliString(parsed.flags, 'to'),
question: optionalRemoteCliString(parsed.flags, 'question'),
resume: optionalRemoteCliString(parsed.flags, 'resume'),
options: optionalRemoteCliString(parsed.flags, 'options'),
timeoutMs: optionalRemoteCliNumber(parsed.flags, 'timeout-ms'),
from: resolveRemoteCliHandle(parsed.flags, env, 'from'),
run: optionalRemoteCliString(parsed.flags, 'run'),
compatibilityCliCommand: 'orca'
},
{
...compatibilityEnvelope,
orchestrationCapability: optionalRemoteCliString(parsed.flags, 'dispatch-capability')
}
)
case 'orchestration reply':
return await call(dispatcher, 'orchestration.reply', {
id: requiredRemoteCliString(parsed.flags, 'id'),
body: requiredRemoteCliString(parsed.flags, 'body'),
from: resolveRemoteCliHandle(parsed.flags, env, 'from')
})
return await call(
dispatcher,
'orchestration.reply',
{
id: requiredRemoteCliString(parsed.flags, 'id'),
body: requiredRemoteCliString(parsed.flags, 'body'),
from: resolveRemoteCliHandle(parsed.flags, env, 'from')
},
compatibilityEnvelope
)
case 'orchestration inbox':
return await call(dispatcher, 'orchestration.inbox', {
limit: optionalRemoteCliNumber(parsed.flags, 'limit'),
terminal: optionalRemoteCliString(parsed.flags, 'terminal')
})
return await call(
dispatcher,
'orchestration.inbox',
{
limit: optionalRemoteCliNumber(parsed.flags, 'limit'),
terminal: optionalRemoteCliString(parsed.flags, 'terminal')
},
compatibilityEnvelope
)
default:
// Why: only reachable when the full host CLI could not be launched;
// include that root cause so users can fix the install instead of
@@ -239,6 +299,9 @@ async function call(
orchestrationContractVersion: method.startsWith('orchestration.')
? ORCHESTRATION_CONTRACT_VERSION
: undefined,
orchestrationRequestId: envelope?.orchestrationRequestId
orchestrationRequestId: envelope?.orchestrationRequestId,
compatibilityInvocationId:
envelope?.orchestrationRequestId ?? envelope?.compatibilityInvocationId,
orchestrationCompatibilityEvidence: envelope?.orchestrationCompatibilityEvidence
})
}
@@ -0,0 +1,66 @@
import type { RpcResponse } from '../runtime/rpc/core'
import { formatRemoteCli } from './ssh-remote-cli-format'
import { hasRemoteLifecycleRejection } from './ssh-remote-orchestration-send'
export function formatRemoteOrchestrationAsk(
response: RpcResponse,
json: boolean
): { stdout: string; stderr: string } {
if (!response.ok || !isRecord(response.result)) {
return json
? { stdout: `${JSON.stringify(response, null, 2)}\n`, stderr: '' }
: formatRemoteCli(response)
}
if (json) {
return { stdout: `${JSON.stringify(response.result)}\n`, stderr: '' }
}
if (isRecord(response.result.legacyCompatibility)) {
const compatibility = response.result.legacyCompatibility
if (compatibility.resumeRequired === true && typeof compatibility.resumeCommand === 'string') {
return {
stdout:
`Question ${String(response.result.messageId ?? 'unknown')} committed.\n` +
`Resume with: ${compatibility.resumeCommand}\n`,
stderr: ''
}
}
}
const answer = typeof response.result.answer === 'string' ? response.result.answer : ''
const thread = typeof response.result.threadId === 'string' ? response.result.threadId : 'unknown'
const timeoutMs =
typeof response.result.timeoutMs === 'number' ? response.result.timeoutMs : undefined
const stderr = response.result.timedOut
? `ask timeout after ${timeoutMs ?? 0}ms (thread ${thread})\n`
: response.result.cancelled
? response.result.connectionLost
? `ask connection closed (question ${String(response.result.messageId ?? 'unknown')})\n`
: `ask cancelled (question ${String(response.result.messageId ?? 'unknown')})\n`
: ''
return { stdout: answer ? `${answer}\n` : '', stderr }
}
export function getRemoteCliExitCode(command: string, response: RpcResponse): number {
if (!response.ok || hasRemoteLifecycleRejection(response.result)) {
return 1
}
if (
command === 'orchestration ask' &&
isRecord(response.result) &&
isRecord(response.result.legacyCompatibility) &&
response.result.legacyCompatibility.resumeRequired === true
) {
return 75
}
if (
command === 'orchestration ask' &&
isRecord(response.result) &&
(response.result.timedOut === true || response.result.cancelled === true)
) {
return 1
}
return 0
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
}
@@ -0,0 +1,48 @@
import {
formatOrchestrationCheckText,
prepareOrchestrationCheckOutput,
type OrchestrationCheckOutput,
type OrchestrationMessageSummary
} from '../../shared/orchestration-check-output'
import type { RpcResponse } from '../runtime/rpc/core'
import { formatRemoteCli } from './ssh-remote-cli-format'
export function formatRemoteOrchestrationCheck(
response: RpcResponse,
json: boolean,
terminal: string,
formattedRequested: boolean
): { stdout: string; stderr: string } {
if (!response.ok || !isRecord(response.result)) {
return json
? { stdout: `${JSON.stringify(response, null, 2)}\n`, stderr: '' }
: formatRemoteCli(response)
}
const messages = Array.isArray(response.result.messages)
? response.result.messages.filter(isMessageSummary)
: []
const count = typeof response.result.count === 'number' ? response.result.count : messages.length
const result = prepareOrchestrationCheckOutput(
{ ...(response.result as OrchestrationCheckOutput), messages, count },
terminal,
formattedRequested
)
if (json) {
return {
stdout: `${JSON.stringify({ ...response, result }, null, 2)}\n`,
stderr: ''
}
}
return {
stdout: `${formatOrchestrationCheckText(result, terminal)}\n`,
stderr: ''
}
}
function isMessageSummary(value: unknown): value is OrchestrationMessageSummary {
return isRecord(value) && typeof value.id === 'string' && typeof value.from_handle === 'string'
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
}
@@ -0,0 +1,401 @@
import { createHash } from 'node:crypto'
import { describe, expect, it, vi } from 'vitest'
vi.mock('electron', () => ({
app: {
isPackaged: false,
getAppPath: () => '/host/app'
}
}))
vi.mock('../persistence', () => ({
getCanonicalUserDataPath: () => '/host/user-data'
}))
import { OrchestrationDb } from '../runtime/orchestration/db'
import { OrcaRuntimeService } from '../runtime/orca-runtime'
import type Database from '../sqlite/sync-database'
import type { HostCliPassthroughOptions } from './ssh-remote-cli-host-passthrough'
import { runRemoteOrcaCli } from './ssh-remote-orca-cli'
import { acknowledgeRemoteOrcaCliPostOutput } from './ssh-remote-orchestration-post-output'
const LEGACY_FALLBACK_OPTIONS: HostCliPassthroughOptions = {
execPath: '/host/electron',
cliEntryPath: '/host/app/out/cli/index.js',
userDataPath: '/host/user-data',
entryExists: () => false
}
const WORKER_HANDLE = 'term_legacy_ssh_worker'
const WORKER_PANE = 'tab_legacy_ssh:33333333-3333-4333-8333-333333333333'
const COORDINATOR_HANDLE = 'term_legacy_ssh_coord'
const COORDINATOR_PANE = 'tab_legacy_coord:44444444-4444-4444-8444-444444444444'
const WORKER_ENV = {
ORCA_TERMINAL_HANDLE: WORKER_HANDLE,
ORCA_PANE_KEY: WORKER_PANE,
ORCA_AGENT_LAUNCH_TOKEN: 'legacy-ssh-token'
}
const COORDINATOR_ENV = {
ORCA_TERMINAL_HANDLE: COORDINATOR_HANDLE,
ORCA_PANE_KEY: COORDINATOR_PANE,
ORCA_AGENT_LAUNCH_TOKEN: 'legacy-ssh-coordinator-token'
}
const RUNTIME_AUTHORITY = {
kind: 'ssh' as const,
targetId: 'saved-target',
connectionIncarnation: 'connection-1',
attachmentId: 'attachment-1'
}
function createLegacyRuntime() {
const db = new OrchestrationDb(':memory:')
const run = db.createRun({
objective: 'Adopted legacy SSH work',
coordinatorHandle: COORDINATOR_HANDLE,
coordinatorPaneKey: COORDINATOR_PANE
})
const task = db.createTask({
spec: 'legacy SSH assignment',
runId: run.id,
createdByTerminalHandle: COORDINATOR_HANDLE
})
const dispatch = db.createDispatchContext(task.id, WORKER_HANDLE, WORKER_PANE)
const sqlite = (db as unknown as { db: Database.Database }).db
sqlite
.prepare(
`UPDATE dispatch_contexts
SET contract_version = 0, process_incarnation = 'process-1'
WHERE id = ?`
)
.run(dispatch.id)
sqlite
.prepare(
`INSERT INTO legacy_adoptions (source_run_id, adopted_run_id, scheduler_state_lost)
VALUES ('run_legacy_local', ?, 1)`
)
.run(run.id)
sqlite
.prepare(
`UPDATE runs
SET coordinator_handle = NULL, coordinator_pane_key = NULL, consumer_generation = 0
WHERE id = ?`
)
.run(run.id)
const runtime = new OrcaRuntimeService()
runtime.setOrchestrationDb(db)
vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) =>
handle === WORKER_HANDLE ? WORKER_PANE : handle === COORDINATOR_HANDLE ? COORDINATOR_PANE : null
)
vi.spyOn(runtime, 'verifyOrchestrationCompatibilityCaller').mockImplementation((evidence) => {
const worker =
evidence?.terminalHandle === WORKER_HANDLE &&
evidence.paneKey === WORKER_PANE &&
evidence.launchToken === WORKER_ENV.ORCA_AGENT_LAUNCH_TOKEN
const coordinator =
evidence?.terminalHandle === COORDINATOR_HANDLE &&
evidence.paneKey === COORDINATOR_PANE &&
evidence.launchToken === COORDINATOR_ENV.ORCA_AGENT_LAUNCH_TOKEN
if (
(!worker && !coordinator) ||
evidence.host?.kind !== 'ssh' ||
evidence.host.targetId !== RUNTIME_AUTHORITY.targetId ||
evidence.host.connectionIncarnation !== RUNTIME_AUTHORITY.connectionIncarnation
) {
return null
}
const identity = worker
? {
terminalHandle: WORKER_HANDLE,
paneKey: WORKER_PANE,
launchToken: WORKER_ENV.ORCA_AGENT_LAUNCH_TOKEN
}
: {
terminalHandle: COORDINATOR_HANDLE,
paneKey: COORDINATOR_PANE,
launchToken: COORDINATOR_ENV.ORCA_AGENT_LAUNCH_TOKEN
}
return {
hostScope: { kind: 'ssh', targetId: RUNTIME_AUTHORITY.targetId },
terminalHandle: identity.terminalHandle,
paneKey: identity.paneKey,
processIncarnation: 'process-1',
launchTokenHash: createHash('sha256').update(identity.launchToken).digest('hex')
}
})
vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {})
return { db, runtime, run: db.getRun(run.id)!, dispatch }
}
describe('legacy SSH orchestration fallback', () => {
it('acknowledges a consuming check only after remote output', async () => {
const { db, runtime, run } = createLegacyRuntime()
const message = db.insertMessage({
runId: run.id,
deliveryContract: 'legacy_direct',
from: COORDINATOR_HANDLE,
to: WORKER_HANDLE,
subject: 'retained SSH mail'
})
const request = {
argv: ['orchestration', 'check', '--unread', '--inject', '--json'],
cwd: '/home/alice/repo',
env: WORKER_ENV,
runtimeAuthority: RUNTIME_AUTHORITY
}
try {
const first = await runRemoteOrcaCli(runtime, request, LEGACY_FALLBACK_OPTIONS)
const replay = await runRemoteOrcaCli(runtime, request, LEGACY_FALLBACK_OPTIONS)
expect(JSON.parse(first.stdout)).toMatchObject({
result: {
messages: [{ id: message.id }],
formatted: expect.stringContaining('retained SSH mail')
}
})
expect(first.postOutput).toEqual({
kind: 'legacy_check_ack',
terminal: WORKER_HANDLE,
messageIds: [message.id]
})
expect(JSON.parse(replay.stdout)).toMatchObject({
result: { messages: [{ id: message.id }] }
})
expect(db.getMessageById(message.id)?.read).toBe(0)
await acknowledgeRemoteOrcaCliPostOutput(runtime, {
postOutput: first.postOutput!,
env: WORKER_ENV,
runtimeAuthority: RUNTIME_AUTHORITY
})
const afterAck = await runRemoteOrcaCli(runtime, request, LEGACY_FALLBACK_OPTIONS)
expect(JSON.parse(afterAck.stdout)).toMatchObject({ result: { messages: [], count: 0 } })
expect(afterAck.postOutput).toBeUndefined()
expect(db.getMessageById(message.id)?.read).toBe(1)
} finally {
db.close()
}
})
it('keeps peek formatted and non-consuming', async () => {
const { db, runtime, run } = createLegacyRuntime()
const message = db.insertMessage({
runId: run.id,
deliveryContract: 'legacy_direct',
from: COORDINATOR_HANDLE,
to: WORKER_HANDLE,
subject: 'inspect retained SSH mail'
})
try {
const peek = await runRemoteOrcaCli(
runtime,
{
argv: ['orchestration', 'check', '--peek', '--format', '--json'],
cwd: '/home/alice/repo',
env: WORKER_ENV,
runtimeAuthority: RUNTIME_AUTHORITY
},
LEGACY_FALLBACK_OPTIONS
)
const output = JSON.parse(peek.stdout) as {
result: { formatted: string }
}
expect(output).toMatchObject({
result: {
messages: [{ id: message.id }],
formatted: expect.stringContaining('inspect retained SSH mail'),
legacyCompatibility: { readOnly: true }
}
})
expect(output.result.formatted).toContain(`${message.id} [legacy, read-only]`)
expect(output.result.formatted).toContain(
'Inspection only: reply and acknowledgment are unavailable.'
)
expect(output.result.formatted).not.toContain('orchestration reply')
expect(peek.postOutput).toBeUndefined()
expect(db.getMessageById(message.id)?.read).toBe(0)
} finally {
db.close()
}
})
it('reads and acknowledges current Run delivery', async () => {
const { db, runtime, run } = createLegacyRuntime()
const message = db.insertMessage({
runId: run.id,
from: WORKER_HANDLE,
to: `run:${run.id}`,
subject: 'current Run mail'
})
const baseRequest = {
cwd: '/home/alice/repo',
env: COORDINATOR_ENV,
runtimeAuthority: RUNTIME_AUTHORITY
}
const spawn = vi.fn()
const hostCliAvailable = {
...LEGACY_FALLBACK_OPTIONS,
entryExists: () => true,
spawn: spawn as HostCliPassthroughOptions['spawn']
}
try {
const checked = await runRemoteOrcaCli(
runtime,
{
...baseRequest,
argv: ['orchestration', 'check', '--run', run.id]
},
hostCliAvailable
)
expect(checked.stdout).toContain('Delivery ')
expect(checked.stdout).toContain(`${message.id} [status] from=${WORKER_HANDLE}`)
expect(spawn).not.toHaveBeenCalled()
const checkedJson = await runRemoteOrcaCli(
runtime,
{
...baseRequest,
argv: ['orchestration', 'check', '--run', run.id, '--json']
},
hostCliAvailable
)
const result = JSON.parse(checkedJson.stdout) as {
result: { deliveryId: string; messages: { id: string }[] }
}
expect(result.result.messages).toEqual([expect.objectContaining({ id: message.id })])
const acknowledged = await runRemoteOrcaCli(
runtime,
{
...baseRequest,
argv: [
'orchestration',
'check',
'--run',
run.id,
'--ack',
result.result.deliveryId,
'--json'
]
},
hostCliAvailable
)
expect(JSON.parse(acknowledged.stdout)).toMatchObject({
result: { acknowledged: result.result.deliveryId }
})
expect(db.getMessageById(message.id)?.read).toBe(1)
} finally {
db.close()
}
})
it('replays an SSH legacy ask by retry request without creating another question', async () => {
const { db, runtime } = createLegacyRuntime()
const argv = [
'orchestration',
'ask',
'--to',
COORDINATOR_HANDLE,
'--question',
'Continue?',
'--timeout-ms',
'1',
'--retry-request',
'ssh-question-1',
'--json'
]
const request = {
argv,
cwd: '/home/alice/repo',
env: WORKER_ENV,
runtimeAuthority: RUNTIME_AUTHORITY
}
try {
const first = await runRemoteOrcaCli(runtime, request, LEGACY_FALLBACK_OPTIONS)
const replay = await runRemoteOrcaCli(runtime, request, LEGACY_FALLBACK_OPTIONS)
const sqlite = (db as unknown as { db: Database.Database }).db
const firstResult = JSON.parse(first.stdout) as { messageId: string; timedOut: boolean }
const replayResult = JSON.parse(replay.stdout) as { messageId: string; timedOut: boolean }
expect(first).toMatchObject({ exitCode: 1 })
expect(firstResult).toMatchObject({ messageId: expect.any(String), timedOut: true })
expect(replay).toMatchObject({ exitCode: 1 })
expect(replayResult).toMatchObject({ messageId: firstResult.messageId, timedOut: true })
expect(
(
sqlite.prepare('SELECT COUNT(*) AS count FROM question_threads').get() as {
count: number
}
).count
).toBe(1)
} finally {
db.close()
}
})
it('resumes and acknowledges a question answer', async () => {
const { db, runtime, run, dispatch } = createLegacyRuntime()
const pending = db.createQuestion({
runId: run.id,
dispatchId: dispatch.id,
askerHandle: WORKER_HANDLE,
question: 'Proceed?'
})
const answer = db.answerQuestion({
messageId: pending.question.message_id,
runId: run.id,
consumerGeneration: run.consumer_generation,
body: 'yes'
})
const sqlite = (db as unknown as { db: Database.Database }).db
sqlite
.prepare(
`UPDATE messages
SET delivery_contract = 'legacy_direct', read = 0
WHERE id = ?`
)
.run(answer.message.id)
try {
const result = await runRemoteOrcaCli(
runtime,
{
argv: ['orchestration', 'ask', '--resume', pending.question.message_id, '--json'],
cwd: '/home/alice/repo',
env: WORKER_ENV,
runtimeAuthority: RUNTIME_AUTHORITY
},
LEGACY_FALLBACK_OPTIONS
)
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({
answer: 'yes',
messageId: pending.question.message_id,
timedOut: false
})
expect(result.postOutput).toEqual({
kind: 'legacy_question_ack',
terminal: WORKER_HANDLE,
questionId: pending.question.message_id,
answerMessageId: answer.message.id
})
expect(db.getMessageById(answer.message.id)?.read).toBe(0)
await acknowledgeRemoteOrcaCliPostOutput(runtime, {
postOutput: result.postOutput!,
env: WORKER_ENV,
runtimeAuthority: RUNTIME_AUTHORITY
})
expect(db.getMessageById(answer.message.id)?.read).toBe(1)
} finally {
db.close()
}
})
})
@@ -0,0 +1,143 @@
import { randomUUID } from 'node:crypto'
import { readOrchestrationCompatibilityEvidence } from '../../shared/orchestration-compatibility-evidence'
import { ORCHESTRATION_CONTRACT_VERSION } from '../../shared/protocol-version'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import type { RpcResponse } from '../runtime/rpc/core'
import { RpcDispatcher } from '../runtime/rpc/dispatcher'
import type {
RemoteOrcaCliPostOutput,
RemoteOrcaCliRequest
} from './ssh-remote-cli-host-passthrough'
import { RemoteCliArgumentError, type ParsedRemoteCli } from './ssh-remote-cli-argument-error'
import { optionalRemoteCliString, resolveRemoteCliHandle } from './ssh-remote-cli-args'
export async function acknowledgeRemoteOrcaCliPostOutput(
runtime: OrcaRuntimeService,
args: {
postOutput: RemoteOrcaCliPostOutput
env: Record<string, string>
runtimeAuthority?: RemoteOrcaCliRequest['runtimeAuthority']
}
): Promise<void> {
const inheritedEvidence = readOrchestrationCompatibilityEvidence(args.env)
const orchestrationCompatibilityEvidence = args.runtimeAuthority
? { ...inheritedEvidence, host: args.runtimeAuthority }
: inheritedEvidence
const params =
args.postOutput.kind === 'legacy_check_ack'
? {
terminal: args.postOutput.terminal,
compatibilityAck: JSON.stringify({
messageIds: args.postOutput.messageIds,
types: args.postOutput.types
})
}
: {
terminal: args.postOutput.terminal,
compatibilityQuestionAck: JSON.stringify({
questionId: args.postOutput.questionId,
answerMessageId: args.postOutput.answerMessageId
})
}
const response = await new RpcDispatcher({ runtime }).dispatch({
id: `remote-cli-post-output-${randomUUID()}`,
authToken: 'remote-cli',
method: 'orchestration.check',
params,
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
compatibilityInvocationId: randomUUID(),
orchestrationCompatibilityEvidence
})
if (!response.ok) {
throw new Error(response.error.message)
}
}
export function parseRemoteOrcaCliPostOutput(value: unknown): RemoteOrcaCliPostOutput {
if (!isRecord(value) || typeof value.kind !== 'string' || typeof value.terminal !== 'string') {
throw invalidPostOutput()
}
if (
value.kind === 'legacy_check_ack' &&
Array.isArray(value.messageIds) &&
value.messageIds.every((id) => typeof id === 'string') &&
(value.types === undefined ||
(Array.isArray(value.types) && value.types.every((type) => typeof type === 'string')))
) {
return {
kind: value.kind,
terminal: value.terminal,
messageIds: value.messageIds,
...(value.types === undefined ? {} : { types: value.types })
}
}
if (
value.kind === 'legacy_question_ack' &&
typeof value.questionId === 'string' &&
typeof value.answerMessageId === 'string'
) {
return {
kind: value.kind,
terminal: value.terminal,
questionId: value.questionId,
answerMessageId: value.answerMessageId
}
}
throw invalidPostOutput()
}
export function getRemoteCliPostOutput(
parsed: ParsedRemoteCli,
env: Record<string, string>,
response: RpcResponse
): RemoteOrcaCliPostOutput | undefined {
if (!response.ok || !isRecord(response.result)) {
return undefined
}
const compatibility = response.result.legacyCompatibility
if (!isRecord(compatibility)) {
return undefined
}
const command = parsed.commandPath.join(' ')
if (
command === 'orchestration check' &&
Array.isArray(compatibility.ackMessageIds) &&
compatibility.ackMessageIds.length > 0 &&
compatibility.ackMessageIds.every((id) => typeof id === 'string')
) {
const types = optionalRemoteCliString(parsed.flags, 'types')
?.split(',')
.map((type) => type.trim())
.filter(Boolean)
return {
kind: 'legacy_check_ack',
terminal: resolveRemoteCliHandle(parsed.flags, env, 'terminal'),
messageIds: compatibility.ackMessageIds,
...(types ? { types } : {})
}
}
const acknowledgement = compatibility.answerAcknowledgement
if (
command === 'orchestration ask' &&
response.result.answer !== null &&
isRecord(acknowledgement) &&
typeof acknowledgement.questionId === 'string' &&
typeof acknowledgement.answerMessageId === 'string'
) {
return {
kind: 'legacy_question_ack',
terminal: resolveRemoteCliHandle(parsed.flags, env, 'from'),
questionId: acknowledgement.questionId,
answerMessageId: acknowledgement.answerMessageId
}
}
return undefined
}
function invalidPostOutput(): RemoteCliArgumentError {
return new RemoteCliArgumentError('invalid_argument', 'Invalid SSH CLI post-output action.')
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
}