@insmind/cli 1.8.0 → 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 (58) 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 +50 -23
  26. package/dist/src/cli/agent-commands.js +1 -0
  27. package/dist/src/cli/errors.js +3 -3
  28. package/dist/src/cli/model-commands.js +6 -3
  29. package/dist/src/cli/tool-commands.js +2 -0
  30. package/dist/src/contracts/schema.js +4 -1
  31. package/dist/src/features/agent/creative-protocol.js +22 -5
  32. package/dist/src/features/agent/resource-authorizer.js +1 -0
  33. package/dist/src/features/agent/use-cases.js +15 -5
  34. package/dist/src/features/task/use-cases.js +4 -3
  35. package/dist/src/features/tool/canvas-copy.js +61 -0
  36. package/dist/src/features/tool/canvas-media.js +193 -0
  37. package/dist/src/features/tool/canvas-models.js +109 -0
  38. package/dist/src/features/tool/canvas-pricing.js +81 -0
  39. package/dist/src/features/tool/canvas-recovery.js +68 -0
  40. package/dist/src/features/tool/canvas-results.js +144 -0
  41. package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
  42. package/dist/src/features/tool/canvas-video.js +84 -0
  43. package/dist/src/features/tool/catalog.js +35 -13
  44. package/dist/src/features/tool/dynamic-schema.js +48 -22
  45. package/dist/src/features/tool/matting-billing.js +103 -0
  46. package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
  47. package/dist/src/features/tool/resource-authorizer.js +34 -0
  48. package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
  49. package/dist/src/features/tool/tool-api-adapter.js +13 -4
  50. package/dist/src/features/tool/use-cases.js +28 -3
  51. package/dist/src/product/config.js +12 -1
  52. package/package.json +5 -4
  53. package/skills/insmind-cli/SKILL.md +2 -0
  54. package/skills/insmind-cli/references/creation.md +2 -0
  55. package/skills/insmind-cli/references/generation-constraints.md +3 -1
  56. package/skills/insmind-cli/references/matting.md +29 -0
  57. package/skills/insmind-cli/references/media-tools.md +40 -0
  58. package/skills/insmind-cli/references/tool.md +1 -1
