@insmind/cli 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/bin/agent-worker.js +2 -1
  2. package/dist/bin/insmind-cli.js +12 -7
  3. package/dist/bin/postinstall.js +7 -5
  4. package/dist/src/bootstrap/create-cli.js +26 -17
  5. package/dist/src/bootstrap/create-runtime.js +31 -13
  6. package/dist/src/bootstrap/run-agent-worker.js +2 -1
  7. package/dist/src/bootstrap/validators.js +10 -5
  8. package/dist/src/cli/action-binding.js +14 -0
  9. package/dist/src/cli/agent-commands.js +8 -3
  10. package/dist/src/cli/auth-commands.js +1 -1
  11. package/dist/src/cli/credits-command.js +2 -2
  12. package/dist/src/cli/dam-commands.js +51 -52
  13. package/dist/src/cli/editor-commands.js +13 -15
  14. package/dist/src/cli/errors.js +91 -41
  15. package/dist/src/cli/model-commands.js +7 -5
  16. package/dist/src/cli/presenter.js +13 -10
  17. package/dist/src/cli/task-commands.js +13 -5
  18. package/dist/src/cli/tool-commands.js +9 -3
  19. package/dist/src/features/agent/use-cases.js +11 -5
  20. package/dist/src/features/auth/credential-store.js +2 -2
  21. package/dist/src/features/auth/sso-service.js +3 -2
  22. package/dist/src/features/auth/state.js +2 -0
  23. package/dist/src/features/auth/use-cases.js +30 -34
  24. package/dist/src/features/credits/use-cases.js +2 -0
  25. package/dist/src/features/dam/file-downloader.js +38 -16
  26. package/dist/src/features/dam/object-storage.js +23 -11
  27. package/dist/src/features/dam/operation-executor.js +46 -37
  28. package/dist/src/features/dam/registered-uploader.js +39 -29
  29. package/dist/src/features/dam/storage-upload.js +5 -4
  30. package/dist/src/features/dam/use-cases.js +81 -60
  31. package/dist/src/features/editor/bridge-client.js +6 -6
  32. package/dist/src/features/editor/bridge-process.js +2 -1
  33. package/dist/src/features/editor/session-state.js +6 -4
  34. package/dist/src/features/editor/session.js +26 -8
  35. package/dist/src/features/editor/use-cases.js +10 -3
  36. package/dist/src/features/org/use-cases.js +2 -1
  37. package/dist/src/features/task/agent-background.js +1 -0
  38. package/dist/src/features/task/store.js +2 -0
  39. package/dist/src/features/task/use-cases.js +80 -27
  40. package/dist/src/features/tool/catalog.js +11 -5
  41. package/dist/src/features/tool/dynamic-schema.js +9 -7
  42. package/dist/src/features/tool/mns-catalog-adapter.js +7 -23
  43. package/dist/src/features/tool/tool-api-adapter.js +8 -7
  44. package/dist/src/features/tool/use-cases.js +7 -3
  45. package/dist/src/features/update/update-notification.js +75 -70
  46. package/dist/src/features/update/update-service.js +24 -20
  47. package/dist/src/platform/file-lock.js +36 -9
  48. package/dist/src/platform/interruption.js +13 -0
  49. package/dist/src/platform/json-input.js +12 -9
  50. package/dist/src/platform/local-json-file.js +8 -4
  51. package/dist/src/platform/redact.js +7 -1
  52. package/dist/src/platform/remote-protocol.js +2 -2
  53. package/dist/src/platform/safe-upload-file.js +2 -1
  54. package/dist/src/platform/schema-issues.js +8 -0
  55. package/dist/src/platform/signed-http-transport.js +8 -7
  56. package/dist/src/platform/text-output.js +33 -0
  57. package/dist/src/telemetry/invocation.js +19 -4
  58. package/dist/src/telemetry/process-errors.js +14 -4
  59. package/dist/src/telemetry/sanitize.js +4 -2
  60. package/dist/src/telemetry/sls-sink.js +36 -20
  61. package/package.json +4 -4
