@gaoding/cli 1.4.0 → 1.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
@@ -29,9 +29,10 @@ gd-cli agent send --schema
29
29
  gd-cli tool list
30
30
  gd-cli model list --tool <tool>
31
31
  gd-cli model get <model>
32
+ gd-cli editor apply --schema
32
33
  ```
33
34
 
34
- 选定 Model 后,以 `model get` 返回的 `parameters` 与 `usageDescription` 构造实际输入;其中 `cost` 是当前上架 SKU 的稿豆价格区间,不表示某次调用的实际扣费。`tool call --schema` 只给出整个 Tool 的参数并集。运行 `gd-cli --help` 查看当前命令;运行任一命令的 `--help` 查看参数。
35
+ 选定 Model 后,以 `model get` 返回的 `parameters` 与 `usageDescription` 构造实际输入;其中 `cost` 是当前上架 SKU 的稿豆价格区间,不表示某次调用的实际扣费。`tool call <tool> --schema` 只给出整个 Tool 的参数并集。运行 `gd-cli --help` 查看当前命令;运行任一命令的 `--help` 查看参数。`editor apply --schema` 无需登录或连接编辑器,输出当前版本的 Action 输入契约;与执行模式 `--input` 互斥。
35
36
 
36
37
  CLI 最多每小时检查一次 npm `latest`,发现新版本后每天最多在 stderr 提醒一次;检查失败不影响原命令,`CI=true` 时跳过。普通启动不会检查或修复 Agent Skill。`gd-cli update` 始终实时检查 `latest`,支持更新 npm、pnpm 全局安装并同步 Agent Skill。
37
38
 
@@ -141,6 +141,19 @@
141
141
  "$ref": "#/$defs/NonBlankString",
142
142
  "description": "参数的用途说明。"
143
143
  },
144
+ "minimum": {
145
+ "type": "number",
146
+ "description": "数值参数允许的最小值(包含);滑块参数的约束。"
147
+ },
148
+ "maximum": {
149
+ "type": "number",
150
+ "description": "数值参数允许的最大值(包含);滑块参数的约束。"
151
+ },
152
+ "step": {
153
+ "type": "number",
154
+ "exclusiveMinimum": 0,
155
+ "description": "滑块参数相邻允许值之间的正数步长,从 minimum 起算。"
156
+ },
144
157
  "default": {
145
158
  "anyOf": [
146
159
  {
@@ -1,3 +1,5 @@
1
+ import { taskScope } from "../features/task/store.js";
2
+ import { TaskNotFoundError } from "../features/task/use-cases.js";
1
3
  import { homedir } from "node:os";
2
4
  import { createAgentBackgroundLauncher } from "../features/task/agent-background.js";
3
5
  import { createTaskStore } from "../features/task/store.js";
@@ -159,6 +161,7 @@ export function createProductionRuntime(options = {}) {
159
161
  const sso = createSsoService({
160
162
  ssoApi: endpoints.ssoApi,
161
163
  clientId: product.deviceClientId,
164
+ traceparent: () => telemetry.traceparent(),
162
165
  fetch,
163
166
  now
164
167
  });
@@ -205,7 +208,12 @@ export function createProductionRuntime(options = {}) {
205
208
  const validators = createContractValidators({
206
209
  organizations: product.exposesOrganizations
207
210
  });
208
- const modelCatalog = createMnsCatalogAdapter({ transport: mnsTransport });
211
+ const modelCatalog = createMnsCatalogAdapter({
212
+ transport: mnsTransport,
213
+ ...(product.id === "insmind"
214
+ ? { invalidModelWarning: (count) => `Ignored ${count} invalid model configuration${count === 1 ? "" : "s"}.` }
215
+ : {})
216
+ });
209
217
  const damApi = createDamApiAdapter({ transport: damTransport });
210
218
  const damRepositories = createDamRepositoryCatalog({ transport: damTransport });
211
219
  const damOperations = createDamOperationExecutor({
@@ -247,26 +255,44 @@ export function createProductionRuntime(options = {}) {
247
255
  },
248
256
  telemetry
249
257
  });
250
- const resourceAuthorizer = createAgentResourceAuthorizer({
251
- authKeys: options.resourceAuthKeys
252
- ?? createFilemsResourceAuthKeyProvider({ transport: createSignedHttpTransport({
253
- baseUrl: endpoints.filemsApi,
254
- fetch,
255
- now,
256
- channelId: "32",
257
- traceparent: () => telemetry.traceparent(),
258
- ...(businessHeaders ? { businessHeaders } : {})
259
- }) })
260
- });
261
- const authorizeTaskResult = async (result, state, signal) => {
258
+ const resourceAuthKeys = options.resourceAuthKeys
259
+ ?? createFilemsResourceAuthKeyProvider({ transport: createSignedHttpTransport({
260
+ baseUrl: endpoints.filemsApi,
261
+ fetch,
262
+ now,
263
+ channelId: "32",
264
+ traceparent: () => telemetry.traceparent(),
265
+ ...(businessHeaders ? { businessHeaders } : {})
266
+ }) });
267
+ const resourceAuthorizer = createAgentResourceAuthorizer({ authKeys: resourceAuthKeys });
268
+ const accessPolicies = createAccessPolicies({ store, now, refreshCurrentOrganization: org.refreshCurrentOrganization });
269
+ const authorizeTaskAccess = async (state, signal) => {
270
+ await telemetry.stage("access", async () => {
271
+ const current = await accessPolicies.organization.authorize(signal);
272
+ if (!("state" in current) || !current.state.organization
273
+ || taskScope(current.state) !== taskScope(state)
274
+ || current.state.credential.accessKey !== state.credential.accessKey) {
275
+ throw new TaskNotFoundError(text("身份或组织已切换,请重新查询原任务。", "The identity or organization changed. Query the original task again."));
276
+ }
277
+ });
278
+ };
279
+ const authorizeTaskResult = async (result, state, signal, alreadyAuthorized = false) => {
280
+ // Bind only if this result actually needs a fresh resource token.
281
+ const taskAuthorizer = createAgentResourceAuthorizer({ authKeys: {
282
+ async getAuthKey(access, tokenSignal) {
283
+ if (!alreadyAuthorized)
284
+ await authorizeTaskAccess(state, tokenSignal);
285
+ return resourceAuthKeys.getAuthKey(access, tokenSignal);
286
+ }
287
+ } });
262
288
  const access = { credential: state.credential, organizationId: state.organization.id };
263
289
  if ("message" in result)
264
- return resourceAuthorizer.authorize(result, access, signal);
290
+ return taskAuthorizer.authorize(result, access, signal);
265
291
  const links = result.content.filter(part => part.type === "resource_link");
266
292
  if (links.length === 0)
267
293
  return result;
268
294
  const parts = links.map(part => ({ url: part.uri, mediaType: part.mimeType ?? "application/octet-stream" }));
269
- const authorized = await resourceAuthorizer.authorize({
295
+ const authorized = await taskAuthorizer.authorize({
270
296
  message: { contextId: "resource-authorization", parts: [parts[0], ...parts.slice(1)] },
271
297
  usage: { cost: { unit: "gaodou", amount: 0 }, items: [] }
272
298
  }, access, signal);
@@ -309,13 +335,14 @@ export function createProductionRuntime(options = {}) {
309
335
  return {
310
336
  state: "unknown", note: text("本地记录未取得服务端会话标识;无法确认提交结果,不自动重新生成。", "No service context was recorded. The submission outcome is unknown; do not generate again.")
311
337
  };
338
+ await authorizeTaskAccess(state, signal);
312
339
  const snapshot = await readAgentResult(agentTransport, {
313
340
  contextId: progress.contextId, localMessageId: progress.localMessageId,
314
341
  credential: state.credential, organizationId: state.organization.id, signal
315
342
  });
316
343
  return { state: "unknown",
317
344
  note: text(`会话连接为 ${snapshot.connectionState};这不是本次调用的完成凭据。已有内容仅作为消息快照。`, `The context connection is ${snapshot.connectionState}; this does not prove that the run completed. Available content is a message snapshot only.`),
318
- ...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal) } : {})
345
+ ...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal, true) } : {})
319
346
  };
320
347
  },
321
348
  async tool(progress, state, signal) {
@@ -323,6 +350,7 @@ export function createProductionRuntime(options = {}) {
323
350
  return {
324
351
  state: "unknown", note: text("本地记录未取得可查询的 Tool 回执;不自动重新生成。", "No queryable Tool receipt was recorded; do not generate again.")
325
352
  };
353
+ await authorizeTaskAccess(state, signal);
326
354
  const response = await queryToolResult(toolTransport, {
327
355
  taskId: progress.remoteTaskId, credential: state.credential,
328
356
  organizationId: state.organization.id, signal
@@ -335,7 +363,7 @@ export function createProductionRuntime(options = {}) {
335
363
  }
336
364
  return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
337
365
  content: response.content, usage: progress.toolUsage
338
- }, product.billingUnit), state, signal) };
366
+ }, product.billingUnit), state, signal, true) };
339
367
  }
340
368
  }
341
369
  });
@@ -425,11 +453,7 @@ export function createProductionRuntime(options = {}) {
425
453
  version: primarySkill.version,
426
454
  telemetry,
427
455
  telemetrySink,
428
- accessPolicies: createAccessPolicies({
429
- store,
430
- now,
431
- refreshCurrentOrganization: org.refreshCurrentOrganization
432
- }),
456
+ accessPolicies,
433
457
  auth,
434
458
  org,
435
459
  agent,
@@ -6,6 +6,13 @@ export function registerDamCommands(program, runtime) {
6
6
  const dam = program.command("dam")
7
7
  .description(text(runtime.product, "DAM 素材管理", "Asset management"))
8
8
  .helpCommand(false);
9
+ dam.addHelpText("after", [
10
+ "",
11
+ text(runtime.product, "先通过 repository list、folder list、tag list 或资源查询取得真实 ID,再操作;名称、前端 URL 和旧缓存不能代替 ID。", "Discover real IDs with repository list, folder list, tag list or asset queries before acting; names, frontend URLs and old caches are not IDs."),
12
+ text(runtime.product, "支持的命令以本 help 为准;读取所选子命令的 --help 获取参数、作用范围和输出形式。", "Available commands are listed here; read the selected subcommand's --help for parameters, scope and output mode."),
13
+ text(runtime.product, "写入结果未确认时先查询实际状态,不重复提交。跨资源库查询、受保护路径上传和永久删除须有用户明确授权。", "Inspect actual state before retrying an unconfirmed write. Cross-repository queries, protected-path uploads and permanent deletion require explicit user authorization."),
14
+ ""
15
+ ].join("\n"));
9
16
  const repository = dam.command("repository")
10
17
  .description(text(runtime.product, "DAM 资源库", "Asset repositories"))
11
18
  .helpCommand(false);
@@ -98,6 +105,7 @@ export function registerDamCommands(program, runtime) {
98
105
  .option("--repository-id <id>", text(runtime.product, "所属资源库 ID", "repository ID"))
99
106
  .option("--output-dir <directory>", text(runtime.product, "输出目录", "output directory"))
100
107
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
108
+ download.addHelpText("after", `\n${text(runtime.product, "只下载一个素材,不支持文件夹;写入本机目录,不覆盖已有同名文件。--json 返回 files 中的路径、字节数与摘要。", "Downloads one asset, not a folder, to a local directory without overwriting same-named files. --json returns paths, byte counts and digests in files.")}\n`);
101
109
  bindPreparedAction(download, "organization", async (signal) => {
102
110
  signal.throwIfAborted();
103
111
  const options = download.opts();
@@ -129,6 +137,7 @@ export function registerDamCommands(program, runtime) {
129
137
  .requiredOption("--title <title>", text(runtime.product, "新标题", "new title"))
130
138
  .option("--repository-id <id>", text(runtime.product, "所属资源库 ID", "repository ID"))
131
139
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
140
+ rename.addHelpText("after", `\n${text(runtime.product, "一次重命名一个条目;若已提交但未确认,先查询条目真实名称,不重复提交。", "Renames one entry. If submitted but unconfirmed, inspect its actual name before considering another write.")}\n`);
132
141
  bindPreparedAction(rename, "organization", async (signal) => {
133
142
  signal.throwIfAborted();
134
143
  const options = rename.opts();
@@ -163,6 +172,12 @@ export function registerDamCommands(program, runtime) {
163
172
  .option("--repository-id <source-id>", text(runtime.product, "源资源库 ID", "source repository ID"))
164
173
  .option("--target-repository-id <target-id>", text(runtime.product, "目标资源库 ID", "target repository ID"))
165
174
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
175
+ command.addHelpText("after", [
176
+ "",
177
+ text(runtime.product, "一次只操作一个素材或文件夹;先核对源与目标资源库、条目类型、目标文件夹。", "Operates on one asset or folder; verify source/destination repositories, entry kind and destination folder first."),
178
+ text(runtime.product, "已提交但未确认时查询目标位置并保留诊断 ID,不直接重提。copy 成功也可能不返回 copied_entry_id;查询目标位置取得新 ID,不猜 ID 或再次复制。", "If submitted but unconfirmed, inspect the destination and retain the diagnostic ID. A successful copy may omit copied_entry_id; discover the new ID at the destination without guessing or copying again."),
179
+ ""
180
+ ].join("\n"));
166
181
  bindPreparedAction(command, "organization", async (signal) => {
167
182
  signal.throwIfAborted();
168
183
  const options = command.opts();
@@ -311,6 +326,7 @@ export function registerDamCommands(program, runtime) {
311
326
  .argument("<asset>", text(runtime.product, "素材 ID", "asset ID"))
312
327
  .option("--repository-id <id>", text(runtime.product, "所属资源库 ID", "repository ID"))
313
328
  .option("--permanent", text(runtime.product, "移入回收站后永久删除", "permanently delete after moving to trash"));
329
+ deleteCommand.addHelpText("after", `\n${text(runtime.product, "默认移入回收站;--permanent 不可恢复,仅在用户明确要求永久删除时使用。支持的回收站操作请查 dam --help,不推断未列出的命令。", "Moves to the recycle bin by default; --permanent is irreversible and requires an explicit request. Consult dam --help for available recycle-bin operations rather than assuming unlisted commands exist.")}\n`);
314
330
  bindPreparedAction(deleteCommand, "organization", async (signal) => {
315
331
  signal.throwIfAborted();
316
332
  const options = deleteCommand.opts();
@@ -1,12 +1,32 @@
1
1
  import { bindAction, bindPreparedAction } from "./action-binding.js";
2
+ import { contractSchema } from "../contracts/schema.js";
3
+ import { CliUsageError } from "./errors.js";
2
4
  import { productText as text } from "../product/text.js";
5
+ const editorApplyInputSchema = contractSchema("editor.apply", "input");
3
6
  export function registerEditorCommands(program, runtime) {
4
7
  const editor = program.command("editor")
5
8
  .description(text(runtime.product, "连接并操作 AI+ Editor", "Connect to and operate insMind Editor"))
6
9
  .helpCommand(false);
10
+ editor.addHelpText("after", [
11
+ "",
12
+ text(runtime.product, "操作一个当前 Session、当前 Page 的直属 Shape 和绑定 Connector;单操作者串行执行。", "Operate one current Session and its Page's direct Shapes and bound Connectors, serially with one operator."),
13
+ text(runtime.product, "元素类型与字段以 editor apply --schema 为准;Schema 查询无需登录或连接 Editor。", "Discover element types and fields with editor apply --schema; no login or Editor connection is required."),
14
+ text(runtime.product, "当前不支持嵌套元素、自由/半绑定 Connector、页面或选择修改;UNSUPPORTED_PAGE_CONTENT 时保留原作品并换用空白或专用 Page。", "Nested elements, free/half-bound Connectors, page and selection changes are unsupported. On UNSUPPORTED_PAGE_CONTENT, preserve the work and use a blank or dedicated Page."),
15
+ text(runtime.product, "流程:connect → snapshot → apply → snapshot/screenshot 复查 → save → disconnect。apply 不代替 save。", "Workflow: connect → snapshot → apply → review snapshot/screenshot → save → disconnect. Apply does not replace Save."),
16
+ text(runtime.product, "EDITOR_BUSY 时等待原命令结束;写入超时、取消或断连时,先重新连接同一作品并检查真实状态,不直接重试写入。", "On EDITOR_BUSY, wait for the original command. After a write times out, is cancelled or disconnects, reconnect to the same work and inspect its state before deciding what to do."),
17
+ ""
18
+ ].join("\n"));
7
19
  const connect = leaf(editor.command("connect"))
8
20
  .description(text(runtime.product, "打开并连接一个 AI+ Editor 作品", "Open and connect to an Editor work"))
9
21
  .argument("[target]", text(runtime.product, "作品 ID 或完整 URL", "work ID or complete URL"));
22
+ connect.addHelpText("after", [
23
+ "",
24
+ text(runtime.product, "省略 target 新建线上 Board;数字按作品 ID 打开;完整 HTTP(S) URL 按该 URL 的环境打开。", "Omit target for a new production Board, use a numeric work ID, or provide a supported insMind production Editor URL."),
25
+ text(runtime.product, "会打开浏览器并替换旧 Session;浏览器登录、加载、Board 类型、编辑/保存权限与页面内容检查通过后才成功。CLI 登录不能替代浏览器登录。", "Opens the browser and replaces the old Session. Browser login, loading, Board type, edit/save permission and page-content checks must pass. CLI credentials do not replace browser login."),
26
+ text(runtime.product, "输出 JSON {target},不含连接凭证。连接失败时停止写入,让用户在页面处理登录或权限,再重新连接。", "Returns JSON {target} without connection credentials. On failure, stop writing and let the user resolve browser login or permissions before reconnecting."),
27
+ text(runtime.product, "页面切换作品会断开 Session;EDITOR_NOT_READY、EDITOR_SESSION_NOT_FOUND 或 EDITOR_NOT_CONNECTED 时确认目标后重连,不轮询旧 Session。", "Switching works disconnects the Session. On EDITOR_NOT_READY, EDITOR_SESSION_NOT_FOUND or EDITOR_NOT_CONNECTED, verify the target and reconnect instead of polling the old Session."),
28
+ ""
29
+ ].join("\n"));
10
30
  bindPreparedAction(connect, "none", async (signal) => {
11
31
  signal.throwIfAborted();
12
32
  const target = connect.processedArgs[0];
@@ -19,29 +39,57 @@ export function registerEditorCommands(program, runtime) {
19
39
  });
20
40
  const disconnect = leaf(editor.command("disconnect"))
21
41
  .description(text(runtime.product, "断开当前 Editor 连接", "Disconnect the current Editor"));
42
+ disconnect.addHelpText("after", `\n${text(runtime.product, "输出 JSON {disconnected};断开连接不保存作品,需先显式执行 editor save。", "Returns JSON {disconnected}. Disconnecting does not save the work; run editor save explicitly first.")}\n`);
22
43
  bindAction(disconnect, "none", async (_context, signal) => {
23
44
  writeJson(runtime, await runtime.editor.disconnect({ signal }));
24
45
  });
25
46
  const snapshot = leaf(editor.command("snapshot"))
26
47
  .description(text(runtime.product, "读取当前作品快照", "Read the current work snapshot"));
48
+ snapshot.addHelpText("after", [
49
+ "",
50
+ text(runtime.product, "输出 JSON {elements, selectedIds};selectedIds 只读。元素字段和类型见 editor apply --schema。", "Returns JSON {elements, selectedIds}; selectedIds is read-only. Discover element fields and types with editor apply --schema."),
51
+ text(runtime.product, "修改时以最新 Snapshot 中的完整元素为基础;每次 apply 后重新读取。UNSUPPORTED_PAGE_CONTENT 时停止并保留原作品。", "Base changes on complete elements from the latest Snapshot and read again after every Apply. On UNSUPPORTED_PAGE_CONTENT, stop and preserve the work."),
52
+ ""
53
+ ].join("\n"));
27
54
  bindAction(snapshot, "none", async (_context, signal) => {
28
55
  writeJson(runtime, await runtime.editor.snapshot({ signal }));
29
56
  });
30
57
  const apply = leaf(editor.command("apply"))
31
58
  .description(text(runtime.product, "按顺序应用元素操作", "Apply element operations in order"))
32
- .requiredOption("--input <file|->", text(runtime.product, "从文件或标准输入读取 JSON", "read JSON from a file or stdin"));
59
+ .option("--schema", text(runtime.product, "输出输入 Schema,不执行操作", "output the input Schema without executing an operation"))
60
+ .option("--input <file|->", text(runtime.product, "从文件或标准输入读取 JSON", "read JSON from a file or stdin"));
61
+ apply.addHelpText("after", [
62
+ "",
63
+ text(runtime.product, "--schema 与 --input 必须且只能选择一个。Schema 为本地契约,不连接 Editor;执行成功输出 JSON {appliedCount}。", "Choose exactly one of --schema and --input. Schema reads the local contract without connecting to Editor; successful execution returns JSON {appliedCount}."),
64
+ text(runtime.product, "输入是按序执行的 Action 数组;类型、必填字段与可选值见 --schema。使用简短语义 ID;create ID 必须唯一,Connector 可引用本批次更早创建的 Shape。", "Input is an ordered Action array; discover types, required fields and choices with --schema. Use short semantic IDs. Create IDs must be unique; a Connector may reference a Shape created earlier in the batch."),
65
+ text(runtime.product, "update 提交完整元素而非 patch,不改变 id 或 _type。delete 要求 ID 存在;删除 Shape 同时删除绑定的 Connector。", "Update requires the full element, not a patch, without changing id or _type. Delete requires an existing ID; deleting a Shape also deletes its bound Connectors."),
66
+ text(runtime.product, "Shape 的 x/y 为 Page 左上角坐标,w/h 大于 0;数值必须有限。颜色用 #RRGGBB 或 #RRGGBBAA,仅 stroke 可为 null。Connector 用 fromId/toId 表达有方向的 Shape 关系。", "Shape x/y locate its top-left corner in Page coordinates; w/h must exceed zero and numbers must be finite. Colors use #RRGGBB or #RRGGBBAA; only stroke accepts null. Connector fromId/toId express a directed Shape relationship."),
67
+ text(runtime.product, "整批先预检,再在可回滚事务中应用;INVALID_ACTIONS 时修正输入,APPLY_FAILED 时读 Snapshot 确认回滚。EDITOR_ROLLBACK_FAILED 时停止 apply/save,只读检查并报告。", "The batch is checked before one rollback-capable transaction. Correct INVALID_ACTIONS; on APPLY_FAILED read a Snapshot to confirm rollback. On EDITOR_ROLLBACK_FAILED, stop apply/save, inspect read-only and report."),
68
+ text(runtime.product, "成功不表示已保存或视觉正确;读取新 Snapshot,涉及布局/文字/连线时查看截图,再显式 save。超时、取消或断连后先检查真实状态,不重复提交。", "Success proves neither persistence nor correct rendering. Read a new Snapshot, view a screenshot for layout/text/connectors, then explicitly save. Inspect real state after timeout, cancellation or disconnection instead of resubmitting."),
69
+ ""
70
+ ].join("\n"));
33
71
  bindPreparedAction(apply, "none", async (signal) => {
34
72
  signal.throwIfAborted();
35
- const source = apply.opts().input;
36
- const input = await runtime.jsonInput.read(source, signal);
73
+ const options = apply.opts();
74
+ if (Number(options.schema === true) + Number(options.input !== undefined) !== 1)
75
+ throw new CliUsageError();
76
+ if (options.schema === true) {
77
+ await runtime.telemetry.stage("output", () => { writeJson(runtime, editorApplyInputSchema); });
78
+ return { handled: true };
79
+ }
80
+ const input = await runtime.jsonInput.read(options.input, signal);
37
81
  runtime.validators.editorApplyInput(input);
38
82
  return { handled: false, input };
39
83
  }, async (_context, input, signal) => {
40
84
  writeJson(runtime, await runtime.editor.apply({ input, signal }));
85
+ }, {
86
+ operation: "editor.apply",
87
+ mode: () => apply.opts().schema === true ? "schema" : "execute"
41
88
  });
42
89
  const screenshot = leaf(editor.command("screenshot"))
43
90
  .description(text(runtime.product, "导出当前作品 PNG 截图", "Export a PNG screenshot of the current work"))
44
91
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
92
+ screenshot.addHelpText("after", `\n${text(runtime.product, "将当前作品截图写入本机 PNG;--json 输出 {path},path 为绝对路径。打开实际图片检查文字、布局与连线,不以文件存在代替视觉验收。", "Writes a PNG screenshot locally; --json returns {path} with an absolute path. View the actual image to check text, layout and connectors; file existence is not visual verification.")}\n`);
45
93
  bindAction(screenshot, "none", async (_context, signal) => {
46
94
  const result = await runtime.editor.screenshot({ signal });
47
95
  runtime.presenter.result(result, {
@@ -52,6 +100,13 @@ export function registerEditorCommands(program, runtime) {
52
100
  const save = leaf(editor.command("save"))
53
101
  .description(text(runtime.product, "保存当前 AI+ Editor 作品", "Save the current Editor work"))
54
102
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
103
+ save.addHelpText("after", [
104
+ "",
105
+ text(runtime.product, "等待真实持久化完成;--json 输出 {workId, url}。新 Board 首次保存创建作品 ID;原样交付公开 url,保留环境参数。", "Waits for real persistence; --json returns {workId, url}. A new Board gets its work ID on first save. Deliver the public url unchanged, retaining environment parameters."),
106
+ text(runtime.product, "Save 最长等待 5 分 30 秒,其他 Editor RPC 默认 1 分钟;继续等待原命令,保持串行。成功前不得报告已保存。", "Save waits up to 5 minutes 30 seconds; other Editor RPCs default to one minute. Keep waiting on the original command and run serially. Do not report persistence before success."),
107
+ text(runtime.product, "SAVE_FAILED 时保留 Session 并处理明确原因;超时、取消或断连不表示未保存,先重连同一作品检查真实状态。EDITOR_ROLLBACK_FAILED 时不得继续保存。", "On SAVE_FAILED retain the Session and resolve the stated cause. Timeout, cancellation or disconnection does not prove failure to save; reconnect to the same work and inspect first. Do not save after EDITOR_ROLLBACK_FAILED."),
108
+ ""
109
+ ].join("\n"));
55
110
  bindAction(save, "none", async (_context, signal) => {
56
111
  const result = await runtime.editor.save({ signal });
57
112
  runtime.presenter.result(result, {
@@ -179,6 +179,8 @@ export function classifyTelemetryError(error, options = {}) {
179
179
  const remoteError = error instanceof RemoteRequestError
180
180
  || error instanceof RemoteProtocolError
181
181
  || error instanceof ToolTaskFailedError
182
+ || error instanceof SsoRequestError
183
+ || error instanceof OrganizationBindFailedError
182
184
  ? error
183
185
  : undefined;
184
186
  return {
@@ -34,6 +34,14 @@ export function registerModelCommands(program, runtime) {
34
34
  .description(text(runtime.product, "查看模型完整信息", "Show complete model information"))
35
35
  .argument("<model>", text(runtime.product, "模型机器标识", "model machine identifier"))
36
36
  .allowExcessArguments(false);
37
+ get.addHelpText("after", [
38
+ "",
39
+ text(runtime.product, "只读查询当前身份可用的 Model,输出 JSON;不提交创作。参数、费用和预估耗时来自实时目录。", "Reads a Model available to the current identity as JSON without submitting creation. Parameters, cost and estimated time come from the live catalog."),
40
+ text(runtime.product, "parameters 是结构化元数据,不是 JSON Schema:遵守 required/type、minimum/maximum/step,SELECT 使用 options[].value 而非 label。", "parameters is structured metadata, not JSON Schema: follow required/type, minimum/maximum/step, and use SELECT options[].value rather than label."),
41
+ text(runtime.product, "Tool 调用须显式提供所有 required 字段;用户未指定时显式使用返回的 default。model 标识放入调用参数顶层,与模型参数并列。", "Tool calls explicitly supply every required field, using a returned default when the user omitted it. Include the returned model identifier at the top level alongside its parameters."),
42
+ text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 是 Tool 级参数并集,不能代替本 Model 的要求。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema is a tool-wide union, not this Model's exact requirements. For Agent, pass explicit generation constraints rather than copying every Tool-required parameter."),
43
+ ""
44
+ ].join("\n"));
37
45
  bindAction(get, "organization", async (context, signal) => {
38
46
  const modelName = get.processedArgs[0];
39
47
  if (typeof modelName !== "string" || modelName.trim() === "")
@@ -10,7 +10,7 @@ export function registerTaskCommands(program, runtime) {
10
10
  .option("--limit <number>", text("返回 1–100 条,默认 20", "return 1–100 tasks; defaults to 20"), "20")
11
11
  .option("--operation <operation>", text("筛选 agent.send 或 tool.call", "filter by agent.send or tool.call"))
12
12
  .allowExcessArguments(false);
13
- bindPreparedAction(list, "organization", async () => {
13
+ bindPreparedAction(list, "local-organization", async () => {
14
14
  const options = list.opts();
15
15
  const limit = Number(options.limit);
16
16
  if (!/^\d+$/u.test(options.limit) || !Number.isInteger(limit) || limit < 1 || limit > 100
@@ -30,12 +30,13 @@ export function registerTaskCommands(program, runtime) {
30
30
  "",
31
31
  text("completed 表示该次执行已有完整结果;running 表示原 CLI 仍在更新记录,或远端任务仍在执行。", "completed means this task has a complete result; running means the original CLI is updating the record or the service is still processing."),
32
32
  text("unknown 表示无法确认本次执行终态;partialResult 仅是已取得的消息片段,不代表完成。", "unknown means completion cannot be confirmed; partialResult is a message snapshot, not a complete result."),
33
+ text("读取本地状态不请求组织绑定;查询远端进度或获取下载授权仍需联网授权。查询请求失败不代表生成失败,可用原 taskId 重查。", "Local status reads do not bind the organization. Remote progress and download authorization still require network access. A failed query does not mean generation failed; query the same taskId again."),
33
34
  text("查询不重新提交创作;同一执行记录多次读取的 usage 是同一份费用。", "Queries never resubmit a creation. Reading the same task again does not add another usage charge."),
34
35
  text(`记录仅来自本机执行;保留至用户删除 ~/${runtime.product.stateDirectory}/tasks。切换身份或组织后只显示对应记录。`, `Tasks are local to this machine and identity context; they remain until you remove ~/${runtime.product.stateDirectory}/tasks.`),
35
36
  text("Agent 首次回执未取得或原连接中断时可能只能确认未知;不会自动选择最近 Context 或重新生成。", "A missing first Agent receipt or interrupted connection may leave the outcome unknown; the CLI does not select another Context or generate again."),
36
37
  ""
37
38
  ].join("\n"));
38
- bindPreparedAction(get, "organization", async () => {
39
+ bindPreparedAction(get, "local-organization", async () => {
39
40
  const id = get.processedArgs[0];
40
41
  if (typeof id !== "string" || !validTaskId(id))
41
42
  throw new CliUsageError();
@@ -4,6 +4,14 @@ export function registerUpdateCommand(program, runtime) {
4
4
  const update = program.command("update")
5
5
  .description(text(runtime.product, "更新 GD CLI 与内置 Agent Skill", "Update insMind CLI and its bundled Agent Skill"))
6
6
  .allowExcessArguments(false);
7
+ update.addHelpText("after", [
8
+ "",
9
+ text(runtime.product, `检查 ${runtime.product.npmPackage} 的 npm latest,更新受支持的全局 npm/pnpm 安装;CLI 已最新时仍同步随包 Skill。`, `Checks npm latest for ${runtime.product.npmPackage}, updates supported global npm/pnpm installations and synchronizes the bundled Skill even when the CLI is current.`),
10
+ text(runtime.product, `只授权本包安装脚本:npm --allow-scripts=${runtime.product.npmPackage},pnpm --allow-build=${runtime.product.npmPackage}。`, `Enables lifecycle scripts only for this package: npm --allow-scripts=${runtime.product.npmPackage}, pnpm --allow-build=${runtime.product.npmPackage}.`),
11
+ text(runtime.product, "普通使用只检查/提醒,不自动安装或同步 Skill。宿主管理的安装拒绝自行升级,并返回对应渠道的处理步骤;遵循该渠道,不覆盖其他宿主的 Skill。", "Normal use only checks/notifies; it does not install or synchronize Skills automatically. Host-managed installations reject self-update and return channel-specific instructions; follow that channel without overwriting other hosts' Skills."),
12
+ text(runtime.product, "若 CLI 更新成功但 Skill 验收失败,保留已更新版本,按错误中的下一步修复;不支持的安装来源也以命令返回的指引为准。", "If the CLI updates but Skill verification fails, keep the updated version and follow the error's next steps. Unsupported installation sources also receive channel-specific guidance."),
13
+ ""
14
+ ].join("\n"));
7
15
  bindAction(update, "none", async (_context, signal) => {
8
16
  const result = await runtime.update.run(signal);
9
17
  await runtime.telemetry.stage("output", async () => {
@@ -312,9 +312,11 @@ function parseQuestionPart(message) {
312
312
  return fail();
313
313
  return { label };
314
314
  });
315
- const allowMultiple = question.allow_multiple ?? question.allowMultiple;
316
- if (typeof allowMultiple !== "boolean")
315
+ const rawAllowMultiple = question.allow_multiple !== undefined
316
+ ? question.allow_multiple : question.allowMultiple;
317
+ if (rawAllowMultiple !== undefined && typeof rawAllowMultiple !== "boolean")
317
318
  return fail();
319
+ const allowMultiple = rawAllowMultiple ?? false;
318
320
  return { question: text, options, allowMultiple };
319
321
  });
320
322
  const title = nonEmptyString(argumentsRecord.title);
@@ -72,6 +72,14 @@ export function createAccessPolicies(dependencies) {
72
72
  return { policy: "credential", state };
73
73
  }
74
74
  },
75
+ "local-organization": {
76
+ async authorize(signal) {
77
+ const state = await readValidState(signal);
78
+ if (!state.organization)
79
+ throw new OrganizationInvalidError();
80
+ return { policy: "local-organization", state: state };
81
+ }
82
+ },
75
83
  organization: {
76
84
  async authorize(signal) {
77
85
  let state = await readValidState(signal);
@@ -1,11 +1,16 @@
1
+ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
1
2
  import { normalizeScope } from "./state.js";
2
3
  import { signBindOrganization } from "../../platform/signature.js";
3
4
  export class SsoRequestError extends Error {
4
5
  status;
5
- constructor(status, cause) {
6
+ remoteCode;
7
+ remoteBody;
8
+ constructor(status, evidence = {}, cause) {
6
9
  super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`, { cause });
