Add --spec-file and one keep-open name to orchestration worker commands (#36545)

worker-start and task-create take --spec-file <path> (or - for stdin). worker-start --keep-open keeps a worker open after it finishes in one step, and worker-keep-open replaces worker-retain (kept as a hidden alias). Concise text output escapes terminal control characters in worker-written values.
This commit is contained in:
Jinwoo Hong
2026-10-31 01:23:25 -04:00
committed by GitHub
parent 48a1c512e3
commit 47b7af097c
25 changed files with 363 additions and 119 deletions
+5 -5
View File
@@ -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: <code>: <message>` 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: <code>: <message>` to stderr.
## Core model
@@ -48,7 +48,7 @@ orca orchestration worker-start --task <taskId> --worktree new-child --name bill
orca orchestration worker-start --task <taskId> --worktree current --agent claude --model <opaque-model-id> --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 <dispatchId>
# 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 <dispatchId>
# Keep a settled worker live for debugging when the user asked to retain it:
orca orchestration worker-retain --dispatch <dispatchId>
# Keep a worker open after it finishes (or start it with worker-start --keep-open):
orca orchestration worker-keep-open --dispatch <dispatchId>
# retry placement is explicit — --retry-of does not inherit --on/worktree:
orca orchestration worker-start --task <taskId> --retry-of <dispatchId> --worktree current --agent codex
```
@@ -115,7 +115,7 @@ orca orchestration dispatch --task <taskId> --to <workerHandle> --inject
## Messaging notes
- Default `check` returns the bound Run's oldest unread mail as one Delivery (FIFO) and marks it handled. `--ack <deliveryId>` 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 <deliveryId>`, ack each Delivery first or `check` returns it again.
- Group addresses: `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, `@worktree:<id>` — never for `worker_done`.
- Every group except `@worktree:<id>` 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:<id>`. `@worktree:<id>` includes coordinators in that workspace.
+3 -2
View File
@@ -65,8 +65,9 @@ Never:
- Lost track? `ORCA orchestration inbox --terminal run:<run_id> --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 <dispatch_id>`.
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 <dispatch_id>`.
If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself.
## Task spec
+3 -2
View File
@@ -2543,8 +2543,9 @@ const ORCHESTRATION_MARKDOWN = [
"- Lost track? `ORCA orchestration inbox --terminal run:<run_id> --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 <dispatch_id>`.",
"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 <dispatch_id>`.",
"If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself.",
"",
"## Task spec",
+56
View File
@@ -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<string, string | boolean>([['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<string, string | boolean>([['spec-file', '-']])
await expect(readTextOrFileFlag(flags, '/', 'spec', true)).resolves.toBe(SPEC)
})
it('refuses the text and file flags together', async () => {
const flags = new Map<string, string | boolean>([
['spec', 'inline'],
['spec-file', 'spec.md']
])
await expect(readTextOrFileFlag(flags, '/', 'spec', false)).rejects.toThrow(
'Use either --spec or --spec-file, not both'
)
})
})
+29 -15
View File
@@ -25,21 +25,8 @@ export async function readCommandBody(
cwd: string,
options: BodyOptions
): Promise<string | undefined> {
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 `--<flag> <text>` or `--<flag>-file <path|->`, refusing both. */
export async function readTextOrFileFlag(
flags: Map<string, string | boolean>,
cwd: string,
flag: string,
required: boolean
): Promise<string | undefined> {
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<string> {
if (path !== '-') {
return readFile(isAbsolute(path) ? path : join(cwd, path), 'utf8')
+2
View File
@@ -30,6 +30,8 @@ export const FLAG_HELP_TEXT: Record<string, string> = {
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 <path|-> Read the spec from a file or stdin',
id: '--id <id> Identifier for a target item or permission',
issue: '--issue <number|null> Linked GitHub issue number',
'gitlab-issue':
+1
View File
@@ -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',
@@ -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<string, string | boolean>([
['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<string, string | boolean>([
['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'
@@ -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',
+3 -2
View File
@@ -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<string, unknown>
@@ -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 {
@@ -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<string, CommandHandler> = {
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'),
@@ -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<string, CommandHandler> = {
'orchestration worker-start': async ({ flags, client, cwd, json }) => {
@@ -34,7 +39,7 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record<string, CommandHandler>
}
}
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<string, CommandHandler>
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<string> {
try {
const { result } = await client.call<WorkerReleaseReceipt>('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'
}
}
@@ -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<WorkerStartAgentReceipt,
residualResources:
value.state !== 'ready' && !unobserved && residual.length ? residual : undefined,
nextCommands: value.state === 'ready' || unobserved ? undefined : value.nextCommands,
keptOpen: value.keptOpen,
next: unobserved
? `Task typed in but the worker hasn't been seen starting; don't resend or abandon it. End your turn; Orca wakes you when it reports. If nothing arrives, run ${renderOrchestrationArgv(['orca', 'orchestration', 'worker-show', '--dispatch', value.dispatchId])}.`
: value.recovery
@@ -22,6 +22,23 @@ const WORKER_TERMINAL_LIST_STATES = [
'released'
] as const
const keepWorkerOpen: CommandHandler = async ({ flags, client, json }) => {
const result = await callOrchestrationMutation<WorkerReleaseReceipt>(
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<string, CommandHandler> = {
'orchestration worker-stop': async ({ flags, client, json }) => {
const result = await callOrchestrationMutation<{
@@ -88,22 +105,8 @@ export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record<string, CommandHandl
printResult(result, json, formatWorkerRelease)
},
'orchestration worker-retain': async ({ flags, client, json }) => {
const result = await callOrchestrationMutation<WorkerReleaseReceipt>(
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')
+8 -1
View File
@@ -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.',
+1 -1
View File
@@ -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',
@@ -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'
])
@@ -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
+29
View File
@@ -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 <task_id> --question <text> [--options <json_array>] [--from <handle>] [--retry-request <id>] [--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 <gate_id> --resolution <text> [--from <handle>] [--retry-request <id>] [--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 <task_id>] [--status <status>] [--run <run_id>] [--from <handle>] [--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.']
}
]
+20 -7
View File
@@ -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 <task_id> | --spec <text>) [--on <saved-environment>] [--worktree <current|selector|new-child|new-top-level>] (--agent <agent> | --terminal <handle>) [--task-title <text>] [--deps <json_array>] [--parent <task_id>] [--model <id>] [--effort <level>] [--name <name>] [--repo <selector>] [--base-branch <ref>] [--display-name <text>] [--comment <text>] [--setup <run|skip|inherit>] [--retry-of <dispatch_id>] [--timeout-ms <n>] [--run <run_id>] [--from <handle>] [--retry-request <id>] [--json]',
'orca orchestration worker-start (--task <task_id> | --spec <text> | --spec-file <path|->) [--keep-open] [--on <saved-environment>] [--worktree <current|selector|new-child|new-top-level>] (--agent <agent> | --terminal <handle>) [--task-title <text>] [--deps <json_array>] [--parent <task_id>] [--model <id>] [--effort <level>] [--name <name>] [--repo <selector>] [--base-branch <ref>] [--display-name <text>] [--comment <text>] [--setup <run|skip|inherit>] [--retry-of <dispatch_id>] [--timeout-ms <n>] [--run <run_id>] [--from <handle>] [--retry-request <id>] [--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 <dispatch_id> [--retry-request <id>] [--json]',
'orca orchestration worker-keep-open --dispatch <dispatch_id> [--retry-request <id>] [--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 <dispatch_id> [--retry-request <id>] [--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).'
+4 -26
View File
@@ -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 <text> [--task-title <text>] [--display-name <text>] [--deps <json_array>] [--parent <task_id>] [--run <run_id>] [--from <handle>] [--retry-request <id>] [--json]',
'orca orchestration task-create (--spec <text> | --spec-file <path|->) [--task-title <text>] [--display-name <text>] [--deps <json_array>] [--parent <task_id>] [--run <run_id>] [--from <handle>] [--retry-request <id>] [--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 <task_id> --question <text> [--options <json_array>] [--from <handle>] [--retry-request <id>] [--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 <gate_id> --resolution <text> [--from <handle>] [--retry-request <id>] [--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 <task_id>] [--status <status>] [--run <run_id>] [--from <handle>] [--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,
@@ -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)
}
@@ -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
@@ -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)
+1
View File
@@ -35,6 +35,7 @@ export const CLI_BOOLEAN_FLAGS = new Set([
'index-status',
'interactive',
'interrupt',
'keep-open',
'json',
'latest-json',
'local',