@@ -1,4 +1,5 @@
1
1
  import { cleanDiagnostic, errorEvidence } from "./sanitize.js";
2
+ import { isInterruption } from "../platform/interruption.js";
2
3
  const detailedStages = {
3
4
  "auth.login": new Set(["authorize", "wait", "identity", "bind"]),
4
5
  "org.switch": new Set(["list", "bind"]),
@@ -9,7 +10,7 @@ const detailedStages = {
9
10
  };
10
11
  export function createTelemetryInvocation(options) {
11
12
  const traceId = options.traceIdFactory();
12
- const startedAt = options.now();
13
+ const startedAt = options.startedAt ?? options.now();
13
14
  let definition;
14
15
  let finished = false;
15
16
  let signal;
@@ -27,7 +28,7 @@ export function createTelemetryInvocation(options) {
27
28
  node_major: options.runtime.nodeMajor };
28
29
  }
29
30
  function classify(error) {
30
- return signal?.aborted && error === signal.reason ? { outcome: "interrupted" } : options.classifyError(error);
31
+ return isInterruption(error, signal) ? { outcome: "interrupted" } : options.classifyError(error);
31
32
  }
32
33
  function errorFields(error) {
33
34
  const c = classify(error);
@@ -60,12 +61,16 @@ export function createTelemetryInvocation(options) {
60
61
  useSignal(next) { signal = next; },
61
62
  annotate(annotation) {
62
63
  for (const [key, value] of Object.entries(annotation)) {
64
+ if (key === "warning_codes" && Array.isArray(value)) {
65
+ context.warning_codes = [...new Set([...(context.warning_codes ?? []), ...value])].slice(0, 20);
66
+ continue;
67
+ }
63
68
  if (value !== undefined)
64
69
  Object.assign(context, { [key]: key === "parameters" ? { ...value } : value });
65
70
  }
66
71
  },
67
72
  creationContext() {
68
- const { record_seq: _seq, occurred_at_ms: _time, parameters: _parameters, content_id: _content, task_id: _task, dify_task_id: _dify, result_state: _state, ...snapshot } = base();
73
+ const { record_seq: _seq, occurred_at_ms: _time, parameters: _parameters, warning_codes: _warnings, invalid_model_count: _invalidModels, content_id: _content, task_id: _task, dify_task_id: _dify, result_state: _state, ...snapshot } = base();
69
74
  return cleanDiagnostic({ ...snapshot, mode: "execute" });
70
75
  },
71
76
  async emit(event) { await publish(remember(event)); },
@@ -92,12 +97,22 @@ export function createTelemetryInvocation(options) {
92
97
  if (finished || !definition)
93
98
  return [];
94
99
  finished = true;
100
+ const causes = [];
101
+ if (completion.outcome !== "success") {
102
+ let error = completion.error;
103
+ for (let depth = 0; error !== undefined && depth < 10 && !causes.includes(error); depth++) {
104
+ causes.push(error);
105
+ error = error instanceof Error ? error.cause : undefined;
106
+ }
107
+ }
95
108
  remember({ ...base(), event_name: "command_finished", outcome: completion.outcome,
96
109
  duration_ms: Math.max(0, options.now() - startedAt),
110
+ ...(completion.outcome === "success" ? {} : {
111
+ failure_stage: failures.find(f => causes.includes(f.error))?.name ?? "unknown"
112
+ }),
97
113
  ...(completion.outcome === "failure" ? errorFields(completion.error) : completion.outcome === "interrupted" && completion.error !== undefined ? errorEvidence(completion.error) : {}),
98
114
  ...(completion.outcome === "failure" ? {
99
115
  error_code: completion.errorCode, error_message: completion.errorMessage,
100
- failure_stage: failures.find(f => f.error === completion.error)?.name ?? "unknown",
101
116
  ...(completion.httpStatus === undefined ? {} : { http_status: completion.httpStatus }),
102
117
  ...(completion.remoteErrorCode === undefined ? {} : { remote_error_code: completion.remoteErrorCode }),
103
118
  ...(completion.remoteErrorBody === undefined ? {} : { remote_error_body: completion.remoteErrorBody })
@@ -1,3 +1,5 @@
1
+ import { classifyTelemetryError, mapCliError } from "../cli/errors.js";
2
+ import { isInterruption } from "../platform/interruption.js";
1
3
  import { randomBytes } from "node:crypto";
2
4
  import { readFile } from "node:fs/promises";
3
5
  import { dirname, join } from "node:path";
@@ -22,15 +24,23 @@ export async function reportProcessError(error, options) {
22
24
  }
23
25
  catch { /* The package file may be unavailable during startup failure. */ }
24
26
  }
27
+ const aborted = isInterruption(error, options.signal);
28
+ const classification = classifyTelemetryError(error, { aborted, product });
29
+ const mapped = mapCliError(error, { aborted, product });
25
30
  const telemetry = createTelemetryInvocation({ cliName: product.commandName, cliVersion: version,
26
31
  env: options.environment ?? (process.env.CLI_TELEMETRY_ENV === "test" ? "test" : "production"),
27
32
  processRole: options.processRole ?? "cli", now: Date.now,
28
- traceIdFactory: () => randomBytes(16).toString("hex"), spanIdFactory: () => randomBytes(8).toString("hex"),
33
+ ...(options.startedAt === undefined ? {} : { startedAt: options.startedAt }),
34
+ traceIdFactory: () => options.traceId ?? randomBytes(16).toString("hex"), spanIdFactory: () => randomBytes(8).toString("hex"),
29
35
  runtime: { os: process.platform, arch: process.arch, nodeMajor: Number(process.versions.node.split(".")[0]) },
30
- classifyError: () => ({ outcome: "failure", errorCode: "INTERNAL_ERROR" }) });
36
+ classifyError: () => classification });
31
37
  telemetry.select({ operation: options.operation });
32
- const events = telemetry.finish({ outcome: "failure", error, errorCode: "INTERNAL_ERROR",
33
- errorMessage: error instanceof Error ? error.message : String(error) });
38
+ const events = telemetry.finish(mapped.kind === "interrupted" ? { outcome: "interrupted", error } : {
39
+ outcome: "failure", error, errorCode: mapped.failure.code, errorMessage: mapped.failure.message,
40
+ ...(classification.httpStatus === undefined ? {} : { httpStatus: classification.httpStatus }),
41
+ ...(classification.remoteErrorCode === undefined ? {} : { remoteErrorCode: classification.remoteErrorCode }),
42
+ ...(classification.remoteErrorBody === undefined ? {} : { remoteErrorBody: classification.remoteErrorBody })
43
+ });
34
44
  const sink = createSlsTelemetrySink({ fetch: globalThis.fetch, trackingUrl: options.trackingUrl ?? product.telemetryUrl,
35
45
  directory: join(options.homeDirectory ?? homedir(), product.stateDirectory, "telemetry") });
36
46
  // Automated process tests persist to their temporary home, without external traffic.
@@ -66,7 +66,9 @@ export function errorEvidence(error) {
66
66
  ...(e.cause === undefined ? [] : [`Caused by: ${describe(e.cause, depth + 1)}`]),
67
67
  ...(e instanceof AggregateError ? e.errors.slice(0, 10).map(x => describe(x, depth + 1)) : [])].join("\n");
68
68
  }
69
+ const message = cleanText(error instanceof Error ? error.message : String(error));
70
+ const stack = cleanText(describe(error));
69
71
  return { error_type: error instanceof Error ? error.name : typeof error,
70
- error_message: cleanText(error instanceof Error ? error.message : String(error)).slice(0, 8192),
71
- error_stack: cleanText(describe(error)).slice(0, 8192) };
72
+ error_message: message.slice(0, 8192), error_stack: stack.slice(0, 8192),
73
+ ...(message.length > 8192 || stack.length > 8192 ? { truncated: true } : {}) };
72
74
  }
@@ -21,8 +21,8 @@ export function wireEvent(event) {
21
21
  wire[key] = typeof value === "object" ? JSON.stringify(value) : String(value);
22
22
  }
23
23
  for (const key of ["error_stack", "remote_error_body", "error_message"]) {
24
- if (wire[key] && wire[key].length > 8192) {
25
- wire[key] = wire[key].slice(0, 8192);
24
+ if (wire[key] && Buffer.byteLength(wire[key]) > 8192) {
25
+ wire[key] = utf8Prefix(wire[key], 8192);
26
26
  wire.truncated = "true";
27
27
  }
28
28
  }
@@ -59,15 +59,21 @@ export function createSlsTelemetrySink(options) {
59
59
  const entries = new Map();
60
60
  let writes = Promise.resolve();
61
61
  const file = (id) => createLocalJsonFile({ directory: options.directory, filename: `${id}.json` });
62
- const locked = (run) => options.directory
63
- ? withFileLock(join(options.directory, ".lock"), run) : run();
64
- async function load() {
62
+ let exitDeadline = Infinity;
63
+ const locked = (run, deadline) => options.directory
64
+ ? withFileLock(join(options.directory, ".lock"), run, { deadline: Math.min(deadline ?? Infinity, exitDeadline) }) : run();
65
+ function checkBudget(deadline) {
66
+ if (Date.now() >= deadline)
67
+ throw new Error("Telemetry delivery budget exhausted.");
68
+ }
69
+ async function load(deadline = exitDeadline) {
65
70
  if (!options.directory)
66
71
  return;
67
72
  entries.clear();
68
73
  await mkdir(options.directory, { recursive: true, mode: 0o700 });
69
74
  await chmod(options.directory, 0o700);
70
75
  for (const name of await readdir(options.directory)) {
76
+ checkBudget(deadline);
71
77
  // All writers hold the same lock, so remaining atomic-write temporaries are orphaned.
72
78
  if (/^(?:[a-f0-9]{64}|delivery-status)\.json\.tmp-[a-f0-9-]+$/u.test(name)) {
73
79
  await unlink(join(options.directory, name)).catch(() => undefined);
@@ -76,8 +82,10 @@ export function createSlsTelemetrySink(options) {
76
82
  }
77
83
  if (!/^[a-f0-9]{64}\.json$/u.test(name))
78
84
  continue;
85
+ // An unreadable valid record is not corrupt and must survive for replay.
86
+ const raw = await readFile(join(options.directory, name), "utf8");
79
87
  try {
80
- const entry = JSON.parse(await readFile(join(options.directory, name), "utf8"));
88
+ const entry = JSON.parse(raw);
81
89
  if (!Number.isFinite(entry.queuedAt) || !entry.event || eventKey(entry.event) !== name.slice(0, -5))
82
90
  throw new Error();
83
91
  entries.set(name.slice(0, -5), entry);
@@ -110,8 +118,9 @@ export function createSlsTelemetrySink(options) {
110
118
  if (options.directory)
111
119
  await file(id).writeTextAtomically(JSON.stringify(entry));
112
120
  }
113
- async function trim() {
121
+ async function trim(deadline = exitDeadline) {
114
122
  for (const [id, entry] of entries) {
123
+ checkBudget(deadline);
115
124
  if (now() - entry.queuedAt > (options.retentionMs ?? TTL)) {
116
125
  await remove(id);
117
126
  await dropped("expired", 1);
@@ -121,6 +130,7 @@ export function createSlsTelemetrySink(options) {
121
130
  const priority = (e) => e.event.event_name === "request_sent" || e.event.event_name === "result_ready" ? 2
122
131
  : "outcome" in e.event && e.event.outcome !== "success" ? 1 : 0;
123
132
  for (const [id, entry] of [...entries].sort((a, b) => priority(a[1]) - priority(b[1]) || a[1].queuedAt - b[1].queuedAt)) {
133
+ checkBudget(deadline);
124
134
  if (size <= (options.maxBytes ?? CAPACITY))
125
135
  break;
126
136
  size -= Buffer.byteLength(JSON.stringify(entry));
@@ -128,21 +138,24 @@ export function createSlsTelemetrySink(options) {
128
138
  await dropped("capacity", 1);
129
139
  }
130
140
  }
131
- function enqueue(events) {
141
+ function enqueue(events, deadline) {
142
+ if (events.length === 0)
143
+ return writes;
132
144
  writes = writes.catch(() => undefined).then(() => locked(async () => {
133
- await load();
145
+ await load(deadline);
134
146
  for (const event of events) {
147
+ checkBudget(deadline ?? exitDeadline);
135
148
  const id = eventKey(event);
136
149
  if (entries.has(id))
137
150
  continue;
138
151
  // Persist the sanitized, bounded wire payload and replay it unchanged.
139
152
  await persist(id, { event: wireEvent(event), queuedAt: now(), nextAttempt: 0, attempts: 0 });
140
153
  }
141
- await trim();
142
- })).catch(() => undefined);
143
- if (options.background)
154
+ await trim(deadline);
155
+ }, deadline)).catch(() => undefined);
156
+ if (options.background && deadline === undefined)
144
157
  void writes.then(() => { if (!sending)
145
- void start(Date.now() + BUDGET); });
158
+ void start(Math.min(Date.now() + BUDGET, exitDeadline)); });
146
159
  return writes;
147
160
  }
148
161
  let sending;
@@ -150,14 +163,14 @@ export function createSlsTelemetrySink(options) {
150
163
  for (let attempt = 0; attempt < 2 && Date.now() < deadline; attempt++) {
151
164
  let batch = [];
152
165
  await locked(async () => {
153
- await load();
154
- await trim();
166
+ await load(deadline);
167
+ await trim(deadline);
155
168
  let bytes = 0;
156
169
  batch = [...entries].filter(([, e]) => e.nextAttempt <= now()).filter(([, e]) => {
157
170
  bytes += Buffer.byteLength(JSON.stringify(e.event));
158
171
  return bytes <= 512 * 1024;
159
172
  }).slice(0, 100);
160
- });
173
+ }, deadline);
161
174
  if (!batch.length || Date.now() >= deadline)
162
175
  return;
163
176
  let response;
@@ -181,9 +194,12 @@ export function createSlsTelemetrySink(options) {
181
194
  catch { /* Retain the original records for the next invocation. */ }
182
195
  const accepted = response?.ok === true;
183
196
  const rejected = response !== undefined && response.status >= 400 && response.status < 500 && response.status !== 429;
197
+ if (Date.now() >= deadline)
198
+ return; // Original records remain safe for at-least-once replay.
184
199
  await locked(async () => {
185
- await load();
200
+ await load(deadline);
186
201
  for (const [id, original] of batch) {
202
+ checkBudget(deadline);
187
203
  const entry = entries.get(id);
188
204
  if (!entry)
189
205
  continue;
@@ -195,7 +211,7 @@ export function createSlsTelemetrySink(options) {
195
211
  }
196
212
  if (rejected)
197
213
  await dropped(`http_${response.status}`, batch.length);
198
- });
214
+ }, deadline);
199
215
  if (!accepted && (retryAfter > 0 || rejected))
200
216
  return;
201
217
  }
@@ -206,8 +222,8 @@ export function createSlsTelemetrySink(options) {
206
222
  }
207
223
  return { enqueue,
208
224
  async send(events) {
209
- const deadline = Date.now() + BUDGET;
210
- await enqueue(events);
225
+ const deadline = exitDeadline = Date.now() + BUDGET;
226
+ await enqueue(events, deadline);
211
227
  if (sending)
212
228
  await sending;
213
229
  if (Date.now() < deadline)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insmind/cli",
3
- "version": "1.5.0",
3
+ "version": "1.5.2",
4
4
  "description": "insMind command-line interface for agents and people.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -46,8 +46,8 @@
46
46
  "@gaoding/cli": "workspace:*"
47
47
  },
48
48
  "gaodingRelease": {
49
- "sourceCommit": "20512692303b4ceff9b97871902c5ba126bdb894",
50
- "pipelineId": "188672",
51
- "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/188672"
49
+ "sourceCommit": "32186c832d858f979844b8ae1c456a19d01576e1",
50
+ "pipelineId": "189711",
51
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/189711"
52
52
  }
53
53
  }