pi-tsgw 0.4.1 → 0.5.0

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
@@ -124,9 +124,23 @@ GLM 5.3 仅支持文本。注册并不证明网关支持推理或工具调用。
124
124
  请保留 `MiniMax-*` 的大小写。网关目录可用时,先与静态目录取交集,再应用过滤。
125
125
  纳入规则无法添加未知或不可用的 ID。
126
126
 
127
- 打开 `/model` 会在后台刷新网关目录,并使用五分钟缓存避免重复请求。
128
- 运行 `/tsgw-refresh` 可绕过缓存立即强制刷新,无需重启或重新加载 Pi。
129
- 刷新失败时,继续使用最近一次成功获取的模型列表。
127
+ 插件启动时复用 **7 天**内的缓存;缓存过期才联网刷新。工具调用复用 **24 小时**内的缓存。
128
+ 宿主额外的非强制后台同步沿用已登记目录,不追加联网请求;需要获取新目录时调用工具
129
+ 或强制刷新。所有入口使用同一份缓存,命中缓存和
130
+ 失败回退均不更新原始获取时间。单次联网超时 **5 秒**;仅启动时无有效作用域缓存
131
+ 允许失败后重试一次,其余情况不自动重试。
132
+ 启动有旧缓存时刷新失败会沿用缓存;无缓存且两次失败时正常加载,但 TSGW 登记零个模型,
133
+ 不回退静态目录。启动失败提示通过宿主 `ui.notify` 发出(Pi Web Toast),提醒择机强制刷新;
134
+ 非 UI 模式仍可使用且保留状态诊断。缺少可解析凭据时不联网、不登记模型。
135
+ 运行 `/tsgw-refresh` 可绕过缓存立即强制刷新,无需重启或重新加载 Pi;成功后可恢复目录。
136
+ 动态刷新失败保留最近已登记的列表。
137
+
138
+ 模型可通过 codemode 调用 `tools.tsgw_refresh_models({})` 自动获取,
139
+ 或 `tools.tsgw_refresh_models({ force: true })` 强制刷新。
140
+ 工具返回 `cacheFilePath`、`count` 与 `storedAt`,随后读取该文件的 `ids` 即为完整网关列表,
141
+ 包括尚未静态登记的型号;不会把完整列表重复塞入工具返回值,也不会自动登记未知型号。
142
+ 工具确认文件符合当前缓存窗口;强制刷新时要求本次写入。取消、刷新失败或未确认落盘时
143
+ 不会把旧文件报成本次刷新成功。
130
144
 
131
145
  内存和磁盘缓存通过 SHA-256 摘要限定在网关根地址与凭据对应的作用域内;不存储明文凭据。
132
146
  磁盘缓存仅有一个槽位,位于 `<agent-dir>/tsgw/models-cache.json`:改变作用域可能需要
