@cleocode/adapters 2026.11.1-canary.9 → 2026.11.1

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 (37) hide show
  1. package/dist/.source-stamp.json +1 -1
  2. package/dist/index.js +1691 -1354
  3. package/dist/index.js.map +3 -3
  4. package/dist/orca-execution.d.ts +90 -0
  5. package/dist/orca-execution.d.ts.map +1 -0
  6. package/dist/orca-execution.js +843 -0
  7. package/dist/orca-execution.js.map +6 -0
  8. package/dist/providers/claude-code/index.js +1689 -1357
  9. package/dist/providers/claude-code/index.js.map +3 -3
  10. package/dist/providers/claude-code/lead-session.d.ts +8 -5
  11. package/dist/providers/claude-code/lead-session.d.ts.map +1 -1
  12. package/dist/providers/claude-sdk/index.js +1674 -1352
  13. package/dist/providers/claude-sdk/index.js.map +3 -3
  14. package/dist/providers/claude-sdk/spawn.d.ts.map +1 -1
  15. package/dist/providers/codex/index.js +1540 -1233
  16. package/dist/providers/codex/index.js.map +3 -3
  17. package/dist/providers/gemini-cli/index.js +1540 -1233
  18. package/dist/providers/gemini-cli/index.js.map +3 -3
  19. package/dist/providers/kimi/index.js +1540 -1233
  20. package/dist/providers/kimi/index.js.map +3 -3
  21. package/dist/providers/openai-sdk/index.js +1660 -1353
  22. package/dist/providers/openai-sdk/index.js.map +3 -3
  23. package/dist/providers/opencode/index.js +1540 -1233
  24. package/dist/providers/opencode/index.js.map +3 -3
  25. package/dist/providers/pi/index.js +1540 -1233
  26. package/dist/providers/pi/index.js.map +3 -3
  27. package/package.json +10 -6
  28. package/src/__tests__/orca-execution-fixture.ts +422 -0
  29. package/src/__tests__/orca-execution.test.ts +1357 -0
  30. package/src/__tests__/orca-plugin-panel.test.ts +661 -0
  31. package/src/__tests__/orca-plugin.test.ts +660 -0
  32. package/src/orca-execution.ts +1193 -0
  33. package/src/providers/claude-code/__tests__/lead-mcp.test.ts +27 -2
  34. package/src/providers/claude-code/lead-session.ts +21 -8
  35. package/src/providers/claude-sdk/__tests__/spawn.test.ts +19 -0
  36. package/src/providers/claude-sdk/spawn.ts +14 -0
  37. package/src/providers/shared/__tests__/lead-tool-strip.test.ts +1 -1
