@insmind/cli 1.7.1 → 1.9.0

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 (73) hide show
  1. package/contracts/operations/model.get/input.schema.json +5 -0
  2. package/contracts/operations/model.get/output.schema.json +9 -1
  3. package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
  4. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +39 -0
  5. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +31 -0
  6. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +26 -0
  7. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +25 -0
  8. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +72 -0
  9. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +58 -0
  10. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +20 -0
  11. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +26 -0
  12. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +34 -0
  13. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +24 -0
  14. package/contracts/operations/tool.call/models/image-ocr.schema.json +20 -0
  15. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +30 -0
  16. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +25 -0
  17. package/contracts/operations/tool.call/models/image-text-edit.schema.json +43 -0
  18. package/contracts/operations/tool.call/models/image-vectorize.schema.json +20 -0
  19. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +68 -0
  20. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +32 -0
  21. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +26 -0
  22. package/contracts/operations/tool.call/ocr-payload.schema.json +65 -0
  23. package/contracts/operations/tool.call/output.schema.json +38 -0
  24. package/contracts/operations/tool.call/template-payload.schema.json +95 -0
  25. package/dist/src/bootstrap/create-runtime.js +61 -25
  26. package/dist/src/bootstrap/validators.js +1 -1
  27. package/dist/src/cli/action-binding.js +3 -0
  28. package/dist/src/cli/agent-commands.js +1 -0
  29. package/dist/src/cli/errors.js +43 -10
  30. package/dist/src/cli/model-commands.js +7 -4
  31. package/dist/src/cli/observed-errors.js +13 -5
  32. package/dist/src/cli/task-commands.js +1 -1
  33. package/dist/src/cli/tool-commands.js +3 -1
  34. package/dist/src/contracts/schema.js +4 -1
  35. package/dist/src/features/agent/creative-protocol.js +22 -5
  36. package/dist/src/features/agent/resource-authorizer.js +1 -0
  37. package/dist/src/features/agent/use-cases.js +15 -5
  38. package/dist/src/features/auth/sso-service.js +13 -4
  39. package/dist/src/features/dam/dam-api-adapter.js +1 -0
  40. package/dist/src/features/dam/file-downloader.js +23 -2
  41. package/dist/src/features/task/store.js +8 -4
  42. package/dist/src/features/task/use-cases.js +14 -11
  43. package/dist/src/features/tool/canvas-copy.js +61 -0
  44. package/dist/src/features/tool/canvas-media.js +193 -0
  45. package/dist/src/features/tool/canvas-models.js +109 -0
  46. package/dist/src/features/tool/canvas-pricing.js +81 -0
  47. package/dist/src/features/tool/canvas-recovery.js +68 -0
  48. package/dist/src/features/tool/canvas-results.js +144 -0
  49. package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
  50. package/dist/src/features/tool/canvas-video.js +84 -0
  51. package/dist/src/features/tool/catalog.js +35 -13
  52. package/dist/src/features/tool/dynamic-schema.js +52 -23
  53. package/dist/src/features/tool/matting-billing.js +103 -0
  54. package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
  55. package/dist/src/features/tool/resource-authorizer.js +34 -0
  56. package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
  57. package/dist/src/features/tool/tool-api-adapter.js +24 -5
  58. package/dist/src/features/tool/use-cases.js +28 -3
  59. package/dist/src/features/update/update-service.js +4 -2
  60. package/dist/src/platform/file-lock.js +12 -0
  61. package/dist/src/platform/local-json-file.js +19 -5
  62. package/dist/src/platform/safe-upload-file.js +18 -10
  63. package/dist/src/platform/schema-issues.js +47 -2
  64. package/dist/src/platform/text-output.js +17 -4
  65. package/dist/src/product/config.js +12 -1
  66. package/dist/src/telemetry/failure-summary.js +18 -0
  67. package/package.json +5 -4
  68. package/skills/insmind-cli/SKILL.md +2 -0
  69. package/skills/insmind-cli/references/creation.md +2 -0
  70. package/skills/insmind-cli/references/generation-constraints.md +3 -1
  71. package/skills/insmind-cli/references/matting.md +29 -0
  72. package/skills/insmind-cli/references/media-tools.md +40 -0
  73. package/skills/insmind-cli/references/tool.md +2 -2
