@insmind/cli 1.9.1 → 2.1.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.
Files changed (66) hide show
  1. package/README.md +5 -0
  2. package/contracts/operations/credits.get/input.schema.json +8 -0
  3. package/contracts/operations/credits.get/output.schema.json +92 -0
  4. package/contracts/operations/credits.usage.get/input.schema.json +17 -0
  5. package/contracts/operations/credits.usage.get/output.schema.json +46 -0
  6. package/contracts/operations/credits.usage.list/input.schema.json +27 -0
  7. package/contracts/operations/credits.usage.list/output.schema.json +135 -0
  8. package/dist/bin/insmind-cli.js +2 -2
  9. package/dist/src/bootstrap/create-cli.js +28 -24
  10. package/dist/src/bootstrap/create-runtime.js +31 -18
  11. package/dist/src/bootstrap/run-task-worker.js +2 -1
  12. package/dist/src/bootstrap/validators.js +7 -2
  13. package/dist/src/cli/action-binding.js +42 -13
  14. package/dist/src/cli/agent-commands.js +8 -12
  15. package/dist/src/cli/credits-command.js +127 -16
  16. package/dist/src/cli/dam-commands.js +3 -2
  17. package/dist/src/cli/editor-commands.js +10 -5
  18. package/dist/src/cli/host-input.js +34 -0
  19. package/dist/src/cli/model-commands.js +4 -3
  20. package/dist/src/cli/presenter.js +4 -0
  21. package/dist/src/cli/tool-commands.js +7 -9
  22. package/dist/src/cli/update-command.js +24 -1
  23. package/dist/src/contracts/creation-input.js +20 -0
  24. package/dist/src/features/agent/creative-protocol.js +12 -14
  25. package/dist/src/features/agent/use-cases.js +6 -31
  26. package/dist/src/features/auth/access-policy.js +1 -3
  27. package/dist/src/features/auth/sso-service.js +6 -4
  28. package/dist/src/features/auth/use-cases.js +2 -1
  29. package/dist/src/features/credits/amount.js +51 -0
  30. package/dist/src/features/credits/response.js +11 -0
  31. package/dist/src/features/credits/use-cases.js +174 -31
  32. package/dist/src/features/dam/file-downloader.js +2 -1
  33. package/dist/src/features/dam/use-cases.js +7 -7
  34. package/dist/src/features/editor/bridge-client.js +1 -1
  35. package/dist/src/features/editor/use-cases.js +6 -8
  36. package/dist/src/features/org/use-cases.js +3 -3
  37. package/dist/src/features/skill/installer.js +24 -22
  38. package/dist/src/features/task/store.js +26 -12
  39. package/dist/src/features/task/use-cases.js +97 -82
  40. package/dist/src/features/tool/canvas-models.js +21 -4
  41. package/dist/src/features/tool/canvas-tool-adapter.js +29 -20
  42. package/dist/src/features/tool/canvas-video.js +2 -4
  43. package/dist/src/features/tool/dynamic-schema.js +29 -64
  44. package/dist/src/features/tool/mns-catalog-adapter.js +9 -2
  45. package/dist/src/features/tool/scene-catalog-adapter.js +0 -1
  46. package/dist/src/features/tool/tool-api-adapter.js +2 -2
  47. package/dist/src/features/tool/use-cases.js +24 -35
  48. package/dist/src/features/update/check-schema.js +17 -0
  49. package/dist/src/features/update/host-receipt.js +30 -0
  50. package/dist/src/features/update/notice-output.js +30 -0
  51. package/dist/src/features/update/update-lock.js +80 -0
  52. package/dist/src/features/update/update-notification.js +129 -240
  53. package/dist/src/platform/json-input.js +1 -1
  54. package/dist/src/platform/safe-upload-file.js +6 -0
  55. package/dist/src/platform/signature.js +3 -1
  56. package/dist/src/platform/signed-http-transport.js +34 -32
  57. package/dist/src/telemetry/host-diagnostics.js +2 -2
  58. package/dist/src/telemetry/invocation.js +87 -24
  59. package/dist/src/telemetry/process-errors.js +36 -3
  60. package/dist/src/telemetry/sls-sink.js +7 -10
  61. package/package.json +4 -4
  62. package/skills/insmind-cli/SKILL.md +2 -0
  63. package/skills/insmind-cli/references/editor.md +1 -1
  64. package/skills/insmind-cli/references/generation-constraints.md +3 -1
  65. package/skills/insmind-cli/references/tool.md +2 -3
  66. package/skills/insmind-cli/references/update.md +2 -0
@@ -3,6 +3,7 @@ const environments = new WeakMap();
3
3
  const boundPolicies = new WeakMap();
4
4
  const jsonCommands = new WeakSet();
5
5
  const selectedCommands = new WeakMap();
6
+ const commandDefinitions = new WeakMap();
6
7
  /** Declare the existing fixed JSON contract alongside the command registration. */
