@cleocode/adapters 2026.11.2 → 2026.11.3-canary.2

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.
@@ -2,8 +2,10 @@
2
2
  * Local Orca execution, with no task-store, claim or filesystem disposal authority.
3
3
  * @packageDocumentation
4
4
  */
5
- import { execFile } from 'node:child_process';
6
- import { isAbsolute } from 'node:path';
5
+ import { execFile, execFileSync } from 'node:child_process';
6
+ import { mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
7
+ import { isAbsolute, join } from 'node:path';
8
+ import { setTimeout as delay } from 'node:timers/promises';
7
9
  import type {
8
10
  OrcaAttempt,
9
11
  OrcaCommandReply,
@@ -12,6 +14,9 @@ import type {
12
14
  OrcaContext,
13
15
  OrcaDiscovery,
14
16
  OrcaLaunch,
17
+ OrcaLeadStartupDiagnostic,
18
+ OrcaLeadTerminal,
19
+ OrcaLeadTerminalLaunch,
15
20
  OrcaReply,
16
21
  OrcaReportSource,
17
22
  OrcaRoutingAdapter,
@@ -28,6 +33,8 @@ import {
28
33
  orcaReportSourceSchema,
29
34
  orcaWorkerDonePayloadSchema,
30
35
  } from '@cleocode/contracts/orca-execution.js';
36
+ import { PS_STABLE_ENV } from '@cleocode/contracts/process-probe.js';
37
+ import { findOnPath, pathDelimiterFor, splitPathEnv } from '@cleocode/paths';
31
38
 
32
39
  const AGENTS = { 'claude-code': 'claude', codex: 'codex', opencode: 'opencode2', grok: 'grok' };
33
40
  const MAX_DIAGNOSTIC_LENGTH = 4_096;
@@ -182,13 +189,22 @@ export class OrcaExecutionError extends Error {
182
189
  readonly fix: string;
183
190
  /** Bounded original receipt, when available; oversized receipts are diagnostic only. */
184
191
  readonly receipt: string | null;
192
+ /** Nonsecret terminal/PID evidence for a guarded lead refusal. */
193
+ readonly details?: OrcaLeadStartupDiagnostic;
185
194
 
186
195
  /** Construct a refusal before any unsupported operation runs. */
187
- constructor(code: string, message: string, fix: string, receipt: string | null = null) {
196
+ constructor(
197
+ code: string,
198
+ message: string,
199
+ fix: string,
200
+ receipt: string | null = null,
201
+ details?: OrcaLeadStartupDiagnostic,
202
+ ) {
188
203
  super(message.slice(0, MAX_DIAGNOSTIC_LENGTH));
189
204
  this.name = 'OrcaExecutionError';
190
205
  this.code = code;
191
206
  this.fix = fix;
207
+ this.details = details;
192
208
  const truncated = '[truncated]\n';
193
209
  this.receipt =
194
210
  receipt !== null && receipt.length > MAX_RECEIPT_LENGTH
@@ -221,7 +237,7 @@ export const runOrcaCommand: OrcaCommandRunner = (executable, args, cwd, input)
221
237
  * provider registry. Core persists each operation before invoking these methods.
222
238
  */
223
239
  export class OrcaExecutionBackend implements OrcaRoutingAdapter {
224
- /** Public launch APIs cannot enforce denied tools or a strict MCP allowlist. */
240
+ /** Worker launch APIs cannot enforce denied tools or a strict MCP allowlist. */
225
241
  readonly leadToolStrip = 'unsupported';
226
242
  private readonly executable: string;
227
243
 
@@ -249,6 +265,284 @@ export class OrcaExecutionBackend implements OrcaRoutingAdapter {
249
265
  );
250
266
  }
251
267
 
268
+ /**
269
+ * Host Claude Code's prepared guard argv in a local Orca terminal. The shell
270
+ * waits for a private release file, so a missing receipt, wrong runtime or
271
+ * disconnected owner terminal cannot start a model turn. Never retry create.
272
+ * @param launch - The provider's guarded command and private startup directory.
273
+ * @param onStarted - Persists the terminal and PID before any model turn is allowed.
274
+ * @returns The verified terminal handle and provider PID.
275
+ */
276
+ async startLead(
277
+ launch: OrcaLeadTerminalLaunch,
278
+ onStarted: (pid: number, terminal?: OrcaLeadTerminal) => void | Promise<void>,
279
+ ): Promise<OrcaLeadTerminal> {
280
+ let diagnostic: OrcaLeadStartupDiagnostic | undefined;
281
+ const refuse = (message: string) =>
282
+ new OrcaExecutionError(
283
+ ORCA_LEAD_LAUNCH_REFUSAL.code,
284
+ message,
285
+ `${diagnostic ? 'Compare the terminal/PID error details: the guarded shell must be the reported process or its OS-proven direct child. ' : ''}Restore a visible connected local Orca terminal and use --adapter claude-code; update the CLI and runtime together if required terminal commands are unavailable; keep orchestrate.leadWorker.v1 enabled.`,
286
+ null,
287
+ diagnostic,
288
+ );
289
+ const handle = process.env.ORCA_TERMINAL_HANDLE;
290
+ if (!handle) {
291
+ throw new OrcaExecutionError(
292
+ 'E_ORCA_CONTEXT',
293
+ 'Orca context hints have no ORCA_TERMINAL_HANDLE; a guarded lead cannot select its owner terminal.',
294
+ 'Run in the intended Orca terminal with its ORCA_TERMINAL_HANDLE, or remove stale ORCA_* hints outside Orca to use the native route; keep orchestrate.leadWorker.v1 enabled.',
295
+ );
296
+ }
297
+ if (
298
+ process.platform === 'win32' ||
299
+ !isAbsolute(launch.command) ||
300
+ !isAbsolute(launch.tempDir) ||
301
+ !launch.env.CLEO_SESSION_ID ||
302
+ !launch.env.CLEO_AGENT_ID ||
303
+ launch.env.CLEO_AGENT_ROLE !== 'lead'
304
+ ) {
305
+ throw refuse(
306
+ 'The guarded Orca lead requires a local POSIX terminal and an absolute provider binary.',
307
+ );
308
+ }
309
+ const registryResult = await this.runner(
310
+ this.executable,
311
+ ['agent-context', '--json'],
312
+ launch.cwd,
313
+ );
314
+ const registry = orcaCommandRegistrySchema.parse(JSON.parse(registryResult.stdout));
315
+ const create = registry.commands.find((entry) => entry.command === 'terminal create');
316
+ const show = registry.commands.find((entry) => entry.command === 'terminal show');
317
+ const close = registry.commands.find((entry) => entry.command === 'terminal close');
318
+ const focus = registry.commands.find((entry) => entry.command === 'terminal switch');
319
+ if (
320
+ registryResult.exitCode !== 0 ||
321
+ !create ||
322
+ !['command', 'worktree', 'title', 'environment'].every((flag) =>
323
+ create.flags.includes(flag),
324
+ ) ||
325
+ !show ||
326
+ !['terminal', 'environment'].every((flag) => show.flags.includes(flag)) ||
327
+ !close ||
328
+ !['terminal', 'environment'].every((flag) => close.flags.includes(flag)) ||
329
+ !focus ||
330
+ !['terminal', 'environment'].every((flag) => focus.flags.includes(flag))
331
+ ) {
332
+ throw refuse('Orca does not declare the guarded terminal command transport.');
333
+ }
334
+ const status = await this.invoke(['status'], launch.cwd);
335
+ const runtimeId = status._meta?.runtimeId;
336
+ if (!status.ok || !runtimeId) throw refuse('Orca did not prove a local runtime.');
337
+ const context: OrcaContext = { runtimeId, coordinatorHandle: handle, executionHostId: 'local' };
338
+ await this.verifyRuntime(launch.cwd, context);
339
+ const caller = (
340
+ await this.query(['terminal', 'show', '--terminal', handle], launch.cwd, context)
341
+ ).result?.terminal;
342
+ const workspace = (
343
+ await this.query(
344
+ ['worktree', 'show', '--worktree', `path:${launch.cwd}`],
345
+ launch.cwd,
346
+ context,
347
+ )
348
+ ).result?.worktree;
349
+ if (
350
+ caller?.handle !== handle ||
351
+ !caller.connected ||
352
+ !caller.writable ||
353
+ caller.executionHostId !== 'local' ||
354
+ !workspace ||
355
+ workspace.path !== launch.cwd ||
356
+ workspace.hostId !== 'local'
357
+ ) {
358
+ throw refuse('Orca did not prove the local caller and existing lead workspace.');
359
+ }
360
+
361
+ const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
362
+ for (const key of Object.keys(launch.env)) {
363
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw refuse('Invalid lead environment key.');
364
+ }
365
+ const dir = await mkdtemp(join(launch.tempDir, 'orca-terminal-'));
366
+ const script = join(dir, 'launch.sh');
367
+ const pidFile = join(dir, 'pid');
368
+ const release = join(dir, 'release');
369
+ let terminalHandle: string | undefined;
370
+ try {
371
+ await writeFile(
372
+ script,
373
+ [
374
+ '#!/bin/sh',
375
+ 'umask 077',
376
+ `trap ${quote(`rm -rf -- ${quote(dir)}`)} EXIT`,
377
+ `printf '%s' "$$" > ${quote(pidFile)}`,
378
+ 'attempt=0',
379
+ `while [ ! -f ${quote(release)} ]; do`,
380
+ ` [ -d ${quote(dir)} ] || exit 1`,
381
+ ' attempt=$((attempt + 1)); [ "$attempt" -le 600 ] || exit 1',
382
+ ' sleep 0.1',
383
+ 'done',
384
+ `cd ${quote(launch.cwd)} || exit 1`,
385
+ ...Object.entries(launch.env).map(([key, value]) => `export ${quote(`${key}=${value}`)}`),
386
+ `exec ${[launch.command, ...launch.args].map(quote).join(' ')}`,
387
+ '',
388
+ ].join('\n'),
389
+ { mode: 0o600 },
390
+ );
391
+ const created = await this.query(
392
+ [
393
+ 'terminal',
394
+ 'create',
395
+ '--worktree',
396
+ workspace.address?.worktree ?? `id:${workspace.id}`,
397
+ '--title',
398
+ 'CLEO no-hands lead',
399
+ '--command',
400
+ `exec /bin/sh ${quote(script)}`,
401
+ ],
402
+ launch.cwd,
403
+ context,
404
+ );
405
+ const terminal = created.result?.terminal;
406
+ if (terminal && terminal.handle !== handle && terminal.executionHostId === 'local') {
407
+ terminalHandle = terminal.handle;
408
+ diagnostic = {
409
+ runtimeId,
410
+ terminalHandle,
411
+ expectedTerminalPid: terminal.processId ?? null,
412
+ observedSupervisorPid: null,
413
+ observedParentPid: null,
414
+ };
415
+ }
416
+ if (
417
+ !terminal ||
418
+ terminal.handle === handle ||
419
+ terminal.executionHostId !== 'local' ||
420
+ terminal.surface !== 'visible' ||
421
+ terminal.hostPlatform !== process.platform
422
+ ) {
423
+ throw refuse('Orca returned no new local lead terminal; its first-turn gate stays closed.');
424
+ }
425
+ let pid = 0;
426
+ for (let attempt = 0; attempt < 100; attempt++) {
427
+ const text = await readFile(pidFile, 'utf8').catch(() => '');
428
+ if (/^[1-9][0-9]*$/.test(text)) {
429
+ pid = Number(text);
430
+ break;
431
+ }
432
+ await delay(100);
433
+ }
434
+ let parentPid: number | null = null;
435
+ let supervisorStartedAt: string | null = null;
436
+ let terminalStartedAt: string | null = null;
437
+ if (Number.isSafeInteger(pid) && pid > 0) {
438
+ try {
439
+ const ps =
440
+ findOnPath('ps', {
441
+ env: {
442
+ ...process.env,
443
+ PATH: splitPathEnv(process.env.PATH).filter(isAbsolute).join(pathDelimiterFor()),
444
+ },
445
+ }) ?? '/bin/ps';
446
+ const rows = execFileSync(
447
+ ps,
448
+ ['-o', 'pid=,ppid=,lstart=', '-p', `${pid},${terminal.processId ?? pid}`],
449
+ {
450
+ encoding: 'utf8',
451
+ timeout: 2_000,
452
+ stdio: ['ignore', 'pipe', 'ignore'],
453
+ env: { ...process.env, ...PS_STABLE_ENV },
454
+ },
455
+ )
456
+ .split('\n')
457
+ .map((line) => /^\s*([0-9]+)\s+([0-9]+)\s+(.+?)\s*$/.exec(line));
458
+ const supervisor = rows.find((row) => Number(row?.[1]) === pid);
459
+ const terminalProcess = rows.find((row) => Number(row?.[1]) === terminal.processId);
460
+ const parent = supervisor?.[2] ?? '';
461
+ if (/^[1-9][0-9]*$/.test(parent) && Number.isSafeInteger(Number(parent)))
462
+ parentPid = Number(parent);
463
+ supervisorStartedAt = supervisor?.[3] ?? null;
464
+ terminalStartedAt = terminalProcess?.[3] ?? null;
465
+ } catch {
466
+ // A failed OS probe cannot prove the private PID belongs to this terminal.
467
+ }
468
+ }
469
+ diagnostic = {
470
+ runtimeId,
471
+ terminalHandle: terminal.handle,
472
+ expectedTerminalPid: terminal.processId ?? null,
473
+ observedSupervisorPid: pid > 0 ? pid : null,
474
+ observedParentPid: parentPid,
475
+ supervisorStartedAt,
476
+ terminalStartedAt,
477
+ };
478
+ // macOS Orca reports /usr/bin/login, whose direct child execs the guarded shell.
479
+ const supervisorStart = Date.parse(`${supervisorStartedAt} UTC`);
480
+ const terminalStart = Date.parse(`${terminalStartedAt} UTC`);
481
+ if (
482
+ parentPid === null ||
483
+ (pid !== terminal.processId && parentPid !== terminal.processId) ||
484
+ !Number.isFinite(supervisorStart) ||
485
+ !Number.isFinite(terminalStart) ||
486
+ supervisorStart < terminalStart
487
+ ) {
488
+ throw refuse(
489
+ 'The guarded terminal supervisor did not prove its startup PID as the Orca process or its direct child with a valid start order.',
490
+ );
491
+ }
492
+ // Older Orca show replies omit surface; an affirmative UI navigation proves visibility now.
493
+ const focused = (
494
+ await this.query(['terminal', 'switch', '--terminal', terminal.handle], launch.cwd, context)
495
+ ).result?.focus;
496
+ const owner = (
497
+ await this.query(['terminal', 'show', '--terminal', terminal.handle], launch.cwd, context)
498
+ ).result?.terminal;
499
+ if (
500
+ owner?.handle !== terminal.handle ||
501
+ !owner.connected ||
502
+ !owner.writable ||
503
+ (owner.surface !== undefined && owner.surface !== 'visible') ||
504
+ focused?.handle !== terminal.handle ||
505
+ !focused.navigated ||
506
+ focused.worktreeId !== workspace.id ||
507
+ owner.tabId !== focused.tabId ||
508
+ owner.executionHostId !== 'local' ||
509
+ owner.worktreePath !== launch.cwd
510
+ ) {
511
+ throw refuse('The lead has no verified owner terminal; its first-turn gate stays closed.');
512
+ }
513
+ const started = { runtimeId, terminalHandle: terminal.handle, pid };
514
+ await onStarted(pid, started);
515
+ await writeFile(`${release}.tmp`, '', { mode: 0o600 });
516
+ await rename(`${release}.tmp`, release);
517
+ return started;
518
+ } catch (error) {
519
+ await rm(dir, { recursive: true, force: true });
520
+ if (terminalHandle) {
521
+ try {
522
+ await this.verifyRuntime(launch.cwd, context);
523
+ const closed = (
524
+ await this.query(
525
+ ['terminal', 'close', '--terminal', terminalHandle],
526
+ launch.cwd,
527
+ context,
528
+ )
529
+ ).result?.close;
530
+ if (closed?.handle !== terminalHandle || !closed.ptyKilled)
531
+ throw refuse('Orca did not prove terminal cleanup.');
532
+ } catch (cleanupError) {
533
+ throw new OrcaExecutionError(
534
+ error instanceof OrcaExecutionError ? error.code : ORCA_LEAD_LAUNCH_REFUSAL.code,
535
+ `${error instanceof Error ? error.message : String(error)}; terminal ${terminalHandle} cleanup is unverified: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
536
+ `${error instanceof OrcaExecutionError ? error.fix : 'Restore the guarded terminal transport.'} Inspect orca terminal show --terminal ${terminalHandle} before closing that exact terminal.`,
537
+ error instanceof OrcaExecutionError ? error.receipt : null,
538
+ error instanceof OrcaExecutionError ? (error.details ?? diagnostic) : diagnostic,
539
+ );
540
+ }
541
+ }
542
+ throw error;
543
+ }
544
+ }
545
+
252
546
  /** Verify the local caller before returning a sanitized account inventory. */
253
547
  async discover(projectRoot: string): Promise<OrcaDiscovery | null> {
254
548
  if (!this.hasContextHints()) return null;
@@ -31,7 +31,10 @@ import { tmpdir } from 'node:os';
31
31
  import { join } from 'node:path';
32
32
  import type { SpawnContext } from '@cleocode/contracts';
33
33
  import { E_LEAD_NO_OWNER_CHANNEL, LEAD_DENIED_TOOLS, LEAD_RUNNER_TOOL } from '@cleocode/contracts';
34
+ import type { OrcaLeadTerminalLauncher } from '@cleocode/contracts/orca-execution.js';
34
35
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
36
+ import { OrcaExecutionError } from '../../../orca-execution.js';
37
+ import * as leadMcpModule from '../lead-mcp.js';
35
38
  import { LEAD_MCP_FILE, prepareLeadMcp, resolveMbxMcpServer } from '../lead-mcp.js';
36
39
  import {
37
40
  LEAD_KICKOFF_PROMPT,
@@ -83,6 +86,8 @@ describe('lead isolation on claude-code (T14363, T14423)', () => {
83
86
  });
84
87
 
85
88
  afterEach(() => {
89
+ vi.restoreAllMocks();
90
+ vi.unstubAllEnvs();
86
91
  rmSync(root, { recursive: true, force: true });
87
92
  });
88
93
 
@@ -147,6 +152,124 @@ describe('lead isolation on claude-code (T14363, T14423)', () => {
147
152
  expect(args.join(' ')).not.toContain('AskUserQuestion');
148
153
  });
149
154
 
155
+ it.skipIf(process.platform === 'win32').each(['interactive', 'detached'] as const)(
156
+ 'hands the production %s guards to Orca and preserves cross-bundle refusals',
157
+ async (mode) => {
158
+ writeFileSync(claudeJson, JSON.stringify({ mcpServers: { mbx, shell: SHELL_SERVER } }));
159
+ for (const name of ['claude', 'cleo']) fakeBinary(join(bin, name), join(root, 'calls.log'));
160
+ vi.stubEnv('PATH', `${bin}:${process.env.PATH}`);
161
+ const prepare = prepareLeadMcp;
162
+ vi.spyOn(leadMcpModule, 'prepareLeadMcp').mockImplementation((dir, cwd, options) =>
163
+ prepare(dir, cwd, { ...options, claudeJsonPath: claudeJson }),
164
+ );
165
+ const started = vi.fn<(pid: number) => void>();
166
+ let promptFile = '';
167
+ const launcher = vi.fn<OrcaLeadTerminalLauncher>(async (launch, onStarted) => {
168
+ const value = (flag: string) => launch.args[launch.args.indexOf(flag) + 1] ?? '';
169
+ expect(launch.command).toBe(join(bin, 'claude'));
170
+ expect(launch.env).toEqual(IDENTITY);
171
+ expect(launch.args).toContain('--restricted');
172
+ expect(launch.args).toContain('--strict-mcp-config');
173
+ expect(launch.args).not.toContain('--dangerously-skip-permissions');
174
+ expect(value('--tools')).toBe(mode === 'interactive' ? 'AskUserQuestion' : '');
175
+ expect(value('--permission-mode')).toBe(mode === 'interactive' ? 'default' : 'dontAsk');
176
+ expect(value('--setting-sources')).toBe('');
177
+ expect(value('--session-id')).toBe(SESSION);
178
+ expect(value('--disallowedTools')).toBe('Bash,Edit,Write,NotebookEdit,WebFetch,WebSearch');
179
+ expect(value('--allowedTools')).toBe(
180
+ `${LEAD_RUNNER_TOOL},mcp__mbx${mode === 'interactive' ? ',AskUserQuestion' : ''}`,
181
+ );
182
+ const config = JSON.parse(readFileSync(value('--mcp-config'), 'utf8'));
183
+ expect(Object.keys(config.mcpServers).sort()).toEqual(['cleo-lead', 'mbx']);
184
+ expect(config.mcpServers['cleo-lead'].env).toEqual(IDENTITY);
185
+ const settings = JSON.parse(readFileSync(value('--settings'), 'utf8'));
186
+ expect(settings.hooks.SessionStart[0].hooks[0].command).toContain(value('--mcp-config'));
187
+ expect(settings.hooks.SessionEnd[0].hooks[0].command).toContain(`--session ${SESSION}`);
188
+ expect(statSync(value('--settings')).mode & 0o077).toBe(0);
189
+ promptFile = value('--append-system-prompt-file');
190
+ expect(readFileSync(promptFile, 'utf8')).toContain('plan');
191
+ expect(started).not.toHaveBeenCalled();
192
+ onStarted(12345);
193
+ return { runtimeId: 'runtime-fixture', terminalHandle: 'term_lead', pid: 12345 };
194
+ });
195
+ try {
196
+ const result = await new ClaudeCodeSpawnProvider().spawn({
197
+ ...lead(mode),
198
+ workingDirectory: project,
199
+ options: { ...lead(mode).options, env: IDENTITY },
200
+ leadTerminalLauncher: launcher,
201
+ onLeadStarted: started,
202
+ });
203
+ expect(result.status).toBe('running');
204
+ expect(result.leadTerminal?.terminalHandle).toBe('term_lead');
205
+ expect(result.leadTempDir).toBeTruthy();
206
+ expect(launcher).toHaveBeenCalledOnce();
207
+ expect(started).toHaveBeenCalledWith(12345);
208
+ const refusal = new OrcaExecutionError(
209
+ 'E_ORCA_CONTEXT',
210
+ 'The owner terminal was refused.',
211
+ 'Restore the owner channel.',
212
+ null,
213
+ {
214
+ runtimeId: 'runtime-fixture',
215
+ terminalHandle: 'term_lead',
216
+ expectedTerminalPid: 354,
217
+ observedSupervisorPid: 365,
218
+ observedParentPid: 353,
219
+ },
220
+ );
221
+ launcher.mockRejectedValueOnce(refusal);
222
+ await expect(
223
+ new ClaudeCodeSpawnProvider().spawn({
224
+ ...lead(mode),
225
+ workingDirectory: project,
226
+ options: { ...lead(mode).options, env: IDENTITY },
227
+ leadTerminalLauncher: launcher,
228
+ onLeadStarted: started,
229
+ }),
230
+ ).rejects.toBe(refusal);
231
+ const refusedDir = launcher.mock.calls.at(-1)?.[0].tempDir;
232
+ expect(refusedDir).toBeTruthy();
233
+ expect(existsSync(refusedDir ?? '')).toBe(false);
234
+ // Separately bundled entrypoints carry the same fields with a different constructor.
235
+ class BundledOrcaExecutionError extends Error {}
236
+ const bundledRefusal = Object.assign(
237
+ new BundledOrcaExecutionError(refusal.message),
238
+ refusal,
239
+ );
240
+ expect(bundledRefusal).not.toBeInstanceOf(OrcaExecutionError);
241
+ launcher.mockRejectedValueOnce(bundledRefusal);
242
+ await expect(
243
+ new ClaudeCodeSpawnProvider().spawn({
244
+ ...lead(mode),
245
+ workingDirectory: project,
246
+ options: { ...lead(mode).options, env: IDENTITY },
247
+ leadTerminalLauncher: launcher,
248
+ onLeadStarted: started,
249
+ }),
250
+ ).rejects.toBe(bundledRefusal);
251
+ expect(bundledRefusal.details).toEqual(refusal.details);
252
+ launcher.mockRejectedValueOnce(new Error('Terminal preparation failed.'));
253
+ await expect(
254
+ new ClaudeCodeSpawnProvider().spawn({
255
+ ...lead(mode),
256
+ workingDirectory: project,
257
+ options: { ...lead(mode).options, env: IDENTITY },
258
+ leadTerminalLauncher: launcher,
259
+ onLeadStarted: started,
260
+ }),
261
+ ).rejects.toMatchObject({
262
+ code: 'E_LEAD_TOOLS_UNSTRIPPED',
263
+ message: 'Terminal preparation failed.',
264
+ exitCode: 63,
265
+ fix: expect.stringContaining('keep orchestrate.leadWorker.v1 enabled'),
266
+ });
267
+ } finally {
268
+ if (promptFile) rmSync(join(promptFile, '..'), { recursive: true, force: true });
269
+ }
270
+ },
271
+ );
272
+
150
273
  it.each([
151
274
  [false, true],
152
275
  [true, false],
@@ -26,6 +26,7 @@ import type {
26
26
  import { getErrorMessage } from '@cleocode/contracts';
27
27
  import { E_LEAD_NO_OWNER_CHANNEL } from '@cleocode/contracts/operations/orchestrate.js';
28
28
  import { findOnPath } from '@cleocode/paths';
29
+ import { OrcaExecutionError } from '../../orca-execution.js';
29
30
  import { buildAgentSpawnArgs } from '../shared/agent-spawn-wrapper.js';
30
31
  import { leadDeniedTools } from '../shared/lead-tool-strip.js';
31
32
  import { removeSpawnPromptFile, writeSpawnPromptFile } from '../shared/prompt-file.js';
@@ -247,6 +248,34 @@ export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
247
248
  leadMcp: leadMcp.report,
248
249
  };
249
250
  }
251
+ if (context.leadTerminalLauncher) {
252
+ const command = resolveAbsoluteBinary('claude');
253
+ if (!command || !context.onLeadStarted) {
254
+ throw new Error(
255
+ 'The guarded Orca lead needs an absolute claude binary and a lifecycle recorder.',
256
+ );
257
+ }
258
+ const terminal = await context.leadTerminalLauncher(
259
+ {
260
+ command,
261
+ args: buildClaudeArgs(context, tmpFile, settingsArgs, leadMcp),
262
+ cwd: context.workingDirectory ?? process.cwd(),
263
+ tempDir: dir,
264
+ env: envStrings(context.options),
265
+ },
266
+ context.onLeadStarted,
267
+ );
268
+ return {
269
+ instanceId,
270
+ taskId: context.taskId,
271
+ providerId: 'claude-code',
272
+ status: 'running',
273
+ startTime,
274
+ leadMcp: leadMcp.report,
275
+ leadTempDir: dir,
276
+ leadTerminal: terminal,
277
+ };
278
+ }
250
279
  if (leadModeOf(context.options) === 'interactive') {
251
280
  // T14363: the owner's terminal — stdio inherited, awaited, not detached.
252
281
  const env = envStrings(context.options);
@@ -354,12 +383,28 @@ export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
354
383
  ...(leadMcp ? { leadMcp: leadMcp.report, leadTempDir: dirname(tmpFile) } : {}),
355
384
  };
356
385
  } catch (error) {
357
- // Log spawn failure for debugging
358
- console.error(`[ClaudeCodeSpawnProvider] Failed to spawn: ${getErrorMessage(error)}`);
359
-
360
386
  if (tmpFile) {
361
387
  await removeSpawnPromptFile(tmpFile);
362
388
  }
389
+ if (context.leadTerminalLauncher) {
390
+ // Public adapter entries are bundled separately, so constructor identity is not shared.
391
+ if (
392
+ typeof error === 'object' &&
393
+ error !== null &&
394
+ 'code' in error &&
395
+ typeof error.code === 'string' &&
396
+ 'fix' in error &&
397
+ typeof error.fix === 'string'
398
+ )
399
+ throw error;
400
+ throw new OrcaExecutionError(
401
+ 'E_LEAD_TOOLS_UNSTRIPPED',
402
+ getErrorMessage(error),
403
+ 'Inspect the guarded Orca terminal setup and use --adapter claude-code; keep orchestrate.leadWorker.v1 enabled.',
404
+ );
405
+ }
406
+ // Log spawn failure for debugging
407
+ console.error(`[ClaudeCodeSpawnProvider] Failed to spawn: ${getErrorMessage(error)}`);
363
408
 
364
409
  return {
365
410
  instanceId,