@insmind/cli 2.0.0 → 2.1.1

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 (113) hide show
  1. package/README.md +5 -0
  2. package/contracts/operations/agent.send/input.schema.json +1 -77
  3. package/contracts/operations/credits.get/input.schema.json +8 -0
  4. package/contracts/operations/credits.get/output.schema.json +92 -0
  5. package/contracts/operations/credits.usage.get/input.schema.json +17 -0
  6. package/contracts/operations/credits.usage.get/output.schema.json +46 -0
  7. package/contracts/operations/credits.usage.list/input.schema.json +27 -0
  8. package/contracts/operations/credits.usage.list/output.schema.json +135 -0
  9. package/contracts/operations/dam.folder.list/input.schema.json +0 -1
  10. package/contracts/operations/dam.folder.list/output.schema.json +1 -2
  11. package/contracts/operations/dam.list/input.schema.json +3 -6
  12. package/contracts/operations/dam.list/output.schema.json +1 -2
  13. package/contracts/operations/dam.search/input.schema.json +3 -6
  14. package/contracts/operations/dam.search/output.schema.json +1 -2
  15. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
  16. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
  17. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
  18. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
  19. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  20. package/dist/bin/postinstall.js +22 -6
  21. package/dist/bin/task-worker.js +2 -2
  22. package/dist/src/bootstrap/create-cli.js +31 -15
  23. package/dist/src/bootstrap/create-runtime.js +103 -30
  24. package/dist/src/bootstrap/run-task-worker.js +6 -2
  25. package/dist/src/bootstrap/validators.js +4 -1
  26. package/dist/src/cli/action-binding.js +17 -50
  27. package/dist/src/cli/agent-commands.js +11 -11
  28. package/dist/src/cli/auth-commands.js +2 -1
  29. package/dist/src/cli/creation-help.js +9 -0
  30. package/dist/src/cli/credits-command.js +127 -16
  31. package/dist/src/cli/dam-commands.js +10 -14
  32. package/dist/src/cli/editor-commands.js +7 -5
  33. package/dist/src/cli/errors.js +81 -22
  34. package/dist/src/cli/host-input.js +64 -5
  35. package/dist/src/cli/model-commands.js +9 -3
  36. package/dist/src/cli/observed-errors.js +7 -3
  37. package/dist/src/cli/org-commands.js +3 -1
  38. package/dist/src/cli/presenter.js +4 -0
  39. package/dist/src/cli/task-commands.js +6 -2
  40. package/dist/src/cli/tool-commands.js +12 -11
  41. package/dist/src/cli/update-command.js +24 -1
  42. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  43. package/dist/src/features/agent/creative-protocol.js +8 -29
  44. package/dist/src/features/agent/resource-authorizer.js +25 -17
  45. package/dist/src/features/agent/result-reader.js +31 -14
  46. package/dist/src/features/agent/use-cases.js +6 -31
  47. package/dist/src/features/credits/amount.js +51 -0
  48. package/dist/src/features/credits/response.js +11 -0
  49. package/dist/src/features/credits/use-cases.js +200 -30
  50. package/dist/src/features/dam/asset-projection.js +3 -6
  51. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  52. package/dist/src/features/dam/repository-catalog.js +30 -21
  53. package/dist/src/features/dam/use-cases.js +12 -7
  54. package/dist/src/features/editor/bridge-client.js +0 -2
  55. package/dist/src/features/editor/public-url.js +1 -36
  56. package/dist/src/features/editor/session.js +3 -2
  57. package/dist/src/features/editor/use-cases.js +27 -2
  58. package/dist/src/features/org/org-service.js +10 -1
  59. package/dist/src/features/org/use-cases.js +18 -4
  60. package/dist/src/features/task/process-owner.js +54 -0
  61. package/dist/src/features/task/store.js +37 -10
  62. package/dist/src/features/task/task-background.js +5 -2
  63. package/dist/src/features/task/use-cases.js +184 -84
  64. package/dist/src/features/tool/argument-paths.js +14 -0
  65. package/dist/src/features/tool/canvas-copy.js +28 -15
  66. package/dist/src/features/tool/canvas-matting.js +123 -0
  67. package/dist/src/features/tool/canvas-media.js +100 -52
  68. package/dist/src/features/tool/canvas-models.js +66 -33
  69. package/dist/src/features/tool/canvas-pricing.js +12 -0
  70. package/dist/src/features/tool/canvas-recovery.js +13 -30
  71. package/dist/src/features/tool/canvas-results.js +79 -87
  72. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  73. package/dist/src/features/tool/canvas-video.js +44 -37
  74. package/dist/src/features/tool/dynamic-schema.js +39 -40
  75. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  76. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  77. package/dist/src/features/tool/resource-authorizer.js +11 -3
  78. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  79. package/dist/src/features/tool/tool-errors.js +25 -0
  80. package/dist/src/features/tool/tool-output.js +15 -0
  81. package/dist/src/features/tool/use-cases.js +74 -98
  82. package/dist/src/features/update/check-schema.js +17 -0
  83. package/dist/src/features/update/host-receipt.js +30 -0
  84. package/dist/src/features/update/notice-output.js +30 -0
  85. package/dist/src/features/update/update-lock.js +80 -0
  86. package/dist/src/features/update/update-notification.js +129 -240
  87. package/dist/src/features/update/update-service.js +95 -21
  88. package/dist/src/platform/media-type.js +46 -0
  89. package/dist/src/platform/public-url.js +35 -0
  90. package/dist/src/platform/remote-error-evidence.js +33 -6
  91. package/dist/src/platform/resource-auth-key.js +35 -1
  92. package/dist/src/platform/safe-upload-file.js +36 -41
  93. package/dist/src/platform/signature.js +3 -1
  94. package/dist/src/platform/signed-http-transport.js +14 -6
  95. package/dist/src/platform/url-safety.js +6 -1
  96. package/dist/src/platform/webm-header.js +41 -0
  97. package/dist/src/telemetry/command-route.js +38 -0
  98. package/dist/src/telemetry/command-routes.json +1 -0
  99. package/dist/src/telemetry/failure-summary.js +1 -1
  100. package/dist/src/telemetry/invocation.js +1 -2
  101. package/dist/src/telemetry/process-errors.js +17 -33
  102. package/dist/src/telemetry/sanitize.js +19 -4
  103. package/dist/src/telemetry/sls-sink.js +8 -0
  104. package/package.json +4 -4
  105. package/skills/insmind-cli/SKILL.md +19 -5
  106. package/skills/insmind-cli/references/agent.md +9 -4
  107. package/skills/insmind-cli/references/creation.md +3 -1
  108. package/skills/insmind-cli/references/editor.md +7 -5
  109. package/skills/insmind-cli/references/errors.md +20 -9
  110. package/skills/insmind-cli/references/matting.md +3 -5
  111. package/skills/insmind-cli/references/media-tools.md +10 -4
  112. package/skills/insmind-cli/references/tool.md +9 -15
  113. package/skills/insmind-cli/references/update.md +2 -0
