pi-tsgw 0.0.5 → 0.0.6

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.
@@ -4,6 +4,7 @@ import { ANTHROPIC_COMPAT } from "./_protocols.ts";
4
4
  /**
5
5
  * Anthropic Claude 系列(anthropic-messages 协议)。
6
6
  * 官方文档:https://docs.claude.com/en/docs/about-claude/models/
7
+ * 规格/定价以网关目录为准(fable/opus/sonnet 三档)。
7
8
  */
8
9
  export function anthropicModels(root: string): ProviderModelConfig[] {
9
10
  const anthropic = `${root}/anthropic`;
@@ -27,8 +28,8 @@ export function anthropicModels(root: string): ProviderModelConfig[] {
27
28
  compat: ANTHROPIC_COMPAT,
28
29
  },
29
30
  {
30
- id: "claude-opus-4-8",
31
- name: "Claude Opus 4.8",
31
+ id: "claude-opus-5",
32
+ name: "Claude Opus 5",
32
33
  api: "anthropic-messages",
33
34
  baseUrl: anthropic,
34
35
  reasoning: true,
@@ -36,158 +37,15 @@ export function anthropicModels(root: string): ProviderModelConfig[] {
36
37
  low: "low",
37
38
  medium: "medium",
38
39
  high: "high",
40
+ xhigh: "xhigh",
39
41
  max: "max",
40
42
  },
41
43
  input: ["text", "image"],
42
- cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
43
- contextWindow: 200000,
44
- maxTokens: 128000,
45
- compat: ANTHROPIC_COMPAT,
46
- },
47
- {
48
- id: "claude-sonnet",
49
- name: "Claude Sonnet 4.6",
50
- api: "anthropic-messages",
51
- baseUrl: anthropic,
52
- reasoning: true,
53
- thinkingLevelMap: {
54
- low: "low",
55
- medium: "medium",
56
- high: "high",
57
- max: "max",
58
- },
59
- input: ["text", "image"],
60
- cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
61
- contextWindow: 200000,
62
- maxTokens: 64000,
63
- compat: ANTHROPIC_COMPAT,
64
- },
65
- {
66
- id: "claude-opus-4",
67
- name: "Claude Opus 4",
68
- api: "anthropic-messages",
69
- baseUrl: anthropic,
70
- reasoning: true,
71
- thinkingLevelMap: {
72
- low: "low",
73
- medium: "medium",
74
- high: "high",
75
- max: "max",
76
- },
77
- input: ["text", "image"],
78
- cost: { input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75 },
79
- contextWindow: 200000,
80
- maxTokens: 32000,
81
- compat: ANTHROPIC_COMPAT,
82
- },
83
- {
84
- id: "claude-opus-4.1",
85
- name: "Claude Opus 4.1",
86
- api: "anthropic-messages",
87
- baseUrl: anthropic,
88
- reasoning: true,
89
- thinkingLevelMap: {
90
- low: "low",
91
- medium: "medium",
92
- high: "high",
93
- max: "max",
94
- },
95
- input: ["text", "image"],
96
- cost: { input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75 },
97
- contextWindow: 200000,
98
- maxTokens: 32000,
99
- compat: ANTHROPIC_COMPAT,
100
- },
101
- {
102
- id: "claude-opus-4.5",
103
- name: "Claude Opus 4.5",
104
- api: "anthropic-messages",
105
- baseUrl: anthropic,
106
- reasoning: true,
107
- thinkingLevelMap: {
108
- low: "low",
109
- medium: "medium",
110
- high: "high",
111
- max: "max",
112
- },
113
- input: ["text", "image"],
114
- cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
115
- contextWindow: 200000,
116
- maxTokens: 64000,
117
- compat: ANTHROPIC_COMPAT,
118
- },
119
- {
120
- id: "claude-opus-4.6",
121
- name: "Claude Opus 4.6",
122
- api: "anthropic-messages",
123
- baseUrl: anthropic,
124
- reasoning: true,
125
- thinkingLevelMap: {
126
- low: "low",
127
- medium: "medium",
128
- high: "high",
129
- max: "max",
130
- },
131
- input: ["text", "image"],
132
- cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
133
- contextWindow: 1000000,
134
- maxTokens: 128000,
135
- compat: ANTHROPIC_COMPAT,
136
- },
137
- {
138
- id: "claude-opus-4.7",
139
- name: "Claude Opus 4.7",
140
- api: "anthropic-messages",
141
- baseUrl: anthropic,
142
- reasoning: true,
143
- thinkingLevelMap: {
144
- low: "low",
145
- medium: "medium",
146
- high: "high",
147
- max: "max",
148
- },
149
- input: ["text", "image"],
150
- cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
44
+ cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },
151
45
  contextWindow: 1000000,
152
46
  maxTokens: 128000,
153
47
  compat: ANTHROPIC_COMPAT,
154
48
  },