@@ -0,0 +1,144 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Ajv2020 } from "ajv/dist/2020.js";
3
+ import addFormatsImport, {} from "ajv-formats";
4
+ import { contractDocument } from "../../contracts/schema.js";
5
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
6
+ import { normalizeToolContent } from "./tool-api-adapter.js";
7
+ export function record(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value);
9
+ }
10
+ export function canvasContent(value) {
11
+ if (record(value) && value.type === "resource" && record(value.resource)) {
12
+ const resource = value.resource;
13
+ // Real RPC resources include nullable text/image/task slots. URI wins for media;
14
+ // OCR's inline JSON has text rather than a usable media URI.
15
+ if (typeof resource.uri === "string" && resource.uri.trim() && resource.mimeType !== "application/json") {
16
+ return normalizeToolContent({ type: "resource", resource: { uri: resource.uri,
17
+ ...(typeof resource.mimeType === "string" && resource.mimeType ? { mimeType: resource.mimeType } : {}) } });
18
+ }
19
+ if (typeof resource.text === "string" && resource.text.trim())
20
+ return { type: "text", text: resource.text };
21
+ }
22
+ return normalizeToolContent(value);
23
+ }
24
+ export function oneResource(content) {
25
+ const resources = content.filter(item => item.type === "resource_link");
26
+ if (resources.length !== 1)
27
+ throw new RemoteProtocolError({}, undefined, "TOOL_SINGLE_RESOURCE_EXPECTED");
28
+ return resources[0].uri;
29
+ }
30
+ export function link(uri, name, mimeType) {
31
+ return [{ type: "resource_link", uri, name, mimeType }];
32
+ }
33
+ const ajv = new Ajv2020({ strict: true, allErrors: true });
34
+ addFormatsImport(ajv);
35
+ const validateTemplate = ajv.compile(contractDocument("tool.call/template-payload.schema.json"));
36
+ const validateOcr = ajv.compile(contractDocument("tool.call/ocr-payload.schema.json"));
37
+ function assertOcrPayload(payload) {
38
+ if (!validateOcr(payload))
39
+ throw new RemoteProtocolError({}, undefined, "OCR_PAYLOAD_INVALID");
40
+ for (const block of payload.blocks) {
41
+ const [l, t, r, b] = block.bbox;
42
+ if (l > r || t > b || r > payload.image.width || b > payload.image.height)
43
+ throw new RemoteProtocolError({}, undefined, "OCR_COORDINATES_INVALID");
44
+ }
45
+ }
46
+ export function readOcrPayload(text) {
47
+ let payload;
48
+ try {
49
+ payload = JSON.parse(text);
50
+ }
51
+ catch (cause) {
52
+ throw new RemoteProtocolError({}, cause, "OCR_JSON_INVALID");
53
+ }
54
+ assertOcrPayload(payload);
55
+ return payload;
56
+ }
57
+ export function ocrResult(content, image, id = randomUUID()) {
58
+ const texts = content.filter(item => item.type === "text");
59
+ if (texts.length !== 1)
60
+ throw new RemoteProtocolError({}, undefined, "OCR_PAYLOAD_MISSING");
61
+ let blocks;
62
+ try {
63
+ blocks = JSON.parse(texts[0].text);
64
+ }
65
+ catch (cause) {
66
+ throw new RemoteProtocolError({}, cause, "OCR_JSON_INVALID");
67
+ }
68
+ const payload = { image, blocks };
69
+ assertOcrPayload(payload);
70
+ return [{ type: "resource", resource: { uri: `urn:uuid:${id}`, mimeType: "application/json", text: JSON.stringify(payload) } }];
71
+ }
72
+ export async function imageResult(content, media, signal) {
73
+ const { default: sharp } = await import("sharp");
74
+ const uri = oneResource(content);
75
+ const bytes = await media.read(uri, signal);
76
+ const metadata = await sharp(bytes).metadata();
77
+ if (!metadata.width || !metadata.height || !["jpeg", "png", "webp", "avif"].includes(metadata.format ?? "")) {
78
+ throw new RemoteProtocolError({}, undefined, "TOOL_IMAGE_INVALID");
79
+ }
80
+ // Decode the pixels as well: a valid header is insufficient evidence of a complete resource.
81
+ await sharp(bytes).stats();
82
+ return link(uri, `result.${metadata.format === "jpeg" ? "jpg" : metadata.format}`, `image/${metadata.format}`);
83
+ }
84
+ export async function vectorResult(content, media, signal) {
85
+ const { default: sharp } = await import("sharp");
86
+ const uri = oneResource(content);
87
+ const bytes = await media.read(uri, signal);
88
+ if ((await sharp(bytes).metadata()).format !== "svg")
89
+ throw new RemoteProtocolError({}, undefined, "SVG_INVALID");
90
+ return link(uri, "result.svg", "image/svg+xml");
91
+ }
92
+ export async function templateResult(content, media, signal, english = false) {
93
+ const text = content.find(item => item.type === "text");
94
+ if (!text || text.type !== "text")
95
+ throw new RemoteProtocolError({}, undefined, "TEMPLATE_URL_MISSING");
96
+ const uri = text.text.trim();
97
+ let template;
98
+ try {
99
+ template = JSON.parse((await media.read(uri, signal)).toString("utf8"));
100
+ }
101
+ catch (cause) {
102
+ throw new RemoteProtocolError({}, cause, "TEMPLATE_JSON_INVALID");
103
+ }
104
+ if (!validateTemplate(template) || !record(template) || !Array.isArray(template.pages) || template.pages.length === 0)
105
+ throw new RemoteProtocolError({}, undefined, "TEMPLATE_PAGES_MISSING");
106
+ const types = new Map();
107
+ const assets = new Set();
108
+ function inspectElements(elements) {
109
+ for (const element of elements) {
110
+ if (!record(element) || typeof element.type !== "string")
111
+ throw new RemoteProtocolError({}, undefined, "TEMPLATE_ELEMENT_INVALID");
112
+ types.set(element.type, (types.get(element.type) ?? 0) + 1);
113
+ if (typeof element.url === "string" && element.url)
114
+ assets.add(element.url);
115
+ if (record(element.background) && record(element.background.image) && typeof element.background.image.url === "string" && element.background.image.url)
116
+ assets.add(element.background.image.url);
117
+ if (element.elements !== undefined) {
118
+ if (!Array.isArray(element.elements))
119
+ throw new RemoteProtocolError();
120
+ inspectElements(element.elements);
121
+ }
122
+ }
123
+ }
124
+ for (const page of template.pages) {
125
+ if (!record(page) || !Array.isArray(page.elements) || page.elements.length === 0)
126
+ throw new RemoteProtocolError();
127
+ for (const layout of page.elements) {
128
+ if (!record(layout) || typeof layout.width !== "number" || layout.width <= 0
129
+ || typeof layout.height !== "number" || layout.height <= 0 || !record(layout.background)
130
+ || !record(layout.background.image) || !Array.isArray(layout.elements))
131
+ throw new RemoteProtocolError({}, undefined, "TEMPLATE_LAYOUT_INVALID");
132
+ }
133
+ inspectElements(page.elements);
134
+ }
135
+ for (const asset of assets) {
136
+ const bytes = await media.read(asset, signal);
137
+ if (bytes.length === 0)
138
+ throw new RemoteProtocolError();
139
+ }
140
+ const counts = [...types].map(([type, count]) => `${type}: ${count}`).join("; ");
141
+ return [...link(uri, "template.json", "application/json"), { type: "text", text: english
142
+ ? `Native template, ${counts}. The editor matches fonts and may substitute missing fonts.`
143
+ : `原生模板,${counts}。字体由编辑器匹配,缺失字体可能替换。` }];
144
+ }
@@ -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
+ }