pi-tsgw 1.5.0 → 1.5.2

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
@@ -4,6 +4,8 @@
4
4
 
5
5
  ## 安装
6
6
 
7
+ 需要 Pi 1.2.0 或以上稳定版。
8
+
7
9
  ```bash
8
10
  pi install npm:pi-tsgw
9
11
  ```
@@ -23,7 +25,7 @@ pi install npm:pi-tsgw
23
25
  ```
24
26
 
25
27
  将占位地址替换为实际网关地址,通过 `/login` 选择 `tsgw` 配置密钥,然后执行 `/reload`。
26
- 使用 `/tsgw` 查看目录状态,`/tsgw-refresh` 强制刷新。图片与分类能力需要 Pi 1.2+。
28
+ 使用 `/tsgw` 查看目录状态,`/tsgw-refresh` 强制刷新。
27
29
 
28
30
  `/insagent` 显式安装标准子代理:覆盖当前定义,删除已退出清单的 `tsgw-*.md`,在代理目录的 `settings.json` 中启用 Agent 并停用 Pi Web 内置代理,最后自动重载当前会话;其他自定义代理和无关设置保留。
29
31
 
@@ -2,8 +2,12 @@ import type { Api, ClassifierContext, Model, Usage } from "@earendil-works/pi-ai
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { isPlainObject, PayloadWriter } from "#tsgw/models/_tools";
4
4
  import { openaiThinking } from "#tsgw/models/vendors/openai";
5
+ import { minimaxThinking } from "#tsgw/models/vendors/minimax";
5
6
  import { DELEGATION_KINDS, resolveDelegationKeys, type DelegationCandidate } from "./policy.ts";
7
+ import { chatFailure, type SelectionFailure } from "./failure.ts";
6
8
 
9
+ export const CHAT_SELECTION_IDS = ["gpt-6-luna", "deepseek-flash", "MiniMax-M3.1-Flash"] as const;
10
+ type ChatSelectionId = (typeof CHAT_SELECTION_IDS)[number];
7
11
  interface ChatSelectionOptions {
8
12
  models: readonly Model<Api>[];
9
13
  signal: AbortSignal;
@@ -13,20 +17,21 @@ interface ChatSelectionOptions {
13
17
  }
14
18
 
15
19
  /**
16
- * 创建前选型的单次聊天通道,不改变原生 classify,也不把 Luna 注册为分类模型。
17
- * 复用宿主认证与 Responses 适配;只发送原分类材料,不携带会话历史、本地工具或搜索。
20
+ * 创建前选型的单次聊天通道,不改变原生 classify,也不将聊天执行器注册为分类模型。
21
+ * 复用宿主认证与各模型原有协议;只发送原分类材料,不携带会话历史、本地工具或搜索。
18
22
  */
19
- export async function selectWithLuna(
23
+ export async function selectWithChat(
20
24
  registry: ExtensionContext["modelRegistry"],
21
25
  context: ClassifierContext,
22
26
  candidates: readonly DelegationCandidate[],
27
+ modelId: ChatSelectionId,
23
28
  options: ChatSelectionOptions,
24
- ): Promise<{ selected: DelegationCandidate; kind: string; model: string } | undefined> {
29
+ ): Promise<{ selected: DelegationCandidate; kind: string; model: string } | { failure: SelectionFailure } | undefined> {
25
30
  const { signal } = options;
26
31
  signal.throwIfAborted();
27
32
  if (typeof registry.streamSimple !== "function") return undefined;
28
33
  // 分类执行器不受子代理输出候选的 scope 限制,但必须尊重宿主可用目录和用户过滤。
29
- const model = options.models.find(entry => entry.provider === "tsgw" && entry.id === "gpt-6-luna" &&
34
+ const model = options.models.find(entry => entry.provider === "tsgw" && entry.id === modelId &&
30
35
  (entry.type === undefined || entry.type === "chat") && entry.input.includes("text"));
31
36
  if (!model) return undefined;
32
37
  // 即使计时器尚未获得执行机会,目录查询耗尽总预算后也不能再发出付费请求。
@@ -46,39 +51,49 @@ export async function selectWithLuna(
46
51
  if (!isPlainObject(payload)) return payload;
47
52
  // 只复用厂商文本策略,不经过会注入 web_search 的公共调度。
48
53
  const writer = new PayloadWriter(payload);
49
- openaiThinking["gpt-6-luna"](writer, {
54
+ const operation = {
50
55
  provider: model.provider, modelId: model.id, api: model.api,
51
- thinkingLevel: "low", tsSearchMode: "cached",
52
- });
53
- // Responses 的格式约束位于 text.format;保留厂商设置的 verbosity。
54
- const text = writer.get("text");
55
- writer.set("text", {
56
- ...(isPlainObject(text) ? text : {}),
57
- format: {
58
- type: "json_schema", name: "delegation_selection", strict: true,
59
- schema: {
60
- type: "object",
61
- properties: {
62
- kind: { type: "string", enum: [...DELEGATION_KINDS] },
63
- selection: { type: "string", enum: [...candidates.map(candidate => candidate.key), "unresolved"] },
56
+ thinkingLevel: "low" as const, tsSearchMode: "cached" as const,
57
+ };
58
+ if (modelId === "MiniMax-M3.1-Flash") {
59
+ minimaxThinking[modelId](writer, operation);
60
+ // 沿用 Anthropic Messages;不假定其支持 Responses 的 text.format。
61
+ // JSON 由提示约束并在响应入口严格校验,与其他通道使用相同硬规则。
62
+ } else {
63
+ if (modelId === "gpt-6-luna") openaiThinking[modelId](writer, operation);
64
+ const text = writer.get("text");
65
+ writer.set("text", {
66
+ ...(isPlainObject(text) ? text : {}),
67
+ format: {
68
+ type: "json_schema", name: "delegation_selection", strict: true,
69
+ schema: {
70
+ type: "object",
71
+ properties: {
72
+ kind: { type: "string", enum: [...DELEGATION_KINDS] },
73
+ selection: { type: "string", enum: [...candidates.map(candidate => candidate.key), "unresolved"] },
74
+ },
75
+ required: ["kind", "selection"], additionalProperties: false,
64
76
  },
65
- required: ["kind", "selection"], additionalProperties: false,
66
77
  },
67
- },
68
- });
78
+ });
79
+ }
69
80
  return writer.result();
70
81
  },
71
82
  }).result();
72
83
  options.onUsage(result.usage);
73
84
  signal.throwIfAborted();
74
- if (result.stopReason !== "stop" || result.content.some(part => part.type === "toolCall")) return undefined;
85
+ if (result.stopReason === "error" || result.stopReason === "aborted") return { failure: chatFailure(result.errorMessage) };
86
+ const invalid: { failure: SelectionFailure } = {
87
+ failure: { failureKind: "invalid_result", reason: "聊天选型结果无效、未决或不符合固定审阅规则。" },
88
+ };
89
+ if (result.stopReason !== "stop" || result.content.some(part => part.type === "toolCall")) return invalid;
75
90
  const text = result.content.flatMap(part => part.type === "text" ? [part.text] : []).join("");
76
91
  try {
77
92
  const answer: unknown = JSON.parse(text);
78
- if (!isPlainObject(answer) || Object.keys(answer).length !== 2 || typeof answer.kind !== "string") return undefined;
93
+ if (!isPlainObject(answer) || Object.keys(answer).length !== 2 || typeof answer.kind !== "string") return invalid;
79
94
  const selected = resolveDelegationKeys(answer.kind, answer.selection, candidates);
80
- return selected ? { selected, kind: answer.kind, model: modelName } : undefined;
95
+ return selected ? { selected, kind: answer.kind, model: modelName } : invalid;
81
96
  } catch {
82
- return undefined;
97
+ return invalid;
83
98
  }
84
99
  }
@@ -4,21 +4,22 @@ export type DelegationFailureKind =
4
4
  | "invalid_response" | "unsupported" | "unknown" | "invalid_input" | "unavailable"
5
5
  | "invalid_result" | "model_unavailable";
6
6
 
7
- interface ClassifierFailure {
7
+ export interface SelectionFailure {
8
8
  failureKind: DelegationFailureKind;
9
9
  reason: string;
10
+ statusCode?: number;
10
11
  }
11
12
 
12
13
  /** 只识别 adapter 的安全类别,不把任意 errorMessage 当作可信展示文本。 */
13
- export function classifierFailure(message: string | undefined, aborted = false): ClassifierFailure {
14
+ export function classifierFailure(message: string | undefined, aborted = false): SelectionFailure {
14
15
  if (aborted) return { failureKind: "cancelled", reason: "分类请求已取消。" };
15
16
  if (message === "分类请求超时。") return { failureKind: "timeout", reason: message };
16
17
  const status = /^分类请求(?:认证失败|被上游限流|失败)(HTTP ([45]\d{2}))。$/.exec(message ?? "")?.[1];
17
18
  if (status) {
18
19
  if (status === "401" || status === "403")
19
- return { failureKind: "authentication", reason: `分类请求认证失败(HTTP ${status})。` };
20
- if (status === "429") return { failureKind: "rate_limit", reason: "分类请求被上游限流(HTTP 429)。" };
21
- return { failureKind: "http", reason: `分类请求失败(HTTP ${status})。` };
20
+ return { failureKind: "authentication", reason: `分类请求认证失败(HTTP ${status})。`, statusCode: Number(status) };
21
+ if (status === "429") return { failureKind: "rate_limit", reason: "分类请求被上游限流(HTTP 429)。", statusCode: 429 };
22
+ return { failureKind: "http", reason: `分类请求失败(HTTP ${status})。`, statusCode: Number(status) };
22
23
  }
23
24
  switch (message) {
24
25
  case "分类请求缺少有效认证信息。":
@@ -36,6 +37,23 @@ export function classifierFailure(message: string | undefined, aborted = false):
36
37
  }
37
38
  }
38
39
 
40
+ /** SDK 错误仅提取 HTTP 状态码;不回显可能含凭据、请求或上游正文的 message。 */
41
+ export function chatFailure(message: string | undefined): SelectionFailure {
42
+ // Responses 使用宿主格式“tsgw API error (状态码):”,Anthropic 保留 SDK 数字前缀。
43
+ const match = /^(?:(?:HTTP\s+)?([45]\d{2})\b|tsgw API error \(([45]\d{2})\):)/i.exec(message ?? "");
44
+ const status = match?.[1] ?? match?.[2];
45
+ if (status) {
46
+ const statusCode = Number(status);
47
+ const failureKind = statusCode === 401 || statusCode === 403 ? "authentication" : statusCode === 429 ? "rate_limit" : "http";
48
+ return { failureKind, reason: `聊天选型请求失败(HTTP ${statusCode})。`, statusCode };
49
+ }
50
+ if (/^(?:request timed out\.?|request timeout\.?)$/i.test(message ?? ""))
51
+ return { failureKind: "timeout", reason: "聊天选型请求超时。" };
52
+ if (/^connection error\.?$/i.test(message ?? ""))
53
+ return { failureKind: "network", reason: "聊天选型连接失败。" };
54
+ return { failureKind: "unknown", reason: "聊天选型请求失败(原因未明)。" };
55
+ }
56
+
39
57
  export function failureGuidance(kind: DelegationFailureKind | undefined): string {
40
58
  if (kind === "cancelled") return "本次未创建子代理。";
41
59
  return "本次未创建子代理。请按以下选型指导处理,不重试自动选型。";
@@ -9,7 +9,7 @@ import {
9
9
  type DelegationCandidate,
10
10
  } from "./policy.ts";
11
11
  import { failureGuidance, type DelegationFailureKind } from "./failure.ts";
12
- import { raceSelection } from "./selection-race.ts";
12
+ import { raceSelection, type SelectionError } from "./selection-race.ts";
13
13
 
14
14
  const TIMEOUT_MS = 15_000;
15
15
  const MAX_CONTEXT_BYTES = 28 * 1024;
@@ -21,6 +21,8 @@ type Decision = {
21
21
  status: "selected" | "blocked";
22
22
  classifier?: string;
23
23
  chatModel?: string;
24
+ chatModels?: string[];
25
+ selectionErrors?: SelectionError[];
24
26
  selectionSource?: { type: "classifier" | "chat"; model: string };
25
27
  model?: string;
26
28
  kind?: string;
@@ -37,10 +39,16 @@ interface Attempt {
37
39
  candidates?: DelegationCandidate[];
38
40
  }
39
41
 
42
+ function selectionErrorsText(decision: Decision): string {
43
+ return decision.selectionErrors?.length ? "\n选型通道报错(返回前已收到):\n" +
44
+ decision.selectionErrors.map(error => `- ${error.source.model}:${error.reason}`).join("\n") : "";
45
+ }
46
+
40
47
  function failureText(decision: Decision): string {
41
48
  return `TSGW ${decision.reason ?? "分类选型未完成。"}${failureGuidance(decision.failureKind)}` +
42
49
  `\n选型来源:无(未完成有效选型${decision.classifier ? `;已尝试分类模型 ${decision.classifier}` : ""}` +
43
- `${decision.chatModel ? `;已尝试聊天模型 ${decision.chatModel}` : ""})。` +
50
+ `${decision.chatModels?.length ? `;已尝试聊天模型 ${decision.chatModels.join("、")}` : ""})。` +
51
+ selectionErrorsText(decision) +
44
52
  (decision.selectionGuide ? `\n\n${decision.selectionGuide}` : "");
45
53
  }
46
54
 
@@ -135,10 +143,12 @@ export function registerDelegation(pi: ExtensionAPI): void {
135
143
  ...(typeof input.run_in_background === "boolean" ? { run_in_background: input.run_in_background } : {}),
136
144
  };
137
145
  let classifierId: string | undefined;
138
- let chatModelId: string | undefined;
146
+ const chatModelIds: string[] = [];
147
+ const selectionErrors: SelectionError[] = [];
139
148
  const failure = (reason: string, kind: DelegationFailureKind): Decision => {
140
149
  return { ...blocked(reason, kind), ...(classifierId ? { classifier: classifierId } : {}),
141
- ...(chatModelId ? { chatModel: chatModelId } : {}),
150
+ ...(chatModelIds.length ? { chatModel: chatModelIds[0], chatModels: [...chatModelIds] } : {}),
151
+ ...(selectionErrors.length ? { selectionErrors: [...selectionErrors] } : {}),
142
152
  ...(kind === "cancelled" ? {} : { selectionGuide: buildDelegationGuide(attempt.candidates) }) };
143
153
  };
144
154
  try {
@@ -163,9 +173,10 @@ export function registerDelegation(pi: ExtensionAPI): void {
163
173
  models, signal, deadlineMs: started + TIMEOUT_MS,
164
174
  onStart: source => {
165
175
  if (source.type === "classifier") classifierId = source.model;
166
- else chatModelId = source.model;
176
+ else chatModelIds.push(source.model);
167
177
  },
168
178
  onUsage: usage => { attempt.usage = addUsage(attempt.usage, usage); },
179
+ onError: error => { selectionErrors.push(error); },
169
180
  }), signal);
170
181
  if ("failure" in result) return failure(result.failure.reason, result.failure.failureKind);
171
182
  const { selected, kind, source } = result.winner;
@@ -175,7 +186,9 @@ export function registerDelegation(pi: ExtensionAPI): void {
175
186
  if (!current.some(candidate => candidate.model === selected.model))
176
187
  return failure("选定模型或思考档位已不在当前可用候选中。", "model_unavailable");
177
188
  return { status: "selected", classifier: classifierId, model: selected.model,
178
- selectionSource: source, ...(chatModelId ? { chatModel: chatModelId } : {}),
189
+ selectionSource: source,
190
+ ...(chatModelIds.length ? { chatModel: chatModelIds[0], chatModels: [...chatModelIds] } : {}),
191
+ ...(selectionErrors.length ? { selectionErrors: [...selectionErrors] } : {}),
179
192
  ...(kind ? { kind } : {}), durationMs: Date.now() - started };
180
193
  } catch {
181
194
  if (cancellation.aborted) return failure("分类选型已取消(调用或会话已结束)。", "cancelled");
@@ -217,10 +230,8 @@ export function registerDelegation(pi: ExtensionAPI): void {
217
230
  if (decision.status === "selected") {
218
231
  const sourceType = decision.selectionSource?.type === "chat" ? "聊天模型" : "分类模型";
219
232
  summary = `TSGW 创建前选型:${decision.model};选型来源:${sourceType} ${decision.selectionSource?.model}`;
220
- summary += "(并行竞速,采用首个有效结果)";
221
- summary += `;${event.isError ? "原 Agent 调用未成功。" : "已交由原 Agent 执行。"}`;
222
- if (decision.classifier && decision.chatModel)
223
- summary += " 并行用量仅累计汇总前已报告部分;取消不保证远端停止处理或计费。";
233
+ if (event.isError) summary += ";Agent 调用未成功。";
234
+ summary += selectionErrorsText(decision);
224
235
  } else {
225
236
  summary = failureText(decision);
226
237
  }
@@ -42,7 +42,7 @@ export interface DelegationCandidate {
42
42
 
43
43
  function candidateInstructions(row: (typeof DELEGATION_KNOWLEDGE)[number]): string {
44
44
  return `模型:${row.id},思考档位:${row.level}。` +
45
- `任务适用性:${row.suitability}。思考投入与成本特征(不承诺实测延迟):${row.effort}。` +
45
+ `任务适用性:${row.suitability}。思考投入与成本特征:${row.effort}。` +
46
46
  `参考成本:输入 ${row.inputPrice} 美元/百万 tokens,输出 ${row.outputPrice} 美元/百万 tokens。` +
47
47
  row.note;
48
48
  }
@@ -1,16 +1,15 @@
1
1
  import type { Api, ClassifierContext, Model, Usage } from "@earendil-works/pi-ai";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { selectWithLuna } from "./chat-selection.ts";
4
- import { classifierFailure, type DelegationFailureKind } from "./failure.ts";
3
+ import { CHAT_SELECTION_IDS, selectWithChat } from "./chat-selection.ts";
4
+ import { chatFailure, classifierFailure, type SelectionFailure } from "./failure.ts";
5
5
  import { chooseClassifier, resolveDelegationChoice, type DelegationCandidate } from "./policy.ts";
6
6
 
7
7
  export interface SelectionSource {
8
8
  type: "classifier" | "chat";
9
9
  model: string;
10
10
  }
11
- interface SelectionFailure {
12
- reason: string;
13
- failureKind: DelegationFailureKind;
11
+ export interface SelectionError extends SelectionFailure {
12
+ source: SelectionSource;
14
13
  }
15
14
  interface RaceOptions {
16
15
  models: readonly Model<Api>[];
@@ -18,6 +17,7 @@ interface RaceOptions {
18
17
  deadlineMs: number;
19
18
  onStart: (source: SelectionSource) => void;
20
19
  onUsage: (usage: Usage) => void;
20
+ onError: (error: SelectionError) => void;
21
21
  }
22
22
  interface SelectionWinner {
23
23
  selected: DelegationCandidate;
@@ -25,7 +25,7 @@ interface SelectionWinner {
25
25
  source: SelectionSource;
26
26
  }
27
27
 
28
- /** 两路各发一次;失败或非法结果不是胜者,不为等待取消确认延长选型。 */
28
+ /** 四路各发一次;失败或非法结果不是胜者,不为等待取消确认延长选型。 */
29
29
  export async function raceSelection(
30
30
  registry: ExtensionContext["modelRegistry"],
31
31
  context: ClassifierContext,
@@ -39,6 +39,7 @@ export async function raceSelection(
39
39
  reason: "选型结果无效、未决或不符合固定审阅规则。", failureKind: "invalid_result",
40
40
  };
41
41
  const native = async (): Promise<SelectionWinner> => {
42
+ let source: SelectionSource | undefined;
42
43
  try {
43
44
  signal.throwIfAborted();
44
45
  if (typeof registry.classify !== "function") {
@@ -57,7 +58,7 @@ export async function raceSelection(
57
58
  nativeFailure = { reason: "选型预算已耗尽。", failureKind: "timeout" };
58
59
  throw new Error("选型预算已耗尽。");
59
60
  }
60
- const source: SelectionSource = { type: "classifier", model: `${classifier.provider}/${classifier.id}` };
61
+ source = { type: "classifier", model: `${classifier.provider}/${classifier.id}` };
61
62
  options.onStart(source);
62
63
  const result = await registry.classify(classifier, context, { signal, timeoutMs: remaining, maxRetries: 0 });
63
64
  if (result.usage) options.onUsage(result.usage);
@@ -76,25 +77,39 @@ export async function raceSelection(
76
77
  return { selected, kind: answer?.type === "choice" ? answer.choice : undefined, source };
77
78
  } catch {
78
79
  nativeFailure ??= { reason: "分类请求失败(原因未明)。", failureKind: "unknown" };
80
+ if (source && !signal.aborted) options.onError({ source, ...nativeFailure });
79
81
  throw new Error("原生选型通道未提供有效结果。");
80
82
  }
81
83
  };
82
- const chat = async (): Promise<SelectionWinner> => {
83
- const result = await selectWithLuna(registry, context, candidates, {
84
- ...options, signal, onStart: model => options.onStart({ type: "chat", model }),
85
- });
86
- if (!result) throw new Error("聊天选型通道未提供有效结果。");
87
- return { selected: result.selected, kind: result.kind, source: { type: "chat", model: result.model } };
84
+ const chat = async (modelId: (typeof CHAT_SELECTION_IDS)[number]): Promise<SelectionWinner> => {
85
+ let source: SelectionSource | undefined;
86
+ let failure: SelectionFailure | undefined;
87
+ try {
88
+ const result = await selectWithChat(registry, context, candidates, modelId, {
89
+ ...options, signal, onStart: model => {
90
+ source = { type: "chat", model };
91
+ options.onStart(source);
92
+ },
93
+ });
94
+ if (result && !("failure" in result))
95
+ return { selected: result.selected, kind: result.kind, source: { type: "chat", model: result.model } };
96
+ if (result) failure = result.failure;
97
+ } catch (error) {
98
+ failure = chatFailure(error instanceof Error ? error.message : undefined);
99
+ }
100
+ // 未发起的通道和获胜/整体取消导致的中止不作为通道报错。
101
+ if (source && !signal.aborted) options.onError({ source, ...(failure ?? invalid) });
102
+ throw new Error("聊天选型通道未提供有效结果。");
88
103
  };
89
104
  try {
90
- const winner = await Promise.any([native(), chat()]);
105
+ const winner = await Promise.any([native(), ...CHAT_SELECTION_IDS.map(chat)]);
91
106
  options.signal.throwIfAborted();
92
107
  return { winner };
93
108
  } catch {
94
109
  options.signal.throwIfAborted();
95
110
  return { failure: nativeFailure ?? invalid };
96
111
  } finally {
97
- // 只取消两条选型请求,不中断获胜后的目录复核;不保证远端停止处理或计费。
112
+ // 只取消选型请求,不中断获胜后的目录复核;不保证远端停止处理或计费。
98
113
  finished.abort();
99
114
  }
100
115
  }
@@ -9,32 +9,32 @@ const IMAGE_MODELS = ["gpt-image-2.5-sunburst", "gpt-image-2.5-flare"] as const;
9
9
  const optional = <T extends import("typebox").TSchema>(schema: T) => Type.Optional(Type.Union([schema, Type.Null()]));
10
10
 
11
11
  export const imageSourceSchema = Type.Union([
12
- Type.Object({ path: Type.String({ minLength: 1, description: "Pi 主机本地普通文件;相对路径以会话 cwd 为基准。直接读取原始字节并外传,不经过内置 read 的审批或缩放。" }) }, { additionalProperties: false }),
12
+ Type.Object({ path: Type.String({ minLength: 1, description: "Pi 主机本地普通文件;相对路径以会话 cwd 为基准。" }) }, { additionalProperties: false }),
13
13
  Type.Object({ image_url: Type.String({ minLength: 1, description: "无用户名密码的 HTTP(S) URL,或 PNG/JPEG/WebP 的 base64 data URI。本工具不下载远程 URL。" }) }, { additionalProperties: false }),
14
14
  Type.Object({ file_id: Type.String({ minLength: 1, description: "上游已有图片的文件 ID。" }) }, { additionalProperties: false }),
15
15
  ], { description: "恰好一个来源:path、image_url 或 file_id;不可混用。" });
16
16
 
17
17
  // Type.Enum 仅输出 enum;Moonshot 拒绝联合分支中缺 type 的枚举,使用宿主显式 string 表达。
18
18
  const common = {
19
- prompt: Type.String({ minLength: 1, maxLength: 32_000, description: "图片生成或编辑要求,最多32000字符。" }),
19
+ prompt: Type.String({ minLength: 1, maxLength: 32_000, description: "图片生成或编辑要求。" }),
20
20
  model: Type.Optional(StringEnum(IMAGE_MODELS, { description: "默认 gpt-image-2.5-sunburst,适合成稿;AI 草稿任务可选 gpt-image-2.5-flare,常配 quality=low。" })),
21
21
  quality: optional(StringEnum(["auto", "low", "medium", "high", "xhigh", "max"], { description: "质量,默认 auto;选择 Flare 不会自动改为 low。" })),
22
22
  size: optional(Type.String({ description: "默认 auto;也可宽x高,均为16倍数、边≤3840、宽高比≤3、像素655360..8294400。" })),
23
23
  background: optional(StringEnum(["auto", "opaque", "transparent"], { description: "背景,默认 auto。透明背景需 PNG/WebP。" })),
24
24
  output_format: optional(StringEnum(["png", "jpeg", "webp"], { description: "输出格式,默认 png;原始字节不转码。" })),
25
25
  output_compression: optional(Type.Integer({ minimum: 0, maximum: 100, description: "仅用于 JPEG/WebP 的压缩质量;省略采用上游默认100。" })),
26
- n: optional(Type.Integer({ minimum: 1, maximum: 10, description: "返回图片数量;默认1,最多10。" })),
26
+ n: optional(Type.Integer({ minimum: 1, maximum: 10, description: "返回图片数量,默认1。" })),
27
27
  moderation: optional(StringEnum(["auto", "low"], { description: "审核强度,默认 auto。" })),
28
- stream: optional(Type.Boolean({ description: "默认 false;支持解析流式响应,不承诺界面渐进预览。" })),
28
+ stream: optional(Type.Boolean({ description: "是否使用流式响应,默认 false;仅返回最终图片。" })),
29
29
  partial_images: optional(Type.Integer({ minimum: 0, maximum: 3, description: "仅 stream=true 时使用;默认0。最终仅返回完成图。" })),
30
- safety_identifier: optional(Type.String({ maxLength: 128, description: "可选安全标识,最长128字符。" })),
30
+ safety_identifier: optional(Type.String({ maxLength: 128, description: "可选安全标识。" })),
31
31
  user: optional(Type.String({ description: "已废弃的上游 user 参数,仅为兼容保留。" })),
32
- timeout_ms: Type.Optional(Type.Number({ minimum: 0, maximum: MAX_IMAGE_TIMEOUT_MS, description: "调用超时毫秒数;默认600000,可显式缩短或延长,最多2147483647。取消不保证上游停止处理或计费。" })),
32
+ timeout_ms: Type.Optional(Type.Number({ minimum: 0, maximum: MAX_IMAGE_TIMEOUT_MS, description: "调用超时毫秒数,默认600000。" })),
33
33
  };
34
34
 
35
35
  export const generateImageSchema = Type.Object(common, { additionalProperties: false });
36
36
  export const editImageSchema = Type.Object({ ...common,
37
- images: Type.Array(imageSourceSchema, { minItems: 1, maxItems: 16, description: "1..16张参考图。每个本地/内联图片小于50 MB,合计最多100 MB;mask另算张数,但计入字节预算。" }),
37
+ images: Type.Array(imageSourceSchema, { minItems: 1, maxItems: 16, description: "每个本地/内联图片小于50 MB,含 mask 合计最多100 MB。" }),
38
38
  mask: optional(imageSourceSchema),
39
39
  }, { additionalProperties: false });
40
40
 
@@ -23,10 +23,8 @@ export function registerImageTools(pi: ExtensionAPI): void {
23
23
  name: operation === "generate" ? "tsgw_generate_image" : "tsgw_edit_image",
24
24
  label: operation === "generate" ? "TSGW 生成图片" : "TSGW 编辑图片",
25
25
  description: (operation === "generate" ? "根据 prompt 生成图片,只需填写 prompt。" : "根据 prompt 和 images 编辑图片,可选 mask;蒙版对应第一张参考图。") +
26
- "默认 Sunburst 用于成稿;AI 草稿任务可选 Flare(通常配 quality=low),不必为普通任务指定型号。" +
27
- "默认 quality/size/background/moderation=auto、output_format=png、n=1、stream=false、partial_images=0、超时600000毫秒。" +
28
- (operation === "edit" ? "本地图片以 Pi 进程操作系统权限直接只读原始字节并外传,不经过内置 read 审批,不是沙箱;仅普通文件,每个小于50 MB、含蒙版合计最多100 MB。不下载远程 URL;远程蒙版的格式与尺寸交上游验证。" : "") +
29
- "返回实际图片块与唯一临时文件路径,不需 codemode 或 image()。请求可能计费;不自动重试或换模型,失败、取消或超时都不保证停止上游处理或未计费。",
26
+ (operation === "edit" ? "仅使用获授权的图片;本地原文件会外传。" : "") +
27
+ "返回图片与临时文件路径。失败、取消或超时后不自动重试或换模型。",
30
28
  parameters: operation === "generate" ? generateImageSchema : editImageSchema,
31
29
  outputSchema: imageToolResultSchema,
32
30
  exposure: "direct",
@@ -59,13 +57,13 @@ export function registerImageTools(pi: ExtensionAPI): void {
59
57
  usage = response.usage;
60
58
  if (response.tsgwUsage?.status === "unaggregated") {
61
59
  usage = undefined;
62
- details.usage_note = "多图流式用量归属未明确,逐事件报告未相加,也未计入会话总量;不是免费。";
60
+ details.usage_note = "多图流式用量未汇总,未计入会话总量。";
63
61
  details.usage_reports = response.tsgwUsage.reports.map(report => ({ ...report }));
64
62
  }
65
63
  if (response.stopReason !== "stop") {
66
64
  details.requestStatus = "unknown";
67
65
  throw new ImageToolFileError(response.stopReason === "aborted" ? "aborted" : "request-failed",
68
- response.stopReason === "aborted" ? "图片调用已取消或超时;无法保证上游停止处理或未计费,请勿自动重试。" : "图片调用未成功;无法确认上游是否处理或计费,请勿自动重试。请检查宿主模型认证与网关;未切换模型。");
66
+ response.stopReason === "aborted" ? "图片调用已取消或超时,结果未知;请勿自动重试。" : "图片调用未成功,结果未知;请勿自动重试,请检查宿主模型认证与网关。");
69
67
  }
70
68
  details.requestStatus = "succeeded";
71
69
  details.phase = "output";
@@ -80,10 +78,10 @@ export function registerImageTools(pi: ExtensionAPI): void {
80
78
  } else {
81
79
  // 不转发供应商异常、输入 URL、base64 或文件系统原始异常。
82
80
  details.error = caller.aborted
83
- ? { code: "aborted", message: details.requestStatus === "not-started" ? "图片工具已取消,尚未调用上游。" : "图片调用已取消;上游结果未知,不保证停止处理或计费,请勿自动重试。" }
81
+ ? { code: "aborted", message: details.requestStatus === "not-started" ? "图片工具已取消,尚未调用上游。" : "图片调用已取消,结果未知;请勿自动重试。" }
84
82
  : details.phase === "validate" || details.phase === "input"
85
83
  ? { code: "invalid-parameters", message: "图片工具参数无效;请检查字段白名单、数值范围、图片来源与参数组合。未调用上游。" }
86
- : { code: "request-unknown", message: "图片调用异常,无法确认上游结果或是否计费;未自动重试,请检查宿主与网关。" };
84
+ : { code: "request-unknown", message: "图片调用异常,结果未知;未自动重试,请检查宿主与网关。" };
87
85
  }
88
86
  }
89
87
  return {
@@ -7,7 +7,7 @@ import { readImageResponse } from "./stream-response.ts";
7
7
 
8
8
  const DEFAULT_TIMEOUT_MS = 600_000;
9
9
  const MAX_TIMEOUT_MS = 2_147_483_647;
10
- const UNCERTAIN = "未自动重试;此结果不代表上游未计费。";
10
+ const FAILURE_NOTE = "未自动重试。";
11
11
  function mergeHeaders(apiKey: string | undefined, ...sources: (ProviderHeaders | undefined)[]): Headers {
12
12
  const headers = new Headers({ "Content-Type": "application/json" });
13
13
  if (apiKey?.trim()) headers.set("Authorization", `Bearer ${apiKey}`);
@@ -104,9 +104,9 @@ export const generateImages: ProviderImages["generateImages"] = async (model, co
104
104
  if (!controller.signal.aborted && Date.now() >= deadline) { timedOut = true; controller.abort(); }
105
105
  if (controller.signal.aborted) {
106
106
  result.stopReason = timedOut ? "error" : "aborted";
107
- result.errorMessage = `${timedOut ? "图片请求超时。" : "图片请求已取消。"}${UNCERTAIN}`;
107
+ result.errorMessage = `${timedOut ? "图片请求超时。" : "图片请求已取消。"}${FAILURE_NOTE}`;
108
108
  } else {
109
- result.errorMessage = `${error instanceof ImageFailure ? error.message : "图片请求失败,请检查认证、网络及请求钩子。"}${UNCERTAIN}`;
109
+ result.errorMessage = `${error instanceof ImageFailure ? error.message : "图片请求失败,请检查认证、网络及请求钩子。"}${FAILURE_NOTE}`;
110
110
  }
111
111
  return result;
112
112
  } finally {
@@ -12,7 +12,7 @@ export function supportsImageModels(version: string): boolean {
12
12
  return supportsStablePi12(version);
13
13
  }
14
14
 
15
- /** 分类目录与桥接沿用 Pi 1.2 稳定版基线,不提高聊天最低 peer。 */
15
+ /** 分类目录与桥接沿用插件的 Pi 1.2 稳定版基线。 */
16
16
  export function supportsClassifierModels(version: string): boolean {
17
17
  return supportsStablePi12(version);
18
18
  }
@@ -58,7 +58,7 @@ export function registerSearchProxyTool(pi: ExtensionAPI, options: SearchProxyOp
58
58
  if (!delegate) throw new Error("TSGW 搜索没有可供当前模型使用的代理模型。");
59
59
  const registry = ctx.modelRegistry;
60
60
  if (typeof registry.streamSimple !== "function")
61
- throw new Error("TSGW 代理搜索要求宿主支持 modelRegistry.streamSimple(已在 Pi 1.1.0 上验证)。");
61
+ throw new Error("TSGW 代理搜索需要宿主支持 modelRegistry.streamSimple。");
62
62
  const model = registry.find("tsgw", delegate.modelId);
63
63
  if (!model || builtinSearchSupport(model.id, model.api) !== delegate.kind)
64
64
  throw new Error("TSGW 搜索代理模型已不再以受支持的协议注册。");
@@ -12,16 +12,15 @@ export function registerUploadTool(pi: ExtensionAPI, dependencies: Pick<UploadDe
12
12
  name: "upload_local_file",
13
13
  label: "上传本地文件",
14
14
  description: "通过已连接的 ts_oht MCP,将明确授权的本地文件从 Pi 主机上传到私有 S3。" +
15
- "读取操作系统允许访问的文件;这不是浏览器上传,也不是沙箱。文件不超过 32 MiB 时使用一次 PUT;更大的文件使用 3 个并发工作单元进行流式分片上传。" +
16
- "返回持有者即可使用的临时下载 URL(默认有效期 24 小时,inline 展示;HTML 可能执行)。存储内容约 7 天后清理。" +
15
+ "返回持有者即可使用的临时下载 URL(inline 展示 HTML 可能执行)。存储内容约 7 天后清理。" +
17
16
  "不会自动重试。失败或结果未知时,请保留 key 和 resume 恢复凭条;仅在明确要求恢复时使用返回的凭条," +
18
17
  "切勿盲目发起全新上传。恢复前,请停止其他客户端对同一文件的上传。不要记录预签名 URL。",
19
18
  parameters: Type.Object({
20
19
  path: Type.String({ minLength: 1, description: "插件运行环境中的路径;相对路径以会话 cwd 为基准。仅支持普通文件。" }),
21
20
  contentType: Type.Optional(Type.String({ minLength: 3, maxLength: 127, pattern: CONTENT_TYPE_PATTERN.source, description: "不带 charset 的 MIME 类型;默认根据扩展名推断,无法推断时使用 application/octet-stream。" })),
22
21
  expiresIn: Type.Optional(Type.Integer({ minimum: 1, maximum: 604800, description: "下载 URL 的有效期,单位为秒;默认 86400。不会延长存储保留时间。" })),
23
- disposition: Type.Optional(Type.Union([Type.Literal("inline"), Type.Literal("attachment")])),
24
- resume: Type.Optional(Type.String({ minLength: 1, maxLength: 8192, pattern: RESUME_PATTERN.source, description: "上次失败调用返回的原样恢复凭条;恢复前会检查旧对象。不含凭据。" })),
22
+ disposition: Type.Optional(Type.Union([Type.Literal("inline"), Type.Literal("attachment")], { description: "默认 inline;attachment 用于下载。" })),
23
+ resume: Type.Optional(Type.String({ minLength: 1, maxLength: 8192, pattern: RESUME_PATTERN.source, description: "原样使用上次失败调用返回的恢复凭条。" })),
25
24
  }),
26
25
  outputSchema: Type.Object({
27
26
  uploaded: Type.Union([Type.Boolean(), Type.Null()]),
@@ -41,7 +40,7 @@ export function registerUploadTool(pi: ExtensionAPI, dependencies: Pick<UploadDe
41
40
  ...dependencies,
42
41
  async call(name, args, operationSignal) {
43
42
  if (typeof ctx.executeTool !== "function" || !Array.isArray(ctx.tools))
44
- throw new UploadError("unsupported-host", "此上传工具需要支持 ctx.executeTool 的 Pi 主机(已使用 1.1.0 测试)。");
43
+ throw new UploadError("unsupported-host", "上传工具需要宿主支持 ctx.executeTool。");
45
44
  if (![UPLOAD_TOOL, URL_TOOL].includes(name) || !ctx.tools.some(tool => tool.name === name))
46
45
  throw new UploadError("mcp-unavailable", "所需的 ts_oht 工具尚未连接或不可调用。请在主机中启用它;本工具未创建连接。");
47
46
  const outcome = await ctx.executeTool(name, args, { signal: operationSignal });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tsgw",
3
- "version": "1.5.0",
3
+ "version": "1.5.2",
4
4
  "description": "面向 TOSSP AIH gateway 的 Pi 扩展:按厂商维护聊天与图片模型目录及思考策略,支持四种聊天协议、图片生成与编辑工具,以及原生 System One 分类模型。",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -32,13 +32,13 @@
32
32
  "test:upload:live": "tsc -p tsconfig.test.json && node scripts/prepare-test-runtime.mjs && node dist/extensions/upload/live.test.js"
33
33
  },
34
34
  "peerDependencies": {
35
- "@earendil-works/pi-coding-agent": ">=0.82.0",
35
+ "@earendil-works/pi-coding-agent": ">=1.2.0",
36
36
  "typebox": "*"
37
37
  },
38
38
  "devDependencies": {
39
- "@earendil-works/pi-ai": "~1.2.0",
40
- "@earendil-works/pi-coding-agent": "~1.2.0",
41
- "@earendil-works/pi-mcp": "~1.2.0",
39
+ "@earendil-works/pi-ai": "1.4.0",
40
+ "@earendil-works/pi-coding-agent": "1.4.0",
41
+ "@earendil-works/pi-mcp": "1.4.0",
42
42
  "typebox": "^1.3.37",
43
43
  "typescript": "^7.0.2"
44
44
  }
@@ -18,133 +18,50 @@ compatibility: 需要 Pi 1.2+、`codemode` 工具、pi-tsgw 图片工具及可
18
18
 
19
19
  ## 通过 `codemode` 工具调用
20
20
 
21
- 生成和编辑统一通过 `codemode` 工具执行脚本,调用 `tools.tsgw_generate_image()` 或 `tools.tsgw_edit_image()`,不要直接发起图片工具调用。检查状态和返回文件后,**按用户意图处理图片,不强制预览或展示**。`codemode` 工具不可用时说明调用条件不足,不改用直接调用或擅自修改配置。
21
+ 生成和编辑都通过 `codemode` 工具脚本调用 `tools.tsgw_generate_image()` 或 `tools.tsgw_edit_image()`;不要直接调用图片工具。检查调用状态与返回文件,按用户意图保存、发送、继续编辑或展示,不强制预览。保存、发送或编辑直接使用返回文件;仅需在对话中展示时,才用 `tools.read()` 读取并调用 `image(block)`。`text(result)` 只报告状态和路径,不代表后续交付已完成;不要打印图片 base64。工具不可用时说明条件不足,不改用其他调用方式或擅自修改配置。
22
22
 
23
- 已实测的路径是通过 `codemode` 工具生成后读图并展示;该验证未覆盖编辑或直接调用。这里规定的是技能调用方式,不代表直接调用必然失败,也不代表此前未发出调用的底层原因已修复。
23
+ 收到生成任务后实际调用并检查结果;没有工具结果不得声称已生成。生成完成以 `requestStatus: succeeded`、`phase: complete` 和返回文件为依据;展示、保存或发送等后续步骤分别核实,失败时保留已有文件,只处理失败步骤,不重新生图。读取、保存与外传受图片工具及宿主权限控制,不绕过限制。
24
24
 
25
- - 读取技能或说“现在生成”不算执行。收到生成任务后,应实际调用工具并检查结果;没有工具结果,不得声称已生成。
26
- - 图片工具有 `outputSchema`,`codemode` 工具内嵌调用返回结构化状态和文件列表。保存、发送或继续编辑可以直接使用返回文件,无需先 `read` 或 `image()`;需要在对话中展示时,才读取文件并显式执行 `image(block)`。`text(result)` 仅报告状态和路径,不等于展示、发送或最终存储已完成;不要打印图片 base64。
27
- - 工具本身直接调用时会返回图片块,但本技能使用 `codemode` 工具的结构化返回与文件处理流程;不要把内嵌调用等同于已向对话输出图片。
28
-
29
- 完整生成示例(一次请求,默认 Sunburst):将下方 JavaScript 作为 `code` 参数传给 `codemode` 工具。默认只返回文件;**任务需要在对话中展示时,将 `display` 改为 `true`**。若已有生成结果,只处理已有文件,不要重新运行生图调用。
25
+ 生成示例(默认参数):
30
26
 
31
27
  ```js
