@zvada/agent-server 0.3.14 → 0.3.16

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 CHANGED
@@ -1,5 +1,59 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.16
4
+
5
+ - List each harness's models live: `runtime.models({ harness, cwd })`, wire
6
+ `models/list`, `client.listModels()`, and `/models` in the interactive CLI.
7
+ Claude Code answers from an idle CLI (no prompt, MCP servers or hooks); Codex
8
+ from `model/list`. Each model comes in one shape, `ModelDescriptor`: `id`,
9
+ `label`, `resolvedId` (what an alias runs), `isDefault` (what a turn naming
10
+ no model runs; for Codex the model `~/.codex/config.toml` selects),
11
+ `thinking.levels` (empty: no thinking control), `thinking.default` when the
12
+ CLI states one, and `images`. Lists depend on the login and folder and are
13
+ cached ten minutes per both (`refresh: true` reads again). When the CLI does
14
+ not answer, the list is the last live one or the catalog, with an `error`. A
15
+ warm read takes about 0.7 s (Claude) or 0.1 s (Codex) and no tokens.
16
+ - `turn.ended.execution.appliedThinkingLevel` says which level a turn ran.
17
+ Claude Code lowers a level its model lacks without saying so (`xhigh` on
18
+ Sonnet 4.6 runs `high`, `ultra` runs `max`), so `claude-code` now fits the
19
+ level to the model's listed levels before starting Claude. An alias such as
20
+ `opus` is fitted only from its own login's list, since its model depends on
21
+ the account. `codex-sdk` fits it to the list read for the login, else the
22
+ catalog. A turn that fails or is cancelled before its model answers reports
23
+ no applied level.
24
+ - `codex-app-server` reports the thread's own effort and model (for example
25
+ from `~/.codex/config.toml`) when the turn names neither. A turn that
26
+ switches models without a level gets that effort fitted to the new model,
27
+ as a requested level is: Codex kept the old one (`ultra` on `gpt-6-luna`,
28
+ whose listed levels top out at `max`). `reportedModels` names the thread's
29
+ model when the stream reports none.
30
+ - The catalog is generated from the pinned CLIs (`bun run models:refresh`)
31
+ instead of kept by hand, and a test fails until it matches the pins. It now
32
+ holds Claude Code's 12 models with each model's levels (Opus 4.6 and Sonnet
33
+ 4.6 have no `xhigh`) and Codex's labels and default levels, logged in and
34
+ logged out (`gpt-5.5`). `CATALOG_MODELS` holds the descriptors;
35
+ `MODEL_CATALOG`, `modelsForHarness` and `modelThinkingLevels` keep their 0.3
36
+ shape.
37
+
38
+ ## 0.3.15
39
+
40
+ - Codex runs the nearest thinking level its model accepts. `off` sent effort
41
+ `minimal`, which every current Codex model rejects, so the turn failed
42
+ ("Unsupported value: 'minimal' is not supported with the 'gpt-6-astra'
43
+ model"); it now sends the model's lowest effort. A level above the model's
44
+ top becomes that top. `codex-app-server` asks the CLI (`model/list`) what the
45
+ thread's model accepts, including a model `~/.codex/config.toml` selected;
46
+ `codex-sdk` uses the catalog.
47
+ - `MODEL_CATALOG` lists each model's real levels instead of all seven for
48
+ every model, and adds `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna` and
49
+ Claude's `fable` alias. Codex models offer no `off`; Claude models offer no
50
+ `ultra` (it runs as `max`); Haiku lists none. `gpt-5.5` is labeled API-key
51
+ only: Codex refuses it for a ChatGPT login.
52
+ - Add `clampThinkingLevel(level, supported)` and `modelThinkingLevels(harness,
53
+ model)` for pickers that switch models.
54
+ - Development only: lift `vite` (through vitest) to 8.3 past a newly
55
+ published advisory so the audit passes.
56
+
3
57
  ## 0.3.14
4
58
 
5
59
  - Update the managed CLIs and development SDKs: Codex 0.160.0 and Claude Agent
package/README.md CHANGED
@@ -50,6 +50,7 @@ bunx @zvada/agent-server install # prefetch pinned claude/codex CLIs
50
50
  import { AgentServerClient } from "@zvada/agent-server/client";
51
51
 
52
52
  const client = await AgentServerClient.connect("ws://127.0.0.1:4747");
53
+ const { models } = await client.listModels({ harness: "claude-code", cwd: "." }); // this login's models
53
54
  const turn = await client.runTurn({ input: "hi", config: { harness: "claude-code", cwd: "." } });
54
55
  for await (const event of turn.events) console.log(event.type);
55
56
  await client.closeSession(turn.sessionId);
package/docs/consuming.md CHANGED
@@ -183,6 +183,30 @@ known `type`, and **store and forward what you don't understand** — a
183
183
  round trip through your persistence layer must not be where a newer server's
184
184
  data disappears. A known type with a malformed body still fails loudly.
185
185
 
186
+ ## Offer models and show what ran
187
+
188
+ Fill a model picker from the harness's own list rather than a hard-coded one:
189
+
190
+ ```ts
191
+ const { models, source, error } = await client.listModels({ harness: "codex-app-server", cwd });
192
+ // source: "catalog" + error = the CLI did not answer (e.g. logged out); offer a login.
193
+ const choice = models.find((m) => m.isDefault) ?? models[0];
194
+ const level = savedLevelFor(choice.id) ?? choice.thinking.default; // never invent one
195
+ ```
196
+
197
+ `thinking.levels` empty means the model has no thinking control. Keep the
198
+ user's level per model, and use `clampThinkingLevel(level, model.thinking.levels)`
199
+ only for a model the user has not set. Pass `refresh: true` after a login;
200
+ lists are cached ten minutes.
201
+
202
+ `turn.ended.execution` records what ran: `appliedThinkingLevel` is the level
203
+ the model ran at (`ultra` on a model whose top is `max` shows `max`), and
204
+ `reportedModels` the models the harness reported (Claude's API model, Codex's
205
+ thread model). Show those, not the requested `model` and `thinkingLevel`,
206
+ when they are present. Both are absent when a turn failed before its model
207
+ answered. List models with the `cwd` (and credentials) your turns use: an
208
+ alias such as `opus` is fitted only from its own login's list.
209
+
186
210
  ## Persist for resume
187
211
 
188
212
  Store `state.nativeSessionId` (from `session.created`) keyed by your logical
package/docs/harnesses.md CHANGED
@@ -67,9 +67,66 @@ but not the logged-in account's claude.ai connectors: a turn gets the MCP
67
67
  servers its config names. Set `ENABLE_CLAUDEAI_MCP_SERVERS=true` in the
68
68
  server's or the turn's env to load them.
69
69
 
70
- `thinkingLevel` runs from `off` to `ultra`. Claude's ceiling is `max` (it runs
71
- `ultra` as `max`); Codex passes the level through, and not every model offers
72
- `ultra`.
70
+ `thinkingLevel` runs from `off` to `ultra`. agent-server fits it to the
71
+ model's levels when it knows them: a level above the model's top becomes that
72
+ top (`ultra` on a model whose top is `max` runs `max`), and on Codex `off`
73
+ becomes the model's lowest (current models reject `minimal`). The levels come
74
+ from the list `models()` read for the turn's login and folder; for a concrete
75
+ model id, any login's list or the catalog also serves, but an alias such as
76
+ Claude's `opus` runs a model that depends on the account, so only its own
77
+ login's list fits it. `turn.ended.execution.appliedThinkingLevel` says which
78
+ level ran. It is absent when that is unknown, or when the turn failed or was
79
+ cancelled before the model answered:
80
+
81
+ - **claude-code** fits the level before starting Claude, because Claude Code
82
+ lowers a level its model lacks without saying so (`xhigh` on Sonnet 4.6 runs
83
+ `high`). With no known levels the level passes through and no applied level
84
+ is reported. `off` is sent as is: some models do not let thinking be
85
+ disabled. An operator `sdkOptions` that sets `effort` or `thinking` wins, and
86
+ then no level is reported.
87
+ - **codex-app-server** reads what the thread's model accepts from its own
88
+ `model/list`. With no level requested it reports the thread's effort (for
89
+ example from `~/.codex/config.toml`), and the thread's model in
90
+ `reportedModels` when the stream names none. A turn that switches models
91
+ without a level gets the thread's effort fitted to the new model. Codex runs
92
+ the effort it is given, so that is the one reported.
93
+ - **codex-sdk** fits the level to the list `models()` read for the login, else
94
+ the catalog.
95
+
96
+ `clampThinkingLevel` picks the nearest level when a picker switches models.
97
+
98
+ ## Model lists
99
+
100
+ `runtime.models({ harness, cwd })` (wire `models/list`, `client.listModels()`)
101
+ returns the models a harness offers, read from its CLI for the login and folder
102
+ a turn with the same `cwd`, `env` and `apiKey` would use:
103
+
104
+ | Harness | Source | Notes |
105
+ | --- | --- | --- |
106
+ | `claude-code` | `query().supportedModels()` on an idle CLI (no prompt, MCP servers or hooks) | The folder's `availableModels` setting narrows the list. `default` is a model id: the account's default. Haiku lists no levels. Operator `sdkOptions` are not applied. |
107
+ | `codex-app-server` | `model/list`, on the session's own process when `sessionId` has one | Lists what the login can run (a ChatGPT login gets no `gpt-5.5`). The default is the model `~/.codex/config.toml` selects, else Codex's own. With host-managed auth, pass the `sessionId` whose account to list. |
108
+ | `codex-sdk` | `model/list` on a short-lived `codex app-server` | `codex exec` cannot list models. The app-server ignores a turn's `apiKey`, so this is the CLI's stored login (Codex's built-in list when logged out). |
109
+ | `acp` | none | The catalog (empty). ACP agents describe models as session config options. |
110
+
111
+ Each `ModelDescriptor` has `id` (pass as `config.model`), `label`,
112
+ `description`, `resolvedId` (what an alias runs), `isDefault`, `thinking`
113
+ (`levels` lowest first, where empty means no thinking control, and `default`
114
+ when the CLI states one; it is never invented) and `images`.
115
+
116
+ Lists are cached for ten minutes per harness, folder and credentials, and per
117
+ session only with host-managed Codex auth; pass `refresh: true` after the user
118
+ logs in. Listing costs one CLI start and no tokens: about 0.7 s for Claude and
119
+ 0.1 s for Codex once warm, a few seconds for the first read after the server
120
+ starts. A CLI that cannot answer within 20 s (logged out, too old) gets the
121
+ catalog with `source: "catalog"` and an `error`, or the last live list with the
122
+ `error` when one was read; a failed read is retried after 30 seconds.
123
+
124
+ The catalog (`CATALOG_MODELS`, and `MODEL_CATALOG` in the 0.3 shape) is what
125
+ the pinned CLIs listed when the release was built (`bun run models:refresh`):
126
+ Claude for the maintainer's login, Codex logged in and logged out (which adds
127
+ the API-key models such as `gpt-5.5`). Keep the user's thinking choice per
128
+ model in your app; start from `thinking.default`, and use `clampThinkingLevel`
129
+ only for a model the user has not set.
73
130
 
