diff --git a/docs/site/content/docs/cli/orchestration.mdx b/docs/site/content/docs/cli/orchestration.mdx index be57b6d2cef..497eb481a6d 100644 --- a/docs/site/content/docs/cli/orchestration.mdx +++ b/docs/site/content/docs/cli/orchestration.mdx @@ -22,7 +22,7 @@ Use it when you need ownership, completion tracking, or a DAG. For one-off promp ## Output -Every orchestration command prints a short view by default: the IDs and state the next command needs, with the next step last. `--json` prints the same fields as one line of JSON (`{"ok":true,"result":{...}}`). `--full` prints the complete record Orca returned, as text or with `--json` as pretty JSON. A failed or unconfirmed outcome exits non-zero and writes `error: : ` to stderr. +Every orchestration command prints a short view by default: the IDs and state the next command needs, with the next step last. `--json` prints the same fields as one line of JSON (`{"ok":true,"result":{...}}`). `--full --json` prints the complete record Orca returned as pretty JSON; `--full` alone prints the longer text receipt. A failed or unconfirmed outcome exits non-zero and writes `error: : ` to stderr. ## Core model @@ -48,7 +48,7 @@ orca orchestration worker-start --task --worktree new-child --name bill orca orchestration worker-start --task --worktree current --agent claude --model --effort high ``` -`--agent` takes any Orca agent ID enabled on the worker server, for example `claude`, `codex`, `cursor`, `antigravity`, `muse`, `opencode`, or `opencode2`. `--model` accepts opaque provider model IDs for Claude, Codex, Cursor, Antigravity, Grok, and Muse (for example `--agent muse --model muse-spark-1.3`); OpenCode accepts a per-launch model only in an existing worktree, when the execution host verifies its CLI version and model availability; OpenCode effort remains unsupported. Other agents run the model from their own config. `--effort` requires `--model` and only applies when that agent/model supports the level. Neither flag can combine with `--terminal` (reuse an existing pane). Overrides apply to that launch only and show as `model` / `effort` in the start receipt (`--full` shows `launch.requested` / `launch.effective`). Federated starts need a worker host that advertises launch-preference support. +`--agent` takes any Orca agent ID enabled on the worker server, for example `claude`, `codex`, `cursor`, `antigravity`, `muse`, `opencode`, or `opencode2`. `--model` accepts opaque provider model IDs for Claude, Codex, Cursor, Antigravity, Grok, and Muse (for example `--agent muse --model muse-spark-1.3`); OpenCode accepts a per-launch model only in an existing worktree, when the execution host verifies its CLI version and model availability; OpenCode effort remains unsupported. Other agents run the model from their own config. `--effort` requires `--model` and only applies when that agent/model supports the level. Neither flag can combine with `--terminal` (reuse an existing pane). Overrides apply to that launch only and show as `model` / `effort` in the start receipt (`--full --json` shows `launch.requested` / `launch.effective`). Federated starts need a worker host that advertises launch-preference support. After starting workers, end your turn. Orca wakes the coordinator when a worker reports, asks, or stops; run the `check` command the wake gives you and handle every message it prints: @@ -80,8 +80,8 @@ orca orchestration worker-stop --dispatch # After an accepted worker_done: reuse the same terminal for a follow-up Dispatch, or release it # (archives inspectable output, then closes only that coordinator-owned agent terminal): orca orchestration worker-release --dispatch -# Keep a settled worker live for debugging when the user asked to retain it: -orca orchestration worker-retain --dispatch +# Keep a worker open after it finishes (or start it with worker-start --keep-open): +orca orchestration worker-keep-open --dispatch # retry placement is explicit — --retry-of does not inherit --on/worktree: orca orchestration worker-start --task --retry-of --worktree current --agent codex ``` @@ -115,7 +115,7 @@ orca orchestration dispatch --task --to --inject ## Messaging notes - Default `check` returns the bound Run's oldest unread mail as one Delivery (FIFO) and marks it handled. `--ack ` acknowledges a Delivery from an older Orca that does not mark it; alone it reads no new mail, and with `--wait` it then waits for and takes the next Delivery. -- `--peek` / `--all` do not consume mail and return no `deliveryId`, so they do not drain a mailbox on their own. `--all` and a Run `--peek` show at most 100 rows. To drain, repeat plain `check` until it prints `No messages.` (with `--json`, until `messages` is empty). +- `--peek` / `--all` do not consume mail and return no `deliveryId`, so they do not drain a mailbox on their own. `--all` and a Run `--peek` show at most 100 rows. To drain, repeat plain `check` until it prints `No messages.` (with `--json`, until `messages` is empty); on an older Orca that asks for `--ack `, ack each Delivery first or `check` returns it again. - Group addresses: `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, `@worktree:` — never for `worker_done`. - Every group except `@worktree:` means the live Dispatches of the sender's own Run, delivered to their Dispatch mailboxes (or child Run mailboxes for nested coordinators). A sender in no Run is refused; `--run` must match the audience and never grants membership. - Run groups exclude their owning coordinator. A worker raising a blocker sends to `run:`. `@worktree:` includes coordinators in that workspace. diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index 68d12af9e51..20a52f6da62 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -65,8 +65,9 @@ Never: - Lost track? `ORCA orchestration inbox --terminal run: --limit 50` shows mail `check` already handled. -Finished workers close on their own unless the user chose Keep open. To keep one -for a follow-up, run `ORCA orchestration worker-retain --dispatch `. +Finished workers close on their own unless the user chose Keep open. If the user +wants to watch a worker, start it with `--keep-open`; to keep one already started, +run `ORCA orchestration worker-keep-open --dispatch `. If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself. ## Task spec diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 9345e070437..f286637f478 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -2543,8 +2543,9 @@ const ORCHESTRATION_MARKDOWN = [ "- Lost track? `ORCA orchestration inbox --terminal run: --limit 50`", " shows mail `check` already handled.", "", - "Finished workers close on their own unless the user chose Keep open. To keep one", - "for a follow-up, run `ORCA orchestration worker-retain --dispatch `.", + "Finished workers close on their own unless the user chose Keep open. If the user", + "wants to watch a worker, start it with `--keep-open`; to keep one already started,", + "run `ORCA orchestration worker-keep-open --dispatch `.", "If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself.", "", "## Task spec", diff --git a/src/cli/command-body-input.test.ts b/src/cli/command-body-input.test.ts new file mode 100644 index 00000000000..36abf50c76c --- /dev/null +++ b/src/cli/command-body-input.test.ts @@ -0,0 +1,56 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { readTextOrFileFlag } from './command-body-input' + +const SPEC = 'Run `pnpm test` and say "done" when it\'s $HOME-free' + +describe('readTextOrFileFlag', () => { + let dir: string | undefined + let restoreStdin: (() => void) | undefined + + afterEach(() => { + restoreStdin?.() + restoreStdin = undefined + if (dir) { + rmSync(dir, { recursive: true, force: true }) + dir = undefined + } + }) + + it('reads the file relative to the caller cwd without shell interpretation', async () => { + dir = mkdtempSync(join(tmpdir(), 'orca-spec-file-')) + writeFileSync(join(dir, 'spec.md'), SPEC) + const flags = new Map([['spec-file', 'spec.md']]) + await expect(readTextOrFileFlag(flags, dir, 'spec', true)).resolves.toBe(SPEC) + }) + + it('reads stdin for -', async () => { + const stdin = process.stdin + const previousIsTTY = stdin.isTTY + Object.defineProperty(stdin, 'isTTY', { configurable: true, value: false }) + Object.defineProperty(stdin, Symbol.asyncIterator, { + configurable: true, + value: async function* () { + yield SPEC + } + }) + restoreStdin = () => { + Object.defineProperty(stdin, 'isTTY', { configurable: true, value: previousIsTTY }) + Reflect.deleteProperty(stdin, Symbol.asyncIterator) + } + const flags = new Map([['spec-file', '-']]) + await expect(readTextOrFileFlag(flags, '/', 'spec', true)).resolves.toBe(SPEC) + }) + + it('refuses the text and file flags together', async () => { + const flags = new Map([ + ['spec', 'inline'], + ['spec-file', 'spec.md'] + ]) + await expect(readTextOrFileFlag(flags, '/', 'spec', false)).rejects.toThrow( + 'Use either --spec or --spec-file, not both' + ) + }) +}) diff --git a/src/cli/command-body-input.ts b/src/cli/command-body-input.ts index 9c200dcb6ae..edcb03bb537 100644 --- a/src/cli/command-body-input.ts +++ b/src/cli/command-body-input.ts @@ -25,21 +25,8 @@ export async function readCommandBody( cwd: string, options: BodyOptions ): Promise { - const hasBody = flags.has('body') - const hasBodyFile = flags.has('body-file') - if (hasBody && hasBodyFile) { - throw new RuntimeClientError('invalid_argument', 'Use either --body or --body-file, not both') - } - if (!hasBody && !hasBodyFile) { - if (options.required) { - throw new RuntimeClientError('invalid_argument', 'Missing --body or --body-file') - } - return undefined - } - const body = hasBody - ? getRequiredStringFlagAllowingEmpty(flags, 'body') - : await readBodyFile(getRequiredStringFlag(flags, 'body-file'), cwd) - if (body.length > options.maximumCharacters) { + const body = await readTextOrFileFlag(flags, cwd, 'body', options.required) + if (body !== undefined && body.length > options.maximumCharacters) { throw new RuntimeClientError( options.tooLargeCode, `${options.label} must be at most ${options.maximumCharacters} characters` @@ -48,6 +35,33 @@ export async function readCommandBody( return body } +/** Reads `-- ` or `---file `, refusing both. */ +export async function readTextOrFileFlag( + flags: Map, + cwd: string, + flag: string, + required: boolean +): Promise { + const fileFlag = `${flag}-file` + const hasText = flags.has(flag) + const hasFile = flags.has(fileFlag) + if (hasText && hasFile) { + throw new RuntimeClientError( + 'invalid_argument', + `Use either --${flag} or --${fileFlag}, not both` + ) + } + if (!hasText && !hasFile) { + if (required) { + throw new RuntimeClientError('invalid_argument', `Missing --${flag} or --${fileFlag}`) + } + return undefined + } + return hasText + ? getRequiredStringFlagAllowingEmpty(flags, flag) + : readBodyFile(getRequiredStringFlag(flags, fileFlag), cwd) +} + async function readBodyFile(path: string, cwd: string): Promise { if (path !== '-') { return readFile(isAbsolute(path) ? path : join(cwd, path), 'utf8') diff --git a/src/cli/flag-help-text.ts b/src/cli/flag-help-text.ts index b98bf48be98..fbbd7914a99 100644 --- a/src/cli/flag-help-text.ts +++ b/src/cli/flag-help-text.ts @@ -30,6 +30,8 @@ export const FLAG_HELP_TEXT: Record = { help: '--help Show this help message', 'include-visual-layouts': '--include-visual-layouts Include tab and pane topology in JSON output', interrupt: '--interrupt Send as an interrupt-style input when supported', + 'keep-open': '--keep-open Keep the worker open after it finishes', + 'spec-file': '--spec-file Read the spec from a file or stdin', id: '--id Identifier for a target item or permission', issue: '--issue Linked GitHub issue number', 'gitlab-issue': diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index bd7674739e7..9bc54fd61d1 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -144,6 +144,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'orchestration worker-stop', 'orchestration worker-abandon', 'orchestration worker-release', + 'orchestration worker-keep-open', 'orchestration worker-retain', 'orchestration worker-list', 'orchestration dispatch', diff --git a/src/cli/handlers/orchestration-worker-cli.test.ts b/src/cli/handlers/orchestration-worker-cli.test.ts index 5bfc5d3a329..96d39e31319 100644 --- a/src/cli/handlers/orchestration-worker-cli.test.ts +++ b/src/cli/handlers/orchestration-worker-cli.test.ts @@ -12,8 +12,10 @@ import { ORCHESTRATION_HANDLERS } from './orchestration' import { printResult } from '../format' import { parseArgs, validateCommandAndFlags } from '../args' import { formatCommandHelp } from '../help' +import { buildAgentContext } from '../agent-context' +import { suggestCommands } from '../command-suggestion' import { okFixture } from '../test-fixtures' -import { RuntimeClient } from '../runtime-client' +import { RuntimeClient, RuntimeClientError } from '../runtime-client' import { ORCHESTRATION_WORKER_COMMAND_SPECS } from '../specs/orchestration-worker-specs' import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../shared/protocol-version' @@ -739,10 +741,8 @@ describe('orchestration worker-start CLI contract', () => { }) it('keeps cleanup and retention TTL controls off the public CLI surface', async () => { - const retained = parseArgs(['orchestration', 'worker-retain', '--dispatch', 'ctx_1']) - expect(() => - validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, retained) - ).not.toThrow() + const kept = parseArgs(['orchestration', 'worker-keep-open', '--dispatch', 'ctx_1']) + expect(() => validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, kept)).not.toThrow() expect(() => validateCommandAndFlags( ORCHESTRATION_WORKER_COMMAND_SPECS, @@ -752,21 +752,15 @@ describe('orchestration worker-start CLI contract', () => { expect(() => validateCommandAndFlags( ORCHESTRATION_WORKER_COMMAND_SPECS, - parseArgs(['orchestration', 'worker-retain', '--until', '2099-01-01T00:00:00Z']) + parseArgs(['orchestration', 'worker-keep-open', '--until', '2099-01-01T00:00:00Z']) ) - ).toThrow('Unknown flag --until for command: orchestration worker-retain') - expect(() => - validateCommandAndFlags( - ORCHESTRATION_WORKER_COMMAND_SPECS, - parseArgs(['orchestration', 'worker-retain', '--policy', 'forever']) - ) - ).toThrow('Unknown flag --policy for command: orchestration worker-retain') + ).toThrow('Unknown flag --until for command: orchestration worker-keep-open') callMock.mockResolvedValue({ result: { dispatchId: 'ctx_1', state: 'retained', processAction: 'none' } }) - await ORCHESTRATION_HANDLERS['orchestration worker-retain']({ - flags: retained.flags, + await ORCHESTRATION_HANDLERS['orchestration worker-keep-open']({ + flags: kept.flags, client, cwd: '/tmp/repo', json: true @@ -774,6 +768,87 @@ describe('orchestration worker-start CLI contract', () => { expect(callMock).toHaveBeenCalledWith('orchestration.workerRetain', { dispatch: 'ctx_1' }) }) + it('still runs worker-retain without listing or suggesting it', () => { + const parsed = parseArgs(['orchestration', 'worker-retain', '--dispatch', 'ctx_1']) + expect(() => validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, parsed)).not.toThrow() + expect(ORCHESTRATION_HANDLERS['orchestration worker-retain']).toBe( + ORCHESTRATION_HANDLERS['orchestration worker-keep-open'] + ) + const listed = buildAgentContext(ORCHESTRATION_WORKER_COMMAND_SPECS).commands + expect(JSON.stringify(listed)).not.toContain('worker-retain') + expect( + suggestCommands(ORCHESTRATION_WORKER_COMMAND_SPECS, ['orchestration', 'worker-retai']) + ).not.toContain('orchestration worker-retain') + }) + + it('keeps a worker started with --keep-open open after it finishes', async () => { + callMock.mockImplementation(async (method: string) => + method === 'orchestration.workerStart' + ? { result: { taskId: 'task_1', dispatchId: 'ctx_1', state: 'ready', effects: [] } } + : { result: { dispatchId: 'ctx_1', state: 'retained', processAction: 'none' } } + ) + await invokeWorkerStart( + new Map([ + ['task', 'task_1'], + ['agent', 'codex'], + ['keep-open', true] + ]), + false + ) + expect(callMock).toHaveBeenLastCalledWith('orchestration.workerRetain', { dispatch: 'ctx_1' }) + expect(printedText()).toContain('keptOpen=true') + }) + + it.each([ + [ + 'released', + { result: { dispatchId: 'ctx_1', state: 'already_released', processAction: 'none' } }, + 'worker-read' + ], + [ + 'no owned terminal', + { + result: { + dispatchId: 'ctx_1', + state: 'retained', + reason: 'no_owned_resource', + processAction: 'none' + } + }, + 'worker-show' + ], + ['error', new RuntimeClientError('runtime_unavailable', 'gone'), 'worker-keep-open'] + ])( + 'prints the start receipt then fails a --keep-open that was not kept (%s)', + async (_, retain, verb) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + callMock.mockImplementation(async (method: string) => { + if (method === 'orchestration.workerStart') { + return { result: { taskId: 'task_1', dispatchId: 'ctx_1', state: 'ready', effects: [] } } + } + if (method === 'orchestration.workerRetain' && retain instanceof Error) { + throw retain + } + return retain + }) + await invokeWorkerStart( + new Map([ + ['task', 'task_1'], + ['agent', 'codex'], + ['keep-open', true] + ]), + false + ) + const text = printedText() + expect(text).toContain('dispatchId=ctx_1') + expect(text).not.toContain('keptOpen') + const error = String(vi.mocked(console.error).mock.calls[0]?.[0]) + expect(error).toContain('not_kept_open') + expect(error).toContain(`${verb} --dispatch ctx_1`) + expect(process.exitCode).toBe(1) + } + ) + it('does not tell a coordinator that chat workers skip automatic release', () => { const spec = ORCHESTRATION_WORKER_COMMAND_SPECS.find( (entry) => entry.path.join(' ') === 'orchestration worker-release' diff --git a/src/cli/handlers/orchestration/agent-view.test.ts b/src/cli/handlers/orchestration/agent-view.test.ts index a826720d8b5..d23b6533b82 100644 --- a/src/cli/handlers/orchestration/agent-view.test.ts +++ b/src/cli/handlers/orchestration/agent-view.test.ts @@ -99,6 +99,19 @@ describe('orchestration agent views', () => { expect(process.exitCode).toBe(1) }) + it('escapes terminal control bytes in worker-written fields', async () => { + const { stdout } = await run('worker-start', [['task', 'task_1']], { + ...OLDER_RUNTIME_START, + state: 'failed', + failedStage: 'agent\x1b]0;x\x07', + lastError: 'bad \x9b31m output' + }) + for (const raw of ['\x1b', '\x07', '\x9b']) { + expect(stdout).not.toContain(raw) + } + expect(stdout).toContain('failedStage=agent\\x1b]0;x\\x07') + }) + it('prints a question with its payload kept apart and a reply command for this executable', async () => { const question = { id: 'msg_q', diff --git a/src/cli/handlers/orchestration/agent-view.ts b/src/cli/handlers/orchestration/agent-view.ts index e4ca3fdf95e..0e7e9742f7f 100644 --- a/src/cli/handlers/orchestration/agent-view.ts +++ b/src/cli/handlers/orchestration/agent-view.ts @@ -5,6 +5,7 @@ import { renderCommand } from '../../orchestration-mutation-recovery' import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command' import type { RuntimeRpcSuccess } from '../../runtime-client' import { withReceiptNext } from './receipt-next-text' +import { escapeTerminalControlCharacters } from '../../../shared/terminal-control-character-escape' type AgentViewFields = Record @@ -115,8 +116,8 @@ function formatFieldValue(value: unknown): string { return value.length ? value.map(formatFieldValue).join(',') : 'none' } const text = typeof value === 'string' ? value : JSON.stringify(value) - // Quote anything that would split a name=value pair. - return /^[^\s"',=]+$/.test(text) ? text : JSON.stringify(text) + // Quote anything that would split a name=value pair; never pass raw control bytes to the terminal. + return escapeTerminalControlCharacters(/^[^\s"',=]+$/.test(text) ? text : JSON.stringify(text)) } function isFieldRecord(value: unknown): value is AgentViewFields { diff --git a/src/cli/handlers/orchestration/task-handlers.ts b/src/cli/handlers/orchestration/task-handlers.ts index cfc00bb1fb5..b5647fe55a7 100644 --- a/src/cli/handlers/orchestration/task-handlers.ts +++ b/src/cli/handlers/orchestration/task-handlers.ts @@ -6,6 +6,7 @@ import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' import { RuntimeClientError } from '../../runtime-client' import { abbreviateOrchestrationTasks } from '../../../shared/orchestration-task-summary' import { callOrchestrationMutation } from './mutation-request' +import { readTextOrFileFlag } from '../../command-body-input' import { resolveCoordinatorTerminalHandle, runScopedSessionCaller } from './terminal-identity' const TASK_STATUS_VALUES = [ @@ -25,7 +26,7 @@ export const ORCHESTRATION_TASK_HANDLERS: Record = { flags, 'orchestration.taskCreate', { - spec: getRequiredStringFlag(flags, 'spec'), + spec: await readTextOrFileFlag(flags, cwd, 'spec', true), taskTitle: getOptionalStringFlag(flags, 'task-title'), displayName: getOptionalStringFlag(flags, 'display-name'), deps: getOptionalStringFlag(flags, 'deps'), diff --git a/src/cli/handlers/orchestration/worker-launch-handler.ts b/src/cli/handlers/orchestration/worker-launch-handler.ts index 0265313c35c..21ba03b8d2f 100644 --- a/src/cli/handlers/orchestration/worker-launch-handler.ts +++ b/src/cli/handlers/orchestration/worker-launch-handler.ts @@ -2,18 +2,23 @@ import type { CommandHandler } from '../../dispatch' import { printResult } from '../../format' import { withReceiptNext } from './receipt-next-text' import { getOptionalStringFlag, getPresentStringFlag } from '../../flags' -import { RuntimeClientError } from '../../runtime-client' +import { RuntimeClientError, type RuntimeClient } from '../../runtime-client' import type { RuntimeStatus } from '../../../shared/runtime-types' import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../../shared/protocol-version' import { callOrchestrationMutation } from './mutation-request' import { getOptionalPositiveIntegerValueFlag } from './numeric-flags' import { isDevCliInvocation } from './runtime-compatibility' import { resolveCoordinatorTerminalHandle } from './terminal-identity' -import { formatWorkerStart } from './worker-output' -import { WORKER_START_VIEW } from './worker-start-agent-view' -import { printOrchestrationResult } from './agent-view' +import { formatWorkerStart, type WorkerReleaseReceipt } from './worker-output' +import { isUnobservedTurnStart, WORKER_START_VIEW } from './worker-start-agent-view' +import { + printOrchestrationResult, + renderOrchestrationArgv, + reportOrchestrationFailure +} from './agent-view' import { explainOlderRuntimeRunRequired } from './older-runtime-run-binding' import { renderResolvedOrchestrationCommand } from '../../orchestration-mutation-recovery' +import { readTextOrFileFlag } from '../../command-body-input' export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record = { 'orchestration worker-start': async ({ flags, client, cwd, json }) => { @@ -34,7 +39,7 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record } } const task = getOptionalStringFlag(flags, 'task') - const spec = getOptionalStringFlag(flags, 'spec') + const spec = await readTextOrFileFlag(flags, cwd, 'spec', false) const taskTitle = getOptionalStringFlag(flags, 'task-title') const deps = getOptionalStringFlag(flags, 'deps') const parent = getOptionalStringFlag(flags, 'parent') @@ -80,21 +85,61 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record if (result.result.state !== 'ready') { process.exitCode = 1 } - const renderedResult = result.result.nextCommands - ? { - ...result, - result: { - ...result.result, - nextCommands: result.result.nextCommands.map((command) => - renderResolvedOrchestrationCommand(command) - ) - } - } - : result - if (!flags.has('full')) { + const keepOpenState = + flags.has('keep-open') && + (result.result.state === 'ready' || isUnobservedTurnStart(result.result)) + ? await keepWorkerOpen(client, result.result.dispatchId) + : undefined + const renderedResult = { + ...result, + result: { + ...result.result, + ...(keepOpenState === 'retained' ? { keptOpen: true as const } : {}), + ...(result.result.nextCommands + ? { + nextCommands: result.result.nextCommands.map((command) => + renderResolvedOrchestrationCommand(command) + ) + } + : {}) + } + } + if (flags.has('full')) { + printResult(renderedResult, json, (value) => + withReceiptNext( + `${formatWorkerStart(value)}${value.keptOpen ? '\nKept open after it finishes' : ''}`, + value + ) + ) + } else { printOrchestrationResult(renderedResult, json, WORKER_START_VIEW) - return + } + if (keepOpenState && keepOpenState !== 'retained') { + const dispatchId = result.result.dispatchId + // The worker runs either way, so the next step never starts it again. + const verb = + keepOpenState === 'already_released' + ? 'worker-read' + : keepOpenState.startsWith('release_') || keepOpenState === 'no_owned_resource' + ? 'worker-show' + : 'worker-keep-open' + reportOrchestrationFailure({ + code: 'not_kept_open', + message: `${dispatchId} started but was not kept open (${keepOpenState}). Run ${renderOrchestrationArgv(['orchestration', verb, '--dispatch', dispatchId])}.` + }) } - printResult(renderedResult, json, (value) => withReceiptNext(formatWorkerStart(value), value)) + } +} + +// Every host version serves workerRetain, so older servers keep the worker open too. +async function keepWorkerOpen(client: RuntimeClient, dispatch: string): Promise { + try { + const { result } = await client.call('orchestration.workerRetain', { + dispatch + }) + // A retained receipt without an owned terminal kept nothing open. + return result.reason === 'no_owned_resource' ? result.reason : result.state + } catch (error) { + return error instanceof RuntimeClientError ? error.code : 'keep_open_failed' } } diff --git a/src/cli/handlers/orchestration/worker-start-agent-view.ts b/src/cli/handlers/orchestration/worker-start-agent-view.ts index b1886918ec0..eae30bef29d 100644 --- a/src/cli/handlers/orchestration/worker-start-agent-view.ts +++ b/src/cli/handlers/orchestration/worker-start-agent-view.ts @@ -15,10 +15,11 @@ export type WorkerStartAgentReceipt = WorkerStartReceipt & { stage?: string turnStart?: string next?: string + keptOpen?: true } // A hook-capable agent that has not shown its turn yet is usually slow, not dead; a resend duplicates the task. -function isUnobservedTurnStart(value: WorkerStartAgentReceipt): boolean { +export function isUnobservedTurnStart(value: WorkerStartAgentReceipt): boolean { return ( value.state === 'outcome_unknown' && (value.turnStart === 'unobserved' || value.stage === 'turn_start_unobserved') @@ -43,6 +44,7 @@ type WorkerStartFields = { warning?: string residualResources?: string[] nextCommands?: string[] + keptOpen?: true next?: string } @@ -76,6 +78,7 @@ export const WORKER_START_VIEW: OrchestrationAgentView { + const result = await callOrchestrationMutation( + client, + flags, + 'orchestration.workerRetain', + { dispatch: getRequiredStringFlag(flags, 'dispatch') } + ) + if (!flags.has('full')) { + printOrchestrationResult(result, json, WORKER_RELEASE_VIEW) + return + } + if (result.result.state === 'release_unknown') { + process.exitCode = 1 + } + printResult(result, json, formatWorkerRelease) +} + export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record = { 'orchestration worker-stop': async ({ flags, client, json }) => { const result = await callOrchestrationMutation<{ @@ -88,22 +105,8 @@ export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record { - const result = await callOrchestrationMutation( - client, - flags, - 'orchestration.workerRetain', - { dispatch: getRequiredStringFlag(flags, 'dispatch') } - ) - if (!flags.has('full')) { - printOrchestrationResult(result, json, WORKER_RELEASE_VIEW) - return - } - if (result.result.state === 'release_unknown') { - process.exitCode = 1 - } - printResult(result, json, formatWorkerRelease) - }, + 'orchestration worker-keep-open': keepWorkerOpen, + 'orchestration worker-retain': keepWorkerOpen, 'orchestration worker-list': async ({ flags, client, cwd, json }) => { const terminalState = getOptionalStringFlag(flags, 'terminal-state') diff --git a/src/cli/orchestration-mutation-recovery.ts b/src/cli/orchestration-mutation-recovery.ts index f79d2094cd0..d005d7d9e36 100644 --- a/src/cli/orchestration-mutation-recovery.ts +++ b/src/cli/orchestration-mutation-recovery.ts @@ -47,7 +47,14 @@ export function orchestrationMutationRecoveryError(error: unknown): unknown { ? `After inspecting the Dispatch, if keyed recovery is still needed, run ${renderCommand(retryCommand)} from this same terminal. --retry-request reuses the same operation identity so Orca can replay, join, or safely recover it without starting a separate duplicate.` : `If request-show reports completed or pending, run ${renderCommand(retryCommand)} from this same terminal. --retry-request reuses the same operation identity so Orca can replay, join, or safely recover it without starting a separate duplicate. If request-show reports absent, inspect the affected state before deciding whether to retry; absence does not prove a retry is safe.` : 'Recovery is blocked until the exact original command is available; no retry command was emitted.' - const nextSteps = [`Run ${renderCommand(queryCommand)} before retrying.`, retryStep] + const readsStdin = retryCommand?.some( + (arg, i) => arg === '-' && /^--[\w-]+-file$/.test(retryCommand[i - 1] ?? '') + ) + const nextSteps = [ + `Run ${renderCommand(queryCommand)} before retrying.`, + retryStep, + ...(readsStdin ? ['Pipe the same input into the retry again; it reads stdin.'] : []) + ] const message = [ stripUnsafeRetryAdvice(error.message, requestId), 'The orchestration mutation may already have taken effect; do not assume it failed.', diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index 3504fcfd68c..a30a904b4d3 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -141,7 +141,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' orchestration worker-stop Fence one Dispatch; stop only its supervised worker', ' orchestration worker-abandon Fence an uncertain worker without claiming it stopped', " orchestration worker-release Release a settled worker's terminal after archiving its output", - ' orchestration worker-retain Keep a worker terminal live for debugging', + ' orchestration worker-keep-open Keep a worker open after it finishes', ' orchestration worker-list Report worker terminal resource accounting', ' orchestration coordinator-start Retired: load the current orchestration skill', ' orchestration coordinator-stop Retired: load the current orchestration skill', diff --git a/src/cli/runtime/orchestration-recovery-command.test.ts b/src/cli/runtime/orchestration-recovery-command.test.ts index 68c0a72c507..96c78edb50c 100644 --- a/src/cli/runtime/orchestration-recovery-command.test.ts +++ b/src/cli/runtime/orchestration-recovery-command.test.ts @@ -112,7 +112,7 @@ describe('orchestration recovery command identity', () => { ).toEqual(['orca-ide', 'orchestration', 'worker-stop', '--dispatch', 'dispatch_1']) }) - it('reconstructs worker-retain when raw argv is unavailable', () => { + it('reconstructs worker-keep-open when raw argv is unavailable', () => { expect( buildOrchestrationRecoveryCommand('orchestration.workerRetain', { dispatch: 'dispatch_1' @@ -120,7 +120,7 @@ describe('orchestration recovery command identity', () => { ).toEqual([ resolveOrchestrationCliExecutable(), 'orchestration', - 'worker-retain', + 'worker-keep-open', '--dispatch', 'dispatch_1' ]) diff --git a/src/cli/runtime/orchestration-recovery-command.ts b/src/cli/runtime/orchestration-recovery-command.ts index 706b1656ac6..65a44121419 100644 --- a/src/cli/runtime/orchestration-recovery-command.ts +++ b/src/cli/runtime/orchestration-recovery-command.ts @@ -52,7 +52,7 @@ export function buildOrchestrationRecoveryCommand( : method === 'orchestration.workerRelease' ? 'worker-release' : method === 'orchestration.workerRetain' - ? 'worker-retain' + ? 'worker-keep-open' : undefined if (!command || params === null || typeof params !== 'object') { return undefined diff --git a/src/cli/specs/orchestration-gate-specs.ts b/src/cli/specs/orchestration-gate-specs.ts new file mode 100644 index 00000000000..57ee98d0cb9 --- /dev/null +++ b/src/cli/specs/orchestration-gate-specs.ts @@ -0,0 +1,29 @@ +import { GLOBAL_FLAGS, type CommandSpec } from '../args' + +export const ORCHESTRATION_GATE_COMMAND_SPECS: CommandSpec[] = [ + { + path: ['orchestration', 'gate-create'], + summary: 'Create a decision gate blocking a task', + usage: + 'orca orchestration gate-create --task --question [--options ] [--from ] [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'task', 'question', 'options', 'from', 'retry-request'], + identityFlagRoles: { from: 'caller' } + }, + { + path: ['orchestration', 'gate-resolve'], + summary: 'Resolve a pending decision gate', + usage: + 'orca orchestration gate-resolve --id --resolution [--from ] [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'id', 'resolution', 'from', 'retry-request'], + identityFlagRoles: { from: 'caller' } + }, + { + path: ['orchestration', 'gate-list'], + summary: 'List decision gates', + usage: + 'orca orchestration gate-list [--task ] [--status ] [--run ] [--from ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'task', 'status', 'run', 'from'], + identityFlagRoles: { from: 'caller' }, + notes: ['--run inspects a named Run without binding; otherwise gates are scoped to the caller.'] + } +] diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index 68f1887b658..4a050b1620f 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -5,11 +5,13 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'worker-start'], summary: 'Start one supervised worker on the Run home or a connected Orca server', usage: - 'orca orchestration worker-start (--task | --spec ) [--on ] [--worktree ] (--agent | --terminal ) [--task-title ] [--deps ] [--parent ] [--model ] [--effort ] [--name ] [--repo ] [--base-branch ] [--display-name ] [--comment ] [--setup ] [--retry-of ] [--timeout-ms ] [--run ] [--from ] [--retry-request ] [--json]', + 'orca orchestration worker-start (--task | --spec | --spec-file ) [--keep-open] [--on ] [--worktree ] (--agent | --terminal ) [--task-title ] [--deps ] [--parent ] [--model ] [--effort ] [--name ] [--repo ] [--base-branch ] [--display-name ] [--comment ] [--setup ] [--retry-of ] [--timeout-ms ] [--run ] [--from ] [--retry-request ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'task', 'spec', + 'spec-file', + 'keep-open', 'task-title', 'deps', 'parent', @@ -49,7 +51,9 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ '--on selects only the worker server; the Run and this command remain on the current Orca server.', 'Remote current and new-child are invalid; discover an exact remote selector or use new-top-level.', '--retry-of needs --task naming the failed Task (--spec creates a new one) and does not inherit placement; repeat the intended --on/worktree and --agent/terminal choices.', - 'The call exits 0 only for ready. Failed or outcome_unknown exits 1 and JSON includes stage/failedStage, setup, effects, residualResources, and recovery commands when needed.' + '--spec-file reads the spec from a file (relative to the current directory) or stdin (-) on this machine, so quotes and backticks need no shell escaping.', + '--keep-open keeps the worker open after it finishes, as worker-keep-open does right after start.', + 'The call exits 0 for ready, and in the concise view for a start whose turn was not yet observed (--full exits 1 for anything but ready). Failed or outcome_unknown exits 1 and JSON includes stage/failedStage, setup, effects, residualResources, and recovery commands when needed.' ] }, { @@ -109,14 +113,14 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'An inspectable output archive is preserved before the terminal closes, so worker-read still returns output afterwards.', 'Never closes setup terminals, configured tabs, reused or pre-existing terminals, terminals the user kept open, or unproven identities.', 'Idempotent: repeating the call reports already_released. Only release_unknown exits 1; retained, release_pending, and already_released exit 0.', - 'On a runtime that advertises orchestration.worker-auto-release.v1, an accepted worker_done already schedules this release about 2 minutes later (autoReleaseAt in worker-show and worker-list); call it only to release sooner or to clear a worker-retain. Chat workers follow autoReleaseAt too. autoReleaseAt is absent while its agent works again, and set afresh when it next goes idle.' + 'On a runtime that advertises orchestration.worker-auto-release.v1, an accepted worker_done already schedules this release about 2 minutes later (autoReleaseAt in worker-show and worker-list); call it only to release sooner or to clear a worker-keep-open. Chat workers follow autoReleaseAt too. autoReleaseAt is absent while its agent works again, and set afresh when it next goes idle.' ] }, { - path: ['orchestration', 'worker-retain'], - summary: 'Keep one supervised worker terminal live for debugging', + path: ['orchestration', 'worker-keep-open'], + summary: 'Keep a worker open after it finishes', usage: - 'orca orchestration worker-retain --dispatch [--retry-request ] [--json]', + 'orca orchestration worker-keep-open --dispatch [--retry-request ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'], notes: [ 'Records a durable user-requested exception; a later explicit worker-release clears it and releases the terminal.', @@ -126,6 +130,15 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'Performs no process or filesystem action.' ] }, + { + // Old name of worker-keep-open; hidden so it runs for existing scripts but is never suggested. + path: ['orchestration', 'worker-retain'], + hidden: true, + summary: 'Keep a worker open after it finishes (old name of worker-keep-open)', + usage: + 'orca orchestration worker-retain --dispatch [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'] + }, { path: ['orchestration', 'worker-list'], summary: 'List supervised worker terminal resource accounting', @@ -134,7 +147,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ allowedFlags: [...GLOBAL_FLAGS, 'run', 'terminal-state', 'include-remote', 'cursor', 'limit'], notes: [ 'Terminal state is process accounting and is reported separately from Task status; a completed Task can still own a live terminal.', - 'A reclaimable worker with resource.autoReleaseAt is released automatically at that time unless it is reused with worker-start --terminal, retained, or kept open by the user.', + 'A reclaimable worker with resource.autoReleaseAt is released automatically at that time unless it is reused with worker-start --terminal or kept open (worker-keep-open, worker-start --keep-open, or the user).', 'Context-only Dispatches created by orchestration dispatch are included as unsupervised with terminal state retained.', 'Returns at most 100 local rows, newest first, by default; --include-remote adds connected-server observations when the host supports fleet listing. Continue with the opaque nextCursor value unchanged.', 'Without --run the list is scoped to the Run bound to the calling terminal, and to every Run when there is no binding; the receipt reports which in scope.source (flag, bound, or all).' diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 927b72a310a..92adc2421ca 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -1,4 +1,5 @@ import { GLOBAL_FLAGS, type CommandSpec } from '../args' +import { ORCHESTRATION_GATE_COMMAND_SPECS } from './orchestration-gate-specs' import { ORCHESTRATION_WORKER_COMMAND_SPECS } from './orchestration-worker-specs' export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ @@ -139,10 +140,11 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'task-create'], summary: 'Create an orchestration task', usage: - 'orca orchestration task-create --spec [--task-title ] [--display-name ] [--deps ] [--parent ] [--run ] [--from ] [--retry-request ] [--json]', + 'orca orchestration task-create (--spec | --spec-file ) [--task-title ] [--display-name ] [--deps ] [--parent ] [--run ] [--from ] [--retry-request ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'spec', + 'spec-file', 'task-title', 'display-name', 'deps', @@ -265,31 +267,7 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ 'This command performs no effects and returns the exact `skills get orchestration --full` recovery action.' ] }, - { - path: ['orchestration', 'gate-create'], - summary: 'Create a decision gate blocking a task', - usage: - 'orca orchestration gate-create --task --question [--options ] [--from ] [--retry-request ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'task', 'question', 'options', 'from', 'retry-request'], - identityFlagRoles: { from: 'caller' } - }, - { - path: ['orchestration', 'gate-resolve'], - summary: 'Resolve a pending decision gate', - usage: - 'orca orchestration gate-resolve --id --resolution [--from ] [--retry-request ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'id', 'resolution', 'from', 'retry-request'], - identityFlagRoles: { from: 'caller' } - }, - { - path: ['orchestration', 'gate-list'], - summary: 'List decision gates', - usage: - 'orca orchestration gate-list [--task ] [--status ] [--run ] [--from ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'task', 'status', 'run', 'from'], - identityFlagRoles: { from: 'caller' }, - notes: ['--run inspects a named Run without binding; otherwise gates are scoped to the caller.'] - }, + ...ORCHESTRATION_GATE_COMMAND_SPECS, { path: ['orchestration', 'reset'], destructive: true, diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts index a20e483e7d1..f7d60beb56a 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts @@ -82,7 +82,7 @@ export function abandonWorkerDispatch( reconcileTaskAfterDispatchInterruption(this, dispatch.task_id, dispatchId) this.closeQuestionsForDispatch(dispatchId) const terminal = this.getWorkerTerminalResourceByOwner(dispatchId) - // Abandon hands an owned terminal back instead of closing it, by the same rule as worker-retain. + // Abandon hands an owned terminal back instead of closing it, by the same rule as worker-keep-open. if (terminal?.ownership_state === 'owned') { retainTerminalResourceInTransaction(this, terminal.id, dispatchId) } diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts index 955b48d9a92..5b28d3582b3 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts @@ -234,7 +234,7 @@ export function retainWorkerTerminalResource( }) } -/** The execution host's half of a forwarded worker-retain. */ +/** The execution host's half of a forwarded worker-keep-open. */ export function retainRemoteAttachmentTerminalResource( this: OrchestrationDb, dispatchId: string diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts index 8c90d8b2da8..d71b7813645 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts @@ -102,7 +102,7 @@ export const ORCHESTRATION_WORKER_RELEASE_METHODS = [ if (!orchestrationMutation) { throw new OrchestrationError( 'invalid_argument', - 'Remote worker-retain requires a durable retry request.' + 'Remote worker-keep-open requires a durable retry request.' ) } db.endFederatedHomeAutoRelease(params.dispatch) diff --git a/src/shared/cli-argument-boundary.ts b/src/shared/cli-argument-boundary.ts index c6c5962eb05..1c4f819bcdc 100644 --- a/src/shared/cli-argument-boundary.ts +++ b/src/shared/cli-argument-boundary.ts @@ -35,6 +35,7 @@ export const CLI_BOOLEAN_FLAGS = new Set([ 'index-status', 'interactive', 'interrupt', + 'keep-open', 'json', 'latest-json', 'local',