@insmind/cli 2.1.0 → 2.1.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 (122) hide show
  1. package/README.md +30 -0
  2. package/contracts/operations/agent.send/input.schema.json +1 -77
  3. package/contracts/operations/dam.folder.list/input.schema.json +0 -1
  4. package/contracts/operations/dam.folder.list/output.schema.json +1 -2
  5. package/contracts/operations/dam.list/input.schema.json +3 -6
  6. package/contracts/operations/dam.list/output.schema.json +1 -2
  7. package/contracts/operations/dam.search/input.schema.json +3 -6
  8. package/contracts/operations/dam.search/output.schema.json +1 -2
  9. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
  10. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
  11. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
  12. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
  13. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  14. package/dist/bin/postinstall.js +22 -6
  15. package/dist/bin/sync-skill.js +33 -0
  16. package/dist/bin/task-worker.js +2 -2
  17. package/dist/src/bootstrap/create-cli.js +13 -6
  18. package/dist/src/bootstrap/create-runtime.js +103 -29
  19. package/dist/src/bootstrap/run-task-worker.js +6 -2
  20. package/dist/src/bootstrap/validators.js +87 -151
  21. package/dist/src/cli/action-binding.js +14 -37
  22. package/dist/src/cli/agent-commands.js +13 -13
  23. package/dist/src/cli/auth-commands.js +2 -1
  24. package/dist/src/cli/creation-help.js +9 -0
  25. package/dist/src/cli/dam-commands.js +10 -14
  26. package/dist/src/cli/editor-commands.js +16 -12
  27. package/dist/src/cli/errors.js +84 -26
  28. package/dist/src/cli/host-input.js +62 -5
  29. package/dist/src/cli/model-commands.js +9 -3
  30. package/dist/src/cli/observed-errors.js +7 -3
  31. package/dist/src/cli/org-commands.js +3 -1
  32. package/dist/src/cli/presenter.js +4 -5
  33. package/dist/src/cli/task-commands.js +6 -2
  34. package/dist/src/cli/tool-commands.js +12 -11
  35. package/dist/src/contracts/creation-input.js +20 -17
  36. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  37. package/dist/src/features/agent/creative-protocol.js +8 -29
  38. package/dist/src/features/agent/resource-authorizer.js +25 -17
  39. package/dist/src/features/agent/result-reader.js +31 -14
  40. package/dist/src/features/agent/use-cases.js +6 -31
  41. package/dist/src/features/auth/credential-store.js +1 -0
  42. package/dist/src/features/credits/use-cases.js +55 -28
  43. package/dist/src/features/dam/asset-projection.js +3 -6
  44. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  45. package/dist/src/features/dam/object-storage.js +2 -1
  46. package/dist/src/features/dam/repository-catalog.js +30 -21
  47. package/dist/src/features/dam/use-cases.js +14 -9
  48. package/dist/src/features/editor/bridge-client.js +0 -2
  49. package/dist/src/features/editor/bridge-process.js +3 -2
  50. package/dist/src/features/editor/public-url.js +1 -36
  51. package/dist/src/features/editor/session-state.js +1 -0
  52. package/dist/src/features/editor/session.js +3 -2
  53. package/dist/src/features/editor/use-cases.js +27 -2
  54. package/dist/src/features/org/org-service.js +10 -1
  55. package/dist/src/features/org/use-cases.js +18 -4
  56. package/dist/src/features/task/process-owner.js +54 -0
  57. package/dist/src/features/task/store.js +102 -32
  58. package/dist/src/features/task/task-background.js +8 -4
  59. package/dist/src/features/task/use-cases.js +184 -84
  60. package/dist/src/features/tool/argument-paths.js +14 -0
  61. package/dist/src/features/tool/canvas-copy.js +28 -15
  62. package/dist/src/features/tool/canvas-matting.js +123 -0
  63. package/dist/src/features/tool/canvas-media.js +102 -55
  64. package/dist/src/features/tool/canvas-models.js +66 -33
  65. package/dist/src/features/tool/canvas-pricing.js +12 -0
  66. package/dist/src/features/tool/canvas-recovery.js +13 -30
  67. package/dist/src/features/tool/canvas-results.js +92 -93
  68. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  69. package/dist/src/features/tool/canvas-video.js +44 -37
  70. package/dist/src/features/tool/catalog.js +2 -23
  71. package/dist/src/features/tool/dynamic-schema.js +42 -46
  72. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  73. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  74. package/dist/src/features/tool/resource-authorizer.js +11 -3
  75. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  76. package/dist/src/features/tool/tool-definitions.js +23 -0
  77. package/dist/src/features/tool/tool-errors.js +25 -0
  78. package/dist/src/features/tool/tool-output.js +15 -0
  79. package/dist/src/features/tool/use-cases.js +74 -98
  80. package/dist/src/features/update/package-manager.js +124 -0
  81. package/dist/src/features/update/update-service.js +195 -55
  82. package/dist/src/platform/detached-spawn.js +9 -0
  83. package/dist/src/platform/file-lock.js +12 -4
  84. package/dist/src/platform/input-uri.js +23 -1
  85. package/dist/src/platform/local-json-file.js +97 -15
  86. package/dist/src/platform/media-type.js +46 -0
  87. package/dist/src/platform/open-browser.js +5 -2
  88. package/dist/src/platform/public-url.js +35 -0
  89. package/dist/src/platform/remote-error-evidence.js +33 -6
  90. package/dist/src/platform/resource-auth-key.js +35 -1
  91. package/dist/src/platform/safe-upload-file.js +38 -44
  92. package/dist/src/platform/schema-compiler.js +16 -0
  93. package/dist/src/platform/signature.js +2 -2
  94. package/dist/src/platform/signed-http-transport.js +4 -1
  95. package/dist/src/platform/url-safety.js +6 -1
  96. package/dist/src/platform/webm-header.js +41 -0
  97. package/dist/src/platform/windows-acl/LICENSE-mingw-w64 +43 -0
  98. package/dist/src/platform/windows-acl/arm64.node +0 -0
  99. package/dist/src/platform/windows-acl/ia32.node +0 -0
  100. package/dist/src/platform/windows-acl/x64.node +0 -0
  101. package/dist/src/platform/windows-host-job/arm64.exe +0 -0
  102. package/dist/src/platform/windows-host-job/ia32.exe +0 -0
  103. package/dist/src/platform/windows-host-job/sha256.json +7 -0
  104. package/dist/src/platform/windows-host-job/x64.exe +0 -0
  105. package/dist/src/platform/windows-private-state.js +72 -0
  106. package/dist/src/product/config.js +1 -1
  107. package/dist/src/telemetry/command-route.js +38 -0
  108. package/dist/src/telemetry/command-routes.json +1 -0
  109. package/dist/src/telemetry/failure-summary.js +3 -3
  110. package/dist/src/telemetry/invocation.js +1 -2
  111. package/dist/src/telemetry/process-errors.js +17 -33
  112. package/dist/src/telemetry/sanitize.js +19 -4
  113. package/dist/src/telemetry/sls-sink.js +45 -20
  114. package/package.json +4 -4
  115. package/skills/insmind-cli/SKILL.md +18 -5
  116. package/skills/insmind-cli/references/agent.md +9 -4
  117. package/skills/insmind-cli/references/creation.md +3 -1
  118. package/skills/insmind-cli/references/editor.md +7 -5
  119. package/skills/insmind-cli/references/errors.md +20 -9
  120. package/skills/insmind-cli/references/matting.md +3 -5
  121. package/skills/insmind-cli/references/media-tools.md +10 -4
  122. package/skills/insmind-cli/references/tool.md +9 -15
