pi-tsgw 0.0.10 → 0.0.12

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/README.md CHANGED
@@ -6,8 +6,9 @@ openai-responses, anthropic-messages, google-generative-ai) and applies
6
6
  per-vendor request-body operations so thinking levels, reasoning formats, and
7
7
  optional built-in web search behave correctly on the gateway.
8
8
 
9
- No API keys, endpoints, or pricing are baked into this package: everything
10
- gateway-specific is configuration.
9
+ No private API keys or gateway endpoints are included. The static catalog
10
+ contains model metadata and public-price estimates; these are not your gateway's
11
+ billing rates.
11
12
 
12
13
  ## Install
13
14
 
@@ -36,7 +37,7 @@ Example:
36
37
  {
37
38
  "tsgw": {
38
39
  "baseUrl": "https://aih.example.net",
39
- "tsSearch": "off",
40
+ "tsSearch": "live",
40
41
  "traceHeaders": false,
41
42
  "excludeModels": ["gpt-*", "claude-*"],
42
43
  "includeModels": ["gpt-5.6-*"]
@@ -52,19 +53,23 @@ placeholder root is used that will not work.
52
53
 
53
54
  ### API key
54
55
 
55
- The extension never reads credential files. Pi resolves the key itself:
56
+ The extension delegates credential reading and resolution to Pi:
56
57
 
57
58
  1. **`/login`** — select the `tsgw` provider and enter the key; pi stores it
58
59
  in `~/.pi/agent/auth.json` (preferred)
59
60
  2. **`TSGW_API_KEY`** environment variable — Pi's fallback when nothing is
60
61
  stored
61
62
 
63
+ Startup discovery uses Pi's stored-credential API; later catalog refreshes use
64
+ the credential supplied by Pi. With environment-only authentication, the initial
65
+ catalog may fall back to static models until Pi refreshes it.
66
+
62
67
  ### Options
63
68
 
64
69
  | Setting (`settings.json` `tsgw.*`) | Default | Meaning |
65
70
  | --- | --- | --- |
66
71
  | `baseUrl` | placeholder | Gateway root (the `/v1` suffix is normalized away) |
67
- | `tsSearch` | `off` | `off`, `cached`, or `live` — appends the built-in `web_search` tool for models with built-in search (GPT / Grok) |
72
+ | `tsSearch` | `live` | GPT: `cached` or `live`; unset, legacy `off`, and invalid values fall back to `live`. Supported Grok models always use live search. |
68
73
  | `traceHeaders` | `false` | Adds `AH-Thread-Id` / `AH-Trace-Id` headers for gateway-side tracing |
69
74
  | `includeModels` | unset | Re-include override: matching model ids are kept even when also matched by `excludeModels` (exact id or `prefix-*` glob) |
70
75
  | `excludeModels` | unset | Blacklist: matching model ids are dropped unless pulled back by `includeModels` (exact id or `prefix-*` glob) |
@@ -72,37 +77,101 @@ The extension never reads credential files. Pi resolves the key itself:
72
77
  ## Model catalog
73
78
 
74
79
  The catalog is assembled from per-vendor slices (`extensions/models/vendors/`),
75
- currently covering 10 vendor families: DeepSeek, GLM (Zhipu), MiMo (Xiaomi),
76
- MiniMax, Kimi (Moonshot), Qwen (Alibaba), GPT (OpenAI), Gemini (Google),
77
- Claude (Anthropic), and LongCat — 59 chat models in total. Each vendor file
78
- carries the official documentation URL in its header comment. Pricing entries
79
- mirror the vendors' public list prices; replace them with your gateway's
80
- actual pricing if it differs.
80
+ covering 11 vendor families: DeepSeek, GLM (Zhipu), MiMo (Xiaomi), MiniMax,
81
+ Kimi (Moonshot), Qwen (Alibaba), GPT (OpenAI), Gemini (Google), Claude
82
+ (Anthropic), LongCat, and Grok (xAI). The current static catalog contains 54 chat
83
+ model IDs, including retained aliases; this is not a live availability count.
84
+ Vendor files carry documentation links and metadata caveats. Alias mappings,
85
+ output limits, and shared thinking policies are not all individually verified
86
+ against gateway endpoints; public-price estimates do not guarantee billing.
81
87
 
82
88
  Use broad `excludeModels` rules to drop model families and precise
83
89
  `includeModels` rules to pull selected models back. `includeModels` is not a
84
90
  global whitelist: models matching neither list remain available. To register
85
91
  only selected models, use `"excludeModels": ["*"]` and pull them back through
86
- `includeModels`.
92
+ `includeModels`. Both lists are case-sensitive and support only exact IDs or
93
+ trailing `*` prefix matching (not general globs); preserve `MiniMax-*` casing.
94
+ When a gateway catalog is available, filtering applies after intersecting it
95
+ with the static catalog. Include rules cannot add unknown or unavailable IDs.
87
96
 
88
97
  Opening `/model` refreshes the gateway catalog in the background, with a
89
98
  five-minute cache to avoid repeated requests. Run `/tsgw-refresh` to bypass the
90
99
  cache and force an immediate refresh without restarting or reloading Pi. If a
91
100
  refresh fails, the last successful model list remains active.
92
101
 
102
+ Memory and disk caches are scoped to the gateway root and credential using a
103
+ SHA-256 digest; plaintext credentials are not stored. The disk cache is a single
104
+ slot at `<agent-dir>/tsgw/models-cache.json`: changing scope may require a fresh
105
+ fetch. Legacy unscoped cache files are ignored and replaced after a successful
106
+ fetch. In-process request ordering prevents late results from replacing newer
107
+ cache writes; this is not a cross-process locking mechanism.
108
+
109
+ ## Status bar and session controls
110
+
111
+ Pi Web clients supporting `command:/…` statuses render these as clickable
112
+ buttons; the terminal CLI displays status text and accepts the same commands:
113
+
114
+ - **`TSGW · N`** (`/tsgw`): one menu for **refreshing the model catalog** and
115
+ **viewing diagnostics**. The count is the filtered registered catalog, not a
116
+ count of healthy inference endpoints. 🟢 means a fresh directory result;
117
+ 🟡 means a static/expired directory or a failed refresh; ⚠️ means missing
118
+ credentials or gateway configuration; ⏳ means a refresh is running.
119
+ - **Built-in search** (`/tsgw-search`): GPT offers only `cached / live`
120
+ for the current session, defaulting to `live`. Supported Grok models use
121
+ fixed live search: the command only shows a notice, without a picker or
122
+ changing the GPT session mode. Unsupported TSGW models are labeled
123
+ accordingly; this button is hidden when another provider is selected.
124
+
125
+ For GPT, you can also type `/tsgw-search cached` or `/tsgw-search live`;
126
+ `off` is no longer accepted. These controls do not modify `settings.json` or
127
+ persist across a reload or a new session; `tsgw.tsSearch` remains the startup
128
+ default. Existing `cached` configuration is preserved; unset, legacy `off`,
129
+ and invalid configuration now default to `live`.
130
+
131
+ Injection remains limited to the existing model/protocol support list. GPT
132
+ Responses appends a `web_search` tool (`external_web_access` is false for
133
+ `cached`, true for `live`); Grok Completions appends
134
+ `search_parameters: { mode: "on" }`. Existing search tools/fields are never
135
+ overwritten. This setting does not control Qwen's vendor policy, external
136
+ tools, or thinking mode and is not a global network-access switch.
137
+
138
+ The standalone `ts_search` tool is no longer bundled. Use a separately configured
139
+ search tool such as `ts_oht.search` instead. Built-in model search remains
140
+ available and does not control external search tools.
141
+
142
+ Diagnostics show directory source, original fetch time, cache freshness,
143
+ configuration presence, and safe refresh error summaries—never API keys or
144
+ URLs. They make no extra network requests. Statuses update on session/model
145
+ activity and directory refreshes; there is no background health polling.
146
+
147
+ Icons use Emoji/Unicode: Pi Web currently strips ANSI colors from command
148
+ buttons. Busy sessions disable the buttons. The terminal CLI shows the same
149
+ statuses as text; use the slash commands there. Pi Web may not show extension
150
+ statuses until the session runtime has started.
151
+
93
152
  ## Development
94
153
 
95
154
  ```bash
96
- npm install
155
+ npm ci
97
156
  npm test
157
+ npm exec -- tsc -p tsconfig.json
158
+ npm pack --dry-run --json
98
159
  ```
99
160
 
100
- Tests run against a fake pi host (`FakePi` + `FakeContext`) and isolate the
101
- config directory through `PI_CODING_AGENT_DIR`, so no pi installation is
102
- needed to run them.
161
+ Pi is installed as a development dependency; the lockfile defines the test
162
+ baseline. Tests isolate configuration and credentials using temporary agent
163
+ directories. Unit tests use a fake host; host integration tests load the extension
164
+ through the real Pi SDK with simulated HTTP responses, without production
165
+ requests. They do not verify upstream inference, native search results, or Pi
166
+ Web rendering. Run the full suite after upgrading Pi.
103
167
 
104
168
  ## Technical details
105
169
 
106
- Per-vendor thinking profiles (the request-body matrix), the built-in web
107
- search injection semantics, and the pi lifecycle compatibility notes live in
108
- [AGENTS.md](AGENTS.md).
170
+ - [Vendor profiles](https://github.com/tossp/pi-tsgw/tree/main/extensions/models/vendors): model metadata, compatibility flags, and thinking mappings.
171
+ - [Request operations](https://github.com/tossp/pi-tsgw/blob/main/extensions/models/operations.ts): copy-on-write dispatch; DeepSeek/Claude response handling stays with Pi's adapters.
172
+ - [Built-in search](https://github.com/tossp/pi-tsgw/blob/main/extensions/models/web-search.ts): exact model/protocol support and append-only injection.
173
+ - [Host integration](https://github.com/tossp/pi-tsgw/blob/main/extensions/index.ts): configuration, refreshes, commands, and lifecycle snapshots. Late request callbacks must not access stale session contexts.
174
+
175
+ These source links describe the repository's current main branch; an installed
176
+ release may differ. Development rules in `AGENTS.md` are repository-only and
177
+ are not part of the npm package.
@@ -1,4 +1,8 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionCommandContext,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
2
6
  import {
3
7
  getAgentDir,
4
8
  readStoredCredential,
@@ -16,11 +20,14 @@ import {
16
20
  } from "./models/catalog.ts";
17
21
  import { getGatewayModelIds } from "./models/gateway-catalog.ts";
18
22
  import { applyModelOperations } from "./models/operations.ts";
19
- import type { ThinkingLevel, WebSearchMode } from "./models/_tools.ts";
23
+ import { builtinSearchSupport } from "./models/web-search.ts";
20
24
  import {
21
- DEFAULT_SEARCH_MODELS,
22
- registerTsSearch,
23
- } from "./ts-search/ts-search.ts";
25
+ catalogLabel,
26
+ catalogDiagnostics,
27
+ searchLabel,
28
+ type CatalogStatus,
29
+ } from "./status.ts";
30
+ import type { ThinkingLevel, WebSearchMode } from "./models/_tools.ts";
24
31
 
25
32
  /**
26
33
  * The data needed by provider hooks, copied while the lifecycle context is
@@ -150,6 +157,7 @@ async function resolveEffectiveModels(
150
157
  ): Promise<{
151
158
  models: ReturnType<typeof modelsForRoot>;
152
159
  gatewayIds: ReadonlySet<string> | undefined;
160
+ catalog: CatalogStatus;
153
161
  }> {
154
162
  // 凭据解析失败不阻塞:无凭据时直接跳过网关层。
155
163
  let apiKey = "";
@@ -161,36 +169,39 @@ async function resolveEffectiveModels(
161
169
  }
162
170
 
163
171
  let gatewayIds: ReadonlySet<string> | undefined;
172
+ let catalog: CatalogStatus = { count: 0, source: "static", loading: false };
164
173
  if (apiKey) {
165
174
  try {
166
175
  const gateway = await getGatewayModelIds(root, apiKey, {
167
176
  cacheFilePath,
168
177
  });
169
- if (gateway.ok) gatewayIds = new Set(gateway.ids);
170
- else
171
- console.warn(
172
- `TSGW: gateway model list unavailable (${gateway.reason ?? "unknown"}); using static catalog.`,
173
- );
178
+ if (gateway.ok) {
179
+ gatewayIds = new Set(gateway.ids);
180
+ catalog = {
181
+ ...catalog,
182
+ source: gateway.cached ? "cache" : "network",
183
+ storedAt: gateway.storedAt,
184
+ error: gateway.stale
185
+ ? `刷新失败(${gateway.fallbackReason ?? "unknown"}),沿用旧目录` : undefined,
186
+ };
187
+ } else catalog.error = `目录获取失败(${gateway.reason}),使用内置目录`;
174
188
  } catch {
175
- console.warn(
176
- `TSGW: gateway model list load failed; using static catalog.`,
177
- );
189
+ catalog.error = "目录获取失败,使用内置目录";
178
190
  }
179
191
  }
180
-
181
- return {
182
- models: effectiveModelsForGateway(root, filter, gatewayIds),
183
- gatewayIds,
184
- };
192
+ if (catalog.error) console.warn(`TSGW: ${catalog.error}`);
193
+ const models = effectiveModelsForGateway(root, filter, gatewayIds);
194
+ return { models, gatewayIds, catalog: { ...catalog, count: models.length } };
185
195
  }
186
196
 
187
197
  export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
188
198
  const settings = readTsgwSettings();
189
199
  const root = rootForRuntime(settings.baseUrl);
190
- const tsSearchMode: WebSearchMode =
200
+ const defaultSearchMode: WebSearchMode =
191
201
  settings.tsSearch === "cached" || settings.tsSearch === "live"
192
202
  ? settings.tsSearch
193
- : "off";
203
+ : "live";
204
+ let tsSearchMode = defaultSearchMode;
194
205
  const traceEnabled = settings.traceHeaders === true;
195
206
  const modelFilter: ModelFilter = {
196
207
  include: settings.includeModels,
@@ -207,12 +218,38 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
207
218
  };
208
219
 
209
220
  // 三层模型过滤:静态目录 ∩ 网关实际列表 ∩ 用户黑白名单。
210
- const { models, gatewayIds } = await resolveEffectiveModels(
221
+ const initial = await resolveEffectiveModels(
211
222
  root,
212
223
  modelFilter,
213
224
  cacheFilePath,
214
225
  );
226
+ const { models } = initial;
215
227
  let latestModels = models;
228
+ let catalog = initial.catalog;
229
+ let credentialConfigured = false;
230
+ let publishStatus: (() => void) | undefined;
231
+ let refreshRevision = 0;
232
+ let lifecycleRevision = 0;
233
+ const rootConfigured = root !== DEFAULT_ROOT;
234
+ const searchSupport = () => requestState?.provider === PROVIDER_ID
235
+ ? builtinSearchSupport(requestState.modelId, requestState.api) : undefined;
236
+ // Retain only the UI sink, never a lifecycle context; disconnect on shutdown.
237
+ const bindStatus = (ctx: ExtensionContext): void => {
238
+ if (!ctx.hasUI) {
239
+ publishStatus = undefined;
240
+ return;
241
+ }
242
+ credentialConfigured = ctx.modelRegistry.getProviderAuthStatus(PROVIDER_ID).configured;
243
+ const ui = ctx.ui;
244
+ publishStatus = () => {
245
+ ui.setStatus("command:/tsgw",
246
+ catalogLabel(catalog, credentialConfigured, rootConfigured));
247
+ ui.setStatus("command:/tsgw-search",
248
+ requestState?.provider === PROVIDER_ID
249
+ ? searchLabel(tsSearchMode, searchSupport()) : undefined);
250
+ };
251
+ publishStatus();
252
+ };
216
253
  pi.registerProvider(PROVIDER_ID, {
217
254
  name: "TSGW",
218
255
  baseUrl: `${root}/v1`,
@@ -222,108 +259,177 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
222
259
  async refreshModels(context) {
223
260
  if (!context.allowNetwork) return latestModels;
224
261
  context.signal.throwIfAborted();
225
- const credential = context.credential;
226
- if (credential?.type !== "api_key" || !credential.key)
227
- throw new Error("TSGW API key is unavailable for model refresh.");
228
-
229
- const gateway = await getGatewayModelIds(root, credential.key, {
230
- cacheFilePath,
231
- force: context.force === true,
232
- signal: context.signal,
233
- });
234
- context.signal.throwIfAborted();
235
- if (!gateway.ok)
236
- throw new Error(
237
- `TSGW gateway model refresh failed (${gateway.reason}).`,
238
- );
239
- if (gateway.stale)
240
- throw new Error(
241
- `TSGW gateway model refresh failed (${gateway.fallbackReason ?? "unknown"}); keeping the last successful catalog.`,
242
- );
243
-
244
- latestModels = effectiveModelsForGateway(
245
- root,
246
- modelFilter,
247
- new Set(gateway.ids),
248
- );
249
- return latestModels;
262
+ const revision = ++refreshRevision;
263
+ catalog = { ...catalog, loading: true };
264
+ publishStatus?.();
265
+ try {
266
+ const credential = context.credential;
267
+ credentialConfigured = credential?.type === "api_key" && !!credential.key;
268
+ if (credential?.type !== "api_key" || !credential.key)
269
+ throw new Error("TSGW API key is unavailable for model refresh.");
270
+ const gateway = await getGatewayModelIds(root, credential.key, {
271
+ cacheFilePath,
272
+ force: context.force === true,
273
+ signal: context.signal,
274
+ });
275
+ context.signal.throwIfAborted();
276
+ if (!gateway.ok)
277
+ throw new Error(`TSGW gateway model refresh failed (${gateway.reason}).`);
278
+ if (gateway.stale)
279
+ throw new Error("TSGW refresh failed; keeping the last successful catalog.");
280
+ if (revision === refreshRevision) {
281
+ latestModels = effectiveModelsForGateway(root, modelFilter, new Set(gateway.ids));
282
+ catalog = {
283
+ count: latestModels.length,
284
+ source: gateway.cached ? "cache" : "network",
285
+ storedAt: gateway.storedAt,
286
+ loading: false,
287
+ };
288
+ }
289
+ return latestModels;
290
+ } catch (error) {
291
+ if (revision === refreshRevision) catalog = {
292
+ ...catalog,
293
+ loading: false,
294
+ error: context.signal.aborted
295
+ ? "刷新已取消,保留原目录" : "刷新失败,保留原目录;请检查凭据、网关与网络",
296
+ };
297
+ throw error;
298
+ } finally {
299
+ if (revision === refreshRevision) publishStatus?.();
300
+ }
250
301
  },
251
302
  });
252
303
 
304
+ let refreshPending = false;
305
+ const refreshCatalog = async (ctx: ExtensionCommandContext): Promise<void> => {
306
+ if (refreshPending) return;
307
+ refreshPending = true;
308
+ const lifecycle = lifecycleRevision;
309
+ let revision = refreshRevision;
310
+ // Provider callbacks own their state; only diagnose failures before one starts.
311
+ const recordFailure = (message: string): void => {
312
+ if (revision === refreshRevision && !catalog.loading) {
313
+ catalog.error = message;
314
+ publishStatus?.();
315
+ }
316
+ };
317
+ try {
318
+ await ctx.waitForIdle();
319
+ if (lifecycle !== lifecycleRevision) return;
320
+ bindStatus(ctx);
321
+ if (!ctx.modelRegistry.getProviderAuthStatus(PROVIDER_ID).configured) {
322
+ ctx.ui.notify("TSGW model refresh skipped: configure an API key with /login first.", "warning");
323
+ return;
324
+ }
325
+ const count = () => ctx.modelRegistry.getAvailable()
326
+ .filter((model) => model.provider === PROVIDER_ID).length;
327
+ const before = count();
328
+ revision = refreshRevision;
329
+ // Older Pi versions return void instead of cancellation/error metadata.
330
+ const result = (await ctx.modelRegistry.refresh({
331
+ providers: [PROVIDER_ID], force: true,
332
+ })) as { aborted?: boolean; errors?: ReadonlyMap<string, Error> } | undefined;
333
+ if (lifecycle !== lifecycleRevision) return;
334
+ const after = count();
335
+ if (result?.aborted) {
336
+ recordFailure("刷新已取消,保留原目录");
337
+ ctx.ui.notify(`TSGW model refresh cancelled (${before} → ${after}).`, "warning");
338
+ } else if (result?.errors?.has(PROVIDER_ID)) {
339
+ recordFailure("刷新失败,保留原目录;请检查凭据、网关与网络");
340
+ ctx.ui.notify(`TSGW model refresh failed (${before} → ${after}).`, "error");
341
+ } else {
342
+ ctx.ui.notify(`TSGW models refreshed (${before} → ${after}).`, "info");
343
+ }
344
+ } catch {
345
+ if (lifecycle !== lifecycleRevision) return;
346
+ recordFailure("刷新失败,保留原目录;请检查凭据、网关与网络");
347
+ ctx.ui.notify("TSGW model refresh failed; keeping the previous catalog.", "error");
348
+ } finally {
349
+ if (lifecycle === lifecycleRevision) refreshPending = false;
350
+ }
351
+ };
253
352
  pi.registerCommand("tsgw-refresh", {
254
353
  description: "Force-refresh the TSGW gateway model catalog",
354
+ handler: async (_args, ctx) => refreshCatalog(ctx),
355
+ });
356
+ pi.registerCommand("tsgw", {
357
+ description: "TSGW model catalog and configuration diagnostics",
255
358
  handler: async (_args, ctx) => {
359
+ if (!ctx.hasUI) return;
360
+ const lifecycle = lifecycleRevision;
361
+ bindStatus(ctx);
362
+ const choice = await ctx.ui.select("TSGW", ["刷新模型目录", "查看状态与诊断"]);
363
+ if (lifecycle !== lifecycleRevision) return;
364
+ if (choice === "刷新模型目录") await refreshCatalog(ctx);
365
+ if (choice === "查看状态与诊断") {
366
+ bindStatus(ctx);
367
+ const diagnostics = catalogDiagnostics(catalog,
368
+ { credentialConfigured, rootConfigured, traceEnabled });
369
+ await ctx.ui.select("TSGW 状态与诊断(选择任一行关闭)", diagnostics.split("\n"));
370
+ }
371
+ },
372
+ });
373
+ pi.registerCommand("tsgw-search", {
374
+ description: "Change built-in web search for this session only",
375
+ handler: async (args, ctx) => {
376
+ const lifecycle = lifecycleRevision;
256
377
  await ctx.waitForIdle();
257
- if (!ctx.modelRegistry.getProviderAuthStatus(PROVIDER_ID).configured) {
258
- ctx.ui.notify(
259
- "TSGW model refresh skipped: configure an API key with /login first.",
260
- "warning",
261
- );
378
+ if (lifecycle !== lifecycleRevision) return;
379
+ refreshRequestState(ctx);
380
+ bindStatus(ctx);
381
+ const support = searchSupport();
382
+ if (!support) {
383
+ ctx.ui.notify("当前模型不支持插件内置联网。", "info");
262
384
  return;
263
385
  }
264
- const count = (): number =>
265
- ctx.modelRegistry
266
- .getAvailable()
267
- .filter((model) => model.provider === PROVIDER_ID).length;
268
- const before = count();
269
- try {
270
- // Pi 0.84+ returns cancellation/errors; older supported Pi versions
271
- // resolve void, so treat missing result metadata as success.
272
- const result = (await ctx.modelRegistry.refresh({
273
- providers: [PROVIDER_ID],
274
- force: true,
275
- })) as
276
- | {
277
- aborted?: boolean;
278
- errors?: ReadonlyMap<string, Error>;
279
- }
280
- | undefined;
281
- const after = count();
282
- const error = result?.errors?.get(PROVIDER_ID);
283
- if (result?.aborted) {
284
- ctx.ui.notify(
285
- `TSGW model refresh cancelled (${before} → ${after}).`,
286
- "warning",
287
- );
288
- } else if (error) {
289
- ctx.ui.notify(
290
- `TSGW model refresh failed (${before} → ${after}): ${error.message}`,
291
- "error",
292
- );
293
- } else {
294
- ctx.ui.notify(
295
- `TSGW models refreshed (${before} → ${after}).`,
296
- "info",
297
- );
298
- }
299
- } catch (error) {
300
- ctx.ui.notify(
301
- `TSGW model refresh failed (${before} → ${count()}): ${error instanceof Error ? error.message : String(error)}`,
302
- "error",
303
- );
386
+ if (support === "grok") {
387
+ ctx.ui.notify("当前 Grok 模型内置联网固定为实时;不修改 GPT 会话模式。", "info");
388
+ return;
389
+ }
390
+ const modes: WebSearchMode[] = ["cached", "live"];
391
+ const labels = modes.map((mode) => searchLabel(mode, support));
392
+ const input = args.trim();
393
+ const choice = input || (ctx.hasUI
394
+ ? await ctx.ui.select("内置联网(仅本会话)", labels) : undefined);
395
+ if (!choice || lifecycle !== lifecycleRevision) return;
396
+ if (searchSupport() !== support) {
397
+ ctx.ui.notify("模型支持性已变化,请重新选择内置联网模式。", "warning");
398
+ return;
304
399
  }
400
+ const mode = modes.find((mode, index) => mode === choice || labels[index] === choice);
401
+ if (!mode) {
402
+ ctx.ui.notify("不支持的模式;GPT 仅支持 cached/live,Grok 固定实时。", "warning");
403
+ return;
404
+ }
405
+ tsSearchMode = mode;
406
+ publishStatus?.();
407
+ ctx.ui.notify(`${searchLabel(mode, support)};仅本会话生效。`, "info");
305
408
  },
306
409
  });
307
410
 
308
- // ts_search 条件注册:固定白名单后端与可用模型列表有交集才注册,
309
- // 否则失活(避免注册一个无后端可用的死工具)。
310
- const availableIds =
311
- gatewayIds ?? new Set(modelsForRoot(root).map(({ id }) => id));
312
- if (DEFAULT_SEARCH_MODELS.some((id) => gatewayHasModel(availableIds, id))) {
313
- registerTsSearch(pi, { baseUrl: root });
314
- }
315
-
316
411
  pi.on("session_start", (_event, ctx) => {
412
+ lifecycleRevision++;
413
+ refreshPending = false;
414
+ tsSearchMode = defaultSearchMode;
317
415
  refreshRequestState(ctx);
416
+ bindStatus(ctx);
318
417
  });
319
418
  pi.on("agent_start", (_event, ctx) => {
320
419
  refreshRequestState(ctx);
420
+ bindStatus(ctx);
421
+ });
422
+ pi.on("session_shutdown", () => {
423
+ lifecycleRevision++;
424
+ refreshPending = false;
425
+ publishStatus = undefined;
321
426
  });
322
- pi.on("model_select", (event) => {
427
+ pi.on("model_select", (event, ctx) => {
323
428
  requestState = requestStateFor(
324
429
  event.model,
325
430
  requestState?.thinkingLevel ?? "off",
326
431
  );
432
+ if (ctx) bindStatus(ctx);
327
433
  });
328
434
  pi.on("thinking_level_select", (event) => {
329
435
  if (requestState)
@@ -5,6 +5,12 @@
5
5
  * 与 operations 调度都从这里引用,避免 vendors ↔ operations 循环依赖。
6
6
  */
7
7
 
8
+ import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
9
+
10
+ // Pi 1.x also includes image/classifier configs; this catalog is chat-only.
11
+ // Structural extraction keeps compatibility with the older chat-only type.
12
+ export type ChatModelConfig = Extract<ProviderModelConfig, { reasoning: boolean }>;
13
+
8
14
  export type ThinkingLevel =
9
15
  | "off"
10
16
  | "minimal"
@@ -13,7 +19,7 @@ export type ThinkingLevel =
13
19
  | "high"
14
20
  | "xhigh"
15
21
  | "max";
16
- export type WebSearchMode = "off" | "cached" | "live";
22
+ export type WebSearchMode = "cached" | "live";
17
23
 
18
24
  export interface ModelOperationContext {
19
25
  provider: string;
@@ -28,7 +34,7 @@ type GoogleThinkingField =
28
34
  | "includeThoughts"
29
35
  | "thinkingLevel"
30
36
  | "thinkingBudget";
31
- type ThinkingUpdate = Partial<Pick<Payload, "type" | "clear_thinking">>;
37
+ type ThinkingUpdate = Partial<Pick<Payload, "type" | "clear_thinking" | "keep">>;
32
38
  type GoogleThinkingUpdate = Partial<Pick<Payload, GoogleThinkingField>>;
33
39
 
34
40
  export function isPlainObject(value: unknown): value is Payload {
@@ -109,7 +115,7 @@ export class PayloadWriter {
109
115
  }
110
116
  }
111
117
 
112
- const THINKING_FIELDS = ["type", "clear_thinking"] as const;
118
+ const THINKING_FIELDS = ["type", "clear_thinking", "keep"] as const;
113
119
  const GOOGLE_THINKING_FIELDS = [
114
120
  "includeThoughts",
115
121
  "thinkingLevel",
@@ -1,4 +1,4 @@
1
- import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
1
+ import type { ChatModelConfig as ProviderModelConfig } from "./_tools.ts";
2
2
  import { anthropicModels } from "./vendors/anthropic.ts";
3
3
  import { deepseekModels } from "./vendors/deepseek.ts";
4
4
  import { geminiModels } from "./vendors/gemini.ts";