pi-tsgw 0.0.10 → 0.0.11

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
@@ -90,6 +90,39 @@ five-minute cache to avoid repeated requests. Run `/tsgw-refresh` to bypass the
90
90
  cache and force an immediate refresh without restarting or reloading Pi. If a
91
91
  refresh fails, the last successful model list remains active.
92
92
 
93
+ ## Status bar and session controls
94
+
95
+ Pi Web 0.11.0+ renders these extension statuses as clickable buttons:
96
+
97
+ - **`TSGW · N`** (`/tsgw`): one menu for **refreshing the model catalog** and
98
+ **viewing diagnostics**. The count is the filtered registered catalog, not a
99
+ count of healthy inference endpoints. 🟢 means a fresh directory result;
100
+ 🟡 means a static/expired directory or a failed refresh; ⚠️ means missing
101
+ credentials or gateway configuration; ⏳ means a refresh is running.
102
+ - **Built-in search** (`/tsgw-search`): choose a mode for the current session.
103
+ GPT offers `off / cached / live`; supported Grok models offer `off / live`
104
+ because the existing Grok request policy does not distinguish cache-only
105
+ search. Unsupported TSGW models are labeled accordingly; this button is
106
+ hidden when another provider is selected.
107
+
108
+ You can also type `/tsgw-search off`, `/tsgw-search cached`, or
109
+ `/tsgw-search live`. These controls do not modify `settings.json` or persist
110
+ across a reload or a new session; `tsgw.tsSearch` remains the startup default.
111
+
112
+ The standalone `ts_search` tool is no longer bundled. Use a separately configured
113
+ search tool such as `ts_oht.search` instead. Built-in model search remains
114
+ available and does not control external search tools.
115
+
116
+ Diagnostics show directory source, original fetch time, cache freshness,
117
+ configuration presence, and safe refresh error summaries—never API keys or
118
+ URLs. They make no extra network requests. Statuses update on session/model
119
+ activity and directory refreshes; there is no background health polling.
120
+
121
+ Icons use Emoji/Unicode: Pi Web currently strips ANSI colors from command
122
+ buttons. Busy sessions disable the buttons. The terminal CLI shows the same
123
+ statuses as text; use the slash commands there. Pi Web may not show extension
124
+ statuses until the session runtime has started.
125
+
93
126
  ## Development
94
127
 
