pi-tsgw 0.0.13 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,7 +20,7 @@ import {
20
20
  } from "./models/catalog.ts";
21
21
  import { getGatewayModelIds } from "./models/gateway-catalog.ts";
22
22
  import { applyModelOperations } from "./models/operations.ts";
23
- import { builtinSearchSupport } from "./models/web-search.ts";
23
+ import { registerSearch } from "./search.ts";
24
24
  import {
25
25
  catalogLabel,
26
26
  catalogDiagnostics,
@@ -28,10 +28,12 @@ import {
28
28
  type CatalogStatus,
29
29
  } from "./status.ts";
30
30
  import type { ThinkingLevel, WebSearchMode } from "./models/_tools.ts";
31
+ import { registerUploadTool } from "./upload/index.ts";
32
+ import { registerTsgwMcp } from "./mcp.ts";
31
33
 
32
34
  /**
33
- * The data needed by provider hooks, copied while the lifecycle context is
34
- * fresh. Keep this structural: stale runners may invoke those hooks later.
35
+ * 在生命周期上下文仍有效时,复制供应商钩子所需的数据。
36
+ * 保持结构化类型:过期的执行器可能稍后才调用这些钩子。
35
37
  */
36
38
  interface RequestState {
37
39
  provider: string;
@@ -49,12 +51,13 @@ interface RequestModel {
49
51
  }
50
52
 
51
53
  /**
52
- * Extension configuration from the `tsgw` namespace of the Pi settings file
53
- * (settings.json). All plugin configuration lives here; the plugin reads no
54
- * environment variables (only Pi's own credential resolution handles keys).
54
+ * 扩展配置来自 Pi 设置文件(settings.json)的 `tsgw` 命名空间。
55
+ * 所有插件配置均放在此处;插件不读取环境变量
56
+ * (密钥仅由 Pi 自身的凭据解析机制处理)。
55
57
  */
56
58
  interface TsgwSettings {
57
59
  baseUrl?: string;
60
+ mcpUrl?: string;
58
61
  tsSearch?: string;
59
62
  traceHeaders?: boolean;
60
63
  includeModels?: string[];
@@ -81,7 +84,7 @@ function rootForRuntime(configured: string | undefined): string {
81
84
  try {
82
85
  return normalizeRoot(configured);
83
86
  } catch {
84
- console.error("TSGW: invalid baseUrl; using the default root.");
87
+ console.error("TSGW:baseUrl 无效;使用默认根地址。");
85
88
  return DEFAULT_ROOT;
86
89
  }
87
90
  }
@@ -112,8 +115,8 @@ function requestStateFor(
112
115
  function isTsgwTraceTarget(state: RequestState, root: string): boolean {
113
116
  if (state.provider !== PROVIDER_ID) return false;
114
117
  try {
115
- // Only trace requests that target the configured gateway root, so a
116
- // model whose baseUrl was overridden elsewhere never gets trace headers.
118
+ // 仅追踪发往已配置网关根地址的请求,避免为在其他位置
119
+ // 覆盖了 baseUrl 的模型添加追踪请求头。
117
120
  return new URL(state.baseUrl).hostname === new URL(root).hostname;
118
121
  } catch {
119
122
  return false;
@@ -195,13 +198,14 @@ async function resolveEffectiveModels(
195
198
  }
196
199
 
197
200
  export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
201
+ registerUploadTool(pi);
198
202
  const settings = readTsgwSettings();
203
+ registerTsgwMcp(pi, settings.mcpUrl);
199
204
  const root = rootForRuntime(settings.baseUrl);
200
205
  const defaultSearchMode: WebSearchMode =
201
206
  settings.tsSearch === "cached" || settings.tsSearch === "live"
202
207
  ? settings.tsSearch
203
208
  : "live";
204
- let tsSearchMode = defaultSearchMode;
205
209
  const traceEnabled = settings.traceHeaders === true;
206
210
  const modelFilter: ModelFilter = {
207
211
  include: settings.includeModels,
@@ -231,9 +235,16 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
231
235
  let refreshRevision = 0;
232
236
  let lifecycleRevision = 0;
233
237
  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.
238
+ const search = registerSearch(pi, {
239
+ defaultMode: defaultSearchMode,
240
+ state: () => requestState,
241
+ models: () => latestModels,
242
+ revision: () => lifecycleRevision,
243
+ refreshState: refreshRequestState,
244
+ bindStatus: ctx => bindStatus(ctx),
245
+ publishStatus: () => publishStatus?.(),
246
+ });
247
+ // 仅保留界面输出端,绝不保留生命周期上下文;关闭时断开。
237
248
  const bindStatus = (ctx: ExtensionContext): void => {
238
249
  if (!ctx.hasUI) {
239
250
  publishStatus = undefined;
@@ -246,7 +257,7 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
246
257
  catalogLabel(catalog, credentialConfigured, rootConfigured));
247
258
  ui.setStatus("command:/tsgw-search",
248
259
  requestState?.provider === PROVIDER_ID
249
- ? searchLabel(tsSearchMode, searchSupport()) : undefined);
260
+ ? searchLabel(search.mode(), search.support()) : undefined);
250
261
  };
251
262
  publishStatus();
252
263
  };
@@ -266,7 +277,7 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
266
277
  const credential = context.credential;
267
278
  credentialConfigured = credential?.type === "api_key" && !!credential.key;
268
279
  if (credential?.type !== "api_key" || !credential.key)
269
- throw new Error("TSGW API key is unavailable for model refresh.");
280
+ throw new Error("刷新模型所需的 TSGW API 密钥不可用。");
270
281
  const gateway = await getGatewayModelIds(root, credential.key, {
271
282
  cacheFilePath,
272
283
  force: context.force === true,
@@ -274,11 +285,12 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
274
285
  });
275
286
  context.signal.throwIfAborted();
276
287
  if (!gateway.ok)
277
- throw new Error(`TSGW gateway model refresh failed (${gateway.reason}).`);
288
+ throw new Error(`TSGW 网关模型刷新失败(${gateway.reason})。`);
278
289
  if (gateway.stale)
279
- throw new Error("TSGW refresh failed; keeping the last successful catalog.");
290
+ throw new Error("TSGW 刷新失败;保留上次成功获取的目录。");
280
291
  if (revision === refreshRevision) {
281
292
  latestModels = effectiveModelsForGateway(root, modelFilter, new Set(gateway.ids));
293
+ search.sync();
282
294
  catalog = {
283
295
  count: latestModels.length,
284
296
  source: gateway.cached ? "cache" : "network",
@@ -307,7 +319,7 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
307
319
  refreshPending = true;
308
320
  const lifecycle = lifecycleRevision;
309
321
  let revision = refreshRevision;
310
- // Provider callbacks own their state; only diagnose failures before one starts.
322
+ // 供应商回调管理自身状态;仅诊断回调开始前的失败。
311
323
  const recordFailure = (message: string): void => {
312
324
  if (revision === refreshRevision && !catalog.loading) {
313
325
  catalog.error = message;
@@ -319,14 +331,14 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
319
331
  if (lifecycle !== lifecycleRevision) return;
320
332
  bindStatus(ctx);
321
333
  if (!ctx.modelRegistry.getProviderAuthStatus(PROVIDER_ID).configured) {
322
- ctx.ui.notify("TSGW model refresh skipped: configure an API key with /login first.", "warning");
334
+ ctx.ui.notify("已跳过 TSGW 模型刷新:请先通过 /login 配置 API 密钥。", "warning");
323
335
  return;
324
336
  }
325
337
  const count = () => ctx.modelRegistry.getAvailable()
326
338
  .filter((model) => model.provider === PROVIDER_ID).length;
327
339
  const before = count();
328
340
  revision = refreshRevision;
329
- // Older Pi versions return void instead of cancellation/error metadata.
341
+ // 较旧的 Pi 版本返回 void,而非取消/错误元数据。
330
342
  const result = (await ctx.modelRegistry.refresh({
331
343
  providers: [PROVIDER_ID], force: true,
332
344
  })) as { aborted?: boolean; errors?: ReadonlyMap<string, Error> } | undefined;
@@ -334,27 +346,27 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
334
346
  const after = count();
335
347
  if (result?.aborted) {
336
348
  recordFailure("刷新已取消,保留原目录");
337
- ctx.ui.notify(`TSGW model refresh cancelled (${before} → ${after}).`, "warning");
349
+ ctx.ui.notify(`TSGW 模型刷新已取消(${before} → ${after})。`, "warning");
338
350
  } else if (result?.errors?.has(PROVIDER_ID)) {
339
351
  recordFailure("刷新失败,保留原目录;请检查凭据、网关与网络");
340
- ctx.ui.notify(`TSGW model refresh failed (${before} → ${after}).`, "error");
352
+ ctx.ui.notify(`TSGW 模型刷新失败(${before} → ${after})。`, "error");
341
353
  } else {
342
- ctx.ui.notify(`TSGW models refreshed (${before} → ${after}).`, "info");
354
+ ctx.ui.notify(`TSGW 模型已刷新(${before} → ${after})。`, "info");
343
355
  }
344
356
  } catch {
345
357
  if (lifecycle !== lifecycleRevision) return;
346
358
  recordFailure("刷新失败,保留原目录;请检查凭据、网关与网络");
347
- ctx.ui.notify("TSGW model refresh failed; keeping the previous catalog.", "error");
359
+ ctx.ui.notify("TSGW 模型刷新失败;保留原目录。", "error");
348
360
  } finally {
349
361
  if (lifecycle === lifecycleRevision) refreshPending = false;
350
362
  }
351
363
  };
352
364
  pi.registerCommand("tsgw-refresh", {
353
- description: "Force-refresh the TSGW gateway model catalog",
365
+ description: "强制刷新 TSGW 网关模型目录",
354
366
  handler: async (_args, ctx) => refreshCatalog(ctx),
355
367
  });
356
368
  pi.registerCommand("tsgw", {
357
- description: "TSGW model catalog and configuration diagnostics",
369
+ description: "TSGW 模型目录与配置诊断",
358
370
  handler: async (_args, ctx) => {
359
371
  if (!ctx.hasUI) return;
360
372
  const lifecycle = lifecycleRevision;
@@ -370,56 +382,21 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
370
382
  }
371
383
  },
372
384
  });
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;
377
- await ctx.waitForIdle();
378
- if (lifecycle !== lifecycleRevision) return;
379
- refreshRequestState(ctx);
380
- bindStatus(ctx);
381
- const support = searchSupport();
382
- if (!support) {
383
- ctx.ui.notify("当前模型不支持插件内置联网。", "info");
384
- return;
385
- }
386
- if (support === "grok") {
387
- ctx.ui.notify("当前 Grok 模型内置联网固定为实时;不修改 GPT 会话模式。", "info");
388
- return;
389
- }
390
- const modes: WebSearchMode[] = ["cached", "live"];
391
- const labels = modes.map((mode) => searchLabel(mode, support));
392
- const input = args.trim();
393
- const choice = input || (ctx.hasUI
394
- ? await ctx.ui.select("内置联网(仅本会话)", labels) : undefined);
395
- if (!choice || lifecycle !== lifecycleRevision) return;
396
- if (searchSupport() !== support) {
397
- ctx.ui.notify("模型支持性已变化,请重新选择内置联网模式。", "warning");
398
- return;
399
- }
400
- const mode = modes.find((mode, index) => mode === choice || labels[index] === choice);
401
- if (!mode) {
402
- ctx.ui.notify("不支持的模式;GPT 仅支持 cached/live,Grok 固定实时。", "warning");
403
- return;
404
- }
405
- tsSearchMode = mode;
406
- publishStatus?.();
407
- ctx.ui.notify(`${searchLabel(mode, support)};仅本会话生效。`, "info");
408
- },
409
- });
410
-
411
385
  pi.on("session_start", (_event, ctx) => {
412
386
  lifecycleRevision++;
413
387
  refreshPending = false;
414
- tsSearchMode = defaultSearchMode;
388
+ search.reset();
415
389
  refreshRequestState(ctx);
390
+ search.sync();
416
391
  bindStatus(ctx);
417
392
  });
418
393
  pi.on("agent_start", (_event, ctx) => {
419
394
  refreshRequestState(ctx);
395
+ search.sync();
420
396
  bindStatus(ctx);
421
397
  });
422
398
  pi.on("session_shutdown", () => {
399
+ search.stop();
423
400
  lifecycleRevision++;
424
401
  refreshPending = false;
425
402
  publishStatus = undefined;
@@ -429,6 +406,7 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
429
406
  event.model,
430
407
  requestState?.thinkingLevel ?? "off",
431
408
  );
409
+ search.sync();
432
410
  if (ctx) bindStatus(ctx);
433
411
  });
434
412
  pi.on("thinking_level_select", (event) => {
@@ -444,7 +422,7 @@ export default async function registerTsgw(pi: ExtensionAPI): Promise<void> {
444
422
  modelId: state.modelId,
445
423
  api: state.api,
446
424
  thinkingLevel: state.thinkingLevel,
447
- tsSearchMode: tsSearchMode,
425
+ tsSearchMode: search.mode(),
448
426
  };
449
427
  // 模型模块统一完成请求改写:厂商思维链策略 + 内置查询工具注入。
450
428
  return applyModelOperations(event.payload, context);
@@ -0,0 +1,26 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ export const TS_OHT_NAME = "ts_oht";
4
+ export const TS_OHT_URL = "https://xn--oht.cc/mcp";
5
+
6
+ /** 仅设置会话默认值;文件覆盖、连接与 OAuth 由 Pi 管理。 */
7
+ export function registerTsgwMcp(pi: ExtensionAPI, configuredUrl?: unknown): void {
8
+ const value = configuredUrl === undefined ? TS_OHT_URL : configuredUrl;
9
+ try {
10
+ if (typeof value !== "string" || value.trim() !== value) throw new Error();
11
+ const url = new URL(value);
12
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.hash)
13
+ throw new Error();
14
+ } catch {
15
+ // 显式配置无效时,不得改用其他默认地址连接。
16
+ // 常规日志中绝不包含 URL 或解析器错误。
17
+ console.error("TSGW:mcpUrl 无效;已跳过 ts_oht 注册。");
18
+ return;
19
+ }
20
+ if (typeof pi.registerMcpServer !== "function") {
21
+ console.error("TSGW:当前 Pi 宿主无法注册 MCP 服务器;已跳过 ts_oht 注册。");
22
+ return;
23
+ }
24
+ // 保留精确 URL,因为 Pi 将 OAuth 绑定到服务器名称与 URL 的组合。
25
+ pi.registerMcpServer(TS_OHT_NAME, { url: value as string, exposure: "codemode" });
26
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 通用请求改写工具:copy-on-write 的 PayloadWriter、类型与共享辅助函数。
2
+ * 通用请求改写工具:写时复制的 PayloadWriter、类型与共享辅助函数。
3
3
  *
4
4
  * 这是 models 模块的内部工具层(下划线前缀 = 不对外暴露),vendors 分片
5
5
  * 与 operations 调度都从这里引用,避免 vendors ↔ operations 循环依赖。
@@ -7,8 +7,8 @@
7
7
 
8
8
  import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
9
9
 
10
- // Pi 1.x also includes image/classifier configs; this catalog is chat-only.
11
- // Structural extraction keeps compatibility with the older chat-only type.
10
+ // Pi 1.x 还包含图像/分类器配置;本目录仅包含聊天模型。
11
+ // 通过结构提取,保持与旧版仅含聊天模型的类型兼容。
12
12
  export type ChatModelConfig = Extract<ProviderModelConfig, { reasoning: boolean }>;
13
13
 
14
14
  export type ThinkingLevel =
@@ -43,7 +43,7 @@ export function isPlainObject(value: unknown): value is Payload {
43
43
  return prototype === Object.prototype || prototype === null;
44
44
  }
45
45
 
46
- /** Copy the top level and nested objects only when a declared operation changes them. */
46
+ /** 仅当声明的操作确实修改对象时,才复制顶层及嵌套对象。 */
47
47
  export class PayloadWriter {
48
48
  private copy: Payload | undefined;
49
49
 
@@ -130,7 +130,7 @@ export function isMaximum(level: ThinkingLevel): boolean {
130
130
  return level === "xhigh" || level === "max";
131
131
  }
132
132
 
133
- /** 通用开关式 thinking:`off` 禁用,其余启用;移除通用 effort 字段。 */
133
+ /** 通用开关式思考:`off` 禁用,其余启用;移除通用思考深度字段。 */
134
134
  export function applyEnabledThinking(
135
135
  writer: PayloadWriter,
136
136
  level: ThinkingLevel,
@@ -139,7 +139,7 @@ export function applyEnabledThinking(
139
139
  writer.setThinking({ type: level === "off" ? "disabled" : "enabled" });
140
140
  }
141
141
 
142
- /** 厂商思维链策略:对指定模型的请求体应用该厂商的 thinking 改写。 */
142
+ /** 厂商思维链策略:对指定模型的请求体应用该厂商的思考配置改写。 */
143
143
  export type ThinkingApplier = (
144
144
  writer: PayloadWriter,
145
145
  context: ModelOperationContext,
@@ -14,22 +14,21 @@ import { qwenModels } from "./vendors/qwen.ts";
14
14
  export const PROVIDER_ID = "tsgw";
15
15
 
16
16
  /**
17
- * Neutral placeholder root. Point the extension at your gateway through
18
- * settings.json (`"tsgw": { "baseUrl": ... }`); this default only applies
19
- * when nothing is configured.
17
+ * 中性的占位根地址。通过 settings.json(`"tsgw": { "baseUrl": ... }`)
18
+ * 将扩展指向你的网关;仅在未配置时使用此默认值。
20
19
  */
21
20
  export const DEFAULT_ROOT = "https://aih.example.com";
22
21
 
23
- /** Normalize a gateway root, including the common accidental `/v1` suffix. */
22
+ /** 规范化网关根地址,包括处理常见的误加 `/v1` 后缀。 */
24
23
  export function normalizeRoot(value = DEFAULT_ROOT): string {
25
24
  let url: URL;
26
25
  try {
27
26
  url = new URL(value);
28
27
  } catch {
29
- throw new Error(`TSGW baseUrl is not a valid URL: ${value}`);
28
+ throw new Error(`TSGW baseUrl 不是有效的 URL:${value}`);
30
29
  }
31
30
  if (url.protocol !== "https:" && url.protocol !== "http:") {
32
- throw new Error("TSGW baseUrl must use http or https");
31
+ throw new Error("TSGW baseUrl 必须使用 http 或 https");
33
32
  }
34
33
  url.hash = "";
35
34
  url.search = "";
@@ -77,10 +76,10 @@ export function filterModels(
77
76
  }
78
77
 
79
78
  /**
80
- * The authoritative TSGW catalog: vendor slices concatenated in a fixed
81
- * order, then filtered by the configured blacklist/whitelist.
79
+ * TSGW 的权威模型目录:按固定顺序拼接各厂商分片,
80
+ * 然后根据配置的黑白名单进行过滤。
82
81
  *
83
- * 新增模型 → 改对应 vendors 文件;新增供应商 → 这里加一行 import + spread。
82
+ * 新增模型 → 改对应 vendors 文件;新增供应商 → 这里增加导入与展开。
84
83
  */
85
84
  export function modelsForRoot(
86
85
  root: string,
@@ -90,7 +90,7 @@ function uniqueModelIds(data: unknown[]): string[] {
90
90
  return Array.from(ids);
91
91
  }
92
92
 
93
- /** Load the OpenAI-compatible model list exposed by a gateway. */
93
+ /** 加载网关提供的 OpenAI 兼容模型列表。 */
94
94
  export async function fetchGatewayModelIds(
95
95
  baseUrl: string,
96
96
  apiKey: string,
@@ -156,12 +156,12 @@ export async function fetchGatewayModelIds(
156
156
  }
157
157
  }
158
158
 
159
- /** Create a defensive, in-memory TTL cache for a gateway model list. */
159
+ /** 为网关模型列表创建带有效期和防御性复制的内存缓存。 */
160
160
  export function createModelCache(
161
161
  ttlMs = DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS,
162
162
  ): ModelCache {
163
163
  if (!Number.isFinite(ttlMs) || ttlMs < 0)
164
- throw new RangeError("ttlMs must be a non-negative finite number");
164
+ throw new RangeError("ttlMs 必须是非负有限数值");
165
165
  let entry: ModelCacheEntry | undefined;
166
166
 
167
167
  return {
@@ -180,7 +180,7 @@ export function createModelCache(
180
180
  };
181
181
  }
182
182
 
183
- /** Hash both identity components; no plaintext credentials in cache keys or files. */
183
+ /** 对两个身份组成部分一起计算哈希;缓存键和文件中不保存明文凭据。 */
184
184
  export function gatewayModelCacheScope(baseUrl: string, apiKey: string): string {
185
185
  return createHash("sha256")
186
186
  .update(JSON.stringify([baseUrl.replace(/\/+$/, ""), apiKey]))
@@ -225,7 +225,7 @@ function isCacheEntryFresh(
225
225
  return Math.max(0, now - entry.storedAt) < ttlMs;
226
226
  }
227
227
 
228
- /** Atomically persist gateway model IDs. Write failures are non-fatal. */
228
+ /** 原子持久化网关模型 ID;写入失败不影响主流程。 */
229
229
  export function saveGatewayModelCache(
230
230
  filePath: string,
231
231
  scope: string,
@@ -245,12 +245,12 @@ export function saveGatewayModelCache(
245
245
  try {
246
246
  unlinkSync(temporaryPath);
247
247
  } catch {
248
- // The temporary file may not have been created.
248
+ // 临时文件可能尚未创建。
249
249
  }
250
250
  }
251
251
  }
252
252
 
253
- /** Load a persisted gateway model list. Missing or invalid files are ignored. */
253
+ /** 加载持久化的网关模型列表;忽略缺失或无效的文件。 */
254
254
  export function loadGatewayModelCache(
255
255
  filePath: string,
256
256
  scope: string,
@@ -258,7 +258,7 @@ export function loadGatewayModelCache(
258
258
  ttlMs = DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS,
259
259
  ): LoadedGatewayModelCache | undefined {
260
260
  if (!Number.isFinite(ttlMs) || ttlMs < 0)
261
- throw new RangeError("ttlMs must be a non-negative finite number");
261
+ throw new RangeError("ttlMs 必须是非负有限数值");
262
262
  const entry = readGatewayModelCacheEntry(filePath, scope);
263
263
  if (!entry) return undefined;
264
264
  return {
@@ -275,7 +275,7 @@ interface PendingRequest {
275
275
  }
276
276
  const inFlightRequests = new Map<string, PendingRequest>();
277
277
  const latestRequests = new Map<string, number>();
278
- // Disk is single-slot per normalized path, independently of the memory scope.
278
+ // 每个规范化路径仅有一个磁盘缓存槽,与内存缓存作用域相互独立。
279
279
  const latestDiskRequests = new Map<string, number>();
280
280
  let revision = 0;
281
281
 
@@ -289,10 +289,10 @@ function cacheFor(key: string): ModelCache {
289
289
  }
290
290
 
291
291
  /**
292
- * Load gateway model IDs with a five-minute process cache.
292
+ * 加载网关模型 ID,使用有效期为五分钟的进程内缓存。
293
293
  *
294
- * Fresh cache entries are returned without I/O. A failed refresh falls back
295
- * to a stale entry when available; otherwise the fetch failure is returned.
294
+ * 缓存未过期时直接返回,不进行输入输出。刷新失败时,若有过期缓存则回退使用;
295
+ * 否则返回获取失败的结果。
296
296
  */
297
297
  export async function getGatewayModelIds(
298
298
  baseUrl: string,
@@ -334,9 +334,9 @@ export async function getGatewayModelIds(
334
334
  }
335
335
 
336
336
  const requestKey = `${key}\0${opts.force ? "force" : "normal"}`;
337
- // A shared request cannot safely inherit one caller's AbortSignal: Pi may
338
- // supersede that refresh while a newer caller is still waiting. Only
339
- // signal-free calls share in-flight work; abortable calls own their fetch.
337
+ // 共享请求无法安全地继承某个调用者的 AbortSignal:较新的调用者仍在等待时,
338
+ // Pi 可能已替换该次刷新。只有不带信号的调用共享进行中的请求;
339
+ // 可取消的调用独立发起获取请求。
340
340
  const shareRequest = opts.signal === undefined;
341
341
  let request = shareRequest ? inFlightRequests.get(requestKey) : undefined;
342
342
  if (!request) {
@@ -356,8 +356,8 @@ export async function getGatewayModelIds(
356
356
 
357
357
  const diskPath = opts.cacheFilePath ? resolve(opts.cacheFilePath) : undefined;
358
358
  if (diskPath) {
359
- // Register every subscriber's path, including shared requests with different
360
- // destinations. Joining an older request must not roll back a newer fence.
359
+ // 登记每个订阅者的路径,包括目标路径不同的共享请求。
360
+ // 加入较旧请求时,不得回退较新的版本屏障。
361
361
  latestDiskRequests.set(diskPath, Math.max(
362
362
  latestDiskRequests.get(diskPath) ?? 0, request.revision,
363
363
  ));
@@ -371,11 +371,11 @@ export async function getGatewayModelIds(
371
371
  inFlightRequests.delete(requestKey);
372
372
  }
373
373
 
374
- // Cancellation never falls back or writes, even if a fetcher ignores its signal.
374
+ // 取消后绝不回退或写入,即使获取器忽略了取消信号。
375
375
  if (opts.signal?.aborted) return { ok: false, reason: "aborted" };
376
376
  if (fetched.ok) {
377
- // Latest-started wins even if the newer request fails or aborts.
378
- // Superseded successes still return to their callers without cache writes.
377
+ // 以后启动的请求为准,即使较新的请求失败或取消。
378
+ // 被取代的成功请求仍向调用者返回结果,但不写入缓存。
379
379
  if (latestRequests.get(key) === request.revision) {
380
380
  cache.set(fetched.ids, request.storedAt);
381
381
  if (diskPath && latestDiskRequests.get(diskPath) === request.revision)
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * 请求体改写调度:按模型 id 查各厂商的思维链策略并应用。
3
3
  *
4
- * 各厂商的 thinking 策略定义在 `vendors/*.ts`(厂商文件自包含其思维链
5
- * 要求),本模块只做汇总与调度,不再硬编码模型族 switch。
4
+ * 各厂商的思维链策略定义在 `vendors/*.ts`(厂商文件自包含其思维链
5
+ * 要求),本模块只做汇总与调度,不再硬编码模型族分支。
6
6
  */
7
7
 
8
8
  import {
@@ -22,7 +22,7 @@ import { minimaxThinking } from "./vendors/minimax.ts";
22
22
  import { openaiThinking } from "./vendors/openai.ts";
23
23
  import { qwenThinking } from "./vendors/qwen.ts";
24
24
 
25
- // 与 catalog.ts 的 PROVIDER_ID 保持一致;此处不 import catalog,避免循环依赖。
25
+ // 与 catalog.ts 的 PROVIDER_ID 保持一致;此处不导入 catalog,避免循环依赖。
26
26
  const TSGW_PROVIDER = "tsgw";
27
27
 
28
28
  const THINKING_STRATEGIES: Record<string, ThinkingApplier> = {
@@ -38,9 +38,9 @@ const THINKING_STRATEGIES: Record<string, ThinkingApplier> = {
38
38
  };
39
39
 
40
40
  /**
41
- * Apply the closed set of per-vendor thinking operations without mutating
42
- * `payload`. Non-plain payloads and all non-TSGW requests are returned
43
- * unchanged. Models without a registered strategy pass through untouched.
41
+ * 应用预先限定的各厂商思维链操作,不修改原始 `payload`。
42
+ * 非普通对象的请求体与所有非 TSGW 请求均原样返回。
43
+ * 未注册策略的模型不做改动,直接透传。
44
44
  */
45
45
  export function applyModelOperations(
46
46
  payload: unknown,
@@ -1,7 +1,7 @@
1
1
  import type { ChatModelConfig as ProviderModelConfig } from "../_tools.ts";
2
2
 
3
3
  /**
4
- * Wire 协议公共配置。
4
+ * 传输协议公共配置。
5
5
  *
6
6
  * 网关上的模型虽然很多,底层协议就这四类:openai-completions、
7
7
  * openai-responses、anthropic-messages、google-generative-ai。
@@ -11,12 +11,12 @@ import type { ChatModelConfig as ProviderModelConfig } from "../_tools.ts";
11
11
  * 有适配需要时再在此扩展。
12
12
  */
13
13
 
14
- /** openai-completions:网关接受 `system` role,但不接受 OpenAI 新的 `developer` role。 */
14
+ /** openai-completions:网关接受 `system` 角色,但不接受 OpenAI 新的 `developer` 角色。 */
15
15
  export const OPENAI_COMPLETIONS_COMPAT: ProviderModelConfig["compat"] = {
16
16
  supportsDeveloperRole: false,
17
17
  };
18
18
 
19
- /** anthropic-messages:Claude 系列使用 Pi 原生 adaptive thinking。 */
19
+ /** anthropic-messages:Claude 系列使用 Pi 原生自适应思考。 */
20
20
  export const ANTHROPIC_COMPAT: ProviderModelConfig["compat"] = {
21
21
  forceAdaptiveThinking: true,
22
22
  };
@@ -1,7 +1,7 @@
1
1
  import type { ChatModelConfig as ProviderModelConfig } from "../_tools.ts";
2
2
 
3
- // DeepSeek Responses 将 developer role 当作 user,且不支持 OpenAI 的
4
- // prompt_cache_retention;其余 reasoning 字段交给 Pi 的 Responses adapter。
3
+ // DeepSeek Responses 将 developer 角色当作 user,且不支持 OpenAI 的
4
+ // prompt_cache_retention;其余 reasoning 字段交给 Pi 的 Responses 适配器。
5
5
  const DEEPSEEK_RESPONSES_COMPAT = {
6
6
  supportsDeveloperRole: false,
7
7
  supportsLongCacheRetention: false,
@@ -9,7 +9,12 @@ const DEEPSEEK_RESPONSES_COMPAT = {
9
9
 
10
10
  /**
11
11
  * DeepSeek(深度求索)系列:V4.1 Flash 与 V4 Pro。
12
- * 官方文档:https://api-docs.deepseek.com/guides/responses_api
12
+ * 协议文档:https://api-docs.deepseek.com/guides/responses_api
13
+ * 定价依据(2026-10-16):https://api-docs.deepseek.com/zh-cn/quick_start/pricing/
14
+ * 国内高峰价(元/百万词元):Flash 输入/输出/命中 2/8/0.04,Pro 9/27/0.30。
15
+ * 按项目固定 0.1475 USD/CNY 折算;静态 cost 用高峰价保守估算,不按请求时间切换。
16
+ * 空闲时段为半价;高峰为北京时间工作日(不含中国法定节假日)9–12、14–18。
17
+ * cacheWrite=0 表示官方未单列附加缓存写入费用;非网关实际计费。
13
18
  */
14
19
  export function deepseekModels(root: string): ProviderModelConfig[] {
15
20
  const v1 = `${root}/v1`;
@@ -21,7 +26,7 @@ export function deepseekModels(root: string): ProviderModelConfig[] {
21
26
  baseUrl: v1,
22
27
  reasoning: true,
23
28
  input: ["text", "image"],
24
- cost: { input: 0.1475, output: 0.295, cacheRead: 0.00295, cacheWrite: 0 },
29
+ cost: { input: 0.295, output: 1.18, cacheRead: 0.0059, cacheWrite: 0 },
25
30
  contextWindow: 1000000,
26
31
  maxTokens: 384000,
27
32
  compat: DEEPSEEK_RESPONSES_COMPAT,
@@ -43,9 +48,9 @@ export function deepseekModels(root: string): ProviderModelConfig[] {
43
48
  reasoning: true,
44
49
  input: ["text"],
45
50
  cost: {
46
- input: 0.4425,
47
- output: 0.885,
48
- cacheRead: 0.0036875,
51
+ input: 1.3275,
52
+ output: 3.9825,
53
+ cacheRead: 0.04425,
49
54
  cacheWrite: 0,
50
55
  },
51
56
  contextWindow: 1000000,
@@ -5,7 +5,7 @@ import { type PayloadWriter, type ThinkingApplier, type ThinkingLevel } from "..
5
5
  * Google Gemini 系列(google-generative-ai 协议)。
6
6
  * 官方文档:https://ai.google.dev/gemini-api/docs
7
7
  * GenerateContent 档位/预算:https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thinking
8
- * gemini-flash 别名保留 budget 策略,其他保留型号使用 level。网关别名的路由仍需网关侧验证。
8
+ * gemini-flash 别名保留预算策略,其他保留型号使用档位策略。网关别名的路由仍需网关侧验证。
9
9
  */
10
10
  export function geminiModels(root: string): ProviderModelConfig[] {
11
11
  const gemini = `${root}/gemini`;
@@ -92,7 +92,7 @@ function applyGeminiPro(writer: PayloadWriter, level: ThinkingLevel): void {
92
92
  writer.setGoogleThinking({ includeThoughts: level !== "off", thinkingLevel }, ["thinkingBudget"]);
93
93
  }
94
94
 
95
- // 3.5 Flash 支持 MINIMAL/LOW/MEDIUM/HIGH,不使用 token budget。
95
+ // 3.5 Flash 支持 MINIMAL/LOW/MEDIUM/HIGH,不使用词元预算。
96
96
  function applyGemini35Flash(writer: PayloadWriter, level: ThinkingLevel): void {
97
97
  writer.remove("reasoning_effort");
98
98
  const thinkingLevel = level === "off" || level === "minimal" ? "MINIMAL"
@@ -5,13 +5,13 @@ import { isMaximum, type PayloadWriter, type ThinkingApplier, type ThinkingLevel
5
5
  /**
6
6
  * 智谱 AI(Zhipu)GLM 系列。
7
7
  * 国内官方依据:
8
- * https://docs.bigmodel.cn/cn/guide/capabilities/thinking (effort 仅 5.2+)
8
+ * https://docs.bigmodel.cn/cn/guide/capabilities/thinking (思考深度设置仅支持 5.2+)
9
9
  * https://docs.bigmodel.cn/cn/guide/capabilities/thinking-mode (保留式思考)
10
10
  * 2026-10-16 5.3 / Flash / FlashX:始终思考,仅 low/high/max。
11
11
  * https://docs.bigmodel.cn/cn/guide/models/text/glm-5.3
12
12
  * https://docs.bigmodel.cn/cn/guide/models/vlm/glm-5.3-flash
13
13
  * https://docs.bigmodel.cn/cn/guide/start/pricing
14
- * 国内 CNY/百万 tokens 按既有固定 0.1475 USD/CNY 估算(非实时汇率);
14
+ * 国内 CNY/百万词元按既有固定 0.1475 USD/CNY 估算(非实时汇率);
15
15
  * 三型号输入/输出/缓存命中为 8/28/2、0.8/2.8/0.23、2/7/0.57,
16
16
  * 缓存存储限时免费。1M 上下文与 128K 最大输出分别登记。
17
17
  */