7
10
  this.name = "SsoRequestError";
8
11
  this.status = status;
12
+ this.remoteCode = evidence.remoteCode;
13
+ this.remoteBody = evidence.remoteBody;
9
14
  }
10
15
  }
11
16
  export function classifyBindOutcome(input) {
@@ -24,22 +29,62 @@ export function createSsoService(options) {
24
29
  const baseUrl = new URL(options.ssoApi);
25
30
  if (!baseUrl.pathname.endsWith("/"))
26
31
  baseUrl.pathname += "/";
32
+ const requests = new WeakMap();
33
+ async function responseError(response, networkError) {
34
+ let evidence = {};
35
+ if (!response.ok && !response.bodyUsed) {
36
+ try {
37
+ evidence = remoteErrorEvidence(await response.text());
38
+ }
39
+ catch (error) {
40
+ networkError = error;
41
+ }
42
+ }
43
+ return new SsoRequestError(response.status, {
44
+ ...(evidence.remoteCode === undefined ? {} : { remoteCode: evidence.remoteCode }),
45
+ ...remoteErrorEvidence({ request: requests.get(response),
46
+ ...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
47
+ ...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
48
+ }, networkError);
49
+ }
50
+ async function responseRecord(response) {
51
+ if (!response.ok) {
52
+ // OAuth pending/slow_down are normal token polling responses.
53
+ const body = await response.clone().json().catch(() => undefined);
54
+ if (isRecord(body) && ["authorization_pending", "slow_down"].includes(String(body.error).toLowerCase()))
55
+ return body;
56
+ throw await responseError(response);
57
+ }
58
+ try {
59
+ const value = await response.json();
60
+ if (isRecord(value))
61
+ return value;
62
+ }
63
+ catch (error) {
64
+ throw await responseError(response, error);
65
+ }
66
+ throw await responseError(response);
67
+ }
27
68
  async function request(relativeUrl, signal, method = "POST") {
28
69
  signal.throwIfAborted();
70
+ const url = new URL(relativeUrl, baseUrl);
71
+ const requestInfo = { method, path: url.pathname };
29
72
  try {
30
- return await options.fetch(new URL(relativeUrl, baseUrl), {
73
+ const response = await options.fetch(url, {
31
74
  method,
32
- headers: { Accept: "application/json" },
75
+ headers: { Accept: "application/json", ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
33
76
  signal: AbortSignal.any([
34
77
  signal,
35
78
  AbortSignal.timeout(options.timeoutMs ?? 30_000)
36
79
  ])
37
80
  });
81
+ requests.set(response, requestInfo);
82
+ return response;
38
83
  }
39
- catch (cause) {
84
+ catch (error) {
40
85
  if (signal.aborted)
41
86
  throw signal.reason;
42
- throw new SsoRequestError(undefined, cause);
87
+ throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error);
43
88
  }
44
89
  }
45
90
  return {
@@ -48,14 +93,14 @@ export function createSsoService(options) {
48
93
  clientId: options.clientId ?? "gdhub-cli"
49
94
  })}`, signal);
50
95
  if (!response.ok)
51
- throw new SsoRequestError(response.status);
96
+ throw await responseError(response);
52
97
  const body = await responseRecord(response);
53
98
  const authorizeCode = nonEmptyString(body.authorize_code);
54
99
  const deviceCode = nonEmptyString(body.device_code);
55
100
  const expiresInSeconds = positiveNumber(body.expires_in);
56
101
  const intervalSeconds = positiveNumber(body.interval);
57
102
  if (!authorizeCode || !deviceCode || !expiresInSeconds || !intervalSeconds) {
58
- throw new SsoRequestError(response.status);
103
+ throw await responseError(response);
59
104
  }
60
105
  return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
61
106
  },
@@ -72,18 +117,18 @@ export function createSsoService(options) {
72
117
  if (error === "slow_down")
73
118
  return { status: "slow_down" };
74
119
  if (!response.ok)
75
- throw new SsoRequestError(response.status);
120
+ throw await responseError(response);
76
121
  const accessKey = nonEmptyString(body.ak);
77
122
  const secretKey = nonEmptyString(body.sk);
78
123
  const expiresAt = dateString(body.expires_at);
79
124
  if (!accessKey || !secretKey || !expiresAt)
80
- throw new SsoRequestError(response.status);
125
+ throw await responseError(response);
81
126
  let scope;
82
127
  try {
83
128
  scope = normalizeScope(body.scope);
84
129
  }
85
130
  catch {
86
- throw new SsoRequestError(response.status);
131
+ throw await responseError(response);
87
132
  }
88
133
  const result = {
89
134
  status: "authorized",
@@ -104,7 +149,7 @@ export function createSsoService(options) {
104
149
  const query = new URLSearchParams({ ak: accessKey });
105
150
  const response = await request(`oauth/device/identity?${query}`, signal, "GET");
106
151
  if (!response.ok)
107
- throw new SsoRequestError(response.status);
152
+ throw await responseError(response);
108
153
  const body = await responseRecord(response);
109
154
  const result = {};
110
155
  const userId = identifier(body.userId);
@@ -130,8 +175,12 @@ export function createSsoService(options) {
130
175
  });
131
176
  const response = await request(`oauth/device/bind-org?${query}`, signal);
132
177
  if (!response.ok)
133
- throw new SsoRequestError(response.status);
134
- const text = await response.text();
178
+ throw await responseError(response);
179
+ const text = await response.text().catch(async (error) => {
180
+ if (signal.aborted)
181
+ throw signal.reason;
182
+ throw await responseError(response, error);
183
+ });
135
184
  if (!text.trim())
136
185
  return {};
137
186
  let parsed;
@@ -142,7 +191,7 @@ export function createSsoService(options) {
142
191
  return { message: text.trim() };
143
192
  }
144
193
  if (!isRecord(parsed))
145
- throw new SsoRequestError(response.status);
194
+ throw await responseError(response);
146
195
  const result = {};
147
196
  if (typeof parsed.code === "string" || typeof parsed.code === "number") {
148
197
  result.code = parsed.code;
@@ -153,23 +202,24 @@ export function createSsoService(options) {
153
202
  if (parsed.bind_expires_at !== undefined) {
154
203
  const bindExpiresAt = dateString(parsed.bind_expires_at);
155
204
  if (!bindExpiresAt)
156
- throw new SsoRequestError(response.status);
205
+ throw await responseError(response);
157
206
  result.bindExpiresAt = bindExpiresAt;
158
207
  }
159
208
  return result;
160
209
  }
161
210
  };
162
211
  }
163
- async function responseRecord(response) {
164
- try {
165
- const value = await response.json();
166
- if (isRecord(value))
167
- return value;
168
- }
169
- catch {
170
- // Handled as one safe protocol failure below.
171
- }
172
- throw new SsoRequestError(response.status);
212
+ // Preserve only bounded diagnostic identifiers, never arbitrary cause messages/URLs.
213
+ function networkFailure(error) {
214
+ const safe = (value) => typeof value === "string" && /^[A-Za-z0-9_]{1,80}$/u.test(value) ? value : undefined;
215
+ const one = (value) => {
216
+ const record = value !== null && typeof value === "object" ? value : {};
217
+ const name = safe(record.name);
218
+ const code = safe(record.code);
219
+ return { ...(name ? { name } : {}), ...(code ? { code } : {}) };
220
+ };
221
+ const cause = error !== null && typeof error === "object" && "cause" in error ? one(error.cause) : undefined;
222
+ return { ...one(error), ...(cause ? { cause } : {}) };
173
223
  }
174
224
  function positiveNumber(value) {
175
225
  return typeof value === "number" && Number.isFinite(value) && value > 0