@insmind/cli 1.5.1 → 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.
Files changed (61) hide show
  1. package/dist/bin/agent-worker.js +2 -1
  2. package/dist/bin/insmind-cli.js +12 -7
  3. package/dist/bin/postinstall.js +7 -5
  4. package/dist/src/bootstrap/create-cli.js +26 -17
  5. package/dist/src/bootstrap/create-runtime.js +31 -13
  6. package/dist/src/bootstrap/run-agent-worker.js +2 -1
  7. package/dist/src/bootstrap/validators.js +10 -5
  8. package/dist/src/cli/action-binding.js +14 -0
  9. package/dist/src/cli/agent-commands.js +8 -3
  10. package/dist/src/cli/auth-commands.js +1 -1
  11. package/dist/src/cli/credits-command.js +2 -2
  12. package/dist/src/cli/dam-commands.js +51 -52
  13. package/dist/src/cli/editor-commands.js +13 -15
  14. package/dist/src/cli/errors.js +91 -41
  15. package/dist/src/cli/model-commands.js +6 -4
  16. package/dist/src/cli/presenter.js +13 -10
  17. package/dist/src/cli/task-commands.js +13 -5
  18. package/dist/src/cli/tool-commands.js +9 -3
  19. package/dist/src/features/agent/use-cases.js +11 -5
  20. package/dist/src/features/auth/credential-store.js +2 -2
  21. package/dist/src/features/auth/sso-service.js +3 -2
  22. package/dist/src/features/auth/state.js +2 -0
  23. package/dist/src/features/auth/use-cases.js +30 -34
  24. package/dist/src/features/credits/use-cases.js +2 -0
  25. package/dist/src/features/dam/file-downloader.js +38 -16
  26. package/dist/src/features/dam/object-storage.js +23 -11
  27. package/dist/src/features/dam/operation-executor.js +46 -37
  28. package/dist/src/features/dam/registered-uploader.js +39 -29
  29. package/dist/src/features/dam/storage-upload.js +5 -4
  30. package/dist/src/features/dam/use-cases.js +81 -60
  31. package/dist/src/features/editor/bridge-client.js +6 -6
  32. package/dist/src/features/editor/bridge-process.js +2 -1
  33. package/dist/src/features/editor/session-state.js +6 -4
  34. package/dist/src/features/editor/session.js +26 -8
  35. package/dist/src/features/editor/use-cases.js +10 -3
  36. package/dist/src/features/org/use-cases.js +2 -1
  37. package/dist/src/features/task/agent-background.js +1 -0
  38. package/dist/src/features/task/store.js +2 -0
  39. package/dist/src/features/task/use-cases.js +80 -27
  40. package/dist/src/features/tool/catalog.js +11 -5
  41. package/dist/src/features/tool/dynamic-schema.js +9 -7
  42. package/dist/src/features/tool/mns-catalog-adapter.js +1 -0
  43. package/dist/src/features/tool/tool-api-adapter.js +8 -7
  44. package/dist/src/features/tool/use-cases.js +7 -3
  45. package/dist/src/features/update/update-notification.js +75 -70
  46. package/dist/src/features/update/update-service.js +24 -20
  47. package/dist/src/platform/file-lock.js +36 -9
  48. package/dist/src/platform/interruption.js +13 -0
  49. package/dist/src/platform/json-input.js +12 -9
  50. package/dist/src/platform/local-json-file.js +8 -4
  51. package/dist/src/platform/redact.js +7 -1
  52. package/dist/src/platform/remote-protocol.js +2 -2
  53. package/dist/src/platform/safe-upload-file.js +2 -1
  54. package/dist/src/platform/schema-issues.js +8 -0
  55. package/dist/src/platform/signed-http-transport.js +8 -7
  56. package/dist/src/platform/text-output.js +33 -0
  57. package/dist/src/telemetry/invocation.js +19 -4
  58. package/dist/src/telemetry/process-errors.js +14 -4
  59. package/dist/src/telemetry/sanitize.js +4 -2
  60. package/dist/src/telemetry/sls-sink.js +36 -20
  61. package/package.json +4 -4