@@ -0,0 +1,843 @@
1
+ // packages/adapters/src/orca-execution.ts
2
+ import { execFile } from "node:child_process";
3
+ import { isAbsolute } from "node:path";
4
+ import {
5
+ ORCA_LEAD_LAUNCH_REFUSAL,
6
+ orcaAccountReplySchema,
7
+ orcaCommandRegistrySchema,
8
+ orcaContextSchema,
9
+ orcaLaunchSchema,
10
+ orcaReplySchema,
11
+ orcaReportMessageSchema,
12
+ orcaReportSourceSchema,
13
+ orcaWorkerDonePayloadSchema
14
+ } from "@cleocode/contracts/orca-execution.js";
15
+ var AGENTS = { "claude-code": "claude", codex: "codex", opencode: "opencode2", grok: "grok" };
16
+ var REQUIRED_COMMANDS = {
17
+ "orchestration worker-start": [
18
+ "from",
19
+ "spec-file",
20
+ "task",
21
+ "run",
22
+ "worktree",
23
+ "agent",
24
+ "retry-of",
25
+ "retry-request",
26
+ "full",
27
+ "model",
28
+ "effort"
29
+ ],
30
+ "orchestration worker-show": ["dispatch", "full"],
31
+ "orchestration worker-read": ["dispatch", "source", "limit", "cursor", "full"],
32
+ "orchestration worker-stop": ["dispatch", "retry-request", "full"],
33
+ "orchestration request-show": ["request", "full"],
34
+ "orchestration run-current": ["from", "full"],
35
+ "worktree show": ["worktree"]
36
+ };
37
+ var SETTLED_HELPER_OUTCOMES = /* @__PURE__ */ new Set(["stopped", "already_finished"]);
38
+ var HELPER_STOP_CAPABILITY = "orchestration.worker-stop-helpers.v1";
39
+ var HELPER_ANCESTRY_LIMIT = 8;
40
+ function readHelperEvidence(attempt, receipt) {
41
+ if (!receipt) return { kind: "absent" };
42
+ let reply;
43
+ try {
44
+ const parsed = orcaReplySchema.safeParse(JSON.parse(receipt));
45
+ if (!parsed.success) return { kind: "absent" };
46
+ reply = parsed.data;
47
+ } catch {
48
+ return { kind: "absent" };
49
+ }
50
+ if (!receiptBelongsToAttempt(attempt, reply)) return { kind: "absent" };
51
+ const value = reply.result;
52
+ const stopReply = value !== void 0 && (value.processAction !== void 0 || value.helpers !== void 0 || value.helperStopError !== void 0);
53
+ if (!value || !stopReply) return { kind: "absent" };
54
+ if (value.helperStopError) return { kind: "absent" };
55
+ if (value.helpers === void 0) return { kind: "empty" };
56
+ const unresolved = value.helpers.filter((helper) => !SETTLED_HELPER_OUTCOMES.has(helper.outcome));
57
+ if (unresolved.length === 0) return { kind: "settled" };
58
+ return {
59
+ kind: "unresolved",
60
+ dispatchIds: [
61
+ ...new Set(
62
+ unresolved.map((helper) => helper.dispatchId).filter((dispatchId) => dispatchId !== void 0)
63
+ )
64
+ ],
65
+ reconcileable: unresolved.every((helper) => helper.dispatchId !== void 0)
66
+ };
67
+ }
68
+ function receiptBelongsToAttempt(attempt, reply) {
69
+ if (reply._meta?.runtimeId !== attempt.context.runtimeId) return false;
70
+ const value = reply.result;
71
+ const dispatchId = value?.dispatchId ?? reply.error?.data?.dispatchId;
72
+ if (!attempt.dispatchId || dispatchId !== attempt.dispatchId) return false;
73
+ if (value?.runId !== void 0 && value.runId !== attempt.runId) return false;
74
+ const refusedKey = reply.error?.data?.orchestrationRequestId;
75
+ if (refusedKey !== void 0) return stopsThisAttempt(attempt, refusedKey);
76
+ if (reply.ok) {
77
+ const succeededKey = value?.mutation?.requestId;
78
+ return succeededKey !== void 0 && stopsThisAttempt(attempt, succeededKey);
79
+ }
80
+ return true;
81
+ }
82
+ function stopsThisAttempt(attempt, requestId) {
83
+ return requestId === attempt.stopRequestKey || requestId === attempt.stopRequestId;
84
+ }
85
+ var OrcaExecutionError = class extends Error {
86
+ /** Numeric CLI refusal status, independent of a worker's exit. */
87
+ exitCode = 63;
88
+ /** Stable refusal code. */
89
+ code;
90
+ /** Recovery instruction that never disables the lead policy. */
91
+ fix;
92
+ /** Original unparseable receipt, when available. */
93
+ receipt;
94
+ /** Construct a refusal before any unsupported operation runs. */
95
+ constructor(code, message, fix, receipt = null) {
96
+ super(message);
97
+ this.name = "OrcaExecutionError";
98
+ this.code = code;
99
+ this.fix = fix;
100
+ this.receipt = receipt;
101
+ }
102
+ };
103
+ var runOrcaCommand = (executable, args, cwd, input) => new Promise((resolve) => {
104
+ const child = execFile(
105
+ executable,
106
+ [...args],
107
+ { cwd, encoding: "utf8", timeout: 9e4, maxBuffer: 4 * 1024 * 1024 },
108
+ (error, stdout, stderr) => resolve({
109
+ stdout,
110
+ stderr: stderr || error?.message || "",
111
+ exitCode: error ? typeof error.code === "number" ? error.code : null : 0
112
+ })
113
+ );
114
+ child.stdin?.on("error", () => void 0);
115
+ child.stdin?.end(input);
116
+ });
117
+ var OrcaExecutionBackend = class {
118
+ /** Resolve the session executable once; never fall through to another runtime. */
119
+ constructor(runner = runOrcaCommand, executable = process.env.ORCA_CLI_COMMAND || (process.env.ORCA_DEV_REPO_ROOT ? "orca-dev" : process.platform === "linux" ? "orca-ide" : "orca")) {
120
+ this.runner = runner;
121
+ this.executable = executable;
122
+ }
123
+ runner;
124
+ /** Public launch APIs cannot enforce denied tools or a strict MCP allowlist. */
125
+ leadToolStrip = "unsupported";
126
+ executable;
127
+ /** Inspect hints without spawning a process; this cannot select an execution backend. */
128
+ hasContextHints() {
129
+ return Boolean(
130
+ process.env.ORCA_TERMINAL_HANDLE || process.env.ORCA_WORKTREE_ID || process.env.ORCA_WORKSPACE_ID || process.env.ORCA_RUNTIME_SOURCE_ID || process.env.ORCA_APP_VERSION
131
+ );
132
+ }
133
+ /** Verify the local caller before returning a sanitized account inventory. */
134
+ async discover(projectRoot) {
135
+ if (!this.hasContextHints()) return null;
136
+ const handle = process.env.ORCA_TERMINAL_HANDLE;
137
+ if (!handle) {
138
+ throw new OrcaExecutionError(
139
+ "E_ORCA_CONTEXT",
140
+ "Orca environment hints have no runtime-issued coordinator handle.",
141
+ "Run this command in the intended Orca agent session with its ORCA_TERMINAL_HANDLE; TERM_PROGRAM alone cannot select a caller."
142
+ );
143
+ }
144
+ const status = await this.invoke(["status"], projectRoot);
145
+ const runtimeId = status._meta?.runtimeId;
146
+ if (!status.ok || !runtimeId) {
147
+ throw new OrcaExecutionError(
148
+ "E_ORCA_CONTEXT",
149
+ "The selected local Orca runtime cannot verify this caller.",
150
+ "Inspect orca status --json in the intended Orca session and restore that runtime before dispatch."
151
+ );
152
+ }
153
+ const context = { runtimeId, coordinatorHandle: handle, executionHostId: "local" };
154
+ await this.verifyRuntime(projectRoot, context);
155
+ const caller = await this.query(
156
+ ["terminal", "show", "--terminal", handle],
157
+ projectRoot,
158
+ context
159
+ );
160
+ const terminal = caller.result?.terminal;
161
+ if (terminal?.handle !== handle || terminal.executionHostId !== "local" || !terminal.connected || !terminal.writable) {
162
+ throw new OrcaExecutionError(
163
+ "E_ORCA_CONTEXT",
164
+ "Orca did not prove a unique connected local coordinator.",
165
+ "Inspect orca terminal show --terminal <handle> --json and run from that live local Orca session; do not substitute a different caller."
166
+ );
167
+ }
168
+ try {
169
+ const accounts = await this.runner(
170
+ this.executable,
171
+ ["account", "list", "--json"],
172
+ projectRoot
173
+ );
174
+ if (accounts.exitCode !== 0) throw new Error("inventory unavailable");
175
+ const { result, _meta } = orcaAccountReplySchema.parse(JSON.parse(accounts.stdout));
176
+ if (_meta.runtimeId !== context.runtimeId) throw new Error("account runtime changed");
177
+ return {
178
+ context,
179
+ accounts: ["codex", "opencode", "claude"].map((provider) => ({
180
+ provider,
181
+ accountCount: result[provider].accounts.length,
182
+ activeAccountPresent: result[provider].activeAccountId !== null
183
+ }))
184
+ };
185
+ } catch {
186
+ throw new OrcaExecutionError(
187
+ "E_ORCA_ACCOUNT_UNAVAILABLE",
188
+ "Orca returned no verifiable local account availability.",
189
+ "Inspect orca account list --json locally and select an active account for an agent in orchestrate.orca.agents."
190
+ );
191
+ }
192
+ }
193
+ /** Read the Run currently bound to the original local coordinator, without mutation. */
194
+ async currentRun(projectRoot, context) {
195
+ await this.verifyRuntime(projectRoot, context);
196
+ const reply = await this.query(
197
+ ["orchestration", "run-current", "--from", context.coordinatorHandle],
198
+ projectRoot,
199
+ context
200
+ );
201
+ const run = reply.result?.run;
202
+ if (run === void 0) {
203
+ throw new OrcaExecutionError(
204
+ "E_ORCA_CONTEXT",
205
+ "Orca did not prove the coordinator Run binding.",
206
+ "Inspect orca orchestration run-current --from <handle> --json in the original local runtime before dispatch."
207
+ );
208
+ }
209
+ return run?.id ?? null;
210
+ }
211
+ /** Verify supported commands, exact runtime and existing canonical workspace. */
212
+ async preflight(launch, context) {
213
+ this.validateLaunch(launch, context);
214
+ const registryResult = await this.runner(
215
+ this.executable,
216
+ ["agent-context", "--json"],
217
+ launch.projectRoot
218
+ );
219
+ if (registryResult.exitCode !== 0) {
220
+ throw new OrcaExecutionError(
221
+ "E_ORCA_CONTEXT",
222
+ "The selected Orca CLI is unavailable.",
223
+ "Inspect the selected Orca executable and runtime; do not substitute a native launch.",
224
+ registryResult.stdout
225
+ );
226
+ }
227
+ let registry;
228
+ try {
229
+ registry = orcaCommandRegistrySchema.parse(JSON.parse(registryResult.stdout));
230
+ } catch {
231
+ throw new OrcaExecutionError(
232
+ "E_ORCA_COMMAND_UNSUPPORTED",
233
+ "The selected Orca CLI returned no valid command registry.",
234
+ "Update the selected Orca CLI and runtime together, then repeat read-only preflight.",
235
+ registryResult.stdout
236
+ );
237
+ }
238
+ for (const [command, flags] of Object.entries(REQUIRED_COMMANDS)) {
239
+ const declared = registry.commands.find((entry) => entry.command === command);
240
+ if (!declared || flags.some((flag) => !declared.flags.includes(flag))) {
241
+ throw new OrcaExecutionError(
242
+ "E_ORCA_COMMAND_UNSUPPORTED",
243
+ `Installed Orca does not declare ${command} with required flags.`,
244
+ "Update the selected Orca CLI and runtime together, then repeat read-only preflight."
245
+ );
246
+ }
247
+ }
248
+ await this.verifyRuntime(launch.projectRoot, context, launch.model !== void 0);
249
+ const workspace = await this.query(
250
+ ["worktree", "show", "--worktree", `path:${launch.worktreePath}`],
251
+ launch.projectRoot,
252
+ context
253
+ ).catch((error) => {
254
+ throw new OrcaExecutionError(
255
+ "E_ORCA_WORKSPACE",
256
+ error.message,
257
+ "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."
258
+ );
259
+ });
260
+ const tree = workspace.result?.worktree;
261
+ if (!tree || tree.path !== launch.worktreePath || tree.hostId !== context.executionHostId || tree.branch.replace(/^refs\/heads\//, "") !== launch.worktreeBranch) {
262
+ throw new OrcaExecutionError(
263
+ "E_ORCA_WORKSPACE",
264
+ "Orca did not resolve the exact local CLEO worktree.",
265
+ "Register the existing canonical checkout in Orca and resolve duplicate workspace entries explicitly."
266
+ );
267
+ }
268
+ return { workspaceId: tree.id, workspaceSelector: tree.address?.worktree ?? `id:${tree.id}` };
269
+ }
270
+ validateLaunch(launch, context) {
271
+ if (!orcaLaunchSchema.safeParse(launch).success || !orcaContextSchema.safeParse(context).success) {
272
+ throw new OrcaExecutionError(
273
+ "E_ORCA_CONTEXT",
274
+ "The prepared assignment or explicit Orca caller is incomplete.",
275
+ "Use canonical CLEO preparation and an explicitly verified local runtime and coordinator handle."
276
+ );
277
+ }
278
+ if (launch.role === "lead") {
279
+ throw new OrcaExecutionError(
280
+ ORCA_LEAD_LAUNCH_REFUSAL.code,
281
+ ORCA_LEAD_LAUNCH_REFUSAL.message,
282
+ ORCA_LEAD_LAUNCH_REFUSAL.fix
283
+ );
284
+ }
285
+ if (launch.accountId !== void 0) {
286
+ throw new OrcaExecutionError(
287
+ "E_ORCA_ACCOUNT_UNSUPPORTED",
288
+ "Exact per-worker account placement is unavailable.",
289
+ "Omit the account constraint to use Orca\u2019s active account for the selected harness."
290
+ );
291
+ }
292
+ if (launch.harness === "kimi") {
293
+ throw new OrcaExecutionError(
294
+ "E_ORCA_HARNESS_UNSUPPORTED",
295
+ "Kimi requires a proven terminal adoption path.",
296
+ "Use a supported Orca harness or the separately supervised Kimi terminal pilot."
297
+ );
298
+ }
299
+ if (!isAbsolute(launch.worktreePath) || launch.worktreeBranch !== `task/${launch.taskId}`) {
300
+ throw new OrcaExecutionError(
301
+ "E_ORCA_WORKSPACE",
302
+ "The assignment does not name a canonical task checkout.",
303
+ "Prepare the task once through cleo orchestrate spawn and preserve its worktree binding."
304
+ );
305
+ }
306
+ if (launch.effort && (!launch.model || launch.harness === "opencode")) {
307
+ throw new OrcaExecutionError(
308
+ "E_ORCA_MODEL_UNSUPPORTED",
309
+ "Effort requires a model and is unsupported for OpenCode.",
310
+ "Omit effort or select a supported harness/model route explicitly."
311
+ );
312
+ }
313
+ }
314
+ /** Start only a persisted launching attempt; no exit code is worker completion. */
315
+ async start(attempt) {
316
+ if (attempt.state !== "launching" || attempt.startRequestId || attempt.dispatchId || attempt.failureCount >= 3) {
317
+ throw new OrcaExecutionError(
318
+ "E_ORCA_ATTEMPT_FENCED",
319
+ "This attempt cannot start another worker.",
320
+ "Inspect the stored exact Dispatch; recover an uncertain request by its issued id."
321
+ );
322
+ }
323
+ return this.startCommand(attempt, attempt.startRequestKey);
324
+ }
325
+ /** Replay an issued or pre-reserved retry key on the same runtime and caller. */
326
+ async replayStart(attempt) {
327
+ const requestId = attempt.startRequestKey ?? attempt.startRequestId;
328
+ if (attempt.state !== "outcome_unknown" || !requestId || !attempt.startBinding || attempt.failureCount >= 3) {
329
+ throw new OrcaExecutionError(
330
+ "E_ORCA_ATTEMPT_FENCED",
331
+ "No replayable uncertain start request is retained.",
332
+ "Inspect the original operation; never substitute a fresh Run, Task or launch."
333
+ );
334
+ }
335
+ await this.verifyRequest(attempt, requestId);
336
+ return this.startCommand(attempt, requestId);
337
+ }
338
+ /**
339
+ * Inspect exactly this attempt, settling a reserved stop only on release proof.
340
+ * @remarks A stop settles only when the parent's exact release and affirmative
341
+ * helper evidence agree. A lost, malformed or non-stop receipt is never helper
342
+ * evidence; each helper the receipt names is re-read from Orca, so one that
343
+ * finishes later can still settle the stop.
344
+ */
345
+ async show(attempt) {
346
+ const dispatchId = this.requireDispatch(attempt);
347
+ const reply = await this.query(
348
+ ["orchestration", "worker-show", "--dispatch", dispatchId],
349
+ attempt.launch.projectRoot,
350
+ attempt.context
351
+ );
352
+ const value = reply.result;
353
+ if (!value?.dispatch || !value.worker || value.dispatch.id !== dispatchId || value.worker.dispatchId !== dispatchId || value.dispatch.taskId !== attempt.orcaTaskId || value.dispatch.runId !== attempt.runId || value.worker.runtimeEpoch !== attempt.context.runtimeId || value.worker.worktreeId !== attempt.workspaceId) {
354
+ throw new OrcaExecutionError(
355
+ "E_ORCA_IDENTITY",
356
+ "Worker observation does not match the stored Dispatch binding.",
357
+ "Retain custody and inspect the stored runtime, Run, Task and workspace; do not use newest-record guesses."
358
+ );
359
+ }
360
+ const failureCount = Math.max(attempt.failureCount, value.dispatch.failureCount);
361
+ const resource = value.projection?.resource;
362
+ const released = value.observation?.exactWorker === true && value.observation.status === "exited" && resource?.ownerDispatchId === dispatchId && resource.state === "released" && resource.releaseState === "released" && resource.terminalState === "released";
363
+ const requestedStop = ["stop_pending", "stop_unknown"].includes(attempt.state);
364
+ const helpersSettled = !requestedStop || released && await this.helpersAffirmativelyStopped(
365
+ attempt,
366
+ readHelperEvidence(attempt, attempt.lastReceipt)
367
+ );
368
+ const settled = released && helpersSettled;
369
+ return {
370
+ ...attempt,
371
+ state: requestedStop ? settled ? "stopped" : "stop_unknown" : attempt.state === "stopped" ? "stopped" : failureCount >= 3 ? "circuit_broken" : released && value.worker.state === "failed" ? "failed" : attempt.state,
372
+ failureCount,
373
+ resourceState: settled ? "stopped" : resource?.state === "owned" ? "owned" : "unknown",
374
+ lastReceipt: requestedStop && !settled ? attempt.lastReceipt : reply.rawReceipt,
375
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
376
+ };
377
+ }
378
+ /** Read one bounded page; retain the returned source-pinned cursor verbatim. */
379
+ async read(attempt, cursor) {
380
+ const dispatchId = this.requireDispatch(attempt);
381
+ const reply = await this.query(
382
+ [
383
+ "orchestration",
384
+ "worker-read",
385
+ "--dispatch",
386
+ dispatchId,
387
+ "--source",
388
+ "auto",
389
+ "--limit",
390
+ "200",
391
+ ...cursor ? ["--cursor", cursor] : []
392
+ ],
393
+ attempt.launch.projectRoot,
394
+ attempt.context
395
+ );
396
+ return reply.rawReceipt;
397
+ }
398
+ /** Fetch one full report pointer after a wake; never acknowledge or poll coordinator mail. */
399
+ async readReport(attempt, messageId) {
400
+ const dispatchId = this.requireDispatch(attempt);
401
+ const { runId, orcaTaskId } = attempt;
402
+ if (!runId || !orcaTaskId) {
403
+ throw new OrcaExecutionError(
404
+ "E_ORCA_IDENTITY",
405
+ "No complete report binding is stored.",
406
+ "Recover the original start receipt before ingesting a worker report."
407
+ );
408
+ }
409
+ let message;
410
+ let source;
411
+ let exhausted = false;
412
+ for (let limit = 200; limit <= 12800; limit *= 2) {
413
+ source = await this.reportSource(
414
+ ["orchestration", "inbox", "--terminal", `run:${runId}`, "--limit", String(limit)],
415
+ attempt
416
+ );
417
+ const rows = source.result.messages ?? [];
418
+ const row = rows.find(
419
+ (entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry) && entry.id === messageId
420
+ );
421
+ if (row) {
422
+ const parsed = orcaReportMessageSchema.safeParse(row);
423
+ if (!parsed.success) {
424
+ throw this.reportSourceRefusal(
425
+ source.command,
426
+ `The requested inbox row is malformed: ${parsed.error.message}`,
427
+ "Inspect the exact message in the original full Run inbox and restore its transport fields before retrying."
428
+ );
429
+ }
430
+ message = parsed.data;
431
+ break;
432
+ }
433
+ exhausted = rows.length < limit;
434
+ if (exhausted) break;
435
+ }
436
+ if (!message || !source) {
437
+ throw new OrcaExecutionError(
438
+ "E_ORCA_REPORT_SOURCE",
439
+ exhausted ? `Message ${messageId} is absent from the exhausted Run inbox.` : `The Run inbox lookup reached 12,800 messages without finding ${messageId}; older history remains unsearched.`,
440
+ exhausted ? `Inspect orca orchestration inbox --terminal run:${runId} --limit 12800 --environment local --json --full and use the original worker_done id for this Run.` : `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.`
441
+ );
442
+ }
443
+ if (message.type !== "worker_done" || message.delivery_contract !== "current_delivery" || message.run_id !== runId || message.to_handle !== `run:${runId}`) {
444
+ throw new OrcaExecutionError(
445
+ "E_ORCA_REPORT_SOURCE",
446
+ "The requested message is not a current worker_done for this Run.",
447
+ "Use the exact worker_done id from the original Run; a wake or prose body is not a report."
448
+ );
449
+ }
450
+ let payload;
451
+ try {
452
+ payload = orcaWorkerDonePayloadSchema.parse(JSON.parse(message.payload ?? "null"));
453
+ } catch (error) {
454
+ throw this.reportSourceRefusal(
455
+ source.command,
456
+ `worker_done has no valid report-path payload: ${error instanceof Error ? error.message : String(error)}`,
457
+ "Supply the original canonical report through worker_done --report-path."
458
+ );
459
+ }
460
+ if (payload.taskId !== orcaTaskId || payload.dispatchId !== dispatchId) {
461
+ throw new OrcaExecutionError(
462
+ "E_ORCA_REPORT_IDENTITY",
463
+ "The report pointer does not match this exact Task and Dispatch.",
464
+ "Retain stale delivery as history; use the current worker record and its report-path."
465
+ );
466
+ }
467
+ const current = await this.reportSource(
468
+ [
469
+ "orchestration",
470
+ "dispatch-show",
471
+ "--task",
472
+ orcaTaskId,
473
+ "--from",
474
+ attempt.context.coordinatorHandle
475
+ ],
476
+ attempt
477
+ );
478
+ const dispatch = current.result.dispatch;
479
+ if (dispatch?.id !== dispatchId || dispatch.run_id !== runId || dispatch.task_id !== orcaTaskId || dispatch.status !== "completed" || !(message.from_handle === dispatch.assignee_handle || message.sender_pane_key && message.sender_pane_key === dispatch.assignee_pane_key)) {
480
+ throw new OrcaExecutionError(
481
+ "E_ORCA_REPORT_IDENTITY",
482
+ "The current Dispatch and its report sender are unproven or unsettled.",
483
+ "Inspect the exact current Dispatch; old, cancelled or superseded deliveries cannot settle this worker."
484
+ );
485
+ }
486
+ return {
487
+ messageId,
488
+ runtimeId: attempt.context.runtimeId,
489
+ runId,
490
+ orcaTaskId,
491
+ dispatchId,
492
+ senderHandle: message.from_handle,
493
+ outcome: payload.outcome,
494
+ body: message.body,
495
+ reportPath: payload.reportPath
496
+ };
497
+ }
498
+ /** Request guarded cancellation; a closed terminal action alone is not exit proof. */
499
+ async stop(attempt) {
500
+ if (attempt.state !== "stop_pending" || attempt.stopRequestId) {
501
+ throw new OrcaExecutionError(
502
+ "E_ORCA_ATTEMPT_FENCED",
503
+ "Stop must be durably reserved before it is sent.",
504
+ "Inspect stop_unknown with worker-show; do not blindly repeat a stop."
505
+ );
506
+ }
507
+ return this.stopCommand(attempt, attempt.stopRequestKey);
508
+ }
509
+ /**
510
+ * Recover a reserved or issued cancellation without sending an unkeyed second stop.
511
+ * @remarks A completed key replays Orca's recorded outcome, which cannot reflect a
512
+ * helper that finished after the original stop; `show` reconciles those helpers.
513
+ */
514
+ async replayStop(attempt) {
515
+ this.requireDispatch(attempt);
516
+ const requestId = attempt.stopRequestKey ?? attempt.stopRequestId;
517
+ if (!["stop_pending", "stop_unknown"].includes(attempt.state) || !requestId) {
518
+ throw new OrcaExecutionError(
519
+ "E_ORCA_ATTEMPT_FENCED",
520
+ "No replayable uncertain stop request is retained.",
521
+ "Inspect the exact Dispatch and original stop receipt; never repeat an unkeyed stop."
522
+ );
523
+ }
524
+ await this.verifyRequest(attempt, requestId);
525
+ return this.stopCommand(attempt, requestId);
526
+ }
527
+ async stopCommand(attempt, requestId) {
528
+ const dispatchId = this.requireDispatch(attempt);
529
+ try {
530
+ const capabilities = await this.verifyRuntime(attempt.launch.projectRoot, attempt.context);
531
+ const result = await this.invoke(
532
+ [
533
+ "orchestration",
534
+ "worker-stop",
535
+ "--dispatch",
536
+ dispatchId,
537
+ ...requestId ? ["--retry-request", requestId] : []
538
+ ],
539
+ attempt.launch.projectRoot
540
+ );
541
+ const value = result.result;
542
+ const helpersStopped = value?.helpers !== void 0 ? value.helpers.every((helper) => SETTLED_HELPER_OUTCOMES.has(helper.outcome)) : capabilities.includes(HELPER_STOP_CAPABILITY);
543
+ const confirmed = result.ok && result._meta?.runtimeId === attempt.context.runtimeId && value?.dispatchId === dispatchId && value.state === "stopped" && value.processAction === "closed_agent_terminal" && !value.helperStopError && helpersStopped;
544
+ return {
545
+ ...attempt,
546
+ state: confirmed ? "stopped" : "stop_unknown",
547
+ stopRequestId: attempt.stopRequestId ?? (result._meta?.runtimeId === attempt.context.runtimeId ? result.error?.data?.orchestrationRequestId ?? null : null),
548
+ // Record that this runtime enumerated helpers, so an omitted list in its reply
549
+ // is latent affirmative evidence rather than an unknown helper tree. Only a
550
+ // proven stopped parent from this exact runtime, Dispatch and request can prove
551
+ // it cannot start a new helper after this reply.
552
+ stopHelperEvidence: confirmed && value?.helpers === void 0 ? "enumerated" : attempt.stopHelperEvidence,
553
+ resourceState: confirmed ? "stopped" : "unknown",
554
+ lastReceipt: result.rawReceipt,
555
+ lastError: result.error?.message ?? value?.lastError ?? null,
556
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
557
+ };
558
+ } catch (error) {
559
+ return {
560
+ ...attempt,
561
+ state: "stop_unknown",
562
+ lastError: String(error),
563
+ lastReceipt: error instanceof OrcaExecutionError ? error.receipt ?? attempt.lastReceipt : attempt.lastReceipt,
564
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
565
+ };
566
+ }
567
+ }
568
+ async startCommand(attempt, requestId) {
569
+ const launch = attempt.launch;
570
+ this.validateLaunch(launch, attempt.context);
571
+ if (launch.harness === "kimi") {
572
+ throw new OrcaExecutionError(
573
+ "E_ORCA_HARNESS_UNSUPPORTED",
574
+ "Kimi has no direct Orca launch route.",
575
+ "Use a supervised terminal adoption path."
576
+ );
577
+ }
578
+ const binding = attempt.startBinding ?? attempt;
579
+ if (attempt.startRequestKey && (!binding.runId || !binding.orcaTaskId || !binding.retryOf || binding.runId !== attempt.runId || binding.orcaTaskId !== attempt.orcaTaskId || binding.retryOf !== attempt.retryOf || requestId !== attempt.startRequestKey || attempt.startRequestId !== null && attempt.startRequestId !== attempt.startRequestKey)) {
580
+ throw new OrcaExecutionError(
581
+ "E_ORCA_ATTEMPT_FENCED",
582
+ "A reserved start key requires the original exact retry binding.",
583
+ "Retain custody and inspect the reserved key, Run, Task and predecessor; never send an unkeyed replacement."
584
+ );
585
+ }
586
+ const args = [
587
+ "orchestration",
588
+ "worker-start",
589
+ "--from",
590
+ attempt.context.coordinatorHandle,
591
+ "--worktree",
592
+ attempt.workspaceSelector,
593
+ "--agent",
594
+ AGENTS[launch.harness],
595
+ ...binding.orcaTaskId ? ["--task", binding.orcaTaskId] : [
596
+ "--spec-file",
597
+ "-",
598
+ "--task-title",
599
+ `${launch.projectId}:${launch.taskId}:${launch.instanceId}`
600
+ ],
601
+ ...binding.runId ? ["--run", binding.runId] : [],
602
+ ...binding.retryOf ? ["--retry-of", binding.retryOf] : [],
603
+ ...launch.model ? ["--model", launch.model] : [],
604
+ ...launch.effort ? ["--effort", launch.effort] : [],
605
+ ...requestId ? ["--retry-request", requestId] : []
606
+ ];
607
+ try {
608
+ await this.verifyRuntime(launch.projectRoot, attempt.context, launch.model !== void 0);
609
+ const reply = await this.invoke(
610
+ args,
611
+ launch.projectRoot,
612
+ binding.orcaTaskId ? void 0 : launch.prompt
613
+ );
614
+ if (!reply.ok && reply.error?.code === "agent_unconfigured" && reply._meta?.runtimeId === attempt.context.runtimeId && !binding.orcaTaskId && !binding.retryOf && !reply.error.data?.dispatchId && !reply.result?.dispatchId && !reply.result?.taskId && !reply.result?.runId && !reply.result?.run && !reply.result?.failureCount && !reply.result?.residualResources?.length && (!reply.result?.effects?.length || reply.result.effects.every(
615
+ (effect) => effect.kind === "worktree" && effect.action === "reused" && effect.id === attempt.workspaceId
616
+ ))) {
617
+ return {
618
+ ...attempt,
619
+ state: "failed",
620
+ resourceState: "stopped",
621
+ startRefusal: "agent_unconfigured",
622
+ startRequestId: reply.error.data?.orchestrationRequestId ?? null,
623
+ lastReceipt: reply.rawReceipt,
624
+ lastError: "agent_unconfigured",
625
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
626
+ };
627
+ }
628
+ const value = reply.result;
629
+ const workspace = value?.effects?.filter((effect) => effect.kind === "worktree");
630
+ const bound = reply._meta?.runtimeId === attempt.context.runtimeId && value?.dispatchId && value.taskId && (value.runId || value.run?.id) && value.dispatchId !== attempt.retryOf && (!attempt.dispatchId || attempt.dispatchId === value.dispatchId) && (!attempt.orcaTaskId || attempt.orcaTaskId === value.taskId) && (!attempt.runId || attempt.runId === (value.runId ?? value.run?.id));
631
+ const matches = bound && workspace?.length === 1 && workspace[0]?.id === attempt.workspaceId && value.launch?.effective?.agent === AGENTS[launch.harness] && (!launch.model || launch.model === value.launch.effective.model) && (!launch.effort || launch.effort === value.launch.effective.effort);
632
+ let state = "outcome_unknown";
633
+ if (matches && reply.ok) {
634
+ if (value.state === "ready") state = "ready";
635
+ else if (value.state === "outcome_unknown" && (value.turnStart === "unobserved" || value.stage === "turn_start_unobserved"))
636
+ state = "turn_unobserved";
637
+ else if (value.state === "failed") state = "failed";
638
+ }
639
+ const failureCount = Math.max(attempt.failureCount, value?.failureCount ?? 0);
640
+ const pending = reply.error?.data;
641
+ const recoveredDispatchId = !reply.ok && reply.error?.code === "operation_unknown" && reply._meta?.runtimeId === attempt.context.runtimeId && requestId && requestId === (attempt.startRequestKey ?? attempt.startRequestId) && pending?.requestId === requestId && pending.orchestrationRequestId === requestId && pending.dispatchId !== attempt.retryOf && (!attempt.dispatchId || attempt.dispatchId === pending.dispatchId) ? pending.dispatchId : null;
642
+ return {
643
+ ...attempt,
644
+ state: failureCount >= 3 ? "circuit_broken" : state,
645
+ runId: bound ? value.runId ?? value.run?.id ?? null : attempt.runId,
646
+ orcaTaskId: bound ? value.taskId ?? null : attempt.orcaTaskId,
647
+ dispatchId: bound ? value.dispatchId ?? null : recoveredDispatchId ?? attempt.dispatchId,
648
+ startRequestId: attempt.startRequestKey ?? attempt.startRequestId ?? (reply._meta?.runtimeId === attempt.context.runtimeId ? reply.error?.data?.orchestrationRequestId ?? null : null),
649
+ failureCount,
650
+ resourceState: matches && state === "ready" ? "owned" : "unknown",
651
+ lastReceipt: reply.rawReceipt,
652
+ lastError: reply.error?.message ?? value?.lastError ?? (matches ? null : "Receipt identity or effective harness is unproven"),
653
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
654
+ };
655
+ } catch (error) {
656
+ return {
657
+ ...attempt,
658
+ state: "outcome_unknown",
659
+ lastError: String(error),
660
+ lastReceipt: error instanceof OrcaExecutionError ? error.receipt ?? attempt.lastReceipt : attempt.lastReceipt,
661
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
662
+ };
663
+ }
664
+ }
665
+ /**
666
+ * Decide whether current Orca evidence proves every helper stopped or finished.
667
+ * @remarks An absent receipt or an incomplete helper tree never settles; a
668
+ * listed helper is settled only by its own exact Dispatch showing an exited
669
+ * process. A completed stop key replays its recorded outcome, so unresolved
670
+ * helpers are re-read rather than replayed.
671
+ */
672
+ async helpersAffirmativelyStopped(attempt, evidence) {
673
+ switch (evidence.kind) {
674
+ case "settled":
675
+ return true;
676
+ case "absent":
677
+ return false;
678
+ case "empty":
679
+ return attempt.stopHelperEvidence === "enumerated";
680
+ case "unresolved": {
681
+ if (!evidence.reconcileable) return false;
682
+ for (const helperDispatchId of evidence.dispatchIds) {
683
+ if (!await this.helperFinished(attempt, helperDispatchId)) return false;
684
+ }
685
+ return true;
686
+ }
687
+ }
688
+ }
689
+ /**
690
+ * Prove one helper Dispatch's process exited under this exact attempt's ancestry.
691
+ * @remarks A helper counts only when its own Dispatch is on this Run and runtime,
692
+ * its process exited, and its creator chain reaches this attempt's Dispatch. An
693
+ * unrelated helper in the same Run therefore never settles this stop.
694
+ */
695
+ async helperFinished(attempt, helperDispatchId) {
696
+ const observation = await this.exactWorkerObservation(attempt, helperDispatchId);
697
+ if (!observation || observation.observation?.exactWorker !== true || observation.observation.status !== "exited") {
698
+ return false;
699
+ }
700
+ return this.descendsFromAttempt(attempt, observation.dispatch?.creatorDispatchId ?? null);
701
+ }
702
+ /** Walk the bounded creator chain of a helper back to this attempt's Dispatch. */
703
+ async descendsFromAttempt(attempt, creatorDispatchId) {
704
+ let creator = creatorDispatchId;
705
+ for (let hop = 0; hop < HELPER_ANCESTRY_LIMIT; hop += 1) {
706
+ if (creator === attempt.dispatchId) return true;
707
+ if (!creator) return false;
708
+ const parent = await this.exactWorkerObservation(attempt, creator);
709
+ creator = parent?.dispatch?.creatorDispatchId ?? null;
710
+ }
711
+ return false;
712
+ }
713
+ /** Read one exact worker observation, refusing any other Dispatch, Run or epoch. */
714
+ async exactWorkerObservation(attempt, dispatchId) {
715
+ const reply = await this.query(
716
+ ["orchestration", "worker-show", "--dispatch", dispatchId],
717
+ attempt.launch.projectRoot,
718
+ attempt.context
719
+ ).catch(() => null);
720
+ const value = reply?.result;
721
+ if (!value?.dispatch || !value.worker || value.dispatch.id !== dispatchId || value.dispatch.runId !== attempt.runId || value.worker.dispatchId !== dispatchId || value.worker.runtimeEpoch !== attempt.context.runtimeId) {
722
+ return null;
723
+ }
724
+ return value;
725
+ }
726
+ async verifyRequest(attempt, requestId) {
727
+ await this.verifyRuntime(attempt.launch.projectRoot, attempt.context);
728
+ const receipt = await this.query(
729
+ ["orchestration", "request-show", "--request", requestId],
730
+ attempt.launch.projectRoot,
731
+ attempt.context
732
+ );
733
+ const reserved = requestId === attempt.startRequestKey || requestId === attempt.stopRequestKey;
734
+ const states = reserved ? ["pending", "completed", "absent"] : ["pending", "completed"];
735
+ if (receipt.result?.requestId !== requestId || !states.includes(receipt.result.state ?? "")) {
736
+ throw new OrcaExecutionError(
737
+ "E_ORCA_ATTEMPT_FENCED",
738
+ "Request absence or a mismatched receipt does not prove that nothing happened.",
739
+ "Retain custody and inspect the original request on its original runtime and caller."
740
+ );
741
+ }
742
+ }
743
+ requireDispatch(attempt) {
744
+ if (!attempt.dispatchId || !attempt.runId || !attempt.orcaTaskId) {
745
+ throw new OrcaExecutionError(
746
+ "E_ORCA_IDENTITY",
747
+ "No complete Dispatch binding is available.",
748
+ "Recover the issued start request, retaining the pending worker record and claim."
749
+ );
750
+ }
751
+ return attempt.dispatchId;
752
+ }
753
+ async verifyRuntime(cwd, context, modelRequested = false) {
754
+ const reply = await this.query(["status"], cwd, context);
755
+ const runtime = reply.result?.runtime;
756
+ if (!runtime?.reachable || runtime.state !== "ready" || runtime.runtimeId !== context.runtimeId || !runtime.capabilities.includes("orchestration.contract.v1") || modelRequested && !runtime.capabilities.includes("orchestration.worker-launch-preferences.v1")) {
757
+ throw new OrcaExecutionError(
758
+ "E_ORCA_CONTEXT",
759
+ "The selected Orca runtime is unavailable or changed.",
760
+ "Inspect Orca status and retain unresolved attempts; explicitly reconcile their original runtime before relaunch."
761
+ );
762
+ }
763
+ return runtime.capabilities;
764
+ }
765
+ async reportSource(args, attempt) {
766
+ const reply = await this.runner(
767
+ this.executable,
768
+ [...args, "--environment", "local", "--json", "--full"],
769
+ attempt.launch.projectRoot
770
+ );
771
+ try {
772
+ const source = orcaReportSourceSchema.parse(JSON.parse(reply.stdout));
773
+ if (reply.exitCode !== 0)
774
+ throw new Error("The report source command did not exit successfully.");
775
+ if (source._meta.runtimeId !== attempt.context.runtimeId)
776
+ throw new Error(
777
+ `Report source runtime ${source._meta.runtimeId} differs from ${attempt.context.runtimeId}.`
778
+ );
779
+ if (args[1] === "inbox" && !source.result.messages)
780
+ throw new Error("The Run inbox omitted its messages array.");
781
+ return { ...source, command: reply };
782
+ } catch (error) {
783
+ throw this.reportSourceRefusal(
784
+ reply,
785
+ error instanceof Error ? error.message : String(error),
786
+ "Inspect the original runtime and full Run inbox; retain the worker record."
787
+ );
788
+ }
789
+ }
790
+ reportSourceRefusal(command, issues, fix) {
791
+ return new OrcaExecutionError(
792
+ "E_ORCA_REPORT_SOURCE",
793
+ `Orca returned no verified report source: ${JSON.stringify({
794
+ exitCode: command.exitCode,
795
+ stderr: command.stderr,
796
+ issues
797
+ })}`,
798
+ fix,
799
+ command.stdout
800
+ );
801
+ }
802
+ async query(args, cwd, context) {
803
+ const reply = await this.invoke(args, cwd);
804
+ if (!reply.ok || reply._meta?.runtimeId !== context.runtimeId) {
805
+ throw new OrcaExecutionError(
806
+ "E_ORCA_CONTEXT",
807
+ reply.error?.message ?? "Orca returned an unproven runtime identity.",
808
+ "Inspect the explicitly selected runtime; preserve pending operations and do not fall back to a native launch."
809
+ );
810
+ }
811
+ return reply;
812
+ }
813
+ async invoke(args, cwd, input) {
814
+ const result = await this.runner(
815
+ this.executable,
816
+ [
817
+ ...args,
818
+ "--environment",
819
+ "local",
820
+ "--json",
821
+ ...args[0] === "orchestration" ? ["--full"] : []
822
+ ],
823
+ cwd,
824
+ input
825
+ );
826
+ try {
827
+ return { ...orcaReplySchema.parse(JSON.parse(result.stdout)), rawReceipt: result.stdout };
828
+ } catch {
829
+ throw new OrcaExecutionError(
830
+ "E_ORCA_RECEIPT",
831
+ "Orca returned no parseable receipt.",
832
+ "Preserve pending custody and inspect the original operation; a CLI exit is not worker exit proof.",
833
+ result.stdout
834
+ );
835
+ }
836
+ }
837
+ };
838
+ export {
839
+ OrcaExecutionBackend,
840
+ OrcaExecutionError,
841
+ runOrcaCommand
842
+ };
843
+ //# sourceMappingURL=orca-execution.js.map