95
128
  ```bash
@@ -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
203
  : "off";
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,174 @@ 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
+ const modes: WebSearchMode[] = support === "gpt"
387
+ ? ["off", "cached", "live"] : ["off", "live"];
388
+ const labels = modes.map((mode) => searchLabel(mode, support));
389
+ const input = args.trim();
390
+ const choice = input || (ctx.hasUI
391
+ ? await ctx.ui.select("内置联网(仅本会话)", labels) : undefined);
392
+ if (!choice || lifecycle !== lifecycleRevision) return;
393
+ if (searchSupport() !== support) {
394
+ ctx.ui.notify("模型支持性已变化,请重新选择内置联网模式。", "warning");
395
+ return;
304
396
  }
397
+ const mode = modes.find((mode, index) => mode === choice || labels[index] === choice);
398
+ if (!mode) {
399
+ ctx.ui.notify("不支持的模式;GPT: off/cached/live,Grok: off/live。", "warning");
400
+ return;
401
+ }
402
+ tsSearchMode = mode;
403
+ publishStatus?.();
404
+ ctx.ui.notify(`${searchLabel(mode, support)};仅本会话生效。`, "info");
305
405
  },
306
406
  });
307
407
 
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
408
  pi.on("session_start", (_event, ctx) => {
409
+ lifecycleRevision++;
410
+ refreshPending = false;
411
+ tsSearchMode = defaultSearchMode;
317
412
  refreshRequestState(ctx);
413
+ bindStatus(ctx);
318
414
  });
319
415
  pi.on("agent_start", (_event, ctx) => {
320
416
  refreshRequestState(ctx);
417
+ bindStatus(ctx);
418
+ });
419
+ pi.on("session_shutdown", () => {
420
+ lifecycleRevision++;
421
+ refreshPending = false;
422
+ publishStatus = undefined;
321
423
  });
322
- pi.on("model_select", (event) => {
424
+ pi.on("model_select", (event, ctx) => {
323
425
  requestState = requestStateFor(
324
426
  event.model,
325
427
  requestState?.thinkingLevel ?? "off",
326
428
  );
429
+ if (ctx) bindStatus(ctx);
327
430
  });
328
431
  pi.on("thinking_level_select", (event) => {
329
432
  if (requestState)
@@ -67,6 +67,7 @@ export type GetGatewayModelIdsResult =
67
67
  ids: string[];
68
68
  cached: boolean;
69
69
  stale: boolean;
70
+ storedAt: number;
70
71
  fallbackReason?: GatewayModelFailureReason;
71
72
  }
72
73
  | Extract<FetchGatewayModelIdsResult, { ok: false }>;
@@ -279,7 +280,14 @@ export async function getGatewayModelIds(
279
280
  const cache = cacheFor(key);
280
281
  if (!opts.force && cache.isFresh(now)) {
281
282
  const entry = cache.get();
282
- if (entry) return { ok: true, ids: entry.ids, cached: true, stale: false };
283
+ if (entry)
284
+ return {
285
+ ok: true,
286
+ ids: entry.ids,
287
+ cached: true,
288
+ stale: false,
289
+ storedAt: entry.storedAt,
290
+ };
283
291
  }
284
292
 
285
293
  const diskEntry = opts.cacheFilePath
@@ -294,6 +302,7 @@ export async function getGatewayModelIds(
294
302
  return {
295
303
  ok: true,
296
304
  ids: [...diskEntry.ids],
305
+ storedAt: diskEntry.storedAt,
297
306
  cached: true,
298
307
  stale: false,
299
308
  };
@@ -326,7 +335,13 @@ export async function getGatewayModelIds(
326
335
  cache.set(fetched.ids, now);
327
336
  if (opts.cacheFilePath)
328
337
  saveGatewayModelCache(opts.cacheFilePath, fetched.ids, now);
329
- return { ok: true, ids: [...fetched.ids], cached: false, stale: false };
338
+ return {
339
+ ok: true,
340
+ ids: [...fetched.ids],
341
+ cached: false,
342
+ stale: false,
343
+ storedAt: now,
344
+ };
330
345
  }
331
346
 
332
347
  const memoryEntry = cache.get();
@@ -340,6 +355,7 @@ export async function getGatewayModelIds(
340
355
  return {
341
356
  ok: true,
342
357
  ids: stale.ids,
358
+ storedAt: stale.storedAt,
343
359
  cached: true,
344
360
  stale: true,
345
361
  fallbackReason: fetched.reason,
@@ -20,6 +20,9 @@ export function openaiModels(root: string): ProviderModelConfig[] {
20
20
  baseUrl: v1,
21
21
  reasoning: true,
22
22
  thinkingLevelMap: {
23
+ // Pi treats omitted lower levels as supported; disable them explicitly.
24
+ off: null,
25
+ minimal: null,
23
26
  low: "low",
24
27
  medium: "medium",
25
28
  high: "high",
@@ -38,6 +41,9 @@ export function openaiModels(root: string): ProviderModelConfig[] {
38
41
  baseUrl: v1,
39
42
  reasoning: true,
40
43
  thinkingLevelMap: {
44
+ // Keep the lowest available level at low, including automatic titles.
45
+ off: null,
46
+ minimal: null,
41
47
  low: "low",
42
48
  medium: "medium",
43
49
  high: "high",
@@ -9,7 +9,7 @@
9
9
  * - Grok(openai-completions):追加 `search_parameters: { mode: "on" }`
10
10
  * (xAI 文档:https://docs.x.ai/developers/tools/web-search)
11
11
  *
12
- * 独立的 ts_search 工具(所有模型可用)单独实现,与内置查询注入分离。
12
+ * 独立搜索由外部工具提供,与本模块的内置查询注入无关。
13
13
  */
14
14
 
15
15
  import {
@@ -44,6 +44,18 @@ const GROK_SEARCH_MODELS = new Set([
44
44
  "grok-4.20-fast",
45
45
  ]);
46
46
 
47
+ /** Exact model/protocol support, shared by request injection and display code. */
48
+ export function builtinSearchSupport(
49
+ modelId: string,
50
+ api: string,
51
+ ): "gpt" | "grok" | undefined {
52
+ if (api === OPENAI_RESPONSES && BUILTIN_SEARCH_MODELS.has(modelId))
53
+ return "gpt";
54
+ if (api === OPENAI_COMPLETIONS && GROK_SEARCH_MODELS.has(modelId))
55
+ return "grok";
56
+ return undefined;
57
+ }
58
+
47
59
  function isExistingWebSearchTool(tools: readonly unknown[]): boolean {
48
60
  return tools.some((tool) => {
49
61
  if (!isPlainObject(tool) || typeof tool.type !== "string") return false;
@@ -93,12 +105,13 @@ export function applyBuiltinSearchTool<T>(
93
105
  ): T | Payload {
94
106
  if (!isPlainObject(payload) || mode === "off") return payload;
95
107
  const writer = new PayloadWriter(payload);
108
+ const support = builtinSearchSupport(modelId, api);
96
109
 
97
- if (api === OPENAI_RESPONSES && BUILTIN_SEARCH_MODELS.has(modelId)) {
110
+ if (support === "gpt") {
98
111
  applyGptSearch(writer, mode);
99
112
  return writer.result();
100
113
  }
101
- if (api === OPENAI_COMPLETIONS && GROK_SEARCH_MODELS.has(modelId)) {
114
+ if (support === "grok") {
102
115
  applyGrokSearch(writer);
103
116
  return writer.result();
104
117
  }
@@ -0,0 +1,89 @@
1
+ import type { WebSearchMode } from "./models/_tools.ts";
2
+ import { DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS } from "./models/gateway-catalog.ts";
3
+
4
+ export interface CatalogStatus {
5
+ count: number;
6
+ source: "static" | "cache" | "network";
7
+ /** 网关目录真实获取时间;从缓存读取时保留原值,不重置为读取时间。 */
8
+ storedAt?: number;
9
+ loading: boolean;
10
+ /** 调用者提供的安全摘要,不应包含密钥或 URL。 */
11
+ error?: string;
12
+ }
13
+
14
+ const SOURCE_LABELS = {
15
+ static: "内置静态",
16
+ cache: "缓存",
17
+ network: "网关",
18
+ } as const;
19
+
20
+ function fetchedAt(state: CatalogStatus): number | undefined {
21
+ const time = state.storedAt;
22
+ if (
23
+ state.source === "static" ||
24
+ time === undefined ||
25
+ !Number.isFinite(time) ||
26
+ time < 0 ||
27
+ Number.isNaN(new Date(time).getTime())
28
+ ) return undefined;
29
+ return time;
30
+ }
31
+
32
+ function freshness(state: CatalogStatus, now: number): "新鲜" | "过期" | "未知" {
33
+ const time = fetchedAt(state);
34
+ if (time === undefined || !Number.isFinite(now)) return "未知";
35
+ // 与目录缓存一致:时钟回拨不判过期,达到 TTL 则过期。
36
+ return Math.max(0, now - time) < DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS
37
+ ? "新鲜"
38
+ : "过期";
39
+ }
40
+
41
+ export function catalogLabel(
42
+ state: CatalogStatus,
43
+ credentialConfigured: boolean,
44
+ rootConfigured: boolean,
45
+ now = Date.now(),
46
+ ): string {
47
+ if (state.loading) return "⏳ TSGW";
48
+ const suffix = `TSGW · ${state.count}`;
49
+ if (!credentialConfigured || !rootConfigured) return `⚠️ ${suffix}`;
50
+ if (state.error || freshness(state, now) !== "新鲜") return `🟡 ${suffix}`;
51
+ return `🟢 ${suffix}`;
52
+ }
53
+
54
+ /** 纯展示:只接受配置是否存在,不读取配置,也不接收密钥或地址。 */
55
+ export function catalogDiagnostics(
56
+ state: CatalogStatus,
57
+ options: {
58
+ credentialConfigured: boolean;
59
+ rootConfigured: boolean;
60
+ traceEnabled: boolean;
61
+ },
62
+ now = Date.now(),
63
+ ): string {
64
+ const time = fetchedAt(state);
65
+ return [
66
+ `目录数量:${state.count}`,
67
+ `目录来源:${SOURCE_LABELS[state.source]}`,
68
+ `目录加载:${state.loading ? "进行中" : "未进行"}`,
69
+ `真实获取时间:${time === undefined ? "未知" : new Date(time).toISOString()}`,
70
+ "(保留网关实际获取时间,不是本轮缓存读取时间)",
71
+ `缓存状态:${freshness(state, now)}`,
72
+ `错误:${state.error || "无"}`,
73
+ `配置凭据:${options.credentialConfigured ? "存在" : "不存在"}`,
74
+ `网关地址:${options.rootConfigured ? "已设置" : "未设置"}`,
75
+ `追踪开关:${options.traceEnabled ? "开" : "关"}`,
76
+ "仅表示目录状态,不代表模型推理健康;不展示密钥或 URL。",
77
+ ].join("\n");
78
+ }
79
+
80
+ export function searchLabel(
81
+ mode: WebSearchMode,
82
+ support: "gpt" | "grok" | undefined,
83
+ ): string {
84
+ if (support === undefined) return "⚪ 内置联网:不支持";
85
+ if (mode === "off") return "⚪ 内置联网:关";
86
+ // Grok 的 cached/live 均注入 mode: "on",不能声称是缓存查询。
87
+ if (support === "grok" || mode === "live") return "🟢 内置联网:实时";
88
+ return "🟡 内置联网:缓存";
89
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tsgw",
3
- "version": "0.0.10",
3
+ "version": "0.0.11",
4
4
  "description": "Pi extension for the TOSSP AIH gateway: per-vendor model catalog and thinking operations for openai-completions, openai-responses, anthropic-messages, and google-generative-ai wire protocols.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -21,7 +21,7 @@
21
21
  ]
22
22
  },
23
23
  "scripts": {
24
- "test": "tsc -p tsconfig.test.json && node dist/extensions/index.test.js && node dist/extensions/models/operations.test.js && node dist/extensions/models/catalog.test.js && node dist/extensions/models/web-search.test.js && node dist/extensions/models/gateway-catalog.test.js && node dist/extensions/ts-search/ts-search.test.js"
24
+ "test": "tsc -p tsconfig.test.json && node dist/extensions/index.test.js && node dist/extensions/status.test.js && node dist/extensions/status-integration.test.js && node dist/extensions/models/gateway-catalog-metadata.test.js && node dist/extensions/models/operations.test.js && node dist/extensions/models/catalog.test.js && node dist/extensions/models/web-search.test.js && node dist/extensions/models/gateway-catalog.test.js"
25
25
  },
26
26
  "peerDependencies": {
27
27
  "@earendil-works/pi-coding-agent": ">=0.82.0",
@@ -1,499 +0,0 @@
1
- /**
2
- * 独立搜索工具(ts_search):任何模型均可通过配置或内置的 GPT / Grok
3
- * 后端执行联网搜索。模型模块自身的内置查询注入在 models/web-search.ts。
4
- */
5
-
6
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
- import { Type } from "typebox";
8
-
9
- export interface TsSearchOptions {
10
- baseUrl: string;
11
- apiKeyProvider?: string;
12
- searchModels?: readonly string[];
13
- }
14
-
15
- export const DEFAULT_SEARCH_MODELS = [
16
- "gpt-5.6-luna",
17
- "grok-chat-fast",
18
- ] as const;
19
- const CHAT_COMPLETIONS_PATH = "v1/chat/completions";
20
- const MAX_ATTEMPTS = 3;
21
- const REQUEST_TIMEOUT_MS = 45_000;
22
- const RETRY_DELAY_MS = 1_000;
23
- const SEARCH_PROMPT = [
24
- "Answer the user's question using the latest available information from the web.",
25
- "Be concise.",
26
- "If sources are available, include only the most relevant source URLs needed to support the answer; avoid link dumping.",
27
- "If no live web information is available, reply exactly: NO_LIVE_WEB.",
28
- ].join(" ");
29
- type SearchFamily = "gpt" | "grok";
30
-
31
- export function detectSearchFamily(
32
- model: string,
33
- ): SearchFamily | "unsupported" {
34
- const lower = model.toLowerCase();
35
- if (lower.startsWith("gpt-")) return "gpt";
36
- if (lower.startsWith("grok-")) return "grok";
37
- return "unsupported";
38
- }
39
-
40
- export function resolveSearchModels(
41
- options: Pick<TsSearchOptions, "searchModels"> = {},
42
- ): string[] {
43
- if (!options.searchModels) return [...DEFAULT_SEARCH_MODELS];
44
-
45
- const models: string[] = [];
46
- const seen = new Set<string>();
47
- for (const value of options.searchModels as readonly unknown[]) {
48
- const model = typeof value === "string" ? value.trim() : "";
49
- if (!model || detectSearchFamily(model) === "unsupported") {
50
- console.warn(
51
- `TSGW: ignoring invalid ts_search model ${JSON.stringify(value)}; expected gpt-* or grok-*`,
52
- );
53
- continue;
54
- }
55
- if (!seen.has(model)) {
56
- seen.add(model);
57
- models.push(model);
58
- }
59
- }
60
-
61
- return models.length > 0 ? models : [...DEFAULT_SEARCH_MODELS];
62
- }
63
-
64
- export function buildSearchUrl(baseUrl: string): string {
65
- const normalizedBase = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
66
- return new URL(CHAT_COMPLETIONS_PATH, normalizedBase).toString();
67
- }
68
-
69
- function flattenText(value: unknown): string {
70
- if (typeof value === "string") return value.trim();
71
- if (Array.isArray(value)) {
72
- return value
73
- .map((item) => flattenText(item))
74
- .filter(Boolean)
75
- .join("\n")
76
- .trim();
77
- }
78
- if (value && typeof value === "object") {
79
- const record = value as Record<string, unknown>;
80
- if (typeof record.text === "string") return record.text.trim();
81
- if (typeof record.content === "string") return record.content.trim();
82
- if (Array.isArray(record.content)) return flattenText(record.content);
83
- }
84
- return "";
85
- }
86
-
87
- function firstNonEmpty(values: unknown[]): string {
88
- for (const value of values) {
89
- const text = flattenText(value);
90
- if (text) return text;
91
- }
92
- return "";
93
- }
94
-
95
- function extractAnswer(payload: Record<string, unknown>): string {
96
- const choices = payload.choices;
97
- if (Array.isArray(choices) && choices.length > 0) {
98
- const first = choices[0] as Record<string, unknown>;
99
- const message = first.message as Record<string, unknown> | undefined;
100
- const answer = flattenText(message?.content);
101
- if (answer) return answer;
102
- const delta = first.delta as Record<string, unknown> | undefined;
103
- const deltaAnswer = flattenText(delta?.content);
104
- if (deltaAnswer) return deltaAnswer;
105
- }
106
- return firstNonEmpty([payload.output_text, payload.answer, payload.message]);
107
- }
108
-
109
- function collectUrls(input: unknown, output = new Set<string>()): Set<string> {
110
- if (typeof input === "string") {
111
- const matches = input.match(/https?:\/\/[^\s)\]}>"']+/g) ?? [];
112
- for (const match of matches) output.add(match.replace(/[.,;]+$/, ""));
113
- return output;
114
- }
115
- if (Array.isArray(input)) {
116
- for (const item of input) collectUrls(item, output);
117
- return output;
118
- }
119
- if (!input || typeof input !== "object") return output;
120
- for (const [key, value] of Object.entries(input)) {
121
- if (typeof value === "string" && key.toLowerCase().includes("url")) {
122
- collectUrls(value, output);
123
- continue;
124
- }
125
- if (
126
- key === "citations" ||
127
- key === "annotations" ||
128
- key === "sources" ||
129
- key === "search_results" ||
130
- key === "results" ||
131
- key === "references"
132
- ) {
133
- collectUrls(value, output);
134
- continue;
135
- }
136
- collectUrls(value, output);
137
- }
138
- return output;
139
- }
140
-
141
- export function buildSearchPayload(
142
- model: string,
143
- family: SearchFamily,
144
- query: string,
145
- ): Record<string, unknown> {
146
- const messages = [
147
- { role: "system", content: SEARCH_PROMPT },
148
- { role: "user", content: query },
149
- ];
150
- if (family === "gpt") {
151
- return {
152
- model,
153
- messages,
154
- tools: [
155
- {
156
- type: "web_search",
157
- search_context_size: "medium",
158
- external_web_access: true,
159
- },
160
- ],
161
- };
162
- }
163
- return { model, messages, search_parameters: { mode: "on" } };
164
- }
165
-
166
- export interface RouteResult {
167
- ok: boolean;
168
- model: string;
169
- family: SearchFamily;
170
- answer: string;
171
- urls: string[];
172
- requestId: string;
173
- error: string;
174
- }
175
-
176
- export interface SearchRetryOptions {
177
- delayMs?: number;
178
- requestTimeoutMs?: number;
179
- fetch?: typeof fetch;
180
- }
181
-
182
- interface SearchAttemptResult {
183
- result: RouteResult;
184
- retryable: boolean;
185
- }
186
-
187
- function failedAttempt(
188
- model: string,
189
- family: SearchFamily,
190
- error: string,
191
- retryable: boolean,
192
- requestId = "",
193
- ): SearchAttemptResult {
194
- return {
195
- result: { ...buildFailure(model, family, error), requestId },
196
- retryable,
197
- };
198
- }
199
-
200
- function requestSignal(
201
- signal: AbortSignal | undefined,
202
- timeoutMs: number,
203
- ): AbortSignal {
204
- const timeout = AbortSignal.timeout(timeoutMs);
205
- return signal ? AbortSignal.any([signal, timeout]) : timeout;
206
- }
207
-
208
- function waitForRetry(
209
- delayMs: number,
210
- signal: AbortSignal | undefined,
211
- ): Promise<void> {
212
- if (delayMs <= 0) return Promise.resolve();
213
- if (signal?.aborted) return Promise.reject(signal.reason);
214
-
215
- return new Promise((resolve, reject) => {
216
- const onAbort = (): void => {
217
- clearTimeout(timer);
218
- reject(signal?.reason);
219
- };
220
- const timer = setTimeout(() => {
221
- signal?.removeEventListener("abort", onAbort);
222
- resolve();
223
- }, delayMs);
224
- signal?.addEventListener("abort", onAbort, { once: true });
225
- });
226
- }
227
-
228
- async function executeSearchAttempt(
229
- model: string,
230
- query: string,
231
- apiKey: string,
232
- baseUrl: string,
233
- signal: AbortSignal | undefined,
234
- fetchImpl: typeof fetch,
235
- requestTimeoutMs: number,
236
- ): Promise<SearchAttemptResult> {
237
- const family = detectSearchFamily(model);
238
- if (family === "unsupported")
239
- return failedAttempt(model, "gpt", `不支持的模型系列:${model}`, false);
240
- if (signal?.aborted)
241
- return failedAttempt(model, family, "请求已取消。", false);
242
-
243
- let response: Response;
244
- try {
245
- response = await fetchImpl(buildSearchUrl(baseUrl), {
246
- method: "POST",
247
- headers: {
248
- authorization: `Bearer ${apiKey}`,
249
- "content-type": "application/json",
250
- },
251
- body: JSON.stringify(buildSearchPayload(model, family, query)),
252
- signal: requestSignal(signal, requestTimeoutMs),
253
- });
254
- } catch (error) {
255
- return failedAttempt(
256
- model,
257
- family,
258
- signal?.aborted
259
- ? "请求已取消。"
260
- : `请求失败:${error instanceof Error ? error.message : String(error)}`,
261
- !signal?.aborted,
262
- );
263
- }
264
-
265
- const requestId = response.headers.get("ah-request-id") ?? "";
266
- let bodyText: string;
267
- try {
268
- bodyText = await response.text();
269
- } catch (error) {
270
- return failedAttempt(
271
- model,
272
- family,
273
- signal?.aborted
274
- ? "请求已取消。"
275
- : `读取网关响应失败:${error instanceof Error ? error.message : String(error)}`,
276
- !signal?.aborted,
277
- requestId,
278
- );
279
- }
280
- if (!response.ok)
281
- return failedAttempt(
282
- model,
283
- family,
284
- `网关请求失败:HTTP ${response.status} ${response.statusText}\n${bodyText}`,
285
- response.status === 429 || response.status >= 500,
286
- requestId,
287
- );
288
-
289
- try {
290
- const parsed: unknown = JSON.parse(bodyText);
291
- if (parsed && typeof parsed === "object") {
292
- const record = parsed as Record<string, unknown>;
293
- return {
294
- result: {
295
- ok: true,
296
- model,
297
- family,
298
- answer: extractAnswer(record) || JSON.stringify(record),
299
- urls: Array.from(collectUrls(record)),
300
- requestId,
301
- error: "",
302
- },
303
- retryable: false,
304
- };
305
- }
306
- } catch {
307
- // 非 JSON 响应按纯文本处理。
308
- }
309
- return {
310
- result: {
311
- ok: true,
312
- model,
313
- family,
314
- answer: bodyText || "网关返回空响应。",
315
- urls: Array.from(collectUrls(bodyText)),
316
- requestId,
317
- error: "",
318
- },
319
- retryable: false,
320
- };
321
- }
322
-
323
- export async function retrySearchRoute(
324
- model: string,
325
- query: string,
326
- apiKey: string,
327
- baseUrl: string,
328
- signal: AbortSignal | undefined,
329
- options: SearchRetryOptions = {},
330
- ): Promise<RouteResult> {
331
- const delayMs = options.delayMs ?? RETRY_DELAY_MS;
332
- const requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
333
- const fetchImpl = options.fetch ?? globalThis.fetch;
334
- let lastResult = buildFailure(model, "gpt", "搜索请求未执行。");
335
-
336
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
337
- const current = await executeSearchAttempt(
338
- model,
339
- query,
340
- apiKey,
341
- baseUrl,
342
- signal,
343
- fetchImpl,
344
- requestTimeoutMs,
345
- );
346
- lastResult = current.result;
347
- if (current.result.ok || !current.retryable || attempt === MAX_ATTEMPTS - 1)
348
- return current.result;
349
-
350
- try {
351
- await waitForRetry(delayMs * 2 ** attempt, signal);
352
- } catch {
353
- const family = detectSearchFamily(model);
354
- return buildFailure(
355
- model,
356
- family === "grok" ? "grok" : "gpt",
357
- "请求已取消。",
358
- );
359
- }
360
- }
361
-
362
- return lastResult;
363
- }
364
-
365
- function buildFailure(
366
- model: string,
367
- family: SearchFamily,
368
- error: string,
369
- ): RouteResult {
370
- return {
371
- ok: false,
372
- model,
373
- family,
374
- answer: "",
375
- urls: [],
376
- requestId: "",
377
- error,
378
- };
379
- }
380
-
381
- function renderMergedResult(results: RouteResult[]): string {
382
- const succeeded = results.filter((item) => item.ok);
383
- const failed = results.filter((item) => !item.ok);
384
- const status =
385
- succeeded.length === results.length
386
- ? "成功"
387
- : succeeded.length > 0
388
- ? "部分成功"
389
- : "失败";
390
- const lines = ["后端:tsgw", `状态:${status}`];
391
-
392
- if (succeeded.length === 0) {
393
- const summary = failed
394
- .map(
395
- (item) =>
396
- `${item.family}(${item.model}):${item.error || "未知错误"}`,
397
- )
398
- .join(";");
399
- lines.push(`全部搜索后端失败:${summary}`);
400
- return lines.join("\n");
401
- }
402
-
403
- for (const item of succeeded) {
404
- lines.push(
405
- `${item.family}(${item.model})结果:`,
406
- item.answer || "未返回答案。",
407
- );
408
- }
409
-
410
- const mergedUrls = Array.from(
411
- new Set(succeeded.flatMap((item) => item.urls)),
412
- );
413
- lines.push("来源链接:");
414
- if (mergedUrls.length) {
415
- for (const url of mergedUrls) lines.push(`- ${url}`);
416
- } else {
417
- lines.push("- 无");
418
- }
419
- for (const item of failed) {
420
- lines.push(`注:${item.family} 后端不可用,已跳过。`);
421
- }
422
- return lines.join("\n");
423
- }
424
-
425
- export function registerTsSearch(
426
- pi: ExtensionAPI,
427
- options: TsSearchOptions,
428
- ): void {
429
- const models = resolveSearchModels(options);
430
- const argsSchema = Type.Object({
431
- query: Type.String({ minLength: 1, description: "搜索查询" }),
432
- });
433
-
434
- pi.registerTool({
435
- name: "ts_search",
436
- label: "TS Search",
437
- description:
438
- "统一网络搜索:通过网关的 GPT / Grok 模型执行联网搜索并返回最新结果。任何模型都可调用。",
439
- parameters: argsSchema,
440
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
441
- const query = params.query.trim();
442
- if (!query) {
443
- return {
444
- content: [{ type: "text", text: "ts_search:查询内容不能为空。" }],
445
- details: {},
446
- };
447
- }
448
-
449
- const apiKeyProvider = options.apiKeyProvider ?? "tsgw";
450
- let apiKey = "";
451
- try {
452
- apiKey =
453
- (await ctx.modelRegistry.getApiKeyForProvider(apiKeyProvider)) ?? "";
454
- } catch (error) {
455
- return {
456
- content: [
457
- {
458
- type: "text",
459
- text: `ts_search:解析 API key 失败:${error instanceof Error ? error.message : String(error)}`,
460
- },
461
- ],
462
- details: {},
463
- };
464
- }
465
- if (!apiKey) {
466
- return {
467
- content: [
468
- {
469
- type: "text",
470
- text: `ts_search:未找到 ${apiKeyProvider} provider 的 API key,请运行 /login 完成配置。`,
471
- },
472
- ],
473
- details: {},
474
- };
475
- }
476
-
477
- const settled = await Promise.allSettled(
478
- models.map((model) =>
479
- retrySearchRoute(model, query, apiKey, options.baseUrl, signal),
480
- ),
481
- );
482
- const results = settled.map((item, index) => {
483
- if (item.status === "fulfilled") return item.value;
484
- const model = models[index];
485
- const family = detectSearchFamily(model);
486
- return buildFailure(
487
- model,
488
- family === "grok" ? "grok" : "gpt",
489
- `搜索路由异常:${String(item.reason)}`,
490
- );
491
- });
492
-
493
- return {
494
- content: [{ type: "text", text: renderMergedResult(results) }],
495
- details: {},
496
- };
497
- },
498
- });
499
- }