@@ -1,4 +1,5 @@
1
- import { createEditorBridgeClient, EditorBridgeUnavailableError } from "./bridge-client.js";
1
+ import { isInterruption } from "../../platform/interruption.js";
2
+ import { createEditorBridgeClient, EditorBridgeError, EditorBridgeUnavailableError } from "./bridge-client.js";
2
3
  import { startEditorBridgeProcess } from "./bridge-process.js";
3
4
  import { toPublicEditorUrl } from "./public-url.js";
4
5
  const DEFAULT_CREATE_URL = new URL("https://www.gaoding.art/editor/canvas?mode=create&type=board");
@@ -14,8 +15,8 @@ export class EditorTargetError extends Error {
14
15
  }
15
16
  export class EditorSessionNotFoundError extends Error {
16
17
  code = "EDITOR_SESSION_NOT_FOUND";
17
- constructor(commandName = "gd-cli") {
18
- super(`当前没有可用的 Editor 会话,请重新执行 ${commandName} editor connect [target]。`);
18
+ constructor(commandName = "gd-cli", cause) {
19
+ super(`当前没有可用的 Editor 会话,请重新执行 ${commandName} editor connect [target]。`, { cause });
19
20
  this.name = "EditorSessionNotFoundError";
20
21
  }
21
22
  }
@@ -49,11 +50,19 @@ export function createEditorSession(dependencies) {
49
50
  ? {}
50
51
  : { stateDirectory: dependencies.stateDirectory }),
51
52
  signal
53
+ }).catch(cause => {
54
+ if (isInterruption(cause, signal))
55
+ throw signal.reason;
56
+ throw new EditorBridgeError("EDITOR_NOT_READY", dependencies.commandName === "insmind-cli" ? "Cannot start the local Editor Bridge." : "无法启动本地 Editor Bridge,请检查本地进程环境后重新连接。", { cause });
52
57
  });
53
58
  const handoffUrl = buildHandoffUrl(targetUrl, state);
54
59
  try {
55
60
  signal.throwIfAborted();
56
- await dependencies.browser.open(handoffUrl);
61
+ await dependencies.browser.open(handoffUrl).catch(cause => {
62
+ if (isInterruption(cause, signal))
63
+ throw signal.reason;
64
+ throw new EditorBridgeError("EDITOR_NOT_READY", dependencies.commandName === "insmind-cli" ? "Cannot open the Editor browser. Check the local browser configuration and reconnect." : "无法打开 Editor 浏览器,请检查浏览器配置后重新连接。", { cause });
65
+ });
57
66
  const client = createClient(state);
58
67
  await waitForPage(client, signal);
59
68
  await client.rpc("preflight", undefined, signal);
@@ -74,10 +83,18 @@ export function createEditorSession(dependencies) {
74
83
  await client.health(signal);
75
84
  }
76
85
  catch (cause) {
77
- signal.throwIfAborted();
86
+ if (isInterruption(cause, signal))
87
+ throw signal.reason;
88
+ await throwUnavailableSession(cause, state);
89
+ }
90
+ try {
91
+ await client.disconnect(signal);
92
+ }
93
+ catch (cause) {
94
+ if (isInterruption(cause, signal))
95
+ throw signal.reason;
78
96
  await throwUnavailableSession(cause, state);
79
97
  }
80
- await client.disconnect(signal);
81
98
  await dependencies.store.removeIfOwned(state.token);
82
99
  return { disconnected: true };
83
100
  },
@@ -90,7 +107,8 @@ export function createEditorSession(dependencies) {
90
107
  return await createClient(state).rpc(method, payload, signal);
91
108
  }
