@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
@@ -1,13 +1,23 @@
1
+ import { isDeepStrictEqual } from "node:util";
1
2
  import { setTimeout as delay } from "node:timers/promises";
2
3
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
3
4
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
4
5
  import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
6
+ import { createCanvasSegmenter } from "./canvas-matting.js";
5
7
  import { ToolInputError } from "./catalog.js";
6
- import { queryToolResult, ToolTaskCanceledError, ToolTaskFailedError } from "./tool-api-adapter.js";
7
- import { composeMatting, expansionGeometry, expansionImage, maskPng, outlineImage } from "./canvas-media.js";
8
- import { createCanvasVideo, videoRatio, videoFormat, videoEditPrompt } from "./canvas-video.js";
9
- import { canvasContent, imageResult, link, ocrResult, oneResource, record, templateResult, vectorResult } from "./canvas-results.js";
8
+ import { presentToolContent } from "./tool-output.js";
9
+ import { normalizeToolItems, queryToolResult, ToolTaskCanceledError, ToolTaskFailedError } from "./tool-api-adapter.js";
10
+ import { expansionGeometry, expansionImage, invertSelectionMask, outlineImage } from "./canvas-media.js";
11
+ import { createCanvasVideo, videoRatio, videoEditPrompt } from "./canvas-video.js";
12
+ import { canvasContent, ocrResult, oneResource, record, templateResult } from "./canvas-results.js";
10
13
  import { estimateCanvasCost } from "./canvas-pricing.js";
14
+ import { canvasProtocol, canvasRemoteControlArguments, unavailableCanvasMediaRoles } from "./canvas-models.js";
15
+ import { assertNoLocalAssetPaths } from "./argument-paths.js";
16
+ const selectionInstructions = {
17
+ "image-edit-smart": ["在青色轮廓标注的区域按要求改图,移除轮廓线。", "Apply the requested edit in the area marked by the cyan outline and remove the outline."],
18
+ "image-matting-smart": ["提取青色轮廓标注的主体,移除背景及轮廓线。", "Extract the subject marked by the cyan outline and remove the background and the outline."],
19
+ "image-remove-smart": ["消除青色轮廓标注的内容,自然补全背景并移除轮廓线。", "Remove the content marked by the cyan outline, fill its background, and remove the outline."]
20
+ };
11
21
  function rpc(name, args) {
12
22
  return { jsonrpc: "2.0", id: 0, method: "tools/call", params: { name, arguments: args } };
13
23
  }
@@ -16,7 +26,7 @@ function nonblank(value) {
16
26
  throw new RemoteProtocolError();
17
27
  return value;
18
28
  }