7
8
  export function jsonOutput(command) {
8
9
  jsonCommands.add(command);
@@ -15,7 +16,7 @@ export function errorUsesJson(program, argv) {
15
16
  return true;
16
17
  const command = selectedCommands.get(program);
17
18
  if (command)
18
- return jsonCommands.has(command) || command.opts().json === true;
19
+ return jsonCommands.has(command) || command.optsWithGlobals().json === true;
19
20
  return jsonErrorsRequested(argv);
20
21
  }
21
22
  export function configureActionEnvironment(program, environment) {
@@ -30,7 +31,6 @@ export function bindAction(command, policy, handler, telemetry) {
30
31
  const environment = environments.get(rootCommand(command));
31
32
  if (!environment)
32
33
  throw new Error("CLI action environment is missing.");
33
- await checkUpdateNotification(environment, telemetry);
34
34
  const context = await environment.telemetry.stage("access", async () => {
35
35
  const authorized = await environment.policies[policy].authorize(environment.signal);
36
36
  if (authorized.policy !== policy) {
@@ -51,7 +51,6 @@ export function bindPreparedAction(command, policy, prepare, run, telemetry) {
51
51
  const environment = environments.get(rootCommand(command));
52
52
  if (!environment)
53
53
  throw new Error("CLI action environment is missing.");
54
- await checkUpdateNotification(environment, telemetry);
55
54
  const prepared = await environment.telemetry.stage("input", () => prepare(environment.signal));
56
55
  if (prepared.handled)
57
56
  return;
@@ -66,16 +65,6 @@ export function bindPreparedAction(command, policy, prepare, run, telemetry) {
66
65
  await run(context, prepared.input, environment.signal);
67
66
  });
68
67
  }
69
- async function checkUpdateNotification(environment, telemetry) {
70
- if (telemetry?.operation === "update")
71
- return;
72
- try {
73
- await environment.updateNotification.check(environment.signal);
74
- }
75
- catch {
76
- // Version availability must never change the requested command outcome.
77
- }
78
- }
79
68
  export function assertAllLeafCommandsBound(program) {
80
69
  for (const command of leafCommands(program)) {
81
70
  if (!boundPolicies.has(command)) {
@@ -96,6 +85,7 @@ function rootCommand(command) {
96
85
  }
97
86
  function bindTelemetrySelection(command, definition) {
98
87
  definition ??= { operation: commandPath(command).split(" ").slice(1).join(".") };
88
+ commandDefinitions.set(command, definition);
99
89
  if (!command.parent)
100
90
  throw new Error(`Telemetry command has no parent: ${command.name()}`);
101
91
  command.parent.hook("preSubcommand", (parent, selected) => {
@@ -116,6 +106,45 @@ function annotateAccessContext(telemetry, context) {
116
106
  organization_id: context.state.organization?.id
117
107
  });
118
108
  }
109
+ /** Identify the invocation before Commander can read stdin, reject arguments or exit for help. */
110
+ export function invocationDefinition(program, argv) {
111
+ let command = program;
112
+ let unknown = false;
113
+ let mode = "execute";
114
+ for (let i = 0; i < argv.length; i++) {
115
+ const token = argv[i];
116
+ if (token === "--")
117
+ break;
118
+ if (token === "-h" || token === "--help") {
119
+ mode = "help";
120
+ continue;
121
+ }
122
+ if (token === "-V" || token === "--version") {
123
+ mode = "version";
124
+ continue;
125
+ }
126
+ if (token.startsWith("-")) {
127
+ const flag = token.split("=")[0];
128
+ const option = [...command.options, ...program.options].find(item => item.long === flag || item.short === flag);
129
+ if (option?.long === "--schema" && mode === "execute")
130
+ mode = "schema";
131
+ if (option?.required && !token.includes("="))
132
+ i++;
133
+ continue;
134
+ }
135
+ if (command.commands.length) {
136
+ const child = command.commands.find(item => item.name() === token || item.aliases().includes(token));
137
+ if (!child) {
138
+ unknown = true;
139
+ break;
140
+ }
141
+ command = child;
142
+ }
143
+ }
144
+ const path = commandPath(command).split(" ").slice(1).join(".");
145
+ const operation = mode === "version" ? "version" : unknown ? "unknown" : commandDefinitions.get(command)?.operation ?? (path || (mode === "help" ? "help" : "unknown"));
146
+ return { operation, mode: () => mode };
147
+ }
119
148
  function commandPath(command) {
120
149
  const names = [];
121
150
  let current = command;
@@ -1,8 +1,8 @@
1
- import { contractSchema } from "../contracts/schema.js";
1
+ import { hostSchema, readHostInput } from "./host-input.js";
2
+ import { agentInputSchema } from "../contracts/creation-input.js";
2
3
  import { jsonOutput, bindPreparedAction } from "./action-binding.js";
3
4
  import { CliUsageError } from "./errors.js";
4
5
  import { productText as text } from "../product/text.js";
5
- const agentSendInputSchema = contractSchema("agent.send", "input");
6
6
  export function registerAgentCommands(program, runtime) {
7
7
  const agent = program.command("agent")
8
8
  .description(text(runtime.product, "稿定 Agent", "insMind Agent"))
@@ -26,7 +26,7 @@ export function registerAgentCommands(program, runtime) {
26
26
  text(runtime.product, "默认模式在 stderr 提示任务 ID,stdout 保持原结果 JSON。", "In default mode the Task ID is written to stderr; stdout contains only the original result JSON."),
27
27
  text(runtime.product, `结果未收到时执行 ${runtime.product.commandName} task list 找到原调用,再执行 ${runtime.product.commandName} task get <id> 查询。`, `If output is missing, find the original run with ${runtime.product.commandName} task list, then query ${runtime.product.commandName} task get <id>.`),
28
28
  text(runtime.product, "首次创作省略 JSON 中的 message.contextId;续聊时传入上次结果的 message.contextId。", "Omit message.contextId for the first creation. Continue a conversation using message.contextId from the previous result."),
29
- text(runtime.product, "Generation Constraints 可选 model 来自 model list;先用 model get 查看控制参数。编辑模型只接受 quality、resolution、audioEnabled、targetLongEdge、maxLayers 中模型实际公开的控制项;prompt、素材与选区要求使用独立 Part,精确几何字段使用 tool call。", "Optional Generation Constraints model comes from model list; inspect controls with model get. Editing models accept only their published quality, resolution, audioEnabled, targetLongEdge or maxLayers controls. Supply prompts, assets and selection instructions as separate Parts; use tool call for exact geometry fields."),
29
+ text(runtime.product, "可用 model 和参数示例见 model list / model get。显式 model 和 arguments 会传给 Agent,编辑模型的已知别名转换为服务字段。文本和素材用独立 Part。", "Discover models and example controls with model list and model get. Explicit model and arguments are sent to the Agent, with known editing aliases mapped to service fields. Supply text and assets as separate Parts."),
30
30
  text(runtime.product, "usage 仅覆盖本次调用,不包含其他命令调用的消耗。", "usage covers this invocation only, excluding other command invocations."),
31
31
  ""
32
32
  ].join("\n"));
@@ -39,11 +39,11 @@ export function registerAgentCommands(program, runtime) {
39
39
  throw new CliUsageError();
40
40
  if (options.schema === true) {
41
41
  await runtime.telemetry.stage("output", async () => {
42
- runtime.io.writeOut(`${JSON.stringify(agentSendInputSchema)}\n`);
42
+ runtime.io.writeOut(`${JSON.stringify(hostSchema(runtime, agentInputSchema))}\n`);
43
43
  });
44
44
  return { handled: true };
45
45
  }
46
- const input = await runtime.jsonInput.read(options.input, signal);
46
+ const input = readHostInput(runtime, await runtime.jsonInput.read(options.input, signal));
47
47
  runtime.validators.agentSendInput(input);
48
48
  runtime.telemetry.annotate({ parameters: { ...input } });
49
49
  return { handled: false, input };
@@ -61,13 +61,9 @@ export function registerAgentCommands(program, runtime) {
61
61
  });
62
62
  return;
63
63
  }
64
- const run = async (observe) => {
65
- const result = await runtime.agent.send({ input,
66
- ...(observe ? { observe } : {}),
67
- access: { credential: context.state.credential, organizationId: context.state.organization.id }, signal });
68
- runtime.validators.agentSendOutput(result);
69
- return result;
70
- };
64
+ const run = (observe) => runtime.agent.send({ input,
65
+ ...(observe ? { observe } : {}),
66
+ access: { credential: context.state.credential, organizationId: context.state.organization.id }, signal });
71
67
  const result = await runtime.tasks.track({ ...task, run });
72
68
  await runtime.telemetry.stage("output", async () => {
73
69
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
@@ -1,23 +1,134 @@
1
- import { bindAction } from "./action-binding.js";
1
+ import { normalizeCreditsUsageListInput } from "../features/credits/use-cases.js";
2
+ import { contractSchema } from "../contracts/schema.js";
3
+ import { productText as text } from "../product/text.js";
4
+ import { bindPreparedAction } from "./action-binding.js";
5
+ import { CliUsageError } from "./errors.js";
2
6
  export function registerCreditsCommand(program, runtime) {
7
+ const product = runtime.product;
3
8
  const credits = program.command("credits")
4
- .description("Show the current insMind credits balance")
5
- .option("--json", "output JSON")
6
- .allowExcessArguments(false);
7
- bindAction(credits, "organization", async (context, signal) => {
9
+ .description(text(product, "查看当前身份与组织的稿豆余额及变动流水", "Show the current credits balance and usage records"))
10
+ .helpCommand(false);
11
+ presentationOptions(credits, runtime);
12
+ credits.addHelpText("after", text(product, "\n只读当前 CLI 身份和组织的权益概览;不提供跨组织钱包或任意用户查询。available=max(0,total-used),成员周期限额单独展示,不能将权益池余额视为成员实际可用额度。pending 保留服务端 wait,不承诺待生效或冻结。\n流水见 credits usage --help;数量是稿豆,不折算货币。\n", "\nRead-only overview for the current CLI identity and organization context. available=max(0,total-used); member period limits are shown separately and may restrict spendable credits. pending preserves service wait without assuming activation or reservation semantics.\nDiscover records with credits usage --help. Credits are not currency.\n"));
13
+ bindPreparedAction(credits, "organization", async () => {
14
+ if (await showSchemas(credits, runtime, "credits.get"))
15
+ return { handled: true };
16
+ return { handled: false, input: undefined };
17
+ }, async (context, _input, signal) => {
8
18
  const result = await runtime.telemetry.stage("request", () => runtime.credits.get({
9
- credential: context.state.credential,
10
- organizationId: context.state.organization.id,
11
- signal
19
+ credential: context.state.credential, organizationId: context.state.organization.id, signal
20
+ }));
21
+ await runtime.telemetry.stage("output", async () => {
22
+ runtime.validators.creditsOutput(result);
23
+ runtime.presenter.result(result, { json: credits.optsWithGlobals().json === true, view: value => balanceView(value, runtime) });
24
+ });
25
+ }, { operation: "credits.get", mode: () => credits.optsWithGlobals().schema === true ? "schema" : "execute" });
26
+ const usage = credits.command("usage")
27
+ .description(text(product, "查询消费、归还、回收和过期流水", "Query consumption, restoration, recycling and expiry records"))
28
+ .helpCommand(false);
29
+ const list = usage.command("list")
30
+ .description(text(product, "读取指定时间区间的一页流水", "Read one page of records in a time range"))
31
+ .option("--from <timestamp>", text(product, "含起始时刻,带时区 ISO 8601;默认 UTC 本月月首", "inclusive ISO 8601 start with timezone; defaults to current UTC month start"))
32
+ .option("--to <timestamp>", text(product, "含结束时刻,带时区 ISO 8601;默认 UTC 本月月末", "inclusive ISO 8601 end with timezone; defaults to current UTC month end"))
33
+ .option("--limit <number>", text(product, "每页条数,默认 20", "page size, default 20"))
34
+ .option("--cursor <cursor>", text(product, "原样使用上一页 nextCursor,并保持查询区间", "reuse nextCursor unchanged with the same time range"));
35
+ presentationOptions(list, runtime);
36
+ list.addHelpText("after", text(product, "\n只读一页服务端账本,输出实际 UTC 区间、items、hasMore 和 nextCursor。没有总条数或完整区间消费合计;不能把消费、归还、回收和过期数量相加称为消费。RESTORE 为归还稿豆,不代表现金退款;未知类型保留原值,不推断方向。\n首次查询可省略日期,翻页时固定首次返回的 range 和 --limit。单条来源拆分见 credits usage get --help。\n", "\nReads one page of the service ledger, returning its actual UTC range, items, hasMore and nextCursor. No ledger total or range spending total is inferred. Consumption, restoration, recycling and expiry are distinct; RESTORE is a credit restoration, not a cash refund. Unknown types retain their value without an assumed direction.\nDates may be omitted on the first page. Continue with the returned range and the same --limit. Discover source breakdown with credits usage get --help.\n"));
37
+ bindPreparedAction(list, "organization", async () => {
38
+ if (await showSchemas(list, runtime, "credits.usage.list"))
39
+ return { handled: true };
40
+ const options = list.opts();
41
+ try {
42
+ const input = normalizeCreditsUsageListInput({
43
+ ...(options.from === undefined ? {} : { from: options.from }),
44
+ ...(options.to === undefined ? {} : { to: options.to }),
45
+ ...(options.limit === undefined ? {} : { limit: Number(options.limit) }),
46
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor })
47
+ }, runtime.now());
48
+ return { handled: false, input };
49
+ }
50
+ catch (error) {
51
+ if (error instanceof RangeError)
52
+ throw new CliUsageError();
53
+ throw error;
54
+ }
55
+ }, async (context, input, signal) => {
56
+ const result = await runtime.telemetry.stage("request", () => runtime.credits.listUsage({
57
+ input, credential: context.state.credential, organizationId: context.state.organization.id, signal
58
+ }));
59
+ await runtime.telemetry.stage("output", async () => {
60
+ runtime.validators.creditsUsageListOutput(result);
61
+ runtime.presenter.result(result, { json: list.optsWithGlobals().json === true, view: value => usageListView(value, input.limit, runtime) });
62
+ });
63
+ }, { operation: "credits.usage.list", mode: () => list.optsWithGlobals().schema === true ? "schema" : "execute" });
64
+ const get = usage.command("get")
65
+ .description(text(product, "按流水 ID 读取来源拆分", "Read source breakdown by record ID"))
66
+ .argument("[record-id]", text(product, "流水 ID;执行查询时必填", "record ID, required for execution"));
67
+ presentationOptions(get, runtime);
68
+ get.addHelpText("after", text(product, "\n直接查询服务端单条来源拆分,不重新扫描流水。旧记录或某些变动类型可能没有来源拆分;空 breakdown 不表示该记录消费为零。usageType=1 为消费、2 为归还,其他值不推断方向。\n", "\nQueries one record directly without rescanning the ledger. Legacy records or some change types may have no source breakdown; an empty breakdown does not mean zero consumption. usageType=1 means consumption, 2 restoration; other values have no assumed direction.\n"));
69
+ bindPreparedAction(get, "organization", async () => {
70
+ if (await showSchemas(get, runtime, "credits.usage.get"))
71
+ return { handled: true };
72
+ const id = get.processedArgs[0];
73
+ if (typeof id !== "string" || id.trim() === "" || id === "." || id === "..")
74
+ throw new CliUsageError();
75
+ return { handled: false, input: { id } };
76
+ }, async (context, input, signal) => {
77
+ const result = await runtime.telemetry.stage("request", () => runtime.credits.getUsage({
78
+ input, credential: context.state.credential, organizationId: context.state.organization.id, signal
12
79
  }));
13
80
  await runtime.telemetry.stage("output", async () => {
14
- runtime.presenter.result(result, {
15
- json: credits.opts().json === true,
16
- view: (value) => {
17
- const balance = value;
18
- return `${balance.credits.available} insMind credits available`;
19
- }
20
- });
81
+ runtime.validators.creditsUsageGetOutput(result);
82
+ runtime.presenter.result(result, { json: get.optsWithGlobals().json === true, view: value => usageGetView(value, runtime) });
21
83
  });
22
- }, { operation: "credits.get" });
84
+ }, { operation: "credits.usage.get", mode: () => get.optsWithGlobals().schema === true ? "schema" : "execute" });
85
+ }
86
+ function presentationOptions(command, runtime) {
87
+ command.option("--json", text(runtime.product, "输出 JSON", "output JSON"))
88
+ .option("--schema", text(runtime.product, "输出本地 inputSchema 与 outputSchema,无需登录,不执行查询", "output local inputSchema and outputSchema without login or execution"))
89
+ .allowExcessArguments(false);
90
+ }
91
+ async function showSchemas(command, runtime, operation) {
92
+ if (command.optsWithGlobals().schema !== true)
93
+ return false;
94
+ await runtime.telemetry.stage("output", async () => {
95
+ runtime.io.writeOut(`${JSON.stringify({ inputSchema: contractSchema(operation, "input"), outputSchema: contractSchema(operation, "output") })}\n`);
96
+ });
97
+ return true;
98
+ }
99
+ function balanceView(result, runtime) {
100
+ const english = runtime.product.id === "insmind";
101
+ const unit = english ? "credits" : "稿豆";
102
+ const balance = result.credits;
103
+ return [english ? `${balance.available} ${unit} available in the overview` : `概览余额:${balance.available} ${unit}`,
104
+ `total=${balance.total}, used=${balance.used}, pending(wait)=${balance.pending}`,
105
+ ...(result.balances ?? []).map(row => [row.identifier ?? "—", `total=${row.total}`, `used=${row.used}`, `pending(wait)=${row.pending}`, `available=${row.available}`,
106
+ ...(row.memberPeriodLimit === undefined ? [] : [english ? `member period limit=${row.memberPeriodLimit}` : `成员周期限额=${row.memberPeriodLimit}`])].join(" · ")),
107
+ ...(result.balances?.some(row => row.memberPeriodLimit !== undefined) ? [english
108
+ ? "Member limits are separate; the overview balance does not guarantee spendable credits."
109
+ : "成员限额单独生效,概览余额不保证当前成员可用数量。"] : [])
110
+ ].join("\n");
111
+ }
112
+ function usageListView(result, limit, runtime) {
113
+ const product = runtime.product;
114
+ const unit = product.id === "gaoding" ? "稿豆" : "credits";
115
+ const more = result.hasMore ? `${product.commandName} credits usage list --from ${quote(result.range.from)} --to ${quote(result.range.to)} --limit ${limit} --cursor ${quote(result.nextCursor)} --json`
116
+ : text(product, "已到末页", "End of records");
117
+ return [`${result.range.from} → ${result.range.to} (UTC)`,
118
+ ...result.items.map(row => `${row.recordedAt} · ${row.id} · ${row.changeType} · ${signedAmount(row.amount, row.changeType)} ${unit}${row.description ? ` · ${row.description}` : ""}`),
119
+ ...(result.items.length ? [] : [text(product, "本页无记录", "No records on this page")]),
120
+ `${text(product, "本页条数", "Page count")}: ${result.items.length}; hasMore=${result.hasMore}`,
121
+ more, text(product, "本页不是区间消费总计;完整字段见 --json。", "This page is not a range spending total. Use --json for all fields.")].join("\n");
122
+ }
123
+ function usageGetView(result, runtime) {
124
+ const product = runtime.product;
125
+ const unit = product.id === "gaoding" ? "稿豆" : "credits";
126
+ return [result.id, ...result.breakdown.map(row => `${row.sourceType ?? text(product, "来源未知", "Unknown source")} · usageType=${row.usageType ?? "?"} · ${row.usageType === 2 ? "+" : row.usageType === 1 ? "-" : ""}${row.amount} ${unit}`),
127
+ ...(result.breakdown.length ? [] : [text(product, "服务端未提供拆分,不代表消耗为零。", "No breakdown returned; this does not mean zero consumption.")])].join("\n");
128
+ }
129
+ function signedAmount(amount, type) {
130
+ if (amount === 0)
131
+ return "0";
132
+ return `${type === "RESTORE" ? "+" : ["CONSUME", "RECYCLE", "EXPIRE"].includes(type) ? "-" : ""}${amount}`;
23
133
  }
134
+ function quote(value) { return `'${value.replaceAll("'", "'\\''")}'`; }
@@ -1,3 +1,4 @@
1
+ import { normalizeDamAssetId } from "../features/dam/input.js";
1
2
  import { bindAction, bindPreparedAction } from "./action-binding.js";
2
3
  import { CliUsageError } from "./errors.js";
3
4
  import { repositoryListView } from "./presenter.js";
@@ -266,7 +267,7 @@ export function registerDamCommands(program, runtime) {
266
267
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
267
268
  bindPreparedAction(get, "organization", async (signal) => {
268
269
  signal.throwIfAborted();
269
- const input = { asset_id: position(get, 0) };
270
+ const input = { asset_id: normalizeDamAssetId(position(get, 0)) };
270
271
  runtime.validators.damGetInput(input);
271
272
  runtime.telemetry.annotate({ parameters: { ...input } });
272
273
  return { handled: false, input };
@@ -331,7 +332,7 @@ export function registerDamCommands(program, runtime) {
331
332
  signal.throwIfAborted();
332
333
  const options = deleteCommand.opts();
333
334
  const input = {
334
- asset_id: position(deleteCommand, 0),
335
+ asset_id: normalizeDamAssetId(position(deleteCommand, 0)),
335
336
  ...defined("repositoryId", options.repositoryId),
336
337
  ...(options.permanent === true ? { permanent: true } : {})
337
338
  };
@@ -1,8 +1,14 @@
1
+ import { hostSchema, readHostInput, editorActions } from "./host-input.js";
1
2
  import { jsonOutput, bindAction, bindPreparedAction } from "./action-binding.js";
2
3
  import { contractSchema } from "../contracts/schema.js";
3
4
  import { CliUsageError } from "./errors.js";
4
5
  import { productText as text } from "../product/text.js";
5
- const editorApplyInputSchema = contractSchema("editor.apply", "input");
6
+ const { $defs, ...actionArray } = contractSchema("editor.apply", "input");
7
+ const editorApplyInputSchema = {
8
+ type: "object", additionalProperties: false, required: ["actions"], properties: { actions: actionArray },
9
+ $defs: Object.fromEntries(Object.entries($defs)
10
+ .map(([name, definition]) => [name, { ...definition, additionalProperties: true }]))
11
+ };
6
12
  export function registerEditorCommands(program, runtime) {
7
13
  const editor = program.command("editor")
8
14
  .description(text(runtime.product, "连接并操作 AI+ Editor", "Connect to and operate insMind Editor"))
@@ -64,7 +70,7 @@ export function registerEditorCommands(program, runtime) {
64
70
  apply.addHelpText("after", [
65
71
  "",
66
72
  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}."),
67
- 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."),
73
+ text(runtime.product, "输入对象包含 host_application 和按序执行的 actions 数组;类型、必填字段与可选值见 --schema。使用简短语义 ID;create ID 必须唯一,Connector 可引用本批次更早创建的 Shape。", "Input is an object with host_application and an ordered actions 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."),
68
74
  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."),
69
75
  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."),
70
76
  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."),
@@ -78,11 +84,10 @@ export function registerEditorCommands(program, runtime) {
78
84
  if (Number(options.schema === true) + Number(options.input !== undefined) !== 1)
79
85
  throw new CliUsageError();
80
86
  if (options.schema === true) {
81
- await runtime.telemetry.stage("output", () => { writeJson(runtime, editorApplyInputSchema); });
87
+ await runtime.telemetry.stage("output", () => { writeJson(runtime, hostSchema(runtime, editorApplyInputSchema)); });
82
88
  return { handled: true };
83
89
  }
84
- const input = await runtime.jsonInput.read(options.input, signal);
85
- runtime.validators.editorApplyInput(input);
90
+ const input = editorActions(readHostInput(runtime, await runtime.jsonInput.read(options.input, signal)));
86
91
  return { handled: false, input };
87
92
  }, async (_context, input, signal) => {
88
93
  writeJson(runtime, await runtime.telemetry.stage("editor.apply", () => runtime.editor.apply({ input, signal })));
@@ -0,0 +1,34 @@
1
+ import { InputContractError } from "../bootstrap/validators.js";
2
+ import { productText } from "../product/text.js";
3
+ function object(value) {
4
+ return !!value && typeof value === "object" && !Array.isArray(value);
5
+ }
6
+ /** The host is CLI metadata. Neither the service nor the shared MCP operation receives it. */
7
+ export function readHostInput(runtime, raw) {
8
+ if (!object(raw))
9
+ return raw;
10
+ const { host_application, ...input } = raw;
11
+ runtime.telemetry.observeHost(host_application);
12
+ return input;
13
+ }
14
+ export function hostSchema(runtime, schema) {
15
+ const description = productText(runtime.product, "填写发起本次 CLI 命令的应用名称,例如 workbuddy、qwenwork 或 trae。应用通过终端执行命令时仍填该应用的名称。用户直接在终端执行时填 terminal。其他应用填写其实际名称。", "Name the application invoking this command, for example workbuddy, qwenwork or trae. When an app uses a terminal, name the app. For direct terminal use, enter terminal. For other apps, enter their actual name.");
16
+ const augment = (source) => ({ ...source,
17
+ properties: { ...(object(source.properties) ? source.properties : {}), host_application: { type: "string", description } },
18
+ required: [...new Set([...(Array.isArray(source.required) ? source.required : []), "host_application"])] });
19
+ const result = augment(schema);
20
+ if (Array.isArray(schema.allOf)) {
21
+ return { ...result, allOf: schema.allOf.map(branch => object(branch) && object(branch.then) ? { ...branch, then: augment(branch.then) } : branch) };
22
+ }
23
+ return result;
24
+ }
25
+ export function editorActions(raw) {
26
+ if (!object(raw) || !Array.isArray(raw.actions))
27
+ throw new InputContractError([
28
+ { field: "/actions", rule: "type", message: "expected an array of editor actions" }
29
+ ]);
30
+ const extra = Object.keys(raw).find(key => key !== "actions");
31
+ if (extra)
32
+ throw new InputContractError([{ field: "/" + extra, rule: "additionalProperties", message: "editor action fields belong inside actions" }]);
33
+ return raw.actions;
34
+ }
@@ -1,3 +1,4 @@
1
+ import { hostSchema } from "./host-input.js";
1
2
  import { jsonOutput, bindAction } from "./action-binding.js";
2
3
  import { CliUsageError } from "./errors.js";
3
4
  import { productText as text } from "../product/text.js";
@@ -41,8 +42,8 @@ export function registerModelCommands(program, runtime) {
41
42
  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."),
42
43
  text(runtime.product, "inputSchema 是选定 Tool + Model 的完整 JSON Schema,包含嵌套对象、数组及约束。同一 Model 用于多个 Tool 时请加 --tool;优先按 inputSchema 构造 Tool 输入。", "inputSchema is the complete JSON Schema for the selected Tool + Model, including nested objects, arrays and constraints. Use --tool when a Model supports multiple Tools; construct Tool input from inputSchema."),
43
44
  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."),
44
- 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."),
45
- text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 根据 model 校验对应必填字段、可用参数和范围;step 及跨字段规则另见本 Model 元数据。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema validates required fields, allowed parameters and ranges per model; follow this Model's metadata for step and cross-field rules. For Agent, pass explicit generation constraints rather than copying every Tool-required parameter."),
45
+ text(runtime.product, "required 和 default 说明模型的输入要求和服务默认值。用户未指定有默认值的参数时可以省略;显式值原样发送。model 放在输入顶层。", "required and default describe the model input and service defaults. Omit a defaulted parameter the user did not specify. Explicit values are forwarded. Put model at the top level."),
46
+ text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 按 model 展示字段、选项和范围;step 及跨字段规则见本 Model 元数据。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema describes fields, options and ranges per model; follow this Model's metadata for step and cross-field rules. For Agent, pass explicit generation constraints rather than copying every Tool-required parameter."),
46
47
  ""
47
48
  ].join("\n"));
48
49
  jsonOutput(get);
@@ -67,7 +68,7 @@ export function registerModelCommands(program, runtime) {
67
68
  });
68
69
  await runtime.telemetry.stage("output", async () => {
69
70
  runtime.validators.modelGetOutput(result);
70
- runtime.io.writeOut(`${JSON.stringify(result)}\n`);
71
+ runtime.io.writeOut(`${JSON.stringify(result.inputSchema ? { ...result, inputSchema: hostSchema(runtime, result.inputSchema) } : result)}\n`);
71
72
  });
72
73
  }, {
73
74
  operation: "model.get"
@@ -5,13 +5,17 @@ export function createPresenter(options) {
5
5
  type: "terminal",
6
6
  small: true
7
7
  }));
8
+ let humanResult = false;
8
9
  return {
10
+ get humanResult() { return humanResult; },
9
11
  result(value, presentation) {
12
+ humanResult = !presentation.json;
10
13
  options.writeOut(presentation.json
11
14
  ? `${JSON.stringify(value)}\n`
12
15
  : `${presentation.view(value)}\n`);
13
16
  },
14
17
  success(message) {
18
+ humanResult = true;
15
19
  options.writeOut(`${message}\n`);
16
20
  },
17
21
  async authorization(input) {
@@ -1,3 +1,4 @@
1
+ import { hostSchema, readHostInput } from "./host-input.js";
1
2
  import { jsonOutput, bindAction, bindPreparedAction } from "./action-binding.js";
2
3
  import { CliUsageError } from "./errors.js";
3
4
  import { productText as text } from "../product/text.js";
@@ -56,7 +57,7 @@ export function registerToolCommands(program, runtime) {
56
57
  if (options.schema === true) {
57
58
  return { handled: false, input: { mode: "schema", name } };
58
59
  }
59
- const argumentsInput = await runtime.jsonInput.read(options.input, signal);
60
+ const argumentsInput = readHostInput(runtime, await runtime.jsonInput.read(options.input, signal));
60
61
  const input = { name, arguments: argumentsInput };
61
62
  runtime.validators.toolCallInput(input);
62
63
  return { handled: false, input: { mode: "call", input, async: options.async === true } };
@@ -73,14 +74,15 @@ export function registerToolCommands(program, runtime) {
73
74
  });
74
75
  runtime.telemetry.annotate({ tool_name: prepared.name });
75
76
  await runtime.telemetry.stage("output", async () => {
76
- runtime.io.writeOut(`${JSON.stringify(schema)}\n`);
77
+ runtime.io.writeOut(`${JSON.stringify(hostSchema(runtime, { ...schema }))}\n`);
77
78
  });
78
79
  return;
79
80
  }
81
+ const { prompt, model } = prepared.input.arguments;
80
82
  const task = {
81
83
  state: context.state,
82
84
  operation: "tool.call",
83
- label: `${prepared.input.name}: ${String(prepared.input.arguments.prompt ?? prepared.input.arguments.model ?? "")}`
85
+ label: `${prepared.input.name}: ${typeof prompt === "string" ? prompt : typeof model === "string" ? model : ""}`
84
86
  };
85
87
  if (prepared.async) {
86
88
  const result = await runtime.startBackgroundTask({ ...task, input: prepared.input }, signal);
@@ -90,12 +92,8 @@ export function registerToolCommands(program, runtime) {
90
92
  });
91
93
  return;
92
94
  }
93
- const run = async (observe) => {
94
- const result = await runtime.tool.call({ input: prepared.input, access, signal,
95
- ...(observe ? { observe } : {}) });
96
- runtime.validators.toolCallOutput(result);
97
- return result;
98
- };
95
+ const run = (observe) => runtime.tool.call({ input: prepared.input, access, signal,
96
+ ...(observe ? { observe } : {}) });
99
97
  const result = await runtime.tasks.track({ ...task, run });
100
98
  await runtime.telemetry.stage("output", async () => {
101
99
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
@@ -1,4 +1,6 @@
1
- import { bindAction } from "./action-binding.js";
1
+ import { waitForHostReceipt } from "../features/update/host-receipt.js";
2
+ import { updateCheckSchema } from "../features/update/check-schema.js";
3
+ import { bindAction, jsonOutput } from "./action-binding.js";
2
4
  import { productText as text } from "../product/text.js";
3
5
  export function registerUpdateCommand(program, runtime) {
4
6
  const update = program.command("update")
@@ -12,6 +14,27 @@ export function registerUpdateCommand(program, runtime) {
12
14
  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
15
  ""
14
16
  ].join("\n"));
17
+ const check = update.command("check")
18
+ .description(text(runtime.product, "只读查询是否有可用升级,无需登录", "Check for an available update without signing in or installing"))
19
+ .option("--for-display", text(runtime.product, "为当前前台入口交付一次到期提醒,写出成功后开始 60 分钟计时", "Deliver a due notice to the current foreground surface and start its 60-minute window on output"))
20
+ .option("--schema", text(runtime.product, "输出本地查询结果的 Schema,不查询 npm", "Print the local output schema without checking npm"))
21
+ .allowExcessArguments(false);
22
+ jsonOutput(check);
23
+ check.addHelpText("after", text(runtime.product, "\n输出单个 JSON。status 为 available、current、managed 或 unknown;仅 available 提供 updateCommand。普通查询不占提醒次数;--for-display 用于会话展示,仅在到期时返回 notice。使用 CLI_HOST_APPLICATION 指定实际宿主名。复用一小时版本缓存,不安装 CLI 或同步 Skill。\n", "\nOutputs one JSON object with status available, current, managed or unknown. Only available includes updateCommand. Checking spends no reminder slot. --for-display includes notice only when due for the surface named by CLI_HOST_APPLICATION. Reuses the hourly cache without installing the CLI or syncing Skills.\n"));
24
+ bindAction(check, "none", async (_context, signal) => {
25
+ const write = (value) => runtime.telemetry.stage("output", async () => {
26
+ runtime.io.writeOut(JSON.stringify(value) + "\n");
27
+ await runtime.io.flush?.();
28
+ });
29
+ if (check.opts().schema)
30
+ return write({ outputSchema: updateCheckSchema });
31
+ const forDisplay = check.opts().forDisplay === true;
32
+ await runtime.updateNotification.report(signal, forDisplay, async (result) => {
33
+ await write(result);
34
+ if (forDisplay && result.status === "available" && result.notice)
35
+ await waitForHostReceipt(signal, result.notice);
36
+ });
37
+ }, { operation: "update.check", mode: () => check.opts().schema ? "schema" : "execute" });
15
38
  bindAction(update, "none", async (_context, signal) => {
16
39
  const result = await runtime.update.run(signal);
17
40
  await runtime.telemetry.stage("output", async () => {
@@ -0,0 +1,20 @@
1
+ import { contractSchema } from "./schema.js";
2
+ // Media alone is a prompt. The service has one scene/parameter map and rewrites a
3
+ // question reply into a function response, discarding any accompanying prompt.
4
+ export const agentInputSchema = contractSchema("agent.send", "input");
5
+ const definitions = agentInputSchema.$defs;
6
+ delete definitions.FirstFramePart;
7
+ delete definitions.LastFramePart;
8
+ const generation = definitions.GenerationConstraintsPart.properties.data;
9
+ const model = generation.properties.model;
10
+ if (model.description)
11
+ model.description = "可选创作模型标识;已知编辑模型别名会映射到服务端 code,其余标识原样发送。";
12
+ delete generation.properties.arguments.minProperties;
13
+ const question = { $ref: "#/$defs/QuestionAnswerPart" };
14
+ definitions.UserMessage.allOf = [
15
+ ...["GenerationConstraintsPart", "QuestionAnswerPart"].map(part => ({
16
+ properties: { parts: { type: "array", contains: { $ref: "#/$defs/" + part }, minContains: 0, maxContains: 1 } }
17
+ })),
18
+ { if: { properties: { parts: { type: "array", contains: question } } },
19
+ then: { required: ["contextId"], properties: { contextId: { type: "string" }, parts: { type: "array", maxItems: 1 } } } }
20
+ ];
@@ -32,7 +32,8 @@ export function buildCreativeRequest(message, ids) {
32
32
  type: "media",
33
33
  url: part.asset.url,
34
34
  name: part.asset.filename,
35
- mime: part.asset.mediaType
35
+ mime: part.asset.mediaType,
36
+ extra: { role: part.role }
36
37
  });
37
38
  attachments.push({
38
39
  uri: part.asset.url,
@@ -144,27 +145,24 @@ export function creativeTurnMessages(value, localMessageId) {
144
145
  if (!Array.isArray(value)) {
145
146
  return fail("AGENT_MESSAGES_NOT_ARRAY", { valueType: value === null ? "null" : typeof value });
146
147
  }
147
- const invalidMessageCount = value.filter((message) => record(message) === undefined).length;
148
- if (invalidMessageCount > 0) {
149
- return fail("AGENT_MESSAGE_INVALID", { messageCount: value.length, invalidMessageCount });
150
- }
151
- const messages = value;
152
- const start = messages.findIndex((message) => {
153
- if (message.local_message_id !== localMessageId)
154
- return false;
155
- return message.role === "user" || contentOf(message)?.type === "function_response";
156
- });
148
+ const messages = value.map(message => record(message));
149
+ const start = messages.findIndex(message => message?.local_message_id === localMessageId
150
+ && (message.role === "user" || contentOf(message)?.type === "function_response"));
157
151
  if (start < 0) {
158
- const matchingLocalMessageCount = messages.filter((message) => message.local_message_id === localMessageId).length;
152
+ const matchingLocalMessageCount = messages.filter((message) => message?.local_message_id === localMessageId).length;
159
153
  return fail(matchingLocalMessageCount > 0 ? "AGENT_TURN_ANCHOR_INVALID" : "AGENT_TURN_ANCHOR_MISSING", {
160
154
  messageCount: messages.length, matchingLocalMessageCount
161
155
  });
162
156
  }
163
- const nextInput = messages.findIndex((message, index) => index > start
157
+ const nextInput = messages.findIndex((message, index) => index > start && message !== undefined
164
158
  && typeof message.local_message_id === "string" && message.local_message_id !== ""
165
159
  && message.local_message_id !== localMessageId
166
160
  && (message.role === "user" || contentOf(message)?.type === "function_response"));
167
- return messages.slice(start, nextInput < 0 ? undefined : nextInput);
161
+ const turn = messages.slice(start, nextInput < 0 ? undefined : nextInput);
162
+ const valid = turn.filter(message => message !== undefined);
163
+ if (valid.length !== turn.length)
164
+ return fail("AGENT_MESSAGE_INVALID", { messageCount: turn.length, invalidMessageCount: turn.length - valid.length });
165
+ return valid;
168
166
  }
169
167
  function contentOf(message) {
170
168
  return record(message.content);