92
109
  catch (cause) {
93
- signal.throwIfAborted();
110
+ if (isInterruption(cause, signal))
111
+ throw signal.reason;
94
112
  await throwUnavailableSession(cause, state);
95
113
  }
96
114
  }
@@ -99,7 +117,7 @@ export function createEditorSession(dependencies) {
99
117
  if (!(cause instanceof EditorBridgeUnavailableError))
100
118
  throw cause;
101
119
  await dependencies.store.removeIfOwned(state.token);
102
- throw new EditorSessionNotFoundError(dependencies.commandName);
120
+ throw new EditorSessionNotFoundError(dependencies.commandName, cause);
103
121
  }
104
122
  async function replaceCurrentSession(signal) {
105
123
  const current = await dependencies.store.read();
@@ -2,6 +2,7 @@ import { mkdtemp, writeFile } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
4
  import { OutputContractError } from "../../bootstrap/validators.js";
5
+ import { LocalFileError } from "../../platform/local-json-file.js";
5
6
  import { toPublicEditorUrl } from "./public-url.js";
6
7
  const PNG_DATA_URL_PREFIX = "data:image/png;base64,";
7
8
  const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
@@ -35,9 +36,15 @@ export function createEditorUseCases(dependencies) {
35
36
  const data = await dependencies.session.rpc("screenshot", undefined, signal);
36
37
  const bytes = decodePngDataUrl(data);
37
38
  signal.throwIfAborted();
38
- const directory = await mkdtemp(join(temporaryDirectory, "gd-cli-editor-"));
39
- const result = { path: join(directory, "screenshot.png") };
40
- await writeFile(result.path, bytes);
39
+ let result;
40
+ try {
41
+ const directory = await mkdtemp(join(temporaryDirectory, "gd-cli-editor-"));
42
+ result = { path: join(directory, "screenshot.png") };
43
+ await writeFile(result.path, bytes);
44
+ }
45
+ catch (cause) {
46
+ throw new LocalFileError(cause, "Editor screenshot");
47
+ }
41
48
  validate.screenshot(result);
42
49
  return result;
43
50
  },
@@ -1,3 +1,4 @@
1
+ import { isInterruption } from "../../platform/interruption.js";
1
2
  import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
2
3
  import { classifyBindOutcome, SsoRequestError } from "../auth/sso-service.js";
3
4
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
@@ -122,7 +123,7 @@ export function createOrgUseCases(dependencies) {
122
123
  };
123
124
  }
124
125
  catch (error) {
125
- if (input.signal.aborted)
126
+ if (isInterruption(error, input.signal))
126
127
  throw input.signal.reason;
127
128
  if (isExpectedAuthorizationFailure(error))
128
129
  return null;
@@ -6,6 +6,7 @@ export class AgentBackgroundError extends Error {
6
6
  super(failure.message);
7
7
  this.failure = failure;
8
8
  this.exitCode = exitCode;
9
+ this.name = "AgentBackgroundError";
9
10
  }
10
11
  }