@@ -0,0 +1,366 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
3
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
4
+ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
5
+ 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";
10
+ import { estimateCanvasCost } from "./canvas-pricing.js";
11
+ function rpc(name, args) {
12
+ return { jsonrpc: "2.0", id: 0, method: "tools/call", params: { name, arguments: args } };
13
+ }
14
+ function nonblank(value) {
15
+ if (typeof value !== "string" || !value.trim())
16
+ throw new RemoteProtocolError();
17
+ return value;
18
+ }
19
+ export async function queryToolkitResult(transport, taskId, context) {
20
+ const task = await transport.getJson({ path: `/ai-toolkit/design/tool-call/tasks/${encodeURIComponent(taskId)}`, ...context.access, signal: context.signal });
21
+ if (!record(task) || typeof task.status !== "string")
22
+ throw new RemoteProtocolError();
23
+ if (task.status === "CANCELLED")
24
+ throw new ToolTaskCanceledError();
25
+ if (task.status === "FAILED")
26
+ throw new ToolTaskFailedError(remoteErrorEvidence(task.response));
27
+ if (task.status === "SUCCEEDED") {
28
+ if (!record(task.response) || !record(task.response.result) || task.response.result.isError !== false
29
+ || !Array.isArray(task.response.result.content) || task.response.result.content.length === 0)
30
+ throw new RemoteProtocolError();
31
+ return { state: "complete", content: task.response.result.content.map(canvasContent) };
32
+ }
33
+ if (!["PENDING", "RUNNING", "QUEUED", "SUBMITTED"].includes(task.status))
34
+ throw new RemoteProtocolError();
35
+ return { state: "pending" };
36
+ }
37
+ export function createCanvasToolAdapter(dependencies) {
38
+ const { transport, media, telemetry } = dependencies;
39
+ 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) {
42
+ await context.observe?.({ toolPipeline: { protocol, model, stage, requiresFinalization,
43
+ ...(partialContent ? { partialContent } : {}), ...(verification ? { verification } : {}) } });
44
+ }
45
+ async function wait(read, signal) {
46
+ let failures = 0;
47
+ while (true) {
48
+ signal.throwIfAborted();
49
+ try {
50
+ const result = await read();
51
+ failures = 0;
52
+ if (result.state === "complete")
53
+ return result.content;
54
+ }
55
+ catch (error) {
56
+ if (signal.aborted)
57
+ throw signal.reason;
58
+ if (!(error instanceof RemoteRequestError) || !error.transient || ++failures > 3)
59
+ throw error;
60
+ }
61
+ await sleep(2000, signal);
62
+ }
63
+ }
64
+ async function contentId(context) {
65
+ const result = await dependencies.recordTransport.postJson({ path: "/tb-dam/asset/id", body: {}, ...context.access, signal: context.signal });
66
+ if (!record(result))
67
+ throw new RemoteProtocolError();
68
+ return nonblank(result.id);
69
+ }
70
+ async function call(name, args, context, protocol = "dify") {
71
+ await context.observe?.({ submissionStarted: true });
72
+ const result = await telemetry.stage("submit", () => transport.postJson({
73
+ path: protocol === "toolkit" ? "/ai-toolkit/design/tool-call/async" : "/gdesign/tool/v1/dify/call_async",
74
+ body: rpc(name, { ...args, content_id: args.content_id ?? "" }), ...context.access, signal: context.signal,
75
+ onDispatch: async (dispatchedAt) => { await context.observe?.({ dispatchedAt }); }
76
+ }));
77
+ if (!record(result))
78
+ throw new RemoteProtocolError();
79
+ if (protocol === "dify" && (!record(result.result) || result.result.isError !== false)) {
80
+ if (record(result.result) && result.result.isError === true)
81
+ throw new ToolTaskFailedError(remoteErrorEvidence(result));
82
+ throw new RemoteProtocolError();
83
+ }
84
+ const taskId = nonblank(result.task_id);
85
+ await context.observe?.({ remoteTaskId: taskId, accepted: true });
86
+ telemetry.annotate({ task_id: taskId });
87
+ return telemetry.stage("wait", () => wait(async () => {
88
+ if (protocol === "toolkit")
89
+ return queryToolkitResult(transport, taskId, context);
90
+ const poll = await queryToolResult(transport, { ...context.access, signal: context.signal, taskId, normalize: canvasContent,
91
+ onDifyTaskId: id => telemetry.annotate({ dify_task_id: id }) });
92
+ if (poll.state === "failed")
93
+ throw poll.error;
94
+ return poll;
95
+ }, context.signal));
96
+ }
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 });
107
+ }
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
+ }
156
+ async function executeCanvas(invocation, context) {
157
+ const { model, arguments: args } = invocation;
158
+ const id = model.model;
159
+ const code = model.execution.code;
160
+ const configuration = model.execution.configuration;
161
+ async function quote(quantities) {
162
+ const cost = estimateCanvasCost(model, quantities);
163
+ if (!cost)
164
+ throw new ToolInputError("component_quote_unavailable", "/model");
165
+ await context.observe?.({ toolUsage: { model: id, cost } });
166
+ }
167
+ const fields = Array.isArray(configuration.fields) ? configuration.fields.filter(record) : [];
168
+ const backend = {};
169
+ for (const field of fields)
170
+ if (["model", "async"].includes(String(field.key)) && field.default_value !== undefined)
171
+ backend[String(field.key)] = field.default_value;
172
+ if (id === "image-matting-smart")
173
+ backend.ratio = "original";
174
+ for (const key of ["resolution", "quality", "audioEnabled"])
175
+ if (args[key] !== undefined)
176
+ backend[key] = args[key];
177
+ const isMatting = id.startsWith("image-matting-");
178
+ const protocol = id.startsWith("image-layers-") ? "toolkit" : "dify";
179
+ await pipeline(context, id, "preparing", isMatting, protocol);
180
+ if (id.startsWith("video-")) {
181
+ const sourceUri = args.video;
182
+ const source = await probe(sourceUri, context.signal);
183
+ const rounded = Math.round(source.duration);
184
+ if (id !== "video-enhance-standard" && (rounded < 2 || rounded > 30)
185
+ || id === "video-edit-smart" && source.duration > 15)
186
+ throw new ToolInputError("video_duration_unsupported", "/arguments/video");
187
+ const references = args.referenceVideos ?? [];
188
+ let total = source.duration;
189
+ for (const reference of references)
190
+ total += (await probe(reference, context.signal)).duration;
191
+ if (id === "video-edit-smart" && total > 15)
192
+ throw new ToolInputError("reference_video_duration_exceeded", "/arguments/referenceVideos");
193
+ await quote({ time: Math.ceil(source.duration), duration: rounded, video_urls: Math.round(total) });
194
+ async function remote(uri) {
195
+ if (!uri.startsWith("file:"))
196
+ return uri;
197
+ const bytes = await media.read(uri, context.signal, 512 * 1024 * 1024);
198
+ return media.upload(bytes, videoFormat(bytes), context.access, context.signal);
199
+ }
200
+ backend.video_urls = JSON.stringify(await Promise.all([sourceUri, ...references].map(remote)));
201
+ if (id === "video-enhance-standard")
202
+ backend.time = String(Math.ceil(source.duration));
203
+ else {
204
+ backend.duration = String(rounded);
205
+ backend.ratio = videoRatio(source);
206
+ backend.prompt = id === "video-edit-smart" ? videoEditPrompt({ video: sourceUri, prompt: args.prompt,
207
+ referenceImages: args.referenceImages ?? [], referenceVideos: references,
208
+ referenceAudios: args.referenceAudios ?? [] }, dependencies.english) : args.prompt;
209
+ }
210
+ for (const [key, target] of [["referenceImages", "image_urls"], ["referenceAudios", "audio_urls"]]) {
211
+ if (Array.isArray(args[key]))
212
+ backend[target] = JSON.stringify(await Promise.all(args[key].map(async (uri) => {
213
+ if (!uri.startsWith("file:"))
214
+ return uri;
215
+ if (key === "referenceAudios")
216
+ return media.uploadFile(uri, context.access, context.signal);
217
+ const image = await media.image(uri, context.signal);
218
+ return media.upload(image.bytes, "png", context.access, context.signal);
219
+ })));
220
+ }
221
+ backend.content_id = await contentId(context);
222
+ await pipeline(context, id, "submitted", false, "dify");
223
+ const content = await call(code, backend, context);
224
+ const uri = oneResource(content);
225
+ let output;
226
+ try {
227
+ output = await probe(uri, context.signal);
228
+ }
229
+ catch (cause) {
230
+ if (context.signal.aborted)
231
+ throw context.signal.reason;
232
+ throw new RemoteProtocolError({}, cause, "VIDEO_OUTPUT_INVALID");
233
+ }
234
+ return link(uri, `result.${output.format}`, output.format === "mov" ? "video/quicktime" : `video/${output.format}`);
235
+ }
236
+ const { default: sharp } = await import("sharp");
237
+ let source = await media.image(args.image, context.signal);
238
+ let selection;
239
+ if (typeof args.mask === "string")
240
+ selection = await media.mask(args.mask, source, context.signal);
241
+ if (id === "image-matting-standard") {
242
+ if (!dependencies.standardMatting)
243
+ throw new ToolInputError("matting_billing_contract_unavailable", "/model");
244
+ if (model.cost === undefined || model.cost.minimum !== model.cost.maximum)
245
+ throw new ToolInputError("matting_quote_unavailable", "/model");
246
+ return dependencies.standardMatting(source, context, model.cost.maximum, () => segment(source, context, args.cropToSubject === true));
247
+ }
248
+ if (id === "image-text-edit") {
249
+ const replacements = args.replacements;
250
+ if (new Set(replacements.map(item => item.from)).size !== replacements.length || replacements.some(item => item.from === item.to)) {
251
+ throw new ToolInputError("text_replacement_conflict_or_noop", "/arguments/replacements");
252
+ }
253
+ backend.text = JSON.stringify(replacements.map(item => ({ origin: item.from, new: item.to === "" ? "REMOVE_TEXT" : item.to })));
254
+ }
255
+ if (id === "image-ocr" || id === "image-text-edit") {
256
+ const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).flatten({ background: "white" }).jpeg().toBuffer();
257
+ const info = await sharp(bytes).metadata();
258
+ source = { bytes, width: info.width, height: info.height };
259
+ }
260
+ if (id.startsWith("image-layers-")) {
261
+ const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).png().toBuffer();
262
+ const info = await sharp(bytes).metadata();
263
+ source = { bytes, width: info.width, height: info.height };
264
+ }
265
+ if (id === "image-layers-smart" && source.width * source.height < 512 * 512)
266
+ throw new ToolInputError("layers_input_too_small", "/arguments/image");
267
+ await quote({ resolution: args.targetLongEdge, max_layers: args.maxLayers });
268
+ let prepared = source.bytes;
269
+ if (selection && id.endsWith("-smart"))
270
+ prepared = await outlineImage(source, selection);
271
+ if (id.startsWith("image-expand-")) {
272
+ const canvas = args.canvas;
273
+ const placement = args.placement;
274
+ const geometry = expansionGeometry(source, canvas, placement);
275
+ if (id === "image-expand-smart") {
276
+ prepared = await expansionImage(source, canvas, placement);
277
+ let a = canvas.width, b = canvas.height;
278
+ while (b)
279
+ [a, b] = [b, a % b];
280
+ backend.ratio = `${canvas.width / a}:${canvas.height / a}`;
281
+ backend.prompt = `扩展第1张图的纯绿色区域,保留原图所在位置和内容,去除绿幕。${args.prompt ?? ""}`;
282
+ }
283
+ else {
284
+ prepared = await sharp(source.bytes).flatten({ background: "white" }).png().toBuffer();
285
+ backend.outer_wh = JSON.stringify(geometry.outer);
286
+ backend.inner_xy_points = JSON.stringify(geometry.corners);
287
+ }
288
+ }
289
+ const image = await media.upload(prepared, id === "image-ocr" || id === "image-text-edit" ? "jpg" : "png", context.access, context.signal);
290
+ if (id.startsWith("image-layers-")) {
291
+ backend.url = image;
292
+ backend.type = id === "image-layers-smart" ? "seedream" : "codia";
293
+ if (id === "image-layers-smart") {
294
+ backend.max_layers = String(args.maxLayers);
295
+ const resolutionField = fields.find(field => field.key === "resolution");
296
+ const options = resolutionField?.options;
297
+ const onlyTwoK = resolutionField?.default_value === "2K" && Array.isArray(options)
298
+ && options.length === 1 && record(options[0]) && options[0].value === "2K";
299
+ backend.resolution = onlyTwoK || source.width * source.height > 1280 * 720 ? "2K" : "1K";
300
+ const field = fields.find(field => field.key === "seedream_model");
301
+ if (field?.default_value !== undefined)
302
+ backend.seedream_model = nonblank(field.default_value);
303
+ }
304
+ }
305
+ else if (["image-remove-smart", "image-enhance-smart", "image-expand-smart"].includes(id))
306
+ backend.image_urls = JSON.stringify([image]);
307
+ else
308
+ backend.image = image;
309
+ if (selection && id.endsWith("-standard"))
310
+ backend.mask = await media.upload(await maskPng(selection, source.width, source.height, id === "image-edit-standard"), "png", context.access, context.signal);
311
+ if (args.prompt !== undefined && id !== "image-expand-smart")
312
+ backend.prompt = args.prompt;
313
+ if (selection && id.endsWith("-smart"))
314
+ backend.prompt = `仅处理青色边界标注的区域,移除青色标记。${backend.prompt ?? ""}`;
315
+ if (id === "image-enhance-standard")
316
+ backend.resolution = args.targetLongEdge;
317
+ if (Array.isArray(args.referenceImages)) {
318
+ const references = await Promise.all(args.referenceImages.map(async (uri) => {
319
+ const reference = await media.image(uri, context.signal);
320
+ return media.upload(reference.bytes, "png", context.access, context.signal);
321
+ }));
322
+ if (id === "image-edit-smart")
323
+ backend.reference_images = JSON.stringify(references);
324
+ else
325
+ backend.image_urls = JSON.stringify([image, ...references]);
326
+ }
327
+ backend.content_id = await contentId(context);
328
+ if (id === "image-remove-standard")
329
+ backend.contentid = backend.content_id;
330
+ await pipeline(context, id, "submitted", isMatting, protocol, undefined, id === "image-ocr" ? { ocr: { uri: image, width: source.width, height: source.height } } : undefined);
331
+ const content = await call(code, backend, context, protocol);
332
+ if (id === "image-matting-smart") {
333
+ await pipeline(context, id, "segmenting", true, "sync", content);
334
+ const generated = await media.image(oneResource(content), context.signal);
335
+ const { content: result } = await segment(generated, context, args.cropToSubject === true);
336
+ return result;
337
+ }
338
+ if (id === "image-ocr")
339
+ return ocrResult(content, { uri: image, width: source.width, height: source.height });
340
+ if (id === "image-vectorize")
341
+ return vectorResult(content, media, context.signal);
342
+ if (id.startsWith("image-layers-"))
343
+ return templateResult(content, media, context.signal, dependencies.english);
344
+ return imageResult(content, media, context.signal);
345
+ }
346
+ return {
347
+ async execute(input) {
348
+ if (input.invocation.kind !== "canvas")
349
+ return dependencies.fallback.execute(input);
350
+ const result = await executeCanvas(input.invocation, input);
351
+ // A late recovery-cache failure must not discard an already validated result (ADR 0015).
352
+ try {
353
+ await pipeline(input, input.invocation.model.model, "complete", false, input.invocation.model.tool === "image.layers" ? "toolkit" : "dify", result);
354
+ }
355
+ catch {
356
+ telemetry.annotate({ warning_codes: ["TASK_RESULT_CACHE_FAILED"] });
357
+ }
358
+ return result;
359
+ },
360
+ async submit(input) {
361
+ if (input.invocation.kind !== "canvas")
362
+ return dependencies.fallback.submit(input);
363
+ await executeCanvas(input.invocation, input);
364
+ }
365
+ };
366
+ }
@@ -0,0 +1,84 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { mkdtemp, writeFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { ToolInputError } from "./catalog.js";
7
+ const run = promisify(execFile);
8
+ /** WAN references are numbered per media type, independently of the uploaded URL's filename. */
9
+ export function videoEditPrompt(input, english = false) {
10
+ function binding(label, uri, role) {
11
+ const pathname = new URL(uri).pathname;
12
+ let name = pathname.split("/").at(-1) ?? "";
13
+ try {
14
+ name = decodeURIComponent(name);
15
+ }
16
+ catch { /* Preserve malformed percent escapes as literal filename data. */ }
17
+ // Quote filename data; never forward local directories, URL credentials, query tokens or fragments.
18
+ return `${label}:${role}${name ? `${english ? ", original filename " : ",原文件名 "}${JSON.stringify(name)}` : ""}`;
19
+ }
20
+ const bindings = [binding("视频1", input.video, english ? "source video to edit" : "待编辑原视频")];
21
+ for (const [index, uri] of (input.referenceImages ?? []).entries())
22
+ bindings.push(binding(`图${index + 1}`, uri, english ? "reference image" : "参考图片"));
23
+ for (const [index, uri] of (input.referenceVideos ?? []).entries())
24
+ bindings.push(binding(`视频${index + 2}`, uri, english ? "reference video" : "参考视频"));
25
+ for (const [index, uri] of (input.referenceAudios ?? []).entries())
26
+ 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}`;
28
+ }
29
+ export function videoFormat(bytes) {
30
+ if (bytes.length >= 12 && bytes.subarray(4, 8).toString() === "ftyp")
31
+ return bytes.subarray(8, 12).toString() === "qt " ? "mov" : "mp4";
32
+ if (bytes.subarray(0, 4).equals(Buffer.from([0x1a, 0x45, 0xdf, 0xa3])))
33
+ return "webm";
34
+ throw new ToolInputError("video_format_requires_mp4_mov_webm", "/arguments/video");
35
+ }
36
+ export function createCanvasVideo(media) {
37
+ 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
+ const [numerator, denominator] = String(stream?.avg_frame_rate).split("/").map(Number);
53
+ const frameDuration = denominator / numerator;
54
+ if (!stream || !Number.isFinite(duration) || duration <= 0 || !Number.isInteger(width) || width <= 0
55
+ || !Number.isInteger(height) || height <= 0 || !Number.isFinite(frameDuration) || frameDuration <= 0) {
56
+ throw new ToolInputError("video_metadata_invalid", "/arguments/video");
57
+ }
58
+ const decoded = await run(probe.path, ["-v", "error", "-protocol_whitelist", "file", "-format_whitelist", "mov,matroska,webm",
59
+ "-read_intervals", "%+1", "-select_streams", "v:0", "-show_frames", "-show_entries", "frame=media_type", "-of", "json", path], { signal, timeout: 30_000, maxBuffer: 1024 * 1024 });
60
+ const frames = JSON.parse(decoded.stdout);
61
+ if (!frames.frames?.some(frame => frame.media_type === "video"))
62
+ throw new ToolInputError("video_decode_failed", "/arguments/video");
63
+ return { duration, width, height, frameDuration, hasAudio: result.streams.some(stream => stream.codec_type === "audio"), format };
64
+ }
65
+ catch (cause) {
66
+ if (signal.aborted)
67
+ throw signal.reason;
68
+ if (cause instanceof ToolInputError)
69
+ throw cause;
70
+ throw new ToolInputError("video_probe_failed", "/arguments/video", [], cause);
71
+ }
72
+ finally {
73
+ await rm(directory, { recursive: true, force: true });
74
+ }
75
+ };
76
+ }
77
+ export function videoRatio(info) {
78
+ for (const ratio of ["1:1", "3:4", "4:3", "9:16", "16:9"]) {
79
+ const [w, h] = ratio.split(":").map(Number);
80
+ if (Math.abs(info.width / info.height - w / h) < 0.01)
81
+ return ratio;
82
+ }
83
+ return "adaptive";
84
+ }
@@ -1,3 +1,5 @@
1
+ import { buildModelArgumentsSchema } from "./dynamic-schema.js";
2
+ import { hasCanvasMetering } from "./canvas-pricing.js";
1
3
  export const defaultToolDefinitions = [
2
4
  {
3
5
  name: "image.generate",
@@ -8,7 +10,18 @@ export const defaultToolDefinitions = [
8
10
  name: "video.generate",
9
11
  title: "视频生成",
10
12
  description: "使用已发布的视频模型,根据文本及可选图片、视频或音频生成视频。"
11
- }
13
+ },
14
+ { name: "image.edit", title: "图片改图", description: "修改原图内容;标准模型使用选区,智能模型可按指令修改。" },
15
+ { name: "image.matting", title: "图片抠图", description: "标准抠图保留源像素;智能抠图先重绘补全再分割。最终交付透明 PNG。" },
16
+ { name: "image.remove", title: "图片消除", description: "移除指定对象并补齐背景。" },
17
+ { name: "image.enhance", title: "图片变清晰", description: "标准超分或生成式修复;智能修复可能改变细节。" },
18
+ { name: "image.expand", title: "图片扩图", description: "按目标画布和原图位置补绘外围。" },
19
+ { name: "image.text_edit", title: "图片改字", description: "按原文替换或删除图片文字,不承诺定位重复原文中的某一次。" },
20
+ { name: "image.ocr", title: "图片文字识别", description: "返回实际识别图尺寸、文字、类别和像素坐标。" },
21
+ { name: "image.layers", title: "图片图文分层", description: "交付原生稿定模板 JSON,保留图层结构。" },
22
+ { name: "image.vectorize", title: "图片转矢量", description: "将位图转换为 SVG。" },
23
+ { name: "video.edit", title: "视频修改", description: "按原视频修改内容,时长由真实素材推导。" },
24
+ { name: "video.enhance", title: "视频变清晰", description: "标准超分或生成式视频修复。" }
12
25
  ];
13
26
  export class ToolInputError extends Error {
14
27
  reason;
@@ -37,7 +50,7 @@ function summary(model) {
37
50
  model: model.model,
38
51
  title: model.title,
39
52
  ...(model.description === undefined ? {} : { description: model.description }),
40
- ...(model.cost === undefined ? {} : { cost: model.cost }),
53
+ ...(model.cost === undefined || hasCanvasMetering(model) ? {} : { cost: model.cost }),
41
54
  ...(model.estimatedTime === undefined ? {} : { estimatedTime: model.estimatedTime })
42
55
  };
43
56
  }
@@ -57,14 +70,21 @@ export function projectModelList(catalog, tool, tools = defaultToolDefinitions)
57
70
  .map(summary)
58
71
  };
59
72
  }
60
- export function findModel(catalog, model) {
61
- const found = catalog.models.find((candidate) => candidate.model === model);
62
- if (found === undefined)
63
- throw new ToolInputError("model_not_found", "/model");
64
- return found;
73
+ export function findModel(catalog, model, tool) {
74
+ const matches = catalog.models.filter(candidate => candidate.model === model);
75
+ if (tool !== undefined)
76
+ return findToolModel(catalog, tool, model);
77
+ const legacy = matches.find(candidate => candidate.tool === "image.generate" || candidate.tool === "video.generate");
78
+ if (legacy)
79
+ return legacy;
80
+ if (matches.length === 1)
81
+ return matches[0];
82
+ if (matches.length > 1)
83
+ throw new ToolInputError("model_tool_required", "/tool");
84
+ throw new ToolInputError("model_not_found", "/model");
65
85
  }
66
- export function projectModelDetail(catalog, model) {
67
- const found = findModel(catalog, model);
86
+ export function projectModelDetail(catalog, model, tool) {
87
+ const found = findModel(catalog, model, tool);
68
88
  return {
69
89
  ...summary(found),
70
90
  ...(found.usageDescription === undefined
@@ -73,12 +93,14 @@ export function projectModelDetail(catalog, model) {
73
93
  ...(found.outputMediaTypes === undefined
74
94
  ? {}
75
95
  : { outputMediaTypes: found.outputMediaTypes }),
76
- parameters: found.parameters
96
+ parameters: found.parameters,
97
+ inputSchema: { ...buildModelArgumentsSchema(found) }
77
98
  };
78
99
  }
79
100
  export function findToolModel(catalog, tool, model) {
80
- const found = findModel(catalog, model);
81
- if (found.tool !== tool)
82
- throw new ToolInputError("model_tool_mismatch", "/model");
101
+ const found = catalog.models.find(candidate => candidate.model === model && candidate.tool === tool);
102
+ if (!found)
103
+ throw new ToolInputError(catalog.models.some(candidate => candidate.model === model)
104
+ ? "model_tool_mismatch" : "model_not_found", "/model");
83
105
  return found;
84
106
  }