@@ -0,0 +1,35 @@
1
+ // Exact account or local connection keys, independent of case and snake/kebab spelling.
2
+ // Resource grants (auth_key, signature, project_token, X-Amz-*) belong to the caller.
3
+ const identityKeys = new Set([
4
+ "ak", "sk", "accesskey", "accesskeyid", "accesskeysecret", "secretkey",
5
+ "accesstoken", "refreshtoken", "authorization", "authorizecode", "authorizationcode",
6
+ "devicecode", "bearer", "cookie", "credential", "credentials", "password", "secret",
7
+ "focusededitorport", "focusededitortoken"
8
+ ]);
9
+ function normalizedKey(name) {
10
+ return name.toLowerCase().replace(/[-_]/gu, "");
11
+ }
12
+ function withoutCredentials(fields, keys) {
13
+ return fields.split("&").filter(field => {
14
+ // Decode only the name. Serializing URLSearchParams would change signed bytes.
15
+ const rawName = field.split("=", 1)[0];
16
+ const name = new URLSearchParams("key=" + rawName).get("key");
17
+ return !keys.has(normalizedKey(name));
18
+ }).join("&");
19
+ }
20
+ export function filterUrlParameters(input, privateKeys) {
21
+ const keys = privateKeys ? new Set(Array.from(privateKeys, normalizedKey)) : identityKeys;
22
+ const out = new URL(input.href);
23
+ const rawQuery = out.search.slice(1);
24
+ const query = withoutCredentials(rawQuery, keys);
25
+ if (query !== rawQuery)
26
+ out.search = query;
27
+ const fragment = out.hash.slice(1);
28
+ // A fragment may be a router query or a plain list whose values themselves contain '?'.
29
+ const route = /^(?:!?\/[^?]*|[^?=&]*)\?/u.exec(fragment)?.[0] ?? "";
30
+ const fields = fragment.slice(route.length);
31
+ const kept = withoutCredentials(fields, keys);
32
+ if (kept !== fields)
33
+ out.hash = kept ? route + kept : route.slice(0, -1);
34
+ return out;
35
+ }
@@ -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,8 +1,10 @@
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";
4
- import { fileURLToPath } from "node:url";
5
- import { canonicalFileUri, uriShape } from "./input-uri.js";
7
+ import { canonicalFileUri, localPathFromFileUri, uriShape } from "./input-uri.js";
6
8
  export class LocalFileInputError extends Error {
7
9
  reason;
8
10
  diagnosticSummary;
@@ -20,6 +22,7 @@ const protectedSegments = new Set([
20
22
  ".docker",
21
23
  ".gd",
22
24
  ".gd-cli-dev",
25
+ ".insmind",
23
26
  ".git",
24
27
  ".gnupg",
25
28
  ".kube",
@@ -39,29 +42,16 @@ const protectedFilenames = new Set([
39
42
  "id_rsa",
40
43
  "known_hosts"
41
44
  ]);
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
45
  function reject(reason) {
59
46
  throw new LocalFileInputError(undefined, reason);
60
47
  }
61
48
  function assertSafePath(filePath) {
62
49
  const segments = filePath.split(sep).filter(Boolean).map((segment) => segment.toLowerCase());
63
50
  const filename = segments.at(-1) ?? "";
64
- if (protectedFilenames.has(filename) || filename.startsWith(".")
51
+ const parent = segments.at(-2);
52
+ const hostCredential = (parent === ".codex" && filename === "auth.json")
53
+ || (parent === ".gemini" && filename === "oauth_creds.json");
54
+ if (hostCredential || protectedFilenames.has(filename) || filename.startsWith(".")
65
55
  || segments.some(segment => protectedSegments.has(segment))) {
66
56
  reject("path_restricted");
67
57
  }
@@ -80,10 +70,15 @@ function detectedFormat(header) {
80
70
  if (signature === "GIF87a" || signature === "GIF89a")
81
71
  return "gif";
82
72
  }
83
- if (header.length >= 12
84
- && header.subarray(0, 4).toString("ascii") === "RIFF"
85
- && header.subarray(8, 12).toString("ascii") === "WEBP")
86
- return "webp";
73
+ if (header.length >= 12 && header.toString("latin1", 0, 4) === "RIFF") {
74
+ const kind = header.toString("latin1", 8, 12);
75
+ if (kind === "WEBP")
76
+ return "webp";
77
+ if (kind === "WAVE")
78
+ return "wav";
79
+ }
80
+ if (hasWebmDocType(header))
81
+ return "webm";
87
82
  if (header.length >= 12 && header.subarray(4, 8).toString("ascii") === "ftyp") {
88
83
  const brand = header.subarray(8, 12).toString("ascii");
89
84
  if (["isom", "iso2", "iso5", "iso6", "mp41", "mp42", "avc1", "dash"].includes(brand))
@@ -103,7 +98,8 @@ async function readHeader(filePath, signal) {
103
98
  signal.throwIfAborted();
104
99
  const handle = await open(filePath, "r");
105
100
  try {
106
- const buffer = Buffer.alloc(32);
101
+ // Read a bounded prefix; the WebM DocType can extend past a 32-byte prefix.
102
+ const buffer = Buffer.alloc(4096);
107
103
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
108
104
  signal.throwIfAborted();
109
105
  return buffer.subarray(0, bytesRead);
@@ -120,7 +116,7 @@ export async function inspectUploadFile(input) {
120
116
  const url = canonicalFileUri(input.url);
121
117
  if (url === undefined)
122
118
  throw new TypeError("Invalid local file URI.");
123
- requestedPath = fileURLToPath(url);
119
+ requestedPath = localPathFromFileUri(url);
124
120
  }
125
121
  catch (cause) {
126
122
  throw new LocalFileInputError(cause, "invalid_file_uri");
@@ -135,31 +131,29 @@ export async function inspectUploadFile(input) {
135
131
  return reject("not_regular_file");
136
132
  const header = await readHeader(filePath, input.signal);
137
133
  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
134
  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");
135
+ const declaration = input.claimedMediaType;
136
+ if (declaration !== undefined) {
137
+ try {
138
+ validateHeaderValue("Content-Type", declaration);
139
+ }
140
+ catch {
141
+ return reject("invalid_media_type_header");
142
+ }
154
143
  }
144
+ const claimed = concreteMediaType(declaration);
145
+ const subtype = claimed?.split("/")[1];
146
+ const declaredFormat = claimed === "image/svg+xml" ? "svg" : claimed === "video/quicktime" ? "mov"
147
+ : subtype && /^[a-z0-9]+$/u.test(subtype) ? subtype : undefined;
148
+ const format = detected ?? (extension === "jpg" ? "jpeg" : extension || declaredFormat || "bin");
155
149
  return {
156
150
  filePath,
157
151
  filename: basename(requestedPath),
158
152
  format,
159
- mediaType: detectedMediaType
160
- ?? input.claimedMediaType
161
- ?? mediaTypes[format]
162
- ?? `application/${format}`,
153
+ mediaType: declaration
154
+ ?? (detected ? mediaTypeForFormat(detected) : undefined)
155
+ ?? mediaTypeForFormat(format)
156
+ ?? (format === "bin" ? "application/octet-stream" : `application/${format}`),
163
157
  size: details.size
164
158
  };
165
159
  }
@@ -0,0 +1,16 @@
1
+ import { createRequire } from "node:module";
2
+ const require = createRequire(import.meta.url);
3
+ // The command graph is shared. A probe that does not validate a document
4
+ // should not pay for loading Ajv, its formats and their dependencies.
5
+ export function lazySchemaCompiler(options) {
6
+ let compiler;
7
+ return () => {
8
+ if (!compiler) {
9
+ const { Ajv2020 } = require("ajv/dist/2020.js");
10
+ const engine = new Ajv2020(options);
11
+ require("ajv-formats")(engine);
12
+ compiler = engine;
13
+ }
14
+ return compiler;
15
+ };
16
+ }
@@ -7,8 +7,8 @@ export function canonicalizeQuery(entries) {
7
7
  .replaceAll("%3A", ":");
8
8
  }
9
9
  export function createSigningString(input) {
10
- // The gateway signs literal base64 padding; keep its wire query URL-encoded.
11
- const signingQuery = input.canonicalQuery.replaceAll("%3D", "=");
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
12
  return `${input.method.toUpperCase()}@${input.pathname}@${signingQuery}@${input.timestamp}`;
13
13
  }
14
14
  export function signRequest(input) {
@@ -235,7 +235,10 @@ export function createSignedHttpTransport(options) {
235
235
  const { response } = received;
236
236
  if (!response.ok) {
237
237
  const body = await readText(received);
238
- 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());
239
242
  }
240
243
  if (!response.body)
241
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,43 @@
1
+ With exception of certain parts that are prominently marked as being
2
+ in the Public Domain, BSD, or LGPL this Software is provided under the
3
+ Zope Public License (ZPL) Version 2.1.
4
+
5
+ Copyright (c) 2009 - 2013 by the mingw-w64 project
6
+
7
+ See the AUTHORS file for the list of contributors to the mingw-w64 project.
8
+
9
+ This license has been certified as open source. It has also been designated
10
+ as GPL compatible by the Free Software Foundation (FSF).
11
+
12
+ Redistribution and use in source and binary forms, with or without
13
+ modification, are permitted provided that the following conditions are met:
14
+
15
+ 1. Redistributions in source code must retain the accompanying copyright
16
+ notice, this list of conditions, and the following disclaimer.
17
+ 2. Redistributions in binary form must reproduce the accompanying
18
+ copyright notice, this list of conditions, and the following disclaimer
19
+ in the documentation and/or other materials provided with the
20
+ distribution.
21
+ 3. Names of the copyright holders must not be used to endorse or promote
22
+ products derived from this software without prior written permission
23
+ from the copyright holders.
24
+ 4. The right to distribute this software or to use it for any purpose does
25
+ not give you the right to use Servicemarks (sm) or Trademarks (tm) of
26
+ the copyright holders. Use of them is covered by separate agreement
27
+ with the copyright holders.
28
+ 5. If any files are modified, you must cause the modified files to carry
29
+ prominent notices stating that you changed the files and the date of
30
+ any change.
31
+
32
+ Disclaimer
33
+
34
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
35
+ OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36
+ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
37
+ EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
38
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
39
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
40
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
43
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,7 @@
1
+ {
2
+ "job-launcher.c": "8c79e1ed2a4eb51deb272299542795c4cab5d73ccdcc7e6351d6dba4c1481c0b",
3
+ "shell-start.h": "6db1ac78fa52269bb91ee4058079eb554ebe1c9f3823389ca94b3d18f54163b8",
4
+ "x64.exe": "d096ab181dba17e132ec7d4c51c1439118add01b6072cdef0b8a498269508614",
5
+ "arm64.exe": "16d1dd531462f37caa3758deeffb0c9754342a56767bb46b5797b6bca23bfc97",
6
+ "ia32.exe": "4346a09da68102b4cc81a113c9bba36c8ae4c0e22a89b9265e490842b10f8e8b"
7
+ }
@@ -0,0 +1,72 @@
1
+ import { close, closeSync, readFile } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { join, toNamespacedPath } from "node:path";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { promisify } from "node:util";
6
+ const read = promisify(readFile);
7
+ const closeFile = promisify(close);
8
+ const require = createRequire(import.meta.url);
9
+ const actions = { file: 0, directory: 1, create: 2 };
10
+ const systemCodes = {
11
+ 2: "ENOENT", 3: "ENOENT", 5: "EACCES", 32: "EBUSY", 33: "EBUSY", 267: "ENOTDIR"
12
+ };
13
+ let open;
14
+ export function openWindowsState(path, action) {
15
+ open ??= require(`./windows-acl/${process.arch}.node`);
16
+ const fd = open(toNamespacedPath(path), actions[action]);
17
+ if (fd < 0)
18
+ throw Object.assign(new Error("Cannot secure local Windows state."), {
19
+ code: systemCodes[-fd] ?? "EIO", win32Code: -fd
20
+ });
21
+ return fd;
22
+ }
23
+ export function openWindowsStateReader(path) {
24
+ const fd = openWindowsState(path, "file");
25
+ return {
26
+ readFile: (encoding) => read(fd, encoding),
27
+ close: () => closeFile(fd)
28
+ };
29
+ }
30
+ /** Pin each managed directory below the caller's trusted home. A child path
31
+ * is never opened through an unchecked or replaceable parent junction. */
32
+ export function pinWindowsStateDirectories(home, components, create) {
33
+ const fds = [];
34
+ const release = () => { for (const fd of fds.reverse())
35
+ closeSync(fd); };
36
+ let path = home;
37
+ try {
38
+ for (const component of components) {
39
+ path = join(path, component);
40
+ fds.push(openWindowsState(path, create ? "create" : "directory"));
41
+ }
42
+ return release;
43
+ }
44
+ catch (cause) {
45
+ release();
46
+ throw cause;
47
+ }
48
+ }
49
+ export async function readWindowsPrivateText(path) {
50
+ const reader = openWindowsStateReader(path);
51
+ try {
52
+ return await reader.readFile("utf8");
53
+ }
54
+ finally {
55
+ await reader.close();
56
+ }
57
+ }
58
+ // MoveFileEx can briefly reject replacement while a reader holds the old file.
59
+ // Retry only the rename of the same prepared temporary file.
60
+ export async function retryWindowsStateRename(rename) {
61
+ for (const wait of [8, 24, 64, 128]) {
62
+ try {
63
+ return await rename();
64
+ }
65
+ catch (cause) {
66
+ if (!(cause instanceof Error && "code" in cause && ["EPERM", "EACCES", "EBUSY"].includes(String(cause.code))))
67
+ throw cause;
68
+ await delay(wait);
69
+ }
70
+ }
71
+ await rename();
72
+ }
@@ -1,4 +1,4 @@
1
- import { defaultToolDefinitions } from "../features/tool/catalog.js";
1
+ import { defaultToolDefinitions } from "../features/tool/tool-definitions.js";
2
2
  function freezeProduct(config) {
3
3
  Object.freeze(config.endpoints);
4
4
  for (const tool of config.tools)
@@ -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",
@@ -27,12 +27,12 @@ const enums = Object.fromEntries(Object.entries({
27
27
  quotaDecisionSource: ["cli_precheck"], quotaUnit: ["gaodou"], quotaLimitScope: ["account", "member_period"],
28
28
  outputWritePhase: ["write_sync", "write_callback", "stream_error"],
29
29
  hostPhase: ["started", "finished"],
30
- hostReason: ["authenticated", "unauthenticated", "version", "timeout", "output_limit", "host_signal", "stdout_closed", "spawn_failure", "cli_exit", "invalid_response"]
30
+ hostReason: ["authenticated", "unauthenticated", "version", "timeout", "output_limit", "host_signal", "stdout_closed", "spawn_failure", "cli_exit", "invalid_response", "helper_unavailable", "upgrade_required"]
31
31
  }).map(([key, values]) => [key, new Set(values)]));
32
32
  const nonnegativeIntegers = new Set(["streamFirstByteMs", "streamReceivedBytes", "lockWaitMs", "lockOwnerCount",
33
33
  "lockOwnerPid", "lockContenderPid", "lockOwnerStartedAtMs", "lockOwnerAgeMs", "lockOwnerAcquiredAtMs", "lockOwnerHeldMs", "localProcessPid", "localParentPid", "workerPid", "downloadUrlCount", "mediaBytesRead", "requestTimeoutMs", "requestDurationMs",
34
34
  "outputElapsedMs", "outputWriteCount", "outputAttemptedBytes", "outputAcknowledgedBytes", "outputPendingWrites", "outputBufferedBytes",
35
- "hostElapsedMs", "hostTimeoutMs", "hostStartedAtMs", "hostProcessPid", "hostParentPid", "hostChildPid", "hostStdoutBytes", "hostStderrBytes"]);
35
+ "hostElapsedMs", "hostTimeoutMs", "hostShellStartedAtMs", "hostWorkerThreadId", "hostStartedAtMs", "hostProcessPid", "hostParentPid", "hostChildPid", "hostStdoutBytes", "hostStderrBytes"]);
36
36
  const quotaNumbers = new Set(["quotaTotal", "quotaUsed", "quotaPending", "quotaMemberLimit", "quotaMemberUsed", "quotaAvailable", "quotaRequired"]);
37
37
  /** Fixed diagnostic facts, never arbitrary response fields or error messages. */
38
38
  export function safeFailureSummary(value) {
@@ -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"