@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
@@ -131,40 +131,37 @@ export function createSignedHttpTransport(options) {
131
131
  let dispatched;
132
132
  try {
133
133
  // Invoke fetch at this boundary; diagnostic persistence never gates dispatch.
134
- let pending;
135
- try {
136
- pending = options.fetch(url, {
137
- method,
138
- headers,
139
- ...(body === undefined ? {} : { body }),
140
- signal
141
- }).then(response => {
142
- // Capture ownership facts before waiting for unrelated dispatch diagnostics.
143
- const received = {
144
- response,
145
- bodyUsedAtReceipt: response.bodyUsed,
146
- bodyLockedAtReceipt: response.body?.locked ?? false,
147
- reusedResponse: seenResponses.has(response),
148
- diagnostics: () => ({ ...diagnostics(), ...responseDiagnostics(response) })
149
- };
150
- seenResponses.add(response);
151
- try {
152
- request.onResponse?.(response.status, received.diagnostics());
153
- }
154
- catch { /* Receipt diagnostics only. */ }
155
- return received;
156
- });
157
- }
158
- finally {
134
+ const pending = options.fetch(url, {
135
+ method,
136
+ headers,
137
+ ...(body === undefined ? {} : { body }),
138
+ signal
139
+ }).then(response => {
140
+ // Capture ownership facts before waiting for unrelated dispatch diagnostics.
141
+ const received = {
142
+ response,
143
+ bodyUsedAtReceipt: response.bodyUsed,
144
+ bodyLockedAtReceipt: response.body?.locked ?? false,
145
+ reusedResponse: seenResponses.has(response),
146
+ diagnostics: () => ({ ...diagnostics(), ...responseDiagnostics(response) })
147
+ };
148
+ seenResponses.add(response);
159
149
  try {
160
- dispatched = request.onDispatch?.(options.now().getTime()).catch(() => undefined);
150
+ request.onResponse?.(response.status, received.diagnostics());
161
151
  }
162
- catch { /* Diagnostic only. */ }
152
+ catch { /* Receipt diagnostics only. */ }
153
+ return received;
154
+ });
155
+ try {
156
+ dispatched = request.onDispatch?.(options.now().getTime()).catch(() => undefined);
163
157
  }
158
+ catch { /* Diagnostic only. */ }
164
159
  const [received] = await Promise.all([pending, dispatched]);
165
160
  return received;
166
161
  }
167
162
  catch (error) {
163
+ // A rejected fetch must not overtake persistence of the dispatch that caused it.
164
+ await dispatched;
168
165
  const diagnosticSummary = diagnostics();
169
166
  if (isInterruption(error, request.signal)) {
170
167
  const reason = request.signal.reason;
@@ -198,24 +195,29 @@ export function createSignedHttpTransport(options) {
198
195
  }, error, diagnosticReason, { ...received.diagnostics(), ...summary });
199
196
  }
200
197
  }
201
- async function json(received) {
198
+ async function json(received, sensitiveResponse = false, parseJson = JSON.parse) {
202
199
  const { response } = received;
203
200
  const body = await readText(received);
204
- const evidence = remoteErrorEvidence(body);
201
+ const originalEvidence = remoteErrorEvidence(body);
202
+ const evidence = sensitiveResponse ? {
203
+ ...(originalEvidence.remoteCode === undefined ? {} : { remoteCode: originalEvidence.remoteCode }),
204
+ ...(originalEvidence.diagnosticReason === undefined ? {} : { diagnosticReason: originalEvidence.diagnosticReason })
205
+ } : originalEvidence;
205
206
  if (!response.ok)
206
207
  throw new RemoteRequestError(response.status, false, evidence, undefined, undefined, received.diagnostics());
207
208
  try {
208
- return JSON.parse(body);
209
+ return parseJson(body);
209
210
  }
210
211
  catch (error) {
211
- throw Object.assign(new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID"), {
212
+ // SyntaxError messages can embed raw JSON fragments, including private ledger data.
213
+ throw Object.assign(new RemoteProtocolError(evidence, sensitiveResponse ? undefined : error, "RESPONSE_JSON_INVALID"), {
212
214
  status: response.status, diagnosticSummary: received.diagnostics()
213
215
  });
214
216
  }
215
217
  }
216
218
  async function getJsonResponse(request) {
217
219
  const received = await send("GET", request, "application/json", undefined, true);
218
- return { body: await json(received), headers: received.response.headers, status: received.response.status };
220
+ return { body: await json(received, request.sensitiveResponse, request.parseJson), headers: received.response.headers, status: received.response.status };
219
221
  }
220
222
  return {
221
223
  async getJson(request) {
@@ -17,7 +17,7 @@ export async function runHostDiagnosticReporter(options) {
17
17
  output.on("error", () => { });
18
18
  const sink = createSlsTelemetrySink({ fetch: options.fetch ?? globalThis.fetch,
19
19
  trackingUrl: options.trackingUrl ?? options.product.telemetryUrl,
20
- directory: join(options.homeDirectory ?? homedir(), options.product.stateDirectory, "telemetry") });
20
+ directory: join(options.homeDirectory ?? homedir(), options.product.stateDirectory, "telemetry", "v6") });
21
21
  const cliVersion = options.cliVersion ?? await packageVersion();
22
22
  // A wrapper may be killed with stdin still open. This helper is always bounded;
23
23
  // queued start evidence survives, and no permanent background process is added.
@@ -55,7 +55,7 @@ export async function runHostDiagnosticReporter(options) {
55
55
  return;
56
56
  if (typeof raw.occurred_at_ms !== "number" || !Number.isSafeInteger(raw.occurred_at_ms) || raw.occurred_at_ms < 0)
57
57
  return;
58
- const event = { ...context, schema_version: "5", cli_name: options.product.commandName,
58
+ const event = { ...context, schema_version: "6", started_at_ms: raw.occurred_at_ms, command_kind: "technical", cli_name: options.product.commandName,
59
59
  cli_version: cliVersion, env: env.CLI_TELEMETRY_ENV === "test" ? "test" : "production",
60
60
  event_name: "host_diagnostic", process_role: "host_connector", trace_id: context.host_invocation_id,
61
61
  record_seq: ++sequence, occurred_at_ms: raw.occurred_at_ms,
@@ -1,11 +1,12 @@
1
1
  import { cleanDiagnostic, errorEvidence } from "./sanitize.js";
2
2
  import { isInterruption } from "../platform/interruption.js";
3
3
  import { safeFailureSummary } from "./failure-summary.js";
4
- /** Only the connector's explicit fixed metadata identifies a host invocation. */
4
+ export function hostName(value) {
5
+ return typeof value === "string" && value.trim() ? value.trim().slice(0, 128) : undefined;
6
+ }
5
7
  export function hostTelemetryContext(env) {
6
8
  return {
7
- ...(["workbuddy", "qwenwork"].includes(env.CLI_HOST_APPLICATION ?? "")
8
- ? { host_application: env.CLI_HOST_APPLICATION } : {}),
9
+ host_application: hostName(env.CLI_HOST_APPLICATION) ?? "unknown",
9
10
  ...(["auth_status", "version_check"].includes(env.CLI_INVOCATION_PURPOSE ?? "")
10
11
  ? { invocation_purpose: env.CLI_INVOCATION_PURPOSE } : {}),
11
12
  ...(/^[a-f0-9]{32}$/u.test(env.CLI_HOST_INVOCATION_ID ?? "") ? { host_invocation_id: env.CLI_HOST_INVOCATION_ID } : {}),
@@ -25,22 +26,30 @@ export function createTelemetryInvocation(options) {
25
26
  const traceId = options.traceIdFactory();
26
27
  const startedAt = options.startedAt ?? options.now();
27
28
  let definition;
29
+ let issued = false;
30
+ let nextStep = "request_sent";
28
31
  let finished = false;
29
32
  let signal;
30
33
  let sequence = 0;
31
34
  const context = {};
32
35
  const events = [];
36
+ const steps = new Map();
33
37
  const published = new Set();
34
38
  const failures = [];
35
- function base() {
39
+ function identity() {
36
40
  const mode = definition?.mode?.();
37
- return { ...context, schema_version: "3", cli_name: options.cliName ?? "gd-cli",
41
+ const creation = mode === "execute" && (definition?.operation === "agent.send" || definition?.operation === "tool.call");
42
+ return { host_application: context.host_application ?? "unknown", schema_version: "6", started_at_ms: startedAt, command_kind: creation ? "creation" : "technical", cli_name: options.cliName ?? "gd-cli",
38
43
  env: options.env ?? "production", process_role: options.processRole ?? "cli",
39
- trace_id: traceId, record_seq: ++sequence, occurred_at_ms: options.now(),
44
+ trace_id: traceId,
40
45
  operation: definition?.operation ?? "unknown", ...(mode ? { mode } : {}),
41
46
  cli_version: options.cliVersion, os: options.runtime.os, arch: options.runtime.arch,
42
47
  node_major: options.runtime.nodeMajor };
43
48
  }
49
+ function base() {
50
+ const { parameters: _input, ...diagnostics } = context;
51
+ return { ...diagnostics, ...identity(), record_seq: ++sequence, occurred_at_ms: options.now() };
52
+ }
44
53
  function classify(error) {
45
54
  return isInterruption(error, signal) ? { outcome: "interrupted" } : options.classifyError(error);
46
55
  }
@@ -66,17 +75,35 @@ export function createTelemetryInvocation(options) {
66
75
  }
67
76
  function remember(event) {
68
77
  const safe = cleanDiagnostic(event);
78
+ if (safe.event_name === "command_step") {
79
+ const key = `${safe.trace_id}/${safe.step}`;
80
+ const first = steps.get(key);
81
+ if (first)
82
+ return first;
83
+ steps.set(key, safe);
84
+ }
69
85
  events.push(safe);
70
86
  return safe;
71
87
  }
88
+ function observeStep(step) {
89
+ if (step === "request_sent")
90
+ nextStep = "result_received";
91
+ if (step === "result_received")
92
+ nextStep = "delivered";
93
+ if (step === "delivered")
94
+ nextStep = undefined;
95
+ }
72
96
  async function publish(event) {
73
97
  if (!options.onEvent)
74
- return;
98
+ return false;
75
99
  try {
76
- if (await options.onEvent(event) !== false)
100
+ if (await options.onEvent(event) !== false) {
77
101
  published.add(event);
102
+ return true;
103
+ }
78
104
  }
79
105
  catch { /* Logging cannot fail the operation. */ }
106
+ return false;
80
107
  }
81
108
  return {
82
109
  traceId,
@@ -86,7 +113,19 @@ export function createTelemetryInvocation(options) {
86
113
  && definition.mode?.() === "execute";
87
114
  return `00-${traceId}-${options.spanIdFactory()}-${paid ? "01" : "00"}`;
88
115
  },
89
- select(next) { definition = next; },
116
+ select(next) { if (!issued)
117
+ definition = next; },
118
+ async issue(next) {
119
+ if (issued)
120
+ return;
121
+ issued = true;
122
+ definition = next;
123
+ await publish(remember({ ...base(), occurred_at_ms: startedAt, event_name: "command_step", step: "issued", outcome: "success" }));
124
+ },
125
+ observeHost(value) {
126
+ if (!context.host_application || context.host_application === "unknown")
127
+ context.host_application = hostName(value) ?? "unknown";
128
+ },
90
129
  useSignal(next) { signal = next; },
91
130
  annotate(annotation) {
92
131
  for (const [key, value] of Object.entries(annotation)) {
@@ -105,10 +144,23 @@ export function createTelemetryInvocation(options) {
105
144
  }
106
145
  },
107
146
  creationContext() {
108
- const { record_seq: _seq, occurred_at_ms: _time, parameters: _parameters, warning_codes: _warnings, invalid_model_count: _invalidModels, diagnostic_summary: _diagnostics, task_state_revision: _revision, task_state_write_confirmed: _written, sls_enqueue_failures: _queueFailures, sls_last_enqueue_error: _queueError, sls_queue_size: _queueSize, sls_queue_oldest_age_ms: _oldestAge, sls_delivery_failures: _deliveryFailures, sls_last_delivery_result: _deliveryResult, sls_last_delivery_http_status: _deliveryStatus, sls_dropped_events: _droppedEvents, sls_last_drop_reason: _dropReason, content_id: _content, task_id: _task, dify_task_id: _dify, result_state: _state, ...snapshot } = base();
109
- return cleanDiagnostic({ ...snapshot, mode: "execute" });
147
+ // Background work and later queries retain the originating invocation's dimensions.
148
+ const snapshot = identity();
149
+ const keys = ["host_invocation_id", "host_connector_version", "installation_owner", "invocation_purpose",
150
+ "account_id", "organization_id", "tool_name", "model_id", "content_id", "task_id", "dify_task_id",
151
+ "cli_task_id", "execution_mode", "parameters"];
152
+ for (const key of keys) {
153
+ if (context[key] !== undefined)
154
+ Object.assign(snapshot, { [key]: context[key] });
155
+ }
156
+ return cleanDiagnostic(snapshot);
157
+ },
158
+ observeStep,
159
+ async emit(event) {
160
+ if (event.trace_id === traceId || event.trace_id === context.creation_trace_id)
161
+ observeStep(event.step);
162
+ return publish(remember(event));
110
163
  },
111
- async emit(event) { await publish(remember(event)); },
112
164
  taskFailure(error) {
113
165
  const c = classify(error);
114
166
  const summary = { ...context.diagnostic_summary, ...c.diagnosticSummary };
@@ -145,18 +197,29 @@ export function createTelemetryInvocation(options) {
145
197
  if (finished || !definition)
146
198
  return [];
147
199
  finished = true;
148
- remember({ ...base(), event_name: "command_finished", outcome: completion.outcome,
149
- duration_ms: Math.max(0, options.now() - startedAt),
150
- ...(completion.outcome === "success" ? {} : {
151
- failure_stage: classify(completion.error).failureStage ?? failureStage(completion.error) ?? "unknown"
152
- }),
153
- ...(completion.outcome === "failure" ? errorFields(completion.error) : completion.outcome === "interrupted" && completion.error !== undefined ? errorEvidence(completion.error) : {}),
154
- ...(completion.outcome === "failure" ? {
155
- error_code: completion.errorCode, error_message: completion.errorMessage,
156
- ...(completion.httpStatus === undefined ? {} : { http_status: completion.httpStatus }),
157
- ...(completion.remoteErrorCode === undefined ? {} : { remote_error_code: completion.remoteErrorCode }),
158
- ...(completion.remoteErrorBody === undefined ? {} : { remote_error_body: completion.remoteErrorBody })
159
- } : {}) });
200
+ const last = base();
201
+ if (completion.outcome === "success" && issued && last.command_kind === "technical") {
202
+ remember({ ...last, event_name: "command_step", step: "delivered", outcome: "success",
203
+ ...(context.parameters ? { parameters: context.parameters } : {}) });
204
+ }
205
+ else if (completion.outcome !== "success" || !issued) {
206
+ const failedStep = last.command_kind === "technical" ? "delivered" : nextStep;
207
+ const stage = completion.outcome === "success" ? "process" : classify(completion.error).failureStage ?? failureStage(completion.error) ?? "command";
208
+ remember({ ...last, event_name: "stage_finished", stage, outcome: completion.outcome,
209
+ ...(completion.outcome !== "success" && failedStep ? { failed_step: failedStep } : {}),
210
+ ...(context.parameters && (!issued || last.command_kind === "technical") ? { parameters: context.parameters } : {}),
211
+ duration_ms: Math.max(0, options.now() - startedAt),
212
+ ...(completion.outcome === "success" ? {} : {
213
+ failure_stage: classify(completion.error).failureStage ?? failureStage(completion.error) ?? "unknown"
214
+ }),
215
+ ...(completion.outcome === "failure" ? errorFields(completion.error) : completion.outcome === "interrupted" && completion.error !== undefined ? errorEvidence(completion.error) : {}),
216
+ ...(completion.outcome === "failure" ? {
217
+ error_code: completion.errorCode, error_message: completion.errorMessage,
218
+ ...(completion.httpStatus === undefined ? {} : { http_status: completion.httpStatus }),
219
+ ...(completion.remoteErrorCode === undefined ? {} : { remote_error_code: completion.remoteErrorCode }),
220
+ ...(completion.remoteErrorBody === undefined ? {} : { remote_error_body: completion.remoteErrorBody })
221
+ } : {}) });
222
+ }
160
223
  return events.filter(event => !published.has(event));
161
224
  }
162
225
  };
@@ -1,13 +1,43 @@
1
1
  import { classifyTelemetryError, mapCliError } from "../cli/errors.js";
2
2
  import { isInterruption } from "../platform/interruption.js";
3
3
  import { randomBytes } from "node:crypto";
4
- import { readFile } from "node:fs/promises";
4
+ import { readFile, readdir } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
6
6
  import { homedir } from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { gaodingProduct, insmindProduct } from "../product/config.js";
9
9
  import { createTelemetryInvocation, hostTelemetryContext } from "./invocation.js";
10
10
  import { createSlsTelemetrySink } from "./sls-sink.js";
11
+ // The CLI module graph may not be loadable. Use packaged operation names only,
12
+ // so a user-supplied positional argument can never become an SLS operation name.
13
+ async function bootstrapDefinition(argv) {
14
+ const names = new Set(["agent.send", "tool.call", "editor.apply", "auth.login", "auth.logout", "org.switch", "credits", "update"]);
15
+ const contracts = new URL("../../../contracts/operations/", import.meta.url);
16
+ for (const name of await readdir(contracts).catch(() => []))
17
+ names.add(name);
18
+ const path = [];
19
+ let mode = "execute";
20
+ for (let i = 0; i < argv.length; i++) {
21
+ const token = argv[i];
22
+ if (token === "--")
23
+ break;
24
+ if (token === "--input" || token === "--locale") {
25
+ i++;
26
+ continue;
27
+ }
28
+ if (token === "--help" || token === "-h")
29
+ mode = "help";
30
+ else if (token === "--version" || token === "-V")
31
+ mode = "version";
32
+ else if (token === "--schema" && mode === "execute")
33
+ mode = "schema";
34
+ else if (!token.startsWith("-") && !names.has(path.join(".")) && path.length < 3)
35
+ path.push(token);
36
+ }
37
+ const name = path.join(".");
38
+ const operation = mode === "version" ? "version" : names.has(name) ? name : !name && mode === "help" ? "help" : "bootstrap";
39
+ return { operation, mode: () => mode };
40
+ }
11
41
  /** Independent fallback for entrypoints which cannot construct the full runtime. */
12
42
  export async function reportProcessError(error, options) {
13
43
  try {
@@ -34,8 +64,11 @@ export async function reportProcessError(error, options) {
34
64
  traceIdFactory: () => options.traceId ?? randomBytes(16).toString("hex"), spanIdFactory: () => randomBytes(8).toString("hex"),
35
65
  runtime: { os: process.platform, arch: process.arch, nodeMajor: Number(process.versions.node.split(".")[0]) },
36
66
  classifyError: () => classification });
37
- telemetry.select({ operation: options.operation });
67
+ const definition = options.argv ? await bootstrapDefinition(options.argv) : { operation: options.operation };
68
+ telemetry.select(definition);
38
69
  telemetry.annotate(hostTelemetryContext(process.env));
70
+ if ((options.processRole ?? "cli") === "cli")
71
+ await telemetry.issue(definition);
39
72
  const events = telemetry.finish(mapped.kind === "interrupted" ? { outcome: "interrupted", error } : {
40
73
  outcome: "failure", error, errorCode: mapped.failure.code, errorMessage: mapped.failure.message,
41
74
  ...(classification.httpStatus === undefined ? {} : { httpStatus: classification.httpStatus }),
@@ -43,7 +76,7 @@ export async function reportProcessError(error, options) {
43
76
  ...(classification.remoteErrorBody === undefined ? {} : { remoteErrorBody: classification.remoteErrorBody })
44
77
  });
45
78
  const sink = createSlsTelemetrySink({ fetch: globalThis.fetch, trackingUrl: options.trackingUrl ?? product.telemetryUrl,
46
- directory: join(options.homeDirectory ?? homedir(), product.stateDirectory, "telemetry") });
79
+ directory: join(options.homeDirectory ?? homedir(), product.stateDirectory, "telemetry", "v6") });
47
80
  // Automated process tests persist to their temporary home, without external traffic.
48
81
  if (process.env.NODE_ENV === "test" || process.env.VITEST)
49
82
  await sink.enqueue?.(events);
@@ -9,11 +9,9 @@ const TTL = 7 * 86_400_000;
9
9
  const CAPACITY = 10 * 1024 * 1024;
10
10
  const BUDGET = 2_000;
11
11
  export function eventKey(event) {
12
- const key = event.event_name === "task_state"
13
- ? [event.cli_name, event.env, event.cli_task_id, "task_state", Number(event.task_revision)]
14
- : event.event_name === "request_sent" || event.event_name === "result_ready"
15
- ? [event.cli_name, event.env, event.cli_task_id, event.event_name]
16
- : [event.cli_name, event.env, event.trace_id, event.process_role, Number(event.record_seq)];
12
+ const key = event.event_name === "command_step"
13
+ ? [event.cli_name, event.env, event.trace_id, event.step]
14
+ : [event.cli_name, event.env, event.trace_id, event.process_role, Number(event.record_seq)];
17
15
  return createHash("sha256").update(JSON.stringify(key)).digest("hex");
18
16
  }
19
17
  export function wireEvent(event) {
@@ -25,7 +23,7 @@ export function wireEvent(event) {
25
23
  else
26
24
  delete safe.diagnostic_summary;
27
25
  }
28
- const wire = {};
26
+ const wire = { event_id: eventKey(safe) };
29
27
  for (const [key, value] of Object.entries(safe)) {
30
28
  if (value !== undefined)
31
29
  wire[key] = typeof value === "object" ? JSON.stringify(value) : String(value);
@@ -100,8 +98,7 @@ export function createSlsTelemetrySink(options) {
100
98
  const value = rawStatus;
101
99
  const count = (key) => typeof value[key] === "number" && Number.isSafeInteger(value[key]) && value[key] >= 0 ? value[key] : 0;
102
100
  status = { count: count("count"), delivery_failures: count("delivery_failures"),
103
- ...(["interrupted_write", "corrupt", "expired", "capacity", "http_rejected"].includes(String(value.reason)) ? { reason: value.reason }
104
- : /^http_4\d\d$/u.test(String(value.reason)) ? { reason: "http_rejected" } : {}),
101
+ ...(["interrupted_write", "corrupt", "expired", "capacity", "http_rejected"].includes(String(value.reason)) ? { reason: value.reason } : {}),
105
102
  ...(["accepted", "http_rejected", "http_retryable", "network_error"].includes(String(value.result)) ? { result: value.result } : {}),
106
103
  ...(typeof value.http_status === "number" && value.http_status >= 100 && value.http_status <= 599 ? { http_status: value.http_status } : {}),
107
104
  ...(count("first_at_ms") ? { first_at_ms: count("first_at_ms") } : {}),
@@ -121,7 +118,7 @@ export function createSlsTelemetrySink(options) {
121
118
  const raw = await readFile(join(options.directory, name), "utf8");
122
119
  try {
123
120
  const entry = JSON.parse(raw);
124
- if (!Number.isFinite(entry.queuedAt) || !entry.event || eventKey(entry.event) !== name.slice(0, -5))
121
+ if (entry.event?.schema_version !== "6" || !Number.isFinite(entry.queuedAt) || !entry.event || eventKey(entry.event) !== name.slice(0, -5))
125
122
  throw new Error();
126
123
  entries.set(name.slice(0, -5), entry);
127
124
  }
@@ -160,7 +157,7 @@ export function createSlsTelemetrySink(options) {
160
157
  }
161
158
  }
162
159
  let size = [...entries.values()].reduce((sum, e) => sum + Buffer.byteLength(JSON.stringify(e)), 0);
163
- const priority = (e) => e.event.event_name === "task_state" || e.event.event_name === "request_sent" || e.event.event_name === "result_ready" ? 2
160
+ const priority = (e) => e.event.event_name === "command_step" ? 2
164
161
  : e.event.event_name === "host_diagnostic" || "outcome" in e.event && e.event.outcome !== "success" ? 1 : 0;
165
162
  for (const [id, entry] of [...entries].sort((a, b) => priority(a[1]) - priority(b[1]) || a[1].queuedAt - b[1].queuedAt)) {
166
163
  checkBudget(deadline);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insmind/cli",
3
- "version": "1.9.1",
3
+ "version": "2.1.0",
4
4
  "description": "insMind command-line interface for agents and people.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -47,8 +47,8 @@
47
47
  "@gaoding/cli": "workspace:*"
48
48
  },
49
49
  "gaodingRelease": {
50
- "sourceCommit": "ad14b59e9789e8e8b7af7b7e38916d920ee0e646",
51
- "pipelineId": "238371",
52
- "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/238371"
50
+ "sourceCommit": "5a8acfd84d3ce5ed311d5442c66ebc6b62c9f680",
51
+ "pipelineId": "241803",
52
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/241803"
53
53
  }
54
54
  }
@@ -7,7 +7,9 @@ description: Use when creating images, videos or text with insMind CLI, operatin
7
7
 
8
8
  ## Discover current capabilities on demand
9
9
 
10
+ - For `agent send`, `tool call` and `editor apply`, set the top-level `host_application` in the input JSON to the calling app, for example `workbuddy`, `qwenwork` or `trae`. Use `terminal` for direct terminal use.
10
11
  - Check `insmind-cli --version` on first use. If the entry point is unclear, read `insmind-cli --help`, follow the relevant command group, then read the chosen command's `--help` before execution. Examples here are not an exhaustive capability list.
12
+ - Relay an available update to the user alongside their foreground result, at most once per hour. For stdout-only hosts, see “Update” below.
11
13
  - For structured input, query `--schema` only where the command exposes it. Discover models, parameter choices, prices and resource IDs through current lists/details rather than old examples. Report missing support or failed discovery without silently replacing explicit user constraints.
12
14
  - Reuse help and static Schema within the same session and CLI path/version; refresh after changing the CLI. Query dynamic metadata when selecting capabilities or quoting prices for this task, and refresh relevant results after identity changes or an explicit mismatch. Avoid unrelated catalog scans.
13
15
  - Discovery describes the installed CLI; it neither upgrades it nor authorizes generation, writes or installation. Recover unknown outcomes through the error-handling reference.
@@ -20,7 +20,7 @@ Completion requires structural and visual verification followed by a successful
20
20
 
21
21
  1. Read `insmind-cli editor connect --help` and choose `insmind-cli editor connect [target]` for the user's intended work. Do not omit the target and create a Board when recovering an existing work. Browser login, loading, edit/save permissions and content checks must pass; stop editing on connection failure.
22
22
  2. Read `insmind-cli editor snapshot`. Base changes on complete elements from the latest Snapshot and change only intended fields. Submit full Updates, never patches.
23
- 3. Build a complete, ordered Action JSON array from the Schema and Snapshot. Run `insmind-cli editor apply --input actions.json`, or use `--input -` for stdin. Use short semantic IDs; Connector direction and targets must preserve business relationships.
23
+ 3. Build an object with `host_application` and an ordered `actions` array from the Schema and Snapshot. Run `insmind-cli editor apply --input actions.json`, or use `--input -` for stdin. Use short semantic IDs; Connector direction and targets must preserve business relationships.
24
24
  4. Read a fresh Snapshot after every Apply. For layout, text or Connector changes, run `insmind-cli editor screenshot --json` and view the actual PNG at its absolute `path`. A file's existence or an accepted Action does not prove correct rendering.
25
25
  5. After structural and visual checks pass, run `insmind-cli editor save --json` and wait for the original command. Do not interrupt during silent periods or issue concurrent Editor operations. Only success proves persistence; deliver the returned `workId` and public `url`, preserving environment parameters. Discover wait limits with `editor save --help`.
26
26
  6. Run `insmind-cli editor disconnect` after saving; disconnecting does not replace saving.
@@ -6,6 +6,7 @@ Generation constraints example:
6
6
 
7
7
  ```json
8
8
  {
9
+ "host_application": "<invoking application>",
9
10
  "message": {
10
11
  "parts": [
11
12
  { "text": "<user request>" },
@@ -22,10 +23,11 @@ Generation constraints example:
22
23
  }
23
24
  ```
24
25
 
25
- `arguments` can be supplied without `model`, allowing the service Agent to select one. With a model, the CLI validates the supplied arguments against live detail; do not fill every Tool-required parameter for an Agent request. Put prompt text in a Text Part and media in separate URL Parts, not in `arguments`. Preserve input Part order. Use `metadata.role` for `reference`, `first_frame` or `last_frame`; do not inject frame-role text. For example:
26
+ `arguments` can be supplied without `model`, allowing the service Agent to select one. With a model, the CLI forwards explicit controls and maps known editing aliases to their service fields. Put prompt text in a Text Part and media in separate URL Parts, not in `arguments`. Preserve input Part order. Use `metadata.role` for `reference`, `first_frame` or `last_frame`; do not inject frame-role text. For example:
26
27
 
27
28
  ```json
28
29
  {
30
+ "host_application": "<invoking application>",
29
31
  "message": {
30
32
  "parts": [
31
33
  { "text": "Generate a transition video" },
@@ -12,14 +12,13 @@ insmind-cli tool call <tool> --input request.json --async
12
12
  insmind-cli task get <taskId>
13
13
  ```
14
14
 
15
- `tool list` lists available Tools. Model discovery provides current descriptions, prices, estimated duration and structured parameters. Follow each parameter's `required`, `type` and `description`; for SELECT parameters use `options[].value`. Explicitly supply a required parameter's `default` when the user did not specify it. Read `usageDescription` for combinations such as video mode and frame/media requirements; individual fields cannot establish these rules. Do not freeze catalog values in prompts or scripts.
16
-
17
- Provide all required fields. Put width, height, resolution and similar requirements in dedicated structured parameters when available, rather than only in prompt text. `tool call <tool> --schema` selects required fields, allowed parameters and ranges by model. Use `model get` for step, defaults and cross-field rules in `usageDescription`. Fixed JSON commands also accept `--json`.
15
+ Read `insmind-cli tool call <tool> --schema` for the input shape and `model get` for the selected model's price and estimated duration. `required` describes required inputs and `default` identifies service defaults. A defaulted field can be omitted when the user did not select a value. Use `options[].value` for a listed option. Put dimensions and resolution in `width`, `height` and `resolution` where available, and preserve explicit user values. Read `usageDescription` for cross-field rules such as video mode and frame roles.
18
16
 
19
17
  Copy the returned `model` identifier into the top-level `model` field of request JSON (runtime `arguments.model`), alongside its parameters:
20
18
 
21
19
  ```json
22
20
  {
21
+ "host_application": "<invoking application>",
23
22
  "model": "<model>",
24
23
  "prompt": "<required prompt>",
25
24
  "<parameter>": "<value>"
@@ -1,5 +1,7 @@
1
1
  # Update
2
2
 
3
+ Relay an update alongside the foreground business result. In a stdout-only host, discover `check` through `insmind-cli update --help`. On first foreground use or after an hour, set `CLI_HOST_APPLICATION` to the actual host, run `insmind-cli update check --json --for-display`, and relay the returned `notice` if present. Ordinary `update check --json` queries do not spend a display slot. For an older CLI, compare its actual version to `npm view @insmind/cli dist-tags.latest` only for a confirmed user installation. Continue the task if the check is unavailable.
4
+
3
5
  When the user requests an upgrade or approves resolving a compatibility issue, discover the current installation channel's update behavior before updating:
4
6
 
5
7
  ```bash