@zvada/agent-server 0.3.12 → 0.3.14
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/CHANGELOG.md +53 -0
- package/docs/deploy.md +4 -0
- package/docs/harnesses.md +44 -2
- package/docs/rfds/0002-native-subagents.md +197 -0
- package/package.json +4 -4
- package/src/core/agents/acp/acp-agent.ts +113 -18
- package/src/core/agents/acp/adapter.ts +23 -4
- package/src/core/agents/base.ts +1 -0
- package/src/core/agents/claude-code/adapter.ts +2 -2
- package/src/core/agents/claude-code/claude-agent.ts +2 -0
- package/src/core/agents/claude-code/options.ts +10 -1
- package/src/core/agents/claude-code/session-manager.ts +1 -0
- package/src/core/agents/codex-app-server/adapter.ts +35 -1
- package/src/core/agents/codex-app-server/client.ts +54 -1
- package/src/core/agents/codex-app-server/codex-app-server-agent.ts +123 -8
- package/src/core/agents/codex-app-server/subagents.ts +201 -0
- package/src/core/agents/codex-items.ts +27 -0
- package/src/core/agents/codex-sdk/adapter.ts +4 -1
- package/src/core/agents/codex-sdk/codex-sdk-agent.ts +28 -18
- package/src/core/agents/session-agent.ts +3 -0
- package/src/core/provision/pins.ts +11 -9
- package/src/core/runtime/agent-runtime.ts +7 -2
- package/src/protocol/config.ts +4 -2
- package/src/protocol/errors.ts +30 -1
- package/src/protocol/guards.ts +1 -1
- package/src/protocol/harness.ts +2 -0
- package/src/protocol/models.ts +23 -9
- package/src/protocol/parts.ts +11 -0
- package/src/protocol/thinking.ts +15 -3
- package/src/server/acp/binding.ts +79 -4
- package/src/server/bin.ts +16 -2
package/src/core/agents/base.ts
CHANGED
|
@@ -196,7 +196,7 @@ function toolResultContent(content: unknown): ToolResultContent[] | undefined {
|
|
|
196
196
|
/**
|
|
197
197
|
* SubagentMetadata from a spawning tool's input, shared by the streamed and
|
|
198
198
|
* non-streaming paths. `subagent_type` in the input identifies a spawn on any
|
|
199
|
-
* tool name;
|
|
199
|
+
* tool name; Claude's `Agent` (formerly `Task`) also counts before its
|
|
200
200
|
* input parses into anything useful (presence of `subagent` is what promotes
|
|
201
201
|
* the part to `kind: "task"` — see protocol §3.5).
|
|
202
202
|
*/
|
|
@@ -207,7 +207,7 @@ function subagentFromInput(
|
|
|
207
207
|
const str = (key: string): string | undefined =>
|
|
208
208
|
typeof input[key] === "string" ? (input[key] as string) : undefined;
|
|
209
209
|
const type = str("subagent_type");
|
|
210
|
-
if (type === undefined && toolName !== "Task") return undefined;
|
|
210
|
+
if (type === undefined && toolName !== "Task" && toolName !== "Agent") return undefined;
|
|
211
211
|
const description = str("description");
|
|
212
212
|
const model = str("model");
|
|
213
213
|
return {
|
|
@@ -25,6 +25,7 @@ const CAPABILITIES: AgentCapabilities = {
|
|
|
25
25
|
images: true,
|
|
26
26
|
mcpServers: true,
|
|
27
27
|
permissionRequests: true,
|
|
28
|
+
turnScopedSubagents: true,
|
|
28
29
|
};
|
|
29
30
|
|
|
30
31
|
/** Convert our normalized input into Claude's message content. */
|
|
@@ -68,6 +69,7 @@ function sessionConfigFrom(
|
|
|
68
69
|
thinkingLevel: options.thinkingLevel,
|
|
69
70
|
permissionMode: options.permissionMode,
|
|
70
71
|
maxTurns: options.maxTurns,
|
|
72
|
+
subagentMode: options.subagentMode,
|
|
71
73
|
systemPromptAppend: options.systemPromptAppend,
|
|
72
74
|
resumeSessionId: options.resumeSessionId,
|
|
73
75
|
resumeSessionAt: options.resumeSessionAt,
|
|
@@ -44,6 +44,7 @@ export interface ClaudeSessionConfig {
|
|
|
44
44
|
thinkingLevel?: ThinkingLevel;
|
|
45
45
|
permissionMode?: PermissionMode;
|
|
46
46
|
maxTurns?: number;
|
|
47
|
+
subagentMode?: "turn";
|
|
47
48
|
systemPromptAppend?: string;
|
|
48
49
|
resumeSessionId?: string;
|
|
49
50
|
resumeSessionAt?: string;
|
|
@@ -89,12 +90,18 @@ function toSdkPermissionMode(mode: PermissionMode | undefined): CCOptions["permi
|
|
|
89
90
|
* entirely when `env` is set, so we must spread `process.env` to preserve PATH/
|
|
90
91
|
* HOME (and thus keychain/subscription auth). We only inject ANTHROPIC_API_KEY
|
|
91
92
|
* when an explicit key is supplied — otherwise the CLI's own auth is used.
|
|
93
|
+
*
|
|
94
|
+
* A subscription login also brings that account's claude.ai connectors (Drive,
|
|
95
|
+
* Gmail, …) into every session. A turn gets the MCP servers its config names,
|
|
96
|
+
* so they stay off unless the operator's or the turn's env turns them on.
|
|
92
97
|
*/
|
|
93
98
|
function buildEnv(config: ClaudeSessionConfig): Record<string, string | undefined> {
|
|
94
99
|
return {
|
|
100
|
+
ENABLE_CLAUDEAI_MCP_SERVERS: "false",
|
|
95
101
|
...process.env,
|
|
96
102
|
...(config.apiKey ? { ANTHROPIC_API_KEY: config.apiKey } : {}),
|
|
97
103
|
...config.env,
|
|
104
|
+
...(config.subagentMode === "turn" && { CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1" }),
|
|
98
105
|
};
|
|
99
106
|
}
|
|
100
107
|
|
|
@@ -129,7 +136,8 @@ export function buildClaudeOptions(
|
|
|
129
136
|
options.thinking = { type: "disabled" };
|
|
130
137
|
} else {
|
|
131
138
|
options.thinking = { type: "adaptive" };
|
|
132
|
-
|
|
139
|
+
// Claude's ceiling is `max`.
|
|
140
|
+
options.effort = config.thinkingLevel === "ultra" ? "max" : config.thinkingLevel;
|
|
133
141
|
}
|
|
134
142
|
}
|
|
135
143
|
if (config.resumeSessionId) {
|
|
@@ -156,6 +164,7 @@ export function buildClaudeOptions(
|
|
|
156
164
|
// this function returns, so those can never be clobbered (and the
|
|
157
165
|
// ClaudeSdkOptionOverrides type excludes them anyway).
|
|
158
166
|
if (overrides) Object.assign(options, overrides);
|
|
167
|
+
if (config.subagentMode === "turn") options.forwardSubagentText = true;
|
|
159
168
|
|
|
160
169
|
// Fable-class models withhold thinking plaintext by default: blocks stream
|
|
161
170
|
// structure + token estimates only, so every reasoning part arrives with
|
|
@@ -42,6 +42,7 @@ export function claudeSessionNeedsRestart(
|
|
|
42
42
|
(prev.maxTurns ?? 100) !== (next.maxTurns ?? 100) ||
|
|
43
43
|
(prev.idleTimeoutMs ?? 5 * 60_000) !== (next.idleTimeoutMs ?? 5 * 60_000) ||
|
|
44
44
|
Boolean(prev.disableTools) !== Boolean(next.disableTools) ||
|
|
45
|
+
prev.subagentMode !== next.subagentMode ||
|
|
45
46
|
configFingerprint(prev.env) !== configFingerprint(next.env)
|
|
46
47
|
// mcpServers deliberately absent: MCP changes hot-swap on the live
|
|
47
48
|
// session (`setMcpServers`) instead of restarting the subprocess.
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
type ReasoningPart,
|
|
5
5
|
type StopReason,
|
|
6
6
|
type StreamContext,
|
|
7
|
+
type SubagentPart,
|
|
7
8
|
type TextPart,
|
|
8
9
|
type TokenUsage,
|
|
9
10
|
type ToolPart,
|
|
@@ -11,6 +12,8 @@ import {
|
|
|
11
12
|
createReasoningPart,
|
|
12
13
|
createTextPart,
|
|
13
14
|
createToolPart,
|
|
15
|
+
generateUUIDv7,
|
|
16
|
+
setToolMeta,
|
|
14
17
|
} from "../../../protocol/index.ts";
|
|
15
18
|
import {
|
|
16
19
|
type CodexToolDescriptor,
|
|
@@ -31,6 +34,9 @@ import type { AdapterEvent, EventTransformer, TransformResult } from "../types.t
|
|
|
31
34
|
interface CodexItem extends CodexToolItem {
|
|
32
35
|
type: string;
|
|
33
36
|
text?: string;
|
|
37
|
+
agentThreadId?: string;
|
|
38
|
+
agentPath?: string;
|
|
39
|
+
kind?: SubagentPart["activity"];
|
|
34
40
|
}
|
|
35
41
|
interface Notification {
|
|
36
42
|
method: string;
|
|
@@ -119,6 +125,8 @@ export class CodexAppServerTransformer implements EventTransformer<unknown> {
|
|
|
119
125
|
|
|
120
126
|
private openItem(item: CodexItem): AdapterEvent[] {
|
|
121
127
|
switch (item.type) {
|
|
128
|
+
case "subAgentActivity":
|
|
129
|
+
return this.activity(item);
|
|
122
130
|
case "agentMessage": {
|
|
123
131
|
const part = createTextPart(this.ctx, item.text ?? "", true);
|
|
124
132
|
this.partByItem.set(item.id, part);
|
|
@@ -142,6 +150,8 @@ export class CodexAppServerTransformer implements EventTransformer<unknown> {
|
|
|
142
150
|
private completeItem(item: CodexItem): AdapterEvent[] {
|
|
143
151
|
const part = this.partByItem.get(item.id);
|
|
144
152
|
switch (item.type) {
|
|
153
|
+
case "subAgentActivity":
|
|
154
|
+
return this.activity(item);
|
|
145
155
|
case "agentMessage":
|
|
146
156
|
case "reasoning": {
|
|
147
157
|
const p = (part ??
|
|
@@ -161,12 +171,34 @@ export class CodexAppServerTransformer implements EventTransformer<unknown> {
|
|
|
161
171
|
const d = codexToolDescriptor(item.type);
|
|
162
172
|
if (!d) return [];
|
|
163
173
|
const tool = this.ensureTool(item, d);
|
|
174
|
+
setToolMeta(tool, d.meta(item));
|
|
164
175
|
completeToolPart(tool, d.result(item));
|
|
165
176
|
return [{ kind: "part-update", part: tool }];
|
|
166
177
|
}
|
|
167
178
|
}
|
|
168
179
|
}
|
|
169
180
|
|
|
181
|
+
private activity(item: CodexItem): AdapterEvent[] {
|
|
182
|
+
if (
|
|
183
|
+
!item.agentThreadId ||
|
|
184
|
+
!item.kind ||
|
|
185
|
+
!["started", "interacted", "interrupted", "completed"].includes(item.kind)
|
|
186
|
+
)
|
|
187
|
+
return [];
|
|
188
|
+
const existing = this.partByItem.get(item.id);
|
|
189
|
+
const part: SubagentPart = {
|
|
190
|
+
...this.ctx,
|
|
191
|
+
id: existing?.id ?? generateUUIDv7(),
|
|
192
|
+
type: "subagent",
|
|
193
|
+
nativeActivityId: item.id,
|
|
194
|
+
nativeThreadId: item.agentThreadId,
|
|
195
|
+
...(item.agentPath && { path: item.agentPath }),
|
|
196
|
+
activity: item.kind,
|
|
197
|
+
};
|
|
198
|
+
this.partByItem.set(item.id, part);
|
|
199
|
+
return [{ kind: existing ? "part-update" : "part-open", part }];
|
|
200
|
+
}
|
|
201
|
+
|
|
170
202
|
private textDelta(
|
|
171
203
|
itemId: string | undefined,
|
|
172
204
|
delta: string | undefined,
|
|
@@ -181,7 +213,9 @@ export class CodexAppServerTransformer implements EventTransformer<unknown> {
|
|
|
181
213
|
? createTextPart(this.ctx, "", true)
|
|
182
214
|
: createReasoningPart(this.ctx, "", true);
|
|
183
215
|
this.partByItem.set(itemId, part);
|
|
184
|
-
|
|
216
|
+
// The processor snapshots at emit time, after the append below. Open
|
|
217
|
+
// with a copy so this delta arrives once.
|
|
218
|
+
events.push({ kind: "part-open", part: structuredClone(part) });
|
|
185
219
|
}
|
|
186
220
|
part.text += delta;
|
|
187
221
|
events.push(
|
|
@@ -51,6 +51,7 @@ export interface CodexAppServerClientOptions {
|
|
|
51
51
|
*/
|
|
52
52
|
export class CodexAppServerClient {
|
|
53
53
|
private proc?: ChildProcess;
|
|
54
|
+
private shutdown?: Promise<boolean>;
|
|
54
55
|
private nextId = 1;
|
|
55
56
|
private buffer = "";
|
|
56
57
|
private readonly decoder = new StringDecoder("utf8");
|
|
@@ -62,6 +63,7 @@ export class CodexAppServerClient {
|
|
|
62
63
|
/** Bounded rolling tail of the subprocess's stderr — folded into the exit
|
|
63
64
|
* error so failures carry the CLI's own explanation. */
|
|
64
65
|
private stderrTail = "";
|
|
66
|
+
private nativeShutdownFailed = false;
|
|
65
67
|
/** Chunk-boundary-safe UTF-8 decoding for the stderr tail; reset per spawn. */
|
|
66
68
|
private stderrDecoder = new StringDecoder("utf8");
|
|
67
69
|
|
|
@@ -122,10 +124,13 @@ export class CodexAppServerClient {
|
|
|
122
124
|
}
|
|
123
125
|
|
|
124
126
|
close(): void {
|
|
127
|
+
if (this.shutdown) return;
|
|
125
128
|
const proc = this.proc;
|
|
126
129
|
const wasOpen = !this.exited;
|
|
127
130
|
this.proc = undefined;
|
|
128
131
|
this.exited = true;
|
|
132
|
+
// Forced process exit cannot attest that native child commands stopped.
|
|
133
|
+
this.shutdown = Promise.resolve(!proc);
|
|
129
134
|
for (const [id, p] of this.pending) {
|
|
130
135
|
if (p.timer) clearTimeout(p.timer);
|
|
131
136
|
p.reject(new Error(`codex app-server closed before '${p.method}'`));
|
|
@@ -135,6 +140,46 @@ export class CodexAppServerClient {
|
|
|
135
140
|
if (wasOpen) this.notifyClosed();
|
|
136
141
|
}
|
|
137
142
|
|
|
143
|
+
/** EOF invokes native thread/tool cleanup. Killing the server alone proves nothing about workers. */
|
|
144
|
+
closeAndWait(timeoutMs = 2_000): Promise<boolean> {
|
|
145
|
+
if (this.shutdown) return this.shutdown;
|
|
146
|
+
const proc = this.proc;
|
|
147
|
+
if (!proc) return Promise.resolve(true);
|
|
148
|
+
if (this.exited || proc.exitCode !== null || proc.signalCode !== null) {
|
|
149
|
+
this.shutdown = Promise.resolve(false);
|
|
150
|
+
return this.shutdown;
|
|
151
|
+
}
|
|
152
|
+
this.exited = true;
|
|
153
|
+
this.shutdown = new Promise<boolean>((resolve) => {
|
|
154
|
+
let forced = false;
|
|
155
|
+
const finish = (confirmed: boolean) => {
|
|
156
|
+
clearTimeout(killTimer);
|
|
157
|
+
clearTimeout(deadline);
|
|
158
|
+
proc.off("close", exited);
|
|
159
|
+
this.proc = undefined;
|
|
160
|
+
resolve(confirmed);
|
|
161
|
+
};
|
|
162
|
+
const exited = (code: number | null, signal: NodeJS.Signals | null) =>
|
|
163
|
+
finish(!forced && !this.nativeShutdownFailed && code === 0 && signal === null);
|
|
164
|
+
proc.once("close", exited);
|
|
165
|
+
const killTimer = setTimeout(() => {
|
|
166
|
+
forced = true;
|
|
167
|
+
proc.kill("SIGKILL");
|
|
168
|
+
}, timeoutMs);
|
|
169
|
+
const deadline = setTimeout(() => finish(false), timeoutMs * 2);
|
|
170
|
+
// In stdio mode SIGTERM bypasses Codex's async shutdown. EOF drains
|
|
171
|
+
// connection tasks and awaits shutdown_threads before a clean exit.
|
|
172
|
+
proc.stdin?.end();
|
|
173
|
+
});
|
|
174
|
+
for (const [id, p] of this.pending) {
|
|
175
|
+
if (p.timer) clearTimeout(p.timer);
|
|
176
|
+
p.reject(new Error(`codex app-server closed before '${p.method}'`));
|
|
177
|
+
this.pending.delete(id);
|
|
178
|
+
}
|
|
179
|
+
this.notifyClosed();
|
|
180
|
+
return this.shutdown;
|
|
181
|
+
}
|
|
182
|
+
|
|
138
183
|
private notifyClosed(error?: Error): void {
|
|
139
184
|
for (const handler of this.closeHandlers) handler(error);
|
|
140
185
|
this.closeHandlers.clear();
|
|
@@ -143,6 +188,7 @@ export class CodexAppServerClient {
|
|
|
143
188
|
private start(): void {
|
|
144
189
|
if (this.proc && !this.exited) return;
|
|
145
190
|
this.exited = false;
|
|
191
|
+
this.shutdown = undefined;
|
|
146
192
|
const spawnProcess = this.opts.spawnProcess ?? nodeSpawn;
|
|
147
193
|
const proc = spawnProcess(this.opts.codexPath ?? "codex", ["app-server"], {
|
|
148
194
|
cwd: this.opts.cwd,
|
|
@@ -151,6 +197,7 @@ export class CodexAppServerClient {
|
|
|
151
197
|
});
|
|
152
198
|
this.proc = proc;
|
|
153
199
|
this.stderrTail = "";
|
|
200
|
+
this.nativeShutdownFailed = false;
|
|
154
201
|
this.stderrDecoder = new StringDecoder("utf8");
|
|
155
202
|
proc.stdout?.on("data", (chunk: Buffer) => this.onStdout(chunk));
|
|
156
203
|
proc.stdin?.on("error", (err) => this.onExit(err));
|
|
@@ -161,7 +208,13 @@ export class CodexAppServerClient {
|
|
|
161
208
|
// from a crash for the integrator staring at the turn error. Decoded
|
|
162
209
|
// via StringDecoder so a UTF-8 sequence split across chunks survives.
|
|
163
210
|
proc.stderr?.on("data", (chunk: Buffer) => {
|
|
164
|
-
|
|
211
|
+
const text = this.stderrTail + this.stderrDecoder.write(chunk);
|
|
212
|
+
// The pinned native server logs these cleanup failures but still exits 0.
|
|
213
|
+
if (
|
|
214
|
+
/failed to submit Shutdown|timed out waiting for .*shut down|shutdown timed out/.test(text)
|
|
215
|
+
)
|
|
216
|
+
this.nativeShutdownFailed = true;
|
|
217
|
+
this.stderrTail = text.slice(-STDERR_TAIL_MAX);
|
|
165
218
|
});
|
|
166
219
|
proc.on("error", (err) => this.onExit(err));
|
|
167
220
|
// Build the exit error on CLOSE, not exit: `exit` can fire before the
|
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
codexMcpServers,
|
|
31
31
|
writeCodexMcpServers,
|
|
32
32
|
} from "./mcp.ts";
|
|
33
|
+
import { CodexTurnSubagents } from "./subagents.ts";
|
|
33
34
|
|
|
34
35
|
const CAPABILITIES: AgentCapabilities = {
|
|
35
36
|
multiTurn: true,
|
|
@@ -40,6 +41,7 @@ const CAPABILITIES: AgentCapabilities = {
|
|
|
40
41
|
images: true,
|
|
41
42
|
mcpServers: true,
|
|
42
43
|
permissionRequests: true,
|
|
44
|
+
turnScopedSubagents: true,
|
|
43
45
|
};
|
|
44
46
|
|
|
45
47
|
export interface AppServerSession {
|
|
@@ -49,6 +51,7 @@ export interface AppServerSession {
|
|
|
49
51
|
approvalPolicy: string;
|
|
50
52
|
sandbox: string;
|
|
51
53
|
systemPromptAppend?: string;
|
|
54
|
+
subagentMode?: "turn";
|
|
52
55
|
envFingerprint: string;
|
|
53
56
|
/** Native model connections retain the identity used at their first handshake. */
|
|
54
57
|
authFingerprint?: string;
|
|
@@ -63,6 +66,7 @@ interface AppServerTurn {
|
|
|
63
66
|
auth?: CodexAppServerAuth;
|
|
64
67
|
permissionHandler?: PermissionRequestHandler;
|
|
65
68
|
signal: AbortSignal;
|
|
69
|
+
subagents?: CodexTurnSubagents;
|
|
66
70
|
}
|
|
67
71
|
|
|
68
72
|
export function appServerSessionCompatible(
|
|
@@ -76,6 +80,7 @@ export function appServerSessionCompatible(
|
|
|
76
80
|
existing.approvalPolicy === approvalPolicyFor(options) &&
|
|
77
81
|
existing.sandbox === mapSandbox(options.permissionMode) &&
|
|
78
82
|
(existing.systemPromptAppend ?? "") === (options.systemPromptAppend ?? "") &&
|
|
83
|
+
existing.subagentMode === options.subagentMode &&
|
|
79
84
|
existing.envFingerprint === configFingerprint(options.env) &&
|
|
80
85
|
(!options.resumeSessionId || options.resumeSessionId === existing.threadId),
|
|
81
86
|
);
|
|
@@ -231,6 +236,7 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
231
236
|
readonly capabilities = CAPABILITIES;
|
|
232
237
|
private readonly sessions = new SessionStore<AppServerSession>();
|
|
233
238
|
private readonly invalidatedClients = new WeakSet<CodexAppServerClient>();
|
|
239
|
+
private readonly unsettledSessions = new Map<string, CodexAppServerClient>();
|
|
234
240
|
/** Home ownership outlives idle process eviction and failed preparation. */
|
|
235
241
|
private readonly mcpHomes = new Map<string, string>();
|
|
236
242
|
/** A cancel acknowledgement belongs to one invocation, even after it drains. */
|
|
@@ -288,7 +294,9 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
288
294
|
(await this.agentOptions.resolveCliPath?.()) ?? process.env.CODEX_CLI_PATH ?? "codex",
|
|
289
295
|
cwd: options.cwd,
|
|
290
296
|
env: options.env ? ({ ...process.env, ...options.env } as NodeJS.ProcessEnv) : process.env,
|
|
291
|
-
...(turn.auth?.type === "chatgptAuthTokens"
|
|
297
|
+
...((turn.auth?.type === "chatgptAuthTokens" || options.subagentMode === "turn") && {
|
|
298
|
+
experimentalApi: true,
|
|
299
|
+
}),
|
|
292
300
|
};
|
|
293
301
|
signal.throwIfAborted();
|
|
294
302
|
const client =
|
|
@@ -305,6 +313,7 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
305
313
|
approvalPolicy,
|
|
306
314
|
sandbox,
|
|
307
315
|
systemPromptAppend: options.systemPromptAppend,
|
|
316
|
+
subagentMode: options.subagentMode,
|
|
308
317
|
envFingerprint: configFingerprint(options.env),
|
|
309
318
|
authFingerprint: identity,
|
|
310
319
|
turn,
|
|
@@ -327,6 +336,15 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
327
336
|
if (options.model) startParams.model = options.model;
|
|
328
337
|
if (options.systemPromptAppend)
|
|
329
338
|
startParams.developerInstructions = options.systemPromptAppend;
|
|
339
|
+
if (options.subagentMode === "turn") {
|
|
340
|
+
startParams.config = { "features.multi_agent": true };
|
|
341
|
+
startParams.developerInstructions = [
|
|
342
|
+
options.systemPromptAppend,
|
|
343
|
+
"Collect the results of every subagent before ending your turn. Stop any worker you no longer need. Delegated work cannot continue after this task completes.",
|
|
344
|
+
]
|
|
345
|
+
.filter(Boolean)
|
|
346
|
+
.join("\n\n");
|
|
347
|
+
}
|
|
330
348
|
|
|
331
349
|
const method = resumeThreadId ? "thread/resume" : "thread/start";
|
|
332
350
|
const result = (await client
|
|
@@ -466,7 +484,14 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
466
484
|
const requestThread = params.threadId ?? params.conversationId;
|
|
467
485
|
const v2 = method.startsWith("item/");
|
|
468
486
|
const decline = v2 ? { decision: "decline" } : { decision: "denied" };
|
|
469
|
-
if (requestThread && requestThread !== session.threadId)
|
|
487
|
+
if (requestThread && requestThread !== session.threadId) {
|
|
488
|
+
if (
|
|
489
|
+
typeof requestThread !== "string" ||
|
|
490
|
+
!turn?.subagents ||
|
|
491
|
+
!(await turn.subagents.owns(requestThread).catch(() => false))
|
|
492
|
+
)
|
|
493
|
+
return decline;
|
|
494
|
+
}
|
|
470
495
|
const handler = turn?.permissionHandler;
|
|
471
496
|
if (!handler || turn?.signal.aborted) return decline;
|
|
472
497
|
const decision = await handler(approvalToolCall(method, params));
|
|
@@ -511,8 +536,16 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
511
536
|
const unsubscribe: Array<() => void> = [];
|
|
512
537
|
let session: AppServerSession | undefined;
|
|
513
538
|
let turnEnded = false;
|
|
539
|
+
let parentEnded = false;
|
|
540
|
+
let managedCompletion: Promise<boolean> | undefined;
|
|
514
541
|
try {
|
|
515
542
|
controller.signal.throwIfAborted();
|
|
543
|
+
const unsettled = this.unsettledSessions.get(options.sessionId);
|
|
544
|
+
if (unsettled) {
|
|
545
|
+
if (!(await unsettled.closeAndWait()))
|
|
546
|
+
throw new Error("Previous Codex execution has not stopped");
|
|
547
|
+
this.unsettledSessions.delete(options.sessionId);
|
|
548
|
+
}
|
|
516
549
|
const requestedMcp = codexMcpServers(snapshotMcpServers(options.mcpServers));
|
|
517
550
|
const mcpServers = this.managedMcpHome(options, Object.keys(requestedMcp).length > 0)
|
|
518
551
|
? requestedMcp
|
|
@@ -527,7 +560,17 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
527
560
|
});
|
|
528
561
|
const threadId = session.threadId;
|
|
529
562
|
const client = session.client;
|
|
530
|
-
|
|
563
|
+
if (options.subagentMode === "turn") {
|
|
564
|
+
turn.subagents = new CodexTurnSubagents(
|
|
565
|
+
client,
|
|
566
|
+
threadId,
|
|
567
|
+
this.agentOptions.cancelGraceMs ?? 2_000,
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
const abortPreparation = () => {
|
|
571
|
+
if (turn.subagents) void client.closeAndWait();
|
|
572
|
+
else client.close();
|
|
573
|
+
};
|
|
531
574
|
controller.signal.addEventListener("abort", abortPreparation, { once: true });
|
|
532
575
|
try {
|
|
533
576
|
controller.signal.throwIfAborted();
|
|
@@ -545,6 +588,47 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
545
588
|
}
|
|
546
589
|
|
|
547
590
|
let turnId: string | undefined;
|
|
591
|
+
const finishManaged = (): Promise<boolean> => {
|
|
592
|
+
if (managedCompletion) return managedCompletion;
|
|
593
|
+
managedCompletion = (async () => {
|
|
594
|
+
let confirmed = true;
|
|
595
|
+
let failure: unknown;
|
|
596
|
+
const graceMs = this.agentOptions.cancelGraceMs ?? 2_000;
|
|
597
|
+
const deadline = setTimeout(() => {
|
|
598
|
+
void client.closeAndWait(graceMs);
|
|
599
|
+
}, graceMs * 5);
|
|
600
|
+
try {
|
|
601
|
+
if (!parentEnded) {
|
|
602
|
+
// A startup interrupt only acknowledges submission, not native settlement.
|
|
603
|
+
if (!turnId) throw new Error("Codex cancelled before turn admission was observed");
|
|
604
|
+
await client.request("turn/interrupt", { threadId, turnId }, graceMs);
|
|
605
|
+
}
|
|
606
|
+
const unfinished = await turn.subagents!.settle();
|
|
607
|
+
// Native terminal registration can land after turn/completed and
|
|
608
|
+
// after an empty terminal inventory. EOF awaits native thread/tool
|
|
609
|
+
// shutdown; an idle snapshot alone cannot release a managed turn.
|
|
610
|
+
confirmed = await client.closeAndWait(graceMs);
|
|
611
|
+
if (!confirmed) throw new Error("Codex native cleanup was not confirmed");
|
|
612
|
+
if (unfinished && !controller.signal.aborted) {
|
|
613
|
+
failure = new Error(
|
|
614
|
+
"Parent finished with outstanding subagent work; workers were stopped and the result is incomplete",
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
} catch (error) {
|
|
618
|
+
failure = error;
|
|
619
|
+
confirmed = await client.closeAndWait(graceMs);
|
|
620
|
+
if (!confirmed) this.unsettledSessions.set(options.sessionId, client);
|
|
621
|
+
} finally {
|
|
622
|
+
clearTimeout(deadline);
|
|
623
|
+
}
|
|
624
|
+
turnEnded = true;
|
|
625
|
+
if (controller.signal.aborted) queue.fail(new Error("turn aborted"));
|
|
626
|
+
else if (failure) queue.fail(failure);
|
|
627
|
+
else queue.end();
|
|
628
|
+
return confirmed;
|
|
629
|
+
})();
|
|
630
|
+
return managedCompletion;
|
|
631
|
+
};
|
|
548
632
|
const forceCancel = () => {
|
|
549
633
|
if (turnEnded) return;
|
|
550
634
|
queue.fail(new Error("turn aborted"));
|
|
@@ -553,6 +637,10 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
553
637
|
const onAbort = () => {
|
|
554
638
|
clearStall();
|
|
555
639
|
if (interruptState.acknowledgement) return;
|
|
640
|
+
if (turn.subagents) {
|
|
641
|
+
interruptState.acknowledgement = finishManaged();
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
556
644
|
if (!turnId) {
|
|
557
645
|
interruptState.acknowledgement = Promise.resolve(false);
|
|
558
646
|
forceCancel();
|
|
@@ -574,6 +662,7 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
574
662
|
|
|
575
663
|
unsubscribe.push(
|
|
576
664
|
client.onNotification((n) => {
|
|
665
|
+
turn.subagents?.observe(n);
|
|
577
666
|
if (n.params.threadId && n.params.threadId !== threadId) return;
|
|
578
667
|
if (n.method === "turn/started") {
|
|
579
668
|
const turn = n.params.turn as { id?: string } | undefined;
|
|
@@ -581,6 +670,12 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
581
670
|
turnId = turn.id;
|
|
582
671
|
}
|
|
583
672
|
}
|
|
673
|
+
if (appServerNotificationEndsTurn(n) && turn.subagents) {
|
|
674
|
+
parentEnded = n.method === "turn/completed";
|
|
675
|
+
queue.push(n);
|
|
676
|
+
void finishManaged();
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
584
679
|
if (appServerNotificationEndsTurn(n)) turnEnded = true;
|
|
585
680
|
if (turnEnded && controller.signal.aborted) {
|
|
586
681
|
queue.fail(new Error("turn aborted"));
|
|
@@ -602,13 +697,14 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
602
697
|
);
|
|
603
698
|
// If the subprocess dies mid-turn, fail the turn instead of hanging.
|
|
604
699
|
unsubscribe.push(
|
|
605
|
-
client.onClose((err) =>
|
|
700
|
+
client.onClose((err) => {
|
|
701
|
+
if (managedCompletion) return;
|
|
606
702
|
queue.fail(
|
|
607
703
|
controller.signal.aborted
|
|
608
704
|
? new Error("turn aborted")
|
|
609
705
|
: (err ?? new Error("codex app-server exited mid-turn")),
|
|
610
|
-
)
|
|
611
|
-
),
|
|
706
|
+
);
|
|
707
|
+
}),
|
|
612
708
|
);
|
|
613
709
|
|
|
614
710
|
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
@@ -628,7 +724,8 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
628
724
|
}
|
|
629
725
|
client.request("turn/start", turnParams).catch((err: unknown) => {
|
|
630
726
|
if (controller.signal.aborted) {
|
|
631
|
-
|
|
727
|
+
if (turn.subagents) void finishManaged();
|
|
728
|
+
else forceCancel();
|
|
632
729
|
return;
|
|
633
730
|
}
|
|
634
731
|
queue.push({ method: "error", params: { message: String(err) } });
|
|
@@ -641,6 +738,11 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
641
738
|
} catch (error) {
|
|
642
739
|
throw controller.signal.aborted ? new Error("turn aborted") : error;
|
|
643
740
|
} finally {
|
|
741
|
+
if (managedCompletion) await managedCompletion;
|
|
742
|
+
// Every exit owns cleanup, including turn/start failure and iterator.return().
|
|
743
|
+
if (options.subagentMode === "turn" && session && !(await session.client.closeAndWait())) {
|
|
744
|
+
this.unsettledSessions.set(options.sessionId, session.client);
|
|
745
|
+
}
|
|
644
746
|
turnEnded = true;
|
|
645
747
|
clearStall();
|
|
646
748
|
if (cancelTimer) clearTimeout(cancelTimer);
|
|
@@ -664,7 +766,13 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
664
766
|
// set on a later microtask, so reading afterwards would race that drain.
|
|
665
767
|
const controllers = [...(this.inflight.get(sessionId) ?? [])];
|
|
666
768
|
const base = await super.cancel(sessionId);
|
|
667
|
-
if (!base.hadTurn)
|
|
769
|
+
if (!base.hadTurn) {
|
|
770
|
+
const unsettled = this.unsettledSessions.get(sessionId);
|
|
771
|
+
if (!unsettled) return base;
|
|
772
|
+
const confirmed = await unsettled.closeAndWait();
|
|
773
|
+
if (confirmed) this.unsettledSessions.delete(sessionId);
|
|
774
|
+
return { confirmed, hadTurn: false };
|
|
775
|
+
}
|
|
668
776
|
const acknowledgements = await Promise.all(
|
|
669
777
|
controllers.map(
|
|
670
778
|
(controller) => this.turnInterruptState.get(controller)?.acknowledgement ?? false,
|
|
@@ -691,6 +799,13 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
691
799
|
}
|
|
692
800
|
|
|
693
801
|
override async release(sessionId: string): Promise<void> {
|
|
802
|
+
// A host may release this harness before switching providers. Do not let
|
|
803
|
+
// that path discard ownership while managed child cleanup is unconfirmed.
|
|
804
|
+
const managed =
|
|
805
|
+
this.unsettledSessions.has(sessionId) ||
|
|
806
|
+
this.sessions.get(sessionId)?.subagentMode === "turn";
|
|
807
|
+
if (managed && !(await this.cancel(sessionId)).confirmed)
|
|
808
|
+
throw new Error("Codex native cleanup was not confirmed; cannot release the session");
|
|
694
809
|
await super.release(sessionId);
|
|
695
810
|
this.sessions.close(sessionId);
|
|
696
811
|
for (const [home, owner] of this.mcpHomes) {
|