11
12
  export function createAgentBackgroundLauncher(options) {
@@ -5,6 +5,8 @@ import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
7
7
  export class TaskStoreError extends LocalFileError {
8
+ context;
9
+ constructor(cause) { super(cause); this.name = "TaskStoreError"; }
8
10
  }
9
11
  export const validTaskId = (id) => /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/iu.test(id);
10
12
  export function taskScope(state) {
@@ -1,7 +1,8 @@
1
1
  import { redactSensitiveText } from "../../platform/redact.js";
2
- import { taskScope } from "./store.js";
2
+ import { TaskStoreError, taskScope } from "./store.js";
3
+ import { LocalFileError } from "../../platform/local-json-file.js";
3
4
  export class TaskNotFoundError extends Error {
4
- constructor(message) { super(message); }
5
+ constructor(message) { super(message); this.name = "TaskNotFoundError"; }
5
6
  }
6
7
  // Cached results are private output data, but expiring resource credentials are
7
8
  // removed. Query delivery uses the existing authorization adapter again.
@@ -36,6 +37,15 @@ const LEASE_MS = 15_000;
36
37
  export function createTaskUseCases(dependencies) {
37
38
  const { text, commandName } = dependencies;
38
39
  const telemetry = dependencies.telemetry;
40
+ const warnedTasks = new Set();
41
+ const stage = (name, run) => telemetry ? telemetry.stage(name, run) : run();
42
+ function cacheWarning(id) {
43
+ if (warnedTasks.has(id))
44
+ return;
45
+ warnedTasks.add(id);
46
+ telemetry?.annotate({ warning_codes: ["TASK_CACHE_UNAVAILABLE"] });
47
+ (dependencies.warning ?? dependencies.notice)(text(`任务 ${id} 的本地记录未能保存,task get 可能无法恢复。请保留本次输出,不要重新提交创作。`, `The local record for task ${id} could not be saved; task get may not recover it. Keep this output and do not submit the creation again.`));
48
+ }
39
49
  async function fact(scope, record, name, at) {
40
50
  if (!telemetry || !record.telemetry)
41
51
  return;
@@ -49,19 +59,18 @@ export function createTaskUseCases(dependencies) {
49
59
  const candidate = { ...context, event_name: name, occurred_at_ms: at,
50
60
  record_seq: name === "request_sent" ? 1 : 2 };
51
61
  try {
52
- const updated = await dependencies.store.update(scope, record.task.taskId, stored => {
62
+ const updated = await stage("telemetry.task", () => dependencies.store.update(scope, record.task.taskId, stored => {
53
63
  if (stored.telemetry && !stored.telemetry[name]) {
54
64
  stored.telemetry.context = context;
55
65
  stored.telemetry[name] = candidate;
56
66
  }
57
- });
67
+ }));
58
68
  if (updated.telemetry)
59
69
  record.telemetry = updated.telemetry;
60
70
  }
61
- catch (error) {
71
+ catch {
62
72
  // Business persistence has its own failure path. Keep the already known fact.
63
73
  record.telemetry[name] ??= candidate;
64
- await telemetry.stage("telemetry.task", () => { throw error; }).catch(() => undefined);
65
74
  }
66
75
  await telemetry.emit(record.telemetry[name] ?? candidate);
67
76
  }
@@ -95,7 +104,23 @@ export function createTaskUseCases(dependencies) {
95
104
  ...(dependencies.creationVersion ? { cli_version: dependencies.creationVersion } : {}),
96
105
  ...(input.state.account ? { account_id: input.state.account.id } : {}), organization_id: input.state.organization.id } };
97
106
  }
98
- await dependencies.store.write(scope, record);
107
+ let dispatched = false;
108
+ let durableAcceptance = false;
109
+ function storageContext(error, phase) {
110
+ if (error instanceof TaskStoreError)
111
+ error.context = { cli_task_id: record.task.taskId, phase,
112
+ request_sent: dispatched, accepted: record.progress.accepted === true || !!record.progress.remoteTaskId,
113
+ result_state: record.task.state };
114
+ return error;
115
+ }
116
+ try {
117
+ await stage("task.create", () => dependencies.store.write(scope, record));
118
+ }
119
+ catch (error) {
120
+ record.task.state = "failed";
121
+ telemetry?.annotate({ result_state: "failed" });
122
+ throw storageContext(error, "before_dispatch");
123
+ }
99
124
  input.onUpdate?.(structuredClone(record.task), { ...record.progress });
100
125
  dependencies.notice(text(`任务 ID: ${record.task.taskId};结果未收到时执行 ${commandName} task get ${record.task.taskId}`, `Task ID: ${record.task.taskId}; retrieve missing output with ${commandName} task get ${record.task.taskId}`));
101
126
  let writes = Promise.resolve();
@@ -107,53 +132,73 @@ export function createTaskUseCases(dependencies) {
107
132
  };
108
133
  let lastHeartbeatError = -Infinity;
109
134
  const timer = setInterval(() => {
110
- void save().catch(async (error) => {
111
- const at = dependencies.now().getTime();
112
- if (at - lastHeartbeatError < 60_000)
113
- return;
114
- lastHeartbeatError = at;
115
- await telemetry?.stage("task.heartbeat", () => { throw error; }).catch(() => undefined);
135
+ const report = dependencies.now().getTime() - lastHeartbeatError >= 60_000;
136
+ void (report ? stage("task.heartbeat", save) : save()).catch(() => {
137
+ if (report)
138
+ lastHeartbeatError = dependencies.now().getTime();
116
139
  });
117
140
  }, HEARTBEAT_MS);
118
141
  timer.unref();
119
142
  try {
120
143
  const result = await input.run(async (progress) => {
121
144
  if (progress.dispatchedAt !== undefined) {
145
+ dispatched = true;
122
146
  await fact(scope, record, "request_sent", progress.dispatchedAt);
123
147
  return;
124
148
  }
125
149
  Object.assign(record.progress, progress);
126
150
  if (progress.contextId)
127
151
  record.task.contextId = progress.contextId;
128
- await save();
152
+ try {
153
+ await stage("task.progress", save);
154
+ }
155
+ catch (error) {
156
+ if (!(error instanceof LocalFileError) || !dispatched || (input.executionMode === "async" && !durableAcceptance)) {
157
+ throw storageContext(error, dispatched ? "after_dispatch" : "before_dispatch");
158
+ }
159
+ cacheWarning(record.task.taskId);
160
+ return;
161
+ }
162
+ durableAcceptance ||= record.progress.accepted === true || !!record.progress.remoteTaskId;
129
163
  input.onUpdate?.(structuredClone(record.task), { ...record.progress });
130
164
  });
131
165
  clearInterval(timer);
132
- finish(record, result);
166
+ await stage("task.validate", async () => { finish(record, result); });
133
167
  telemetry?.annotate({ result_state: record.task.state });
134
168
  if (record.task.state === "completed")
135
169
  await fact(scope, record, "result_ready", dependencies.now().getTime());
136
- await save();
170
+ try {
171
+ await stage("task.persist", save);
172
+ }
173
+ catch (error) {
174
+ if (!(error instanceof LocalFileError) || record.task.state !== "completed" || input.executionMode === "async") {
175
+ throw storageContext(error, "final_persist");
176
+ }
177
+ cacheWarning(record.task.taskId);
178
+ }
137
179
  return { task: record.task, result };
138
180
  }
139
181
  catch (error) {
140
182
  clearInterval(timer);
141
183
  if (record.task.state !== "completed") {
142
- record.task.state = record.progress.submissionStarted ? "unknown" : "failed";
143
- record.task.note = record.progress.submissionStarted
184
+ const mayBeRunning = dispatched || record.progress.submissionStarted;
185
+ record.task.state = mayBeRunning ? "unknown" : "failed";
186
+ record.task.note = mayBeRunning
144
187
  ? text("CLI 未取得完整回执或结果;远端可能仍在执行。查询原任务,不自动重新生成。", "The CLI did not receive a complete receipt or result; the service may still be running. Query this task instead of submitting again.")
145
188
  : text("CLI 在提交创作前结束;具体错误见原命令。", "The CLI stopped before submitting the creation. See the original command for the error.");
146
189
  }
147
190
  const detail = dependencies.failureNote?.(error);
148
191
  if (detail)
149
- record.task.note = `${record.task.note} ${redactSensitiveText(detail)}`;
150
- await (telemetry ? telemetry.stage("task.persist", save) : save()).catch(() => undefined);
192
+ record.task.note = [record.task.note, redactSensitiveText(detail)].filter(Boolean).join(" ");
193
+ telemetry?.annotate({ result_state: record.task.state });
194
+ await stage("task.persist", save).catch(() => undefined);
151
195
  throw error;
152
196
  }
153
197
  }
154
198
  return {
155
199
  async track(input) {
156
200
  return (await execute(input, (record, result) => {
201
+ dependencies.validateResult?.(result);
157
202
  record.task.state = "completed";
158
203
  record.task.result = withoutResourceKeys(result);
159
204
  if ("message" in result)
@@ -164,39 +209,47 @@ export function createTaskUseCases(dependencies) {
164
209
  return (await execute({ ...input, executionMode: "async" }, record => { record.progress.detached = true; })).task;
165
210
  },
166
211
  async list({ state, limit, operation }) {
167
- const records = await dependencies.store.list(taskScope(state));
212
+ const records = await stage("task.read", () => dependencies.store.list(taskScope(state)));
168
213
  return { tasks: records.filter(r => !operation || r.task.operation === operation).slice(0, limit).map(summary) };
169
214
  },
170
215
  async get({ state, id, signal }) {
171
216
  signal.throwIfAborted();
172
217
  const scope = taskScope(state);
173
- const record = await dependencies.store.read(scope, id);
218
+ telemetry?.annotate({ cli_task_id: id });
219
+ const record = await stage("task.read", () => dependencies.store.read(scope, id));
174
220
  if (!record)
175
221
  throw new TaskNotFoundError(text(`当前身份中没有该任务。请执行 ${commandName} task list 查找。`, `No task was found in the current identity context. Use ${commandName} task list to find it.`));
176
222
  telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
177
223
  await replay(record);
178
224
  if (record.task.state === "completed" && record.task.result) {
179
- return { ...record.task, result: await dependencies.recovery.authorize(record.task.result, state, signal) };
225
+ return { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };
180
226
  }
181
227
  const task = summary(record);
182
228
  if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
183
229
  return task;
184
- const recovered = await dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal);
230
+ const recovered = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
185
231
  const { note: _note, ...metadata } = task;
186
232
  const result = { ...metadata, ...recovered };
187
233
  if (result.state === "unknown" && task.note) {
188
234
  result.note = [task.note, recovered.note].filter(Boolean).join(" ");
189
235
  }
190
- telemetry?.annotate({ result_state: result.state });
191
236
  if (result.state === "completed" && result.result) {
192
- dependencies.validateResult?.(result.result);
237
+ await stage("task.validate", async () => { dependencies.validateResult?.(result.result); });
193
238
  await fact(scope, record, "result_ready", dependencies.now().getTime());
194
239
  }
240
+ telemetry?.annotate({ result_state: result.state });
195
241
  // Store merging protects terminal results and facts against stale heartbeats.
196
242
  if (result.state === "completed" || result.state === "failed") {
197
243
  result.updatedAt = dependencies.now().toISOString();
198
244
  record.task = withoutResourceKeys(result);
199
- await dependencies.store.write(scope, record);
245
+ try {
246
+ await stage("task.persist", () => dependencies.store.write(scope, record));
247
+ }
248
+ catch (error) {
249
+ if (!(error instanceof LocalFileError) || result.state !== "completed" || !result.result)
250
+ throw error;
251
+ cacheWarning(id);
252
+ }
200
253
  }
201
254
  return result;
202
255
  }
@@ -11,8 +11,14 @@ export const defaultToolDefinitions = [
11
11
  }
12
12
  ];
13
13
  export class ToolInputError extends Error {
14
- constructor() {
15
- super("Tool 输入不可用。");
14
+ reason;
15
+ field;
16
+ issues;
17
+ constructor(reason = "invalid_tool_input", field, issues = [], cause) {
18
+ super(`Tool 输入不可用:${reason}${field ? ` (${field})` : ""}${issues.length ? ` ${JSON.stringify(issues)}` : ""}`, { cause });
19
+ this.reason = reason;
20
+ this.field = field;
21
+ this.issues = issues;
16
22
  this.name = "ToolInputError";
17
23
  }
18
24
  }
@@ -42,7 +48,7 @@ export function projectToolList(catalog, tools = defaultToolDefinitions) {
42
48
  }
43
49
  export function projectModelList(catalog, tool, tools = defaultToolDefinitions) {
44
50
  if (tool !== undefined && !catalog.models.some((model) => model.tool === tool)) {
45
- throw new ToolInputError();
51
+ throw new ToolInputError("tool_not_found", "/tool");
46
52
  }
47
53
  return {
48
54
  models: catalog.models
@@ -54,7 +60,7 @@ export function projectModelList(catalog, tool, tools = defaultToolDefinitions)
54
60
  export function findModel(catalog, model) {
55
61
  const found = catalog.models.find((candidate) => candidate.model === model);
56
62
  if (found === undefined)
57
- throw new ToolInputError();
63
+ throw new ToolInputError("model_not_found", "/model");
58
64
  return found;
59
65
  }
60
66
  export function projectModelDetail(catalog, model) {
@@ -73,6 +79,6 @@ export function projectModelDetail(catalog, model) {
73
79
  export function findToolModel(catalog, tool, model) {
74
80
  const found = findModel(catalog, model);
75
81
  if (found.tool !== tool)
76
- throw new ToolInputError();
82
+ throw new ToolInputError("model_tool_mismatch", "/model");
77
83
  return found;
78
84
  }
@@ -1,5 +1,6 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import addFormatsImport, {} from "ajv-formats";
3
+ import { validationIssues } from "../../platform/schema-issues.js";
3
4
  import { ToolInputError } from "./catalog.js";
4
5
  function parameterSchema(parameter, includeBounds = false) {
5
6
  const common = {
@@ -55,14 +56,14 @@ function mergeSchema(current, next) {
55
56
  enum: [...new Set([...current.enum, ...next.enum])]
56
57
  };
57
58
  }
58
- export function buildToolArgumentsSchema(catalog, tool) {
59
+ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要调用的模型机器标识;取值来自 model list。") {
59
60
  const models = catalog.models.filter((model) => model.tool === tool);
60
61
  if (models.length === 0)
61
- throw new ToolInputError();
62
+ throw new ToolInputError("tool_not_found", "/tool");
62
63
  const properties = {
63
64
  model: {
64
65
  type: "string",
65
- description: "要调用的模型机器标识;取值来自 model list。"
66
+ description: modelDescription
66
67
  }
67
68
  };
68
69
  for (const model of models) {
@@ -125,10 +126,11 @@ function controlArgumentsValidator(model) {
125
126
  });
126
127
  }
127
128
  export function assertModelArguments(model, value) {
128
- if (typeof value !== "object" || value === null
129
- || !validator(model)(value)
130
- || !sliderStepsAreValid(model, value)) {
131
- throw new ToolInputError();
129
+ const validate = validator(model);
130
+ if (!validate(value))
131
+ throw new ToolInputError("model_parameters", "/arguments", validationIssues(validate.errors));
132
+ if (!sliderStepsAreValid(model, value)) {
133
+ throw new ToolInputError("model_parameters", "/arguments");
132
134
  }
133
135
  }
134
136
  function sliderStepsAreValid(model, value) {
@@ -248,6 +248,7 @@ export function createMnsCatalogAdapter(dependencies) {
248
248
  || (left.model < right.model ? -1 : left.model > right.model ? 1 : 0));
249
249
  return {
250
250
  models,
251
+ ...(invalidCount > 0 ? { invalidModelCount: invalidCount } : {}),
251
252
  warnings: invalidCount === 0
252
253
  ? []
253
254
  : [dependencies.invalidModelWarning?.(invalidCount)
@@ -1,3 +1,4 @@
1
+ import { isInterruption } from "../../platform/interruption.js";
1
2
  import { randomInt } from "node:crypto";
2
3
  import { setTimeout as delay } from "node:timers/promises";
3
4
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
@@ -252,11 +253,11 @@ async function safePost(transport, request) {
252
253
  return await transport.postJson(request);
253
254
  }
254
255
  catch (error) {
255
- if (request.signal.aborted)
256
+ if (isInterruption(error, request.signal))
256
257
  throw request.signal.reason;
257
258
  if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
258
259
  throw error;
259
- throw new RemoteRequestError();
260
+ throw new RemoteRequestError(undefined, false, {}, error);
260
261
  }
261
262
  }
262
263
  async function defaultSleep(milliseconds, signal) {
@@ -264,10 +265,10 @@ async function defaultSleep(milliseconds, signal) {
264
265
  try {
265
266
  await delay(milliseconds, undefined, { signal });
266
267
  }
267
- catch {
268
- if (signal.aborted)
268
+ catch (error) {
269
+ if (isInterruption(error, signal))
269
270
  throw signal.reason;
270
- throw new RemoteRequestError();
271
+ throw new RemoteRequestError(undefined, false, {}, error);
271
272
  }
272
273
  }
273
274
  function defaultContentId() {
@@ -344,9 +345,9 @@ export function createToolApiAdapter(dependencies) {
344
345
  transientFailures = 0;
345
346
  }
346
347
  catch (error) {
347
- if (signal.aborted)
348
+ if (isInterruption(error, signal))
348
349
  throw signal.reason;
349
- if (!(error instanceof RemoteRequestError) || !error.transient)
350
+ if (signal.aborted || !(error instanceof RemoteRequestError) || !error.transient)
350
351
  throw error;
351
352
  transientFailures += 1;
352
353
  if (transientFailures > 3)
@@ -41,7 +41,7 @@ function remoteMedia(value, name) {
41
41
  }
42
42
  catch (error) {
43
43
  if (error instanceof UrlSafetyError)
44
- throw new ToolInputError();
44
+ throw new ToolInputError("invalid_asset_url", `/arguments/${name}`, [], error);
45
45
  throw error;
46
46
  }
47
47
  }
@@ -50,16 +50,20 @@ export function createToolUseCases(dependencies) {
50
50
  signal.throwIfAborted();
51
51
  const catalog = await dependencies.telemetry.stage("catalog", () => (dependencies.catalog.load({ access, signal })));
52
52
  signal.throwIfAborted();
53
+ if (catalog.warnings.length)
54
+ dependencies.telemetry.annotate({ warning_codes: ["MODEL_CATALOG_INCOMPLETE"], invalid_model_count: catalog.invalidModelCount });
53
55
  for (const warning of catalog.warnings)
54
56
  dependencies.warn(warning);
55
57
  return catalog;
56
58
  }
57
59
  async function prepare({ input, access, signal, observe }) {
60
+ dependencies.telemetry.annotate({ tool_name: input.name,
61
+ ...(typeof input.arguments.model === "string" ? { model_id: input.arguments.model } : {}) });
58
62
  const catalog = await load(access, signal);
59
63
  const model = await dependencies.telemetry.stage("input", () => {
60
64
  const modelName = input.arguments.model;
61
65
  if (typeof modelName !== "string")
62
- throw new ToolInputError();
66
+ throw new ToolInputError("model_required", "/arguments/model");
63
67
  const selected = findToolModel(catalog, input.name, modelName);
64
68
  assertModelArguments(selected, input.arguments);
65
69
  return selected;
@@ -165,7 +169,7 @@ export function createToolUseCases(dependencies) {
165
169
  return projectModelDetail(await load(access, signal), input.model);
166
170
  },
167
171
  async getArgumentsSchema({ name, access, signal }) {
168
- return buildToolArgumentsSchema(await load(access, signal), name);
172
+ return buildToolArgumentsSchema(await load(access, signal), name, dependencies.modelDescription);
169
173
  },
170
174
  async call(input) {
171
175
  const { invocation, usage } = await prepare(input);