155
- {
156
- id: "claude-sonnet-4",
157
- name: "Claude Sonnet 4",
158
- api: "anthropic-messages",
159
- baseUrl: anthropic,
160
- reasoning: true,
161
- thinkingLevelMap: {
162
- low: "low",
163
- medium: "medium",
164
- high: "high",
165
- max: "max",
166
- },
167
- input: ["text", "image"],
168
- cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
169
- contextWindow: 200000,
170
- maxTokens: 64000,
171
- compat: ANTHROPIC_COMPAT,
172
- },
173
- {
174
- id: "claude-sonnet-4.5",
175
- name: "Claude Sonnet 4.5",
176
- api: "anthropic-messages",
177
- baseUrl: anthropic,
178
- reasoning: true,
179
- thinkingLevelMap: {
180
- low: "low",
181
- medium: "medium",
182
- high: "high",
183
- max: "max",
184
- },
185
- input: ["text", "image"],
186
- cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
187
- contextWindow: 200000,
188
- maxTokens: 64000,
189
- compat: ANTHROPIC_COMPAT,
190
- },
191
49
  {
192
50
  id: "claude-sonnet-5",
193
51
  name: "Claude Sonnet 5",
@@ -198,11 +56,11 @@ export function anthropicModels(root: string): ProviderModelConfig[] {
198
56
  low: "low",
199
57
  medium: "medium",
200
58
  high: "high",
59
+ xhigh: "xhigh",
201
60
  max: "max",
202
61
  },
203
62
  input: ["text", "image"],
204
- // 官方 introductory 定价(至 2026-08-31),其后为 $3/$15。
205
- cost: { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 2.5 },
63
+ cost: { input: 6, output: 30, cacheRead: 0.6, cacheWrite: 7.5 },
206
64
  contextWindow: 1000000,
207
65
  maxTokens: 128000,
208
66
  compat: ANTHROPIC_COMPAT,
@@ -8,6 +8,25 @@ import { type PayloadWriter, type ThinkingApplier } from "../_tools.ts";
8
8
  export function openaiModels(root: string): ProviderModelConfig[] {
9
9
  const v1 = `${root}/v1`;
10
10
  return [
11
+ {
12
+ // 参数与 GPT 5.6 Sol 一致。
13
+ id: "hack",
14
+ name: "日站专用",
15
+ api: "openai-responses",
16
+ baseUrl: v1,
17
+ reasoning: true,
18
+ thinkingLevelMap: {
19
+ low: "low",
20
+ medium: "medium",
21
+ high: "high",
22
+ xhigh: "xhigh",
23
+ max: "max",
24
+ },
25
+ input: ["text", "image"],
26
+ cost: { input: 5, output: 30, cacheRead: 0.5, cacheWrite: 6.25 },
27
+ contextWindow: 372000,
28
+ maxTokens: 128000,
29
+ },
11
30
  {
12
31
  id: "gpt-5.6-sol",
13
32
  name: "GPT 5.6 Sol",
@@ -235,6 +254,7 @@ function applyOpenAIResponses(writer: PayloadWriter, modelId: string): void {
235
254
  }
236
255
 
237
256
  export const openaiThinking: Record<string, ThinkingApplier> = {
257
+ "hack": (w, c) => applyOpenAIResponses(w, c.modelId),
238
258
  "gpt-5.6-sol": (w, c) => applyOpenAIResponses(w, c.modelId),
239
259
  "gpt-5.6-terra": (w, c) => applyOpenAIResponses(w, c.modelId),
240
260
  "gpt-5.6-luna": (w, c) => applyOpenAIResponses(w, c.modelId),
@@ -1,11 +1,6 @@
1
1
  /**
2
- * 独立搜索工具(ts_search):供所有模型直接调用的统一搜索入口。
3
- *
4
- * 与模型模块的内置查询注入(models/web-search.ts)分离:
5
- * - 内置查询注入:GPT/Grok 模型请求时自动附加搜索能力
6
- * - 本工具:任何模型主动调用,内部通过固定的 GPT / Grok 后端联网搜索
7
- *
8
- * 工具只接收查询;搜索后端由扩展维护,避免调用方猜测或误选模型。
2
+ * 独立搜索工具(ts_search):任何模型均可通过配置或内置的 GPT / Grok
3
+ * 后端执行联网搜索。模型模块自身的内置查询注入在 models/web-search.ts。
9
4
  */
10
5
 
11
6
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
@@ -13,22 +8,24 @@ import { Type } from "typebox";
13
8
 
14
9
  export interface TsSearchOptions {
15
10
  baseUrl: string;
16
- /** 凭据 provider(默认 tsgw,走 Pi 凭据机制)。 */
17
11
  apiKeyProvider?: string;
18
- /** @deprecated 固定白名单已内置;仅兼容旧 index.ts,值会被忽略。 */
19
12
  searchModels?: readonly string[];
20
13
  }
21
14
 
22
- export const DEFAULT_SEARCH_MODELS = ["gpt-5.6-luna", "grok-chat-fast"] as const;
15
+ export const DEFAULT_SEARCH_MODELS = [
16
+ "gpt-5.6-luna",
17
+ "grok-chat-fast",
18
+ ] as const;
23
19
  const CHAT_COMPLETIONS_PATH = "v1/chat/completions";
24
-
20
+ const MAX_ATTEMPTS = 3;
21
+ const REQUEST_TIMEOUT_MS = 45_000;
22
+ const RETRY_DELAY_MS = 1_000;
25
23
  const SEARCH_PROMPT = [
26
24
  "Answer the user's question using the latest available information from the web.",
27
25
  "Be concise.",
28
26
  "If sources are available, include only the most relevant source URLs needed to support the answer; avoid link dumping.",
29
27
  "If no live web information is available, reply exactly: NO_LIVE_WEB.",
30
28
  ].join(" ");
31
-
32
29
  type SearchFamily = "gpt" | "grok";
33
30
 
34
31
  export function detectSearchFamily(
@@ -40,8 +37,28 @@ export function detectSearchFamily(
40
37
  return "unsupported";
41
38
  }
42
39
 
43
- export function resolveSearchModels(): string[] {
44
- return [...DEFAULT_SEARCH_MODELS];
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];
45
62
  }
46
63
 
47
64
  export function buildSearchUrl(baseUrl: string): string {
@@ -146,7 +163,7 @@ export function buildSearchPayload(
146
163
  return { model, messages, search_parameters: { mode: "on" } };
147
164
  }
148
165
 
149
- interface RouteResult {
166
+ export interface RouteResult {
150
167
  ok: boolean;
151
168
  model: string;
152
169
  family: SearchFamily;
@@ -156,78 +173,195 @@ interface RouteResult {
156
173
  error: string;
157
174
  }
158
175
 
159
- async function executeSearchRoute(
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(
160
229
  model: string,
161
230
  query: string,
162
231
  apiKey: string,
163
232
  baseUrl: string,
164
233
  signal: AbortSignal | undefined,
165
- ): Promise<RouteResult> {
234
+ fetchImpl: typeof fetch,
235
+ requestTimeoutMs: number,
236
+ ): Promise<SearchAttemptResult> {
166
237
  const family = detectSearchFamily(model);
167
- if (family === "unsupported") {
168
- return buildFailure(model, "gpt", `不支持的模型系列:${model}`);
169
- }
238
+ if (family === "unsupported")
239
+ return failedAttempt(model, "gpt", `不支持的模型系列:${model}`, false);
240
+ if (signal?.aborted)
241
+ return failedAttempt(model, family, "请求已取消。", false);
170
242
 
171
243
  let response: Response;
172
244
  try {
173
- response = await fetch(buildSearchUrl(baseUrl), {
245
+ response = await fetchImpl(buildSearchUrl(baseUrl), {
174
246
  method: "POST",
175
247
  headers: {
176
248
  authorization: `Bearer ${apiKey}`,
177
249
  "content-type": "application/json",
178
250
  },
179
251
  body: JSON.stringify(buildSearchPayload(model, family, query)),
180
- signal,
252
+ signal: requestSignal(signal, requestTimeoutMs),
181
253
  });
182
254
  } catch (error) {
183
- return buildFailure(
255
+ return failedAttempt(
184
256
  model,
185
257
  family,
186
- `请求失败:${error instanceof Error ? error.message : String(error)}`,
258
+ signal?.aborted
259
+ ? "请求已取消。"
260
+ : `请求失败:${error instanceof Error ? error.message : String(error)}`,
261
+ !signal?.aborted,
187
262
  );
188
263
  }
189
264
 
190
265
  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
- ),
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,
199
277
  requestId,
200
- };
278
+ );
201
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
+ );
202
288
 
203
289
  try {
204
290
  const parsed: unknown = JSON.parse(bodyText);
205
291
  if (parsed && typeof parsed === "object") {
206
292
  const record = parsed as Record<string, unknown>;
207
293
  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: "",
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,
215
304
  };
216
305
  }
217
306
  } catch {
218
307
  // 非 JSON 响应按纯文本处理。
219
308
  }
220
309
  return {
221
- ok: true,
222
- model,
223
- family,
224
- answer: bodyText || "网关返回空响应。",
225
- urls: Array.from(collectUrls(bodyText)),
226
- requestId,
227
- error: "",
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,
228
320
  };
229
321
  }
230
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
+
231
365
  function buildFailure(
232
366
  model: string,
233
367
  family: SearchFamily,
@@ -288,11 +422,11 @@ function renderMergedResult(results: RouteResult[]): string {
288
422
  return lines.join("\n");
289
423
  }
290
424
 
291
- /** 注册 ts_search 工具,固定并行请求白名单内的 GPT + Grok 后端。 */
292
425
  export function registerTsSearch(
293
426
  pi: ExtensionAPI,
294
427
  options: TsSearchOptions,
295
428
  ): void {
429
+ const models = resolveSearchModels(options);
296
430
  const argsSchema = Type.Object({
297
431
  query: Type.String({ minLength: 1, description: "搜索查询" }),
298
432
  });
@@ -340,10 +474,9 @@ export function registerTsSearch(
340
474
  };
341
475
  }
342
476
 
343
- const models = resolveSearchModels();
344
477
  const settled = await Promise.allSettled(
345
478
  models.map((model) =>
346
- executeSearchRoute(model, query, apiKey, options.baseUrl, signal),
479
+ retrySearchRoute(model, query, apiKey, options.baseUrl, signal),
347
480
  ),
348
481
  );
349
482
  const results = settled.map((item, index) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tsgw",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
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": [