pi-tsgw 0.0.2 → 0.0.4

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
@@ -36,10 +36,10 @@ Example:
36
36
  {
37
37
  "tsgw": {
38
38
  "baseUrl": "https://aih.example.net",
39
- "webSearch": "off",
39
+ "tsSearch": "off",
40
40
  "traceHeaders": false,
41
- "includeModels": ["gpt-5.6-*", "claude-*"],
42
- "excludeModels": ["gpt-5.3-*"]
41
+ "excludeModels": ["gpt-*", "claude-*"],
42
+ "includeModels": ["gpt-5.6-*"]
43
43
  }
44
44
  }
45
45
  ```
@@ -64,10 +64,10 @@ The extension never reads credential files. Pi resolves the key itself:
64
64
  | Setting (`settings.json` `tsgw.*`) | Default | Meaning |
65
65
  | --- | --- | --- |
66
66
  | `baseUrl` | placeholder | Gateway root (the `/v1` suffix is normalized away) |
67
- | `webSearch` | `off` | `off`, `cached`, or `live` — appends the built-in `web_search` tool for models with built-in search (GPT / Grok) |
67
+ | `tsSearch` | `off` | `off`, `cached`, or `live` — appends the built-in `web_search` tool for models with built-in search (GPT / Grok) |
68
68
  | `traceHeaders` | `false` | Adds `AH-Thread-Id` / `AH-Trace-Id` headers for gateway-side tracing |
69
- | `includeModels` | unset | Whitelist: only these model ids are registered (exact id or `prefix-*` glob) |
70
- | `excludeModels` | unset | Blacklist: these model ids are dropped (exact id or `prefix-*` glob); blacklist wins over whitelist |
69
+ | `includeModels` | unset | Re-include override: matching model ids are kept even when also matched by `excludeModels` (exact id or `prefix-*` glob) |
70
+ | `excludeModels` | unset | Blacklist: matching model ids are dropped unless pulled back by `includeModels` (exact id or `prefix-*` glob) |
71
71
 
72
72
  ## Model catalog
73
73
 
@@ -79,8 +79,11 @@ carries the official documentation URL in its header comment. Pricing entries
79
79
  mirror the vendors' public list prices; replace them with your gateway's
80
80
  actual pricing if it differs.
81
81
 
82
- Use `includeModels` / `excludeModels` to register only the models your
83
- gateway plan actually supports.
82
+ Use broad `excludeModels` rules to drop model families and precise
83
+ `includeModels` rules to pull selected models back. `includeModels` is not a
84
+ global whitelist: models matching neither list remain available. To register
85
+ only selected models, use `"excludeModels": ["*"]` and pull them back through
86
+ `includeModels`.
84
87
 
85
88
  ## Development
86
89
 
@@ -1,18 +1,28 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ CONFIG_DIR_NAME,
4
+ getAgentDir,
5
+ readStoredCredential,
6
+ } from "@earendil-works/pi-coding-agent";
3
7
  import { readFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
4
9
  import { join } from "node:path";
5
10
  import { randomUUID } from "node:crypto";
6
11
  import {
7
12
  DEFAULT_ROOT,
8
13
  PROVIDER_ID,
14
+ filterModels,
9
15
  modelsForRoot,
10
16
  normalizeRoot,
11
17
  type ModelFilter,
12
18
  } from "./models/catalog.ts";
19
+ import { getGatewayModelIds } from "./models/gateway-catalog.ts";
13
20
  import { applyModelOperations } from "./models/operations.ts";
14
21
  import type { ThinkingLevel, WebSearchMode } from "./models/_tools.ts";
15
- import { applyWebSearchTool } from "./web-search/web-search.ts";
22
+ import {
23
+ DEFAULT_SEARCH_MODELS,
24
+ registerTsSearch,
25
+ } from "./ts-search/ts-search.ts";
16
26
 
17
27
  /**
18
28
  * The data needed by provider hooks, copied while the lifecycle context is
@@ -40,7 +50,7 @@ interface RequestModel {
40
50
  */
41
51
  interface TsgwSettings {
42
52
  baseUrl?: string;
43
- webSearch?: string;
53
+ tsSearch?: string;
44
54
  traceHeaders?: boolean;
45
55
  includeModels?: string[];
46
56
  excludeModels?: string[];
@@ -105,12 +115,72 @@ function isTsgwTraceTarget(state: RequestState, root: string): boolean {
105
115
  }
106
116
  }
107
117
 
118
+ /** 网关 id 匹配:精确匹配,或允许带供应商前缀变体(google/gemini-3.5-flash 匹配 gemini-3.5-flash)。 */
119
+ function gatewayHasModel(gatewayIds: ReadonlySet<string>, id: string): boolean {
120
+ if (gatewayIds.has(id)) return true;
121
+ const suffix = `/${id}`;
122
+ for (const gatewayId of gatewayIds)
123
+ if (gatewayId.endsWith(suffix)) return true;
124
+ return false;
125
+ }
126
+
127
+ /** 模型缓存文件:~/.pi/tsgw/models-cache.json(CONFIG_DIR_NAME 跟随 piConfig 覆盖)。 */
128
+ function gatewayModelCachePath(): string {
129
+ return join(homedir(), CONFIG_DIR_NAME, "tsgw", "models-cache.json");
130
+ }
131
+
132
+ /**
133
+ * 三层模型过滤:静态目录 ∩ 网关实际列表 ∩ 用户黑白名单。
134
+ * 网关列表拉取失败/无凭据时跳过网关层(回退静态目录)。
135
+ */
136
+ async function resolveEffectiveModels(
137
+ root: string,
138
+ filter: ModelFilter | undefined,
139
+ ): Promise<{
140
+ models: ReturnType<typeof modelsForRoot>;
141
+ gatewayIds: ReadonlySet<string> | undefined;
142
+ }> {
143
+ const staticModels = modelsForRoot(root);
144
+
145
+ // 凭据解析失败不阻塞:无凭据时直接跳过网关层。
146
+ let apiKey = "";
147
+ try {
148
+ const credential = readStoredCredential(PROVIDER_ID);
149
+ apiKey = credential?.type === "api_key" ? (credential.key ?? "") : "";
150
+ } catch {
151
+ apiKey = "";
152
+ }
153
+
154
+ let gatewayIds: ReadonlySet<string> | undefined;
155
+ if (apiKey) {
156
+ try {
157
+ const gateway = await getGatewayModelIds(root, apiKey, {
158
+ cacheFilePath: gatewayModelCachePath(),
159
+ });
160
+ if (gateway.ok) gatewayIds = new Set(gateway.ids);
161
+ else
162
+ console.warn(
163
+ `TSGW: gateway model list unavailable (${gateway.reason ?? "unknown"}); using static catalog.`,
164
+ );
165
+ } catch (error) {
166
+ console.warn(
167
+ `TSGW: gateway model list load failed; using static catalog.`,
168
+ );
169
+ }
170
+ }
171
+
172
+ const intersected = gatewayIds
173
+ ? staticModels.filter((model) => gatewayHasModel(gatewayIds, model.id))
174
+ : staticModels;
175
+ return { models: filterModels(intersected, filter), gatewayIds };
176
+ }
177
+
108
178
  export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
109
179
  const settings = readTsgwSettings();
110
180
  const root = rootForRuntime(settings.baseUrl);
111
- const webSearchMode: WebSearchMode =
112
- settings.webSearch === "cached" || settings.webSearch === "live"
113
- ? settings.webSearch
181
+ const tsSearchMode: WebSearchMode =
182
+ settings.tsSearch === "cached" || settings.tsSearch === "live"
183
+ ? settings.tsSearch
114
184
  : "off";
115
185
  const traceEnabled = settings.traceHeaders === true;
116
186
  const modelFilter: ModelFilter = {
@@ -126,14 +196,27 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
126
196
  requestState = requestStateFor(ctx.model, ctx.thinkingLevel ?? "off");
127
197
  };
128
198
 
199
+ // 三层模型过滤:静态目录 ∩ 网关实际列表 ∩ 用户黑白名单。
200
+ const { models, gatewayIds } = await resolveEffectiveModels(
201
+ root,
202
+ modelFilter,
203
+ );
129
204
  pi.registerProvider(PROVIDER_ID, {
130
205
  name: "TSGW",
131
206
  baseUrl: `${root}/v1`,
132
207
  api: "openai-completions",
133
208
  apiKey: "$TSGW_API_KEY",
134
- models: modelsForRoot(root, modelFilter),
209
+ models,
135
210
  });
136
211
 
212
+ // ts_search 条件注册:固定白名单后端与可用模型列表有交集才注册,
213
+ // 否则失活(避免注册一个无后端可用的死工具)。
214
+ const availableIds =
215
+ gatewayIds ?? new Set(modelsForRoot(root).map(({ id }) => id));
216
+ if (DEFAULT_SEARCH_MODELS.some((id) => gatewayHasModel(availableIds, id))) {
217
+ registerTsSearch(pi, { baseUrl: root });
218
+ }
219
+
137
220
  pi.on("session_start", (_event, ctx) => {
138
221
  refreshRequestState(ctx);
139
222
  });
@@ -159,13 +242,10 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
159
242
  modelId: state.modelId,
160
243
  api: state.api,
161
244
  thinkingLevel: state.thinkingLevel,
245
+ tsSearchMode: tsSearchMode,
162
246
  };
163
- // 模型模块:厂商思维链改写 → 网络模块:内置查询工具注入(两模块互不感知)。
164
- return applyWebSearchTool(applyModelOperations(event.payload, context), {
165
- modelId: state.modelId,
166
- api: state.api,
167
- mode: webSearchMode,
168
- });
247
+ // 模型模块统一完成请求改写:厂商思维链策略 + 内置查询工具注入。
248
+ return applyModelOperations(event.payload, context);
169
249
  });
170
250
 
171
251
  if (!traceEnabled) return;
@@ -20,6 +20,7 @@ export interface ModelOperationContext {
20
20
  modelId: string;
21
21
  api: string;
22
22
  thinkingLevel: ThinkingLevel;
23
+ tsSearchMode: WebSearchMode;
23
24
  }
24
25
 
25
26
  export type Payload = Record<string, unknown>;
@@ -3,6 +3,7 @@ import { anthropicModels } from "./vendors/anthropic.ts";
3
3
  import { deepseekModels } from "./vendors/deepseek.ts";
4
4
  import { geminiModels } from "./vendors/gemini.ts";
5
5
  import { glmModels } from "./vendors/glm.ts";
6
+ import { grokModels } from "./vendors/grok.ts";
6
7
  import { kimiModels } from "./vendors/kimi.ts";
7
8
  import { longcatModels } from "./vendors/longcat.ts";
8
9
  import { mimoModels } from "./vendors/mimo.ts";
@@ -40,7 +41,7 @@ export function normalizeRoot(value = DEFAULT_ROOT): string {
40
41
  return url.toString().replace(/\/$/, "");
41
42
  }
42
43
 
43
- /** 模型黑白名单。`include` 只保留匹配的模型;`exclude` 始终生效(黑名单优先)。 */
44
+ /** 模型黑白名单。`exclude` 负责排除;`include` 可拉回匹配项(拉回优先)。 */
44
45
  export interface ModelFilter {
45
46
  include?: readonly string[];
46
47
  exclude?: readonly string[];
@@ -56,7 +57,7 @@ function compilePatterns(patterns: readonly string[]): (id: string) => boolean {
56
57
  return (id) => patterns.some((pattern) => matches(pattern, id));
57
58
  }
58
59
 
59
- /** 按黑白名单过滤模型目录;无过滤条件时原样返回。 */
60
+ /** 按“拉回优先”语义过滤模型目录;无过滤条件时原样返回。 */
60
61
  export function filterModels(
61
62
  models: readonly ProviderModelConfig[],
62
63
  filter?: ModelFilter,
@@ -68,10 +69,11 @@ export function filterModels(
68
69
  const exclude = filter.exclude?.length
69
70
  ? compilePatterns(filter.exclude)
70
71
  : undefined;
71
- return models.filter(
72
- (model) =>
73
- (!include || include(model.id)) && (!exclude || !exclude(model.id)),
74
- );
72
+ return models.filter((model) => {
73
+ const included = include?.(model.id) ?? false;
74
+ const excluded = exclude?.(model.id) ?? false;
75
+ return included || !excluded;
76
+ });
75
77
  }
76
78
 
77
79
  /**
@@ -95,6 +97,7 @@ export function modelsForRoot(
95
97
  ...openaiModels(root),
96
98
  ...geminiModels(root),
97
99
  ...anthropicModels(root),
100
+ ...grokModels(root),
98
101
  ];
99
102
  return filterModels(models, filter);
100
103
  }
@@ -0,0 +1,333 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ mkdirSync,
4
+ readFileSync,
5
+ renameSync,
6
+ unlinkSync,
7
+ writeFileSync,
8
+ } from "node:fs";
9
+ import { dirname } from "node:path";
10
+
11
+ export const DEFAULT_GATEWAY_MODEL_TIMEOUT_MS = 5_000;
12
+ export const DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS = 5 * 60 * 1_000;
13
+
14
+ export type GatewayModelFailureReason =
15
+ | "http"
16
+ | "timeout"
17
+ | "network"
18
+ | "invalid-json"
19
+ | "invalid-data"
20
+ | "empty";
21
+
22
+ export type GatewayFetch = (
23
+ input: string | URL,
24
+ init?: RequestInit,
25
+ ) => Promise<Response>;
26
+
27
+ export interface FetchGatewayModelIdsOptions {
28
+ timeoutMs?: number;
29
+ fetcher?: GatewayFetch;
30
+ }
31
+
32
+ export interface GetGatewayModelIdsOptions extends FetchGatewayModelIdsOptions {
33
+ cacheFilePath?: string;
34
+ }
35
+
36
+ export type FetchGatewayModelIdsResult =
37
+ | { ok: true; ids: string[] }
38
+ | {
39
+ ok: false;
40
+ reason: GatewayModelFailureReason;
41
+ status?: number;
42
+ detail?: string;
43
+ };
44
+
45
+ export interface ModelCacheEntry {
46
+ ids: string[];
47
+ storedAt: number;
48
+ }
49
+
50
+ export interface ModelCache {
51
+ get(): ModelCacheEntry | undefined;
52
+ set(ids: readonly string[], now?: number): void;
53
+ isFresh(now?: number): boolean;
54
+ }
55
+
56
+ export interface LoadedGatewayModelCache {
57
+ ids: string[];
58
+ fresh: boolean;
59
+ }
60
+
61
+ export type GetGatewayModelIdsResult =
62
+ | {
63
+ ok: true;
64
+ ids: string[];
65
+ cached: boolean;
66
+ stale: boolean;
67
+ fallbackReason?: GatewayModelFailureReason;
68
+ }
69
+ | Extract<FetchGatewayModelIdsResult, { ok: false }>;
70
+
71
+ function errorDetail(error: unknown): string {
72
+ return error instanceof Error ? error.message : String(error);
73
+ }
74
+
75
+ function modelsUrl(baseUrl: string): string {
76
+ return `${baseUrl.replace(/\/+$/, "")}/v1/models`;
77
+ }
78
+
79
+ function uniqueModelIds(data: unknown[]): string[] {
80
+ const ids = new Set<string>();
81
+ for (const item of data) {
82
+ if (!item || typeof item !== "object") continue;
83
+ const id = (item as { id?: unknown }).id;
84
+ if (typeof id === "string" && id.trim()) ids.add(id.trim());
85
+ }
86
+ return Array.from(ids);
87
+ }
88
+
89
+ /** Load the OpenAI-compatible model list exposed by a gateway. */
90
+ export async function fetchGatewayModelIds(
91
+ baseUrl: string,
92
+ apiKey: string,
93
+ opts: FetchGatewayModelIdsOptions = {},
94
+ ): Promise<FetchGatewayModelIdsResult> {
95
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_GATEWAY_MODEL_TIMEOUT_MS;
96
+ const fetcher = opts.fetcher ?? globalThis.fetch;
97
+ const controller = new AbortController();
98
+ let timedOut = false;
99
+ const timeout = setTimeout(
100
+ () => {
101
+ timedOut = true;
102
+ controller.abort();
103
+ },
104
+ Math.max(0, timeoutMs),
105
+ );
106
+
107
+ try {
108
+ let response: Response;
109
+ try {
110
+ response = await fetcher(modelsUrl(baseUrl), {
111
+ method: "GET",
112
+ headers: { authorization: `Bearer ${apiKey}` },
113
+ signal: controller.signal,
114
+ });
115
+ } catch (error) {
116
+ return timedOut
117
+ ? { ok: false, reason: "timeout" }
118
+ : { ok: false, reason: "network", detail: errorDetail(error) };
119
+ }
120
+
121
+ if (!response.ok) {
122
+ return { ok: false, reason: "http", status: response.status };
123
+ }
124
+
125
+ let payload: unknown;
126
+ try {
127
+ payload = await response.json();
128
+ } catch (error) {
129
+ return timedOut
130
+ ? { ok: false, reason: "timeout" }
131
+ : { ok: false, reason: "invalid-json", detail: errorDetail(error) };
132
+ }
133
+
134
+ if (!payload || typeof payload !== "object")
135
+ return { ok: false, reason: "invalid-data" };
136
+ const data = (payload as { data?: unknown }).data;
137
+ if (!Array.isArray(data)) return { ok: false, reason: "invalid-data" };
138
+ const ids = uniqueModelIds(data);
139
+ if (ids.length === 0) return { ok: false, reason: "empty" };
140
+ return { ok: true, ids };
141
+ } finally {
142
+ clearTimeout(timeout);
143
+ }
144
+ }
145
+
146
+ /** Create a defensive, in-memory TTL cache for a gateway model list. */
147
+ export function createModelCache(
148
+ ttlMs = DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS,
149
+ ): ModelCache {
150
+ if (!Number.isFinite(ttlMs) || ttlMs < 0)
151
+ throw new RangeError("ttlMs must be a non-negative finite number");
152
+ let entry: ModelCacheEntry | undefined;
153
+
154
+ return {
155
+ get() {
156
+ return entry
157
+ ? { ids: [...entry.ids], storedAt: entry.storedAt }
158
+ : undefined;
159
+ },
160
+ set(ids, now = Date.now()) {
161
+ entry = { ids: [...ids], storedAt: now };
162
+ },
163
+ isFresh(now = Date.now()) {
164
+ if (!entry) return false;
165
+ return Math.max(0, now - entry.storedAt) < ttlMs;
166
+ },
167
+ };
168
+ }
169
+
170
+ function readGatewayModelCacheEntry(
171
+ filePath: string,
172
+ ): ModelCacheEntry | undefined {
173
+ try {
174
+ const payload: unknown = JSON.parse(readFileSync(filePath, "utf8"));
175
+ if (!payload || typeof payload !== "object") return undefined;
176
+ const { storedAt, ids } = payload as {
177
+ storedAt?: unknown;
178
+ ids?: unknown;
179
+ };
180
+ if (
181
+ typeof storedAt !== "number" ||
182
+ !Number.isFinite(storedAt) ||
183
+ storedAt < 0 ||
184
+ !Array.isArray(ids) ||
185
+ !ids.every((id) => typeof id === "string" && id.trim())
186
+ )
187
+ return undefined;
188
+ return {
189
+ storedAt,
190
+ ids: Array.from(new Set(ids.map((id) => id.trim()))),
191
+ };
192
+ } catch {
193
+ return undefined;
194
+ }
195
+ }
196
+
197
+ function isCacheEntryFresh(
198
+ entry: ModelCacheEntry,
199
+ now: number,
200
+ ttlMs: number,
201
+ ): boolean {
202
+ return Math.max(0, now - entry.storedAt) < ttlMs;
203
+ }
204
+
205
+ /** Atomically persist gateway model IDs. Write failures are non-fatal. */
206
+ export function saveGatewayModelCache(
207
+ filePath: string,
208
+ ids: readonly string[],
209
+ now = Date.now(),
210
+ ): void {
211
+ const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
212
+ try {
213
+ mkdirSync(dirname(filePath), { recursive: true });
214
+ writeFileSync(
215
+ temporaryPath,
216
+ JSON.stringify({ storedAt: now, ids: [...ids] }),
217
+ { encoding: "utf8", mode: 0o600 },
218
+ );
219
+ renameSync(temporaryPath, filePath);
220
+ } catch {
221
+ try {
222
+ unlinkSync(temporaryPath);
223
+ } catch {
224
+ // The temporary file may not have been created.
225
+ }
226
+ }
227
+ }
228
+
229
+ /** Load a persisted gateway model list. Missing or invalid files are ignored. */
230
+ export function loadGatewayModelCache(
231
+ filePath: string,
232
+ now = Date.now(),
233
+ ttlMs = DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS,
234
+ ): LoadedGatewayModelCache | undefined {
235
+ if (!Number.isFinite(ttlMs) || ttlMs < 0)
236
+ throw new RangeError("ttlMs must be a non-negative finite number");
237
+ const entry = readGatewayModelCacheEntry(filePath);
238
+ if (!entry) return undefined;
239
+ return {
240
+ ids: [...entry.ids],
241
+ fresh: isCacheEntryFresh(entry, now, ttlMs),
242
+ };
243
+ }
244
+
245
+ const gatewayCaches = new Map<string, ModelCache>();
246
+ const inFlightRequests = new Map<string, Promise<FetchGatewayModelIdsResult>>();
247
+
248
+ function cacheFor(baseUrl: string): ModelCache {
249
+ const key = baseUrl.replace(/\/+$/, "");
250
+ let cache = gatewayCaches.get(key);
251
+ if (!cache) {
252
+ cache = createModelCache();
253
+ gatewayCaches.set(key, cache);
254
+ }
255
+ return cache;
256
+ }
257
+
258
+ /**
259
+ * Load gateway model IDs with a five-minute process cache.
260
+ *
261
+ * Fresh cache entries are returned without I/O. A failed refresh falls back
262
+ * to a stale entry when available; otherwise the fetch failure is returned.
263
+ */
264
+ export async function getGatewayModelIds(
265
+ baseUrl: string,
266
+ apiKey: string,
267
+ opts: GetGatewayModelIdsOptions = {},
268
+ now = Date.now(),
269
+ ): Promise<GetGatewayModelIdsResult> {
270
+ const key = baseUrl.replace(/\/+$/, "");
271
+ const cache = cacheFor(key);
272
+ if (cache.isFresh(now)) {
273
+ const entry = cache.get();
274
+ if (entry) return { ok: true, ids: entry.ids, cached: true, stale: false };
275
+ }
276
+
277
+ const diskEntry = opts.cacheFilePath
278
+ ? readGatewayModelCacheEntry(opts.cacheFilePath)
279
+ : undefined;
280
+ if (
281
+ diskEntry &&
282
+ isCacheEntryFresh(diskEntry, now, DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS)
283
+ ) {
284
+ cache.set(diskEntry.ids, diskEntry.storedAt);
285
+ return {
286
+ ok: true,
287
+ ids: [...diskEntry.ids],
288
+ cached: true,
289
+ stale: false,
290
+ };
291
+ }
292
+
293
+ let request = inFlightRequests.get(key);
294
+ if (!request) {
295
+ request = fetchGatewayModelIds(key, apiKey, {
296
+ fetcher: opts.fetcher,
297
+ timeoutMs: opts.timeoutMs,
298
+ });
299
+ inFlightRequests.set(key, request);
300
+ }
301
+
302
+ let fetched: FetchGatewayModelIdsResult;
303
+ try {
304
+ fetched = await request;
305
+ } finally {
306
+ if (inFlightRequests.get(key) === request) inFlightRequests.delete(key);
307
+ }
308
+
309
+ if (fetched.ok) {
310
+ cache.set(fetched.ids, now);
311
+ if (opts.cacheFilePath)
312
+ saveGatewayModelCache(opts.cacheFilePath, fetched.ids, now);
313
+ return { ok: true, ids: [...fetched.ids], cached: false, stale: false };
314
+ }
315
+
316
+ const memoryEntry = cache.get();
317
+ const stale =
318
+ memoryEntry && diskEntry
319
+ ? memoryEntry.storedAt >= diskEntry.storedAt
320
+ ? memoryEntry
321
+ : diskEntry
322
+ : (memoryEntry ?? diskEntry);
323
+ if (stale) {
324
+ return {
325
+ ok: true,
326
+ ids: stale.ids,
327
+ cached: true,
328
+ stale: true,
329
+ fallbackReason: fetched.reason,
330
+ };
331
+ }
332
+ return fetched;
333
+ }
@@ -11,9 +11,11 @@ import {
11
11
  type ModelOperationContext,
12
12
  type ThinkingApplier,
13
13
  } from "./_tools.ts";
14
+ import { applyBuiltinSearchTool } from "./web-search.ts";
14
15
  import { deepseekThinking } from "./vendors/deepseek.ts";
15
16
  import { geminiThinking } from "./vendors/gemini.ts";
16
17
  import { glmThinking } from "./vendors/glm.ts";
18
+ import { grokThinking } from "./vendors/grok.ts";
17
19
  import { kimiThinking } from "./vendors/kimi.ts";
18
20
  import { longcatThinking } from "./vendors/longcat.ts";
19
21
  import { mimoThinking } from "./vendors/mimo.ts";
@@ -34,6 +36,7 @@ const THINKING_STRATEGIES: Record<string, ThinkingApplier> = {
34
36
  ...qwenThinking,
35
37
  ...openaiThinking,
36
38
  ...geminiThinking,
39
+ ...grokThinking,
37
40
  };
38
41
 
39
42
  /**
@@ -50,5 +53,11 @@ export function applyModelOperations(
50
53
  const writer = new PayloadWriter(payload);
51
54
  const applier = THINKING_STRATEGIES[context.modelId];
52
55
  if (applier) applier(writer, context);
53
- return writer.result();
56
+ // 思维链改写后,再为支持内置查询的模型注入 web_search 工具。
57
+ return applyBuiltinSearchTool(
58
+ writer.result(),
59
+ context.modelId,
60
+ context.api,
61
+ context.tsSearchMode,
62
+ );
54
63
  }
@@ -0,0 +1,118 @@
1
+ import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
2
+ import { OPENAI_COMPLETIONS_COMPAT } from "./_protocols.ts";
3
+ import { type PayloadWriter, type ThinkingApplier, type ThinkingLevel } from "../_tools.ts";
4
+
5
+ /**
6
+ * xAI Grok 系列(openai-completions 协议)。
7
+ * 官方文档:https://docs.x.ai/developers/models
8
+ * 定价(docs.x.ai/developers/pricing,<200k prompt 档):
9
+ * grok-4.20 / grok-4.3:input $1.25 / cached $0.20 / output $2.50 per 1M
10
+ * grok-4.5:input $2.00 / cached $0.30 / output $6.00 per 1M
11
+ */
12
+ export function grokModels(root: string): ProviderModelConfig[] {
13
+ const v1 = `${root}/v1`;
14
+ return [
15
+ {
16
+ id: "grok-4.20",
17
+ name: "Grok 4.20",
18
+ api: "openai-completions",
19
+ baseUrl: v1,
20
+ reasoning: true,
21
+ input: ["text", "image"],
22
+ cost: { input: 1.25, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },
23
+ contextWindow: 1000000,
24
+ maxTokens: 65536,
25
+ compat: OPENAI_COMPLETIONS_COMPAT,
26
+ },
27
+ {
28
+ id: "grok-4.5",
29
+ name: "Grok 4.5",
30
+ api: "openai-completions",
31
+ baseUrl: v1,
32
+ reasoning: true,
33
+ input: ["text", "image"],
34
+ cost: { input: 2, output: 6, cacheRead: 0.3, cacheWrite: 0 },
35
+ contextWindow: 500000,
36
+ maxTokens: 65536,
37
+ compat: OPENAI_COMPLETIONS_COMPAT,
38
+ },
39
+ {
40
+ id: "grok-4.3-low",
41
+ name: "Grok 4.3",
42
+ api: "openai-completions",
43
+ baseUrl: v1,
44
+ reasoning: true,
45
+ input: ["text", "image"],
46
+ // 网关思考档位别名,规格继承 grok-4.3。
47
+ cost: { input: 1.25, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },
48
+ contextWindow: 1000000,
49
+ maxTokens: 65536,
50
+ compat: OPENAI_COMPLETIONS_COMPAT,
51
+ },
52
+ {
53
+ id: "grok-4.3-medium",
54
+ name: "Grok 4.3",
55
+ api: "openai-completions",
56
+ baseUrl: v1,
57
+ reasoning: true,
58
+ input: ["text", "image"],
59
+ // 网关思考档位别名,规格继承 grok-4.3。
60
+ cost: { input: 1.25, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },
61
+ contextWindow: 1000000,
62
+ maxTokens: 65536,
63
+ compat: OPENAI_COMPLETIONS_COMPAT,
64
+ },
65
+ {
66
+ id: "grok-4.3-high",
67
+ name: "Grok 4.3",
68
+ api: "openai-completions",
69
+ baseUrl: v1,
70
+ reasoning: true,
71
+ input: ["text", "image"],
72
+ // 网关思考档位别名,规格继承 grok-4.3。
73
+ cost: { input: 1.25, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },
74
+ contextWindow: 1000000,
75
+ maxTokens: 65536,
76
+ compat: OPENAI_COMPLETIONS_COMPAT,
77
+ },
78
+ {
79
+ id: "grok-4.20-fast",
80
+ name: "Grok 4.20 Fast",
81
+ api: "openai-completions",
82
+ baseUrl: v1,
83
+ reasoning: true,
84
+ input: ["text", "image"],
85
+ // 网关快速档别名,规格继承 grok-4.20。
86
+ cost: { input: 1.25, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },
87
+ contextWindow: 1000000,
88
+ maxTokens: 65536,
89
+ compat: OPENAI_COMPLETIONS_COMPAT,
90
+ },
91
+ ];
92
+ }
93
+
94
+ // Grok 思维链:`reasoning_effort`(none/low/medium/high)。
95
+ // 注意:grok-4.5 不支持禁用 reasoning(none),off 档映射到最小 effort "low"。
96
+ function applyGrok(writer: PayloadWriter, level: ThinkingLevel): void {
97
+ writer.remove("thinking");
98
+ if (level === "off") {
99
+ writer.set("reasoning_effort", "low");
100
+ return;
101
+ }
102
+ const effort =
103
+ level === "minimal" || level === "low"
104
+ ? "low"
105
+ : level === "medium"
106
+ ? "medium"
107
+ : "high";
108
+ writer.set("reasoning_effort", effort);
109
+ }
110
+
111
+ export const grokThinking: Record<string, ThinkingApplier> = {
112
+ "grok-4.20": (w, c) => applyGrok(w, c.thinkingLevel),
113
+ "grok-4.5": (w, c) => applyGrok(w, c.thinkingLevel),
114
+ "grok-4.3-low": (w, c) => applyGrok(w, c.thinkingLevel),
115
+ "grok-4.3-medium": (w, c) => applyGrok(w, c.thinkingLevel),
116
+ "grok-4.3-high": (w, c) => applyGrok(w, c.thinkingLevel),
117
+ "grok-4.20-fast": (w, c) => applyGrok(w, c.thinkingLevel),
118
+ };
@@ -226,10 +226,11 @@ export function openaiModels(root: string): ProviderModelConfig[] {
226
226
  ];
227
227
  }
228
228
 
229
- // GPT Responses 思维链:保留 Pi 的 `reasoning`,固定 `service_tier=flex`,按别名调文本 verbosity。
229
+ // GPT Responses 思维链:保留 Pi 的 `reasoning`,按别名调文本 verbosity。
230
+ // 不写 service_tier:flex 为 beta 有限支持(受模型/账号限制),会被 OpenAI upstream 以
231
+ // 400 "Unsupported service_tier: flex" 拒绝,让请求走项目默认 tier。
230
232
  function applyOpenAIResponses(writer: PayloadWriter, modelId: string): void {
231
233
  const verbosity = modelId === "gpt-5.6-terra" ? "medium" : "low";
232
- writer.set("service_tier", "flex");
233
234
  writer.setTextVerbosity(verbosity);
234
235
  }
235
236
 
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 内置查询注入(Built-in web search tool injection)。
3
+ *
4
+ * 对原生支持内置查询的模型(GPT Responses / Grok),在请求改写阶段把
5
+ * 搜索参数追加进请求。属于模型请求改写的一部分,与思维链策略一起在
6
+ * `before_provider_request` 中应用。
7
+ *
8
+ * - GPT(openai-responses):追加 `tools: [{ type: "web_search", ... }]`
9
+ * - Grok(openai-completions):追加 `search_parameters: { mode: "on" }`
10
+ * (xAI 文档:https://docs.x.ai/developers/tools/web-search)
11
+ *
12
+ * 独立的 ts_search 工具(所有模型可用)单独实现,与内置查询注入分离。
13
+ */
14
+
15
+ import { isPlainObject, PayloadWriter, type WebSearchMode } from "./_tools.ts";
16
+
17
+ const OPENAI_RESPONSES = "openai-responses";
18
+ const OPENAI_COMPLETIONS = "openai-completions";
19
+
20
+ // 支持内置查询的模型名单(GPT Responses 系列)。
21
+ const BUILTIN_SEARCH_MODELS = new Set([
22
+ "gpt-5.6-sol",
23
+ "gpt-5.6-terra",
24
+ "gpt-5.6-luna",
25
+ "gpt-5.5",
26
+ ]);
27
+
28
+ // 支持内置查询的 Grok 系列(openai-completions 协议,search_parameters 模式)。
29
+ const GROK_SEARCH_MODELS = new Set([
30
+ "grok-4.20",
31
+ "grok-4.5",
32
+ "grok-4.3-low",
33
+ "grok-4.3-medium",
34
+ "grok-4.3-high",
35
+ "grok-4.20-fast",
36
+ ]);
37
+
38
+ function isExistingWebSearchTool(tools: readonly unknown[]): boolean {
39
+ return tools.some((tool) => {
40
+ if (!isPlainObject(tool) || typeof tool.type !== "string") return false;
41
+ return tool.type === "web_search" || tool.type.startsWith("web_search_");
42
+ });
43
+ }
44
+
45
+ function hasGrokSearchFields(payload: Record<string, unknown>): boolean {
46
+ return (
47
+ Object.hasOwn(payload, "search_parameters") ||
48
+ Object.hasOwn(payload, "web_search_options")
49
+ );
50
+ }
51
+
52
+ function applyGptSearch(writer: PayloadWriter, mode: WebSearchMode): void {
53
+ const tools = writer.get("tools");
54
+ if (tools !== undefined && !Array.isArray(tools)) return;
55
+ const currentTools = tools ?? [];
56
+ if (isExistingWebSearchTool(currentTools)) return;
57
+ writer.set("tools", [
58
+ ...currentTools,
59
+ {
60
+ type: "web_search",
61
+ search_context_size: "medium",
62
+ external_web_access: mode === "live",
63
+ },
64
+ ]);
65
+ }
66
+
67
+ function applyGrokSearch(writer: PayloadWriter): void {
68
+ if (hasGrokSearchFields(writer.result())) return;
69
+ writer.set("search_parameters", { mode: "on" });
70
+ }
71
+
72
+ /**
73
+ * Append-only built-in search injection for models with native search.
74
+ * Non-plain payloads, `off` mode, and unsupported models are returned
75
+ * unchanged. Existing function tools, `tool_choice`, and `include` are
76
+ * preserved. Pi drops requested sources, so GPT injection deliberately does
77
+ * not request them.
78
+ */
79
+ export function applyBuiltinSearchTool(
80
+ payload: unknown,
81
+ modelId: string,
82
+ api: string,
83
+ mode: WebSearchMode,
84
+ ): unknown {
85
+ if (!isPlainObject(payload) || mode === "off") return payload;
86
+ const writer = new PayloadWriter(payload);
87
+
88
+ if (api === OPENAI_RESPONSES && BUILTIN_SEARCH_MODELS.has(modelId)) {
89
+ applyGptSearch(writer, mode);
90
+ return writer.result();
91
+ }
92
+ if (api === OPENAI_COMPLETIONS && GROK_SEARCH_MODELS.has(modelId)) {
93
+ applyGrokSearch(writer);
94
+ return writer.result();
95
+ }
96
+ return payload;
97
+ }
@@ -0,0 +1,366 @@
1
+ /**
2
+ * 独立搜索工具(ts_search):供所有模型直接调用的统一搜索入口。
3
+ *
4
+ * 与模型模块的内置查询注入(models/web-search.ts)分离:
5
+ * - 内置查询注入:GPT/Grok 模型请求时自动附加搜索能力
6
+ * - 本工具:任何模型主动调用,内部通过固定的 GPT / Grok 后端联网搜索
7
+ *
8
+ * 工具只接收查询;搜索后端由扩展维护,避免调用方猜测或误选模型。
9
+ */
10
+
11
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
+ import { Type } from "typebox";
13
+
14
+ export interface TsSearchOptions {
15
+ baseUrl: string;
16
+ /** 凭据 provider(默认 tsgw,走 Pi 凭据机制)。 */
17
+ apiKeyProvider?: string;
18
+ /** @deprecated 固定白名单已内置;仅兼容旧 index.ts,值会被忽略。 */
19
+ searchModels?: readonly string[];
20
+ }
21
+
22
+ export const DEFAULT_SEARCH_MODELS = ["gpt-5.6-luna", "grok-4.20"] as const;
23
+ const CHAT_COMPLETIONS_PATH = "v1/chat/completions";
24
+
25
+ const SEARCH_PROMPT = [
26
+ "Answer the user's question using the latest available information from the web.",
27
+ "Be concise.",
28
+ "If sources are available, include only the most relevant source URLs needed to support the answer; avoid link dumping.",
29
+ "If no live web information is available, reply exactly: NO_LIVE_WEB.",
30
+ ].join(" ");
31
+
32
+ type SearchFamily = "gpt" | "grok";
33
+
34
+ export function detectSearchFamily(
35
+ model: string,
36
+ ): SearchFamily | "unsupported" {
37
+ const lower = model.toLowerCase();
38
+ if (lower.startsWith("gpt-")) return "gpt";
39
+ if (lower.startsWith("grok-")) return "grok";
40
+ return "unsupported";
41
+ }
42
+
43
+ export function resolveSearchModels(): string[] {
44
+ return [...DEFAULT_SEARCH_MODELS];
45
+ }
46
+
47
+ export function buildSearchUrl(baseUrl: string): string {
48
+ const normalizedBase = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
49
+ return new URL(CHAT_COMPLETIONS_PATH, normalizedBase).toString();
50
+ }
51
+
52
+ function flattenText(value: unknown): string {
53
+ if (typeof value === "string") return value.trim();
54
+ if (Array.isArray(value)) {
55
+ return value
56
+ .map((item) => flattenText(item))
57
+ .filter(Boolean)
58
+ .join("\n")
59
+ .trim();
60
+ }
61
+ if (value && typeof value === "object") {
62
+ const record = value as Record<string, unknown>;
63
+ if (typeof record.text === "string") return record.text.trim();
64
+ if (typeof record.content === "string") return record.content.trim();
65
+ if (Array.isArray(record.content)) return flattenText(record.content);
66
+ }
67
+ return "";
68
+ }
69
+
70
+ function firstNonEmpty(values: unknown[]): string {
71
+ for (const value of values) {
72
+ const text = flattenText(value);
73
+ if (text) return text;
74
+ }
75
+ return "";
76
+ }
77
+
78
+ function extractAnswer(payload: Record<string, unknown>): string {
79
+ const choices = payload.choices;
80
+ if (Array.isArray(choices) && choices.length > 0) {
81
+ const first = choices[0] as Record<string, unknown>;
82
+ const message = first.message as Record<string, unknown> | undefined;
83
+ const answer = flattenText(message?.content);
84
+ if (answer) return answer;
85
+ const delta = first.delta as Record<string, unknown> | undefined;
86
+ const deltaAnswer = flattenText(delta?.content);
87
+ if (deltaAnswer) return deltaAnswer;
88
+ }
89
+ return firstNonEmpty([payload.output_text, payload.answer, payload.message]);
90
+ }
91
+
92
+ function collectUrls(input: unknown, output = new Set<string>()): Set<string> {
93
+ if (typeof input === "string") {
94
+ const matches = input.match(/https?:\/\/[^\s)\]}>"']+/g) ?? [];
95
+ for (const match of matches) output.add(match.replace(/[.,;]+$/, ""));
96
+ return output;
97
+ }
98
+ if (Array.isArray(input)) {
99
+ for (const item of input) collectUrls(item, output);
100
+ return output;
101
+ }
102
+ if (!input || typeof input !== "object") return output;
103
+ for (const [key, value] of Object.entries(input)) {
104
+ if (typeof value === "string" && key.toLowerCase().includes("url")) {
105
+ collectUrls(value, output);
106
+ continue;
107
+ }
108
+ if (
109
+ key === "citations" ||
110
+ key === "annotations" ||
111
+ key === "sources" ||
112
+ key === "search_results" ||
113
+ key === "results" ||
114
+ key === "references"
115
+ ) {
116
+ collectUrls(value, output);
117
+ continue;
118
+ }
119
+ collectUrls(value, output);
120
+ }
121
+ return output;
122
+ }
123
+
124
+ export function buildSearchPayload(
125
+ model: string,
126
+ family: SearchFamily,
127
+ query: string,
128
+ ): Record<string, unknown> {
129
+ const messages = [
130
+ { role: "system", content: SEARCH_PROMPT },
131
+ { role: "user", content: query },
132
+ ];
133
+ if (family === "gpt") {
134
+ return {
135
+ model,
136
+ messages,
137
+ tools: [
138
+ {
139
+ type: "web_search",
140
+ search_context_size: "medium",
141
+ external_web_access: true,
142
+ },
143
+ ],
144
+ };
145
+ }
146
+ return { model, messages, search_parameters: { mode: "on" } };
147
+ }
148
+
149
+ interface RouteResult {
150
+ ok: boolean;
151
+ model: string;
152
+ family: SearchFamily;
153
+ answer: string;
154
+ urls: string[];
155
+ requestId: string;
156
+ error: string;
157
+ }
158
+
159
+ async function executeSearchRoute(
160
+ model: string,
161
+ query: string,
162
+ apiKey: string,
163
+ baseUrl: string,
164
+ signal: AbortSignal | undefined,
165
+ ): Promise<RouteResult> {
166
+ const family = detectSearchFamily(model);
167
+ if (family === "unsupported") {
168
+ return buildFailure(model, "gpt", `不支持的模型系列:${model}`);
169
+ }
170
+
171
+ let response: Response;
172
+ try {
173
+ response = await fetch(buildSearchUrl(baseUrl), {
174
+ method: "POST",
175
+ headers: {
176
+ authorization: `Bearer ${apiKey}`,
177
+ "content-type": "application/json",
178
+ },
179
+ body: JSON.stringify(buildSearchPayload(model, family, query)),
180
+ signal,
181
+ });
182
+ } catch (error) {
183
+ return buildFailure(
184
+ model,
185
+ family,
186
+ `请求失败:${error instanceof Error ? error.message : String(error)}`,
187
+ );
188
+ }
189
+
190
+ const requestId = response.headers.get("ah-request-id") ?? "";
191
+ const bodyText = await response.text();
192
+ if (!response.ok) {
193
+ return {
194
+ ...buildFailure(
195
+ model,
196
+ family,
197
+ `网关请求失败:HTTP ${response.status} ${response.statusText}\n${bodyText}`,
198
+ ),
199
+ requestId,
200
+ };
201
+ }
202
+
203
+ try {
204
+ const parsed: unknown = JSON.parse(bodyText);
205
+ if (parsed && typeof parsed === "object") {
206
+ const record = parsed as Record<string, unknown>;
207
+ return {
208
+ ok: true,
209
+ model,
210
+ family,
211
+ answer: extractAnswer(record) || JSON.stringify(record),
212
+ urls: Array.from(collectUrls(record)),
213
+ requestId,
214
+ error: "",
215
+ };
216
+ }
217
+ } catch {
218
+ // 非 JSON 响应按纯文本处理。
219
+ }
220
+ return {
221
+ ok: true,
222
+ model,
223
+ family,
224
+ answer: bodyText || "网关返回空响应。",
225
+ urls: Array.from(collectUrls(bodyText)),
226
+ requestId,
227
+ error: "",
228
+ };
229
+ }
230
+
231
+ function buildFailure(
232
+ model: string,
233
+ family: SearchFamily,
234
+ error: string,
235
+ ): RouteResult {
236
+ return {
237
+ ok: false,
238
+ model,
239
+ family,
240
+ answer: "",
241
+ urls: [],
242
+ requestId: "",
243
+ error,
244
+ };
245
+ }
246
+
247
+ function renderMergedResult(results: RouteResult[]): string {
248
+ const succeeded = results.filter((item) => item.ok);
249
+ const failed = results.filter((item) => !item.ok);
250
+ const status =
251
+ succeeded.length === results.length
252
+ ? "成功"
253
+ : succeeded.length > 0
254
+ ? "部分成功"
255
+ : "失败";
256
+ const lines = ["后端:tsgw", `状态:${status}`];
257
+
258
+ if (succeeded.length === 0) {
259
+ const summary = failed
260
+ .map(
261
+ (item) =>
262
+ `${item.family}(${item.model}):${item.error || "未知错误"}`,
263
+ )
264
+ .join(";");
265
+ lines.push(`全部搜索后端失败:${summary}`);
266
+ return lines.join("\n");
267
+ }
268
+
269
+ for (const item of succeeded) {
270
+ lines.push(
271
+ `${item.family}(${item.model})结果:`,
272
+ item.answer || "未返回答案。",
273
+ );
274
+ }
275
+
276
+ const mergedUrls = Array.from(
277
+ new Set(succeeded.flatMap((item) => item.urls)),
278
+ );
279
+ lines.push("来源链接:");
280
+ if (mergedUrls.length) {
281
+ for (const url of mergedUrls) lines.push(`- ${url}`);
282
+ } else {
283
+ lines.push("- 无");
284
+ }
285
+ for (const item of failed) {
286
+ lines.push(`注:${item.family} 后端不可用,已跳过。`);
287
+ }
288
+ return lines.join("\n");
289
+ }
290
+
291
+ /** 注册 ts_search 工具,固定并行请求白名单内的 GPT + Grok 后端。 */
292
+ export function registerTsSearch(
293
+ pi: ExtensionAPI,
294
+ options: TsSearchOptions,
295
+ ): void {
296
+ const argsSchema = Type.Object({
297
+ query: Type.String({ minLength: 1, description: "搜索查询" }),
298
+ });
299
+
300
+ pi.registerTool({
301
+ name: "ts_search",
302
+ label: "TS Search",
303
+ description:
304
+ "统一网络搜索:通过网关的 GPT / Grok 模型执行联网搜索并返回最新结果。任何模型都可调用。",
305
+ parameters: argsSchema,
306
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
307
+ const query = params.query.trim();
308
+ if (!query) {
309
+ return {
310
+ content: [{ type: "text", text: "ts_search:查询内容不能为空。" }],
311
+ details: {},
312
+ };
313
+ }
314
+
315
+ const apiKeyProvider = options.apiKeyProvider ?? "tsgw";
316
+ let apiKey = "";
317
+ try {
318
+ apiKey =
319
+ (await ctx.modelRegistry.getApiKeyForProvider(apiKeyProvider)) ?? "";
320
+ } catch (error) {
321
+ return {
322
+ content: [
323
+ {
324
+ type: "text",
325
+ text: `ts_search:解析 API key 失败:${error instanceof Error ? error.message : String(error)}`,
326
+ },
327
+ ],
328
+ details: {},
329
+ };
330
+ }
331
+ if (!apiKey) {
332
+ return {
333
+ content: [
334
+ {
335
+ type: "text",
336
+ text: `ts_search:未找到 ${apiKeyProvider} provider 的 API key,请运行 /login 完成配置。`,
337
+ },
338
+ ],
339
+ details: {},
340
+ };
341
+ }
342
+
343
+ const models = resolveSearchModels();
344
+ const settled = await Promise.allSettled(
345
+ models.map((model) =>
346
+ executeSearchRoute(model, query, apiKey, options.baseUrl, signal),
347
+ ),
348
+ );
349
+ const results = settled.map((item, index) => {
350
+ if (item.status === "fulfilled") return item.value;
351
+ const model = models[index];
352
+ const family = detectSearchFamily(model);
353
+ return buildFailure(
354
+ model,
355
+ family === "grok" ? "grok" : "gpt",
356
+ `搜索路由异常:${String(item.reason)}`,
357
+ );
358
+ });
359
+
360
+ return {
361
+ content: [{ type: "text", text: renderMergedResult(results) }],
362
+ details: {},
363
+ };
364
+ },
365
+ });
366
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tsgw",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
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,13 +21,15 @@
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/web-search/web-search.test.js"
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"
25
25
  },
26
26
  "peerDependencies": {
27
- "@earendil-works/pi-coding-agent": ">=0.82.0"
27
+ "@earendil-works/pi-coding-agent": ">=0.82.0",
28
+ "typebox": "*"
28
29
  },
29
30
  "devDependencies": {
30
- "@earendil-works/pi-coding-agent": "^0.83.0",
31
+ "@earendil-works/pi-coding-agent": "^0.84.1",
32
+ "typebox": "^1.3.11",
31
33
  "typescript": "^7.0.2"
32
34
  }
33
35
  }
@@ -1,73 +0,0 @@
1
- /**
2
- * 网络模块:内置查询(built-in web search)工具注入。
3
- *
4
- * 与模型模块平行、互不依赖:这里只维护"哪些模型支持内置查询"及注入
5
- * 格式,不读取模型目录数据。支持的模型:GPT 系列(OpenAI Responses
6
- * 协议)与 Grok 系列(xAI,工具名同为 `web_search`,见
7
- * https://docs.x.ai/developers/tools/web-search)。Grok 的协议端点与
8
- * 注入参数待其模型加入目录后按网关实际行为确认。
9
- */
10
-
11
- import {
12
- isPlainObject,
13
- PayloadWriter,
14
- type WebSearchMode,
15
- } from "../models/_tools.ts";
16
-
17
- const OPENAI_RESPONSES = "openai-responses";
18
-
19
- // 支持内置查询的模型名单。Grok 系列工具格式已确认(`web_search`),
20
- // 待其协议端点确认后加入。
21
- const BUILTIN_SEARCH_MODELS = new Set([
22
- "gpt-5.6-sol",
23
- "gpt-5.6-terra",
24
- "gpt-5.6-luna",
25
- "gpt-5.5",
26
- ]);
27
-
28
- function isExistingWebSearchTool(tools: readonly unknown[]): boolean {
29
- return tools.some((tool) => {
30
- if (!isPlainObject(tool) || typeof tool.type !== "string") return false;
31
- return tool.type === "web_search" || tool.type.startsWith("web_search_");
32
- });
33
- }
34
-
35
- export interface WebSearchContext {
36
- modelId: string;
37
- api: string;
38
- mode: WebSearchMode;
39
- }
40
-
41
- /**
42
- * Append-only web_search tool injection for models with built-in search.
43
- * Non-plain payloads and unsupported models are returned unchanged.
44
- *
45
- * `cached` uses `external_web_access: false`; `live` uses `true`. Existing
46
- * function tools, `tool_choice`, and `include` are preserved. Pi drops
47
- * requested sources, so this operation deliberately does not request them.
48
- */
49
- export function applyWebSearchTool(
50
- payload: unknown,
51
- context: WebSearchContext,
52
- ): unknown {
53
- if (!isPlainObject(payload) || context.mode === "off") return payload;
54
- if (
55
- context.api !== OPENAI_RESPONSES ||
56
- !BUILTIN_SEARCH_MODELS.has(context.modelId)
57
- )
58
- return payload;
59
- const writer = new PayloadWriter(payload);
60
- const tools = writer.get("tools");
61
- if (tools !== undefined && !Array.isArray(tools)) return payload;
62
- const currentTools = tools ?? [];
63
- if (isExistingWebSearchTool(currentTools)) return payload;
64
- writer.set("tools", [
65
- ...currentTools,
66
- {
67
- type: "web_search",
68
- search_context_size: "medium",
69
- external_web_access: context.mode === "live",
70
- },
71
- ]);
72
- return writer.result();
73
- }