@insmind/cli 2.1.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 (95) hide show
  1. package/contracts/operations/agent.send/input.schema.json +1 -77
  2. package/contracts/operations/dam.folder.list/input.schema.json +0 -1
  3. package/contracts/operations/dam.folder.list/output.schema.json +1 -2
  4. package/contracts/operations/dam.list/input.schema.json +3 -6
  5. package/contracts/operations/dam.list/output.schema.json +1 -2
  6. package/contracts/operations/dam.search/input.schema.json +3 -6
  7. package/contracts/operations/dam.search/output.schema.json +1 -2
  8. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
  9. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
  10. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
  11. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
  12. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  13. package/dist/bin/postinstall.js +22 -6
  14. package/dist/bin/task-worker.js +2 -2
  15. package/dist/src/bootstrap/create-cli.js +13 -6
  16. package/dist/src/bootstrap/create-runtime.js +98 -28
  17. package/dist/src/bootstrap/run-task-worker.js +6 -2
  18. package/dist/src/bootstrap/validators.js +1 -1
  19. package/dist/src/cli/action-binding.js +14 -37
  20. package/dist/src/cli/agent-commands.js +11 -11
  21. package/dist/src/cli/auth-commands.js +2 -1
  22. package/dist/src/cli/creation-help.js +9 -0
  23. package/dist/src/cli/dam-commands.js +10 -14
  24. package/dist/src/cli/editor-commands.js +7 -5
  25. package/dist/src/cli/errors.js +81 -22
  26. package/dist/src/cli/host-input.js +64 -5
  27. package/dist/src/cli/model-commands.js +9 -3
  28. package/dist/src/cli/observed-errors.js +7 -3
  29. package/dist/src/cli/org-commands.js +3 -1
  30. package/dist/src/cli/task-commands.js +6 -2
  31. package/dist/src/cli/tool-commands.js +12 -11
  32. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  33. package/dist/src/features/agent/creative-protocol.js +8 -29
  34. package/dist/src/features/agent/resource-authorizer.js +25 -17
  35. package/dist/src/features/agent/result-reader.js +31 -14
  36. package/dist/src/features/agent/use-cases.js +6 -31
  37. package/dist/src/features/credits/use-cases.js +55 -28
  38. package/dist/src/features/dam/asset-projection.js +3 -6
  39. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  40. package/dist/src/features/dam/repository-catalog.js +30 -21
  41. package/dist/src/features/dam/use-cases.js +12 -7
  42. package/dist/src/features/editor/bridge-client.js +0 -2
  43. package/dist/src/features/editor/public-url.js +1 -36
  44. package/dist/src/features/editor/session.js +3 -2
  45. package/dist/src/features/editor/use-cases.js +27 -2
  46. package/dist/src/features/org/org-service.js +10 -1
  47. package/dist/src/features/org/use-cases.js +18 -4
  48. package/dist/src/features/task/process-owner.js +54 -0
  49. package/dist/src/features/task/store.js +37 -10
  50. package/dist/src/features/task/task-background.js +5 -2
  51. package/dist/src/features/task/use-cases.js +184 -84
  52. package/dist/src/features/tool/argument-paths.js +14 -0
  53. package/dist/src/features/tool/canvas-copy.js +28 -15
  54. package/dist/src/features/tool/canvas-matting.js +123 -0
  55. package/dist/src/features/tool/canvas-media.js +100 -52
  56. package/dist/src/features/tool/canvas-models.js +66 -33
  57. package/dist/src/features/tool/canvas-pricing.js +12 -0
  58. package/dist/src/features/tool/canvas-recovery.js +13 -30
  59. package/dist/src/features/tool/canvas-results.js +79 -87
  60. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  61. package/dist/src/features/tool/canvas-video.js +44 -37
  62. package/dist/src/features/tool/dynamic-schema.js +39 -40
  63. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  64. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  65. package/dist/src/features/tool/resource-authorizer.js +11 -3
  66. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  67. package/dist/src/features/tool/tool-errors.js +25 -0
  68. package/dist/src/features/tool/tool-output.js +15 -0
  69. package/dist/src/features/tool/use-cases.js +74 -98
  70. package/dist/src/features/update/update-service.js +95 -21
  71. package/dist/src/platform/media-type.js +46 -0
  72. package/dist/src/platform/public-url.js +35 -0
  73. package/dist/src/platform/remote-error-evidence.js +33 -6
  74. package/dist/src/platform/resource-auth-key.js +35 -1
  75. package/dist/src/platform/safe-upload-file.js +36 -41
  76. package/dist/src/platform/signature.js +2 -2
  77. package/dist/src/platform/signed-http-transport.js +4 -1
  78. package/dist/src/platform/url-safety.js +6 -1
  79. package/dist/src/platform/webm-header.js +41 -0
  80. package/dist/src/telemetry/command-route.js +38 -0
  81. package/dist/src/telemetry/command-routes.json +1 -0
  82. package/dist/src/telemetry/failure-summary.js +1 -1
  83. package/dist/src/telemetry/invocation.js +1 -2
  84. package/dist/src/telemetry/process-errors.js +17 -33
  85. package/dist/src/telemetry/sanitize.js +19 -4
  86. package/dist/src/telemetry/sls-sink.js +8 -0
  87. package/package.json +4 -4
  88. package/skills/insmind-cli/SKILL.md +18 -5
  89. package/skills/insmind-cli/references/agent.md +9 -4
  90. package/skills/insmind-cli/references/creation.md +3 -1
  91. package/skills/insmind-cli/references/editor.md +7 -5
  92. package/skills/insmind-cli/references/errors.md +20 -9
  93. package/skills/insmind-cli/references/matting.md +3 -5
  94. package/skills/insmind-cli/references/media-tools.md +10 -4
  95. package/skills/insmind-cli/references/tool.md +9 -15
