@cleocode/adapters 2026.10.27 → 2026.11.1-canary.10

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 +2676 -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 +89 -0
  10. package/dist/orca-execution.d.ts.map +1 -0
  11. package/dist/orca-execution.js +794 -0
  12. package/dist/orca-execution.js.map +6 -0
  13. package/dist/providers/claude-code/index.js +46710 -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 +44549 -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 +19315 -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 +18877 -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 +18806 -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 +44190 -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 +19317 -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 +18453 -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 +380 -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 +1136 -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,241 @@
1
+ /**
2
+ * The no-hands lead's Claude Code session (T14363): argv for both modes, the
3
+ * session hooks, and the interactive run.
4
+ *
5
+ * - `interactive` (default): no `--print`; the lead opens in the caller's
6
+ * terminal (stdio inherited, not detached) and asks the owner with
7
+ * `AskUserQuestion`, its only built-in tool.
8
+ * - `detached`: `--print`, no built-in tool at all; owner decisions go to the
9
+ * owner's AgentMBX mailbox (the prompt says how).
10
+ *
11
+ * In both, tools are an allow list (T14423): only the runner, mbx and (when
12
+ * interactive) `AskUserQuestion`; Manual mode for interactive owner answers,
13
+ * `dontAsk` for detached runs, no settings sources, and denied tools as a second layer.
14
+ *
15
+ * `cleo` and `agentmbx` in hooks and the runner entry are absolute paths
16
+ * resolved at spawn time from the absolute entries of PATH, never relative
17
+ * entries that would resolve inside the project.
18
+ *
19
+ * @task T14363
20
+ * @epic T14351
21
+ */
22
+
23
+ import { spawn as nodeSpawn } from 'node:child_process';
24
+ import { isAbsolute } from 'node:path';
25
+ import type { LeadMode, SpawnContext } from '@cleocode/contracts';
26
+ import {
27
+ E_LEAD_NO_OWNER_CHANNEL,
28
+ LEAD_ASK_TOOL,
29
+ } from '@cleocode/contracts/operations/orchestrate.js';
30
+ import { findOnPath, pathDelimiterFor, pathEnvKey, splitPathEnv } from '@cleocode/paths';
31
+ import { type LeadMcpSetup, leadAllowedTools } from './lead-mcp.js';
32
+
33
+ /** The first user turn of a lead: its instructions are the appended system prompt. */
34
+ export const LEAD_KICKOFF_PROMPT =
35
+ 'You are the no-hands lead. Your full instructions are in your system prompt: follow them, using only your allowed tools.';
36
+
37
+ /**
38
+ * The lead's pre-assigned provider session id (`options.leadSessionId`), when it
39
+ * is a UUID; `undefined` otherwise.
40
+ *
41
+ * @param options - Spawn context options.
42
+ * @returns The session id, or undefined.
43
+ * @task T14363
44
+ */
45
+ export function leadSessionId(options: SpawnContext['options']): string | undefined {
46
+ const id = options?.leadSessionId;
47
+ return typeof id === 'string' &&
48
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)
49
+ ? id
50
+ : undefined;
51
+ }
52
+
53
+ /**
54
+ * The lead's mode (`options.leadMode`); anything but `detached` is interactive.
55
+ *
56
+ * @param options - Spawn context options.
57
+ * @returns The mode.
58
+ * @task T14363
59
+ */
60
+ export function leadModeOf(options: SpawnContext['options']): LeadMode {
61
+ return options?.leadMode === 'detached' ? 'detached' : 'interactive';
62
+ }
63
+
64
+ /**
65
+ * Resolve a binary to an absolute path from the ABSOLUTE entries of PATH only,
66
+ * so a relative entry (`.`, `node_modules/.bin`) can never pick a binary out
67
+ * of the project the lead runs in.
68
+ *
69
+ * @param name - Binary name, e.g. `cleo`.
70
+ * @param env - Environment. @defaultValue `process.env`
71
+ * @returns The absolute path, or `null` when not found.
72
+ * @task T14363
73
+ */
74
+ export function resolveAbsoluteBinary(
75
+ name: string,
76
+ env: NodeJS.ProcessEnv = process.env,
77
+ ): string | null {
78
+ const key = pathEnvKey(env);
79
+ const absolute = splitPathEnv(env[key]).filter((dir) => isAbsolute(dir));
80
+ return findOnPath(name, { env: { ...env, [key]: absolute.join(pathDelimiterFor()) } });
81
+ }
82
+
83
+ /** Single-quote a value for a hook's shell command; refuses one holding a quote. */
84
+ function shellQuote(value: string): string {
85
+ if (value.includes("'")) throw new Error(`refusing a hook argument with a quote: ${value}`);
86
+ return `'${value}'`;
87
+ }
88
+
89
+ /** Absolute binaries the lead's hooks call; `null` when not found. */
90
+ export interface LeadBinaries {
91
+ readonly cleo: string | null;
92
+ readonly agentmbx: string | null;
93
+ }
94
+
95
+ /**
96
+ * Claude Code settings for a lead, passed with `--settings` (which still
97
+ * applies under `--setting-sources ""`):
98
+ *
99
+ * - `SessionStart` deletes the MCP config file: Claude Code has read it, and
100
+ * it may hold the mbx server's env secrets.
101
+ * - `SessionEnd` removes the spawn's temp directory, ends the lead's CLEO
102
+ * session (releasing its epic claim) and releases the lead mailbox held
103
+ * for this session. A lead killed before its hooks run is reaped by the
104
+ * next `cleo orchestrate lead` or `cleo orchestrate status`.
105
+ *
106
+ * @param input - Temp dir, MCP file, the lead's session id and absolute binaries.
107
+ * @returns The settings JSON.
108
+ * @task T14363
109
+ */
110
+ export function leadSessionSettings(input: {
111
+ readonly dir: string;
112
+ readonly mcpFile: string;
113
+ readonly sessionId?: string;
114
+ readonly binaries: LeadBinaries;
115
+ }): string {
116
+ const end = [`rm -rf ${shellQuote(input.dir)}`];
117
+ if (input.binaries.cleo) {
118
+ end.push(`${shellQuote(input.binaries.cleo)} session end --note 'lead exited'`);
119
+ }
120
+ if (input.binaries.agentmbx && input.sessionId !== undefined) {
121
+ end.push(
122
+ `${shellQuote(input.binaries.agentmbx)} identity release --cli claude --session ${input.sessionId} --json`,
123
+ );
124
+ }
125
+ const hook = (command: string) => [{ hooks: [{ type: 'command', command }] }];
126
+ return JSON.stringify({
127
+ hooks: {
128
+ SessionStart: hook(`rm -f ${shellQuote(input.mcpFile)}`),
129
+ SessionEnd: hook(`${end.join('; ')}; true`),
130
+ },
131
+ });
132
+ }
133
+
134
+ /**
135
+ * The lead's `claude` argv. An allow list, layered:
136
+ *
137
+ * - `--restricted --tools <built-ins>`: interactive gets `AskUserQuestion`
138
+ * only; detached gets no built-in tool at all;
139
+ * - `--mcp-config <file> --strict-mcp-config`: only the runner and a
140
+ * validated mbx; `--allowedTools` names exactly the allowed tools;
141
+ * - Manual (`default`) permission mode permits interactive owner answers;
142
+ * `dontAsk` denies them even when `AskUserQuestion` is explicitly allowed;
143
+ * - `--setting-sources ""` excludes user/project permission settings;
144
+ * - `--disallowedTools <denied>` as a second layer, excluding the retired
145
+ * `MultiEdit` name (already absent under `--tools`).
146
+ *
147
+ * Interactive drops `--print` and `--output-format`; detached keeps both.
148
+ * The prompt file is the appended system prompt (the lead cannot Read
149
+ * files); the user turn is {@link LEAD_KICKOFF_PROMPT}.
150
+ *
151
+ * @param input - Mode, denied tools, MCP setup, prompt file, session id, extra settings args.
152
+ * @returns Argument list for the `claude` binary.
153
+ * @task T14363
154
+ */
155
+ export function buildLeadArgs(input: {
156
+ readonly mode: LeadMode;
157
+ readonly denied: readonly string[];
158
+ readonly leadMcp: LeadMcpSetup;
159
+ readonly promptFile: string;
160
+ readonly sessionId?: string;
161
+ readonly settingsArgs?: readonly string[];
162
+ }): string[] {
163
+ const interactive = input.mode === 'interactive';
164
+ const allowed = [
165
+ ...leadAllowedTools(input.leadMcp.report),
166
+ ...(interactive ? [LEAD_ASK_TOOL] : []),
167
+ ];
168
+ // Variadic flags are each followed by another flag, so none swallows the kickoff prompt.
169
+ return [
170
+ ...(interactive ? [] : ['--print']),
171
+ '--restricted',
172
+ '--tools',
173
+ interactive ? LEAD_ASK_TOOL : '',
174
+ '--allowedTools',
175
+ allowed.join(','),
176
+ '--disallowedTools',
177
+ input.denied.filter((tool) => tool !== 'MultiEdit').join(','),
178
+ '--mcp-config',
179
+ input.leadMcp.config,
180
+ '--strict-mcp-config',
181
+ '--permission-mode',
182
+ interactive ? 'default' : 'dontAsk',
183
+ '--setting-sources',
184
+ '',
185
+ ...(input.sessionId !== undefined ? ['--session-id', input.sessionId] : []),
186
+ ...(input.settingsArgs ?? []),
187
+ '--append-system-prompt-file',
188
+ input.promptFile,
189
+ ...(interactive ? [] : ['--output-format', 'json']),
190
+ LEAD_KICKOFF_PROMPT,
191
+ ];
192
+ }
193
+
194
+ /** Outcome of {@link runInteractiveLead}. */
195
+ export interface InteractiveLeadExit {
196
+ /** The lead's pid while it ran. */
197
+ readonly pid: number | undefined;
198
+ /** Exit code; `null` when killed by a signal. */
199
+ readonly exitCode: number | null;
200
+ }
201
+
202
+ /**
203
+ * Run an interactive lead in the caller's terminal: stdio inherited, not
204
+ * detached, awaited until the owner ends the session.
205
+ *
206
+ * @param command - The `claude` binary.
207
+ * @param args - From {@link buildLeadArgs} with mode `interactive`.
208
+ * @param opts - Working directory, environment and a started-pid callback.
209
+ * @returns The pid and exit code once the session ends.
210
+ * @throws When stdin or stdout is not a terminal; use `--detached` instead.
211
+ * @task T14363
212
+ */
213
+ export function runInteractiveLead(
214
+ command: string,
215
+ args: readonly string[],
216
+ opts: {
217
+ readonly cwd?: string;
218
+ readonly env?: NodeJS.ProcessEnv;
219
+ /** Called with the lead's pid once it started (the lead record names it). */
220
+ readonly onStart?: (pid: number) => void;
221
+ },
222
+ ): Promise<InteractiveLeadExit> {
223
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
224
+ return Promise.reject(
225
+ new Error(
226
+ `${E_LEAD_NO_OWNER_CHANNEL}: interactive AskUserQuestion needs terminal stdin and stdout; use --detached with --adapter claude-code and a configured mbx MCP server`,
227
+ ),
228
+ );
229
+ }
230
+ return new Promise((resolve, reject) => {
231
+ const child = nodeSpawn(command, [...args], {
232
+ stdio: 'inherit',
233
+ detached: false,
234
+ ...(opts.cwd ? { cwd: opts.cwd } : {}),
235
+ ...(opts.env ? { env: opts.env } : {}),
236
+ });
237
+ child.once('error', reject);
238
+ if (child.pid !== undefined) opts.onStart?.(child.pid);
239
+ child.once('exit', (code) => resolve({ pid: child.pid, exitCode: code }));
240
+ });
241
+ }
@@ -11,9 +11,12 @@
11
11
  *