@@ -9,7 +9,8 @@ import {
9
9
  import { dirname, resolve } from "node:path";
10
10
 
11
11
  export const DEFAULT_GATEWAY_MODEL_TIMEOUT_MS = 5_000;
12
- export const DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS = 5 * 60 * 1_000;
12
+ export const DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS = 24 * 60 * 60 * 1_000;
13
+ export const STARTUP_GATEWAY_MODEL_CACHE_TTL_MS = 7 * DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS;
13
14
 
14
15
  export type GatewayModelFailureReason =
15
16
  | "http"
@@ -34,6 +35,10 @@ export interface FetchGatewayModelIdsOptions {
34
35
  export interface GetGatewayModelIdsOptions extends FetchGatewayModelIdsOptions {
35
36
  cacheFilePath?: string;
36
37
  force?: boolean;
38
+ /** 各入口独立判断新鲜度,但共用原始获取时间与缓存。 */
39
+ ttlMs?: number;
40
+ /** 仅启动无有效作用域缓存时允许失败后重试一次。 */
41
+ retryWithoutCache?: boolean;
37
42
  }
38
43
 
39
44
  export type FetchGatewayModelIdsResult =
@@ -187,10 +192,9 @@ export function gatewayModelCacheScope(baseUrl: string, apiKey: string): string
187
192
  .digest("hex");
188
193
  }
189
194
 
190
- function readGatewayModelCacheEntry(
195
+ function readGatewayModelCacheSnapshot(
191
196
  filePath: string,
192
- scope: string,
193
- ): ModelCacheEntry | undefined {
197
+ ): (ModelCacheEntry & { scope: string }) | undefined {
194
198
  try {
195
199
  const payload: unknown = JSON.parse(readFileSync(filePath, "utf8"));
196
200
  if (!payload || typeof payload !== "object") return undefined;
@@ -200,15 +204,16 @@ function readGatewayModelCacheEntry(
200
204
  ids?: unknown;
201
205
  };
202
206
  if (
203
- !scope || storedScope !== scope ||
207
+ typeof storedScope !== "string" || !storedScope ||
204
208
  typeof storedAt !== "number" ||
205
209
  !Number.isFinite(storedAt) ||
206
210
  storedAt < 0 ||
207
- !Array.isArray(ids) ||
211
+ !Array.isArray(ids) || ids.length === 0 ||
208
212
  !ids.every((id) => typeof id === "string" && id.trim())
209
213
  )
210
214
  return undefined;
211
215
  return {
216
+ scope: storedScope,
212
217
  storedAt,
213
218
  ids: Array.from(new Set(ids.map((id) => id.trim()))),
214
219
  };
@@ -217,6 +222,27 @@ function readGatewayModelCacheEntry(
217
222
  }
218
223
  }
219
224
 
225
+ function readGatewayModelCacheEntry(
226
+ filePath: string,
227
+ scope: string,
228
+ ): ModelCacheEntry | undefined {
229
+ const snapshot = readGatewayModelCacheSnapshot(filePath);
230
+ if (!scope || snapshot?.scope !== scope) return undefined;
231
+ return { storedAt: snapshot.storedAt, ids: snapshot.ids };
232
+ }
233
+
234
+ /** 刷新后的文件摘要;只确认可读性与获取时间,不用于恢复目录或认证作用域。 */
235
+ export function readGatewayModelCacheSummary(
236
+ cacheFilePath: string,
237
+ minimumStoredAt: number,
238
+ ): { cacheFilePath: string; count: number; storedAt: number } | undefined {
239
+ if (!Number.isFinite(minimumStoredAt) || minimumStoredAt < 0) return undefined;
240
+ const snapshot = readGatewayModelCacheSnapshot(cacheFilePath);
241
+ if (!snapshot || !snapshot.ids.length || snapshot.storedAt < minimumStoredAt)
242
+ return undefined;
243
+ return { cacheFilePath, count: snapshot.ids.length, storedAt: snapshot.storedAt };
244
+ }
245
+
220
246
  function isCacheEntryFresh(
221
247
  entry: ModelCacheEntry,
222
248
  now: number,
@@ -289,7 +315,7 @@ function cacheFor(key: string): ModelCache {
289
315
  }
290
316
 
291
317
  /**
292
- * 加载网关模型 ID,使用有效期为五分钟的进程内缓存。
318
+ * 加载网关模型 ID,默认有效期为 24 小时;启动入口可指定 7 天。
293
319
  *
294
320
  * 缓存未过期时直接返回,不进行输入输出。刷新失败时,若有过期缓存则回退使用;
295
321
  * 否则返回获取失败的结果。
@@ -302,9 +328,12 @@ export async function getGatewayModelIds(
302
328
  ): Promise<GetGatewayModelIdsResult> {
303
329
  if (opts.signal?.aborted) return { ok: false, reason: "aborted" };
304
330
  const key = gatewayModelCacheScope(baseUrl, apiKey);
331
+ const ttlMs = opts.ttlMs ?? DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS;
332
+ if (!Number.isFinite(ttlMs) || ttlMs < 0) throw new RangeError("ttlMs 必须是非负有限数值");
305
333
  const cache = cacheFor(key);
306
- if (!opts.force && cache.isFresh(now)) {
307
- const entry = cache.get();
334
+ const memoryEntryBefore = cache.get();
335
+ if (!opts.force && memoryEntryBefore && isCacheEntryFresh(memoryEntryBefore, now, ttlMs)) {
336
+ const entry = memoryEntryBefore;
308
337
  if (entry)
309
338
  return {
310
339
  ok: true,
@@ -321,7 +350,7 @@ export async function getGatewayModelIds(
321
350
  if (
322
351
  !opts.force &&
323
352
  diskEntry &&
324
- isCacheEntryFresh(diskEntry, now, DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS)
353
+ isCacheEntryFresh(diskEntry, now, ttlMs)
325
354
  ) {
326
355
  cache.set(diskEntry.ids, diskEntry.storedAt);
327
356
  return {
@@ -333,7 +362,8 @@ export async function getGatewayModelIds(
333
362
  };
334
363
  }
335
364
 
336
- const requestKey = `${key}\0${opts.force ? "force" : "normal"}`;
365
+ const retry = opts.retryWithoutCache === true && !memoryEntryBefore && !diskEntry;
366
+ const requestKey = `${key}\0${opts.force ? "force" : "normal"}\0${retry}\0${opts.timeoutMs ?? DEFAULT_GATEWAY_MODEL_TIMEOUT_MS}`;
337
367
  // 共享请求无法安全地继承某个调用者的 AbortSignal:较新的调用者仍在等待时,
338
368
  // Pi 可能已替换该次刷新。只有不带信号的调用共享进行中的请求;
339
369
  // 可取消的调用独立发起获取请求。
@@ -345,11 +375,11 @@ export async function getGatewayModelIds(
345
375
  request = {
346
376
  revision: requestRevision,
347
377
  storedAt: now,
348
- promise: fetchGatewayModelIds(baseUrl, apiKey, {
349
- fetcher: opts.fetcher,
350
- timeoutMs: opts.timeoutMs,
351
- signal: opts.signal,
352
- }),
378
+ promise: (async () => {
379
+ const first = await fetchGatewayModelIds(baseUrl, apiKey, opts);
380
+ if (first.ok || !retry || first.reason === "aborted" || opts.signal?.aborted) return first;
381
+ return fetchGatewayModelIds(baseUrl, apiKey, opts);
382
+ })(),
353
383
  };
354
384
  if (shareRequest) inFlightRequests.set(requestKey, request);
355
385
  }
@@ -19,7 +19,7 @@ import {
19
19
  normalizeRoot,
20
20
  type ModelFilter,
21
21
  } from "../models/catalog.ts";
22
- import { getGatewayModelIds } from "../models/gateway-catalog.ts";
22
+ import { getGatewayModelIds, STARTUP_GATEWAY_MODEL_CACHE_TTL_MS } from "../models/gateway-catalog.ts";
23
23
  import { applyModelOperations } from "../models/operations.ts";
24
24
  import { registerSearch } from "../search/index.ts";
25
25
  import { IMAGE_API, imageModelsForRoot, supportsImageModels } from "../images/models.ts";
@@ -32,6 +32,7 @@ import {
32
32
  } from "./status.ts";
33
33
  import type { ThinkingLevel, WebSearchMode } from "../models/_tools.ts";
34
34
  import type { TsgwSettings } from "./config.ts";
35
+ import { registerRefreshTool } from "./refresh-tool.ts";
35
36
 
36
37
  /**
37
38
  * 在生命周期上下文仍有效时,复制供应商钩子所需的数据。
@@ -121,13 +122,13 @@ function effectiveModelsForGateway(
121
122
  ];
122
123
  const intersected = gatewayIds
123
124
  ? staticModels.filter((model) => gatewayHasModel(gatewayIds, model.id))
124
- : staticModels;
125
+ : [];
125
126
  return filterModels(intersected, filter);
126
127
  }
127
128
 
128
129
  /**
129
130
  * 三层模型过滤:静态目录 ∩ 网关实际列表 ∩ 用户黑白名单。
130
- * 网关列表拉取失败/无凭据时跳过网关层(回退静态目录)。
131
+ * 无网关目录时不登记模型,避免将静态登记误认为网关可用。
131
132
  */
132
133
  async function resolveEffectiveModels(
133
134
  root: string,
@@ -139,7 +140,7 @@ async function resolveEffectiveModels(
139
140
  gatewayIds: ReadonlySet<string> | undefined;
140
141
  catalog: CatalogStatus;
141
142
  }> {
142
- // 凭据解析失败不阻塞:无凭据时直接跳过网关层。
143
+ // 凭据解析失败不阻塞插件加载,但不登记未经网关确认的模型。
143
144
  let apiKey = "";
144
145
  try {
145
146
  const credential = readStoredCredential(PROVIDER_ID);
@@ -149,11 +150,15 @@ async function resolveEffectiveModels(
149
150
  }
150
151
 
151
152
  let gatewayIds: ReadonlySet<string> | undefined;
152
- let catalog: CatalogStatus = { count: 0, source: "static", loading: false };
153
+ let catalog: CatalogStatus = { count: 0, source: "empty", loading: false,
154
+ ttlMs: STARTUP_GATEWAY_MODEL_CACHE_TTL_MS,
155
+ error: "模型目录获取失败,当前无可用模型;请配置凭据后择机强制刷新。" };
153
156
  if (apiKey) {
154
157
  try {
155
158
  const gateway = await getGatewayModelIds(root, apiKey, {
156
159
  cacheFilePath,
160
+ ttlMs: STARTUP_GATEWAY_MODEL_CACHE_TTL_MS,
161
+ retryWithoutCache: true,
157
162
  });
158
163
  if (gateway.ok) {
159
164
  gatewayIds = new Set(gateway.ids);
@@ -162,11 +167,11 @@ async function resolveEffectiveModels(
162
167
  source: gateway.cached ? "cache" : "network",
163
168
  storedAt: gateway.storedAt,
164
169
  error: gateway.stale
165
- ? `刷新失败(${gateway.fallbackReason ?? "unknown"}),沿用旧目录` : undefined,
170
+ ? "模型目录刷新失败,已沿用缓存,请择机强制刷新。" : undefined,
166
171
  };
167
- } else catalog.error = `目录获取失败(${gateway.reason}),使用内置目录`;
172
+ } else catalog.error = "模型目录获取失败,当前无可用模型,请择机强制刷新。";
168
173
  } catch {
169
- catalog.error = "目录获取失败,使用内置目录";
174
+ catalog.error = "模型目录获取失败,当前无可用模型,请择机强制刷新。";
170
175
  }
171
176
  }
172
177
  if (catalog.error) console.warn(`TSGW: ${catalog.error}`);
@@ -189,6 +194,7 @@ export async function registerTsgwProvider(
189
194
  exclude: settings.excludeModels,
190
195
  };
191
196
  const cacheFilePath = gatewayModelCachePath();
197
+ registerRefreshTool(pi, cacheFilePath);
192
198
  let requestState: RequestState | undefined;
193
199
 
194
200
  const refreshRequestState = (ctx: {
@@ -208,6 +214,7 @@ export async function registerTsgwProvider(
208
214
  const { models } = initial;
209
215
  let latestModels = models;
210
216
  let catalog = initial.catalog;
217
+ let startupNotice = initial.catalog.error;
211
218
  let credentialConfigured = false;
212
219
  let publishStatus: (() => void) | undefined;
213
220
  let refreshRevision = 0;
@@ -247,7 +254,9 @@ export async function registerTsgwProvider(
247
254
  models,
248
255
  ...(imagesEnabled ? { images: { [IMAGE_API]: { generateImages } } } : {}),
249
256
  async refreshModels(context) {
250
- if (!context.allowNetwork) return latestModels;
257
+ // 启动获取已完成;宿主的额外自动同步不再追加联网请求。
258
+ // 工具检查 24 小时窗口,必要时与命令一样显式传入 force。
259
+ if (!context.allowNetwork || context.force !== true) return latestModels;
251
260
  context.signal.throwIfAborted();
252
261
  const revision = ++refreshRevision;
253
262
  catalog = { ...catalog, loading: true };
@@ -263,11 +272,10 @@ export async function registerTsgwProvider(
263
272
  signal: context.signal,
264
273
  });
265
274
  context.signal.throwIfAborted();
266
- if (!gateway.ok)
267
- throw new Error(`TSGW 网关模型刷新失败(${gateway.reason})。`);
268
- if (gateway.stale)
275
+ if (!gateway.ok || gateway.stale)
269
276
  throw new Error("TSGW 刷新失败;保留上次成功获取的目录。");
270
277
  if (revision === refreshRevision) {
278
+ startupNotice = undefined;
271
279
  latestModels = effectiveModelsForGateway(root, modelFilter, new Set(gateway.ids), imagesEnabled);
272
280
  search.sync();
273
281
  catalog = {
@@ -370,6 +378,10 @@ export async function registerTsgwProvider(
370
378
  refreshRequestState(ctx);
371
379
  search.sync();
372
380
  bindStatus(ctx);
381
+ if (startupNotice && ctx.hasUI) {
382
+ ctx.ui.notify(startupNotice, "warning");
383
+ startupNotice = undefined;
384
+ }
373
385
  });
374
386
  pi.on("agent_start", (_event, ctx) => {
375
387
  refreshRequestState(ctx);
@@ -0,0 +1,48 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { PROVIDER_ID } from "../models/catalog.ts";
4
+ import { DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS, readGatewayModelCacheSummary } from "../models/gateway-catalog.ts";
5
+
6
+ /** 默认检查缓存时间;需要联网时复用宿主 provider 的强制刷新。 */
7
+ export function registerRefreshTool(pi: ExtensionAPI, cacheFilePath: string): void {
8
+ pi.registerTool({
9
+ name: "tsgw_refresh_models",
10
+ label: "刷新 TSGW 模型目录",
11
+ description: "获取 AIH 网关可用模型,默认复用 24 小时内的缓存;force=true 忽略有效期强制联网刷新。单次联网超时 5 秒,不发推理请求、不修改配置、不自动重试。返回缓存文件路径、网关模型数与获取时间;随后读取该文件的 ids 获取完整列表(含插件尚未登记的型号)。不自动登记未知型号。",
12
+ parameters: Type.Object({
13
+ force: Type.Optional(Type.Boolean({ description: "忽略缓存有效期强制联网刷新,默认 false。" })),
14
+ }),
15
+ outputSchema: Type.Object({
16
+ cacheFilePath: Type.String(), count: Type.Integer(), storedAt: Type.Number(),
17
+ }),
18
+ exposure: "codemode",
19
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
20
+ async execute(_id, params, signal, _onUpdate, ctx) {
21
+ const caller = signal && ctx.signal && signal !== ctx.signal
22
+ ? AbortSignal.any([signal, ctx.signal]) : signal ?? ctx.signal;
23
+ const registry = ctx.modelRegistry;
24
+ const startedAt = Date.now();
25
+ let details;
26
+ let refreshed;
27
+ try {
28
+ caller?.throwIfAborted();
29
+ if (!registry.getProviderAuthStatus(PROVIDER_ID).configured) throw new Error("缺少凭据");
30
+ if (params.force !== true)
31
+ details = readGatewayModelCacheSummary(cacheFilePath, startedAt - DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS + 1);
32
+ if (!details) {
33
+ refreshed = await registry.refresh({ providers: [PROVIDER_ID], force: true, signal: caller });
34
+ caller?.throwIfAborted();
35
+ }
36
+ } catch {
37
+ throw new Error(caller?.aborted ? "TSGW 模型刷新已取消。" : "TSGW 模型刷新失败;请检查宿主凭据、网关与网络。未输出原始错误。");
38
+ }
39
+ if (refreshed?.aborted) throw new Error("TSGW 模型刷新已取消。");
40
+ if (refreshed?.errors?.has(PROVIDER_ID))
41
+ throw new Error("TSGW 模型刷新失败,保留原目录;请检查宿主凭据、网关与网络。");
42
+ details ??= readGatewayModelCacheSummary(cacheFilePath, startedAt);
43
+ if (!details)
44
+ throw new Error("未确认本次完整网关目录已写入缓存文件;不能将旧文件当作本次刷新结果。provider 可能已经更新。");
45
+ return { content: [{ type: "text", text: JSON.stringify(details) }], details, structuredContent: details };
46
+ },
47
+ });
48
+ }
@@ -3,7 +3,9 @@ import { DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS } from "../models/gateway-catalog.ts
3
3
 
4
4
  export interface CatalogStatus {
5
5
  count: number;
6
- source: "static" | "cache" | "network";
6
+ source: "static" | "empty" | "cache" | "network";
7
+ /** 当前入口采用的新鲜度窗口;启动为 7 天,运行时为 24 小时。 */
8
+ ttlMs?: number;
7
9
  /** 网关目录真实获取时间;从缓存读取时保留原值,不重置为读取时间。 */
8
10
  storedAt?: number;
9
11
  loading: boolean;
@@ -13,6 +15,7 @@ export interface CatalogStatus {
13
15
 
14
16
  const SOURCE_LABELS = {
15
17
  static: "内置静态",
18
+ empty: "无可用目录",
16
19
  cache: "缓存",
17
20
  network: "网关",
18
21
  } as const;
@@ -20,7 +23,7 @@ const SOURCE_LABELS = {
20
23
  function fetchedAt(state: CatalogStatus): number | undefined {
21
24
  const time = state.storedAt;
22
25
  if (
23
- state.source === "static" ||
26
+ (state.source === "static" || state.source === "empty") ||
24
27
  time === undefined ||
25
28
  !Number.isFinite(time) ||
26
29
  time < 0 ||
@@ -33,7 +36,7 @@ function freshness(state: CatalogStatus, now: number): "新鲜" | "过期" | "
33
36
  const time = fetchedAt(state);
34
37
  if (time === undefined || !Number.isFinite(now)) return "未知";
35
38
  // 与目录缓存一致:时钟回拨不判过期,达到 TTL 则过期。
36
- return Math.max(0, now - time) < DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS
39
+ return Math.max(0, now - time) < (state.ttlMs ?? DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS)
37
40
  ? "新鲜"
38
41
  : "过期";
39
42
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tsgw",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "面向 TOSSP AIH gateway 的 Pi 扩展:按厂商维护聊天与图片模型目录及思考策略,支持四种聊天协议与图片生成、编辑工具。",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -24,7 +24,7 @@
24
24
  ]
25
25
  },
26
26
  "scripts": {
27
- "test": "tsc -p tsconfig.test.json && node dist/extensions/provider/index.test.js && node dist/extensions/prompts.test.js && node dist/extensions/provider/status.test.js && node dist/extensions/search/index.test.js && node dist/extensions/search/proxy.test.js && node dist/extensions/search/host-integration.test.js && node dist/extensions/provider/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 && node dist/extensions/models/gateway-catalog-isolation.test.js && node dist/extensions/models/vendor-strategies.test.js && node dist/extensions/images/models.test.js && node dist/extensions/images/parameters.test.js && node dist/extensions/images/input-budget.test.js && node dist/extensions/images/edit-request.test.js && node dist/extensions/images/image-data.test.js && node dist/extensions/images/response.test.js && node dist/extensions/images/stream-response.test.js && node dist/extensions/images/adapter.test.js && node dist/extensions/images/tool-files.test.js && node dist/extensions/images/tools.test.js && node dist/extensions/images/host-integration.test.js && node dist/extensions/images/tools-host.test.js && node dist/index.test.js && node dist/extensions/skills.test.js && node dist/extensions/skill-resources.test.js && node dist/extensions/upload/protocol.test.js && node dist/extensions/upload/schema.test.js && node dist/extensions/upload/uploader.test.js && node dist/extensions/upload/transport.test.js && node dist/extensions/upload/host-integration.test.js && node dist/extensions/upload/readiness-host.test.js",
27
+ "test": "tsc -p tsconfig.test.json && node dist/extensions/provider/index.test.js && node dist/extensions/provider/refresh-tool.test.js && node dist/extensions/provider/startup-catalog.test.js && node dist/extensions/prompts.test.js && node dist/extensions/provider/status.test.js && node dist/extensions/search/index.test.js && node dist/extensions/search/proxy.test.js && node dist/extensions/search/host-integration.test.js && node dist/extensions/provider/status-integration.test.js && node dist/extensions/models/gateway-catalog-metadata.test.js && node dist/extensions/models/gateway-catalog-policy.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/models/gateway-catalog-isolation.test.js && node dist/extensions/models/vendor-strategies.test.js && node dist/extensions/images/models.test.js && node dist/extensions/images/parameters.test.js && node dist/extensions/images/input-budget.test.js && node dist/extensions/images/edit-request.test.js && node dist/extensions/images/image-data.test.js && node dist/extensions/images/response.test.js && node dist/extensions/images/stream-response.test.js && node dist/extensions/images/adapter.test.js && node dist/extensions/images/tool-files.test.js && node dist/extensions/images/tools.test.js && node dist/extensions/images/host-integration.test.js && node dist/extensions/images/tools-host.test.js && node dist/index.test.js && node dist/extensions/skills.test.js && node dist/extensions/skill-resources.test.js && node dist/extensions/upload/protocol.test.js && node dist/extensions/upload/schema.test.js && node dist/extensions/upload/uploader.test.js && node dist/extensions/upload/transport.test.js && node dist/extensions/upload/host-integration.test.js && node dist/extensions/upload/readiness-host.test.js",
28
28
  "test:upload:live": "tsc -p tsconfig.test.json && node dist/extensions/upload/live.test.js"
29
29
  },
30
30
  "peerDependencies": {
@@ -1,32 +1,32 @@
1
1
  ---
2
2
  name: tsgw-image-generation
3
- description: 当用户要求生成图片、生图或画图,以及修改图片、参考图创作或蒙版编辑时使用。通过 Code Mode 调用 tsgw_generate_image 或 tsgw_edit_image,根据草稿或成稿选择模型与参数,再按用户意图保存、发送、展示或继续编辑。
3
+ description: 当用户要求生成图片、生图或画图,以及修改图片、参考图创作或蒙版编辑时使用。通过 `codemode` 工具调用 tsgw_generate_image 或 tsgw_edit_image,根据草稿或成稿选择模型与参数,再按用户意图保存、发送、展示或继续编辑。
4
4
  license: MIT
5
- compatibility: 需要 Pi 1.2+、Code Mode、pi-tsgw 图片工具及可用的 tsgw 图片模型。
5
+ compatibility: 需要 Pi 1.2+、`codemode` 工具、pi-tsgw 图片工具及可用的 tsgw 图片模型。
6
6
  ---
7
7
 
8
8
  # 图片生成与编辑
9
9
 
10
10
  ## 选择工具和模型
11
11
 
12
- - 从文字创建图片:在 Code Mode 中调用 `tools.tsgw_generate_image()`,填写 `prompt`。
13
- - 根据一张或多张图片修改、参考创作:在 Code Mode 中调用 `tools.tsgw_edit_image()`,填写 `prompt` 和 `images`;局部修改可增加 `mask`。
12
+ - 从文字创建图片:在 `codemode` 工具的脚本中调用 `tools.tsgw_generate_image()`,填写 `prompt`。
13
+ - 根据一张或多张图片修改、参考创作:在 `codemode` 工具的脚本中调用 `tools.tsgw_edit_image()`,填写 `prompt` 和 `images`;局部修改可增加 `mask`。
14
14
  - **草稿、构图探索、速度优先**:选择 `gpt-image-2.5-flare`,质量可用 `low`。
15
15
  - **正式成图、精细修改、质量优先**:选择 `gpt-image-2.5-sunburst`,这是工具的默认模型;质量按需求从 `auto` 或 `high` 起选。
16
16
 
17
17
  按用户任务选择模型和参数。`prompt` 写清主体、构图、风格、尺寸意图,以及需要呈现或保留的文字与细节;编辑时区分“修改什么”和“保留什么”。
18
18
 
19
- ## 通过 Code Mode 调用
19
+ ## 通过 `codemode` 工具调用
20
20
 
21
- 生成和编辑统一通过 `codemode` 执行 `tools.tsgw_generate_image()` 或 `tools.tsgw_edit_image()`,不要直接发起图片工具调用。检查状态和返回文件后,**按用户意图处理图片,不强制预览或展示**。Code Mode 不可用时说明调用条件不足,不改用直接调用或擅自修改配置。
21
+ 生成和编辑统一通过 `codemode` 工具执行脚本,调用 `tools.tsgw_generate_image()` 或 `tools.tsgw_edit_image()`,不要直接发起图片工具调用。检查状态和返回文件后,**按用户意图处理图片,不强制预览或展示**。`codemode` 工具不可用时说明调用条件不足,不改用直接调用或擅自修改配置。
22
22
 
23
- 已实测的路径是 Code Mode 生成后读图并展示;该验证未覆盖编辑或直接调用。这里规定的是技能调用方式,不代表直接调用必然失败,也不代表此前未发出调用的底层原因已修复。
23
+ 已实测的路径是通过 `codemode` 工具生成后读图并展示;该验证未覆盖编辑或直接调用。这里规定的是技能调用方式,不代表直接调用必然失败,也不代表此前未发出调用的底层原因已修复。
24
24
 
25
25
  - 读取技能或说“现在生成”不算执行。收到生成任务后,应实际调用工具并检查结果;没有工具结果,不得声称已生成。
26
- - 图片工具有 `outputSchema`,Code Mode 内嵌调用返回结构化状态和文件列表。保存、发送或继续编辑可以直接使用返回文件,无需先 `read` 或 `image()`;需要在对话中展示时,才读取文件并显式执行 `image(block)`。`text(result)` 仅报告状态和路径,不等于展示、发送或最终存储已完成;不要打印图片 base64。
27
- - 工具本身直接调用时会返回图片块,但本技能使用 Code Mode 的结构化返回与文件处理流程;不要把内嵌调用等同于已向对话输出图片。
26
+ - 图片工具有 `outputSchema`,`codemode` 工具内嵌调用返回结构化状态和文件列表。保存、发送或继续编辑可以直接使用返回文件,无需先 `read` 或 `image()`;需要在对话中展示时,才读取文件并显式执行 `image(block)`。`text(result)` 仅报告状态和路径,不等于展示、发送或最终存储已完成;不要打印图片 base64。
27
+ - 工具本身直接调用时会返回图片块,但本技能使用 `codemode` 工具的结构化返回与文件处理流程;不要把内嵌调用等同于已向对话输出图片。
28
28
 
29
- 完整生成示例(一次请求,默认 Sunburst):默认只返回文件;**任务需要在对话中展示时,将 `display` 改为 `true`**。若已有生成结果,只处理已有文件,不要重新运行生图调用。
29
+ 完整生成示例(一次请求,默认 Sunburst):将下方 JavaScript 作为 `code` 参数传给 `codemode` 工具。默认只返回文件;**任务需要在对话中展示时,将 `display` 改为 `true`**。若已有生成结果,只处理已有文件,不要重新运行生图调用。
30
30
 
31
31
  ```js
32
32
  // @options: {"timeout_ms": 660000, "max_output_tokens": 2000}
@@ -83,9 +83,9 @@ text({ generated: true, imagesEmitted: displayed, fileCount: result.files.length
83
83
 
84
84
  后续读取、展示、保存或发送失败,与图片生成失败分开报告;保留已生成文件,只处理失败的后续步骤,不重新生图。
85
85
 
86
- ## Code Mode 参数示例
86
+ ## `codemode` 工具内的参数示例
87
87
 
88
- 以下是传给 Code Mode 中相应 `tools.*` 调用的参数,不是直接工具调用指令,也不要逐个执行。
88
+ 以下是传给 `codemode` 工具脚本中相应 `tools.*` 调用的参数,不是直接工具调用指令,也不要逐个执行。
89
89
 
90
90
  `tools.tsgw_generate_image()` 的最简参数:
91
91
 
@@ -106,7 +106,7 @@ text({ generated: true, imagesEmitted: displayed, fileCount: result.files.length
106
106
  }
107
107
  ```
108
108
 
109
- 在上述 Code Mode 脚本中,将生成调用替换为 `tools.tsgw_edit_image()` 并传入以下参数即可编辑本地图片;蒙版对应第一张原图。沿用状态检查,再按用户意图处理返回文件;仅需展示时使用读图和 `image(block)` 步骤。**这是编辑契约示例,本次 Code Mode 实测未覆盖编辑。**
109
+ 在传给 `codemode` 工具的上述脚本中,将生成调用替换为 `tools.tsgw_edit_image()` 并传入以下参数即可编辑本地图片;蒙版对应第一张原图。沿用状态检查,再按用户意图处理返回文件;仅需展示时使用读图和 `image(block)` 步骤。**这是编辑契约示例,本次通过 `codemode` 工具的实测未覆盖编辑。**
110
110
 
111
111
  ```json
112
112
  {
@@ -136,13 +136,13 @@ text({ generated: true, imagesEmitted: displayed, fileCount: result.files.length
136
136
  | `partial_images` | `0` | 流式请求中希望收到的过程图数量,`0–3` |
137
137
  | `safety_identifier` | 省略 | 应用需要时提供稳定的匿名用户标识,最多 128 字符 |
138
138
  | `user` | 省略 | 上游旧用户标识字段;新接入使用 `safety_identifier` |
139
- | `timeout_ms` | `600000` | 单次调用等待时间,单位毫秒;可按任务覆盖。通过 codemode 包装调用时,脚本截止应留余量,例如默认请求配 `660000` |
139
+ | `timeout_ms` | `600000` | 单次调用等待时间,单位毫秒;可按任务覆盖。通过 `codemode` 工具调用时,脚本截止应留余量,例如默认请求配 `660000` |
140
140
 
141
141
  自定义尺寸:宽高都是 16 的倍数,单边至多 3840,长短边比例至多 3,总像素为 655360–8294400;超过 3686400 像素属于上游实验范围。
142
142
 
143
143
  ## 超时、安全与结果
144
144
 
145
- - 生成可能耗时数分钟。工具请求默认 `600000ms`;Code Mode 示例用 `660000ms` 为调用、读图和输出留余量。延长请求的 `timeout_ms` 时,脚本截止也要相应留余量;脚本超时可能无法进入示例的 catch,仍应核对已有结果而不是再次生图。
145
+ - 生成可能耗时数分钟。工具请求默认 `600000ms`;`codemode` 工具的示例脚本用 `660000ms` 为调用、读图和输出留余量。延长请求的 `timeout_ms` 时,脚本截止也要相应留余量;脚本超时可能无法进入示例的 catch,仍应核对已有结果而不是再次生图。
146
146
  - 请求失败、取消或超时不代表上游未处理或未计费;不自动重试或换模型。费用显示为 0 表示尚未映射准确价格,不表示免费。
147
147
  - `requestStatus: succeeded`、`phase: complete` 和返回文件是生成完成的依据。生成成功不代表展示、发送或指定位置的保存也成功;只有任务要求的后续操作实际完成,才能作相应声明。没有展示要求时,不把未展示视为失败。
148
148
  - 实际格式及尺寸以工具返回的 `files[].mimeType/width/height` 为准,不把请求的 `size` 直接当作最终尺寸。`read` 预览可能缩放或转码;继续编辑时使用原始文件的 `images[].path`,不要把预览当作原图。