32
28
  // @options: {"timeout_ms": 660000, "max_output_tokens": 2000}
33
- const display = false; // 按用户意图设置;仅需要在对话中展示时改为 true。
34
- let result;
35
- try {
36
- result = await tools.tsgw_generate_image({
37
- prompt: "横版中国水墨山水画,远山、薄雾、一叶扁舟,不要文字、题款、印章或水印。",
38
- size: "1536x1024"
39
- });
40
- } catch {
41
- text({ error: "图片调用未正常返回;请检查已有工具结果。上游是否已处理或计费可能未知,不自动重试或换模型。" });
42
- return;
43
- }
29
+ const result = await tools.tsgw_generate_image({
30
+ prompt: "横版水墨山水,远山薄雾,一叶扁舟,不要文字"
31
+ });
44
32
  text(result);
45
-
46
- if (result?.requestStatus !== "succeeded" || result.phase !== "complete") {
47
- text({ error: result?.requestStatus === "succeeded"
48
- ? "上游已成功,但结果处理或保存未完成;不要重新生成。"
49
- : "未确认生成完成;按工具结果说明状态,不自动重试。" });
50
- return;
51
- }
52
- if (!Array.isArray(result.files) || result.files.length === 0) {
53
- text({ error: "工具报告完成但没有返回文件,无法继续交付;不要重新生成。" });
54
- return;
55
- }
56
-
57
- if (!display) return; // 返回文件可用于保存、发送或继续编辑,不必读图预览。
58
- let displayed = 0;
59
- for (const file of result.files) {
60
- try {
61
- const block = await tools.read({ path: file.path });
62
- if (block && typeof block === "object" && block.type === "image") {
63
- image(block);
64
- displayed++;
65
- } else {
66
- text({ error: "文件已生成,但未能读取为图片", path: file.path });
67
- }
68
- } catch {
69
- text({ error: "文件已生成,但读取或展示失败;保留此路径,不要重新生成", path: file.path });
70
- }
71
- }
72
- text({ generated: true, imagesEmitted: displayed, fileCount: result.files.length });
33
+ // 核对状态与 files;再按用户意图处理返回文件。
73
34
  ```
74
35
 
75
36
  ### 按意图处理返回文件
76
37
 
77
38
  | 用户意图 | 后续操作 |
78
39
  | --- | --- |
79
- | 展示图片 | 对返回文件执行 `tools.read()`,再 `image(block)`;`imagesEmitted` 只统计已输出的图片块 |
80
- | 保存图片 | 使用原始文件保存到用户要求的位置;工具返回的是临时路径,不等于已完成指定位置的持久保存 |
81
- | 发送或上传 | 将文件交给相应的可用工具,在已有授权范围内执行;依据发送或上传结果确认完成 |
82
- | 继续编辑 | 将原始文件路径用于下一次 `images[].path`,不必先读取预览 |
83
-
84
- 后续读取、展示、保存或发送失败,与图片生成失败分开报告;保留已生成文件,只处理失败的后续步骤,不重新生图。
40
+ | 展示图片 | 对返回文件执行 `tools.read()`,再 `image(block)` |
41
+ | 保存图片 | 将原始文件保存到用户要求的位置;临时路径不等于已持久保存到指定位置 |
42
+ | 发送或上传 | 在已有授权范围内交给相应工具,并依据结果确认完成 |
43
+ | 继续编辑 | 将原始文件路径用于下一次 `images[].path`,无需先读预览 |
85
44
 
86
- ## `codemode` 工具内的参数示例
45
+ ## 编辑参考图
87
46
 
88
- 以下是传给 `codemode` 工具脚本中相应 `tools.*` 调用的参数,不是直接工具调用指令,也不要逐个执行。
47
+ 编辑时传入修改要求与 `images`;局部编辑可加 `mask`:
89
48
 
90
- `tools.tsgw_generate_image()` 的最简参数:
91
-
92
- ```json
93
- {
94
- "prompt": "横版水墨山水,远山薄雾,一叶扁舟,不要文字"
95
- }
49
+ ```js
50
+ // @options: {"timeout_ms": 660000, "max_output_tokens": 2000}
51
+ const result = await tools.tsgw_edit_image({
52
+ prompt: "把蒙版区域改为盛开的荷花,保留原图其余构图和水墨风格",
53
+ images: [{ path: "source.png" }],
54
+ mask: { path: "mask.png" }
55
+ });
56
+ text(result);
96
57
  ```