74
131
  Consult `runtime.capabilities(harness)` before relying on a capability.
75
132
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvada/agent-server",
3
- "version": "0.3.14",
3
+ "version": "0.3.16",
4
4
  "description": "Harness-agnostic agent execution engine: run Claude Code, Codex (SDK/CLI + app-server), and any ACP agent behind one interface with a normalized event stream, multi-turn sessions, and resume. Root export is the wire contract; /core, /server, /client are the seats.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -6,6 +6,8 @@ import {
6
6
  type InitializeResult,
7
7
  InitializeResultSchema,
8
8
  type JsonRpcId,
9
+ type ModelList,
10
+ type ModelsListParams,
9
11
  type PermissionOutcome,
10
12
  PermissionRespondResultSchema,
11
13
  SessionCloseResultSchema,
@@ -23,6 +25,7 @@ import {
23
25
  type WireTransport,
24
26
  createSeqCursor,
25
27
  decodeEventsReplayResult,
28
+ decodeModelList,
26
29
  decodeWireEventEnvelope,
27
30
  decodeWireMessage,
28
31
  encodeRequest,
@@ -136,6 +139,17 @@ const REPLAY_RESULT: ResultSchema<DecodedEventsReplayResult> = {
136
139
  },
137
140
  };
138
141
 
