@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.
@@ -0,0 +1,201 @@
1
+ import type { CodexAppServerClient, CodexNotification } from "./client.ts";
2
+
3
+ interface NativeThread {
4
+ id: string;
5
+ parentThreadId?: string | null;
6
+ status?: { type: string };
7
+ source?: { subagent?: { thread_spawn?: { parent_thread_id?: string } } } | string;
8
+ turns?: Array<{ id: string; status: string }>;
9
+ }
10
+
11
+ function parentOf(thread: NativeThread): string | undefined {
12
+ return (
13
+ thread.parentThreadId ??
14
+ (typeof thread.source === "object"
15
+ ? thread.source.subagent?.thread_spawn?.parent_thread_id
16
+ : undefined)
17
+ );
18
+ }
19
+
20
+ /** Native ownership and cleanup for ONE execution; scheduling stays in Codex. */
21
+ export class CodexTurnSubagents {
22
+ private readonly parents = new Map<string, string>();
23
+ private readonly candidates = new Set<string>();
24
+ private readonly active = new Set<string>();
25
+ private activeAtParentEnd = new Set<string>();
26
+
27
+ constructor(
28
+ private readonly client: CodexAppServerClient,
29
+ private readonly root: string,
30
+ private readonly timeoutMs: number,
31
+ ) {}
32
+
33
+ observe(notification: CodexNotification): void {
34
+ const id = notification.params.threadId;
35
+ if (id && id !== this.root) {
36
+ if (notification.method === "turn/started") this.active.add(id);
37
+ if (notification.method === "turn/completed") this.active.delete(id);
38
+ if (notification.method === "thread/status/changed") {
39
+ const status = notification.params.status as { type?: string } | undefined;
40
+ if (status?.type === "active") this.active.add(id);
41
+ else if (status?.type) this.active.delete(id);
42
+ }
43
+ }
44
+ if (id === this.root && notification.method === "turn/completed")
45
+ this.activeAtParentEnd = new Set(this.active);
46
+ if (notification.method === "thread/started") {
47
+ const thread = notification.params.thread as NativeThread | undefined;
48
+ const parent = thread && parentOf(thread);
49
+ if (thread?.id && parent) {
50
+ this.parents.set(thread.id, parent);
51
+ this.candidates.add(thread.id);
52
+ if (thread.status?.type === "active") this.active.add(thread.id);
53
+ }
54
+ }
55
+ if (notification.params.threadId !== this.root) return;
56
+ const item = notification.params.item as
57
+ | {
58
+ type?: string;
59
+ agentThreadId?: string;
60
+ receiverThreadIds?: string[];
61
+ agentsStates?: Record<string, { status: string }>;
62
+ }
63
+ | undefined;
64
+ if (item?.type === "subAgentActivity" && item.agentThreadId)
65
+ this.candidates.add(item.agentThreadId);
66
+ if (item?.type === "collabAgentToolCall") {
67
+ for (const id of item.receiverThreadIds ?? []) this.candidates.add(id);
68
+ for (const [id, state] of Object.entries(item.agentsStates ?? {})) {
69
+ if (state.status === "running" || state.status === "pendingInit") this.active.add(id);
70
+ else this.active.delete(id);
71
+ }
72
+ }
73
+ }
74
+
75
+ private async read(id: string): Promise<NativeThread> {
76
+ const result = (await this.client.request(
77
+ "thread/read",
78
+ { threadId: id, includeTurns: true },
79
+ this.timeoutMs,
80
+ )) as { thread?: NativeThread };
81
+ if (result.thread?.id !== id)
82
+ throw new Error("Codex did not confirm the requested child thread");
83
+ const parent = parentOf(result.thread);
84
+ if (parent) this.parents.set(id, parent);
85
+ return result.thread;
86
+ }
87
+
88
+ async owns(id: string): Promise<boolean> {
89
+ const visited = new Set<string>();
90
+ let current = id;
91
+ while (current !== this.root) {
92
+ if (visited.has(current) || visited.size >= 32) return false;
93
+ visited.add(current);
94
+ const parent = this.parents.get(current) ?? parentOf(await this.read(current));
95
+ if (!parent) return false;
96
+ current = parent;
97
+ }
98
+ if (id !== this.root) this.candidates.add(id);
99
+ return true;
100
+ }
101
+
102
+ private async descendants(): Promise<NativeThread[]> {
103
+ // The native inventory closes missed/start-notification races, including nested workers.
104
+ let cursor: string | undefined;
105
+ const cursors = new Set<string>();
106
+ do {
107
+ const page = (await this.client.request(
108
+ "thread/loaded/list",
109
+ {
110
+ limit: 100,
111
+ ...(cursor && { cursor }),
112
+ },
113
+ this.timeoutMs,
114
+ )) as { data?: string[]; nextCursor?: string | null };
115
+ if (!Array.isArray(page.data)) throw new Error("Codex did not return its child inventory");
116
+ for (const id of page.data) this.candidates.add(id);
117
+ cursor = page.nextCursor ?? undefined;
118
+ if (cursor && cursors.has(cursor)) throw new Error("Codex repeated a child inventory cursor");
119
+ if (cursor) cursors.add(cursor);
120
+ if (this.candidates.size > 512)
121
+ throw new Error("Codex child inventory exceeds the managed turn limit");
122
+ } while (cursor);
123
+ const threads: NativeThread[] = [];
124
+ for (const id of this.candidates) {
125
+ if (id !== this.root && (await this.owns(id))) threads.push(await this.read(id));
126
+ }
127
+ return threads;
128
+ }
129
+
130
+ /** Root must have stopped first. Returns whether it left unfinished delegated work. */
131
+ async settle(): Promise<boolean> {
132
+ let unfinished = false;
133
+ for (const id of this.activeAtParentEnd) {
134
+ if (await this.owns(id)) unfinished = true;
135
+ }
136
+ let idleInventory: string | undefined;
137
+ for (let pass = 0; pass < 8; pass++) {
138
+ let stoppedWork = false;
139
+ const descendants = await this.descendants();
140
+ for (const thread of descendants) {
141
+ if (!thread.status) throw new Error("Codex child liveness is unknown");
142
+ if (thread.status.type === "active") {
143
+ unfinished = true;
144
+ stoppedWork = true;
145
+ const active = thread.turns
146
+ ?.slice()
147
+ .reverse()
148
+ .find((turn) => turn.status === "inProgress");
149
+ // Empty IDs are native startup interrupts, acknowledged on submission.
150
+ // The read below and final EOF cleanup still have to establish settlement.
151
+ // A worker can finish naturally between the inventory and the interrupt.
152
+ await this.client
153
+ .request(
154
+ "turn/interrupt",
155
+ { threadId: thread.id, turnId: active?.id ?? "" },
156
+ this.timeoutMs,
157
+ )
158
+ .catch(async (error) => {
159
+ if ((await this.read(thread.id)).status?.type !== "idle") throw error;
160
+ });
161
+ const stopped = await this.read(thread.id);
162
+ if (!stopped.status || stopped.status.type === "active")
163
+ throw new Error("Codex child interrupt was not confirmed");
164
+ }
165
+ if (thread.status.type === "notLoaded") continue;
166
+ const terminals = (await this.client.request(
167
+ "thread/backgroundTerminals/list",
168
+ { threadId: thread.id },
169
+ this.timeoutMs,
170
+ )) as { data?: unknown[] };
171
+ if (!Array.isArray(terminals.data))
172
+ throw new Error("Codex child terminal liveness is unknown");
173
+ if (terminals.data.length) {
174
+ unfinished = true;
175
+ stoppedWork = true;
176
+ await this.client.request(
177
+ "thread/backgroundTerminals/clean",
178
+ { threadId: thread.id },
179
+ this.timeoutMs,
180
+ );
181
+ const remaining = (await this.client.request(
182
+ "thread/backgroundTerminals/list",
183
+ { threadId: thread.id },
184
+ this.timeoutMs,
185
+ )) as { data?: unknown[] };
186
+ if (!Array.isArray(remaining.data) || remaining.data.length)
187
+ throw new Error("Codex child terminals did not stop");
188
+ }
189
+ }
190
+ // Interrupting a worker may race its final spawn. Reconcile the native
191
+ // inventory after stops, while the root can no longer create new work.
192
+ const inventory = descendants
193
+ .map((thread) => thread.id)
194
+ .sort()
195
+ .join("\n");
196
+ if (!stoppedWork && inventory === idleInventory) return unfinished;
197
+ idleInventory = stoppedWork ? undefined : inventory;
198
+ }
199
+ throw new Error("Codex descendants did not settle within the managed cleanup bound");
200
+ }
201
+ }
@@ -23,6 +23,10 @@ export interface CodexToolItem {
23
23
  result?: unknown;
24
24
  error?: { message?: string } | string;
25
25
  query?: string;
26
+ receiverThreadIds?: string[];
27
+ prompt?: string | null;
28
+ model?: string | null;
29
+ agentsStates?: Record<string, { status: string; message?: string | null }>;
26
30
  }