97
58
 
98
- 快速草稿:
59
+ `images` 保留参考图顺序,每个来源选择 `path`、`image_url`、`file_id` 其中之一。`path` 是 Pi 运行主机上的文件路径,相对路径以会话工作目录为准;`image_url` 接受 HTTP(S) URL 或图片 data URI,`file_id` 使用上游已有文件 ID。蒙版可省略;提供时,与第一张原图保持格式及尺寸一致,并带透明通道,用透明区域指示编辑范围。继续编辑应使用原始文件而非可能缩放或转码的预览。
99
60
 
100
- ```json
101
- {
102
- "prompt": "极简咖啡馆标志草稿,咖啡杯与山峰结合,无文字",
103
- "model": "gpt-image-2.5-flare",
104
- "quality": "low",
105
- "size": "1024x1024"
106
- }
107
- ```
61
+ ## 参数选择与结果边界
108
62
 
109
- 在传给 `codemode` 工具的上述脚本中,将生成调用替换为 `tools.tsgw_edit_image()` 并传入以下参数即可编辑本地图片;蒙版对应第一张原图。沿用状态检查,再按用户意图处理返回文件;仅需展示时使用读图和 `image(block)` 步骤。**这是编辑契约示例,本次通过 `codemode` 工具的实测未覆盖编辑。**
110
-
111
- ```json
112
- {
113
- "prompt": "把蒙版标出的区域改为盛开的荷花,保留原图其余构图和水墨风格",
114
- "images": [{ "path": "source.png" }],
115
- "mask": { "path": "mask.png" }
116
- }
117
- ```
63
+ 只填写任务需要覆盖的参数。按画面需要选择 `size`、`background`、`output_format`、图片数量等;透明背景使用支持透明的 PNG 或 WebP。尺寸限制及所有默认值、上下限以图片工具字段说明为准。
118
64
 