12
12
  * @task T5240
13
13
  * @task T11998 — per-session scope/pgid suite containment
14
+ * @task T14357 — lead spawns strip denied tools via --disallowedTools
14
15
  */
15
16
 
16
17
  import { spawn as nodeSpawn } from 'node:child_process';
18
+ import { writeFile } from 'node:fs/promises';
19
+ import { dirname, join } from 'node:path';
17
20
  import type {
18
21
  AdapterSpawnProvider,
19
22
  AgentSuiteOwnership,
@@ -21,11 +24,56 @@ import type {
21
24
  SpawnResult,
22
25
  } from '@cleocode/contracts';
23
26
  import { getErrorMessage } from '@cleocode/contracts';
27
+ import { E_LEAD_NO_OWNER_CHANNEL } from '@cleocode/contracts/operations/orchestrate.js';
24
28
  import { findOnPath } from '@cleocode/paths';
25
29
  import { buildAgentSpawnArgs } from '../shared/agent-spawn-wrapper.js';
30
+ import { leadDeniedTools } from '../shared/lead-tool-strip.js';
26
31
  import { removeSpawnPromptFile, writeSpawnPromptFile } from '../shared/prompt-file.js';
32
+ import { type LeadMcpSetup, prepareLeadMcp, runnerOnlyLeadMcp } from './lead-mcp.js';
33
+ import {
34
+ buildLeadArgs,
35
+ leadModeOf,
36
+ leadSessionId,
37
+ leadSessionSettings,
38
+ resolveAbsoluteBinary,
39
+ runInteractiveLead,
40
+ } from './lead-session.js';
27
41
  import { reapAgentSuite } from './suite-reaper.js';
28
42
 
43
+ /**
44
+ * Instance id CLEO pre-assigned to a tracked worker (`options.workerInstanceId`,
45
+ * set only under `orchestrate.leadWorker.v1`), when it is shell-safe.
46
+ *
47
+ * @param options - Spawn context options.
48
+ * @returns The id, or undefined when the spawn is not tracked.
49
+ */
50
+ export function trackedWorkerInstanceId(options: SpawnContext['options']): string | undefined {
51
+ const id = options?.workerInstanceId;
52
+ return typeof id === 'string' && /^[A-Za-z0-9-]+$/.test(id) ? id : undefined;
53
+ }
54
+
55
+ /**
56
+ * Claude Code settings that make a spawned worker report its own exit: a
57
+ * `SessionEnd` hook running `cleo orchestrate worker-exit` for this instance,
58
+ * which closes the worker record and fires SubagentStop once (T14359).
59
+ *
60
+ * @param instanceId - Spawn instance id the worker record is keyed by.
61
+ * @returns The settings JSON passed to `claude --settings`.
62
+ */
63
+ export function workerExitSettings(instanceId: string): string {
64
+ const command = `cleo orchestrate worker-exit --instance ${instanceId}`;
65
+ return JSON.stringify({ hooks: { SessionEnd: [{ hooks: [{ type: 'command', command }] }] } });
66
+ }
67
+
68
+ /** The string-valued entries of `options.env`. */
69
+ function envStrings(options: SpawnContext['options']): Record<string, string> {
70
+ const env = options?.env;
71
+ const out: Record<string, string> = {};
72
+ if (typeof env !== 'object' || env === null) return out;
73
+ for (const [key, value] of Object.entries(env)) if (typeof value === 'string') out[key] = value;
74
+ return out;
75
+ }
76
+
29
77
  /** Internal tracking entry for a spawned process. */
30
78
  interface TrackedProcess {
31
79
  pid: number;
@@ -35,6 +83,51 @@ interface TrackedProcess {
35
83
  ownership: AgentSuiteOwnership;
36
84
  }
37
85
 
86
+ /**
87
+ * Build the `claude` CLI argv for a spawn.
88
+ *
89
+ * - `--print`: non-interactive batch mode (process prompt, output response, exit)
90
+ * - `--output-format json`: structured output for parsing
91
+ * - Worker: `--dangerously-skip-permissions` allows every tool call without approval.
92
+ * - Lead (`context.leadDeniedTools` set): an allow list built by
93
+ * `buildLeadArgs` (lead-session.ts) for the lead's mode, interactive or
94
+ * detached (T14363, T14423).
95
+ *
96
+ * @param context - Spawn context.
97
+ * @param promptFile - Path of the prompt file passed as the final argument.
98
+ * @param settingsArgs - Extra `--settings <file>` args (a tracked worker's exit hook, T14359).
99
+ * @param leadMcp - A lead's MCP setup (from `prepareLeadMcp`). @defaultValue the runner alone, inline
100
+ * @returns Argument list for the `claude` binary.
101
+ * @task T14357
102
+ */
103
+ export function buildClaudeArgs(
104
+ context: SpawnContext,
105
+ promptFile: string,
106
+ settingsArgs: readonly string[] = [],
107
+ leadMcp: LeadMcpSetup = runnerOnlyLeadMcp(),
108
+ ): string[] {
109
+ const denied = leadDeniedTools(context);
110
+ if (denied === null) {
111
+ return [
112
+ '--print',
113
+ '--dangerously-skip-permissions',
114
+ '--output-format',
115
+ 'json',
116
+ ...settingsArgs,
117
+ promptFile,
118
+ ];
119
+ }
120
+ const sessionId = leadSessionId(context.options);
121
+ return buildLeadArgs({
122
+ mode: leadModeOf(context.options),
123
+ denied,
124
+ leadMcp,
125
+ promptFile,
126
+ ...(sessionId !== undefined ? { sessionId } : {}),
127
+ settingsArgs,
128
+ });
129
+ }
130
+
38
131
  /**
39
132
  * Spawn provider for Claude Code.
40
133
  *
@@ -51,6 +144,9 @@ interface TrackedProcess {
51
144
  * in-memory map and verified via `kill(pid, 0)` liveness checks.
52
145
  */
53
146
  export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
147
+ /** Lead spawns lose their denied tools through `--disallowedTools` (T14357). */
148
+ readonly leadToolStrip = 'enforced' as const;
149
+
54
150
  /** Map of instance IDs to tracked process info. */
55
151
  private processMap = new Map<string, TrackedProcess>();
56
152
 
@@ -73,7 +169,10 @@ export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
73
169
  * @returns Spawn result with instance ID and status
74
170
  */
75
171
  async spawn(context: SpawnContext): Promise<SpawnResult> {
76
- const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
172
+ // T14359: a tracked worker keeps the instance id its record was stored under.
173
+ const trackedId = trackedWorkerInstanceId(context.options);
174
+ const instanceId =
175
+ trackedId ?? `claude-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
77
176
  const startTime = new Date().toISOString();
78
177
  let tmpFile: string | undefined;
79
178
 
@@ -97,17 +196,84 @@ export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
97
196
  }
98
197
 
99
198
  tmpFile = await writeSpawnPromptFile('claude-spawn', enrichedPrompt);
199
+ // T14359: a tracked worker signals its own exit. SessionEnd fires once
200
+ // when the run ends; Stop fires every turn and may be blocked.
201
+ let settingsArgs: string[] = [];
202
+ if (trackedId !== undefined) {
203
+ const settingsFile = join(dirname(tmpFile), 'settings.json');
204
+ await writeFile(settingsFile, workerExitSettings(trackedId), 'utf-8');
205
+ settingsArgs = ['--settings', settingsFile];
206
+ }
100
207
 
101
- // --print: non-interactive batch mode (process prompt, output response, exit)
102
- // --dangerously-skip-permissions: allow all tool calls without human approval
103
- // --output-format json: structured output for parsing
104
- const claudeArgs = [
105
- '--print',
106
- '--dangerously-skip-permissions',
107
- '--output-format',
108
- 'json',
109
- tmpFile,
110
- ];
208
+ // T14423: a lead loads only the runner and the user's validated mbx
209
+ // server; its settings delete the MCP file at start and the temp dir at end.
210
+ let leadMcp: LeadMcpSetup | undefined;
211
+ if (leadDeniedTools(context) !== null) {
212
+ const dir = dirname(tmpFile);
213
+ // T14363: absolute binaries, resolved now from absolute PATH entries.
214
+ const binaries = {
215
+ cleo: resolveAbsoluteBinary('cleo'),
216
+ agentmbx: resolveAbsoluteBinary('agentmbx'),
217
+ };
218
+ leadMcp = await prepareLeadMcp(dir, context.workingDirectory ?? process.cwd(), {
219
+ identityEnv: envStrings(context.options),
220
+ ...(binaries.cleo ? { cleoBin: binaries.cleo } : {}),
221
+ });
222
+ const settingsFile = join(dir, 'lead-settings.json');
223
+ const sessionId = leadSessionId(context.options);
224
+ await writeFile(
225
+ settingsFile,
226
+ leadSessionSettings({
227
+ dir,
228
+ mcpFile: leadMcp.config,
229
+ binaries,
230
+ ...(sessionId !== undefined ? { sessionId } : {}),
231
+ }),
232
+ { mode: 0o600 },
233
+ );
234
+ settingsArgs = ['--settings', settingsFile];
235
+ // T14363: a detached lead's only owner channel is the mbx server. Without
236
+ // a loaded one it could never ask the owner, so it does not start.
237
+ if (leadModeOf(context.options) === 'detached' && leadMcp.report.mailbox !== 'loaded') {
238
+ await removeSpawnPromptFile(tmpFile);
239
+ return {
240
+ instanceId,
241
+ taskId: context.taskId,
242
+ providerId: 'claude-code',
243
+ status: 'failed',
244
+ startTime,
245
+ endTime: new Date().toISOString(),
246
+ error: `${E_LEAD_NO_OWNER_CHANNEL}: a detached lead needs the mbx MCP server to reach the owner (${leadMcp.report.warning ?? 'none is configured'})`,
247
+ leadMcp: leadMcp.report,
248
+ };
249
+ }
250
+ if (leadModeOf(context.options) === 'interactive') {
251
+ // T14363: the owner's terminal — stdio inherited, awaited, not detached.
252
+ const env = envStrings(context.options);
253
+ const exit = await runInteractiveLead(
254
+ 'claude',
255
+ buildClaudeArgs(context, tmpFile, settingsArgs, leadMcp),
256
+ {
257
+ ...(context.workingDirectory ? { cwd: context.workingDirectory } : {}),
258
+ ...(Object.keys(env).length > 0 ? { env: { ...process.env, ...env } } : {}),
259
+ ...(context.onLeadStarted ? { onStart: context.onLeadStarted } : {}),
260
+ },
261
+ );
262
+ await removeSpawnPromptFile(tmpFile);
263
+ return {
264
+ instanceId,
265
+ taskId: context.taskId,
266
+ providerId: 'claude-code',
267
+ status: exit.exitCode === 0 ? 'completed' : 'failed',
268
+ ...(exit.exitCode !== null ? { exitCode: exit.exitCode } : {}),
269
+ startTime,
270
+ endTime: new Date().toISOString(),
271
+ leadMcp: leadMcp.report,
272
+ };
273
+ }
274
+ }
275
+ // --settings: a tracked worker's exit hook, or a lead's session hooks
276
+ const claudeArgs = buildClaudeArgs(context, tmpFile, settingsArgs, leadMcp);
111
277
 
112
278
  // T11998: Build the argv with per-session containment.
113
279
  // On Linux with systemd, this wraps 'claude' inside a transient
@@ -147,6 +313,8 @@ export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
147
313
  // unref() so the parent process can exit without waiting for the child.
148
314
  // The containment scope/pgid ensures the child tree can still be reaped.
149
315
  child.unref();
316
+ // T14363: a detached lead's record names its own pid.
317
+ if (leadMcp !== undefined && child.pid !== undefined) context.onLeadStarted?.(child.pid);
150
318
 
151
319
  // Resolve the ownership handle: for the pgid path the pgid is the same
152
320
  // as the pid when detached:true (Node sets the child as the group leader).
@@ -183,6 +351,7 @@ export class ClaudeCodeSpawnProvider implements AdapterSpawnProvider {
183
351
  // T11998: surface the ownership handle in the result so callers can
184
352
  // persist it or pass it to reapAgentSuite on session end.
185
353
  ownership,
354
+ ...(leadMcp ? { leadMcp: leadMcp.report, leadTempDir: dirname(tmpFile) } : {}),
186
355
  };
187
356
  } catch (error) {
188
357
  // Log spawn failure for debugging
@@ -16,13 +16,21 @@ import { ClaudeSDKSpawnProvider } from '../spawn.js';
16
16
  // Mock Vercel AI SDK surface
17
17
  // ---------------------------------------------------------------------------
18
18
 
19
+ /** Arguments the provider passes to the mocked `generateText`. */
20
+ interface GenerateTextCall {
21
+ model: unknown;
22
+ prompt: string;
23
+ tools?: object;
24
+ providerOptions?: { anthropic?: { cleoAllowedTools?: string[] } };
25
+ }
26
+
19
27
  /** Shared mock state tracked across tests. */
20
28
  const { mockState } = vi.hoisted(() => {
21
29
  return {
22
30
  mockState: {
23
31
  text: 'mocked claude response',
24
32
  shouldThrow: false,
25
- lastCall: null as null | { model: unknown; prompt: string },
33
+ lastCall: null as null | GenerateTextCall,
26
34
  },
27
35
  };
28
36
  });
@@ -38,8 +46,8 @@ vi.mock('@ai-sdk/anthropic', () => ({
38
46
 
39
47
  // Mock 'ai' generateText to drive deterministic test outputs.
40
48
  vi.mock('ai', () => ({
41
- generateText: vi.fn(async ({ model, prompt }: { model: unknown; prompt: string }) => {
42
- mockState.lastCall = { model, prompt };
49
+ generateText: vi.fn(async (call: GenerateTextCall) => {
50
+ mockState.lastCall = call;
43
51
  if (mockState.shouldThrow) {
44
52
  throw new Error('mock AI SDK error');
45
53
  }
@@ -219,6 +227,58 @@ describe('ClaudeSDKSpawnProvider', () => {
219
227
  | undefined;
220
228
  expect(model?.modelId).toBe('claude-sonnet-4-6');
221
229
  });
230
+
231
+ it('declares lead tool strip as enforced (T14357)', () => {
232
+ expect(provider.leadToolStrip).toBe('enforced');
233
+ });
234
+
235
+ it.each([
236
+ undefined,
237
+ 'interactive',
238
+ ])('refuses an interactive lead (%s) before generation, naming --detached', async (leadMode) => {
239
+ const result = await provider.spawn({
240
+ taskId: 'T005',
241
+ prompt: 'Plan only.',
242
+ leadDeniedTools: ['Bash', 'Edit', 'Write'],
243
+ options: { leadMode },
244
+ });
245
+ expect(result.status).toBe('failed');
246
+ expect(result.error).toContain('E_LEAD_NO_OWNER_CHANNEL');
247
+ expect(result.error).toContain('--detached');
248
+ expect(result.error).toContain('--adapter claude-code');
249
+ expect(mockState.lastCall).toBeNull();
250
+ expect(await provider.listRunning()).toEqual([]);
251
+ });
252
+
253
+ it('lead spawn: passes no tools and drops denied tools from the allowlist (T14357)', async () => {
254
+ const result = await provider.spawn({
255
+ taskId: 'T005',
256
+ prompt: 'Plan only.',
257
+ leadDeniedTools: ['Bash', 'Edit', 'Write'],
258
+ options: { leadMode: 'detached' },
259
+ });
260
+
261
+ expect(result.status).toBe('completed');
262
+ expect(mockState.lastCall?.tools).toBeUndefined();
263
+ expect(mockState.lastCall?.providerOptions?.anthropic?.cleoAllowedTools).toEqual([
264
+ 'Read',
265
+ 'Glob',
266
+ 'Grep',
267
+ ]);
268
+ });
269
+
270
+ it('worker spawn keeps the default tool allowlist (T14357)', async () => {
271
+ await provider.spawn({ taskId: 'T006', prompt: 'Do the work.' });
272
+
273
+ expect(mockState.lastCall?.providerOptions?.anthropic?.cleoAllowedTools).toEqual([
274
+ 'Read',
275
+ 'Write',
276
+ 'Edit',
277
+ 'Bash',
278
+ 'Glob',
279
+ 'Grep',
280
+ ]);
281
+ });
222
282
  });
223
283
 
224
284
  // -------------------------------------------------------------------------
@@ -25,7 +25,9 @@
25
25
 
26
26
  import type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/contracts';
27
27
  import { getErrorMessage } from '@cleocode/contracts';
28
+ import { E_LEAD_NO_OWNER_CHANNEL } from '@cleocode/contracts/operations/orchestrate.js';
28
29
  import { resolveCredentials } from '../shared/credentials.js';
30
+ import { leadDeniedTools } from '../shared/lead-tool-strip.js';
29
31
  import { SessionStore } from './session-store.js';
30
32
  import { resolveTools } from './tool-bridge.js';
31
33
 
@@ -48,6 +50,13 @@ const DEFAULT_MODEL = 'claude-sonnet-4-5';
48
50
  * agent registry) remains the source of truth for scaffolding.
49
51
  */
50
52
  export class ClaudeSDKSpawnProvider implements AdapterSpawnProvider {
53
+ /**
54
+ * `generateText()` is called with no `tools`, so a spawned agent can call no
55
+ * tool at all; for a lead the denied tools are also dropped from the recorded
56
+ * allowlist (T14357).
57
+ */
58
+ readonly leadToolStrip = 'enforced' as const;
59
+
51
60
  /** In-memory session registry. */
52
61
  private readonly sessions = new SessionStore();
53
62
 
@@ -79,6 +88,19 @@ export class ClaudeSDKSpawnProvider implements AdapterSpawnProvider {
79
88
  const sessionId = `cleo-${instanceId}`;
80
89
  const startTime = new Date().toISOString();
81
90
 
91
+ if (leadDeniedTools(context) !== null && context.options?.leadMode !== 'detached') {
92
+ return {
93
+ instanceId,
94
+ taskId: context.taskId,
95
+ providerId: 'claude-sdk',
96
+ status: 'failed',
97
+ startTime,
98
+ endTime: new Date().toISOString(),
99
+ exitCode: 1,
100
+ error: `${E_LEAD_NO_OWNER_CHANNEL}: claude-sdk cannot deliver interactive AskUserQuestion answers; use --detached with --adapter claude-code and a configured mbx MCP server`,
101
+ };
102
+ }
103
+
82
104
  // Register in session store immediately so listRunning() reflects it
83
105
  // before the async generation starts.
84
106
  this.sessions.add({
@@ -131,7 +153,12 @@ export class ClaudeSDKSpawnProvider implements AdapterSpawnProvider {
131
153
  // orchestration (composeSpawnPayload) applies allowlists before prompt
132
154
  // composition; this array is surfaced so telemetry remains complete.
133
155
  const toolAllowlist = context.options?.toolAllowlist as string[] | undefined;
134
- const allowedTools = resolveTools(toolAllowlist);
156
+ // T14357: a lead's denied tools never appear in the allowlist. The real
157
+ // enforcement is structural: generateText() below receives no `tools`.
158
+ const denied = leadDeniedTools(context);
159
+ const allowedTools = resolveTools(toolAllowlist).filter(
160
+ (tool) => denied === null || !(denied as readonly string[]).includes(tool),
161
+ );
135
162
 
136
163
  const modelId = (context.options?.model as string) ?? DEFAULT_MODEL;
137
164
 
@@ -29,6 +29,7 @@ import type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/
29
29
  import { getErrorMessage } from '@cleocode/contracts';
30
30
  import { findOnPath } from '@cleocode/paths';
31
31
  import { spawnCli } from '../shared/cli-spawn.js';
32
+ import { assertLeadToolsStrippable } from '../shared/lead-tool-strip.js';
32
33
  import { removeSpawnPromptFile, writeSpawnPromptFile } from '../shared/prompt-file.js';
33
34
 
34
35
  /** Internal tracking entry for a spawned process. */
@@ -56,6 +57,9 @@ interface TrackedProcess {
56
57
  * @task T648
57
58
  */
58
59
  export class CodexSpawnProvider implements AdapterSpawnProvider {
60
+ /** Cannot remove tools from a spawned agent: a lead spawn is refused (T14357). */
61
+ readonly leadToolStrip = 'unsupported' as const;
62
+
59
63
  /** Map of instance IDs to tracked process info. */
60
64
  private processMap = new Map<string, TrackedProcess>();
61
65
 
@@ -84,6 +88,7 @@ export class CodexSpawnProvider implements AdapterSpawnProvider {
84
88
  * @returns Spawn result with instance ID and status
85
89
  */
86
90
  async spawn(context: SpawnContext): Promise<SpawnResult> {
91
+ assertLeadToolsStrippable('codex', this.leadToolStrip, context);
87
92
  const instanceId = `codex-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
88
93
  const startTime = new Date().toISOString();
89
94
  let tmpFile: string | undefined;
@@ -18,6 +18,9 @@ import type { AdapterSpawnProvider, SpawnContext, SpawnResult } from '@cleocode/
18
18
  * either reject or return empty results.
19
19
  */
20
20
  export class CursorSpawnProvider implements AdapterSpawnProvider {
21
+ /** Cannot remove tools from a spawned agent: a lead spawn is refused (T14357). */
22
+ readonly leadToolStrip = 'unsupported' as const;
23
+
21
24
  /**
22
25
  * Check if Cursor supports spawning subagents.
23
26
  *