@cleocode/adapters 2026.10.27 → 2026.11.1-canary.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +2 -0
  2. package/dist/.source-stamp.json +4 -0
  3. package/dist/index.js +2694 -1895
  4. package/dist/index.js.map +3 -3
  5. package/dist/manifests.d.ts +25 -0
  6. package/dist/manifests.d.ts.map +1 -0
  7. package/dist/manifests.js +28 -0
  8. package/dist/manifests.js.map +6 -0
  9. package/dist/orca-execution.d.ts +90 -0
  10. package/dist/orca-execution.d.ts.map +1 -0
  11. package/dist/orca-execution.js +843 -0
  12. package/dist/orca-execution.js.map +6 -0
  13. package/dist/providers/claude-code/index.js +46728 -0
  14. package/dist/providers/claude-code/index.js.map +6 -0
  15. package/dist/providers/claude-code/lead-mcp.d.ts +99 -0
  16. package/dist/providers/claude-code/lead-mcp.d.ts.map +1 -0
  17. package/dist/providers/claude-code/lead-session.d.ts +133 -0
  18. package/dist/providers/claude-code/lead-session.d.ts.map +1 -0
  19. package/dist/providers/claude-code/spawn.d.ts +39 -0
  20. package/dist/providers/claude-code/spawn.d.ts.map +1 -1
  21. package/dist/providers/claude-sdk/index.js +44567 -0
  22. package/dist/providers/claude-sdk/index.js.map +6 -0
  23. package/dist/providers/claude-sdk/spawn.d.ts +6 -0
  24. package/dist/providers/claude-sdk/spawn.d.ts.map +1 -1
  25. package/dist/providers/codex/index.js +19333 -0
  26. package/dist/providers/codex/index.js.map +6 -0
  27. package/dist/providers/codex/spawn.d.ts +2 -0
  28. package/dist/providers/codex/spawn.d.ts.map +1 -1
  29. package/dist/providers/cursor/index.js +637 -0
  30. package/dist/providers/cursor/index.js.map +6 -0
  31. package/dist/providers/cursor/spawn.d.ts +2 -0
  32. package/dist/providers/cursor/spawn.d.ts.map +1 -1
  33. package/dist/providers/gemini-cli/index.js +18895 -0
  34. package/dist/providers/gemini-cli/index.js.map +6 -0
  35. package/dist/providers/gemini-cli/spawn.d.ts +2 -0
  36. package/dist/providers/gemini-cli/spawn.d.ts.map +1 -1
  37. package/dist/providers/kimi/index.js +18824 -0
  38. package/dist/providers/kimi/index.js.map +6 -0
  39. package/dist/providers/kimi/spawn.d.ts +2 -0
  40. package/dist/providers/kimi/spawn.d.ts.map +1 -1
  41. package/dist/providers/openai-sdk/adapter.d.ts +1 -1
  42. package/dist/providers/openai-sdk/index.d.ts +0 -1
  43. package/dist/providers/openai-sdk/index.d.ts.map +1 -1
  44. package/dist/providers/openai-sdk/index.js +44208 -0
  45. package/dist/providers/openai-sdk/index.js.map +6 -0
  46. package/dist/providers/openai-sdk/spawn.d.ts +4 -2
  47. package/dist/providers/openai-sdk/spawn.d.ts.map +1 -1
  48. package/dist/providers/openai-sdk/tracing.d.ts +8 -82
  49. package/dist/providers/openai-sdk/tracing.d.ts.map +1 -1
  50. package/dist/providers/opencode/index.js +19335 -0
  51. package/dist/providers/opencode/index.js.map +6 -0
  52. package/dist/providers/opencode/spawn.d.ts +2 -0
  53. package/dist/providers/opencode/spawn.d.ts.map +1 -1
  54. package/dist/providers/pi/index.js +18471 -0
  55. package/dist/providers/pi/index.js.map +6 -0
  56. package/dist/providers/pi/spawn.d.ts +2 -0
  57. package/dist/providers/pi/spawn.d.ts.map +1 -1
  58. package/dist/providers/shared/lead-tool-strip.d.ts +52 -0
  59. package/dist/providers/shared/lead-tool-strip.d.ts.map +1 -0
  60. package/dist/registry.d.ts +2 -55
  61. package/dist/registry.d.ts.map +1 -1
  62. package/package.json +14 -6
  63. package/src/__tests__/harness-interop.test.ts +0 -7
  64. package/src/__tests__/orca-execution-fixture.ts +422 -0
  65. package/src/__tests__/orca-execution.test.ts +1357 -0
  66. package/src/__tests__/orca-plugin-panel.test.ts +661 -0
  67. package/src/__tests__/orca-plugin.test.ts +660 -0
  68. package/src/manifests.ts +55 -0
  69. package/src/orca-execution.ts +1193 -0
  70. package/src/providers/claude-code/__tests__/lead-mcp.test.ts +348 -0
  71. package/src/providers/claude-code/__tests__/worker-exit-settings.test.ts +32 -0
  72. package/src/providers/claude-code/lead-mcp.ts +244 -0
  73. package/src/providers/claude-code/lead-session.ts +241 -0
  74. package/src/providers/claude-code/spawn.ts +180 -11
  75. package/src/providers/claude-sdk/__tests__/spawn.test.ts +63 -3
  76. package/src/providers/claude-sdk/spawn.ts +28 -1
  77. package/src/providers/codex/spawn.ts +5 -0
  78. package/src/providers/cursor/spawn.ts +3 -0
  79. package/src/providers/gemini-cli/spawn.ts +5 -0
  80. package/src/providers/kimi/spawn.ts +5 -0
  81. package/src/providers/openai-sdk/__tests__/openai-sdk-spawn.test.ts +0 -80
  82. package/src/providers/openai-sdk/adapter.ts +1 -1
  83. package/src/providers/openai-sdk/index.ts +0 -1
  84. package/src/providers/openai-sdk/manifest.json +1 -1
  85. package/src/providers/openai-sdk/spawn.ts +10 -16
  86. package/src/providers/openai-sdk/tracing.ts +8 -169
  87. package/src/providers/opencode/spawn.ts +5 -0
  88. package/src/providers/pi/spawn.ts +5 -0
  89. package/src/providers/shared/__tests__/lead-tool-strip.test.ts +126 -0
  90. package/src/providers/shared/lead-tool-strip.ts +76 -0
  91. package/src/registry.ts +2 -78
  92. package/dist/providers/shared/conduit-trace-writer.d.ts +0 -72
  93. package/dist/providers/shared/conduit-trace-writer.d.ts.map +0 -1
  94. package/src/providers/shared/conduit-trace-writer.ts +0 -101