119
- `images` 保留参考图顺序,支持 1–16 张;每个来源选择 `path`、`image_url`、`file_id` 其中之一。`path` 是 Pi 运行主机上的文件路径,相对路径以会话工作目录为准;`image_url` 接受 HTTP(S) URL 或图片 data URI,`file_id` 使用上游已有文件 ID。蒙版可省略;提供时,与第一张原图保持格式及尺寸一致,并带透明通道,用透明区域指示编辑范围。
120
-
121
- ## 可选参数
122
-
123
- 生成和编辑共用下列可选参数,省略时使用默认值;只填写任务需要覆盖的项。
124
-
125
- | 参数 | 默认值 | 用途与取值 |
126
- | --- | --- | --- |
127
- | `model` | `gpt-image-2.5-sunburst` | 草稿用 Flare,正式成图用 Sunburst |
128
- | `quality` | `auto` | `low`、`medium`、`high`、`xhigh`、`max`、`auto`;`xhigh`/`max` 用于确实需要额外细节的任务 |
129
- | `size` | `auto` | `宽x高`;例如 `1024x1024`、`1536x1024`、`1024x1536`、`2048x1152`、`3840x2160` |
130
- | `background` | `auto` | `auto`、`opaque`、`transparent`;透明输出搭配 PNG 或 WebP |
131
- | `output_format` | `png` | `png`、`jpeg`、`webp` |
132
- | `output_compression` | JPEG/WebP 使用 `100` | `0–100` 整数,用于 JPEG/WebP |
133
- | `n` | `1` | 一次请求生成 `1–10` 张图片 |
134
- | `moderation` | `auto` | `auto` 或 `low` |
135
- | `stream` | `false` | 是否使用上游流式响应;工具处理完成后返回最终图片 |
136
- | `partial_images` | `0` | 流式请求中希望收到的过程图数量,`0–3` |
137
- | `safety_identifier` | 省略 | 应用需要时提供稳定的匿名用户标识,最多 128 字符 |
138
- | `user` | 省略 | 上游旧用户标识字段;新接入使用 `safety_identifier` |
139
- | `timeout_ms` | `600000` | 单次调用等待时间,单位毫秒;可按任务覆盖。通过 `codemode` 工具调用时,脚本截止应留余量,例如默认请求配 `660000` |
140
-
141
- 自定义尺寸:宽高都是 16 的倍数,单边至多 3840,长短边比例至多 3,总像素为 655360–8294400;超过 3686400 像素属于上游实验范围。
142
-
143
- ## 超时、安全与结果
144
-
145
- - 生成可能耗时数分钟。工具请求默认 `600000ms`;`codemode` 工具的示例脚本用 `660000ms` 为调用、读图和输出留余量。延长请求的 `timeout_ms` 时,脚本截止也要相应留余量;脚本超时可能无法进入示例的 catch,仍应核对已有结果而不是再次生图。
146
- - 请求失败、取消或超时不代表上游未处理或未计费;不自动重试或换模型。费用显示为 0 表示尚未映射准确价格,不表示免费。
147
- - `requestStatus: succeeded`、`phase: complete` 和返回文件是生成完成的依据。生成成功不代表展示、发送或指定位置的保存也成功;只有任务要求的后续操作实际完成,才能作相应声明。没有展示要求时,不把未展示视为失败。
148
- - 实际格式及尺寸以工具返回的 `files[].mimeType/width/height` 为准,不把请求的 `size` 直接当作最终尺寸。`read` 预览可能缩放或转码;继续编辑时使用原始文件的 `images[].path`,不要把预览当作原图。
149
- - 本地/内联图片每个小于 50 MB,参考图与蒙版合计不超过 100 MB。原文件读取和外传由图片工具及宿主权限控制,不等于内置 `read` 的审批或沙箱;不绕过宿主对读图或工具的限制。
65
+ - 生成耗时较长时,脚本截止时间应比请求的 `timeout_ms` 留有处理余量;超时或结果未知时先核对已有结果,不自动重试或换模型。
66
+ - 以工具返回的 `files[].mimeType/width/height` 判断实际格式和尺寸,不将请求的 `size` 当作最终结果。生成成功不代表展示、发送或指定位置保存也成功;只有任务要求的后续操作实际完成,才能相应声明。没有展示要求时,不把未展示视为失败。
150
67
  - 若结果带 `usage_note`,按其说明报告计量状态;多图流式的逐事件用量可能无法确定汇总值。