27
31
 
28
32
  export interface CodexToolDescriptor {
@@ -60,6 +64,27 @@ function stringifyMcpResult(result: unknown): string {
60
64
  const failed = (item: CodexToolItem) => item.status === "failed";
61
65
 
62
66
  export const CODEX_TOOL_ITEMS: Record<string, CodexToolDescriptor> = {
67
+ collabAgentToolCall: {
68
+ toolName: (item) => item.tool ?? "collabAgentToolCall",
69
+ input: (item) => ({
70
+ ...(item.prompt != null && { prompt: item.prompt }),
71
+ ...(item.model != null && { model: item.model }),
72
+ receiverThreadIds: item.receiverThreadIds ?? [],
73
+ }),
74
+ meta: (item) => ({
75
+ kind: "task",
76
+ ...(item.tool === "spawnAgent" && {
77
+ subagent: {
78
+ ...(item.model && { model: item.model }),
79
+ ...(item.receiverThreadIds?.[0] && { agentId: item.receiverThreadIds[0] }),
80
+ },
81
+ }),
82
+ }),
83
+ result: (item) => ({
84
+ output: JSON.stringify(item.agentsStates ?? {}),
85
+ isError: failed(item) || item.status === "interrupted",
86
+ }),
87
+ },
63
88
  commandExecution: {
64
89
  toolName: () => "shell",
65
90
  input: (item) => ({ command: item.command ?? "" }),
@@ -104,6 +129,8 @@ export const CODEX_TOOL_ITEMS: Record<string, CodexToolDescriptor> = {
104
129
  /** Map either protocol's item-type spelling onto a descriptor. */
105
130
  export function codexToolDescriptor(itemType: string): CodexToolDescriptor | undefined {
106
131
  switch (itemType) {
132
+ case "collabAgentToolCall":
133
+ return CODEX_TOOL_ITEMS.collabAgentToolCall;
107
134
  case "command_execution":
108
135
  case "commandExecution":
109
136
  return CODEX_TOOL_ITEMS.commandExecution;
@@ -152,7 +152,10 @@ export class CodexSdkTransformer implements EventTransformer<unknown> {
152
152
  // single finalized snapshot below: pushing both part-open and part-update
153
153
  // for the same in-place-mutated object doubles the text, since the processor
154
154
  // clones each at emit time and by then both read as "done".
155
- if (isNew && phase !== "completed") events.push({ kind: "part-open", part });
155
+ // A copy: the processor snapshots at emit time, after the text set below,
156
+ // and a first sight that already carries text sends it as the delta.
157
+ if (isNew && phase !== "completed")
158
+ events.push({ kind: "part-open", part: structuredClone(part) });
156
159
 
157
160
  const text = item.text ?? "";
158
161
  const prevLen = this.textLenByItem.get(item.id) ?? 0;
@@ -216,26 +216,36 @@ export class CodexSdkAgent extends SessionAgent {
216
216
  const { events } = await live.thread.runStreamed(toCodexInput(input), {
217
217
  signal: controller.signal,
218
218
  });
219
- for await (const event of events as AsyncGenerator<ThreadEvent>) {
220
- if (event.type === "thread.started") {
221
- if (options.resumeSessionId && event.thread_id !== options.resumeSessionId) {
222
- // The SDK mutates Thread.id before yielding this event. Discard
223
- // that wrapper; the retained resume target remains unchanged.
224
- if (this.threads.get(options.sessionId) === live) this.threads.delete(options.sessionId);
225
- controller.abort();
226
- throw new SessionResumeError(
227
- options.resumeSessionId,
228
- `Codex returned a different thread: ${event.thread_id}`,
229
- );
230
- }
231
- if (!reported) {
232
- reported = true;
233
- options.onNativeSession?.(event.thread_id, {
234
- resumed: Boolean(options.resumeSessionId),
235
- });
219
+ // `codex exec` reports a fatal turn on its stream, then exits non-zero; the
220
+ // SDK throws for that exit with only stderr. Keep the reported cause.
221
+ let failure: string | undefined;
222
+ try {
223
+ for await (const event of events as AsyncGenerator<ThreadEvent>) {
224
+ if (event.type === "turn.failed") failure = event.error.message;
225
+ if (event.type === "thread.started") {
226
+ if (options.resumeSessionId && event.thread_id !== options.resumeSessionId) {
227
+ // The SDK mutates Thread.id before yielding this event. Discard
228
+ // that wrapper; the retained resume target remains unchanged.
229
+ if (this.threads.get(options.sessionId) === live)
230
+ this.threads.delete(options.sessionId);
231
+ controller.abort();
232
+ throw new SessionResumeError(
233
+ options.resumeSessionId,
234
+ `Codex returned a different thread: ${event.thread_id}`,
235
+ );
236
+ }
237
+ if (!reported) {
238
+ reported = true;
239
+ options.onNativeSession?.(event.thread_id, {
240
+ resumed: Boolean(options.resumeSessionId),
241
+ });
242
+ }
236
243
  }
244
+ yield event as RawAgentEvent;
237
245
  }
238
- yield event as RawAgentEvent;
246
+ } catch (error) {
247
+ if (failure === undefined || controller.signal.aborted) throw error;
248
+ throw new Error(failure, { cause: error });
239
249
  }
240
250
  }
241
251
 
@@ -21,6 +21,9 @@ export abstract class SessionAgent extends BaseAgent {
21
21
  ): AsyncIterableIterator<RawAgentEvent> {
22
22
  const { sessionId } = options;
23
23
  if (this.terminated) throw new Error("Agent has been terminated");
24
+ if (options.subagentMode && !this.capabilities.turnScopedSubagents) {
25
+ throw new Error(`${this.harness} does not support turn-scoped subagents`);
26
+ }
24
27
  if (this.activeSessions.has(sessionId)) throw new TurnActiveError(sessionId);
25
28
  this.activeSessions.add(sessionId);
26
29
  const controller = this.trackTurn(sessionId, options.signal);
@@ -27,15 +27,17 @@ export type CliTool = (typeof CLI_TOOLS)[number];
27
27
  * set `provision.pins.codex` to their SDK's vendored version.
28
28
  */
29
29
  export const DEFAULT_PINS: Record<CliTool, string> = {
30
- // Held at 0.3.220: the paired CLI (2.1.220) honors `--thinking-display
31
- // summarized`, so reasoning parts carry text. 2.1.233 ignores the flag and
32
- // streams token-estimate placeholders instead — bump only after verifying
33
- // thinking summaries still flow (see options.ts extraArgs).
34
- claude: "0.3.220",
35
- // 0.153.4 re-verified 2026-09-08 against generate-ts: host-managed
36
- // ChatGPT auth, thread/turn/item methods, token usage, and approvals
37
- // remain compatible. Astra requires CLI 0.153.0 or newer.
38
- codex: "0.153.4",
30
+ // 0.3.288 verified 2026-10-03: the paired CLI honors `--thinking-display
31
+ // summarized`, so reasoning parts carry text (2.1.233 ignored the flag and
32
+ // streamed token-estimate placeholders). Re-check thinking summaries on
33
+ // every bump (see options.ts extraArgs).
34
+ claude: "0.3.288",
35
+ // 0.160.0 re-verified 2026-10-03 against generate-ts: thread/turn/item
36
+ // methods, token usage, approvals, and host-managed ChatGPT auth changed
37
+ // only additively since 0.153.4. The GPT-6 family needs 0.159 or newer.
38
+ // Since 0.160 a thread has one writer: resuming it from a second process
39
+ // fails until the first releases it.
40
+ codex: "0.160.0",
39
41
  };
40
42
 
41
43
  /**
@@ -3,6 +3,7 @@ import {
3
3
  classifyError,
4
4
  isCancellation,
5
5
  isRecoverable,
6
+ readableErrorMessage,
6
7
  } from "../../protocol/errors.ts";
7
8
  import type {
8
9
  AgentCapabilities,
@@ -396,6 +397,7 @@ export class AgentRuntime {
396
397
  thinkingLevel: config.thinkingLevel,
397
398
  permissionMode: config.permissionMode,
398
399
  maxTurns: config.maxTurns,
400
+ subagentMode: config.subagentMode,
399
401
  systemPromptAppend: config.systemPromptAppend,
400
402
  resumeSessionId: config.resumeSessionId,
401
403
  resumeSessionAt: config.resumeSessionAt,
@@ -442,7 +444,7 @@ export class AgentRuntime {
442
444
  cancelled = isCancellation(err);
443
445
  if (!cancelled) {
444
446
  const category = classifyError(err);
445
- const message = err instanceof Error ? err.message : String(err);
447
+ const message = readableErrorMessage(err instanceof Error ? err.message : String(err));
446
448
  errored = { category, message };
447
449
  await emit({
448
450
  type: "error",
@@ -462,7 +464,10 @@ export class AgentRuntime {
462
464
  const result = transformer.finish();
463
465
  cancelled = cancelled || Boolean(result.cancelled);
464
466
  if (result.error && !errored && !cancelled) {
465
- errored = { category: classifyError(new Error(result.error)), message: result.error };
467
+ errored = {
468
+ category: classifyError(new Error(result.error)),
469
+ message: readableErrorMessage(result.error),
470
+ };
466
471
  }
467
472
  const stopReason: StopReason = cancelled
468
473
  ? "cancelled"
@@ -51,12 +51,14 @@ export const RunConfigSchema = z.object({
51
51
  cwd: z.string(),
52
52
  /**
53
53
  * Extra directories the agent may access beyond `cwd`. Mapped by the
54
- * claude-code and codex-sdk harnesses; codex-app-server and acp have no
55
- * native equivalent today and ignore it.
54
+ * claude-code and codex-sdk harnesses, and by acp for agents that advertise
55
+ * the capability; codex-app-server has no native equivalent and ignores it.
56
56
  */
57
57
  additionalDirectories: z.array(z.string()).optional(),
58
58
  systemPromptAppend: z.string().optional(),
59
59
  maxTurns: z.number().int().positive().optional(),
60
+ /** Native workers must settle before this managed execution releases its context. */
61
+ subagentMode: z.literal("turn").optional(),
60
62
  permissionMode: PermissionModeSchema.optional(),
61
63
  /**
62
64
  * Native session/thread id to resume (from a prior `session.created`). When
@@ -72,7 +72,15 @@ const RULES: ReadonlyArray<[ErrorCategory, readonly string[]]> = [
72
72
  ],
73
73
  [
74
74
  "invalid_request",
75
- ["invalid request", "invalid_request_error", "status 400", "http 400", "bad request"],
75
+ [
76
+ "invalid request",
77
+ "invalid_request_error",
78
+ "status 400",
79
+ "http 400",
80
+ "bad request",
81
+ // Claude Code's wording for an unknown or inaccessible model.
82
+ "issue with the selected model",
83
+ ],
76
84
  ],
77
85
  ["process_exit", ["exited with code", "process exited", "spawn", "enoent", "killed"]],
78
86
  ];
@@ -94,6 +102,27 @@ export function classifyError(error: unknown): ErrorCategory {
94
102
  return "internal";
95
103
  }
96
104
 
105
+ /**
106
+ * The message to show for a failure. Providers often answer with a JSON
107
+ * envelope (`{"error":{"message":…}}`), sometimes behind a transport prefix;
108
+ * its message is the readable part. Classify the raw text first: the envelope
109
+ * carries the status and error type the rules match on.
110
+ */
111
+ export function readableErrorMessage(message: string): string {
112
+ const start = message.indexOf("{");
113
+ if (start < 0) return message;
114
+ try {
115
+ const body = JSON.parse(message.slice(start)) as {
116
+ error?: { message?: unknown };
117
+ message?: unknown;
118
+ };
119
+ const inner = body.error?.message ?? body.message;
120
+ return typeof inner === "string" && inner ? inner : message;
121
+ } catch {
122
+ return message;
123
+ }
124
+ }
125
+
97
126
  /** Whether a turn can plausibly be retried after this error. */
98
127
  export function isRecoverable(category: ErrorCategory): boolean {
99
128
  return category === "rate_limit" || category === "network";
@@ -14,7 +14,7 @@
14
14
  import type { DecodedLifecycleEvent, UnknownEvent } from "./lifecycle.ts";
15
15
  import type { Part, UnknownPart } from "./parts.ts";
16
16
 
17
- export const PART_TYPES = ["text", "reasoning", "tool", "image", "file"] as const;
17
+ export const PART_TYPES = ["text", "reasoning", "tool", "subagent", "image", "file"] as const;
18
18
 
19
19
  export function isKnownPartType(type: unknown): type is (typeof PART_TYPES)[number] {
20
20
  return typeof type === "string" && (PART_TYPES as readonly string[]).includes(type);
@@ -46,5 +46,7 @@ export const AgentCapabilitiesSchema = z.object({
46
46
  mcpServers: z.boolean(),
47
47
  /** Can raise interactive `permission.requested` round-trips mid-turn. */
48
48
  permissionRequests: z.boolean(),
49
+ /** Supports native delegation contained within the current execution. */
50
+ turnScopedSubagents: z.boolean().optional(),
49
51
  });
50
52
  export type AgentCapabilities = z.infer<typeof AgentCapabilitiesSchema>;
@@ -1,5 +1,5 @@
1
1
  import type { AgentHarness } from "./harness.ts";
2
- import type { ThinkingLevel } from "./thinking.ts";
2
+ import { THINKING_LEVELS, type ThinkingLevel } from "./thinking.ts";
3
3
 
4
4
  /**
5
5
  * Advisory catalog of known-good models per harness. `model` on a RunConfig is
@@ -13,7 +13,16 @@ export interface ModelInfo {
13
13
  readonly thinking: readonly ThinkingLevel[];
14
14
  }
15
15
 
16
- const ALL: readonly ThinkingLevel[] = ["off", "low", "medium", "high", "xhigh"];
16
+ const ALL: readonly ThinkingLevel[] = THINKING_LEVELS;
17
+
18
+ // As listed by Codex CLI 0.160.0. The GPT-6 family needs CLI 0.159 or newer.
19
+ const CODEX_MODELS: ReadonlyArray<readonly [id: string, label: string]> = [
20
+ ["gpt-6.1-sol", "GPT-6.1 Sol"],
21
+ ["gpt-6-astra", "GPT-6 Astra"],
22
+ ["gpt-6-sol", "GPT-6 Sol"],
23
+ ["gpt-6-luna", "GPT-6 Luna"],
24
+ ["gpt-5.5", "GPT-5.5"],
25
+ ];
17
26
 
18
27
  export const MODEL_CATALOG: readonly ModelInfo[] = [
19
28
  // Claude (the claude CLI also accepts the bare aliases "sonnet"/"opus"/"haiku").
@@ -21,18 +30,23 @@ export const MODEL_CATALOG: readonly ModelInfo[] = [
21
30
  { id: "opus", harness: "claude-code", label: "Claude Opus (latest)", thinking: ALL },
22
31
  { id: "haiku", harness: "claude-code", label: "Claude Haiku (latest)", thinking: ALL },
23
32
  // Codex (shared between codex-sdk and codex-app-server).
24
- { id: "gpt-5.5", harness: "codex-sdk", label: "GPT-5.5", thinking: ALL },
25
- { id: "gpt-5.5-codex", harness: "codex-sdk", label: "GPT-5.5 Codex", thinking: ALL },
26
- { id: "gpt-5.5", harness: "codex-app-server", label: "GPT-5.5", thinking: ALL },
27
- { id: "gpt-5.5-codex", harness: "codex-app-server", label: "GPT-5.5 Codex", thinking: ALL },
33
+ ...CODEX_MODELS.flatMap(([id, label]) =>
34
+ (["codex-sdk", "codex-app-server"] as const).map((harness) => ({
35
+ id,
36
+ harness,
37
+ label,
38
+ thinking: ALL,
39
+ })),
40
+ ),
28
41
  ];
29
42
 
30
43
  /**
31
- * Default model per harness. `undefined` means "let the harness/CLI use its own
32
- * configured default" (Codex reads `~/.codex/config.toml`).
44
+ * The model a turn runs on when its config names none. `undefined` means the
45
+ * harness's CLI picks: Claude Code its own default for the account, Codex the
46
+ * one in `~/.codex/config.toml`. The engine never substitutes a model.
33
47
  */
34
48
  export const DEFAULT_MODELS: Record<AgentHarness, string | undefined> = {
35
- "claude-code": "sonnet",
49
+ "claude-code": undefined,
36
50
  "codex-sdk": undefined,
37
51
  "codex-app-server": undefined,
38
52
  // ACP v1 has no portable model parameter (selection is agent-defined via
@@ -81,6 +81,16 @@ export const ToolPartSchema = PartBase.extend({
81
81
  });
82
82
  export type ToolPart = z.infer<typeof ToolPartSchema>;
83
83
 
84
+ /** Native worker activity, including harnesses without a public spawning tool call. */
85
+ export const SubagentPartSchema = PartBase.extend({
86
+ type: z.literal("subagent"),
87
+ nativeActivityId: z.string(),
88
+ nativeThreadId: z.string(),
89
+ path: z.string().optional(),
90
+ activity: z.enum(["started", "interacted", "interrupted", "completed"]),
91
+ });
92
+ export type SubagentPart = z.infer<typeof SubagentPartSchema>;
93
+
84
94
  /**
85
95
  * Exactly one of `data` (base64) | `url` — ENFORCED, not merely documented: a
86
96
  * payload-less blob part renders as a broken image, and one carrying both
@@ -112,6 +122,7 @@ export const PartSchema = z.discriminatedUnion("type", [
112
122
  TextPartSchema,
113
123
  ReasoningPartSchema,
114
124
  ToolPartSchema,
125
+ SubagentPartSchema,
115
126
  ImagePartSchema,
116
127
  FilePartSchema,
117
128
  ]);
@@ -3,9 +3,10 @@ import { z } from "zod";
3
3
  /**
4
4
  * A single, harness-agnostic reasoning dial. Each harness maps it to its own
5
5
  * native control: Claude -> adaptive `thinking` + `effort`; Codex ->
6
- * `ReasoningEffort`.
6
+ * `ReasoningEffort`. The top levels depend on the model: Claude's ceiling is
7
+ * `max` (it runs `ultra` as `max`), and not every Codex model offers `ultra`.
7
8
  */
8
- export const THINKING_LEVELS = ["off", "low", "medium", "high", "xhigh"] as const;
9
+ export const THINKING_LEVELS = ["off", "low", "medium", "high", "xhigh", "max", "ultra"] as const;
9
10
  export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
10
11
  export const ThinkingLevelSchema = z.enum(THINKING_LEVELS);
11
12
  export const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
@@ -15,7 +16,14 @@ export function isThinkingLevel(v: string): v is ThinkingLevel {
15
16
  }
16
17
 
17
18
  /** Codex reasoning-effort string for a level (matches the `ReasoningEffort` enum). */
18
- export type CodexReasoningEffort = "minimal" | "low" | "medium" | "high" | "xhigh";
19
+ export type CodexReasoningEffort =
20
+ | "minimal"
21
+ | "low"
22
+ | "medium"
23
+ | "high"
24
+ | "xhigh"
25
+ | "max"
26
+ | "ultra";
19
27
  export function codexReasoningEffort(level: ThinkingLevel): CodexReasoningEffort {
20
28
  switch (level) {
21
29
  case "off":
@@ -28,5 +36,9 @@ export function codexReasoningEffort(level: ThinkingLevel): CodexReasoningEffort
28
36
  return "high";
29
37
  case "xhigh":
30
38
  return "xhigh";
39
+ case "max":
40
+ return "max";
41
+ case "ultra":
42
+ return "ultra";
31
43
  }
32
44
  }