@@ -3,7 +3,13 @@ const maximumLength = 8_192;
3
3
  const truncationMarker = "[TRUNCATED]";
4
4
  export function remoteErrorEvidence(value) {
5
5
  const normalized = parseJson(value);
6
- const remoteCode = topLevelCode(normalized) ?? jsonRpcErrorCode(normalized) ?? mcpErrorContentCode(normalized);
6
+ const envelopeCode = topLevelCode(normalized) ?? jsonRpcErrorCode(normalized);
7
+ const mcp = envelopeCode === undefined ? mcpErrorContent(normalized) : undefined;
8
+ const remoteCode = envelopeCode ?? mcp?.remoteCode;
9
+ if (mcp?.imagePixelRequirement) {
10
+ // The provider text can embed the source URL, prompt, request ID and stack.
11
+ return { ...mcp, remoteBody: JSON.stringify({ code: remoteCode, ...mcp.imagePixelRequirement }) };
12
+ }
7
13
  const diagnosticReason = imageAuditTimeout(normalized, remoteCode);
8
14
  const sanitized = sanitize(normalized);
9
15
  if (sanitized === undefined) {
@@ -47,10 +53,11 @@ function jsonRpcErrorCode(value) {
47
53
  }
48
54
  return normalizeCode(record.error.code);
49
55
  }
50
- function mcpErrorContentCode(value) {
56
+ function mcpErrorContent(value) {
51
57
  if (value === null || typeof value !== "object" || Array.isArray(value))
52
58
  return undefined;
53
- const result = value.result;
59
+ const envelope = value;
60
+ const result = envelope.result;
54
61
  if (result === null || typeof result !== "object" || Array.isArray(result))
55
62
  return undefined;
56
63
  const record = result;
@@ -63,12 +70,32 @@ function mcpErrorContentCode(value) {
63
70
  || typeof item.text !== "string" || item.text.length > maximumLength)
64
71
  continue;
65
72
  const error = parseJson(item.text);
66
- const code = topLevelCode(error) ?? jsonRpcErrorCode(error);
67
- if (code !== undefined)
68
- return code;
73
+ const directCode = topLevelCode(error);
74
+ const code = directCode ?? jsonRpcErrorCode(error);
75
+ if (code === undefined)
76
+ continue;
77
+ const requirement = directCode === "12020700" && !Object.hasOwn(envelope, "error")
78
+ && (envelope.jsonrpc === undefined || envelope.jsonrpc === "2.0") ? imagePixelRequirement(error) : undefined;
79
+ return { remoteCode: code, ...(requirement ? { imagePixelRequirement: requirement } : {}) };
69
80
  }
70
81
  return undefined;
71
82
  }
83
+ function imagePixelRequirement(error) {
84
+ if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string")
85
+ return;
86
+ const providerCode = /\bInvalidParameter\b/u.exec(error.message);
87
+ if (!providerCode)
88
+ return;
89
+ const message = error.message.slice(providerCode.index + providerCode[0].length);
90
+ const match = /\bexpected the pixel to be at least ([1-9]\d{0,15})px,\s*but received an? ([1-9]\d{0,15})x([1-9]\d{0,15})px image instead\b/iu.exec(message);
91
+ if (!match)
92
+ return;
93
+ const minimumPixels = Number(match[1]);
94
+ const width = Number(match[2]);
95
+ const height = Number(match[3]);
96
+ if (Number.isSafeInteger(minimumPixels) && width * height < minimumPixels)
97
+ return { minimumPixels, width, height };
98
+ }
72
99
  function normalizeCode(code) {
73
100
  if (typeof code === "string")
74
101
  return redactRemoteText(code);
@@ -1 +1,35 @@
1
- export {};
1
+ import { RemoteProtocolError } from "./remote-protocol.js";
2
+ /** FileMS keys are valid only on the verified HTTPS resource origins. */
3
+ export function isFilemsResource(url) {
4
+ const privateHost = /^gd-ai-[a-z0-9-]+\.dancf\.com$/iu.test(url.hostname)
5
+ || /^gdesign-dam(?:-[a-z0-9-]+)?\.dancf\.com$/iu.test(url.hostname)
6
+ || url.hostname === "dify-grsai.dancf.com"
7
+ || url.hostname === "dify-aiznt.dancf.com";
8
+ if (!privateHost)
9
+ return false;
10
+ if (url.protocol !== "https:" || url.username || url.password || url.port) {
11
+ throw new RemoteProtocolError({}, undefined, "RESOURCE_AUTH_URL_UNSAFE");
12
+ }
13
+ return true;
14
+ }
15
+ /** The rest of a signed URL is opaque: URLSearchParams.set would also re-encode unrelated values. */
16
+ export function withFilemsAuthKey(uri, authKey) {
17
+ const hash = uri.indexOf("#");
18
+ const [beforeHash, fragment] = hash < 0 ? [uri, ""] : [uri.slice(0, hash), uri.slice(hash)];
19
+ const query = beforeHash.indexOf("?");
20
+ const base = query < 0 ? beforeHash : beforeHash.slice(0, query);
21
+ const raw = query < 0 ? "" : beforeHash.slice(query + 1);
22
+ const fields = raw ? raw.split("&") : [];
23
+ const token = encodeURIComponent(authKey);
24
+ let present = false;
25
+ const updated = fields.map(field => {
26
+ const name = field.split("=", 1)[0];
27
+ if (new URLSearchParams("name=" + name).get("name") !== "auth_key")
28
+ return field;
29
+ present = true;
30
+ return name + "=" + token;
31
+ });
32
+ if (!present)
33
+ updated.push("auth_key=" + token);
34
+ return base + "?" + updated.join("&") + fragment;
35
+ }
@@ -1,3 +1,6 @@
1
+ import { validateHeaderValue } from "node:http";
2
+ import { concreteMediaType, mediaTypeForFormat } from "./media-type.js";
3
+ import { hasWebmDocType } from "./webm-header.js";
1
4
  import { isInterruption } from "./interruption.js";
2
5
  import { open, realpath, stat } from "node:fs/promises";
3
6
  import { basename, extname, sep } from "node:path";
@@ -20,6 +23,7 @@ const protectedSegments = new Set([
20
23
  ".docker",
21
24
  ".gd",
22
25
  ".gd-cli-dev",
26
+ ".insmind",
23
27
  ".git",
24
28
  ".gnupg",
25
29
  ".kube",
@@ -39,29 +43,16 @@ const protectedFilenames = new Set([
39
43
  "id_rsa",
40
44
  "known_hosts"
41
45
  ]);
42
- const mediaTypes = {
43
- avif: "image/avif",
44
- bmp: "image/bmp",
45
- gif: "image/gif",
46
- heic: "image/heic",
47
- heif: "image/heif",
48
- jpeg: "image/jpeg",
49
- m4v: "video/x-m4v",
50
- mkv: "video/x-matroska",
51
- mov: "video/quicktime",
52
- mp4: "video/mp4",
53
- png: "image/png",
54
- svg: "image/svg+xml",
55
- webm: "video/webm",
56
- webp: "image/webp"
57
- };
58
46
  function reject(reason) {
59
47
  throw new LocalFileInputError(undefined, reason);
60
48
  }
61
49
  function assertSafePath(filePath) {
62
50
  const segments = filePath.split(sep).filter(Boolean).map((segment) => segment.toLowerCase());
63
51
  const filename = segments.at(-1) ?? "";
64
- if (protectedFilenames.has(filename) || filename.startsWith(".")
52
+ const parent = segments.at(-2);
53
+ const hostCredential = (parent === ".codex" && filename === "auth.json")
54
+ || (parent === ".gemini" && filename === "oauth_creds.json");
55
+ if (hostCredential || protectedFilenames.has(filename) || filename.startsWith(".")
65
56
  || segments.some(segment => protectedSegments.has(segment))) {
66
57
  reject("path_restricted");
67
58
  }
@@ -80,10 +71,15 @@ function detectedFormat(header) {
80
71
  if (signature === "GIF87a" || signature === "GIF89a")
81
72
  return "gif";
82
73
  }
83
- if (header.length >= 12
84
- && header.subarray(0, 4).toString("ascii") === "RIFF"
85
- && header.subarray(8, 12).toString("ascii") === "WEBP")
86
- return "webp";
74
+ if (header.length >= 12 && header.toString("latin1", 0, 4) === "RIFF") {
75
+ const kind = header.toString("latin1", 8, 12);
76
+ if (kind === "WEBP")
77
+ return "webp";
78
+ if (kind === "WAVE")
79
+ return "wav";
80
+ }
81
+ if (hasWebmDocType(header))
82
+ return "webm";
87
83
  if (header.length >= 12 && header.subarray(4, 8).toString("ascii") === "ftyp") {
88
84
  const brand = header.subarray(8, 12).toString("ascii");
89
85
  if (["isom", "iso2", "iso5", "iso6", "mp41", "mp42", "avc1", "dash"].includes(brand))
@@ -103,7 +99,8 @@ async function readHeader(filePath, signal) {
103
99
  signal.throwIfAborted();
104
100
  const handle = await open(filePath, "r");
105
101
  try {
106
- const buffer = Buffer.alloc(32);
102
+ // Read a bounded prefix; the WebM DocType can extend past a 32-byte prefix.
103
+ const buffer = Buffer.alloc(4096);
107
104
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
108
105
  signal.throwIfAborted();
109
106
  return buffer.subarray(0, bytesRead);
@@ -135,31 +132,29 @@ export async function inspectUploadFile(input) {
135
132
  return reject("not_regular_file");
136
133
  const header = await readHeader(filePath, input.signal);
137
134
  const detected = detectedFormat(header);
138
- // Hidden host/workspace ancestors are not themselves secrets. Only known
139
- // media headers may pass there; named credential paths remain blocked on
140
- // both requested and canonical paths before any file is opened.
141
- if (input.allowSensitivePath !== true && detected === undefined
142
- && [requestedPath, filePath].some(path => path.split(sep).some(segment => segment.startsWith(".")))) {
143
- return reject("path_restricted");
144
- }
145
135
  const extension = extname(requestedPath).slice(1).toLowerCase();
146
- const format = detected ?? (extension === "jpg" ? "jpeg" : extension);
147
- if (format === "")
148
- return reject("format_missing");
149
- const detectedMediaType = detected === undefined ? undefined : mediaTypes[detected];
150
- if (detectedMediaType !== undefined
151
- && input.claimedMediaType !== undefined
152
- && input.claimedMediaType.trim().toLowerCase() !== detectedMediaType) {
153
- return reject("media_type_mismatch");
136
+ const declaration = input.claimedMediaType;
137
+ if (declaration !== undefined) {
138
+ try {
139
+ validateHeaderValue("Content-Type", declaration);
140
+ }
141
+ catch {
142
+ return reject("invalid_media_type_header");
143
+ }
154
144
  }
145
+ const claimed = concreteMediaType(declaration);
146
+ const subtype = claimed?.split("/")[1];
147
+ const declaredFormat = claimed === "image/svg+xml" ? "svg" : claimed === "video/quicktime" ? "mov"
148
+ : subtype && /^[a-z0-9]+$/u.test(subtype) ? subtype : undefined;
149
+ const format = detected ?? (extension === "jpg" ? "jpeg" : extension || declaredFormat || "bin");
155
150
  return {
156
151
  filePath,
157
152
  filename: basename(requestedPath),
158
153
  format,
159
- mediaType: detectedMediaType
160
- ?? input.claimedMediaType
161
- ?? mediaTypes[format]
162
- ?? `application/${format}`,
154
+ mediaType: declaration
155
+ ?? (detected ? mediaTypeForFormat(detected) : undefined)
156
+ ?? mediaTypeForFormat(format)
157
+ ?? (format === "bin" ? "application/octet-stream" : `application/${format}`),
163
158
  size: details.size
164
159
  };
165
160
  }
@@ -7,7 +7,9 @@ export function canonicalizeQuery(entries) {
7
7
  .replaceAll("%3A", ":");
8
8
  }
9
9
  export function createSigningString(input) {
10
- return `${input.method.toUpperCase()}@${input.pathname}@${input.canonicalQuery}@${input.timestamp}`;
10
+ // The gateway signs decoded form values. On the wire, a space is + and a literal plus is %2B.
11
+ const signingQuery = decodeURIComponent(input.canonicalQuery.replaceAll("+", " "));
12
+ return `${input.method.toUpperCase()}@${input.pathname}@${signingQuery}@${input.timestamp}`;
11
13
  }
12
14
  export function signRequest(input) {
13
15
  return hmac(input.secretKey, createSigningString(input));
@@ -195,24 +195,29 @@ export function createSignedHttpTransport(options) {
195
195
  }, error, diagnosticReason, { ...received.diagnostics(), ...summary });
196
196
  }
197
197
  }
198
- async function json(received) {
198
+ async function json(received, sensitiveResponse = false, parseJson = JSON.parse) {
199
199
  const { response } = received;
200
200
  const body = await readText(received);
201
- 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;
202
206
  if (!response.ok)
203
207
  throw new RemoteRequestError(response.status, false, evidence, undefined, undefined, received.diagnostics());
204
208
  try {
205
- return JSON.parse(body);
209
+ return parseJson(body);
206
210
  }
207
211
  catch (error) {
208
- 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"), {
209
214
  status: response.status, diagnosticSummary: received.diagnostics()
210
215
  });
211
216
  }
212
217
  }
213
218
  async function getJsonResponse(request) {
214
219
  const received = await send("GET", request, "application/json", undefined, true);
215
- 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 };
216
221
  }
217
222
  return {
218
223
  async getJson(request) {
@@ -230,7 +235,10 @@ export function createSignedHttpTransport(options) {
230
235
  const { response } = received;
231
236
  if (!response.ok) {
232
237
  const body = await readText(received);
233
- throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body), undefined, undefined, received.diagnostics());
238
+ const original = remoteErrorEvidence(body);
239
+ const evidence = request.sensitiveResponse
240
+ ? (original.remoteCode === undefined ? {} : { remoteCode: original.remoteCode }) : original;
241
+ throw new RemoteRequestError(response.status, false, evidence, undefined, undefined, received.diagnostics());
234
242
  }
235
243
  if (!response.body)
236
244
  throw new RemoteRequestError(response.status, false, {}, undefined, "RESPONSE_BODY_MISSING", received.diagnostics());
@@ -65,7 +65,7 @@ function isPrivateIpv6(parts) {
65
65
  }
66
66
  return unspecified || loopback || uniqueLocal || linkLocal;
67
67
  }
68
- export function parseSafeRemoteAssetUrl(value) {
68
+ export function parseHttpAssetUrl(value) {
69
69
  let url;
70
70
  try {
71
71
  url = new URL(value);
@@ -78,6 +78,11 @@ export function parseSafeRemoteAssetUrl(value) {
78
78
  || url.password !== "") {
79
79
  return fail();
80
80
  }
81
+ return url;
82
+ }
83
+ /** Only a process that opens the URL needs to enforce the local network boundary. */
84
+ export function parseSafeRemoteAssetUrl(value) {
85
+ const url = parseHttpAssetUrl(value);
81
86
  const hostname = url.hostname
82
87
  .replace(/^\[|\]$/g, "")
83
88
  .replace(/[.]+$/, "")
@@ -0,0 +1,41 @@
1
+ function vintWidth(first) {
2
+ if (!first)
3
+ return 0;
4
+ // The leading marker bit determines the width of an EBML variable-size integer.
5
+ return Math.clz32(first) - 23;
6
+ }
7
+ function ebmlPayload(bytes, sizeOffset, limit) {
8
+ const width = vintWidth(bytes[sizeOffset]);
9
+ const start = sizeOffset + width;
10
+ if (!width || start > limit)
11
+ return;
12
+ let length = bytes[sizeOffset] & (0xff >>> width);
13
+ for (let i = sizeOffset + 1; i < start; i++)
14
+ length = length * 256 + bytes[i];
15
+ if (length > limit - start || length === 2 ** (7 * width) - 1)
16
+ return;
17
+ return { start, end: start + length };
18
+ }
19
+ export function hasWebmDocType(bytes) {
20
+ if (bytes.length < 5 || bytes.readUInt32BE(0) !== 0x1a45dfa3)
21
+ return false;
22
+ const header = ebmlPayload(bytes, 4, bytes.length);
23
+ if (!header)
24
+ return false;
25
+ let found = false;
26
+ for (let offset = header.start; offset < header.end;) {
27
+ const idWidth = vintWidth(bytes[offset]);
28
+ if (!idWidth || idWidth > 4)
29
+ return false;
30
+ const field = ebmlPayload(bytes, offset + idWidth, header.end);
31
+ if (!field)
32
+ return false;
33
+ if (idWidth === 2 && bytes.readUInt16BE(offset) === 0x4282) {
34
+ if (found || field.end - field.start !== 4 || bytes.toString("latin1", field.start, field.end) !== "webm")
35
+ return false;
36
+ found = true;
37
+ }
38
+ offset = field.end;
39
+ }
40
+ return found;
41
+ }
@@ -0,0 +1,38 @@
1
+ import { Command } from "commander";
2
+ /** Read only argv. Commander owns option arity, the -- separator and the choice of subcommand. */
3
+ export function identifyInvocation(root, argv) {
4
+ let route = root;
5
+ let operands = [];
6
+ let unknown = argv;
7
+ let schema = false;
8
+ const selected = (operation, mode) => ({ operation, mode: () => mode });
9
+ while (true) {
10
+ // Parse the option declarations on a disposable command; the real flags, actions and I/O are untouched.
11
+ const parser = new Command().exitOverride().configureOutput({ writeErr() { } });
12
+ for (const flags of route.options)
13
+ parser.option(flags);
14
+ let parsed;
15
+ try {
16
+ parsed = parser.parseOptions(unknown);
17
+ }
18
+ catch {
19
+ if (parser.opts().version)
20
+ return selected("version", "version");
21
+ return selected(route.operation, schema || parser.opts().schema ? "schema" : "execute");
22
+ }
23
+ if (parser.opts().version)
24
+ return selected("version", "version");
25
+ schema ||= parser.opts().schema === true;
26
+ operands = operands.concat(parsed.operands);
27
+ unknown = parsed.unknown;
28
+ const name = operands[0];
29
+ if (name && Object.hasOwn(route.children, name)) {
30
+ route = route.children[name];
31
+ operands = operands.slice(1);
32
+ continue;
33
+ }
34
+ if (unknown.includes("--help") || unknown.includes("-h"))
35
+ return selected(route === root ? "help" : route.operation, "help");
36
+ return selected(name && !route.action ? "unknown" : route.operation, schema ? "schema" : "execute");
37
+ }
38
+ }
@@ -0,0 +1 @@
1
+ {"operation":"unknown","action":false,"options":["-V, --version","--json-errors","--locale <locale>"],"children":{"auth":{"operation":"auth","action":false,"options":[],"children":{"login":{"operation":"auth.login","action":true,"options":["--no-browser","--require-browser"],"children":{}},"status":{"operation":"auth.status","action":true,"options":["--json"],"children":{}},"logout":{"operation":"auth.logout","action":true,"options":[],"children":{}}}},"agent":{"operation":"agent","action":false,"options":[],"children":{"send":{"operation":"agent.send","action":true,"options":["--schema","--input <file|->","--async","--json"],"children":{}}}},"tool":{"operation":"tool","action":false,"options":[],"children":{"list":{"operation":"tool.list","action":true,"options":["--json"],"children":{}},"call":{"operation":"tool.call","action":true,"options":["--schema","--input <file|->","--async","--json"],"children":{}}}},"model":{"operation":"model","action":false,"options":[],"children":{"list":{"operation":"model.list","action":true,"options":["--tool <tool>","--json"],"children":{}},"get":{"operation":"model.get","action":true,"options":["--tool <tool>","--json"],"children":{}}}},"editor":{"operation":"editor","action":false,"options":[],"children":{"connect":{"operation":"editor.connect","action":true,"options":["--json"],"children":{}},"disconnect":{"operation":"editor.disconnect","action":true,"options":["--json"],"children":{}},"snapshot":{"operation":"editor.snapshot","action":true,"options":["--json"],"children":{}},"apply":{"operation":"editor.apply","action":true,"options":["--schema","--input <file|->","--json"],"children":{}},"screenshot":{"operation":"editor.screenshot","action":true,"options":["--json"],"children":{}},"save":{"operation":"editor.save","action":true,"options":["--json"],"children":{}}}},"dam":{"operation":"dam","action":false,"options":[],"children":{"repository":{"operation":"dam.repository","action":false,"options":[],"children":{"list":{"operation":"dam.repository.list","action":true,"options":["--json"],"children":{}}}},"folder":{"operation":"dam.folder","action":false,"options":[],"children":{"list":{"operation":"dam.folder.list","action":true,"options":["--repository-id <id>","--parent-id <id>","--query <text>","--page <n>","--page-size <number>","--json"],"children":{}}}},"tag":{"operation":"dam.tag","action":false,"options":[],"children":{"list":{"operation":"dam.tag.list","action":true,"options":["--repository-id <id>","--query <text>","--json"],"children":{}}}},"download":{"operation":"dam.download","action":true,"options":["--repository-id <id>","--output-dir <directory>","--json"],"children":{}},"rename":{"operation":"dam.rename","action":true,"options":["--kind <asset|folder>","--title <title>","--repository-id <id>","--json"],"children":{}},"move":{"operation":"dam.move","action":true,"options":["--kind <asset|folder>","--target-folder-id <id>","--repository-id <source-id>","--target-repository-id <target-id>","--json"],"children":{}},"copy":{"operation":"dam.copy","action":true,"options":["--kind <asset|folder>","--target-folder-id <id>","--repository-id <source-id>","--target-repository-id <target-id>","--json"],"children":{}},"list":{"operation":"dam.list","action":true,"options":["--repository-id <id>","--all-repositories","--folder-id <id>","--no-include-child-folder","--type <type>","--asset-format <csv>","--tag-ids <csv>","--page-size <number>","--cursor <id>","--json"],"children":{}},"search":{"operation":"dam.search","action":true,"options":["--repository-id <id>","--all-repositories","--folder-id <id>","--no-include-child-folder","--type <type>","--asset-format <csv>","--tag-ids <csv>","--page-size <number>","--cursor <id>","--json"],"children":{}},"get":{"operation":"dam.get","action":true,"options":["--json"],"children":{}},"upload":{"operation":"dam.upload","action":true,"options":["--repository-id <id>","--title <title>","--folder-id <id>","--tag-ids <csv>","--allow-sensitive-path","--wait-analysis","--json"],"children":{}},"delete":{"operation":"dam.delete","action":true,"options":["--repository-id <id>","--permanent"],"children":{}}}},"update":{"operation":"update","action":true,"options":[],"children":{"check":{"operation":"update.check","action":true,"options":["--for-display","--schema","--json"],"children":{}}}},"task":{"operation":"task","action":false,"options":[],"children":{"list":{"operation":"task.list","action":true,"options":["--limit <number>","--operation <operation>","--json"],"children":{}},"get":{"operation":"task.get","action":true,"options":["--json"],"children":{}}}},"credits":{"operation":"credits.get","action":true,"options":["--json","--schema"],"children":{"usage":{"operation":"credits.usage","action":false,"options":[],"children":{"list":{"operation":"credits.usage.list","action":true,"options":["--from <timestamp>","--to <timestamp>","--limit <number>","--cursor <cursor>","--json","--schema"],"children":{}},"get":{"operation":"credits.usage.get","action":true,"options":["--json","--schema"],"children":{}}}}}}}}
@@ -6,7 +6,7 @@ const flags = new Set(["bodyUsedAtReceipt", "bodyLockedAtReceipt", "bodyUsedBefo
6
6
  const counts = new Set(["messageCount", "invalidMessageCount", "systemErrorCount", "publicPartCount",
7
7
  "streamPayloadCount", "streamJsonValueCount"]);
8
8
  const localFileSteps = new Set(["directory_create", "directory_permissions", "directory_read", "stat", "parse", "validate", "open", "file_permissions", "read", "write", "sync", "close", "rename", "unlink"]);
9
- const inputReasons = new Set(["path_restricted", "not_regular_file", "format_missing", "media_type_mismatch", "file_read_failed",
9
+ const inputReasons = new Set(["path_restricted", "not_regular_file", "format_missing", "invalid_media_type_header", "file_read_failed",
10
10
  "json_read", "json_parse", "schema_validation", "invalid_task_id", "command_arguments", "model_required", "model_not_found",
11
11
  "model_tool_mismatch", "model_parameters", "tool_not_found", "invalid_asset_url", "commander.unknownOption",
12
12
  "commander.unknownCommand", "commander.missingArgument", "commander.excessArguments", "commander.help",
@@ -148,7 +148,7 @@ export function createTelemetryInvocation(options) {
148
148
  const snapshot = identity();
149
149
  const keys = ["host_invocation_id", "host_connector_version", "installation_owner", "invocation_purpose",
150
150
  "account_id", "organization_id", "tool_name", "model_id", "content_id", "task_id", "dify_task_id",
151
- "cli_task_id", "execution_mode", "parameters"];
151
+ "cli_task_id", "execution_mode", "execution_protocol", "parameters"];
152
152
  for (const key of keys) {
153
153
  if (context[key] !== undefined)
154
154
  Object.assign(snapshot, { [key]: context[key] });
@@ -207,7 +207,6 @@ export function createTelemetryInvocation(options) {
207
207
  const stage = completion.outcome === "success" ? "process" : classify(completion.error).failureStage ?? failureStage(completion.error) ?? "command";
208
208
  remember({ ...last, event_name: "stage_finished", stage, outcome: completion.outcome,
209
209
  ...(completion.outcome !== "success" && failedStep ? { failed_step: failedStep } : {}),
210
- ...(context.parameters && (!issued || last.command_kind === "technical") ? { parameters: context.parameters } : {}),
211
210
  duration_ms: Math.max(0, options.now() - startedAt),
212
211
  ...(completion.outcome === "success" ? {} : {
213
212
  failure_stage: classify(completion.error).failureStage ?? failureStage(completion.error) ?? "unknown"
@@ -1,42 +1,23 @@
1
- import { classifyTelemetryError, mapCliError } from "../cli/errors.js";
2
1
  import { isInterruption } from "../platform/interruption.js";
3
2
  import { randomBytes } from "node:crypto";
4
- import { readFile, readdir } from "node:fs/promises";
3
+ import { readFile } from "node:fs/promises";
5
4
  import { dirname, join } from "node:path";
6
5
  import { homedir } from "node:os";
7
6
  import { fileURLToPath } from "node:url";
8
7
  import { gaodingProduct, insmindProduct } from "../product/config.js";
9
8
  import { createTelemetryInvocation, hostTelemetryContext } from "./invocation.js";
10
9
  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.
10
+ // The normal runtime or even Commander may be unavailable. Only package-owned names may enter SLS.
13
11
  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);
12
+ try {
13
+ const [{ identifyInvocation }, catalog] = await Promise.all([
14
+ import("./command-route.js"), readFile(new URL("./command-routes.json", import.meta.url), "utf8")
15
+ ]);
16
+ return identifyInvocation(JSON.parse(catalog), argv);
17
+ }
18
+ catch {
19
+ return { operation: "bootstrap", mode: () => "execute" };
36
20
  }
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
21
  }
41
22
  /** Independent fallback for entrypoints which cannot construct the full runtime. */
42
23
  export async function reportProcessError(error, options) {
@@ -55,8 +36,11 @@ export async function reportProcessError(error, options) {
55
36
  catch { /* The package file may be unavailable during startup failure. */ }
56
37
  }
57
38
  const aborted = isInterruption(error, options.signal);
58
- const classification = classifyTelemetryError(error, { aborted, product });
59
- const mapped = mapCliError(error, { aborted, product });
39
+ // The application error mapper imports Commander and feature dependencies which can themselves fail to load.
40
+ const mapper = await import("../cli/errors.js").catch(() => undefined);
41
+ const classification = mapper?.classifyTelemetryError(error, { aborted, product })
42
+ ?? { outcome: aborted ? "interrupted" : "failure", errorCode: "INTERNAL_ERROR" };
43
+ const failure = mapper?.mapCliError(error, { aborted, product }).failure;
60
44
  const telemetry = createTelemetryInvocation({ cliName: product.commandName, cliVersion: version,
61
45
  env: options.environment ?? (process.env.CLI_TELEMETRY_ENV === "test" ? "test" : "production"),
62
46
  processRole: options.processRole ?? "cli", now: Date.now,
@@ -69,8 +53,8 @@ export async function reportProcessError(error, options) {
69
53
  telemetry.annotate(hostTelemetryContext(process.env));
70
54
  if ((options.processRole ?? "cli") === "cli")
71
55
  await telemetry.issue(definition);
72
- const events = telemetry.finish(mapped.kind === "interrupted" ? { outcome: "interrupted", error } : {
73
- outcome: "failure", error, errorCode: mapped.failure.code, errorMessage: mapped.failure.message,
56
+ const events = telemetry.finish(classification.outcome === "interrupted" ? { outcome: "interrupted", error } : {
57
+ outcome: "failure", error, errorCode: failure?.code ?? "INTERNAL_ERROR", errorMessage: failure?.message ?? "CLI startup failed.",
74
58
  ...(classification.httpStatus === undefined ? {} : { httpStatus: classification.httpStatus }),
75
59
  ...(classification.remoteErrorCode === undefined ? {} : { remoteErrorCode: classification.remoteErrorCode }),
76
60
  ...(classification.remoteErrorBody === undefined ? {} : { remoteErrorBody: classification.remoteErrorBody })
@@ -1,3 +1,4 @@
1
+ import { posix, win32 } from "node:path";
1
2
  import { isSensitiveKey, redactSensitiveText } from "../platform/redact.js";
2
3
  const ids = new Set(["account_id", "organization_id", "cli_task_id", "task_id", "dify_task_id", "content_id"]);
3
4
  function sensitive(key) {
@@ -28,7 +29,15 @@ export function cleanText(value) {
28
29
  }
29
30
  export function cleanDiagnostic(value) {
30
31
  const seen = new WeakSet();
31
- function clean(item, depth) {
32
+ const envelope = value && typeof value === "object" ? value : {};
33
+ const tool = envelope.operation === "tool.call";
34
+ const toolDiagnostic = (tool || (envelope.operation === "task.get" && ["dify", "toolkit", "sync"].includes(String(envelope.execution_protocol)))) && envelope.event_name === "stage_finished";
35
+ function clean(item, depth, inParameters = false) {
36
+ if (typeof item === "string" && inParameters) {
37
+ if (posix.isAbsolute(item) || win32.isAbsolute(item) || /^file:\/\//iu.test(item))
38
+ return "[Local file]";
39
+ item = item.replace(/file:\/\/[^\s<>"`]+/giu, "[Local file]");
40
+ }
32
41
  if (typeof item === "string")
33
42
  return /^data:[^,]*;base64,/iu.test(item) ? "[Binary omitted]" : cleanText(item);
34
43
  if (typeof item === "bigint")
@@ -45,9 +54,15 @@ export function cleanDiagnostic(value) {
45
54
  if (item instanceof Error)
46
55
  return errorEvidence(item);
47
56
  if (Array.isArray(item))
48
- return item.map(v => clean(v, depth + 1));
49
- return Object.fromEntries(Object.entries(item).map(([key, v]) => [key,
50
- depth === 0 && ids.has(key) ? v : sensitive(key) ? "[REDACTED]" : clean(v, depth + 1)]));
57
+ return item.map(v => clean(v, depth + 1, inParameters));
58
+ const entries = Object.entries(item);
59
+ const fields = depth === 0 && envelope.event_name === "stage_finished"
60
+ ? entries.filter(([key]) => key !== "parameters") : entries;
61
+ return Object.fromEntries(fields.map(([key, v]) => [key,
62
+ depth === 0 && toolDiagnostic && ["error_message", "error_stack", "remote_error_body"].includes(key)
63
+ ? (key === "error_message" ? envelope.error_code ?? "TOOL_ERROR" : "[User content omitted]") :
64
+ inParameters && tool && key === "prompt" ? "[User content omitted]" :
65
+ depth === 0 && ids.has(key) ? v : sensitive(key) || (inParameters && key === "answers") ? "[REDACTED]" : clean(v, depth + 1, inParameters || key === "parameters")]));
51
66
  }
52
67
  return clean(value, 0);
53
68
  }
@@ -120,6 +120,14 @@ export function createSlsTelemetrySink(options) {
120
120
  const entry = JSON.parse(raw);
121
121
  if (entry.event?.schema_version !== "6" || !Number.isFinite(entry.queuedAt) || !entry.event || eventKey(entry.event) !== name.slice(0, -5))
122
122
  throw new Error();
123
+ // Earlier v6 clients could queue input parameters and echoed Agent HTTP errors.
124
+ const event = entry.event;
125
+ if (event.event_name === "stage_finished") {
126
+ delete event.parameters;
127
+ const agent = event.operation === "agent.send" || (event.operation === "task.get" && !event.execution_protocol);
128
+ if (agent && Number(event.http_status) >= 400)
129
+ delete event.remote_error_body;
130
+ }
123
131
  entries.set(name.slice(0, -5), entry);
124
132
  }
125
133
  catch {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insmind/cli",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
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": "216c910373e0a89ff902e655f3cda89cae32887b",
51
- "pipelineId": "241612",
52
- "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/241612"
50
+ "sourceCommit": "6bb95e37a8accaddd86c5219d536bd9db493ed32",
51
+ "pipelineId": "245407",
52
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/245407"
53
53
  }
54
54
  }