@@ -44,7 +44,7 @@ text(entries.map(model => ({
44
44
  ## 判断和报告
45
45
 
46
46
  - 分别报告文本回复、工具往返是否通过,并列出实际使用的型号和思考档位;宿主若报告了不同的实际档位,应明确说明,不算原指定组合通过。
47
- - 失败、取消或超时就报告实际阶段和可公开的错误,不主动刷新目录、重试、换档位或换模型。用户另行指定下一次测试时再执行;取消不保证远端停止处理或计费。
47
+ - 失败、取消或超时就报告实际阶段和可公开的错误,不主动刷新目录、重试、换档位或换模型。用户另行指定下一次测试时再执行。
48
48
  - 未创建子代理、仍在执行或结果未知时如实说明,不把它们写成模型已通过或端点已被证明不可用。
49
49
  - 一次通过只证明该型号、档位在本次最小任务中可用,不推广为全部模态、长期稳定性或复杂工程能力已验收。
50
50
  - 验证候选模型不等于已经切换主会话或修改默认配置;切换按用户授权另行执行。
@@ -54,22 +54,9 @@ metadata:
54
54
  - 对其他重复笔记,先提取仍有价值的差异内容,合并写入主记录
55
55
  - 可自主修正标签、更新或合并记录、归档或删除无价值重复记录及恢复误归档记录;方向或范围不同的外部知识应独立且互相关联,不得错误合并。
56
56
 
57
- ### 标签 = 关键词提取
57
+ ### 标签
58
58
 
59
- 核心原则:**多标签 = 多维度关联**
60
-
61
- - 从笔记内容中提取多个关键词作为标签
62
- - 用词保持一致:避免 "#Linux" 和 "#linux" 混用
63
- - 实践中自然生长:不需要预设复杂标签体系
64
-
65
- ### 层级结构
66
-
67
- ```
68
- 技术类: #windows #linux #debian #python
69
- 运维类: #运维/晨云 #运维/川大 #运维信息
70
- 技巧类: #技巧/windows #技巧/linux #技巧/ntp
71
- 业务类: #晨云 #川大 #水利
72
- ```
59
+ 从笔记内容提取多个关键词,形成多维度关联;标签用词保持一致(如统一使用 `#Linux`,不混用 `#linux`)。按实际内容自然使用普通标签或层级标签,例如 `#python`、`#技巧/linux`、`#运维/晨云`,不预设复杂体系。命中且复用时校验标签,补齐内容关键词并修正不一致用词。
73
60
 
74
61
  ### 查询策略 (MUST)
75
62
 
@@ -79,14 +66,6 @@ metadata:
79
66
  - 对明确的外部调研任务,命中记录不得自动停止外部调研;按本次问题开展当前外部补充或事实核验。已有记忆可决定检索范围和强度,但不能替代事实核验;核验强度应与知识的风险和时效相关,无须每次无差别从零开始。
80
67
  - 命中条目时检查其来源、适用边界、状态和时效信息,并为后续比较保留稳定条目 ID 或链接。
81
68
 
82
- ### 标签校验
83
-
84
- **命中且复用时校验**:
85
-
86
- - 搜索命中的笔记,检查内容关键词是否反映在标签中
87
- - 如果笔记提到 "dify" 但没有 "#dify" 标签 → 添加
88
- - 如果笔记是关于 Linux 但用了根级 "linux" 而不是 "#技巧/linux" → 修正
89
-
90
69
  ### 维护、清理与验证 (MUST)
91
70
 
92
71
  - **持续维护授权包含删除**:与当前任务或知识维护直接相关的创建、单条或批量更新、标签调整、合并、归档、恢复及删除(含永久删除),模型可自主判断执行,无须逐条确认;不强制先标记 `#待删除`、归档或备份。
@@ -158,20 +137,10 @@ metadata:
158
137
  ## 分流与维护示例
159
138
 
160
139
  ```text
161
- 核验官方文档:软件 X v1.2 支持条件 Y
162
- → 维护 Blinko 主条目,记录来源、版本、核验时间和适用边界。
163
-
164
- 发现某台设备实际运行版本或服务配置
165
- → 回写该项目正式资料,按需更新本机 ctx,不写入 Blinko。
166
-
167
- 归纳用户个人沟通风格/行为倾向
168
- → 属原生 user-profile 机制;明确执行规范归用户级规则,不写入 Blinko。
169
-
170
- 确认重复条目含少量独有信息
171
- → 合入主记录并回读验证,再自主归档或删除重复条目,回报 ID 与理由。
172
-
173
- 用户要求每天提醒
174
- → 属定时任务意图,核对具体范围后处理,不借普通条目维护权限自行建任务。
140
+ 外部调研或通用知识 → 按 MUST 规则检索、核验并沉淀 Blinko。
141
+ 项目现场/个人倾向/敏感内容 → 分别归项目资料/user-profile/受保护位置,不写入 Blinko。
142
+ 发现重复条目 → 合并独有价值、验证主记录,再按授权决定归档或删除并回报。
143
+ 用户明确要求定时任务 → 核对范围后处理;不从普通条目维护授权推定可操作定时任务。
175
144
  ```
176
145
 
177
146
  ## 参考资料
@@ -0,0 +1,47 @@
1
+ ---
2
+ name: tsgw-synology-dav
3
+ description: 查询或管理群晖日历、日程及联系人时使用,通过 tsn__* MCP 工具读取真实数据,并在明确授权后创建、修改或删除。
4
+ license: MIT
5
+ compatibility: 需要宿主已连接并获准使用提供 tsn__* 工具的 MCP 服务及已有 DAV 账号配置。
6
+ ---
7
+
8
+ # 群晖日历与联系人
9
+
10
+ 涉及用户日程、联系人或空闲时间时,优先查询真实数据,不凭记忆猜测。本技能只指导宿主现有 MCP 调用,不新增 DAV 客户端、认证存储或连接配置。
11
+
12
+ ## 工具发现与连接
13
+
14
+ - 先通过当前宿主的工具发现入口查找 `tsn__calendar_list`、`tsn__calendar_event_list`、`tsn__contacts_search` 等实际工具,再读取其参数 schema。工具可能带服务前缀;以发现的完整名称调用,不猜测名称或参数,不把描述中提及的其他工具视为已经可用。
15
+ - 在 Pi codemode 中可用 `searchTools('tsn__calendar_list', { limit: 3 })` 发现工具,必要时用 `describeTool()` 查看参数,再调用实际返回的 `tools.<完整工具名>(...)`。不得搜索或输出凭据。
16
+ - 提示账号未连接时,可调用 `dav_reconnect` 使用已有配置重连;已知目标账号时显式指定,避免无故重连全部账号。重连后重新查询目标目录或数据;连接成功、发现目录成功和读取真实数据是不同证据。
17
+ - 认证失败立即停止,不反复尝试,不索取或读取保存的密码,也不改用 `dav_connect` 绕过失败。配置缺失、权限不足或工具不可用时明确报告阻塞,不自行安装、登录或修改 MCP 配置。
18
+ - 同时检查工具错误标记及文本结果;不能仅因调用正常返回就断言成功,未连接或业务错误也可能出现在文本中。
19
+
20
+ ## 日历查询
21
+
22
+ 1. 先调用 `calendar_list`,确认实际账号、日历名称和路径。不要硬编码个人目录,也不要将 calendar home 当作具体日历路径。
23
+ 2. 未指定时区时使用 `Asia/Shanghai`;根据当前真实日期将“今天、明天、下周”等转换为具体起止日期。“下周”默认目标周周一 `00:00` 至再下一周周一 `00:00`,即目标周周一至周日;若上下文有其他含义,先澄清。调用时用带时区偏移的 ISO 8601 时间,并在结果中说明具体范围及所用时区。
24
+ 3. 调用 `calendar_event_list`,必传明确的 `start`、`end`。整天查询从当天 `00:00:00+08:00` 到次日 `00:00:00+08:00`,避免用 `23:59:59` 漏掉小数秒;不臆测服务端边界是否包含,必要时核对返回的边界事件。指定日历时使用发现的账号和路径。当前实现中,传 `account` 却省略 `calendar` 只查询该账号的第一个日历,与工具描述的范围不一致;需要覆盖多个日历时,按发现结果逐个显式传 `account` 和 `calendar`,分别检查结果,不依赖省略参数的聚合查询(它可能跳过部分失败)。不把默认主日历当作全部日历。
25
+ 4. 先读取列表摘要,仅在完成任务确有必要且存在相应工具时再取单项详情。注意全天、跨天、重复事件及其例外;不要未经核验把重复规则当作已展开的每次发生记录,也不要把局部列表当作完整空闲证明。
26
+ 5. 查询为空时说明查了哪些日历及哪个时间范围。寻找近期安排或做只读实测时,可合理扩大到前后数周,明确区分各次结果;用户只问某一天时不为证明服务器有数据而无故扩查。不得把“当天无事件”说成“服务器没有数据”。
27
+
28
+ ## 联系人查询
29
+
30
+ - 已有姓名、邮箱或电话线索时优先 `contacts_search`;确实需要浏览列表或做一次只读能力验证时用 `contacts_list`。需要单项详情时,先确认实际存在的工具及目标 UID。
31
+ - 当前搜索会读取地址簿后在本地按姓名、邮箱、电话、组织或备注做不区分大小写的子串筛选,不是廉价的服务端索引查询。避免连续试探大量关键词或反复拉取整本地址簿;先利用已返回的结果,只有线索实质变化才再查询。
32
+ - 账号与地址簿参数按实际 schema 选择;默认主地址簿不代表所有地址簿。查不到时说明查询线索和范围,不断言联系人不存在于整个服务器。
33
+ - 同名或多个匹配结果时,只展示区分目标所需的少量字段;涉及写入则先请用户确认,不能自行挑选。
34
+
35
+ ## 写入授权与核验
36
+
37
+ - 查询可直接执行;创建、修改和删除日程或联系人,必须有用户针对该动作的明确授权。“实测工具”“检查连接”或本技能本身都不是业务写入授权,不为验收创建再删除测试数据。
38
+ - 操作前查询现状,确认账号、具体日历或地址簿、目标 UID、时间与时区,以及用户要求变更的字段。存在重名、重复事件、重复联系人、时间歧义或周期事件单次/整组范围不明时,先询问,不误改其他数据。
39
+ - 新建前在相关时间范围或联系人线索内核对是否已有目标。修改只传明确要求改变的字段;省略字段与空字符串可能含义不同,不用猜测值填满参数。删除前精确定位目标,不仅凭名称执行,也不依赖跨目录模糊搜索。
40
+ - 周期事件、待办或日志类能力,仅在用户确有需求、实际工具支持且获得对应授权时使用;不把日程工具的能力推定为其他类型也支持。
41
+ - 写入返回后,在授权范围内按实际可用查询工具回读核对。请求失败或结果不明时先查询,避免重复创建或重复执行;未确认结果就报告“未确认”,不得声称成功或自动补偿删除。
42
+
43
+ ## 隐私与结果汇报
44
+
45
+ - 只展示完成任务所需的信息,不倾倒整本通讯录或日程。只读实测优先输出查询范围、数量或成功/失败摘要,不展示无关正文;使用 codemode 时在当前调用内处理并精简输出,不把原始工具结果整段 `text()` 回显。
46
+ - 不把凭据、联系人正文或日程正文写入 `store`、日志、额外文件、代码仓库或记忆条目;也不在示例中固化真实姓名、电话、邮箱、UID 或个人目录。
47
+ - 分开汇报连接、目录发现、真实数据读取和写入结果;列出失败及未验证项。空结果不等于故障,也不证明有数据;只读成功不代表创建、修改、删除或周期处理已经通过验收。