@cleocode/adapters 2026.11.3 → 2026.11.4-canary.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cleocode/adapters",
3
- "version": "2026.11.3",
3
+ "version": "2026.11.4-canary.1",
4
4
  "description": "Unified provider adapters for CLEO (Claude Code, OpenCode, Cursor)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -35,9 +35,9 @@
35
35
  "@ai-sdk/anthropic": "^3.0.69",
36
36
  "@ai-sdk/openai": "^2.0.53",
37
37
  "ai": "^6.0.168",
38
- "@cleocode/caamp": "2026.11.3",
39
- "@cleocode/contracts": "2026.11.3",
40
- "@cleocode/paths": "2026.11.3"
38
+ "@cleocode/caamp": "2026.11.4-canary.1",
39
+ "@cleocode/contracts": "2026.11.4-canary.1",
40
+ "@cleocode/paths": "2026.11.4-canary.1"
41
41
  },
42
42
  "license": "MIT",
43
43
  "engines": {
@@ -50,8 +50,8 @@
50
50
  "devDependencies": {
51
51
  "@types/node": "^24.3.0",
52
52
  "vitest": "^4.1.4",
53
- "@cleocode/core": "2026.11.3",
54
- "@cleocode/playbooks": "2026.11.3"
53
+ "@cleocode/core": "2026.11.4-canary.1",
54
+ "@cleocode/playbooks": "2026.11.4-canary.1"
55
55
  },
56
56
  "repository": {
57
57
  "type": "git",
@@ -21,8 +21,14 @@ import {
21
21
  runOrcaFixture,
22
22
  } from './orca-execution-fixture.js';
23
23
 
24
+ vi.mock('node:fs/promises', async (importOriginal) => {
25
+ const actual = await importOriginal<typeof import('node:fs/promises')>();
26
+ return { ...actual, rm: vi.fn(actual.rm) };
27
+ });
28
+
24
29
  describe('Orca execution process boundary', () => {
25
30
  beforeEach(() => {
31
+ vi.mocked(rm).mockClear();
26
32
  fixtureRunner.mockReset().mockImplementation(runOrcaFixture);
27
33
  orcaFixture.launch = { ...fixtureLaunch };
28
34
  orcaFixture.start = fixtureStart();
@@ -353,6 +359,7 @@ describe('Orca execution process boundary', () => {
353
359
  .skipIf(process.platform === 'win32')
354
360
  .each([
355
361
  'ready',
362
+ 'create-before-start',
356
363
  'login-wrapper',
357
364
  'ps-from-path',
358
365
  'ps-fallback',
@@ -363,16 +370,24 @@ describe('Orca execution process boundary', () => {
363
370
  'background',
364
371
  'hidden-after-create',
365
372
  'cleanup-unverified',
373
+ 'cleanup-race',
374
+ 'cleanup-race-persistent',
375
+ 'cleanup-both-failed',
366
376
  'not-navigated',
367
377
  'pid-mismatch',
368
378
  'missing-terminal-pid',
369
379
  'recorder-failed',
370
380
  'wrong-runtime',
371
381
  'lost-receipt',
382
+ 'lost-receipt-before-start',
383
+ 'lost-receipt-race',
372
384
  ] as const)(
373
385
  'gates the exact terminal argv before a model turn: %s (inert executable only)',
386
+ { repeats: 2 },
374
387
  async (condition) => {
375
388
  vi.stubEnv('ORCA_TERMINAL_HANDLE', fixtureContext.coordinatorHandle);
389
+ // The terminal's inherited environment holds a trust variable the launch unsets (T14515).
390
+ vi.stubEnv('CLAUDE_CODE_SANDBOXED', '1');
376
391
  const root = mkdtempSync(join(tmpdir(), 'orca-lead-fixture-'));
377
392
  const cwd = join(root, "project ' `literal` $(literal)");
378
393
  mkdirSync(cwd);
@@ -405,7 +420,7 @@ else {
405
420
  const binary = join(root, 'claude');
406
421
  writeFileSync(
407
422
  binary,
408
- `#!${process.execPath}\nimport {writeFileSync} from 'node:fs';\nwriteFileSync(${JSON.stringify(capture)}, JSON.stringify({args:process.argv.slice(2),session:process.env.CLEO_SESSION_ID,role:process.env.CLEO_AGENT_ROLE,cwd:process.cwd()}));\n`,
423
+ `#!${process.execPath}\nimport {writeFileSync} from 'node:fs';\nwriteFileSync(${JSON.stringify(capture)}, JSON.stringify({args:process.argv.slice(2),session:process.env.CLEO_SESSION_ID,role:process.env.CLEO_AGENT_ROLE,sandboxed:process.env.CLAUDE_CODE_SANDBOXED??null,cwd:process.cwd()}));\n`,
409
424
  { mode: 0o700 },
410
425
  );
411
426
  const args = [
@@ -416,6 +431,13 @@ else {
416
431
  ];
417
432
  let child: ChildProcess | undefined;
418
433
  let exit: Promise<void> | undefined;
434
+ let startupDir = '';
435
+ let cleanupAttempts = 0;
436
+ let closedBeforeCleanup = false;
437
+ const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
438
+ const cleanupRace = condition.includes('race') || condition === 'cleanup-both-failed';
439
+ const persistentCleanupRace =
440
+ condition === 'cleanup-race-persistent' || condition === 'cleanup-both-failed';
419
441
  const started = vi.fn<(pid: number, terminal?: OrcaLeadTerminal) => Promise<void>>(
420
442
  async () => {
421
443
  await new Promise((resolve) => setTimeout(resolve, 250));
@@ -431,18 +453,51 @@ else {
431
453
  });
432
454
  if (argv[0] === 'terminal' && argv[1] === 'create') {
433
455
  const command = argv[argv.indexOf('--command') + 1];
456
+ const directory = readdirSync(root).find((name) => name.startsWith('orca-terminal-'));
457
+ if (!directory) throw new Error('Missing guarded launch directory');
458
+ startupDir = join(root, directory);
459
+ const startup =
460
+ condition === 'lost-receipt' || condition === 'lost-receipt-race'
461
+ ? watch(startupDir)
462
+ : undefined;
463
+ const pidWritten = startup ? once(startup, 'change') : undefined;
464
+ const startsLate =
465
+ condition === 'lost-receipt-before-start' || condition === 'create-before-start';
434
466
  child = spawn(
435
467
  '/bin/sh',
436
468
  [
437
469
  '-c',
438
- condition === 'login-wrapper' || condition === 'ps-newer-parent'
439
- ? `${command} & wait`
440
- : (command ?? 'exit 99'),
470
+ startsLate
471
+ ? `read -r release; ${command}`
472
+ : condition === 'login-wrapper' || condition === 'ps-newer-parent'
473
+ ? `${command} & wait`
474
+ : (command ?? 'exit 99'),
441
475
  ],
442
- { stdio: 'ignore' },
476
+ {
477
+ stdio: [startsLate ? 'pipe' : 'ignore', 'ignore', 'ignore'],
478
+ },
443
479
  );
444
- exit = new Promise<void>((resolve) => child?.once('exit', () => resolve()));
445
- if (condition === 'lost-receipt') return { stdout: '', stderr: 'lost', exitCode: null };
480
+ exit = new Promise<void>((resolve, reject) =>
481
+ child?.once('exit', () => resolve()).once('error', reject),
482
+ );
483
+ try {
484
+ // Explicit after-start receipt loss must leave an already looping shell unowned.
485
+ if (pidWritten)
486
+ await Promise.race([
487
+ pidWritten,
488
+ exit.then(() => {
489
+ throw new Error('Guarded shell exited before publishing its PID');
490
+ }),
491
+ ]);
492
+ } finally {
493
+ startup?.close();
494
+ }
495
+ if (condition === 'create-before-start') {
496
+ expect(existsSync(join(startupDir, 'pid'))).toBe(false);
497
+ setImmediate(() => child?.stdin?.end('\n'));
498
+ }
499
+ if (condition.startsWith('lost-receipt'))
500
+ return { stdout: '', stderr: 'lost', exitCode: null };
446
501
  return fixtureReply({
447
502
  terminal: {
448
503
  handle: 'term_lead',
@@ -461,14 +516,21 @@ else {
461
516
  executionHostId: 'local',
462
517
  incarnationId: 'incarnation-lead',
463
518
  hostPlatform: process.platform,
464
- surface: condition === 'background' ? 'background' : 'visible',
519
+ surface:
520
+ condition === 'background' || condition.startsWith('cleanup-race')
521
+ ? 'background'
522
+ : 'visible',
465
523
  },
466
524
  });
467
525
  }
468
526
  if (argv[0] === 'terminal' && argv[1] === 'close') {
469
527
  child?.kill('SIGTERM');
528
+ await exit;
470
529
  return fixtureReply({
471
- close: { handle: 'term_lead', ptyKilled: condition !== 'cleanup-unverified' },
530
+ close: {
531
+ handle: 'term_lead',
532
+ ptyKilled: condition !== 'cleanup-unverified' && condition !== 'cleanup-both-failed',
533
+ },
472
534
  });
473
535
  }
474
536
  if (argv[0] === 'terminal' && argv[1] === 'switch') {
@@ -486,7 +548,10 @@ else {
486
548
  terminal: {
487
549
  handle: 'term_lead',
488
550
  connected: true,
489
- writable: condition !== 'disconnected' && condition !== 'cleanup-unverified',
551
+ writable:
552
+ condition !== 'disconnected' &&
553
+ condition !== 'cleanup-unverified' &&
554
+ condition !== 'cleanup-both-failed',
490
555
  executionHostId: 'local',
491
556
  worktreePath: cwd,
492
557
  tabId: 'tab-lead',
@@ -500,6 +565,22 @@ else {
500
565
  return runOrcaFixture(...params);
501
566
  });
502
567
  try {
568
+ if (cleanupRace)
569
+ vi.mocked(rm).mockImplementation(async (path, options) => {
570
+ expect(path).toBe(startupDir);
571
+ if (cleanupAttempts === 0)
572
+ closedBeforeCleanup = fixtureRunner.mock.calls.some(
573
+ ([, argv]) => argv[1] === 'close',
574
+ );
575
+ cleanupAttempts++;
576
+ if (cleanupAttempts > 1 && !persistentCleanupRace) return actualFs.rm(path, options);
577
+ // Force rimraf's enumerate -> late PID write -> rmdir interleaving with real I/O.
578
+ await actualFs.mkdir(startupDir, { recursive: true });
579
+ for (const name of await actualFs.readdir(startupDir))
580
+ await actualFs.rm(join(startupDir, name), { recursive: true, force: true });
581
+ await actualFs.writeFile(join(startupDir, 'pid'), 'late writer');
582
+ await actualFs.rmdir(startupDir);
583
+ });
503
584
  const result = new OrcaExecutionBackend(fixtureRunner).startLead(
504
585
  {
505
586
  command: binary,
@@ -511,12 +592,35 @@ else {
511
592
  CLEO_AGENT_ID: 'agent-own',
512
593
  CLEO_AGENT_ROLE: 'lead',
513
594
  },
595
+ unsetEnv: ['CLAUDE_CODE_SANDBOXED'],
514
596
  },
515
597
  started,
516
598
  );
517
- const ready = ['ready', 'login-wrapper', 'ps-from-path', 'ps-fallback'].includes(condition);
599
+ const ready = [
600
+ 'ready',
601
+ 'create-before-start',
602
+ 'login-wrapper',
603
+ 'ps-from-path',
604
+ 'ps-fallback',
605
+ ].includes(condition);
518
606
  if (!ready) {
519
607
  await expect(result).rejects.toThrow();
608
+ if (cleanupRace) {
609
+ await expect(result).rejects.toMatchObject({
610
+ code: condition.startsWith('lost-receipt')
611
+ ? 'E_ORCA_RECEIPT'
612
+ : 'E_LEAD_TOOLS_UNSTRIPPED',
613
+ });
614
+ expect(closedBeforeCleanup).toBe(!condition.startsWith('lost-receipt'));
615
+ expect(cleanupAttempts).toBe(persistentCleanupRace ? 3 : 2);
616
+ expect(existsSync(startupDir)).toBe(persistentCleanupRace);
617
+ }
618
+ if (persistentCleanupRace)
619
+ await expect(result).rejects.toMatchObject({
620
+ message: expect.stringMatching(
621
+ /startup directory.*cleanup is unverified:.*ENOTEMPTY/,
622
+ ),
623
+ });
520
624
  if (condition === 'pid-mismatch')
521
625
  await expect(result).rejects.toMatchObject({
522
626
  details: {
@@ -526,7 +630,7 @@ else {
526
630
  observedParentPid: process.pid,
527
631
  },
528
632
  });
529
- if (condition === 'cleanup-unverified')
633
+ if (condition === 'cleanup-unverified' || condition === 'cleanup-both-failed')
530
634
  await expect(result).rejects.toMatchObject({
531
635
  code: 'E_LEAD_TOOLS_UNSTRIPPED',
532
636
  message: expect.stringContaining('cleanup is unverified'),
@@ -556,6 +660,7 @@ else {
556
660
  args,
557
661
  session: 'ses_own',
558
662
  role: 'lead',
663
+ sandboxed: null,
559
664
  cwd,
560
665
  });
561
666
  expect(existsSync(join(cwd, 'injected'))).toBe(false);
@@ -573,11 +678,17 @@ else {
573
678
  ).toBe(false);
574
679
  expect(fixtureRunner.mock.calls.filter(([, argv]) => argv[1] === 'create')).toHaveLength(1);
575
680
  expect(fixtureRunner.mock.calls.filter(([, argv]) => argv[1] === 'close')).toHaveLength(
576
- ready || condition === 'lost-receipt' ? 0 : 1,
681
+ ready || condition.startsWith('lost-receipt') ? 0 : 1,
577
682
  );
578
- if (condition === 'lost-receipt')
579
- await expect.poll(() => child?.exitCode, { timeout: 1500 }).toBeTypeOf('number');
683
+ if (condition.startsWith('lost-receipt')) {
684
+ if (condition === 'lost-receipt-before-start') child?.stdin?.end('\n');
685
+ await exit;
686
+ expect(child?.exitCode).toBeTypeOf('number');
687
+ expect(child?.exitCode).not.toBe(0);
688
+ expect(existsSync(capture)).toBe(false);
689
+ }
580
690
  } finally {
691
+ vi.mocked(rm).mockImplementation(actualFs.rm);
581
692
  child?.kill('SIGTERM');
582
693
  await exit;
583
694
  rmSync(root, { recursive: true, force: true });
@@ -1791,14 +1902,18 @@ else {
1791
1902
  });
1792
1903
 
1793
1904
  import { type ChildProcess, spawn } from 'node:child_process';
1905
+ import { once } from 'node:events';
1794
1906
  import {
1795
1907
  existsSync,
1796
1908
  mkdirSync,
1797
1909
  mkdtempSync,
1910
+ readdirSync,
1798
1911
  readFileSync,
1799
1912
  rmSync,
1800
1913
  symlinkSync,
1914
+ watch,
1801
1915
  writeFileSync,
1802
1916
  } from 'node:fs';
1917
+ import { rm } from 'node:fs/promises';
1803
1918
  import { tmpdir } from 'node:os';
1804
1919
  import { join } from 'node:path';
@@ -269,6 +269,7 @@ export class OrcaExecutionBackend implements OrcaRoutingAdapter {
269
269
  * Host Claude Code's prepared guard argv in a local Orca terminal. The shell
270
270
  * waits for a private release file, so a missing receipt, wrong runtime or
271
271
  * disconnected owner terminal cannot start a model turn. Never retry create.
272
+ * Refusals close a known terminal before bounded cleanup and retain their original code.
272
273
  * @param launch - The provider's guarded command and private startup directory.
273
274
  * @param onStarted - Persists the terminal and PID before any model turn is allowed.
274
275
  * @returns The verified terminal handle and provider PID.
@@ -359,7 +360,8 @@ export class OrcaExecutionBackend implements OrcaRoutingAdapter {
359
360
  }
360
361
 
361
362
  const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
362
- for (const key of Object.keys(launch.env)) {
363
+ const unsetEnv = launch.unsetEnv ?? [];
364
+ for (const key of [...Object.keys(launch.env), ...unsetEnv]) {
363
365
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw refuse('Invalid lead environment key.');
364
366
  }
365
367
  const dir = await mkdtemp(join(launch.tempDir, 'orca-terminal-'));
@@ -382,6 +384,7 @@ export class OrcaExecutionBackend implements OrcaRoutingAdapter {
382
384
  ' sleep 0.1',
383
385
  'done',
384
386
  `cd ${quote(launch.cwd)} || exit 1`,
387
+ ...unsetEnv.map((key) => `unset ${key}`),
385
388
  ...Object.entries(launch.env).map(([key, value]) => `export ${quote(`${key}=${value}`)}`),
386
389
  `exec ${[launch.command, ...launch.args].map(quote).join(' ')}`,
387
390
  '',
@@ -516,7 +519,7 @@ export class OrcaExecutionBackend implements OrcaRoutingAdapter {
516
519
  await rename(`${release}.tmp`, release);
517
520
  return started;
518
521
  } catch (error) {
519
- await rm(dir, { recursive: true, force: true });
522
+ const cleanupFailures: string[] = [];
520
523
  if (terminalHandle) {
521
524
  try {
522
525
  await this.verifyRuntime(launch.cwd, context);
@@ -530,15 +533,38 @@ export class OrcaExecutionBackend implements OrcaRoutingAdapter {
530
533
  if (closed?.handle !== terminalHandle || !closed.ptyKilled)
531
534
  throw refuse('Orca did not prove terminal cleanup.');
532
535
  } 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,
536
+ cleanupFailures.push(
537
+ `terminal ${terminalHandle} cleanup is unverified: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
539
538
  );
540
539
  }
541
540
  }
541
+ // A lost receipt leaves an unowned shell that can publish its PID during removal.
542
+ for (let attempt = 0; attempt < 3; attempt++) {
543
+ try {
544
+ await rm(dir, { recursive: true, force: true });
545
+ break;
546
+ } catch (cleanupError) {
547
+ if (
548
+ attempt < 2 &&
549
+ cleanupError instanceof Error &&
550
+ 'code' in cleanupError &&
551
+ cleanupError.code === 'ENOTEMPTY'
552
+ )
553
+ continue;
554
+ cleanupFailures.push(
555
+ `startup directory ${dir} cleanup is unverified: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
556
+ );
557
+ break;
558
+ }
559
+ }
560
+ if (cleanupFailures.length > 0)
561
+ throw new OrcaExecutionError(
562
+ error instanceof OrcaExecutionError ? error.code : ORCA_LEAD_LAUNCH_REFUSAL.code,
563
+ `${error instanceof Error ? error.message : String(error)}; ${cleanupFailures.join('; ')}`,
564
+ `${error instanceof OrcaExecutionError ? error.fix : 'Restore the guarded terminal transport.'} ${terminalHandle ? `Inspect orca terminal show --terminal ${terminalHandle} before closing that exact terminal. ` : ''}Inspect the private startup directory ${dir} before removing it.`,
565
+ error instanceof OrcaExecutionError ? error.receipt : null,
566
+ error instanceof OrcaExecutionError ? (error.details ?? diagnostic) : diagnostic,
567
+ );
542
568
  throw error;
543
569
  }
544
570
  }