142
+ /** A model list from a server that may know thinking levels this build does not. */
143
+ const MODEL_LIST: ResultSchema<ModelList> = {
144
+ safeParse(raw) {
145
+ try {
146
+ return { success: true, data: decodeModelList(raw) };
147
+ } catch {
148
+ return { success: false };
149
+ }
150
+ },
151
+ };
152
+
139
153
  type TransportFactory = () => Promise<WireTransport> | WireTransport;
140
154
 
141
155
  /**
@@ -398,6 +412,15 @@ export class AgentServerClient {
398
412
  return closed;
399
413
  }
400
414
 
415
+ /**
416
+ * The models a harness offers for the login and folder a turn with the same
417
+ * `cwd`, `env` and `apiKey` would use. `source: "catalog"` (with `error`)
418
+ * means the CLI did not answer and the list is agent-server's built-in one.
419
+ */
420
+ listModels(params: ModelsListParams): Promise<ModelList> {
421
+ return this.request(WIRE_METHODS.modelsList, params, MODEL_LIST);
422
+ }
423
+
401
424
  /** Fetch buffered events (`seq >= fromSeq`) without touching seq tracking. */
402
425
  replay(sessionId: string, fromSeq: number): Promise<DecodedEventsReplayResult> {
403
426
  return this.request(WIRE_METHODS.eventsReplay, { sessionId, fromSeq }, REPLAY_RESULT);
@@ -3,6 +3,7 @@ import type {
3
3
  AgentHarness,
4
4
  AgentInput,
5
5
  McpServerConfig,
6
+ ModelDescriptor,
6
7
  PermissionMode,
7
8
  PermissionToolCall,
8
9
  ThinkingLevel,
@@ -63,6 +64,12 @@ export interface AgentExecuteOptions {
63
64
  apiKey?: string;
64
65
  /** Disable all built-in tools for this turn (text-only). */
65
66
  disableTools?: boolean;
67
+ /**
68
+ * The levels `model` runs, lowest first, when the engine knows them (a live
69
+ * list or the catalog). A harness fits `thinkingLevel` to them. Empty: the
70
+ * model has no thinking control.
71
+ */
72
+ modelThinking?: readonly ThinkingLevel[];
66
73
  signal?: AbortSignal;
67
74
  /**
68
75
  * Called once with the harness-native session/thread id (for resume).
@@ -73,6 +80,29 @@ export interface AgentExecuteOptions {
73
80
  onNativeSession?: (nativeSessionId: string, info?: { resumed?: boolean }) => void;
74
81
  /** Engine-brokered approval round-trip (see PermissionRequestHandler). */
75
82
  onPermissionRequest?: PermissionRequestHandler;
83
+ /** What the harness configured for this turn, once known (see `AppliedExecution`). */
84
+ onExecution?: (applied: AppliedExecution) => void;
85
+ }
86
+
87
+ /**
88
+ * What a harness runs a turn with, as far as it knows. Report only facts: a
89
+ * level the harness may still lower on its own is not an applied level.
90
+ */
91
+ export interface AppliedExecution {
92
+ /** The thinking level the turn runs at (`turn.ended.execution.appliedThinkingLevel`). */
93
+ thinkingLevel?: ThinkingLevel;
94
+ /** A model the harness reported for this turn (joins `reportedModels`). */
95
+ model?: string;
96
+ }
97
+
98
+ /** Whose models to list: the same login and folder a turn would use. */
99
+ export interface ListModelsOptions {
100
+ cwd: string;
101
+ /** Host-managed credentials resolve per session (Codex `resolveAuth`). */
102
+ sessionId?: string;
103
+ env?: Record<string, string>;
104
+ apiKey?: string;
105
+ signal?: AbortSignal;
76
106
  }
77
107
 
78
108
  /** Raw, harness-specific event. Adapters interpret it; the engine never does. */
@@ -108,6 +138,13 @@ export interface Agent {
108
138
  release?(sessionId: string): Promise<void>;
109
139
  /** Mark retained MCP connections stale after host suspension; repair before the next turn. */
110
140
  invalidateMcpConnections?(): void;
141
+ /**
142
+ * The models this harness's CLI offers for a login and folder. Throws when
143
+ * the CLI cannot answer; the runtime then serves the catalog.
144
+ */
145
+ listModels?(options: ListModelsOptions): Promise<ModelDescriptor[]>;
146
+ /** Whether `listModels` depends on `sessionId` (credentials the host selects per session). */
147
+ readonly modelsPerSession?: boolean;
111
148
  /** Tear down every live session (process shutdown). Built-ins reject subsequent turns. */
112
149
  terminateAll(): Promise<void>;
113
150
  }
@@ -1,9 +1,19 @@
1
1
  import type { SDKMessage, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
2
2
  import type { McpSetServersResult } from "@anthropic-ai/claude-agent-sdk";
3
- import type { AgentCapabilities, AgentInput, McpServerConfig } from "../../../protocol/index.ts";
3
+ import type {
4
+ AgentCapabilities,
5
+ AgentInput,
6
+ McpServerConfig,
7
+ ModelDescriptor,
8
+ } from "../../../protocol/index.ts";
4
9
  import { type DiagnosticHandler, emitDiagnostic } from "../../diagnostics.ts";
5
10
  import { SessionResumeError } from "../../utils/errors.ts";
6
- import type { AgentExecuteOptions, CancelResult, RawAgentEvent } from "../base.ts";
11
+ import type {
12
+ AgentExecuteOptions,
13
+ CancelResult,
14
+ ListModelsOptions,
15
+ RawAgentEvent,
16
+ } from "../base.ts";
7
17
  import { SessionAgent } from "../session-agent.ts";
8
18
  import type {
9
19
  ClaudeGeneratorSession,
@@ -12,6 +22,7 @@ import type {
12
22
  ClaudeSessionExtras,
13
23
  ClaudeToolPolicy,
14
24
  } from "./generator-session.ts";
25
+ import { claudeModelDescriptors, fitClaudeThinking, readClaudeModels } from "./models.ts";
15
26
  import type { ClaudeSessionConfig } from "./options.ts";
16
27
  import { ClaudeSessionManager } from "./session-manager.ts";
17
28
 
@@ -159,11 +170,14 @@ export class ClaudeCodeAgent extends SessionAgent {
159
170
  const cliPath = await this.agentOptions.resolveCliPath?.();
160
171
  const content = toClaudeContent(input);
161
172
  controller.signal.throwIfAborted();
173
+ const thinking = fitClaudeThinking(options.thinkingLevel, options.modelThinking);
162
174
  const { session, spawned } = await this.manager.getOrCreate(
163
175
  options.sessionId,
164
- sessionConfigFrom(options, cliPath),
176
+ { ...sessionConfigFrom(options, cliPath), thinkingLevel: thinking.send },
165
177
  this.sessionExtras(),
166
178
  );
179
+ if (thinking.applied && !session.operatorThinking)
180
+ options.onExecution?.({ thinkingLevel: thinking.applied });
167
181
  const attemptedResume = spawned && Boolean(options.resumeSessionId);
168
182
  if (spawned) unconfirmedSession = session;
169
183
  // A cancel during connection repair must never submit the prompt.
@@ -232,6 +246,17 @@ export class ClaudeCodeAgent extends SessionAgent {
232
246
  }
233
247
  }
234
248
 
249
+ /** The models this login offers in `options.cwd`, from the Claude Code CLI. */
250
+ async listModels(options: ListModelsOptions): Promise<ModelDescriptor[]> {
251
+ const cliPath = await this.agentOptions.resolveCliPath?.();
252
+ options.signal?.throwIfAborted();
253
+ const models = await readClaudeModels(
254
+ { cwd: options.cwd, env: options.env, apiKey: options.apiKey, cliPath },
255
+ options.signal,
256
+ );
257
+ return claudeModelDescriptors(models);
258
+ }
259
+
235
260
  /**
236
261
  * Hot-swap the live session's wire MCP servers without a restart (context
237
262
  * intact). Returns false when the session isn't live. In-process servers
@@ -127,6 +127,8 @@ export class ClaudeGeneratorSession {
127
127
  private startupError: unknown;
128
128
  /** SDK cost is cumulative within this query; token usage is already per turn. */
129
129
  private cumulativeCost: number | undefined = 0;
130
+ /** The operator's `sdkOptions` set the effort or thinking, not the engine. */
131
+ private thinkingOverridden = false;
130
132
 
131
133
  private currentTap: AsyncQueue<SDKMessage> | null = null;
132
134
  private readonly idleWaiters: Array<() => void> = [];
@@ -164,6 +166,10 @@ export class ClaudeGeneratorSession {
164
166
  get currentConfig(): Readonly<ClaudeSessionConfig> {
165
167
  return this.config;
166
168
  }
169
+ /** Whether the operator's `sdkOptions` chose the thinking settings this session runs. */
170
+ get operatorThinking(): boolean {
171
+ return this.thinkingOverridden;
172
+ }
167
173
  get mcpConnectionsStale(): boolean {
168
174
  return this.mcpUpdateFailed || this.processInvalidated;
169
175
  }
@@ -284,13 +290,17 @@ export class ClaudeGeneratorSession {
284
290
  sessionId: this.id,
285
291
  cwd: this.config.cwd,
286
292
  });
293
+ const overrides = await this.extras?.sdkOptions?.({ sessionId: this.id, cwd: this.config.cwd });
294
+ this.thinkingOverridden = Boolean(
295
+ overrides && ("effort" in overrides || "thinking" in overrides),
296
+ );
287
297
  const options = buildClaudeOptions(
288
298
  // CLI startup MCP entries can survive the first dynamic removal and
289
299
  // reconnect-by-name can reuse their original credentials. Give every
290
300
  // wire server one owner: register it dynamically before the first turn.
291
301
  { ...this.config, mcpServers: {} },
292
302
  this.sdkServers,
293
- await this.extras?.sdkOptions?.({ sessionId: this.id, cwd: this.config.cwd }),
303
+ overrides,
294
304
  );
295
305
  if (this.extras?.hooks) {
296
306
  options.hooks = this.extras.hooks({
@@ -0,0 +1,76 @@
1
+ import type { ModelInfo as ClaudeModelInfo, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
2
+ import {
3
+ AsyncQueue,
4
+ type ModelDescriptor,
5
+ type ThinkingLevel,
6
+ clampThinkingLevel,
7
+ } from "../../../protocol/index.ts";
8
+ import { knownThinkingLevels } from "../thinking-levels.ts";
9
+ import { type ClaudeSessionConfig, buildClaudeOptions } from "./options.ts";
10
+
11
+ /**
12
+ * Claude Code's model rows in the shared shape. `default` (the account's
13
+ * default model) is a model id Claude accepts, so it stays a row of its own.
14
+ * A row Claude marks disabled is not selectable and is left out.
15
+ */
16
+ export function claudeModelDescriptors(models: readonly ClaudeModelInfo[]): ModelDescriptor[] {
17
+ return models
18
+ .filter((model) => !(model as { disabled?: boolean }).disabled)
19
+ .map((model) => ({
20
+ id: model.value,
21
+ harness: "claude-code" as const,
22
+ label: model.displayName || model.value,
23
+ ...(model.description && { description: model.description }),
24
+ ...(model.resolvedModel &&
25
+ model.resolvedModel !== model.value && { resolvedId: model.resolvedModel }),
26
+ ...(model.value === "default" && { isDefault: true }),
27
+ thinking: { levels: knownThinkingLevels(model.supportedEffortLevels ?? []) },
28
+ }));
29
+ }
30
+
31
+ /**
32
+ * The level to start Claude with, and the level it then runs. Claude Code
33
+ * lowers a level its model lacks on its own and does not say so (`max` and
34
+ * `xhigh` become `high`), so the level is fitted here, where the model's levels
35
+ * are known. `off` is sent as it is: some models do not let thinking be
36
+ * disabled, and Claude Code then thinks at its default effort.
37
+ */
38
+ export function fitClaudeThinking(
39
+ level: ThinkingLevel | undefined,
40
+ levels: readonly ThinkingLevel[] | undefined,
41
+ ): { send?: ThinkingLevel; applied?: ThinkingLevel } {
42
+ if (level === undefined) return {};
43
+ if (level === "off" || !levels?.length) return { send: level };
44
+ const fitted = clampThinkingLevel(level, levels) ?? level;
45
+ return { send: fitted, applied: fitted };
46
+ }
47
+
48
+ /**
49
+ * Ask Claude Code which models it offers. Starts the CLI the way a turn would
50
+ * (same folder settings, environment and credentials, which decide the list)
51
+ * but sends no prompt, loads no MCP server and runs no hook. Answers from the
52
+ * CLI's initialization: under a second, no tokens.
53
+ */
54
+ export async function readClaudeModels(
55
+ config: Pick<ClaudeSessionConfig, "cwd" | "env" | "apiKey" | "cliPath">,
56
+ signal?: AbortSignal,
57
+ ): Promise<ClaudeModelInfo[]> {
58
+ const sdk = await import("@anthropic-ai/claude-agent-sdk");
59
+ signal?.throwIfAborted();
60
+ const options = buildClaudeOptions({ ...config, maxTurns: 1 });
61
+ options.strictMcpConfig = true;
62
+ options.mcpServers = {};
63
+ options.settings = { disableAllHooks: true };
64
+ // An open prompt stream that never yields: the CLI initializes and waits.
65
+ const prompt = new AsyncQueue<SDKUserMessage>();
66
+ const query = sdk.query({ prompt, options });
67
+ const stop = () => query.close();
68
+ signal?.addEventListener("abort", stop, { once: true });
69
+ try {
70
+ return await query.supportedModels();
71
+ } finally {
72
+ signal?.removeEventListener("abort", stop);
73
+ prompt.end();
74
+ query.close();
75
+ }
76
+ }