@zvada/agent-server 0.3.15 → 0.3.17
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 +52 -0
- package/README.md +1 -0
- package/docs/consuming.md +24 -0
- package/docs/harnesses.md +68 -11
- package/package.json +1 -1
- package/src/client/client.ts +23 -0
- package/src/core/agents/base.ts +37 -0
- package/src/core/agents/claude-code/claude-agent.ts +28 -3
- package/src/core/agents/claude-code/generator-session.ts +11 -1
- package/src/core/agents/claude-code/models.ts +76 -0
- package/src/core/agents/codex-app-server/adapter.ts +31 -3
- package/src/core/agents/codex-app-server/codex-app-server-agent.ts +122 -70
- package/src/core/agents/codex-app-server/models.ts +177 -0
- package/src/core/agents/codex-sdk/adapter.ts +45 -15
- package/src/core/agents/codex-sdk/codex-sdk-agent.ts +69 -7
- package/src/core/agents/thinking-levels.ts +9 -0
- package/src/core/agents/types.ts +2 -1
- package/src/core/index.ts +4 -1
- package/src/core/provision/pins.ts +4 -2
- package/src/core/runtime/agent-runtime.ts +47 -7
- package/src/core/runtime/event-processor.ts +34 -6
- package/src/core/runtime/model-lists.ts +204 -0
- package/src/protocol/execution.ts +8 -2
- package/src/protocol/model-catalog.ts +220 -0
- package/src/protocol/models.ts +95 -49
- package/src/protocol/wire.ts +24 -1
- package/src/server/agent-server.ts +17 -0
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
import type { Codex, Thread, ThreadEvent, ThreadOptions } from "@openai/codex-sdk";
|
|
2
|
-
import type {
|
|
2
|
+
import type {
|
|
3
|
+
AgentCapabilities,
|
|
4
|
+
AgentInput,
|
|
5
|
+
ModelDescriptor,
|
|
6
|
+
PermissionMode,
|
|
7
|
+
} from "../../../protocol/index.ts";
|
|
3
8
|
import { codexReasoningEffort, modelThinkingLevels } from "../../../protocol/index.ts";
|
|
4
9
|
import { SessionResumeError } from "../../utils/errors.ts";
|
|
5
|
-
import type { AgentExecuteOptions, RawAgentEvent } from "../base.ts";
|
|
10
|
+
import type { AgentExecuteOptions, ListModelsOptions, RawAgentEvent } from "../base.ts";
|
|
11
|
+
import {
|
|
12
|
+
codexModelDescriptors,
|
|
13
|
+
codexThinkingLevel,
|
|
14
|
+
listCodexModels,
|
|
15
|
+
} from "../codex-app-server/models.ts";
|
|
6
16
|
import { configFingerprint } from "../config-fingerprint.ts";
|
|
7
17
|
import { SessionAgent } from "../session-agent.ts";
|
|
18
|
+
import { type CodexExecUsage, USAGE_BASELINE_EVENT } from "./adapter.ts";
|
|
8
19
|
|
|
9
20
|
const CAPABILITIES: AgentCapabilities = {
|
|
10
21
|
multiTurn: true,
|
|
@@ -23,6 +34,10 @@ export interface LiveThread {
|
|
|
23
34
|
codexPathOverride?: string;
|
|
24
35
|
model?: string;
|
|
25
36
|
thinkingLevel?: string;
|
|
37
|
+
/** The effort the thread was started with; `codex exec` keeps it for the thread's life. */
|
|
38
|
+
effort?: string;
|
|
39
|
+
/** The thread's usage totals after its last turn; absent or `null` when unknown. */
|
|
40
|
+
usage?: CodexExecUsage | null;
|
|
26
41
|
cwd: string;
|
|
27
42
|
permissionMode?: PermissionMode;
|
|
28
43
|
credentialsFingerprint: string;
|
|
@@ -113,11 +128,13 @@ export function threadOptions(options: AgentExecuteOptions): ThreadOptions {
|
|
|
113
128
|
: {}),
|
|
114
129
|
};
|
|
115
130
|
if (options.model) opts.model = options.model;
|
|
116
|
-
// `codex exec` cannot list models
|
|
131
|
+
// `codex exec` cannot list models: the engine's list (or the catalog) says
|
|
132
|
+
// what a model accepts.
|
|
117
133
|
if (options.thinkingLevel)
|
|
118
134
|
opts.modelReasoningEffort = codexReasoningEffort(
|
|
119
135
|
options.thinkingLevel,
|
|
120
|
-
options.
|
|
136
|
+
options.modelThinking ??
|
|
137
|
+
(options.model ? modelThinkingLevels("codex-sdk", options.model) : undefined),
|
|
121
138
|
"minimal",
|
|
122
139
|
);
|
|
123
140
|
return opts;
|
|
@@ -192,14 +209,18 @@ export class CodexSdkAgent extends SessionAgent {
|
|
|
192
209
|
if (signal?.aborted) throw new Error("turn aborted");
|
|
193
210
|
const fingerprint = credentialsFingerprint(options);
|
|
194
211
|
const resumeThreadId = options.resumeSessionId;
|
|
212
|
+
const settings = threadOptions(options);
|
|
195
213
|
const thread = resumeThreadId
|
|
196
|
-
? codex.resumeThread(resumeThreadId,
|
|
197
|
-
: codex.startThread(
|
|
214
|
+
? codex.resumeThread(resumeThreadId, settings)
|
|
215
|
+
: codex.startThread(settings);
|
|
198
216
|
const live: LiveThread = {
|
|
199
217
|
thread,
|
|
200
218
|
codexPathOverride,
|
|
201
219
|
model: options.model,
|
|
202
220
|
thinkingLevel: effort,
|
|
221
|
+
effort: settings.modelReasoningEffort,
|
|
222
|
+
// A thread restarted here keeps its totals; one resumed from elsewhere has unknown ones.
|
|
223
|
+
usage: !resumeThreadId ? {} : existing?.thread.id === resumeThreadId ? existing.usage : null,
|
|
203
224
|
cwd: options.cwd,
|
|
204
225
|
permissionMode: options.permissionMode,
|
|
205
226
|
credentialsFingerprint: fingerprint,
|
|
@@ -218,16 +239,28 @@ export class CodexSdkAgent extends SessionAgent {
|
|
|
218
239
|
controller.signal.throwIfAborted();
|
|
219
240
|
const live = await this.resolveThread(options, controller.signal);
|
|
220
241
|
controller.signal.throwIfAborted();
|
|
242
|
+
// Codex runs the effort it is given.
|
|
243
|
+
const applied = codexThinkingLevel(live.effort);
|
|
244
|
+
if (applied) options.onExecution?.({ thinkingLevel: applied });
|
|
221
245
|
let reported = false;
|
|
222
246
|
const { events } = await live.thread.runStreamed(toCodexInput(input), {
|
|
223
247
|
signal: controller.signal,
|
|
224
248
|
});
|
|
249
|
+
let baselineSent = false;
|
|
250
|
+
let completed = false;
|
|
225
251
|
// `codex exec` reports a fatal turn on its stream, then exits non-zero; the
|
|
226
252
|
// SDK throws for that exit with only stderr. Keep the reported cause.
|
|
227
253
|
let failure: string | undefined;
|
|
228
254
|
try {
|
|
229
255
|
for await (const event of events as AsyncGenerator<ThreadEvent>) {
|
|
230
|
-
if (event.type === "turn.failed")
|
|
256
|
+
if (event.type === "turn.failed") {
|
|
257
|
+
failure = event.error.message;
|
|
258
|
+
live.usage = null;
|
|
259
|
+
}
|
|
260
|
+
if (event.type === "turn.completed") {
|
|
261
|
+
completed = true;
|
|
262
|
+
live.usage = event.usage;
|
|
263
|
+
}
|
|
231
264
|
if (event.type === "thread.started") {
|
|
232
265
|
if (options.resumeSessionId && event.thread_id !== options.resumeSessionId) {
|
|
233
266
|
// The SDK mutates Thread.id before yielding this event. Discard
|
|
@@ -247,14 +280,43 @@ export class CodexSdkAgent extends SessionAgent {
|
|
|
247
280
|
});
|
|
248
281
|
}
|
|
249
282
|
}
|
|
283
|
+
if (!baselineSent) {
|
|
284
|
+
baselineSent = true;
|
|
285
|
+
// `codex exec` reports thread totals; the adapter needs the turn's
|
|
286
|
+
// starting point. Sent with the first event, so nothing precedes it.
|
|
287
|
+
yield { type: USAGE_BASELINE_EVENT, usage: live.usage ?? null } as RawAgentEvent;
|
|
288
|
+
}
|
|
250
289
|
yield event as RawAgentEvent;
|
|
251
290
|
}
|
|
252
291
|
} catch (error) {
|
|
253
292
|
if (failure === undefined || controller.signal.aborted) throw error;
|
|
254
293
|
throw new Error(failure, { cause: error });
|
|
294
|
+
} finally {
|
|
295
|
+
// A turn that started and did not complete (cancelled, or the CLI died)
|
|
296
|
+
// may have spent tokens the thread's totals now include, unseen here.
|
|
297
|
+
if (baselineSent && !completed) live.usage = null;
|
|
255
298
|
}
|
|
256
299
|
}
|
|
257
300
|
|
|
301
|
+
/**
|
|
302
|
+
* The models Codex offers the CLI's stored login (its built-in list when
|
|
303
|
+
* logged out), from `codex app-server`: `codex exec` cannot list them, and
|
|
304
|
+
* the app-server ignores the `CODEX_API_KEY` a turn's `apiKey` becomes.
|
|
305
|
+
*/
|
|
306
|
+
async listModels(options: ListModelsOptions): Promise<ModelDescriptor[]> {
|
|
307
|
+
const codexPath =
|
|
308
|
+
(await this.agentOptions.resolveCliPath?.()) ?? process.env.CODEX_CLI_PATH ?? "codex";
|
|
309
|
+
const listing = await listCodexModels(
|
|
310
|
+
{
|
|
311
|
+
codexPath,
|
|
312
|
+
cwd: options.cwd,
|
|
313
|
+
env: options.env ? ({ ...process.env, ...options.env } as NodeJS.ProcessEnv) : process.env,
|
|
314
|
+
},
|
|
315
|
+
{ signal: options.signal },
|
|
316
|
+
);
|
|
317
|
+
return codexModelDescriptors(listing.models, this.harness, listing.configuredModel);
|
|
318
|
+
}
|
|
319
|
+
|
|
258
320
|
override async release(sessionId: string): Promise<void> {
|
|
259
321
|
await super.release(sessionId);
|
|
260
322
|
this.threads.delete(sessionId);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { THINKING_LEVELS, type ThinkingLevel, isThinkingLevel } from "../../protocol/index.ts";
|
|
2
|
+
|
|
3
|
+
/** The values that are thinking levels, once each, lowest first. */
|
|
4
|
+
export function knownThinkingLevels(values: Iterable<unknown>): ThinkingLevel[] {
|
|
5
|
+
const levels = new Set<ThinkingLevel>();
|
|
6
|
+
for (const value of values)
|
|
7
|
+
if (typeof value === "string" && isThinkingLevel(value)) levels.add(value);
|
|
8
|
+
return THINKING_LEVELS.filter((level) => levels.has(level));
|
|
9
|
+
}
|
package/src/core/agents/types.ts
CHANGED
|
@@ -31,7 +31,8 @@ export type AdapterEvent =
|
|
|
31
31
|
|
|
32
32
|
/** Terminal result of a turn, surfaced on `turn.ended`. */
|
|
33
33
|
export interface TransformResult {
|
|
34
|
-
usage
|
|
34
|
+
/** This turn's usage. Absent when the harness cannot tell it apart from earlier turns. */
|
|
35
|
+
usage?: TokenUsage;
|
|
35
36
|
/** Models observed on the primary run, excluding subagents and configured defaults. */
|
|
36
37
|
reportedModels?: string[];
|
|
37
38
|
/** Normalized terminal status, when the harness reported one. The engine
|
package/src/core/index.ts
CHANGED
|
@@ -9,13 +9,16 @@ export {
|
|
|
9
9
|
CollectingSink,
|
|
10
10
|
teeSink,
|
|
11
11
|
} from "./runtime/event-sink.ts";
|
|
12
|
-
export { EventProcessor } from "./runtime/event-processor.ts";
|
|
12
|
+
export { EventProcessor, endedExecution } from "./runtime/event-processor.ts";
|
|
13
|
+
export { type ModelsQuery, catalogModelList } from "./runtime/model-lists.ts";
|
|
13
14
|
|
|
14
15
|
// Agent abstraction
|
|
15
16
|
export {
|
|
16
17
|
type Agent,
|
|
17
18
|
type AgentExecuteOptions,
|
|
19
|
+
type AppliedExecution,
|
|
18
20
|
type CancelResult,
|
|
21
|
+
type ListModelsOptions,
|
|
19
22
|
type RawAgentEvent,
|
|
20
23
|
BaseAgent,
|
|
21
24
|
} from "./agents/base.ts";
|
|
@@ -25,6 +25,9 @@ export type CliTool = (typeof CLI_TOOLS)[number];
|
|
|
25
25
|
* pair). The pin governs downloads (compiled binaries / bare sandboxes /
|
|
26
26
|
* `pinned` mode); embedders wanting an exact codex-sdk pairing there can
|
|
27
27
|
* set `provision.pins.codex` to their SDK's vendored version.
|
|
28
|
+
*
|
|
29
|
+
* After any bump, run `bun run models:refresh`: the model catalog records the
|
|
30
|
+
* versions that listed it, and a test fails until it matches these pins.
|
|
28
31
|
*/
|
|
29
32
|
export const DEFAULT_PINS: Record<CliTool, string> = {
|
|
30
33
|
// 0.3.288 verified 2026-10-03: the paired CLI honors `--thinking-display
|
|
@@ -36,8 +39,7 @@ export const DEFAULT_PINS: Record<CliTool, string> = {
|
|
|
36
39
|
// methods, token usage, approvals, and host-managed ChatGPT auth changed
|
|
37
40
|
// only additively since 0.153.4. The GPT-6 family needs 0.159 or newer.
|
|
38
41
|
// Since 0.160 a thread has one writer: resuming it from a second process
|
|
39
|
-
// fails until the first releases it.
|
|
40
|
-
// and update MODEL_CATALOG's Codex models and thinking levels.
|
|
42
|
+
// fails until the first releases it.
|
|
41
43
|
codex: "0.160.0",
|
|
42
44
|
};
|
|
43
45
|
|
|
@@ -9,6 +9,7 @@ import type {
|
|
|
9
9
|
AgentCapabilities,
|
|
10
10
|
AgentHarness,
|
|
11
11
|
LifecycleEvent,
|
|
12
|
+
ModelList,
|
|
12
13
|
PermissionOption,
|
|
13
14
|
PermissionOutcome,
|
|
14
15
|
PermissionToolCall,
|
|
@@ -18,12 +19,18 @@ import type {
|
|
|
18
19
|
TurnExecution,
|
|
19
20
|
} from "../../protocol/index.ts";
|
|
20
21
|
import { DEFAULT_TOKEN_USAGE, generateUUIDv7 } from "../../protocol/index.ts";
|
|
21
|
-
import type {
|
|
22
|
+
import type {
|
|
23
|
+
AgentExecuteOptions,
|
|
24
|
+
AppliedExecution,
|
|
25
|
+
CancelResult,
|
|
26
|
+
PermissionDecision,
|
|
27
|
+
} from "../agents/base.ts";
|
|
22
28
|
import type { AgentRegistry } from "../agents/registry.ts";
|
|
23
29
|
import { type DiagnosticHandler, emitDiagnostic } from "../diagnostics.ts";
|
|
24
30
|
import { TurnConflictError } from "../utils/errors.ts";
|
|
25
|
-
import { EventProcessor } from "./event-processor.ts";
|
|
31
|
+
import { EventProcessor, endedExecution } from "./event-processor.ts";
|
|
26
32
|
import type { EventSink } from "./event-sink.ts";
|
|
33
|
+
import { ModelLists, type ModelsQuery } from "./model-lists.ts";
|
|
27
34
|
|
|
28
35
|
/** What a completed turn reports back to the caller (in addition to the streamed events). */
|
|
29
36
|
export interface RunSummary {
|
|
@@ -115,6 +122,7 @@ export class AgentRuntime {
|
|
|
115
122
|
/** Per-session convergence window; old turns fall out and a stale retry would re-execute. */
|
|
116
123
|
private static readonly COMPLETED_TURN_MEMORY = 16;
|
|
117
124
|
private shutdownPromise?: Promise<void>;
|
|
125
|
+
private readonly modelLists = new ModelLists();
|
|
118
126
|
|
|
119
127
|
constructor(
|
|
120
128
|
private readonly registry: AgentRegistry,
|
|
@@ -129,6 +137,17 @@ export class AgentRuntime {
|
|
|
129
137
|
return this.registry.getAgent(harness).capabilities;
|
|
130
138
|
}
|
|
131
139
|
|
|
140
|
+
/**
|
|
141
|
+
* The models a harness offers, read from its CLI for the login and folder a
|
|
142
|
+
* turn with the same `cwd`, `env` and `apiKey` would use, and cached. Never
|
|
143
|
+
* rejects for a registered harness: without a live list it returns the
|
|
144
|
+
* catalog, with `error` saying why. Turns then fit their thinking level to
|
|
145
|
+
* the listed levels of the model they run.
|
|
146
|
+
*/
|
|
147
|
+
async models(query: ModelsQuery): Promise<ModelList> {
|
|
148
|
+
return await this.modelLists.get(this.registry.getAgent(query.harness), query);
|
|
149
|
+
}
|
|
150
|
+
|
|
132
151
|
/**
|
|
133
152
|
* Answer a pending `permission.requested` event. Returns false when the
|
|
134
153
|
* request is unknown (already resolved, cancelled, or a sessionId mismatch).
|
|
@@ -248,6 +267,20 @@ export class AgentRuntime {
|
|
|
248
267
|
...(config.thinkingLevel !== undefined && { thinkingLevel: config.thinkingLevel }),
|
|
249
268
|
};
|
|
250
269
|
const processor = new EventProcessor(sessionId, turnId, execution);
|
|
270
|
+
const modelThinking =
|
|
271
|
+
config.model !== undefined
|
|
272
|
+
? this.modelLists.thinkingFor(
|
|
273
|
+
{
|
|
274
|
+
harness: config.harness,
|
|
275
|
+
cwd: config.cwd,
|
|
276
|
+
sessionId,
|
|
277
|
+
env: config.env,
|
|
278
|
+
apiKey: config.apiKey,
|
|
279
|
+
},
|
|
280
|
+
config.model,
|
|
281
|
+
)
|
|
282
|
+
: undefined;
|
|
283
|
+
let applied: AppliedExecution | undefined;
|
|
251
284
|
|
|
252
285
|
// Isolate sink failures: a misbehaving transport must never break the
|
|
253
286
|
// turn's lifecycle bracketing (turn.started ... turn.ended).
|
|
@@ -406,6 +439,7 @@ export class AgentRuntime {
|
|
|
406
439
|
env: config.env,
|
|
407
440
|
apiKey: config.apiKey,
|
|
408
441
|
disableTools: config.disableTools,
|
|
442
|
+
...(modelThinking && { modelThinking }),
|
|
409
443
|
signal: opts.signal,
|
|
410
444
|
onNativeSession: (id, info) => {
|
|
411
445
|
// Agents report once the native conversation is confirmed; guard against a
|
|
@@ -417,6 +451,9 @@ export class AgentRuntime {
|
|
|
417
451
|
if (config.resumeSessionId && info?.resumed !== undefined) resumed = info.resumed;
|
|
418
452
|
},
|
|
419
453
|
onPermissionRequest: requestPermission,
|
|
454
|
+
onExecution: (update) => {
|
|
455
|
+
applied = { ...applied, ...update };
|
|
456
|
+
},
|
|
420
457
|
};
|
|
421
458
|
|
|
422
459
|
let cancelled = false;
|
|
@@ -474,7 +511,13 @@ export class AgentRuntime {
|
|
|
474
511
|
: errored
|
|
475
512
|
? "error"
|
|
476
513
|
: (result.stopReason ?? "end_turn");
|
|
477
|
-
|
|
514
|
+
// What the harness configured ran only if its model answered: a turn that
|
|
515
|
+
// failed or was cancelled first ran nothing.
|
|
516
|
+
const ran =
|
|
517
|
+
processor.modelAnswered || (stopReason !== "error" && stopReason !== "cancelled")
|
|
518
|
+
? applied
|
|
519
|
+
: undefined;
|
|
520
|
+
for (const le of processor.finish(result, stopReason, errored, ran)) await emit(le);
|
|
478
521
|
|
|
479
522
|
return {
|
|
480
523
|
sessionId,
|
|
@@ -483,10 +526,7 @@ export class AgentRuntime {
|
|
|
483
526
|
nativeSessionId,
|
|
484
527
|
...(resumed !== undefined && { resumed }),
|
|
485
528
|
usage: result.usage ?? DEFAULT_TOKEN_USAGE,
|
|
486
|
-
execution:
|
|
487
|
-
...execution,
|
|
488
|
-
...(result.reportedModels && { reportedModels: result.reportedModels }),
|
|
489
|
-
},
|
|
529
|
+
execution: endedExecution(execution, result, ran),
|
|
490
530
|
stopReason,
|
|
491
531
|
finishReason: result.finishReason,
|
|
492
532
|
cost: result.cost,
|
|
@@ -13,8 +13,32 @@ import type {
|
|
|
13
13
|
StopReason,
|
|
14
14
|
TurnExecution,
|
|
15
15
|
} from "../../protocol/index.ts";
|
|
16
|
+
import type { AppliedExecution } from "../agents/base.ts";
|
|
16
17
|
import type { AdapterEvent, TransformResult } from "../agents/types.ts";
|
|
17
18
|
|
|
19
|
+
/**
|
|
20
|
+
* The execution `turn.ended` carries: the request, plus what the harness said
|
|
21
|
+
* it ran. Models the stream reported (Claude's API model, a Codex reroute) say
|
|
22
|
+
* what answered; the model the agent reported for its thread fills in
|
|
23
|
+
* otherwise. Pass `applied` only for a turn whose model ran.
|
|
24
|
+
*/
|
|
25
|
+
export function endedExecution(
|
|
26
|
+
execution: TurnExecution,
|
|
27
|
+
result: Pick<TransformResult, "reportedModels">,
|
|
28
|
+
applied?: AppliedExecution,
|
|
29
|
+
): TurnExecution {
|
|
30
|
+
const reportedModels = result.reportedModels?.length
|
|
31
|
+
? result.reportedModels
|
|
32
|
+
: applied?.model
|
|
33
|
+
? [applied.model]
|
|
34
|
+
: [];
|
|
35
|
+
return {
|
|
36
|
+
...execution,
|
|
37
|
+
...(applied?.thinkingLevel !== undefined && { appliedThinkingLevel: applied.thinkingLevel }),
|
|
38
|
+
...(reportedModels.length > 0 && { reportedModels }),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
18
42
|
/** Where a part lives on the wire — fixed at first emission for the whole turn. */
|
|
19
43
|
interface PartAddress {
|
|
20
44
|
messageId: string;
|
|
@@ -37,6 +61,8 @@ export class EventProcessor {
|
|
|
37
61
|
/** `parentToolCallId` of the open message (undefined for top-level messages). */
|
|
38
62
|
private openMessageParent?: string;
|
|
39
63
|
private currentOutputIndex = -1;
|
|
64
|
+
/** Whether the harness produced any output this turn (its model answered). */
|
|
65
|
+
private answered = false;
|
|
40
66
|
private nextOutputIndex = 0;
|
|
41
67
|
private nextPartIndex = 0;
|
|
42
68
|
private readonly partAddressById = new Map<string, PartAddress>();
|
|
@@ -123,6 +149,11 @@ export class EventProcessor {
|
|
|
123
149
|
}
|
|
124
150
|
}
|
|
125
151
|
|
|
152
|
+
/** Whether the harness produced output this turn, so its model ran. */
|
|
153
|
+
get modelAnswered(): boolean {
|
|
154
|
+
return this.answered;
|
|
155
|
+
}
|
|
156
|
+
|
|
126
157
|
/** Preserve the runtime's classified error; standalone callers can use the adapter text. */
|
|
127
158
|
*finish(
|
|
128
159
|
result: TransformResult,
|
|
@@ -130,6 +161,7 @@ export class EventProcessor {
|
|
|
130
161
|
error: ErrorInfo | undefined = result.error && !result.cancelled && stopReason !== "cancelled"
|
|
131
162
|
? { category: classifyError(result.error), message: result.error }
|
|
132
163
|
: undefined,
|
|
164
|
+
applied?: AppliedExecution,
|
|
133
165
|
): Generator<LifecycleEvent> {
|
|
134
166
|
yield* this.closeMessage();
|
|
135
167
|
yield {
|
|
@@ -140,12 +172,7 @@ export class EventProcessor {
|
|
|
140
172
|
finishReason: result.finishReason,
|
|
141
173
|
tokens: result.usage,
|
|
142
174
|
cost: result.cost,
|
|
143
|
-
...(this.execution && {
|
|
144
|
-
execution: {
|
|
145
|
-
...this.execution,
|
|
146
|
-
...(result.reportedModels && { reportedModels: result.reportedModels }),
|
|
147
|
-
},
|
|
148
|
-
}),
|
|
175
|
+
...(this.execution && { execution: endedExecution(this.execution, result, applied) }),
|
|
149
176
|
error,
|
|
150
177
|
timestamp: Date.now(),
|
|
151
178
|
};
|
|
@@ -158,6 +185,7 @@ export class EventProcessor {
|
|
|
158
185
|
id?: string,
|
|
159
186
|
): Generator<LifecycleEvent> {
|
|
160
187
|
if (this.openMessageId) yield* this.closeMessage();
|
|
188
|
+
if (role === "assistant") this.answered = true;
|
|
161
189
|
const messageId = id ?? generateUUIDv7();
|
|
162
190
|
this.openMessageId = messageId;
|
|
163
191
|
this.openMessageParent = parentToolCallId;
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AgentHarness,
|
|
3
|
+
CATALOG_MODELS,
|
|
4
|
+
type ModelDescriptor,
|
|
5
|
+
type ModelList,
|
|
6
|
+
type ThinkingLevel,
|
|
7
|
+
} from "../../protocol/index.ts";
|
|
8
|
+
import type { Agent } from "../agents/base.ts";
|
|
9
|
+
|
|
10
|
+
/** Whose models to list: the login and folder a turn with the same config would use. */
|
|
11
|
+
export interface ModelsQuery {
|
|
12
|
+
harness: AgentHarness;
|
|
13
|
+
/** The folder whose settings apply. Defaults to the process's working directory. */
|
|
14
|
+
cwd?: string;
|
|
15
|
+
/** List with this session's credentials (host-managed Codex auth resolves per session). */
|
|
16
|
+
sessionId?: string;
|
|
17
|
+
env?: Record<string, string>;
|
|
18
|
+
apiKey?: string;
|
|
19
|
+
/** Read the CLI again instead of the cache, e.g. after the user logs in. */
|
|
20
|
+
refresh?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A live list is reused this long. Logins change outside agent-server; `refresh` reads sooner. */
|
|
24
|
+
const LIVE_TTL_MS = 10 * 60_000;
|
|
25
|
+
/** A failed read is reused this long, so a logged-out CLI is not started on every call. */
|
|
26
|
+
const FAILURE_TTL_MS = 30_000;
|
|
27
|
+
/** A read that takes longer falls back to the catalog, inside a client's 30 s request deadline. */
|
|
28
|
+
const LIST_TIMEOUT_MS = 20_000;
|
|
29
|
+
/** Distinct folders/credentials remembered; the oldest is dropped first. */
|
|
30
|
+
const MAX_ENTRIES = 64;
|
|
31
|
+
|
|
32
|
+
interface Entry {
|
|
33
|
+
list: ModelList;
|
|
34
|
+
expiresAt: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface Read {
|
|
38
|
+
generation: number;
|
|
39
|
+
refresh: boolean;
|
|
40
|
+
list: Promise<ModelList>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The catalog's models for a harness, as a list (`source: "catalog"`). */
|
|
44
|
+
export function catalogModelList(harness: AgentHarness, fetchedAt = Date.now()): ModelList {
|
|
45
|
+
return {
|
|
46
|
+
harness,
|
|
47
|
+
models: CATALOG_MODELS.filter((model) => model.harness === harness),
|
|
48
|
+
source: "catalog",
|
|
49
|
+
fetchedAt,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** An alias (Claude `opus`, `default`) runs a model that depends on the account. */
|
|
54
|
+
const isAlias = (model: ModelDescriptor) => model.resolvedId !== undefined;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Model lists per harness, login and folder. Concurrent reads of one key share
|
|
58
|
+
* a single CLI read, and a result is stored only if no newer read started
|
|
59
|
+
* meanwhile, so a slow stale read cannot replace a refresh. A failed read keeps
|
|
60
|
+
* the last live list (with the error) rather than falling back to the catalog.
|
|
61
|
+
*/
|
|
62
|
+
export class ModelLists {
|
|
63
|
+
private readonly entries = new Map<string, Entry>();
|
|
64
|
+
private readonly reads = new Map<string, Read>();
|
|
65
|
+
private generation = 0;
|
|
66
|
+
|
|
67
|
+
constructor(private readonly options: { now?: () => number; timeoutMs?: number } = {}) {}
|
|
68
|
+
|
|
69
|
+
private now(): number {
|
|
70
|
+
return this.options.now?.() ?? Date.now();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private key(
|
|
74
|
+
harness: AgentHarness,
|
|
75
|
+
cwd: string,
|
|
76
|
+
sessionId: string | undefined,
|
|
77
|
+
query: Pick<ModelsQuery, "apiKey" | "env">,
|
|
78
|
+
): string {
|
|
79
|
+
return JSON.stringify([
|
|
80
|
+
harness,
|
|
81
|
+
cwd,
|
|
82
|
+
sessionId ?? null,
|
|
83
|
+
query.apiKey ?? null,
|
|
84
|
+
query.env ? Object.entries(query.env).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) : null,
|
|
85
|
+
]);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
get(agent: Agent, query: ModelsQuery): Promise<ModelList> {
|
|
89
|
+
const listModels = agent.listModels?.bind(agent);
|
|
90
|
+
if (!listModels) return Promise.resolve(catalogModelList(query.harness, this.now()));
|
|
91
|
+
const cwd = query.cwd ?? globalThis.process?.cwd?.() ?? "/";
|
|
92
|
+
// Only a harness whose credentials follow the session lists per session.
|
|
93
|
+
const key = this.key(
|
|
94
|
+
query.harness,
|
|
95
|
+
cwd,
|
|
96
|
+
agent.modelsPerSession ? query.sessionId : undefined,
|
|
97
|
+
query,
|
|
98
|
+
);
|
|
99
|
+
const pending = this.reads.get(key);
|
|
100
|
+
if (query.refresh) {
|
|
101
|
+
if (pending?.refresh) return pending.list;
|
|
102
|
+
} else {
|
|
103
|
+
const entry = this.entries.get(key);
|
|
104
|
+
if (entry && entry.expiresAt > this.now()) return Promise.resolve(entry.list);
|
|
105
|
+
if (pending) return pending.list;
|
|
106
|
+
}
|
|
107
|
+
const generation = ++this.generation;
|
|
108
|
+
const list = this.read(query.harness, (signal) =>
|
|
109
|
+
listModels({
|
|
110
|
+
cwd,
|
|
111
|
+
...(query.sessionId !== undefined && { sessionId: query.sessionId }),
|
|
112
|
+
...(query.env !== undefined && { env: query.env }),
|
|
113
|
+
...(query.apiKey !== undefined && { apiKey: query.apiKey }),
|
|
114
|
+
signal,
|
|
115
|
+
}),
|
|
116
|
+
).then((read) => {
|
|
117
|
+
const previous = this.entries.get(key)?.list;
|
|
118
|
+
const result: ModelList =
|
|
119
|
+
read.source === "catalog" && previous?.source === "live"
|
|
120
|
+
? { ...previous, ...(read.error !== undefined && { error: read.error }) }
|
|
121
|
+
: read;
|
|
122
|
+
if (this.reads.get(key)?.generation === generation) {
|
|
123
|
+
this.reads.delete(key);
|
|
124
|
+
this.entries.delete(key);
|
|
125
|
+
this.entries.set(key, {
|
|
126
|
+
list: result,
|
|
127
|
+
expiresAt: this.now() + (read.source === "live" ? LIVE_TTL_MS : FAILURE_TTL_MS),
|
|
128
|
+
});
|
|
129
|
+
while (this.entries.size > MAX_ENTRIES) {
|
|
130
|
+
const oldest = this.entries.keys().next().value;
|
|
131
|
+
if (oldest === undefined) break;
|
|
132
|
+
this.entries.delete(oldest);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return result;
|
|
136
|
+
});
|
|
137
|
+
this.reads.set(key, { generation, refresh: Boolean(query.refresh), list });
|
|
138
|
+
return list;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The levels `model` runs on a turn with this login and folder. First the
|
|
143
|
+
* list read for that login; failing that, any login's list or the catalog,
|
|
144
|
+
* but only for a model id that is not an alias: an alias such as Claude's
|
|
145
|
+
* `opus` runs a model that depends on the account and provider.
|
|
146
|
+
* `undefined` when nothing known applies.
|
|
147
|
+
*/
|
|
148
|
+
thinkingFor(
|
|
149
|
+
query: Omit<ModelsQuery, "refresh" | "cwd"> & { cwd: string },
|
|
150
|
+
model: string,
|
|
151
|
+
): readonly ThinkingLevel[] | undefined {
|
|
152
|
+
const own = [query.sessionId, undefined].map((sessionId) =>
|
|
153
|
+
this.key(query.harness, query.cwd, sessionId, query),
|
|
154
|
+
);
|
|
155
|
+
for (const key of own) {
|
|
156
|
+
const list = this.entries.get(key)?.list;
|
|
157
|
+
const found = list?.source === "live" && list.models.find((m) => m.id === model);
|
|
158
|
+
if (found) return found.thinking.levels;
|
|
159
|
+
}
|
|
160
|
+
let newest: { levels: readonly ThinkingLevel[]; fetchedAt: number } | undefined;
|
|
161
|
+
for (const { list } of this.entries.values()) {
|
|
162
|
+
if (list.harness !== query.harness || list.source !== "live") continue;
|
|
163
|
+
if (newest && newest.fetchedAt >= list.fetchedAt) continue;
|
|
164
|
+
const found = list.models.find((candidate) => candidate.id === model);
|
|
165
|
+
if (found && !isAlias(found))
|
|
166
|
+
newest = { levels: found.thinking.levels, fetchedAt: list.fetchedAt };
|
|
167
|
+
}
|
|
168
|
+
if (newest) return newest.levels;
|
|
169
|
+
const listed = CATALOG_MODELS.find(
|
|
170
|
+
(candidate) => candidate.harness === query.harness && candidate.id === model,
|
|
171
|
+
);
|
|
172
|
+
return listed && !isAlias(listed) ? listed.thinking.levels : undefined;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private async read(
|
|
176
|
+
harness: AgentHarness,
|
|
177
|
+
list: (signal: AbortSignal) => Promise<ModelList["models"]>,
|
|
178
|
+
): Promise<ModelList> {
|
|
179
|
+
const controller = new AbortController();
|
|
180
|
+
const timeoutMs = this.options.timeoutMs ?? LIST_TIMEOUT_MS;
|
|
181
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
182
|
+
const deadline = new Promise<never>((_, reject) => {
|
|
183
|
+
timer = setTimeout(() => {
|
|
184
|
+
const error = new Error(
|
|
185
|
+
`the ${harness} CLI did not list its models within ${timeoutMs} ms`,
|
|
186
|
+
);
|
|
187
|
+
controller.abort(error);
|
|
188
|
+
reject(error);
|
|
189
|
+
}, timeoutMs);
|
|
190
|
+
});
|
|
191
|
+
try {
|
|
192
|
+
const models = await Promise.race([list(controller.signal), deadline]);
|
|
193
|
+
if (!models.length) throw new Error(`the ${harness} CLI listed no models`);
|
|
194
|
+
return { harness, models, source: "live", fetchedAt: this.now() };
|
|
195
|
+
} catch (error) {
|
|
196
|
+
return {
|
|
197
|
+
...catalogModelList(harness, this.now()),
|
|
198
|
+
error: error instanceof Error ? error.message : String(error),
|
|
199
|
+
};
|
|
200
|
+
} finally {
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -9,8 +9,14 @@ export const TurnExecutionSchema = z.object({
|
|
|
9
9
|
model: z.string().optional(),
|
|
10
10
|
/** Requested setting, not a measurement of the model's internal reasoning. */
|
|
11
11
|
thinkingLevel: ThinkingLevelSchema.optional(),
|
|
12
|
-
/**
|
|
13
|
-
*
|
|
12
|
+
/** The level the harness ran this turn at: the request fitted to the model's levels
|
|
13
|
+
* (`ultra` on a model topping out at `max` runs `max`), or the harness's own setting
|
|
14
|
+
* when the turn requested none. Only on `turn.ended`; absent when unknown or when the
|
|
15
|
+
* turn failed or was cancelled before the model answered. */
|
|
16
|
+
appliedThinkingLevel: ThinkingLevelSchema.optional(),
|
|
17
|
+
/** Distinct models the primary harness reported for this turn, in observation order:
|
|
18
|
+
* those its stream named, else the model Codex reported for the thread. Excludes
|
|
19
|
+
* subagents. Absence means unreported, never a fallback to the requested alias. */
|
|
14
20
|
reportedModels: z.array(z.string()).optional(),
|
|
15
21
|
});
|
|
16
22
|
export type TurnExecution = z.infer<typeof TurnExecutionSchema>;
|