@@ -1,51 +1,52 @@
1
- import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
1
+ import { parseHttpAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
2
2
  import { findToolModel, defaultToolDefinitions, projectModelDetail, projectModelList, projectToolList, ToolInputError } from "./catalog.js";
3
3
  import { assertModelArguments, buildToolArgumentsSchema } from "./dynamic-schema.js";
4
+ import { mediaFilename, mediaTypeFromFilename } from "../../platform/media-type.js";
5
+ import { assertNoLocalAssetPaths } from "./argument-paths.js";
4
6
  import { hasCanvasMetering } from "./canvas-pricing.js";
5
- const mediaTypes = {
6
- avif: "image/avif",
7
- gif: "image/gif",
8
- heic: "image/heic",
9
- jpeg: "image/jpeg",
10
- jpg: "image/jpeg",
11
- mov: "video/quicktime",
12
- mp3: "audio/mpeg",
13
- mp4: "video/mp4",
14
- png: "image/png",
15
- wav: "audio/wav",
16
- webm: "video/webm",
17
- webp: "image/webp"
18
- };
19
- function inferRemoteMediaType(url) {
20
- const segment = url.pathname.split("/").filter(Boolean).at(-1) ?? "";
21
- let filename = segment;
7
+ function remoteMedia(value, name, path = name) {
22
8
  try {
23
- filename = decodeURIComponent(segment);
24
- }
25
- catch {
26
- // The extension remains usable when the path contains malformed escapes.
27
- }
28
- const extension = filename.split(".").at(-1)?.toLowerCase();
29
- return extension === undefined || extension === filename.toLowerCase()
30
- ? "application/octet-stream"
31
- : mediaTypes[extension] ?? "application/octet-stream";
32
- }
33
- function remoteMedia(value, name) {
34
- try {
35
- const url = parseSafeRemoteAssetUrl(value);
9
+ const url = parseHttpAssetUrl(value);
36
10
  return {
37
11
  type: "media",
38
12
  url: value,
39
- mime: inferRemoteMediaType(url),
13
+ mime: mediaTypeFromFilename(mediaFilename(url)) ?? "application/octet-stream",
40
14
  name
41
15
  };
42
16
  }
43
17
  catch (error) {
44
18
  if (error instanceof UrlSafetyError)
45
- throw new ToolInputError("invalid_asset_url", `/arguments/${name}`, [], error);
19
+ throw new ToolInputError("invalid_asset_url", `/arguments/${path}`, [], error);
46
20
  throw error;
47
21
  }
48
22
  }
23
+ function prepareGenerationInput(model, parameters) {
24
+ const prompt = [];
25
+ const controls = Object.create(null);
26
+ const fields = new Map(model.parameters.map(field => [field.name, field]));
27
+ const references = [];
28
+ for (const [name, value] of Object.entries(parameters)) {
29
+ if (name === "prompt") {
30
+ if (typeof value !== "string")
31
+ throw new ToolInputError("prompt_must_be_text", "/arguments/prompt");
32
+ prompt.push({ type: "text", content: value });
33
+ continue;
34
+ }
35
+ const field = fields.get(name);
36
+ if (field?.type === "uri" || field?.type === "uri[]") {
37
+ // assertModelArguments has checked and canonicalized these URI fields.
38
+ const uris = field.type === "uri[]" ? value : [value];
39
+ for (const [index, uri] of uris.entries()) {
40
+ const path = field.type === "uri[]" ? `${name}/${index}` : name;
41
+ references.push(uri.startsWith("file:") ? { type: "local", name, url: uri } : remoteMedia(uri, name, path));
42
+ }
43
+ continue;
44
+ }
45
+ assertNoLocalAssetPaths(value, `/arguments/${name}`, field?.type);
46
+ controls[name] = value;
47
+ }
48
+ return { prompt, controls, references };
49
+ }
49
50
  export function createToolUseCases(dependencies) {
50
51
  async function load(access, signal) {
51
52
  signal.throwIfAborted();
@@ -61,12 +62,13 @@ export function createToolUseCases(dependencies) {
61
62
  dependencies.telemetry.annotate({ tool_name: input.name,
62
63
  ...(typeof input.arguments.model === "string" ? { model_id: input.arguments.model } : {}) });
63
64
  const catalog = await load(access, signal);
64
- const model = await dependencies.telemetry.stage("input", () => {
65
+ const { model, parameters, generationInput } = await dependencies.telemetry.stage("input", () => {
65
66
  const modelName = input.arguments.model;
66
67
  if (typeof modelName !== "string")
67
68
  throw new ToolInputError("model_required", "/arguments/model");
68
69
  const selected = findToolModel(catalog, input.name, modelName);
69
70
  assertModelArguments(selected, input.arguments);
71
+ const { model: _id, ...parameters } = input.arguments;
70
72
  if (selected.execution?.kind === "canvas") {
71
73
  for (const parameter of selected.parameters) {
72
74
  const value = input.arguments[parameter.name];
@@ -77,86 +79,60 @@ export function createToolUseCases(dependencies) {
77
79
  remoteMedia(uri, parameter.type === "uri[]" ? `${parameter.name}/${index}` : parameter.name);
78
80
  }
79
81
  }
82
+ return { model: selected, parameters };
80
83
  }
81
- return selected;
84
+ return { model: selected, parameters, generationInput: prepareGenerationInput(selected, parameters) };
82
85
  });
83
- const { model: ignoredModel, ...parameters } = input.arguments;
84
- void ignoredModel;
85
86
  dependencies.telemetry.annotate({
86
87
  tool_name: model.tool,
87
88
  model_id: model.model,
88
89
  parameters
89
90
  });
90
- if (model.execution?.kind === "canvas") {
91
+ if (!generationInput) {
91
92
  const usage = { model: model.model, ...(model.cost === undefined || hasCanvasMetering(model) ? {} : { cost: model.cost }) };
92
93
  await observe?.({ toolUsage: usage, generation: { tool: model.tool, model: model.model } });
93
94
  return { invocation: { kind: "canvas", model, arguments: input.arguments }, usage };
94
95
  }
95
- const prompt = [];
96
- if (Object.hasOwn(parameters, "content_id"))
97
- throw new ToolInputError("managed_argument", "/arguments/content_id");
98
- const requestParameters = { ...parameters };
99
- const directArguments = { ...parameters };
100
- const prepare = async () => {
101
- if (typeof parameters.prompt === "string") {
102
- prompt.push({ type: "text", content: parameters.prompt });
103
- delete requestParameters.prompt;
104
- }
105
- for (const parameter of model.parameters) {
106
- if (parameter.type !== "uri" && parameter.type !== "uri[]")
107
- continue;
108
- const value = parameters[parameter.name];
109
- if (value === undefined)
110
- continue;
111
- const urls = [];
112
- for (const url of (Array.isArray(value) ? value : [value])) {
113
- signal.throwIfAborted();
114
- const media = url.startsWith("file:")
115
- ? await dependencies.uploader.upload({ url }, access, signal).then(upload => ({
116
- type: "media", url: upload.url, mime: upload.mediaType, name: parameter.name
117
- }))
118
- : remoteMedia(url, parameter.name);
119
- prompt.push(media);
120
- urls.push(media.url);
96
+ const { prompt, controls, references } = generationInput;
97
+ const explicitArguments = { ...parameters };
98
+ // Empty media lists remain explicit values, even though they add no prompt items.
99
+ for (const field of model.parameters) {
100
+ if (field.type === "uri[]" && Object.hasOwn(parameters, field.name))
101
+ explicitArguments[field.name] = [];
102
+ }
103
+ const prepareMedia = async () => {
104
+ const uploaded = new Map();
105
+ for (const ref of references) {
106
+ signal.throwIfAborted();
107
+ let media;
108
+ if (ref.type === "media")
109
+ media = ref;
110
+ else {
111
+ let asset = uploaded.get(ref.url);
112
+ if (!asset) {
113
+ asset = await dependencies.uploader.upload({ url: ref.url }, access, signal);
114
+ uploaded.set(ref.url, asset);
115
+ }
116
+ media = { type: "media", url: asset.url, mime: asset.mediaType, name: ref.name };
121
117
  }
122
- // Preserve scalar/array semantics after converting local files to service URLs.
123
- directArguments[parameter.name] = parameter.type === "uri[]" ? urls : urls[0];
124
- delete requestParameters[parameter.name];
118
+ prompt.push(media);
119
+ if (Array.isArray(explicitArguments[ref.name]))
120
+ explicitArguments[ref.name].push(media.url);
121
+ else
122
+ explicitArguments[ref.name] = media.url;
125
123
  }
126
124
  };
127
- const hasLocalMedia = model.parameters.some((parameter) => {
128
- const value = input.arguments[parameter.name];
129
- return parameter.type === "uri"
130
- ? typeof value === "string" && value.startsWith("file:")
131
- : parameter.type === "uri[]"
132
- && Array.isArray(value) && value.some((url) => url.startsWith("file:"));
133
- });
134
- if (hasLocalMedia) {
135
- await dependencies.telemetry.stage("upload", prepare);
136
- }
137
- else {
138
- await prepare();
139
- }
125
+ if (references.some(ref => ref.type === "local"))
126
+ await dependencies.telemetry.stage("upload", prepareMedia);
127
+ else
128
+ await prepareMedia();
140
129
  signal.throwIfAborted();
141
- const requiresIntent = prompt.some((item) => item.type === "media")
142
- || Object.values(requestParameters).some((value) => value === "");
130
+ const mediaKind = model.tool === "video.generate" ? "video" : "image";
131
+ const requiresIntent = references.length > 0 || Object.values(controls).some(value => value === "");
143
132
  const invocation = requiresIntent
144
- ? {
145
- kind: "intent",
146
- model: model.model,
147
- prompt,
148
- parameters: requestParameters,
149
- explicitArguments: directArguments,
150
- optionalMediaParameters: model.parameters
151
- .filter((parameter) => ((parameter.type === "uri" || parameter.type === "uri[]")
152
- && !parameter.required))
153
- .map((parameter) => parameter.name)
154
- }
155
- : {
156
- kind: "direct",
157
- name: model.model,
158
- arguments: directArguments
159
- };
133
+ ? { kind: "intent", model: model.model, mediaKind, prompt, parameters: controls, explicitArguments,
134
+ optionalMediaParameters: model.parameters.filter(field => !field.required && (field.type === "uri" || field.type === "uri[]")).map(field => field.name) }
135
+ : { kind: "direct", name: model.model, mediaKind, arguments: explicitArguments };
160
136
  const usage = {
161
137
  model: model.model,
162
138
  ...(model.cost === undefined ? {} : { cost: model.cost })
@@ -1,7 +1,9 @@
1
1
  import { isInterruption } from "../../platform/interruption.js";
2
2
  import { spawn } from "node:child_process";
3
- import { realpathSync } from "node:fs";
4
- import { resolve } from "node:path";
3
+ import { lstatSync, readFileSync, readlinkSync, realpathSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, isAbsolute, join, resolve } from "node:path";
6
+ import { loadBundledSkills } from "../skill/bundled-skills.js";
5
7
  import { gt } from "semver";
6
8
  import { syncBundledSkills, SkillSyncError, verifyBundledSkills } from "../skill/installer.js";
7
9
  import { fetchLatestVersion } from "./latest-version.js";
@@ -43,6 +45,15 @@ export function detectInstallSource(input) {
43
45
  if (!isWithin(realBinaryPath, packageRoot)) {
44
46
  return unsupported("CLI binary 与 package 不匹配");
45
47
  }
48
+ // pnpm 12 can link global and project installs to the same store. The hash
49
+ // alone is not ownership evidence: match the actual invocation to its global launcher.
50
+ const command = input.binaryName ?? "gd-cli";
51
+ if (realBinaryPath === `${packageRoot}/dist/bin/${command}.js`
52
+ && pnpmSnapshotDirectory(binaryPath, packageName, command)
53
+ && pnpmLauncherTargets(input.env, command).some(target => target === resolve(input.binaryPath))
54
+ && safeRealpath(input.binaryPath) === input.realBinaryPath) {
55
+ return { kind: "global", manager: "pnpm", packageRoot: input.packageRoot };
56
+ }
46
57
  if (packageRoot.includes(`/global/`) && packageRoot.includes(`/.pnpm/${encodedPackage}@`)
47
58
  || packageRoot.includes(`/node_modules/${packageName}`)
48
59
  && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}\//u.test(packageRoot)
@@ -56,6 +67,43 @@ export function detectInstallSource(input) {
56
67
  }
57
68
  return unsupported("无法确认 npm 或 pnpm 全局安装");
58
69
  }
70
+ function pnpmSnapshotDirectory(binaryPath, name, command) {
71
+ const suffix = `/node_modules/${name}/dist/bin/${command}.js`;
72
+ const normalized = normalizePath(binaryPath);
73
+ if (!normalized.endsWith(suffix))
74
+ return;
75
+ const snapshot = normalized.slice(0, -suffix.length);
76
+ if (/\/v\d+\/(?:[a-f0-9]{64}|[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16})$/u.test(snapshot))
77
+ return dirname(dirname(snapshot));
78
+ }
79
+ function pnpmLauncherTargets(env, command) {
80
+ const home = env.HOME || env.USERPROFILE || homedir();
81
+ const pnpmHome = env.PNPM_HOME || (process.platform === "darwin" ? join(home, "Library", "pnpm")
82
+ : process.platform === "win32" ? join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "pnpm")
83
+ : join(env.XDG_DATA_HOME || join(home, ".local", "share"), "pnpm"));
84
+ if (!isAbsolute(pnpmHome))
85
+ return [];
86
+ const targets = [];
87
+ for (const dir of [join(pnpmHome, "bin"), pnpmHome]) {
88
+ for (const ext of process.platform === "win32" ? [".cmd", ".ps1", ""] : [""]) {
89
+ const launcher = join(dir, command + ext);
90
+ try {
91
+ const stat = lstatSync(launcher);
92
+ const target = stat.isSymbolicLink() ? readlinkSync(launcher)
93
+ : stat.isFile() && stat.size < 131072
94
+ ? /^(?:#|::|@?REM)\s+cmd-shim-target=(.+)$/imu.exec(readFileSync(launcher, "utf8"))?.[1]?.trim()
95
+ : undefined;
96
+ if (target) {
97
+ const entry = resolve(dirname(launcher), target);
98
+ realpathSync(entry);
99
+ targets.push(entry);
100
+ }
101
+ }
102
+ catch { /* Another launcher location may exist; ambiguous ownership is never writable. */ }
103
+ }
104
+ }
105
+ return targets;
106
+ }
59
107
  export function createUpdateService(options) {
60
108
  const fetchPackage = options.fetch ?? globalThis.fetch;
61
109
  const runProcess = options.runProcess ?? spawnProcess;
@@ -110,6 +158,22 @@ export function createUpdateService(options) {
110
158
  env,
111
159
  ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {})
112
160
  };
161
+ const binaryPath = options.binaryPath ?? process.argv[1] ?? "";
162
+ const source = detectInstallSource({
163
+ binaryPath,
164
+ realBinaryPath: safeRealpath(binaryPath),
165
+ packageRoot: options.packageRoot,
166
+ cwd: options.cwd ?? process.cwd(),
167
+ env,
168
+ packageName,
169
+ binaryName: commandName
170
+ });
171
+ const nextSteps = [insmind ? "Choose the command for your original package manager:" : "按原安装工具选择下面一条命令执行:", ...manualCommands(latest, packageName)];
172
+ if (source.kind === "unsupported") {
173
+ throw new UpdateError("UPDATE_FAILED", insmind
174
+ ? "The current installation method does not support automatic updates."
175
+ : `当前安装方式不支持自动更新:${source.reason}。`, nextSteps);
176
+ }
113
177
  if (!gt(latest, options.currentVersion)) {
114
178
  await options.telemetry.stage("sync", async () => {
115
179
  try {
@@ -127,26 +191,18 @@ export function createUpdateService(options) {
127
191
  });
128
192
  return { version: options.currentVersion, updated: false };
129
193
  }
130
- const binaryPath = options.binaryPath ?? process.argv[1] ?? "";
131
- const source = detectInstallSource({
132
- binaryPath,
133
- realBinaryPath: safeRealpath(binaryPath),
134
- packageRoot: options.packageRoot,
135
- cwd: options.cwd ?? process.cwd(),
136
- env,
137
- packageName,
138
- binaryName: commandName
139
- });
140
- const nextSteps = [insmind ? "Choose the command for your original package manager:" : "按原安装工具选择下面一条命令执行:", ...manualCommands(latest, packageName)];
141
- if (source.kind === "unsupported") {
142
- throw new UpdateError("UPDATE_FAILED", insmind
143
- ? "The current installation method does not support automatic updates."
144
- : `当前安装方式不支持自动更新:${source.reason}。`, nextSteps);
145
- }
146
194
  const command = source.manager;
195
+ const globalDirectory = command === "pnpm" && pnpmLauncherTargets(env, commandName).includes(resolve(binaryPath))
196
+ ? pnpmSnapshotDirectory(binaryPath, packageName, commandName) : undefined;
197
+ const modulesParent = dirname(dirname(dirname(source.packageRoot)));
198
+ // npm puts global modules under <prefix>/lib/node_modules on POSIX and
199
+ // <prefix>/node_modules on Windows. Never let today's config redirect a prior one-off install.
200
+ const npmPrefix = normalizePath(source.packageRoot).endsWith(`/lib/node_modules/${packageName}`)
201
+ ? dirname(modulesParent) : modulesParent;
147
202
  const args = source.manager === "npm"
148
- ? ["install", "--global", `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
149
- : ["add", "--global", `--allow-build=${packageName}`, `${packageName}@${latest}`];
203
+ ? ["install", "--global", "--prefix", npmPrefix, `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
204
+ : ["add", "--global", ...(globalDirectory ? ["--global-dir", globalDirectory] : []),
205
+ `--allow-build=${packageName}`, `${packageName}@${latest}`];
150
206
  await options.telemetry.stage("install", async () => {
151
207
  try {
152
208
  await runProcess(command, args, signal);
@@ -166,7 +222,25 @@ export function createUpdateService(options) {
166
222
  }));
167
223
  await options.telemetry.stage("verify", async () => {
168
224
  try {
169
- await verifySkills(targetSkills, skillOptions);
225
+ try {
226
+ await verifySkills(targetSkills, skillOptions);
227
+ }
228
+ catch (verificationError) {
229
+ if (isInterruption(verificationError, signal) || !globalDirectory)
230
+ throw verificationError;
231
+ // A pnpm store cache hit may skip postinstall. Only use new Skill bytes
232
+ // from the verified replacement launcher in the same global installation.
233
+ const target = pnpmLauncherTargets(env, commandName)
234
+ .find(entry => pnpmSnapshotDirectory(entry, packageName, commandName) === globalDirectory);
235
+ if (!target)
236
+ throw verificationError;
237
+ const actual = loadBundledSkills(realpathSync(target));
238
+ if (!actual.length || actual.some(s => s.skill !== commandName || s.version !== latest)
239
+ || readInstallationOwner(dirname(dirname(actual[0].sourceDirectory))) !== "user")
240
+ throw verificationError;
241
+ await syncSkills(actual, skillOptions);
242
+ await verifySkills(actual, skillOptions);
243
+ }
170
244
  }
171
245
  catch (error) {
172
246
  if (isInterruption(error, signal))
@@ -0,0 +1,46 @@
1
+ const mediaTypes = {
2
+ avif: "image/avif",
3
+ bmp: "image/bmp",
4
+ gif: "image/gif",
5
+ heic: "image/heic",
6
+ heif: "image/heif",
7
+ jpeg: "image/jpeg",
8
+ jpg: "image/jpeg",
9
+ m4v: "video/x-m4v",
10
+ mkv: "video/x-matroska",
11
+ mov: "video/quicktime",
12
+ mp3: "audio/mpeg",
13
+ mp4: "video/mp4",
14
+ png: "image/png",
15
+ svg: "image/svg+xml",
16
+ wav: "audio/wav",
17
+ webm: "video/webm",
18
+ webp: "image/webp"
19
+ };
20
+ export function mediaFilename(url) {
21
+ const segment = url.pathname.split("/").filter(Boolean).at(-1);
22
+ if (segment === undefined)
23
+ return "creative-media";
24
+ try {
25
+ const name = decodeURIComponent(segment);
26
+ return name.trim() ? name : "creative-media";
27
+ }
28
+ catch {
29
+ return segment;
30
+ }
31
+ }
32
+ export function mediaTypeForFormat(format) {
33
+ return Object.hasOwn(mediaTypes, format) ? mediaTypes[format] : undefined;
34
+ }
35
+ // Only a concrete type can contradict a recognized file. MIME parameters are not part of the type.
36
+ export function concreteMediaType(declaration) {
37
+ const type = declaration?.split(";", 1)[0]?.trim().toLowerCase();
38
+ return type === "application/octet-stream" ? undefined : type;
39
+ }
40
+ export function mediaTypeFromFilename(filename) {
41
+ const dot = filename.lastIndexOf(".");
42
+ if (dot < 0)
43
+ return undefined;
44
+ const extension = filename.slice(dot + 1).toLowerCase();
45
+ return mediaTypeForFormat(extension);
46
+ }
@@ -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
+ }