19
- export async function queryToolkitResult(transport, taskId, context) {
29
+ export async function queryToolkitResult(transport, taskId, context, onUnrepresented) {
20
30
  const task = await transport.getJson({ path: `/ai-toolkit/design/tool-call/tasks/${encodeURIComponent(taskId)}`, ...context.access, signal: context.signal });
21
31
  if (!record(task) || typeof task.status !== "string")
22
32
  throw new RemoteProtocolError();
@@ -28,17 +38,18 @@ export async function queryToolkitResult(transport, taskId, context) {
28
38
  if (!record(task.response) || !record(task.response.result) || task.response.result.isError !== false
29
39
  || !Array.isArray(task.response.result.content) || task.response.result.content.length === 0)
30
40
  throw new RemoteProtocolError();
31
- return { state: "complete", content: task.response.result.content.map(canvasContent) };
41
+ return { state: "complete", content: normalizeToolItems(task.response.result.content, canvasContent, onUnrepresented) };
32
42
  }
33
43
  if (!["PENDING", "RUNNING", "QUEUED", "SUBMITTED"].includes(task.status))
34
44
  throw new RemoteProtocolError();
35
45
  return { state: "pending" };
36
46
  }
37
47
  export function createCanvasToolAdapter(dependencies) {
38
- const { transport, media, telemetry } = dependencies;
48
+ const { transport, telemetry } = dependencies;
49
+ const mediaFor = (access) => typeof dependencies.media === "function" ? dependencies.media(access) : dependencies.media;
39
50
  const sleep = dependencies.sleep ?? (async (ms, signal) => { await delay(ms, undefined, { signal }); });
40
- const probe = createCanvasVideo(media);
41
- async function pipeline(context, model, stage, requiresFinalization, protocol = "dify", partialContent, verification) {
51
+ const segment = createCanvasSegmenter({ ...dependencies, wait });
52
+ async function pipeline(context, model, stage, requiresFinalization, protocol, partialContent, verification) {
42
53
  await context.observe?.({ toolPipeline: { protocol, model, stage, requiresFinalization,
43
54
  ...(partialContent ? { partialContent } : {}), ...(verification ? { verification } : {}) } });
44
55
  }
@@ -65,7 +76,9 @@ export function createCanvasToolAdapter(dependencies) {
65
76
  const result = await dependencies.recordTransport.postJson({ path: "/tb-dam/asset/id", body: {}, ...context.access, signal: context.signal });
66
77
  if (!record(result))
67
78
  throw new RemoteProtocolError();
68
- return nonblank(result.id);
79
+ const id = nonblank(result.id);
80
+ telemetry.annotate({ content_id: id });
81
+ return id;
69
82
  }
70
83
  async function call(name, args, context, protocol = "dify") {
71
84
  await context.observe?.({ submissionStarted: true });
@@ -76,9 +89,11 @@ export function createCanvasToolAdapter(dependencies) {
76
89
  }));
77
90
  if (!record(result))
78
91
  throw new RemoteProtocolError();
92
+ if (record(result.error))
93
+ throw new ToolTaskFailedError(remoteErrorEvidence(result.error));
79
94
  if (protocol === "dify" && (!record(result.result) || result.result.isError !== false)) {
80
95
  if (record(result.result) && result.result.isError === true)
81
- throw new ToolTaskFailedError(remoteErrorEvidence(result));
96
+ throw new ToolTaskFailedError(remoteErrorEvidence(result.result));
82
97
  throw new RemoteProtocolError();
83
98
  }
84
99
  const taskId = nonblank(result.task_id);
@@ -86,74 +101,25 @@ export function createCanvasToolAdapter(dependencies) {
86
101
  telemetry.annotate({ task_id: taskId });
87
102
  return telemetry.stage("wait", () => wait(async () => {
88
103
  if (protocol === "toolkit")
89
- return queryToolkitResult(transport, taskId, context);
90
- const poll = await queryToolResult(transport, { ...context.access, signal: context.signal, taskId, normalize: canvasContent,
104
+ return queryToolkitResult(transport, taskId, context, dependencies.onUnrepresented);
105
+ const poll = await queryToolResult(transport, { ...context.access, signal: context.signal, taskId, normalize: canvasContent, onUnrepresented: dependencies.onUnrepresented,
91
106
  onDifyTaskId: id => telemetry.annotate({ dify_task_id: id }) });
92
107
  if (poll.state === "failed")
93
108
  throw poll.error;
94
109
  return poll;
95
110
  }, context.signal));
96
111
  }
97
- async function sync(name, image, context) {
98
- const response = await transport.postJson({ path: "/gdesign/tool/v1/dify/call_sync", body: rpc(name, { image }),
99
- ...context.access, signal: context.signal,
100
- onDispatch: async (dispatchedAt) => { await context.observe?.({ dispatchedAt, submissionStarted: true }); } });
101
- if (!record(response))
102
- throw new RemoteProtocolError();
103
- const taskId = typeof response.task_id === "string" ? response.task_id : undefined;
104
- if (taskId) {
105
- await context.observe?.({ remoteTaskId: taskId, accepted: true });
106
- telemetry.annotate({ dify_task_id: taskId });
112
+ async function saveResult(context, model, content) {
113
+ // The completed, validated result must still reach the caller on a late cache failure (ADR 0015).
114
+ try {
115
+ await pipeline(context, model, "complete", false, canvasProtocol(model), content);
116
+ }
117
+ catch {
118
+ telemetry.annotate({ warning_codes: ["TASK_RESULT_CACHE_FAILED"] });
107
119
  }
108
- const parse = (value) => {
109
- if (!record(value) || value.error)
110
- throw new RemoteProtocolError(remoteErrorEvidence(value));
111
- if (!record(value.result)) {
112
- if (typeof value.task_id === "string" && value.task_id)
113
- return { state: "pending" };
114
- throw new RemoteProtocolError();
115
- }
116
- if (value.result.isError === true)
117
- throw new ToolTaskFailedError(remoteErrorEvidence(value));
118
- if ((value.result.isError !== undefined && value.result.isError !== false) || !Array.isArray(value.result.content))
119
- throw new RemoteProtocolError();
120
- const content = value.result.content;
121
- const status = content.find(item => record(item) && item.type === "task");
122
- if (record(status) && record(status.task)) {
123
- if (["NOT_PASSED", "FAIL"].includes(String(status.task.status)))
124
- throw new ToolTaskFailedError(remoteErrorEvidence(value));
125
- if (status.task.status === "CANCELED")
126
- throw new ToolTaskCanceledError();
127
- return { state: "pending" };
128
- }
129
- if (!content.length)
130
- return { state: "pending" };
131
- return { state: "complete", content: content.map(canvasContent) };
132
- };
133
- const direct = parse(response);
134
- if (direct.state === "complete")
135
- return direct.content;
136
- if (!taskId)
137
- throw new RemoteProtocolError();
138
- return wait(async () => parse(await transport.getJson({ path: "/gdesign/tool/v1/dify/task/process", query: { task_id: taskId },
139
- ...context.access, signal: context.signal })), context.signal);
140
- }
141
- async function segment(source, context, crop) {
142
- const { default: sharp } = await import("sharp");
143
- const input = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).png().toBuffer();
144
- const uri = await media.upload(input, "png", context.access, context.signal);
145
- const classification = await sync("matting-classify", uri, context);
146
- const classificationText = classification.find(item => item.type === "text");
147
- if (!classificationText || classificationText.type !== "text" || !/^[012]$/u.test(classificationText.text.trim()))
148
- throw new RemoteProtocolError();
149
- const category = Number(classificationText.text.trim());
150
- const scene = ["matting-graphs", "matting-person", "matting-product"][category];
151
- const maskUri = oneResource(await sync(scene, uri, context));
152
- const bytes = await composeMatting(source, await media.read(maskUri, context.signal), category === 1 ? "alpha" : "red", crop);
153
- const finalUri = await media.upload(bytes, "png", context.access, context.signal);
154
- return { content: link(finalUri, "cutout.png", "image/png"), inputUri: uri, scene: ["graphic", "portrait", "product"][category] };
155
120
  }
156
121
  async function executeCanvas(invocation, context) {
122
+ const media = mediaFor(context.access);
157
123
  const { model, arguments: args } = invocation;
158
124
  const id = model.model;
159
125
  const code = model.execution.code;
@@ -164,92 +130,98 @@ export function createCanvasToolAdapter(dependencies) {
164
130
  await context.observe?.({ toolUsage: { model: id, cost } });
165
131
  }
166
132
  const fields = Array.isArray(configuration.fields) ? configuration.fields.filter(record) : [];
167
- const backend = {};
133
+ const protocol = canvasProtocol(id);
134
+ telemetry.annotate({ execution_protocol: protocol });
168
135
  const extra = Object.entries(args).filter(([key]) => key !== "model" && !model.parameters.some(field => field.name === key));
169
- // Dedicated adapters translate public fields; generic fields can travel only on an actual service request.
136
+ const unavailable = unavailableCanvasMediaRoles({ properties: Object.fromEntries(model.parameters.map(p => [p.name, true])) });
137
+ for (const [key, value] of extra) {
138
+ if (unavailable.includes(key) || id === "image-matting-standard")
139
+ throw new ToolInputError("unmapped_argument", "/arguments/" + key);
140
+ if (["content_id", "contentid", "async"].includes(key))
141
+ throw new ToolInputError("managed_argument", "/arguments/" + key);
142
+ assertNoLocalAssetPaths(value, "/arguments/" + key);
143
+ }
144
+ if (id.startsWith("image-matting-") && args.cropToSubject !== undefined && typeof args.cropToSubject !== "boolean") {
145
+ throw new ToolInputError("boolean_required", "/arguments/cropToSubject");
146
+ }
147
+ if (["image-edit-standard", "image-remove-standard"].includes(id) && typeof args.mask !== "string") {
148
+ throw new ToolInputError("mask_required", "/arguments/mask");
149
+ }
150
+ if (((typeof args.mask === "string" && Object.hasOwn(selectionInstructions, id)) || id === "video-edit-smart" || id === "image-expand-smart")
151
+ && args.prompt !== undefined && typeof args.prompt !== "string") {
152
+ throw new ToolInputError("text_required", "/arguments/prompt");
153
+ }
154
+ // These public aliases refer to one service field. Normalize and compare both before touching media.
155
+ const normalizedExtra = canvasRemoteControlArguments(id, Object.fromEntries(extra));
156
+ const controls = Object.entries(args).filter(([name]) => ["resolution", "quality", "audioEnabled", "targetLongEdge", "maxLayers", "max_layers"].includes(name));
157
+ for (const [key, value] of controls) {
158
+ assertNoLocalAssetPaths(value, "/arguments/" + key, model.parameters.find(field => field.name === key)?.type);
159
+ }
160
+ if (args.prompt && typeof args.prompt === "object")
161
+ assertNoLocalAssetPaths(args.prompt, "/arguments/prompt");
162
+ const mappedControls = canvasRemoteControlArguments(id, Object.fromEntries(controls));
163
+ const backend = { ...mappedControls };
170
164
  function serviceArguments() {
171
- for (const [key] of extra) {
172
- if (["content_id", "contentid", "async", "model"].includes(key) || (Object.hasOwn(backend, key) && backend[key] !== args[key])) {
173
- throw new ToolInputError("managed_argument", "/arguments/" + key);
174
- }
165
+ for (const [key, value] of Object.entries(normalizedExtra)) {
166
+ if (Object.hasOwn(backend, key) && !isDeepStrictEqual(backend[key], value))
167
+ throw new ToolInputError("conflicting_arguments", "/arguments/" + key);
175
168
  }
176
- return { ...Object.fromEntries(extra), ...backend };
169
+ return { ...normalizedExtra, ...backend };
177
170
  }
178
171
  for (const field of fields)
179
172
  if (["model", "async"].includes(String(field.key)) && field.default_value !== undefined)
180
173
  backend[String(field.key)] = field.default_value;
181
- if (id === "image-matting-smart")
182
- backend.ratio = "original";
183
- for (const key of ["resolution", "quality", "audioEnabled"])
184
- if (args[key] !== undefined)
185
- backend[key] = args[key];
186
- const isMatting = id.startsWith("image-matting-");
187
- const protocol = id.startsWith("image-layers-") ? "toolkit" : "dify";
174
+ const isMatting = model.tool === "image.matting";
188
175
  await pipeline(context, id, "preparing", isMatting, protocol);
189
176
  if (id.startsWith("video-")) {
177
+ const probe = createCanvasVideo(media);
190
178
  const sourceUri = args.video;
191
179
  const source = await probe(sourceUri, context.signal);
192
180
  const rounded = Math.round(source.duration);
193
181
  const references = args.referenceVideos ?? [];
194
182
  let total = source.duration;
195
- for (const reference of references)
196
- total += (await probe(reference, context.signal)).duration;
197
- await quote({ time: Math.ceil(source.duration), duration: rounded, video_urls: Math.round(total) });
198
- async function remote(uri) {
199
- if (!uri.startsWith("file:"))
200
- return uri;
201
- const bytes = await media.read(uri, context.signal, 512 * 1024 * 1024);
202
- return media.upload(bytes, videoFormat(bytes), context.access, context.signal);
183
+ if (model.cost) {
184
+ for (const reference of references) {
185
+ try {
186
+ total += (await probe(reference, context.signal)).duration;
187
+ }
188
+ catch {
189
+ context.signal.throwIfAborted();
190
+ total = undefined;
191
+ break;
192
+ }
193
+ }
203
194
  }
195
+ await quote({ time: Math.ceil(source.duration), duration: rounded, ...(total === undefined ? {} : { video_urls: Math.round(total) }) });
196
+ const remote = (uri) => uri.startsWith("file:") ? media.uploadFile(uri, context.access, context.signal) : uri;
204
197
  backend.video_urls = JSON.stringify(await Promise.all([sourceUri, ...references].map(remote)));
205
198
  if (id === "video-enhance-standard")
206
199
  backend.time = String(Math.ceil(source.duration));
207
200
  else {
208
201
  backend.duration = String(rounded);
209
202
  backend.ratio = videoRatio(source);
210
- backend.prompt = id === "video-edit-smart" ? videoEditPrompt({ video: sourceUri, prompt: args.prompt,
203
+ backend.prompt = id === "video-edit-smart" ? videoEditPrompt({ video: sourceUri, ...(typeof args.prompt === "string" ? { prompt: args.prompt } : {}),
211
204
  referenceImages: args.referenceImages ?? [], referenceVideos: references,
212
205
  referenceAudios: args.referenceAudios ?? [] }, dependencies.english) : args.prompt;
213
206
  }
214
207
  for (const [key, target] of [["referenceImages", "image_urls"], ["referenceAudios", "audio_urls"]]) {
215
208
  if (Array.isArray(args[key]))
216
- backend[target] = JSON.stringify(await Promise.all(args[key].map(async (uri) => {
217
- if (!uri.startsWith("file:"))
218
- return uri;
219
- if (key === "referenceAudios")
220
- return media.uploadFile(uri, context.access, context.signal);
221
- const image = await media.image(uri, context.signal);
222
- return media.upload(image.bytes, "png", context.access, context.signal);
223
- })));
209
+ backend[target] = JSON.stringify(await Promise.all(args[key].map(remote)));
224
210
  }
225
211
  backend.content_id = await contentId(context);
226
212
  await pipeline(context, id, "submitted", false, "dify");
227
213
  const content = await call(code, serviceArguments(), context);
228
- const uri = oneResource(content);
229
- let output;
230
- try {
231
- output = await probe(uri, context.signal);
232
- }
233
- catch (cause) {
234
- if (context.signal.aborted)
235
- throw context.signal.reason;
236
- throw new RemoteProtocolError({}, cause, "VIDEO_OUTPUT_INVALID");
237
- }
238
- return link(uri, `result.${output.format}`, output.format === "mov" ? "video/quicktime" : `video/${output.format}`);
214
+ return presentToolContent(content, "video", dependencies.onMissingMedia);
239
215
  }
240
216
  const { default: sharp } = await import("sharp");
241
217
  let source = await media.image(args.image, context.signal);
242
- let selection;
243
- if (typeof args.mask === "string")
244
- selection = await media.mask(args.mask, source, context.signal);
245
- if (id === "image-matting-standard") {
218
+ const selection = typeof args.mask === "string" ? await media.read(args.mask, context.signal) : undefined;
219
+ if (protocol === "sync") {
246
220
  if (!dependencies.standardMatting)
247
221
  throw new ToolInputError("matting_billing_contract_unavailable", "/model");
248
222
  if (model.cost === undefined || model.cost.minimum !== model.cost.maximum)
249
223
  throw new ToolInputError("matting_quote_unavailable", "/model");
250
- if (extra.length)
251
- throw new ToolInputError("unmapped_argument", "/arguments/" + extra[0][0]);
252
- return dependencies.standardMatting(source, context, model.cost.maximum, () => segment(source, context, args.cropToSubject === true));
224
+ return dependencies.standardMatting(source, context, model.cost.maximum, () => segment(source, media, context, args.cropToSubject === true));
253
225
  }
254
226
  if (id === "image-text-edit") {
255
227
  const replacements = args.replacements;
@@ -258,6 +230,7 @@ export function createCanvasToolAdapter(dependencies) {
258
230
  if (Object.hasOwn(fields, key))
259
231
  throw new ToolInputError("managed_argument", `/arguments/replacements/${index}/${key}`);
260
232
  }
233
+ assertNoLocalAssetPaths(fields, `/arguments/replacements/${index}`);
261
234
  return { ...fields, origin: from, new: to === "" ? "REMOVE_TEXT" : to };
262
235
  }));
263
236
  }
@@ -266,15 +239,19 @@ export function createCanvasToolAdapter(dependencies) {
266
239
  const info = await sharp(bytes).metadata();
267
240
  source = { bytes, width: info.width, height: info.height };
268
241
  }
269
- if (id.startsWith("image-layers-")) {
242
+ if (protocol === "toolkit") {
270
243
  const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).png().toBuffer();
271
244
  const info = await sharp(bytes).metadata();
272
245
  source = { bytes, width: info.width, height: info.height };
273
246
  }
274
- await quote({ resolution: args.targetLongEdge, max_layers: args.maxLayers });
247
+ const layerCount = mappedControls.max_layers;
248
+ await quote({ resolution: mappedControls.resolution,
249
+ max_layers: typeof layerCount === "string" && /^\d+$/u.test(layerCount) ? Number(layerCount) : layerCount });
275
250
  let prepared = source.bytes;
276
- if (selection && id.endsWith("-smart"))
251
+ if (selection && Object.hasOwn(selectionInstructions, id))
277
252
  prepared = await outlineImage(source, selection);
253
+ if (id === "image-matting-smart")
254
+ backend.ratio = "original";
278
255
  if (id.startsWith("image-expand-")) {
279
256
  const canvas = args.canvas;
280
257
  const placement = args.placement;
@@ -285,7 +262,10 @@ export function createCanvasToolAdapter(dependencies) {
285
262
  while (b)
286
263
  [a, b] = [b, a % b];
287
264
  backend.ratio = `${canvas.width / a}:${canvas.height / a}`;
288
- backend.prompt = `扩展第1张图的纯绿色区域,保留原图所在位置和内容,去除绿幕。${args.prompt ?? ""}`;
265
+ const instruction = dependencies.english
266
+ ? "Extend the green area of the first image, keeping the original image at its position and removing the green screen."
267
+ : "扩展第1张图的纯绿色区域,保留原图所在位置和内容,去除绿幕。";
268
+ backend.prompt = typeof args.prompt === "string" ? instruction + "\n" + args.prompt : instruction;
289
269
  }
290
270
  else {
291
271
  prepared = await sharp(source.bytes).flatten({ background: "white" }).png().toBuffer();
@@ -294,18 +274,19 @@ export function createCanvasToolAdapter(dependencies) {
294
274
  }
295
275
  }
296
276
  const image = await media.upload(prepared, id === "image-ocr" || id === "image-text-edit" ? "jpg" : "png", context.access, context.signal);
297
- if (id.startsWith("image-layers-")) {
277
+ if (protocol === "toolkit") {
298
278
  backend.url = image;
299
279
  backend.type = id === "image-layers-smart" ? "seedream" : "codia";
300
280
  if (id === "image-layers-smart") {
301
- if (args.maxLayers !== undefined)
302
- backend.max_layers = typeof args.maxLayers === "number" ? String(args.maxLayers) : args.maxLayers;
303
281
  const resolutionField = fields.find(field => field.key === "resolution");
304
- const options = resolutionField?.options;
305
- const onlyTwoK = resolutionField?.default_value === "2K" && Array.isArray(options)
306
- && options.length === 1 && record(options[0]) && options[0].value === "2K";
307
- if (args.resolution === undefined)
308
- backend.resolution = onlyTwoK || source.width * source.height > 1280 * 720 ? "2K" : "1K";
282
+ if (args.resolution === undefined) {
283
+ const tiers = Array.isArray(configuration.layerTiers) ? configuration.layerTiers
284
+ : Array.isArray(resolutionField?.options) ? resolutionField.options.filter(record).map(option => option.value) : [];
285
+ const preferred = source.width * source.height > 1280 * 720 ? "2K" : "1K";
286
+ const tier = tiers.length === 1 ? tiers[0] : tiers.includes(preferred) ? preferred : resolutionField?.default_value;
287
+ if (typeof tier === "string" && (!tiers.length || tiers.includes(tier)))
288
+ backend.resolution = tier;
289
+ }
309
290
  const field = fields.find(field => field.key === "seedream_model");
310
291
  if (args.seedream_model === undefined && field?.default_value !== undefined)
311
292
  backend.seedream_model = nonblank(field.default_value);
@@ -315,19 +296,18 @@ export function createCanvasToolAdapter(dependencies) {
315
296
  backend.image_urls = JSON.stringify([image]);
316
297
  else
317
298
  backend.image = image;
318
- if (selection && id.endsWith("-standard"))
319
- backend.mask = await media.upload(await maskPng(selection, source.width, source.height, id === "image-edit-standard"), "png", context.access, context.signal);
299
+ if (selection && (id === "image-edit-standard" || id === "image-remove-standard")) {
300
+ const bytes = id === "image-edit-standard" ? await invertSelectionMask(selection) : selection;
301
+ backend.mask = await media.upload(bytes, "png", context.access, context.signal);
302
+ }
320
303
  if (args.prompt !== undefined && id !== "image-expand-smart")
321
304
  backend.prompt = args.prompt;
322
- if (selection && id.endsWith("-smart"))
323
- backend.prompt = `仅处理青色边界标注的区域,移除青色标记。${backend.prompt ?? ""}`;
324
- if (id === "image-enhance-standard" && args.targetLongEdge !== undefined)
325
- backend.resolution = args.targetLongEdge;
305
+ if (selection && Object.hasOwn(selectionInstructions, id)) {
306
+ const cue = selectionInstructions[id][dependencies.english ? 1 : 0];
307
+ backend.prompt = typeof args.prompt === "string" ? cue + "\n" + args.prompt : cue;
308
+ }
326
309
  if (Array.isArray(args.referenceImages)) {
327
- const references = await Promise.all(args.referenceImages.map(async (uri) => {
328
- const reference = await media.image(uri, context.signal);
329
- return media.upload(reference.bytes, "png", context.access, context.signal);
330
- }));
310
+ const references = await Promise.all(args.referenceImages.map(uri => uri.startsWith("file:") ? media.uploadFile(uri, context.access, context.signal) : uri));
331
311
  if (id === "image-edit-smart")
332
312
  backend.reference_images = JSON.stringify(references);
333
313
  else
@@ -336,34 +316,31 @@ export function createCanvasToolAdapter(dependencies) {
336
316
  backend.content_id = await contentId(context);
337
317
  if (id === "image-remove-standard")
338
318
  backend.contentid = backend.content_id;
339
- await pipeline(context, id, "submitted", isMatting, protocol, undefined, id === "image-ocr" ? { ocr: { uri: image, width: source.width, height: source.height } } : undefined);
319
+ const toolPipeline = { protocol, model: id, stage: "submitted", requiresFinalization: isMatting,
320
+ ...(isMatting ? { matting: { cropToSubject: args.cropToSubject === true } } : {}),
321
+ ...(id === "image-ocr" ? { verification: { ocr: { uri: image, width: source.width, height: source.height } } } : {}) };
322
+ await context.observe?.({ toolPipeline });
340
323
  const content = await call(code, serviceArguments(), context, protocol);
341
324
  if (id === "image-matting-smart") {
342
- await pipeline(context, id, "segmenting", true, "sync", content);
343
- const generated = await media.image(oneResource(content), context.signal);
344
- const { content: result } = await segment(generated, context, args.cropToSubject === true);
345
- return result;
325
+ const sourceUri = oneResource(content);
326
+ const generated = await media.image(sourceUri, context.signal);
327
+ const result = await segment(generated, media, context, args.cropToSubject === true, {
328
+ ...toolPipeline, matting: { cropToSubject: args.cropToSubject === true, sourceUri }
329
+ });
330
+ return content.map(item => item.type === "resource_link" ? result.content[0] : item);
346
331
  }
347
332
  if (id === "image-ocr")
348
333
  return ocrResult(content, { uri: image, width: source.width, height: source.height });
349
- if (id === "image-vectorize")
350
- return vectorResult(content, media, context.signal);
351
- if (id.startsWith("image-layers-"))
334
+ if (protocol === "toolkit")
352
335
  return templateResult(content, media, context.signal, dependencies.english);
353
- return imageResult(content, media, context.signal);
336
+ return presentToolContent(content, "image", dependencies.onMissingMedia);
354
337
  }
355
338
  return {
356
339
  async execute(input) {
357
340
  if (input.invocation.kind !== "canvas")
358
341
  return dependencies.fallback.execute(input);
359
342
  const result = await executeCanvas(input.invocation, input);
360
- // A late recovery-cache failure must not discard an already validated result (ADR 0015).
361
- try {
362
- await pipeline(input, input.invocation.model.model, "complete", false, input.invocation.model.tool === "image.layers" ? "toolkit" : "dify", result);
363
- }
364
- catch {
365
- telemetry.annotate({ warning_codes: ["TASK_RESULT_CACHE_FAILED"] });
366
- }
343
+ await saveResult(input, input.invocation.model.model, result);
367
344
  return result;
368
345
  },
369
346
  async submit(input) {
@@ -3,7 +3,9 @@ import { promisify } from "node:util";
3
3
  import { mkdtemp, writeFile, rm } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
+ import { hasWebmDocType } from "../../platform/webm-header.js";
6
7
  import { ToolInputError } from "./catalog.js";
8
+ import { resolveFfprobeExecutable } from "./ffprobe-executable.js";
7
9
  const run = promisify(execFile);
8
10
  /** WAN references are numbered per media type, independently of the uploaded URL's filename. */
9
11
  export function videoEditPrompt(input, english = false) {
@@ -14,6 +16,7 @@ export function videoEditPrompt(input, english = false) {
14
16
  name = decodeURIComponent(name);
15
17
  }
16
18
  catch { /* Preserve malformed percent escapes as literal filename data. */ }
19
+ name = name.replaceAll("\\", "/").split("/").at(-1) ?? "";
17
20
  // Quote filename data; never forward local directories, URL credentials, query tokens or fragments.
18
21
  return `${label}:${role}${name ? `${english ? ", original filename " : ",原文件名 "}${JSON.stringify(name)}` : ""}`;
19
22
  }
@@ -24,52 +27,56 @@ export function videoEditPrompt(input, english = false) {
24
27
  bindings.push(binding(`视频${index + 2}`, uri, english ? "reference video" : "参考视频"));
25
28
  for (const [index, uri] of (input.referenceAudios ?? []).entries())
26
29
  bindings.push(binding(`音频${index + 1}`, uri, english ? "reference audio" : "参考音频"));
27
- return `${english ? "Media bindings (filenames identify assets only):" : "素材对应关系(文件名仅用于识别素材):"}\n${bindings.join("\n")}\n${english ? "User instructions:" : "用户要求:"}\n${input.prompt}`;
30
+ const header = english ? "Media bindings (filenames identify assets only):" : "素材对应关系(文件名仅用于识别素材):";
31
+ const media = [header, ...bindings].join("\n");
32
+ return input.prompt === undefined ? media : [media, english ? "User instructions:" : "用户要求:", input.prompt].join("\n");
28
33
  }
29
34
  export function videoFormat(bytes) {
30
35
  if (bytes.length >= 12 && bytes.subarray(4, 8).toString() === "ftyp")
31
36
  return bytes.subarray(8, 12).toString() === "qt " ? "mov" : "mp4";
32
- if (bytes.subarray(0, 4).equals(Buffer.from([0x1a, 0x45, 0xdf, 0xa3])))
37
+ if (hasWebmDocType(bytes))
33
38
  return "webm";
34
39
  throw new ToolInputError("video_format_requires_mp4_mov_webm", "/arguments/video");
35
40
  }
41
+ async function probeVideo(media, uri, signal) {
42
+ const bytes = await media.read(uri, signal, 512 * 1024 * 1024);
43
+ const format = videoFormat(bytes);
44
+ const directory = await mkdtemp(join(tmpdir(), "gd-cli-video-"));
45
+ try {
46
+ const path = join(directory, `input.${format}`);
47
+ await writeFile(path, bytes, { mode: 0o600, signal });
48
+ const { default: probe } = await import("@ffprobe-installer/ffprobe");
49
+ const probePath = await resolveFfprobeExecutable(probe.path, directory);
50
+ const { stdout } = await run(probePath, ["-v", "error", "-protocol_whitelist", "file", "-format_whitelist", "mov,matroska,webm",
51
+ "-show_format", "-show_streams", "-of", "json", path], { signal, timeout: 30_000, maxBuffer: 1024 * 1024 });
52
+ const result = JSON.parse(stdout);
53
+ const stream = result.streams?.find(stream => stream.codec_type === "video");
54
+ const duration = Number(stream?.duration ?? result.format?.duration);
55
+ const width = Number(stream?.width);
56
+ const height = Number(stream?.height);
57
+ if (!stream || !Number.isInteger(width) || width <= 0
58
+ || !Number.isInteger(height) || height <= 0) {
59
+ throw new ToolInputError("video_metadata_invalid", "/arguments/video");
60
+ }
61
+ return { duration, width, height, hasAudio: result.streams.some(stream => stream.codec_type === "audio"), format };
62
+ }
63
+ catch (cause) {
64
+ if (signal.aborted)
65
+ throw signal.reason;
66
+ if (cause instanceof ToolInputError)
67
+ throw cause;
68
+ throw new ToolInputError("video_probe_failed", "/arguments/video", [], cause);
69
+ }
70
+ finally {
71
+ await rm(directory, { recursive: true, force: true });
72
+ }
73
+ }
36
74
  export function createCanvasVideo(media) {
37
75
  return async (uri, signal) => {
38
- const bytes = await media.read(uri, signal, 512 * 1024 * 1024);
39
- const format = videoFormat(bytes);
40
- const directory = await mkdtemp(join(tmpdir(), "gd-cli-video-"));
41
- try {
42
- const path = join(directory, `input.${format}`);
43
- await writeFile(path, bytes, { mode: 0o600, signal });
44
- const { default: probe } = await import("@ffprobe-installer/ffprobe");
45
- const { stdout } = await run(probe.path, ["-v", "error", "-protocol_whitelist", "file", "-format_whitelist", "mov,matroska,webm",
46
- "-show_format", "-show_streams", "-of", "json", path], { signal, timeout: 30_000, maxBuffer: 1024 * 1024 });
47
- const result = JSON.parse(stdout);
48
- const stream = result.streams?.find(stream => stream.codec_type === "video");
49
- const duration = Number(stream?.duration ?? result.format?.duration);
50
- const width = Number(stream?.width);
51
- const height = Number(stream?.height);
52
- if (!stream || !Number.isFinite(duration) || duration <= 0 || !Number.isInteger(width) || width <= 0
53
- || !Number.isInteger(height) || height <= 0) {
54
- throw new ToolInputError("video_metadata_invalid", "/arguments/video");
55
- }
56
- const decoded = await run(probe.path, ["-v", "error", "-protocol_whitelist", "file", "-format_whitelist", "mov,matroska,webm",
57
- "-read_intervals", "%+1", "-select_streams", "v:0", "-show_frames", "-show_entries", "frame=media_type", "-of", "json", path], { signal, timeout: 30_000, maxBuffer: 1024 * 1024 });
58
- const frames = JSON.parse(decoded.stdout);
59
- if (!frames.frames?.some(frame => frame.media_type === "video"))
60
- throw new ToolInputError("video_decode_failed", "/arguments/video");
61
- return { duration, width, height, hasAudio: result.streams.some(stream => stream.codec_type === "audio"), format };
62
- }
63
- catch (cause) {
64
- if (signal.aborted)
65
- throw signal.reason;
66
- if (cause instanceof ToolInputError)
67
- throw cause;
68
- throw new ToolInputError("video_probe_failed", "/arguments/video", [], cause);
69
- }
70
- finally {
71
- await rm(directory, { recursive: true, force: true });
72
- }
76
+ const info = await probeVideo(media, uri, signal);
77
+ if (!Number.isFinite(info.duration) || info.duration <= 0)
78
+ throw new ToolInputError("video_metadata_invalid", "/arguments/video");
79
+ return info;
73
80
  };
74
81
  }
75
82
  export function videoRatio(info) {