@@ -0,0 +1,1193 @@
1
+ /**
2
+ * Local Orca execution, with no task-store, claim or filesystem disposal authority.
3
+ * @packageDocumentation
4
+ */
5
+ import { execFile } from 'node:child_process';
6
+ import { isAbsolute } from 'node:path';
7
+ import type {
8
+ OrcaAttempt,
9
+ OrcaCommandReply,
10
+ OrcaCommandResult,
11
+ OrcaCommandRunner,
12
+ OrcaContext,
13
+ OrcaDiscovery,
14
+ OrcaLaunch,
15
+ OrcaReply,
16
+ OrcaReportSource,
17
+ OrcaRoutingAdapter,
18
+ OrcaWorkerDone,
19
+ } from '@cleocode/contracts/orca-execution.js';
20
+ import {
21
+ ORCA_LEAD_LAUNCH_REFUSAL,
22
+ orcaAccountReplySchema,
23
+ orcaCommandRegistrySchema,
24
+ orcaContextSchema,
25
+ orcaLaunchSchema,
26
+ orcaReplySchema,
27
+ orcaReportMessageSchema,
28
+ orcaReportSourceSchema,
29
+ orcaWorkerDonePayloadSchema,
30
+ } from '@cleocode/contracts/orca-execution.js';
31
+
32
+ const AGENTS = { 'claude-code': 'claude', codex: 'codex', opencode: 'opencode2', grok: 'grok' };
33
+ const REQUIRED_COMMANDS = {
34
+ 'orchestration worker-start': [
35
+ 'from',
36
+ 'spec-file',
37
+ 'task',
38
+ 'run',
39
+ 'worktree',
40
+ 'agent',
41
+ 'retry-of',
42
+ 'retry-request',
43
+ 'full',
44
+ 'model',
45
+ 'effort',
46
+ ],
47
+ 'orchestration worker-show': ['dispatch', 'full'],
48
+ 'orchestration worker-read': ['dispatch', 'source', 'limit', 'cursor', 'full'],
49
+ 'orchestration worker-stop': ['dispatch', 'retry-request', 'full'],
50
+ 'orchestration request-show': ['request', 'full'],
51
+ 'orchestration run-current': ['from', 'full'],
52
+ 'worktree show': ['worktree'],
53
+ };
54
+
55
+ /** Helper outcomes that prove Orca released the helper rather than leaving it running. */
56
+ const SETTLED_HELPER_OUTCOMES = new Set(['stopped', 'already_finished']);
57
+
58
+ /** Runtime capability proving worker-stop enumerates every helper it stopped. */
59
+ const HELPER_STOP_CAPABILITY = 'orchestration.worker-stop-helpers.v1';
60
+
61
+ /** Bounded creator chain walk; a helper nested under another helper needs its own link. */
62
+ const HELPER_ANCESTRY_LIMIT = 8;
63
+
64
+ /**
65
+ * What a stored receipt proves about the helpers a stopped worker started.
66
+ * @remarks `settled` is affirmative evidence that no helper is still running;
67
+ * `absent` is no trustworthy evidence at all (lost, malformed or non-stop
68
+ * receipt); `empty` is a stop reply that listed no helpers; `unresolved` names
69
+ * the helper Dispatches a stop reply could not settle.
70
+ */
71
+ type HelperEvidence =
72
+ | { readonly kind: 'absent' }
73
+ | { readonly kind: 'empty' }
74
+ | { readonly kind: 'settled' }
75
+ | {
76
+ readonly kind: 'unresolved';
77
+ readonly dispatchIds: readonly string[];
78
+ readonly reconcileable: boolean;
79
+ };
80
+
81
+ /**
82
+ * Read the helper evidence a stored receipt carries for exactly this attempt.
83
+ * @remarks Only a stop reply speaks about helpers, and only a listing of each
84
+ * helper proves it stopped. A lost, malformed or non-stop receipt is `absent`,
85
+ * which never settles a stop. A receipt that belongs to another attempt (another
86
+ * Dispatch, Run, runtime epoch or stop request key) is `absent` too, so a
87
+ * mismatched stop reply can never be promoted later by a parent release. A stop
88
+ * reply's `helperStopError` means the tree may be incomplete, so it is `absent`.
89
+ * @param attempt - The attempt whose stop the retained receipt would settle.
90
+ * @param receipt - Last stored raw receipt, or null when none was retained.
91
+ * @returns The evidence class and any helper Dispatch ids still unresolved.
92
+ * @example
93
+ * ```ts
94
+ * readHelperEvidence(attempt, '{"ok":true,"result":{"dispatchId":"ctx_1","processAction":"closed_agent_terminal","helpers":[],"mutation":{"requestId":"<issued stop key>"}}}');
95
+ * ```
96
+ */
97
+ function readHelperEvidence(attempt: OrcaAttempt, receipt: string | null): HelperEvidence {
98
+ if (!receipt) return { kind: 'absent' };
99
+ let reply: OrcaReply;
100
+ try {
101
+ const parsed = orcaReplySchema.safeParse(JSON.parse(receipt));
102
+ if (!parsed.success) return { kind: 'absent' };
103
+ reply = parsed.data;
104
+ } catch {
105
+ return { kind: 'absent' };
106
+ }
107
+ if (!receiptBelongsToAttempt(attempt, reply)) return { kind: 'absent' };
108
+ const value = reply.result;
109
+ const stopReply =
110
+ value !== undefined &&
111
+ (value.processAction !== undefined ||
112
+ value.helpers !== undefined ||
113
+ value.helperStopError !== undefined);
114
+ if (!value || !stopReply) return { kind: 'absent' };
115
+ if (value.helperStopError) return { kind: 'absent' };
116
+ // A stop reply that omits the helper list enumerated nothing this client can read.
117
+ if (value.helpers === undefined) return { kind: 'empty' };
118
+ const unresolved = value.helpers.filter((helper) => !SETTLED_HELPER_OUTCOMES.has(helper.outcome));
119
+ if (unresolved.length === 0) return { kind: 'settled' };
120
+ return {
121
+ kind: 'unresolved',
122
+ dispatchIds: [
123
+ ...new Set(
124
+ unresolved
125
+ .map((helper) => helper.dispatchId)
126
+ .filter((dispatchId): dispatchId is string => dispatchId !== undefined),
127
+ ),
128
+ ],
129
+ reconcileable: unresolved.every((helper) => helper.dispatchId !== undefined),
130
+ };
131
+ }
132
+
133
+ /**
134
+ * Prove a retained reply was produced by this attempt's own mutation.
135
+ * @remarks The runtime epoch, target Dispatch, Run (when the reply names one)
136
+ * and the issued stop request key must all match the stored binding. A refusal
137
+ * names the key under `error.data.orchestrationRequestId`; a successful mutation
138
+ * names it under `result.mutation.requestId` (installed Orca stamps the ledger
139
+ * identity on every successful result), so a successful receipt with no key or
140
+ * another attempt's key is never evidence either. Anything that fails is another
141
+ * attempt's receipt and never evidence.
142
+ * @param attempt - The attempt the receipt is being read for.
143
+ * @param reply - Parsed reply from the retained receipt.
144
+ * @returns True only when every identity the reply carries matches this attempt.
145
+ */
146
+ function receiptBelongsToAttempt(attempt: OrcaAttempt, reply: OrcaReply): boolean {
147
+ if (reply._meta?.runtimeId !== attempt.context.runtimeId) return false;
148
+ const value = reply.result;
149
+ const dispatchId = value?.dispatchId ?? reply.error?.data?.dispatchId;
150
+ if (!attempt.dispatchId || dispatchId !== attempt.dispatchId) return false;
151
+ if (value?.runId !== undefined && value.runId !== attempt.runId) return false;
152
+ const refusedKey = reply.error?.data?.orchestrationRequestId;
153
+ if (refusedKey !== undefined) return stopsThisAttempt(attempt, refusedKey);
154
+ if (reply.ok) {
155
+ // A successful mutation always carries its ledger key; only the stop key this
156
+ // attempt issued may settle it, so another mutation on the same Dispatch cannot.
157
+ const succeededKey = value?.mutation?.requestId;
158
+ return succeededKey !== undefined && stopsThisAttempt(attempt, succeededKey);
159
+ }
160
+ return true;
161
+ }
162
+
163
+ /**
164
+ * Compare a reply's request key with the stop key this attempt issued.
165
+ * @param attempt - The attempt whose stop key would be settled.
166
+ * @param requestId - Request key the reply reports.
167
+ * @returns True when the reply belongs to this attempt's own stop request.
168
+ */
169
+ function stopsThisAttempt(attempt: OrcaAttempt, requestId: string): boolean {
170
+ return requestId === attempt.stopRequestKey || requestId === attempt.stopRequestId;
171
+ }
172
+
173
+ /** Actionable refusal; callers must retain any attempt already sent to Orca. */
174
+ export class OrcaExecutionError extends Error {
175
+ /** Numeric CLI refusal status, independent of a worker's exit. */
176
+ readonly exitCode = 63;
177
+ /** Stable refusal code. */
178
+ readonly code: string;
179
+ /** Recovery instruction that never disables the lead policy. */
180
+ readonly fix: string;
181
+ /** Original unparseable receipt, when available. */
182
+ readonly receipt: string | null;
183
+
184
+ /** Construct a refusal before any unsupported operation runs. */
185
+ constructor(code: string, message: string, fix: string, receipt: string | null = null) {
186
+ super(message);
187
+ this.name = 'OrcaExecutionError';
188
+ this.code = code;
189
+ this.fix = fix;
190
+ this.receipt = receipt;
191
+ }
192
+ }
193
+
194
+ /** Bounded argv-only process runner; stdin carries the prepared prompt unchanged. */
195
+ export const runOrcaCommand: OrcaCommandRunner = (executable, args, cwd, input) =>
196
+ new Promise((resolve) => {
197
+ const child = execFile(
198
+ executable,
199
+ [...args],
200
+ { cwd, encoding: 'utf8', timeout: 90_000, maxBuffer: 4 * 1024 * 1024 },
201
+ (error, stdout, stderr) =>
202
+ resolve({
203
+ stdout,
204
+ stderr: stderr || error?.message || '',
205
+ exitCode: error ? (typeof error.code === 'number' ? error.code : null) : 0,
206
+ }),
207
+ );
208
+ // EPIPE is reported through the process result, never as evidence of worker exit.
209
+ child.stdin?.on('error', () => undefined);
210
+ child.stdin?.end(input);
211
+ });
212
+
213
+ /**
214
+ * Execution backend around a selected harness, deliberately absent from the
215
+ * provider registry. Core persists each operation before invoking these methods.
216
+ */
217
+ export class OrcaExecutionBackend implements OrcaRoutingAdapter {
218
+ /** Public launch APIs cannot enforce denied tools or a strict MCP allowlist. */
219
+ readonly leadToolStrip = 'unsupported';
220
+ private readonly executable: string;
221
+
222
+ /** Resolve the session executable once; never fall through to another runtime. */
223
+ constructor(
224
+ private readonly runner: OrcaCommandRunner = runOrcaCommand,
225
+ executable = process.env.ORCA_CLI_COMMAND ||
226
+ (process.env.ORCA_DEV_REPO_ROOT
227
+ ? 'orca-dev'
228
+ : process.platform === 'linux'
229
+ ? 'orca-ide'
230
+ : 'orca'),
231
+ ) {
232
+ this.executable = executable;
233
+ }
234
+
235
+ /** Inspect hints without spawning a process; this cannot select an execution backend. */
236
+ hasContextHints(): boolean {
237
+ return Boolean(
238
+ process.env.ORCA_TERMINAL_HANDLE ||
239
+ process.env.ORCA_WORKTREE_ID ||
240
+ process.env.ORCA_WORKSPACE_ID ||
241
+ process.env.ORCA_RUNTIME_SOURCE_ID ||
242
+ process.env.ORCA_APP_VERSION,
243
+ );
244
+ }
245
+
246
+ /** Verify the local caller before returning a sanitized account inventory. */
247
+ async discover(projectRoot: string): Promise<OrcaDiscovery | null> {
248
+ if (!this.hasContextHints()) return null;
249
+ const handle = process.env.ORCA_TERMINAL_HANDLE;
250
+ if (!handle) {
251
+ throw new OrcaExecutionError(
252
+ 'E_ORCA_CONTEXT',
253
+ 'Orca environment hints have no runtime-issued coordinator handle.',
254
+ 'Run this command in the intended Orca agent session with its ORCA_TERMINAL_HANDLE; TERM_PROGRAM alone cannot select a caller.',
255
+ );
256
+ }
257
+ const status = await this.invoke(['status'], projectRoot);
258
+ const runtimeId = status._meta?.runtimeId;
259
+ if (!status.ok || !runtimeId) {
260
+ throw new OrcaExecutionError(
261
+ 'E_ORCA_CONTEXT',
262
+ 'The selected local Orca runtime cannot verify this caller.',
263
+ 'Inspect orca status --json in the intended Orca session and restore that runtime before dispatch.',
264
+ );
265
+ }
266
+ const context: OrcaContext = { runtimeId, coordinatorHandle: handle, executionHostId: 'local' };
267
+ await this.verifyRuntime(projectRoot, context);
268
+ const caller = await this.query(
269
+ ['terminal', 'show', '--terminal', handle],
270
+ projectRoot,
271
+ context,
272
+ );
273
+ const terminal = caller.result?.terminal;
274
+ if (
275
+ terminal?.handle !== handle ||
276
+ terminal.executionHostId !== 'local' ||
277
+ !terminal.connected ||
278
+ !terminal.writable
279
+ ) {
280
+ throw new OrcaExecutionError(
281
+ 'E_ORCA_CONTEXT',
282
+ 'Orca did not prove a unique connected local coordinator.',
283
+ 'Inspect orca terminal show --terminal <handle> --json and run from that live local Orca session; do not substitute a different caller.',
284
+ );
285
+ }
286
+ // account list is host-local and rejects --environment; never retain its private stdout.
287
+ try {
288
+ const accounts = await this.runner(
289
+ this.executable,
290
+ ['account', 'list', '--json'],
291
+ projectRoot,
292
+ );
293
+ if (accounts.exitCode !== 0) throw new Error('inventory unavailable');
294
+ const { result, _meta } = orcaAccountReplySchema.parse(JSON.parse(accounts.stdout));
295
+ if (_meta.runtimeId !== context.runtimeId) throw new Error('account runtime changed');
296
+ return {
297
+ context,
298
+ accounts: (['codex', 'opencode', 'claude'] as const).map((provider) => ({
299
+ provider,
300
+ accountCount: result[provider].accounts.length,
301
+ activeAccountPresent: result[provider].activeAccountId !== null,
302
+ })),
303
+ };
304
+ } catch {
305
+ throw new OrcaExecutionError(
306
+ 'E_ORCA_ACCOUNT_UNAVAILABLE',
307
+ 'Orca returned no verifiable local account availability.',
308
+ 'Inspect orca account list --json locally and select an active account for an agent in orchestrate.orca.agents.',
309
+ );
310
+ }
311
+ }
312
+
313
+ /** Read the Run currently bound to the original local coordinator, without mutation. */
314
+ async currentRun(projectRoot: string, context: OrcaContext): Promise<string | null> {
315
+ await this.verifyRuntime(projectRoot, context);
316
+ const reply = await this.query(
317
+ ['orchestration', 'run-current', '--from', context.coordinatorHandle],
318
+ projectRoot,
319
+ context,
320
+ );
321
+ const run = reply.result?.run;
322
+ if (run === undefined) {
323
+ throw new OrcaExecutionError(
324
+ 'E_ORCA_CONTEXT',
325
+ 'Orca did not prove the coordinator Run binding.',
326
+ 'Inspect orca orchestration run-current --from <handle> --json in the original local runtime before dispatch.',
327
+ );
328
+ }
329
+ return run?.id ?? null;
330
+ }
331
+
332
+ /** Verify supported commands, exact runtime and existing canonical workspace. */
333
+ async preflight(
334
+ launch: OrcaLaunch,
335
+ context: OrcaContext,
336
+ ): Promise<Pick<OrcaAttempt, 'workspaceId' | 'workspaceSelector'>> {
337
+ this.validateLaunch(launch, context);
338
+ const registryResult = await this.runner(
339
+ this.executable,
340
+ ['agent-context', '--json'],
341
+ launch.projectRoot,
342
+ );
343
+ if (registryResult.exitCode !== 0) {
344
+ throw new OrcaExecutionError(
345
+ 'E_ORCA_CONTEXT',
346
+ 'The selected Orca CLI is unavailable.',
347
+ 'Inspect the selected Orca executable and runtime; do not substitute a native launch.',
348
+ registryResult.stdout,
349
+ );
350
+ }
351
+ let registry: ReturnType<typeof orcaCommandRegistrySchema.parse>;
352
+ try {
353
+ registry = orcaCommandRegistrySchema.parse(JSON.parse(registryResult.stdout));
354
+ } catch {
355
+ throw new OrcaExecutionError(
356
+ 'E_ORCA_COMMAND_UNSUPPORTED',
357
+ 'The selected Orca CLI returned no valid command registry.',
358
+ 'Update the selected Orca CLI and runtime together, then repeat read-only preflight.',
359
+ registryResult.stdout,
360
+ );
361
+ }
362
+ for (const [command, flags] of Object.entries(REQUIRED_COMMANDS)) {
363
+ const declared = registry.commands.find((entry) => entry.command === command);
364
+ if (!declared || flags.some((flag) => !declared.flags.includes(flag))) {
365
+ throw new OrcaExecutionError(
366
+ 'E_ORCA_COMMAND_UNSUPPORTED',
367
+ `Installed Orca does not declare ${command} with required flags.`,
368
+ 'Update the selected Orca CLI and runtime together, then repeat read-only preflight.',
369
+ );
370
+ }
371
+ }
372
+ await this.verifyRuntime(launch.projectRoot, context, launch.model !== undefined);
373
+ const workspace = await this.query(
374
+ ['worktree', 'show', '--worktree', `path:${launch.worktreePath}`],
375
+ launch.projectRoot,
376
+ context,
377
+ ).catch((error: Error) => {
378
+ throw new OrcaExecutionError(
379
+ 'E_ORCA_WORKSPACE',
380
+ error.message,
381
+ 'Inspect orca status --json and orca worktree show --worktree <exact-selector> --json; resolve ambiguous entries for the existing canonical checkout before dispatch. Do not create a replacement checkout.',
382
+ );
383
+ });
384
+ const tree = workspace.result?.worktree;
385
+ if (
386
+ !tree ||
387
+ tree.path !== launch.worktreePath ||
388
+ tree.hostId !== context.executionHostId ||
389
+ tree.branch.replace(/^refs\/heads\//, '') !== launch.worktreeBranch
390
+ ) {
391
+ throw new OrcaExecutionError(
392
+ 'E_ORCA_WORKSPACE',
393
+ 'Orca did not resolve the exact local CLEO worktree.',
394
+ 'Register the existing canonical checkout in Orca and resolve duplicate workspace entries explicitly.',
395
+ );
396
+ }
397
+ return { workspaceId: tree.id, workspaceSelector: tree.address?.worktree ?? `id:${tree.id}` };
398
+ }
399
+
400
+ private validateLaunch(launch: OrcaLaunch, context: OrcaContext): void {
401
+ if (
402
+ !orcaLaunchSchema.safeParse(launch).success ||
403
+ !orcaContextSchema.safeParse(context).success
404
+ ) {
405
+ throw new OrcaExecutionError(
406
+ 'E_ORCA_CONTEXT',
407
+ 'The prepared assignment or explicit Orca caller is incomplete.',
408
+ 'Use canonical CLEO preparation and an explicitly verified local runtime and coordinator handle.',
409
+ );
410
+ }
411
+ if (launch.role === 'lead') {
412
+ throw new OrcaExecutionError(
413
+ ORCA_LEAD_LAUNCH_REFUSAL.code,
414
+ ORCA_LEAD_LAUNCH_REFUSAL.message,
415
+ ORCA_LEAD_LAUNCH_REFUSAL.fix,
416
+ );
417
+ }
418
+ if (launch.accountId !== undefined) {
419
+ throw new OrcaExecutionError(
420
+ 'E_ORCA_ACCOUNT_UNSUPPORTED',
421
+ 'Exact per-worker account placement is unavailable.',
422
+ 'Omit the account constraint to use Orca’s active account for the selected harness.',
423
+ );
424
+ }
425
+ if (launch.harness === 'kimi') {
426
+ throw new OrcaExecutionError(
427
+ 'E_ORCA_HARNESS_UNSUPPORTED',
428
+ 'Kimi requires a proven terminal adoption path.',
429
+ 'Use a supported Orca harness or the separately supervised Kimi terminal pilot.',
430
+ );
431
+ }
432
+ if (!isAbsolute(launch.worktreePath) || launch.worktreeBranch !== `task/${launch.taskId}`) {
433
+ throw new OrcaExecutionError(
434
+ 'E_ORCA_WORKSPACE',
435
+ 'The assignment does not name a canonical task checkout.',
436
+ 'Prepare the task once through cleo orchestrate spawn and preserve its worktree binding.',
437
+ );
438
+ }
439
+ if (launch.effort && (!launch.model || launch.harness === 'opencode')) {
440
+ throw new OrcaExecutionError(
441
+ 'E_ORCA_MODEL_UNSUPPORTED',
442
+ 'Effort requires a model and is unsupported for OpenCode.',
443
+ 'Omit effort or select a supported harness/model route explicitly.',
444
+ );
445
+ }
446
+ }
447
+
448
+ /** Start only a persisted launching attempt; no exit code is worker completion. */
449
+ async start(attempt: OrcaAttempt): Promise<OrcaAttempt> {
450
+ if (
451
+ attempt.state !== 'launching' ||
452
+ attempt.startRequestId ||
453
+ attempt.dispatchId ||
454
+ attempt.failureCount >= 3
455
+ ) {
456
+ throw new OrcaExecutionError(
457
+ 'E_ORCA_ATTEMPT_FENCED',
458
+ 'This attempt cannot start another worker.',
459
+ 'Inspect the stored exact Dispatch; recover an uncertain request by its issued id.',
460
+ );
461
+ }
462
+ return this.startCommand(attempt, attempt.startRequestKey);
463
+ }
464
+
465
+ /** Replay an issued or pre-reserved retry key on the same runtime and caller. */
466
+ async replayStart(attempt: OrcaAttempt): Promise<OrcaAttempt> {
467
+ const requestId = attempt.startRequestKey ?? attempt.startRequestId;
468
+ if (
469
+ attempt.state !== 'outcome_unknown' ||
470
+ !requestId ||
471
+ !attempt.startBinding ||
472
+ attempt.failureCount >= 3
473
+ ) {
474
+ throw new OrcaExecutionError(
475
+ 'E_ORCA_ATTEMPT_FENCED',
476
+ 'No replayable uncertain start request is retained.',
477
+ 'Inspect the original operation; never substitute a fresh Run, Task or launch.',
478
+ );
479
+ }
480
+ await this.verifyRequest(attempt, requestId);
481
+ return this.startCommand(attempt, requestId);
482
+ }
483
+
484
+ /**
485
+ * Inspect exactly this attempt, settling a reserved stop only on release proof.
486
+ * @remarks A stop settles only when the parent's exact release and affirmative
487
+ * helper evidence agree. A lost, malformed or non-stop receipt is never helper
488
+ * evidence; each helper the receipt names is re-read from Orca, so one that
489
+ * finishes later can still settle the stop.
490
+ */
491
+ async show(attempt: OrcaAttempt): Promise<OrcaAttempt> {
492
+ const dispatchId = this.requireDispatch(attempt);
493
+ const reply = await this.query(
494
+ ['orchestration', 'worker-show', '--dispatch', dispatchId],
495
+ attempt.launch.projectRoot,
496
+ attempt.context,
497
+ );
498
+ const value = reply.result;
499
+ if (
500
+ !value?.dispatch ||
501
+ !value.worker ||
502
+ value.dispatch.id !== dispatchId ||
503
+ value.worker.dispatchId !== dispatchId ||
504
+ value.dispatch.taskId !== attempt.orcaTaskId ||
505
+ value.dispatch.runId !== attempt.runId ||
506
+ value.worker.runtimeEpoch !== attempt.context.runtimeId ||
507
+ value.worker.worktreeId !== attempt.workspaceId
508
+ ) {
509
+ throw new OrcaExecutionError(
510
+ 'E_ORCA_IDENTITY',
511
+ 'Worker observation does not match the stored Dispatch binding.',
512
+ 'Retain custody and inspect the stored runtime, Run, Task and workspace; do not use newest-record guesses.',
513
+ );
514
+ }
515
+ const failureCount = Math.max(attempt.failureCount, value.dispatch.failureCount);
516
+ const resource = value.projection?.resource;
517
+ const released =
518
+ value.observation?.exactWorker === true &&
519
+ value.observation.status === 'exited' &&
520
+ resource?.ownerDispatchId === dispatchId &&
521
+ resource.state === 'released' &&
522
+ resource.releaseState === 'released' &&
523
+ resource.terminalState === 'released';
524
+ // A worker-show reply never carries helper outcomes, so only a stop receipt can
525
+ // name the helpers this worker started. A parent release alone must never override
526
+ // that evidence: a helper kept open or unconfirmed still runs, so the stop stays
527
+ // fenced and unsettled.
528
+ const requestedStop = ['stop_pending', 'stop_unknown'].includes(attempt.state);
529
+ const helpersSettled =
530
+ !requestedStop ||
531
+ (released &&
532
+ (await this.helpersAffirmativelyStopped(
533
+ attempt,
534
+ readHelperEvidence(attempt, attempt.lastReceipt),
535
+ )));
536
+ const settled = released && helpersSettled;
537
+ // Anything less than parent plus helper release proof stays uncertain rather than
538
+ // repeating or guessing at the original cancellation. The stop receipt keeps the
539
+ // only proof of what is still running, so it is replaced only once the stop settles.
540
+ return {
541
+ ...attempt,
542
+ state: requestedStop
543
+ ? settled
544
+ ? 'stopped'
545
+ : 'stop_unknown'
546
+ : attempt.state === 'stopped'
547
+ ? 'stopped'
548
+ : failureCount >= 3
549
+ ? 'circuit_broken'
550
+ : released && value.worker.state === 'failed'
551
+ ? 'failed'
552
+ : attempt.state,
553
+ failureCount,
554
+ resourceState: settled ? 'stopped' : resource?.state === 'owned' ? 'owned' : 'unknown',
555
+ lastReceipt: requestedStop && !settled ? attempt.lastReceipt : reply.rawReceipt,
556
+ observedAt: new Date().toISOString(),
557
+ };
558
+ }
559
+
560
+ /** Read one bounded page; retain the returned source-pinned cursor verbatim. */
561
+ async read(attempt: OrcaAttempt, cursor?: string): Promise<string> {
562
+ const dispatchId = this.requireDispatch(attempt);
563
+ const reply = await this.query(
564
+ [
565
+ 'orchestration',
566
+ 'worker-read',
567
+ '--dispatch',
568
+ dispatchId,
569
+ '--source',
570
+ 'auto',
571
+ '--limit',
572
+ '200',
573
+ ...(cursor ? ['--cursor', cursor] : []),
574
+ ],
575
+ attempt.launch.projectRoot,
576
+ attempt.context,
577
+ );
578
+ return reply.rawReceipt;
579
+ }
580
+
581
+ /** Fetch one full report pointer after a wake; never acknowledge or poll coordinator mail. */
582
+ async readReport(attempt: OrcaAttempt, messageId: string): Promise<OrcaWorkerDone> {
583
+ const dispatchId = this.requireDispatch(attempt);
584
+ const { runId, orcaTaskId } = attempt;
585
+ if (!runId || !orcaTaskId) {
586
+ throw new OrcaExecutionError(
587
+ 'E_ORCA_IDENTITY',
588
+ 'No complete report binding is stored.',
589
+ 'Recover the original start receipt before ingesting a worker report.',
590
+ );
591
+ }
592
+ let message: ReturnType<typeof orcaReportMessageSchema.parse> | undefined;
593
+ let source: OrcaReportSource | undefined;
594
+ let exhausted = false;
595
+ // shortcut: Orca has no inbox cursor; widen up to 12,800 rows until it offers paging or exact lookup.
596
+ for (let limit = 200; limit <= 12_800; limit *= 2) {
597
+ source = await this.reportSource(
598
+ ['orchestration', 'inbox', '--terminal', `run:${runId}`, '--limit', String(limit)],
599
+ attempt,
600
+ );
601
+ const rows = source.result.messages ?? [];
602
+ const row = rows.find(
603
+ (entry) =>
604
+ entry !== null &&
605
+ typeof entry === 'object' &&
606
+ !Array.isArray(entry) &&
607
+ entry.id === messageId,
608
+ );
609
+ if (row) {
610
+ const parsed = orcaReportMessageSchema.safeParse(row);
611
+ if (!parsed.success) {
612
+ throw this.reportSourceRefusal(
613
+ source.command,
614
+ `The requested inbox row is malformed: ${parsed.error.message}`,
615
+ 'Inspect the exact message in the original full Run inbox and restore its transport fields before retrying.',
616
+ );
617
+ }
618
+ message = parsed.data;
619
+ break;
620
+ }
621
+ exhausted = rows.length < limit;
622
+ if (exhausted) break;
623
+ }
624
+ if (!message || !source) {
625
+ throw new OrcaExecutionError(
626
+ 'E_ORCA_REPORT_SOURCE',
627
+ exhausted
628
+ ? `Message ${messageId} is absent from the exhausted Run inbox.`
629
+ : `The Run inbox lookup reached 12,800 messages without finding ${messageId}; older history remains unsearched.`,
630
+ exhausted
631
+ ? `Inspect orca orchestration inbox --terminal run:${runId} --limit 12800 --environment local --json --full and use the original worker_done id for this Run.`
632
+ : `Inspect orca orchestration inbox --terminal run:${runId} --limit 25600 --environment local --json --full for the exact id; update Orca to support paged or exact lookup before retrying older history. Retain the worker record.`,
633
+ );
634
+ }
635
+ if (
636
+ message.type !== 'worker_done' ||
637
+ message.delivery_contract !== 'current_delivery' ||
638
+ message.run_id !== runId ||
639
+ message.to_handle !== `run:${runId}`
640
+ ) {
641
+ throw new OrcaExecutionError(
642
+ 'E_ORCA_REPORT_SOURCE',
643
+ 'The requested message is not a current worker_done for this Run.',
644
+ 'Use the exact worker_done id from the original Run; a wake or prose body is not a report.',
645
+ );
646
+ }
647
+ let payload: ReturnType<typeof orcaWorkerDonePayloadSchema.parse>;
648
+ try {
649
+ payload = orcaWorkerDonePayloadSchema.parse(JSON.parse(message.payload ?? 'null'));
650
+ } catch (error) {
651
+ throw this.reportSourceRefusal(
652
+ source.command,
653
+ `worker_done has no valid report-path payload: ${error instanceof Error ? error.message : String(error)}`,
654
+ 'Supply the original canonical report through worker_done --report-path.',
655
+ );
656
+ }
657
+ if (payload.taskId !== orcaTaskId || payload.dispatchId !== dispatchId) {
658
+ throw new OrcaExecutionError(
659
+ 'E_ORCA_REPORT_IDENTITY',
660
+ 'The report pointer does not match this exact Task and Dispatch.',
661
+ 'Retain stale delivery as history; use the current worker record and its report-path.',
662
+ );
663
+ }
664
+ const current = await this.reportSource(
665
+ [
666
+ 'orchestration',
667
+ 'dispatch-show',
668
+ '--task',
669
+ orcaTaskId,
670
+ '--from',
671
+ attempt.context.coordinatorHandle,
672
+ ],
673
+ attempt,
674
+ );
675
+ const dispatch = current.result.dispatch;
676
+ if (
677
+ dispatch?.id !== dispatchId ||
678
+ dispatch.run_id !== runId ||
679
+ dispatch.task_id !== orcaTaskId ||
680
+ dispatch.status !== 'completed' ||
681
+ !(
682
+ message.from_handle === dispatch.assignee_handle ||
683
+ (message.sender_pane_key && message.sender_pane_key === dispatch.assignee_pane_key)
684
+ )
685
+ ) {
686
+ throw new OrcaExecutionError(
687
+ 'E_ORCA_REPORT_IDENTITY',
688
+ 'The current Dispatch and its report sender are unproven or unsettled.',
689
+ 'Inspect the exact current Dispatch; old, cancelled or superseded deliveries cannot settle this worker.',
690
+ );
691
+ }
692
+ return {
693
+ messageId,
694
+ runtimeId: attempt.context.runtimeId,
695
+ runId,
696
+ orcaTaskId,
697
+ dispatchId,
698
+ senderHandle: message.from_handle,
699
+ outcome: payload.outcome,
700
+ body: message.body,
701
+ reportPath: payload.reportPath,
702
+ };
703
+ }
704
+
705
+ /** Request guarded cancellation; a closed terminal action alone is not exit proof. */
706
+ async stop(attempt: OrcaAttempt): Promise<OrcaAttempt> {
707
+ if (attempt.state !== 'stop_pending' || attempt.stopRequestId) {
708
+ throw new OrcaExecutionError(
709
+ 'E_ORCA_ATTEMPT_FENCED',
710
+ 'Stop must be durably reserved before it is sent.',
711
+ 'Inspect stop_unknown with worker-show; do not blindly repeat a stop.',
712
+ );
713
+ }
714
+ // The reserved key makes the first send idempotent, so a lost reply reuses it.
715
+ return this.stopCommand(attempt, attempt.stopRequestKey);
716
+ }
717
+
718
+ /**
719
+ * Recover a reserved or issued cancellation without sending an unkeyed second stop.
720
+ * @remarks A completed key replays Orca's recorded outcome, which cannot reflect a
721
+ * helper that finished after the original stop; `show` reconciles those helpers.
722
+ */
723
+ async replayStop(attempt: OrcaAttempt): Promise<OrcaAttempt> {
724
+ this.requireDispatch(attempt);
725
+ const requestId = attempt.stopRequestKey ?? attempt.stopRequestId;
726
+ if (!['stop_pending', 'stop_unknown'].includes(attempt.state) || !requestId) {
727
+ throw new OrcaExecutionError(
728
+ 'E_ORCA_ATTEMPT_FENCED',
729
+ 'No replayable uncertain stop request is retained.',
730
+ 'Inspect the exact Dispatch and original stop receipt; never repeat an unkeyed stop.',
731
+ );
732
+ }
733
+ await this.verifyRequest(attempt, requestId);
734
+ return this.stopCommand(attempt, requestId);
735
+ }
736
+
737
+ private async stopCommand(attempt: OrcaAttempt, requestId?: string): Promise<OrcaAttempt> {
738
+ const dispatchId = this.requireDispatch(attempt);
739
+ try {
740
+ const capabilities = await this.verifyRuntime(attempt.launch.projectRoot, attempt.context);
741
+ const result = await this.invoke(
742
+ [
743
+ 'orchestration',
744
+ 'worker-stop',
745
+ '--dispatch',
746
+ dispatchId,
747
+ ...(requestId ? ['--retry-request', requestId] : []),
748
+ ],
749
+ attempt.launch.projectRoot,
750
+ );
751
+ const value = result.result;
752
+ // An omitted helper list is affirmative only when this runtime enumerates the
753
+ // helper tree; otherwise helpers could still run and the stop stays unknown.
754
+ const helpersStopped =
755
+ value?.helpers !== undefined
756
+ ? value.helpers.every((helper) => SETTLED_HELPER_OUTCOMES.has(helper.outcome))
757
+ : capabilities.includes(HELPER_STOP_CAPABILITY);
758
+ const confirmed =
759
+ result.ok &&
760
+ result._meta?.runtimeId === attempt.context.runtimeId &&
761
+ value?.dispatchId === dispatchId &&
762
+ value.state === 'stopped' &&
763
+ value.processAction === 'closed_agent_terminal' &&
764
+ !value.helperStopError &&
765
+ helpersStopped;
766
+ return {
767
+ ...attempt,
768
+ state: confirmed ? 'stopped' : 'stop_unknown',
769
+ stopRequestId:
770
+ attempt.stopRequestId ??
771
+ (result._meta?.runtimeId === attempt.context.runtimeId
772
+ ? (result.error?.data?.orchestrationRequestId ?? null)
773
+ : null),
774
+ // Record that this runtime enumerated helpers, so an omitted list in its reply
775
+ // is latent affirmative evidence rather than an unknown helper tree. Only a
776
+ // proven stopped parent from this exact runtime, Dispatch and request can prove
777
+ // it cannot start a new helper after this reply.
778
+ stopHelperEvidence:
779
+ confirmed && value?.helpers === undefined ? 'enumerated' : attempt.stopHelperEvidence,
780
+ resourceState: confirmed ? 'stopped' : 'unknown',
781
+ lastReceipt: result.rawReceipt,
782
+ lastError: result.error?.message ?? value?.lastError ?? null,
783
+ observedAt: new Date().toISOString(),
784
+ };
785
+ } catch (error) {
786
+ return {
787
+ ...attempt,
788
+ state: 'stop_unknown',
789
+ lastError: String(error),
790
+ lastReceipt:
791
+ error instanceof OrcaExecutionError
792
+ ? (error.receipt ?? attempt.lastReceipt)
793
+ : attempt.lastReceipt,
794
+ observedAt: new Date().toISOString(),
795
+ };
796
+ }
797
+ }
798
+
799
+ private async startCommand(attempt: OrcaAttempt, requestId?: string): Promise<OrcaAttempt> {
800
+ const launch = attempt.launch;
801
+ this.validateLaunch(launch, attempt.context);
802
+ if (launch.harness === 'kimi') {
803
+ throw new OrcaExecutionError(
804
+ 'E_ORCA_HARNESS_UNSUPPORTED',
805
+ 'Kimi has no direct Orca launch route.',
806
+ 'Use a supervised terminal adoption path.',
807
+ );
808
+ }
809
+ const binding = attempt.startBinding ?? attempt;
810
+ if (
811
+ attempt.startRequestKey &&
812
+ (!binding.runId ||
813
+ !binding.orcaTaskId ||
814
+ !binding.retryOf ||
815
+ binding.runId !== attempt.runId ||
816
+ binding.orcaTaskId !== attempt.orcaTaskId ||
817
+ binding.retryOf !== attempt.retryOf ||
818
+ requestId !== attempt.startRequestKey ||
819
+ (attempt.startRequestId !== null && attempt.startRequestId !== attempt.startRequestKey))
820
+ ) {
821
+ throw new OrcaExecutionError(
822
+ 'E_ORCA_ATTEMPT_FENCED',
823
+ 'A reserved start key requires the original exact retry binding.',
824
+ 'Retain custody and inspect the reserved key, Run, Task and predecessor; never send an unkeyed replacement.',
825
+ );
826
+ }
827
+ const args = [
828
+ 'orchestration',
829
+ 'worker-start',
830
+ '--from',
831
+ attempt.context.coordinatorHandle,
832
+ '--worktree',
833
+ attempt.workspaceSelector,
834
+ '--agent',
835
+ AGENTS[launch.harness],
836
+ ...(binding.orcaTaskId
837
+ ? ['--task', binding.orcaTaskId]
838
+ : [
839
+ '--spec-file',
840
+ '-',
841
+ '--task-title',
842
+ `${launch.projectId}:${launch.taskId}:${launch.instanceId}`,
843
+ ]),
844
+ ...(binding.runId ? ['--run', binding.runId] : []),
845
+ ...(binding.retryOf ? ['--retry-of', binding.retryOf] : []),
846
+ ...(launch.model ? ['--model', launch.model] : []),
847
+ ...(launch.effort ? ['--effort', launch.effort] : []),
848
+ ...(requestId ? ['--retry-request', requestId] : []),
849
+ ];
850
+ try {
851
+ await this.verifyRuntime(launch.projectRoot, attempt.context, launch.model !== undefined);
852
+ const reply = await this.invoke(
853
+ args,
854
+ launch.projectRoot,
855
+ binding.orcaTaskId ? undefined : launch.prompt,
856
+ );
857
+ if (
858
+ !reply.ok &&
859
+ reply.error?.code === 'agent_unconfigured' &&
860
+ reply._meta?.runtimeId === attempt.context.runtimeId &&
861
+ !binding.orcaTaskId &&
862
+ !binding.retryOf &&
863
+ !reply.error.data?.dispatchId &&
864
+ !reply.result?.dispatchId &&
865
+ !reply.result?.taskId &&
866
+ !reply.result?.runId &&
867
+ !reply.result?.run &&
868
+ !reply.result?.failureCount &&
869
+ !reply.result?.residualResources?.length &&
870
+ (!reply.result?.effects?.length ||
871
+ reply.result.effects.every(
872
+ (effect) =>
873
+ effect.kind === 'worktree' &&
874
+ effect.action === 'reused' &&
875
+ effect.id === attempt.workspaceId,
876
+ ))
877
+ ) {
878
+ return {
879
+ ...attempt,
880
+ state: 'failed',
881
+ resourceState: 'stopped',
882
+ startRefusal: 'agent_unconfigured',
883
+ startRequestId: reply.error.data?.orchestrationRequestId ?? null,
884
+ lastReceipt: reply.rawReceipt,
885
+ lastError: 'agent_unconfigured',
886
+ observedAt: new Date().toISOString(),
887
+ };
888
+ }
889
+ const value = reply.result;
890
+ const workspace = value?.effects?.filter((effect) => effect.kind === 'worktree');
891
+ const bound =
892
+ reply._meta?.runtimeId === attempt.context.runtimeId &&
893
+ value?.dispatchId &&
894
+ value.taskId &&
895
+ (value.runId || value.run?.id) &&
896
+ value.dispatchId !== attempt.retryOf &&
897
+ (!attempt.dispatchId || attempt.dispatchId === value.dispatchId) &&
898
+ (!attempt.orcaTaskId || attempt.orcaTaskId === value.taskId) &&
899
+ (!attempt.runId || attempt.runId === (value.runId ?? value.run?.id));
900
+ const matches =
901
+ bound &&
902
+ workspace?.length === 1 &&
903
+ workspace[0]?.id === attempt.workspaceId &&
904
+ value.launch?.effective?.agent === AGENTS[launch.harness] &&
905
+ (!launch.model || launch.model === value.launch.effective.model) &&
906
+ (!launch.effort || launch.effort === value.launch.effective.effort);
907
+ let state: OrcaAttempt['state'] = 'outcome_unknown';
908
+ if (matches && reply.ok) {
909
+ if (value.state === 'ready') state = 'ready';
910
+ else if (
911
+ value.state === 'outcome_unknown' &&
912
+ (value.turnStart === 'unobserved' || value.stage === 'turn_start_unobserved')
913
+ )
914
+ state = 'turn_unobserved';
915
+ else if (value.state === 'failed') state = 'failed';
916
+ }
917
+ const failureCount = Math.max(attempt.failureCount, value?.failureCount ?? 0);
918
+ const pending = reply.error?.data;
919
+ const recoveredDispatchId =
920
+ !reply.ok &&
921
+ reply.error?.code === 'operation_unknown' &&
922
+ reply._meta?.runtimeId === attempt.context.runtimeId &&
923
+ requestId &&
924
+ requestId === (attempt.startRequestKey ?? attempt.startRequestId) &&
925
+ pending?.requestId === requestId &&
926
+ pending.orchestrationRequestId === requestId &&
927
+ pending.dispatchId !== attempt.retryOf &&
928
+ (!attempt.dispatchId || attempt.dispatchId === pending.dispatchId)
929
+ ? pending.dispatchId
930
+ : null;
931
+ return {
932
+ ...attempt,
933
+ state: failureCount >= 3 ? 'circuit_broken' : state,
934
+ runId: bound ? (value.runId ?? value.run?.id ?? null) : attempt.runId,
935
+ orcaTaskId: bound ? (value.taskId ?? null) : attempt.orcaTaskId,
936
+ dispatchId: bound
937
+ ? (value.dispatchId ?? null)
938
+ : (recoveredDispatchId ?? attempt.dispatchId),
939
+ startRequestId:
940
+ attempt.startRequestKey ??
941
+ attempt.startRequestId ??
942
+ (reply._meta?.runtimeId === attempt.context.runtimeId
943
+ ? (reply.error?.data?.orchestrationRequestId ?? null)
944
+ : null),
945
+ failureCount,
946
+ resourceState: matches && state === 'ready' ? 'owned' : 'unknown',
947
+ lastReceipt: reply.rawReceipt,
948
+ lastError:
949
+ reply.error?.message ??
950
+ value?.lastError ??
951
+ (matches ? null : 'Receipt identity or effective harness is unproven'),
952
+ observedAt: new Date().toISOString(),
953
+ };
954
+ } catch (error) {
955
+ return {
956
+ ...attempt,
957
+ state: 'outcome_unknown',
958
+ lastError: String(error),
959
+ lastReceipt:
960
+ error instanceof OrcaExecutionError
961
+ ? (error.receipt ?? attempt.lastReceipt)
962
+ : attempt.lastReceipt,
963
+ observedAt: new Date().toISOString(),
964
+ };
965
+ }
966
+ }
967
+
968
+ /**
969
+ * Decide whether current Orca evidence proves every helper stopped or finished.
970
+ * @remarks An absent receipt or an incomplete helper tree never settles; a
971
+ * listed helper is settled only by its own exact Dispatch showing an exited
972
+ * process. A completed stop key replays its recorded outcome, so unresolved
973
+ * helpers are re-read rather than replayed.
974
+ */
975
+ private async helpersAffirmativelyStopped(
976
+ attempt: OrcaAttempt,
977
+ evidence: HelperEvidence,
978
+ ): Promise<boolean> {
979
+ switch (evidence.kind) {
980
+ case 'settled':
981
+ return true;
982
+ case 'absent':
983
+ return false;
984
+ case 'empty':
985
+ // Only a stop reply from a runtime that proved it enumerates helpers turns an
986
+ // omitted list into affirmative "this worker started no helper" evidence.
987
+ return attempt.stopHelperEvidence === 'enumerated';
988
+ case 'unresolved': {
989
+ if (!evidence.reconcileable) return false;
990
+ for (const helperDispatchId of evidence.dispatchIds) {
991
+ if (!(await this.helperFinished(attempt, helperDispatchId))) return false;
992
+ }
993
+ return true;
994
+ }
995
+ }
996
+ }
997
+
998
+ /**
999
+ * Prove one helper Dispatch's process exited under this exact attempt's ancestry.
1000
+ * @remarks A helper counts only when its own Dispatch is on this Run and runtime,
1001
+ * its process exited, and its creator chain reaches this attempt's Dispatch. An
1002
+ * unrelated helper in the same Run therefore never settles this stop.
1003
+ */
1004
+ private async helperFinished(attempt: OrcaAttempt, helperDispatchId: string): Promise<boolean> {
1005
+ const observation = await this.exactWorkerObservation(attempt, helperDispatchId);
1006
+ if (
1007
+ !observation ||
1008
+ observation.observation?.exactWorker !== true ||
1009
+ observation.observation.status !== 'exited'
1010
+ ) {
1011
+ return false;
1012
+ }
1013
+ return this.descendsFromAttempt(attempt, observation.dispatch?.creatorDispatchId ?? null);
1014
+ }
1015
+
1016
+ /** Walk the bounded creator chain of a helper back to this attempt's Dispatch. */
1017
+ private async descendsFromAttempt(
1018
+ attempt: OrcaAttempt,
1019
+ creatorDispatchId: string | null,
1020
+ ): Promise<boolean> {
1021
+ let creator = creatorDispatchId;
1022
+ for (let hop = 0; hop < HELPER_ANCESTRY_LIMIT; hop += 1) {
1023
+ if (creator === attempt.dispatchId) return true;
1024
+ if (!creator) return false;
1025
+ const parent = await this.exactWorkerObservation(attempt, creator);
1026
+ creator = parent?.dispatch?.creatorDispatchId ?? null;
1027
+ }
1028
+ return false;
1029
+ }
1030
+
1031
+ /** Read one exact worker observation, refusing any other Dispatch, Run or epoch. */
1032
+ private async exactWorkerObservation(
1033
+ attempt: OrcaAttempt,
1034
+ dispatchId: string,
1035
+ ): Promise<OrcaReply['result'] | null> {
1036
+ const reply = await this.query(
1037
+ ['orchestration', 'worker-show', '--dispatch', dispatchId],
1038
+ attempt.launch.projectRoot,
1039
+ attempt.context,
1040
+ ).catch(() => null);
1041
+ const value = reply?.result;
1042
+ if (
1043
+ !value?.dispatch ||
1044
+ !value.worker ||
1045
+ value.dispatch.id !== dispatchId ||
1046
+ value.dispatch.runId !== attempt.runId ||
1047
+ value.worker.dispatchId !== dispatchId ||
1048
+ value.worker.runtimeEpoch !== attempt.context.runtimeId
1049
+ ) {
1050
+ return null;
1051
+ }
1052
+ return value;
1053
+ }
1054
+
1055
+ private async verifyRequest(attempt: OrcaAttempt, requestId: string): Promise<void> {
1056
+ await this.verifyRuntime(attempt.launch.projectRoot, attempt.context);
1057
+ const receipt = await this.query(
1058
+ ['orchestration', 'request-show', '--request', requestId],
1059
+ attempt.launch.projectRoot,
1060
+ attempt.context,
1061
+ );
1062
+ // Reserved keys keep their identity; Orca atomically refuses a second mutation
1063
+ // even if its receipt was pruned, so an absent receipt is never proof of absence.
1064
+ const reserved = requestId === attempt.startRequestKey || requestId === attempt.stopRequestKey;
1065
+ const states = reserved ? ['pending', 'completed', 'absent'] : ['pending', 'completed'];
1066
+ if (receipt.result?.requestId !== requestId || !states.includes(receipt.result.state ?? '')) {
1067
+ throw new OrcaExecutionError(
1068
+ 'E_ORCA_ATTEMPT_FENCED',
1069
+ 'Request absence or a mismatched receipt does not prove that nothing happened.',
1070
+ 'Retain custody and inspect the original request on its original runtime and caller.',
1071
+ );
1072
+ }
1073
+ }
1074
+
1075
+ private requireDispatch(attempt: OrcaAttempt): string {
1076
+ if (!attempt.dispatchId || !attempt.runId || !attempt.orcaTaskId) {
1077
+ throw new OrcaExecutionError(
1078
+ 'E_ORCA_IDENTITY',
1079
+ 'No complete Dispatch binding is available.',
1080
+ 'Recover the issued start request, retaining the pending worker record and claim.',
1081
+ );
1082
+ }
1083
+ return attempt.dispatchId;
1084
+ }
1085
+
1086
+ private async verifyRuntime(
1087
+ cwd: string,
1088
+ context: OrcaContext,
1089
+ modelRequested = false,
1090
+ ): Promise<string[]> {
1091
+ const reply = await this.query(['status'], cwd, context);
1092
+ const runtime = reply.result?.runtime;
1093
+ if (
1094
+ !runtime?.reachable ||
1095
+ runtime.state !== 'ready' ||
1096
+ runtime.runtimeId !== context.runtimeId ||
1097
+ !runtime.capabilities.includes('orchestration.contract.v1') ||
1098
+ (modelRequested &&
1099
+ !runtime.capabilities.includes('orchestration.worker-launch-preferences.v1'))
1100
+ ) {
1101
+ throw new OrcaExecutionError(
1102
+ 'E_ORCA_CONTEXT',
1103
+ 'The selected Orca runtime is unavailable or changed.',
1104
+ 'Inspect Orca status and retain unresolved attempts; explicitly reconcile their original runtime before relaunch.',
1105
+ );
1106
+ }
1107
+ return runtime.capabilities;
1108
+ }
1109
+
1110
+ private async reportSource(args: string[], attempt: OrcaAttempt): Promise<OrcaReportSource> {
1111
+ const reply = await this.runner(
1112
+ this.executable,
1113
+ [...args, '--environment', 'local', '--json', '--full'],
1114
+ attempt.launch.projectRoot,
1115
+ );
1116
+ try {
1117
+ const source = orcaReportSourceSchema.parse(JSON.parse(reply.stdout));
1118
+ if (reply.exitCode !== 0)
1119
+ throw new Error('The report source command did not exit successfully.');
1120
+ if (source._meta.runtimeId !== attempt.context.runtimeId)
1121
+ throw new Error(
1122
+ `Report source runtime ${source._meta.runtimeId} differs from ${attempt.context.runtimeId}.`,
1123
+ );
1124
+ if (args[1] === 'inbox' && !source.result.messages)
1125
+ throw new Error('The Run inbox omitted its messages array.');
1126
+ return { ...source, command: reply };
1127
+ } catch (error) {
1128
+ throw this.reportSourceRefusal(
1129
+ reply,
1130
+ error instanceof Error ? error.message : String(error),
1131
+ 'Inspect the original runtime and full Run inbox; retain the worker record.',
1132
+ );
1133
+ }
1134
+ }
1135
+
1136
+ private reportSourceRefusal(
1137
+ command: OrcaCommandResult,
1138
+ issues: string,
1139
+ fix: string,
1140
+ ): OrcaExecutionError {
1141
+ return new OrcaExecutionError(
1142
+ 'E_ORCA_REPORT_SOURCE',
1143
+ `Orca returned no verified report source: ${JSON.stringify({
1144
+ exitCode: command.exitCode,
1145
+ stderr: command.stderr,
1146
+ issues,
1147
+ })}`,
1148
+ fix,
1149
+ command.stdout,
1150
+ );
1151
+ }
1152
+
1153
+ private async query(
1154
+ args: string[],
1155
+ cwd: string,
1156
+ context: OrcaContext,
1157
+ ): Promise<OrcaCommandReply> {
1158
+ const reply = await this.invoke(args, cwd);
1159
+ if (!reply.ok || reply._meta?.runtimeId !== context.runtimeId) {
1160
+ throw new OrcaExecutionError(
1161
+ 'E_ORCA_CONTEXT',
1162
+ reply.error?.message ?? 'Orca returned an unproven runtime identity.',
1163
+ 'Inspect the explicitly selected runtime; preserve pending operations and do not fall back to a native launch.',
1164
+ );
1165
+ }
1166
+ return reply;
1167
+ }
1168
+
1169
+ private async invoke(args: string[], cwd: string, input?: string): Promise<OrcaCommandReply> {
1170
+ const result: OrcaCommandResult = await this.runner(
1171
+ this.executable,
1172
+ [
1173
+ ...args,
1174
+ '--environment',
1175
+ 'local',
1176
+ '--json',
1177
+ ...(args[0] === 'orchestration' ? ['--full'] : []),
1178
+ ],
1179
+ cwd,
1180
+ input,
1181
+ );
1182
+ try {
1183
+ return { ...orcaReplySchema.parse(JSON.parse(result.stdout)), rawReceipt: result.stdout };
1184
+ } catch {
1185
+ throw new OrcaExecutionError(
1186
+ 'E_ORCA_RECEIPT',
1187
+ 'Orca returned no parseable receipt.',
1188
+ 'Preserve pending custody and inspect the original operation; a CLI exit is not worker exit proof.',
1189
+ result.stdout,
1190
+ );
1191
+ }
1192
+ }
1193
+ }