@insmind/cli 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/contracts/operations/agent.send/input.schema.json +1 -77
  2. package/contracts/operations/dam.folder.list/input.schema.json +0 -1
  3. package/contracts/operations/dam.folder.list/output.schema.json +1 -2
  4. package/contracts/operations/dam.list/input.schema.json +3 -6
  5. package/contracts/operations/dam.list/output.schema.json +1 -2
  6. package/contracts/operations/dam.search/input.schema.json +3 -6
  7. package/contracts/operations/dam.search/output.schema.json +1 -2
  8. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
  9. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
  10. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
  11. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
  12. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  13. package/dist/bin/postinstall.js +22 -6
  14. package/dist/bin/task-worker.js +2 -2
  15. package/dist/src/bootstrap/create-cli.js +13 -6
  16. package/dist/src/bootstrap/create-runtime.js +98 -28
  17. package/dist/src/bootstrap/run-task-worker.js +6 -2
  18. package/dist/src/bootstrap/validators.js +1 -1
  19. package/dist/src/cli/action-binding.js +14 -37
  20. package/dist/src/cli/agent-commands.js +11 -11
  21. package/dist/src/cli/auth-commands.js +2 -1
  22. package/dist/src/cli/creation-help.js +9 -0
  23. package/dist/src/cli/dam-commands.js +10 -14
  24. package/dist/src/cli/editor-commands.js +7 -5
  25. package/dist/src/cli/errors.js +81 -22
  26. package/dist/src/cli/host-input.js +64 -5
  27. package/dist/src/cli/model-commands.js +9 -3
  28. package/dist/src/cli/observed-errors.js +7 -3
  29. package/dist/src/cli/org-commands.js +3 -1
  30. package/dist/src/cli/task-commands.js +6 -2
  31. package/dist/src/cli/tool-commands.js +12 -11
  32. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  33. package/dist/src/features/agent/creative-protocol.js +8 -29
  34. package/dist/src/features/agent/resource-authorizer.js +25 -17
  35. package/dist/src/features/agent/result-reader.js +31 -14
  36. package/dist/src/features/agent/use-cases.js +6 -31
  37. package/dist/src/features/credits/use-cases.js +55 -28
  38. package/dist/src/features/dam/asset-projection.js +3 -6
  39. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  40. package/dist/src/features/dam/repository-catalog.js +30 -21
  41. package/dist/src/features/dam/use-cases.js +12 -7
  42. package/dist/src/features/editor/bridge-client.js +0 -2
  43. package/dist/src/features/editor/public-url.js +1 -36
  44. package/dist/src/features/editor/session.js +3 -2
  45. package/dist/src/features/editor/use-cases.js +27 -2
  46. package/dist/src/features/org/org-service.js +10 -1
  47. package/dist/src/features/org/use-cases.js +18 -4
  48. package/dist/src/features/task/process-owner.js +54 -0
  49. package/dist/src/features/task/store.js +37 -10
  50. package/dist/src/features/task/task-background.js +5 -2
  51. package/dist/src/features/task/use-cases.js +184 -84
  52. package/dist/src/features/tool/argument-paths.js +14 -0
  53. package/dist/src/features/tool/canvas-copy.js +28 -15
  54. package/dist/src/features/tool/canvas-matting.js +123 -0
  55. package/dist/src/features/tool/canvas-media.js +100 -52
  56. package/dist/src/features/tool/canvas-models.js +66 -33
  57. package/dist/src/features/tool/canvas-pricing.js +12 -0
  58. package/dist/src/features/tool/canvas-recovery.js +13 -30
  59. package/dist/src/features/tool/canvas-results.js +79 -87
  60. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  61. package/dist/src/features/tool/canvas-video.js +44 -37
  62. package/dist/src/features/tool/dynamic-schema.js +39 -40
  63. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  64. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  65. package/dist/src/features/tool/resource-authorizer.js +11 -3
  66. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  67. package/dist/src/features/tool/tool-errors.js +25 -0
  68. package/dist/src/features/tool/tool-output.js +15 -0
  69. package/dist/src/features/tool/use-cases.js +74 -98
  70. package/dist/src/features/update/update-service.js +95 -21
  71. package/dist/src/platform/media-type.js +46 -0
  72. package/dist/src/platform/public-url.js +35 -0
  73. package/dist/src/platform/remote-error-evidence.js +33 -6
  74. package/dist/src/platform/resource-auth-key.js +35 -1
  75. package/dist/src/platform/safe-upload-file.js +36 -41
  76. package/dist/src/platform/signature.js +2 -2
  77. package/dist/src/platform/signed-http-transport.js +4 -1
  78. package/dist/src/platform/url-safety.js +6 -1
  79. package/dist/src/platform/webm-header.js +41 -0
  80. package/dist/src/telemetry/command-route.js +38 -0
  81. package/dist/src/telemetry/command-routes.json +1 -0
  82. package/dist/src/telemetry/failure-summary.js +1 -1
  83. package/dist/src/telemetry/invocation.js +1 -2
  84. package/dist/src/telemetry/process-errors.js +17 -33
  85. package/dist/src/telemetry/sanitize.js +19 -4
  86. package/dist/src/telemetry/sls-sink.js +8 -0
  87. package/package.json +4 -4
  88. package/skills/insmind-cli/SKILL.md +18 -5
  89. package/skills/insmind-cli/references/agent.md +9 -4
  90. package/skills/insmind-cli/references/creation.md +3 -1
  91. package/skills/insmind-cli/references/editor.md +7 -5
  92. package/skills/insmind-cli/references/errors.md +20 -9
  93. package/skills/insmind-cli/references/matting.md +3 -5
  94. package/skills/insmind-cli/references/media-tools.md +10 -4
  95. package/skills/insmind-cli/references/tool.md +9 -15
@@ -0,0 +1,123 @@
1
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
2
+ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
3
+ import { authorizeToolResources } from "./resource-authorizer.js";
4
+ import { composeMatting } from "./canvas-media.js";
5
+ import { canvasContent, link, oneResource, record } from "./canvas-results.js";
6
+ import { ToolTaskCanceledError, ToolTaskFailedError } from "./tool-errors.js";
7
+ function parseSyncResult(value) {
8
+ if (!record(value))
9
+ throw new RemoteProtocolError();
10
+ if (record(value.error))
11
+ throw new ToolTaskFailedError(remoteErrorEvidence(value.error));
12
+ if (value.error)
13
+ throw new RemoteProtocolError(remoteErrorEvidence(value));
14
+ if (!record(value.result)) {
15
+ if (typeof value.task_id === "string" && value.task_id)
16
+ return { state: "pending" };
17
+ throw new RemoteProtocolError();
18
+ }
19
+ if (value.result.isError === true)
20
+ throw new ToolTaskFailedError(remoteErrorEvidence(value.result));
21
+ if ((value.result.isError !== undefined && value.result.isError !== false) || !Array.isArray(value.result.content))
22
+ throw new RemoteProtocolError();
23
+ const content = value.result.content;
24
+ const status = content.find(item => record(item) && item.type === "task");
25
+ if (record(status) && record(status.task)) {
26
+ if (["NOT_PASSED", "FAIL"].includes(String(status.task.status)))
27
+ throw new ToolTaskFailedError(remoteErrorEvidence(value));
28
+ if (status.task.status === "CANCELED")
29
+ throw new ToolTaskCanceledError();
30
+ return { state: "pending" };
31
+ }
32
+ if (!content.length)
33
+ return { state: "pending" };
34
+ return { state: "complete", content: content.map(canvasContent) };
35
+ }
36
+ export function createCanvasSegmenter(dependencies) {
37
+ const { transport, telemetry, wait, resourceAuthorizer } = dependencies;
38
+ async function sync(name, image, context, options) {
39
+ let taskId = options.taskId;
40
+ if (!taskId) {
41
+ if (options.main)
42
+ await context.observe?.({ submissionStarted: true });
43
+ const response = await transport.postJson({ path: "/gdesign/tool/v1/dify/call_sync",
44
+ body: { jsonrpc: "2.0", id: 0, method: "tools/call", params: { name, arguments: { image } } }, ...context.access, signal: context.signal,
45
+ ...(options.main ? { onDispatch: async (dispatchedAt) => {
46
+ await context.observe?.({ dispatchedAt });
47
+ } } : {}) });
48
+ if (!record(response))
49
+ throw new RemoteProtocolError();
50
+ if (typeof response.task_id === "string" && response.task_id.trim()) {
51
+ taskId = response.task_id;
52
+ if (options.main) {
53
+ await context.observe?.({ remoteTaskId: taskId, accepted: true });
54
+ telemetry.annotate({ dify_task_id: taskId });
55
+ }
56
+ await options.accepted?.(taskId);
57
+ }
58
+ const direct = parseSyncResult(response);
59
+ if (direct.state === "complete")
60
+ return direct.content;
61
+ if (!taskId)
62
+ throw new RemoteProtocolError();
63
+ }
64
+ const query = { task_id: taskId };
65
+ return wait(async () => parseSyncResult(await transport.getJson({ path: "/gdesign/tool/v1/dify/task/process", query,
66
+ ...context.access, signal: context.signal })), context.signal);
67
+ }
68
+ async function authorizeMattingImage(uri, context) {
69
+ if (!resourceAuthorizer)
70
+ return uri;
71
+ const authorized = await authorizeToolResources({ content: link(uri, "matting.png", "image/png"), usage: { model: "image.matting" } }, resourceAuthorizer, context.access, context.signal);
72
+ return oneResource(authorized.content);
73
+ }
74
+ return async function segment(source, media, context, crop, redraw) {
75
+ let stage = redraw?.stage;
76
+ let state = redraw?.matting ?? { cropToSubject: crop };
77
+ async function checkpoint(next, update) {
78
+ state = { ...state, ...update };
79
+ stage = next;
80
+ if (redraw)
81
+ await context.observe?.({ toolPipeline: { ...redraw, stage, matting: state } });
82
+ }
83
+ if (!state.inputUri) {
84
+ const { default: sharp } = await import("sharp");
85
+ const input = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).png().toBuffer();
86
+ const inputUri = await media.upload(input, "png", context.access, context.signal);
87
+ await checkpoint("prepared", { inputUri });
88
+ }
89
+ const inputUri = state.inputUri;
90
+ async function child(name, next, key) {
91
+ const taskId = state[key];
92
+ // A non-idempotent child might have been accepted even without a receipt.
93
+ // Resume by its known ID; never submit the uncertain child again.
94
+ if (stage === next && !taskId)
95
+ throw new RemoteProtocolError({}, undefined, "MATTING_CHILD_RECEIPT_UNKNOWN");
96
+ const uri = taskId ? inputUri : await authorizeMattingImage(inputUri, context);
97
+ context.signal.throwIfAborted();
98
+ await checkpoint(next, {});
99
+ return sync(name, uri, context, { ...(taskId ? { taskId } : {}),
100
+ main: !redraw && next === "classifying",
101
+ accepted: id => checkpoint(next, { [key]: id }) });
102
+ }
103
+ if (state.category === undefined) {
104
+ const classification = await child("matting-classify", "classifying", "classifyTaskId");
105
+ const text = classification.find(item => item.type === "text");
106
+ if (!text || !/^[012]$/u.test(text.text.trim()))
107
+ throw new RemoteProtocolError();
108
+ await checkpoint("classified", { category: Number(text.text.trim()) });
109
+ }
110
+ const category = state.category;
111
+ if (!state.maskUri) {
112
+ const scene = ["matting-graphs", "matting-person", "matting-product"][category];
113
+ if (!scene)
114
+ throw new RemoteProtocolError();
115
+ const mask = await child(scene, "segmenting", "segmentTaskId");
116
+ await checkpoint("compositing", { maskUri: oneResource(mask) });
117
+ }
118
+ const maskUri = await authorizeMattingImage(state.maskUri, context);
119
+ const bytes = await composeMatting(source, await media.read(maskUri, context.signal), category === 1 ? "alpha" : "red", crop);
120
+ const finalUri = await media.upload(bytes, "png", context.access, context.signal);
121
+ return { content: link(finalUri, "cutout.png", "image/png"), inputUri, scene: ["graphic", "portrait", "product"][category] };
122
+ };
123
+ }
@@ -4,7 +4,8 @@ import { join } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { inspectUploadFile, LocalFileInputError } from "../../platform/safe-upload-file.js";
6
6
  import { uriShape } from "../../platform/input-uri.js";
7
- import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
7
+ import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
8
+ import { isFilemsResource, withFilemsAuthKey } from "../../platform/resource-auth-key.js";
8
9
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
9
10
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
10
11
  import { ToolInputError } from "./catalog.js";
@@ -20,6 +21,8 @@ function mediaFailure(phase, summary, status, cause) {
20
21
  return new RemoteRequestError(status, false, {}, cause, `MEDIA_${phase.toUpperCase()}_FAILED`, { ...summary, mediaPhase: phase });
21
22
  }
22
23
  export function createCanvasMedia(dependencies) {
24
+ // Scoped to this call's identity. A later consumer of the same asset must receive the URL that actually worked.
25
+ const renewed = new Map();
23
26
  async function readWithEvidence(uri, signal, limit = 64 * 1024 * 1024) {
24
27
  signal.throwIfAborted();
25
28
  if (uri.startsWith("file:")) {
@@ -37,7 +40,27 @@ export function createCanvasMedia(dependencies) {
37
40
  }
38
41
  }
39
42
  let url = parseSafeRemoteAssetUrl(uri);
40
- for (let redirects = 0; redirects <= 5; redirects++) {
43
+ const protectedOrigin = isFilemsResource(url);
44
+ let authKey;
45
+ let freshKey;
46
+ let redirects = 0;
47
+ while (redirects <= 5) {
48
+ if (protectedOrigin) {
49
+ const existing = url.searchParams.get("auth_key");
50
+ if (existing?.trim())
51
+ authKey = existing;
52
+ else {
53
+ if (!authKey) {
54
+ const filems = dependencies.filems;
55
+ if (!filems)
56
+ throw new RemoteProtocolError({}, undefined, "RESOURCE_AUTH_REQUIRED");
57
+ authKey = await filems.authKeys.getAuthKey(filems.access, signal);
58
+ freshKey = authKey;
59
+ signal.throwIfAborted();
60
+ }
61
+ url = new URL(withFilemsAuthKey(url.href, authKey));
62
+ }
63
+ }
41
64
  let response;
42
65
  try {
43
66
  response = await dependencies.fetch(url, { redirect: "manual", signal });
@@ -49,13 +72,27 @@ export function createCanvasMedia(dependencies) {
49
72
  }
50
73
  signal.throwIfAborted();
51
74
  const summary = responseDiagnostics(url, redirects, response.headers);
75
+ if (response.status === 403 && protectedOrigin && freshKey === undefined && dependencies.filems) {
76
+ await response.body?.cancel().catch(() => undefined);
77
+ const { authKeys, access } = dependencies.filems;
78
+ authKey = await authKeys.getAuthKey(access, signal);
79
+ signal.throwIfAborted();
80
+ freshKey = authKey;
81
+ url = new URL(withFilemsAuthKey(url.href, authKey));
82
+ continue; // Retry only this GET. A second 403 follows the normal error path.
83
+ }
52
84
  if ([301, 302, 303, 307, 308].includes(response.status)) {
53
85
  const location = response.headers.get("location");
54
86
  await response.body?.cancel().catch(() => undefined);
55
87
  if (!location || redirects === 5)
56
88
  throw mediaFailure("redirect", summary, response.status);
57
89
  try {
58
- url = parseSafeRemoteAssetUrl(new URL(location, url).href);
90
+ const next = parseSafeRemoteAssetUrl(new URL(location, url).href);
91
+ // A FileMS key may follow a same-origin path, never a cross-origin redirect in either direction.
92
+ if (next.origin !== url.origin && (protectedOrigin || isFilemsResource(next)))
93
+ throw new UrlSafetyError();
94
+ url = next;
95
+ redirects++;
59
96
  }
60
97
  catch (cause) {
61
98
  throw mediaFailure("redirect", summary, response.status, cause);
@@ -100,6 +137,8 @@ export function createCanvasMedia(dependencies) {
100
137
  throw Object.assign(cause, { diagnosticSummary: evidence });
101
138
  throw mediaFailure("read", evidence, response.status, cause);
102
139
  }
140
+ if (freshKey !== undefined)
141
+ renewed.set(uri, withFilemsAuthKey(uri, freshKey));
103
142
  return { bytes: Buffer.concat(chunks), summary: { ...summary, mediaPhase: "read", mediaBytesRead: size }, status: response.status };
104
143
  }
105
144
  throw mediaFailure("redirect", responseDiagnostics(url, 5));
@@ -138,76 +177,82 @@ export function createCanvasMedia(dependencies) {
138
177
  await rm(directory, { recursive: true, force: true });
139
178
  }
140
179
  }
141
- async function mask(uri, source, signal) {
142
- const { default: sharp } = await import("sharp");
143
- const bytes = await read(uri, signal);
144
- const metadata = await sharp(bytes).metadata();
145
- if (metadata.format !== "png" || metadata.width !== source.width || metadata.height !== source.height
146
- || (metadata.orientation !== undefined && metadata.orientation !== 1)) {
147
- throw new ToolInputError("mask_geometry_or_format", "/arguments/mask");
148
- }
149
- const { data, info } = await sharp(bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
150
- const mono = Buffer.alloc(info.width * info.height);
151
- let selected = false;
152
- for (let i = 0; i < mono.length; i++) {
153
- const offset = i * 4;
154
- const value = data[offset];
155
- if ((value !== 0 && value !== 255) || data[offset + 1] !== value || data[offset + 2] !== value || data[offset + 3] !== 255) {
156
- throw new ToolInputError("mask_requires_opaque_binary_png", "/arguments/mask");
157
- }
158
- mono[i] = value;
159
- selected ||= value === 255;
160
- }
161
- if (!selected)
162
- throw new ToolInputError("mask_empty_selection", "/arguments/mask");
163
- return mono;
164
- }
165
180
  async function uploadFile(uri, access, signal) {
166
181
  // Keep the actual input extension/MIME for audio references instead of renaming every file .mp3.
167
- await read(uri, signal);
168
182
  return (await dependencies.uploader.upload({ url: uri }, access, signal)).url;
169
183
  }
170
- return { read, image, upload, uploadFile, mask };
184
+ return { read, image, upload, uploadFile, deliveryUri: (uri) => renewed.get(uri) ?? uri };
185
+ }
186
+ /** A media limit reached while retrieving a result is a delivery failure, not a user input error. */
187
+ export async function readOutputMedia(media, uri, signal) {
188
+ try {
189
+ return await media.read(uri, signal);
190
+ }
191
+ catch (cause) {
192
+ signal.throwIfAborted();
193
+ if (!(cause instanceof ToolInputError))
194
+ throw cause;
195
+ throw new RemoteProtocolError({}, cause, cause.reason === "media_too_large" ? "TOOL_OUTPUT_MEDIA_TOO_LARGE" : "TOOL_OUTPUT_READ_FAILED");
196
+ }
197
+ }
198
+ function maskConversionError(cause) {
199
+ return new ToolInputError("mask_geometry_or_format", "/arguments/mask", [], cause);
171
200
  }
172
- export async function maskPng(mask, width, height, invert = false) {
201
+ async function selectionImage(bytes) {
173
202
  const { default: sharp } = await import("sharp");
174
- return sharp(invert ? Buffer.from(mask.map(value => 255 - value)) : mask, { raw: { width, height, channels: 1 } }).png().toBuffer();
203
+ try {
204
+ const image = sharp(bytes, { limitInputPixels: 64 * 1024 * 1024 });
205
+ const { pages } = await image.metadata();
206
+ if ((pages ?? 1) === 1)
207
+ return image.autoOrient();
208
+ }
209
+ catch (cause) {
210
+ throw maskConversionError(cause);
211
+ }
212
+ // Both local transforms produce a single frame. Never silently drop extra frames.
213
+ throw maskConversionError();
214
+ }
215
+ export async function invertSelectionMask(bytes) {
216
+ const image = await selectionImage(bytes);
217
+ return image.negate({ alpha: false }).png().toBuffer().catch(cause => { throw maskConversionError(cause); });
175
218
  }
176
- export async function outlineImage(source, mask) {
219
+ export async function outlineImage(source, selection) {
177
220
  const { default: sharp } = await import("sharp");
178
221
  const { width, height } = source;
222
+ const image = await selectionImage(selection);
223
+ const { data: mask, info } = await image.flatten({ background: "black" }).greyscale().raw()
224
+ .toBuffer({ resolveWithObject: true }).catch(cause => { throw maskConversionError(cause); });
225
+ if (info.width !== width || info.height !== height)
226
+ throw maskConversionError();
179
227
  const { data } = await sharp(source.bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
180
228
  const radius = Math.max(1, Math.round(Math.max(width, height) / 600));
181
229
  for (let y = 0; y < height; y++)
182
230
  for (let x = 0; x < width; x++) {
183
231
  const index = y * width + x;
184
- if (mask[index] !== 255)
232
+ const center = mask[index];
233
+ if (!center)
185
234
  continue;
186
- let boundary = false;
187
- for (const [dx, dy] of [[-radius, 0], [radius, 0], [0, -radius], [0, radius]]) {
188
- const nx = x + dx;
189
- const ny = y + dy;
190
- if (nx < 0 || nx >= width || ny < 0 || ny >= height || mask[ny * width + nx] !== 255) {
191
- boundary = true;
192
- break;
193
- }
194
- }
195
- if (boundary) {
196
- const offset = index * 4;
197
- data[offset] = 0;
198
- data[offset + 1] = 255;
199
- data[offset + 2] = 255;
200
- data[offset + 3] = 255;
201
- }
235
+ // Draw the inside edge of the supplied selection, keeping its coverage at soft edges.
236
+ const neighbor = Math.min(center, x >= radius ? mask[index - radius] : 0, x + radius < width ? mask[index + radius] : 0, y >= radius ? mask[index - radius * width] : 0, y + radius < height ? mask[index + radius * width] : 0);
237
+ const coverage = (center - neighbor) / 255;
238
+ if (!coverage)
239
+ continue;
240
+ const offset = index * 4;
241
+ const sourceAlpha = (1 - coverage) * data[offset + 3] / 255;
242
+ const alpha = coverage + sourceAlpha;
243
+ data[offset] = Math.round(data[offset] * sourceAlpha / alpha);
244
+ data[offset + 1] = Math.round((255 * coverage + data[offset + 1] * sourceAlpha) / alpha);
245
+ data[offset + 2] = Math.round((255 * coverage + data[offset + 2] * sourceAlpha) / alpha);
246
+ data[offset + 3] = Math.round(255 * alpha);
202
247
  }
203
248
  return sharp(data, { raw: { width, height, channels: 4 } }).png().toBuffer();
204
249
  }
205
250
  export function expansionGeometry(source, canvas, placement) {
206
251
  const { width, height } = canvas;
207
252
  const { x, y } = placement;
208
- if (width > 4096 || height > 4096 || width * height > 16 * 1024 * 1024
209
- || x + source.width > width || y + source.height > height
210
- || (width === source.width && height === source.height)) {
253
+ if (![width, height].every(n => Number.isSafeInteger(n) && n > 0)
254
+ || ![x, y].every(n => Number.isSafeInteger(n) && n >= 0)
255
+ || x + source.width > width || y + source.height > height) {
211
256
  throw new ToolInputError("expansion_geometry", "/arguments/canvas");
212
257
  }
213
258
  return { outer: [width, height], corners: [[x, y], [x + source.width, y], [x + source.width, y + source.height], [x, y + source.height]] };
@@ -215,6 +260,9 @@ export function expansionGeometry(source, canvas, placement) {
215
260
  export async function expansionImage(source, canvas, placement) {
216
261
  const { default: sharp } = await import("sharp");
217
262
  expansionGeometry(source, canvas, placement);
263
+ if (canvas.width > 4096 || canvas.height > 4096 || canvas.width * canvas.height > 16 * 1024 * 1024) {
264
+ throw new ToolInputError("expansion_canvas_too_large", "/arguments/canvas");
265
+ }
218
266
  const flattened = await sharp(source.bytes).flatten({ background: "white" }).png().toBuffer();
219
267
  return sharp({ create: { ...canvas, channels: 3, background: { r: 0, g: 255, b: 0 } } })
220
268
  .composite([{ input: flattened, left: placement.x, top: placement.y }]).png().toBuffer();
@@ -1,29 +1,43 @@
1
+ import { isDeepStrictEqual } from "node:util";
1
2
  import { englishCanvasCopy } from "./canvas-copy.js";
2
3
  import { canvasPricingDescription } from "./canvas-pricing.js";
3
4
  import { contractDocument } from "../../contracts/schema.js";
4
5
  import { ToolInputError } from "./catalog.js";
5
6
  /** Service protocol bindings, not a local inventory of available models. MNS supplies availability. */
6
7
  export const canvasModelBindings = [
7
- ["image.edit", "image-edit-standard", "canvas-quick-image-edit", "canvas-image-edit", "标准改图"],
8
- ["image.edit", "image-edit-smart", "canvas-smart-image-edit", "canvas-image-edit", "智能改图"],
9
- ["image.matting", "image-matting-standard", "old_matting", "canvas-image-matting", "标准抠图"],
10
- ["image.matting", "image-matting-smart", "canvas-smart-matting", "canvas-image-matting", "智能抠图"],
11
- ["image.remove", "image-remove-standard", "canvas-quick-image-remove", "canvas-image-remove", "标准消除"],
12
- ["image.remove", "image-remove-smart", "canvas-image-remove-smart", "canvas-image-remove", "智能消除"],
13
- ["image.enhance", "image-enhance-standard", "eval-tencent-mps-super-resolution", "canvas-image-enhance", "标准超分"],
14
- ["image.enhance", "image-enhance-smart", "canvas-image-enhance-generative", "canvas-image-enhance", "智能修复"],
15
- ["image.expand", "image-expand-standard", "outpainting-pro", "canvas-image-expand", "标准扩图"],
16
- ["image.expand", "image-expand-smart", "canvas-image-expand-sunburst", "canvas-image-expand", "智能扩图"],
17
- ["image.text_edit", "image-text-edit", "TextEdit", "TextEdit", "图片改字"],
18
- ["image.ocr", "image-ocr", "new-image-ocr", "new-image-ocr", "文字识别"],
19
- ["image.layers", "image-layers-layout", "codia", "special-agent-tools", "图文分层"],
20
- ["image.layers", "image-layers-smart", "seedream-layer-decomposition", "special-agent-tools", "智能分层"],
21
- ["image.vectorize", "image-vectorize", "eval-recraft-vectorize", "canvas-image-vectorize", "图片转矢量"],
22
- ["video.edit", "video-edit-smart", "canvas-video-edit-smart", "canvas-video-edit", "智能改视频"],
23
- ["video.enhance", "video-enhance-standard", "canvas-video-enhance-fast", "canvas-video-enhance", "标准视频超分"],
24
- ["video.enhance", "video-enhance-smart", "canvas-video-enhance-smart", "canvas-video-enhance", "智能视频修复"]
8
+ ["image.edit", "image-edit-standard", "canvas-quick-image-edit", "canvas-image-edit", "标准改图", "dify"],
9
+ ["image.edit", "image-edit-smart", "canvas-smart-image-edit", "canvas-image-edit", "智能改图", "dify"],
10
+ ["image.matting", "image-matting-standard", "old_matting", "canvas-image-matting", "标准抠图", "sync"],
11
+ ["image.matting", "image-matting-smart", "canvas-smart-matting", "canvas-image-matting", "智能抠图", "dify"],
12
+ ["image.remove", "image-remove-standard", "canvas-quick-image-remove", "canvas-image-remove", "标准消除", "dify"],
13
+ ["image.remove", "image-remove-smart", "canvas-image-remove-smart", "canvas-image-remove", "智能消除", "dify"],
14
+ ["image.enhance", "image-enhance-standard", "eval-tencent-mps-super-resolution", "canvas-image-enhance", "标准超分", "dify"],
15
+ ["image.enhance", "image-enhance-smart", "canvas-image-enhance-generative", "canvas-image-enhance", "智能修复", "dify"],
16
+ ["image.expand", "image-expand-standard", "outpainting-pro", "canvas-image-expand", "标准扩图", "dify"],
17
+ ["image.expand", "image-expand-smart", "canvas-image-expand-sunburst", "canvas-image-expand", "智能扩图", "dify"],
18
+ ["image.text_edit", "image-text-edit", "TextEdit", "TextEdit", "图片改字", "dify"],
19
+ ["image.ocr", "image-ocr", "new-image-ocr", "new-image-ocr", "文字识别", "dify"],
20
+ ["image.layers", "image-layers-layout", "codia", "special-agent-tools", "图文分层", "toolkit"],
21
+ ["image.layers", "image-layers-smart", "seedream-layer-decomposition", "special-agent-tools", "智能分层", "toolkit"],
22
+ ["image.vectorize", "image-vectorize", "eval-recraft-vectorize", "canvas-image-vectorize", "图片转矢量", "dify"],
23
+ ["video.edit", "video-edit-smart", "canvas-video-edit-smart", "canvas-video-edit", "智能改视频", "dify"],
24
+ ["video.enhance", "video-enhance-standard", "canvas-video-enhance-fast", "canvas-video-enhance", "标准视频超分", "dify"],
25
+ ["video.enhance", "video-enhance-smart", "canvas-video-enhance-smart", "canvas-video-enhance", "智能视频修复", "dify"]
25
26
  ];
26
27
  export const canvasSceneCodes = [...new Set(canvasModelBindings.map(binding => binding[3]))];
28
+ export function canvasProtocol(model) {
29
+ const binding = canvasModelBindings.find(([, id]) => id === model);
30
+ if (!binding)
31
+ throw new ToolInputError("model_not_found", "/arguments/model");
32
+ return binding[5];
33
+ }
34
+ // A media role must have a translation on this binding. Arbitrary business controls
35
+ // still travel through its ordinary argument channel.
36
+ export function unavailableCanvasMediaRoles(schema) {
37
+ return ["image", "video", "mask", "referenceImages", "referenceVideos", "referenceAudios",
38
+ "image_urls", "video_urls", "audio_urls", "file_urls", "reference_images", "start_frame", "end_frame"]
39
+ .filter(name => !Object.hasOwn(schema.properties, name));
40
+ }
27
41
  export const canvasControlParameterNames = new Set(["quality", "resolution", "audioEnabled", "targetLongEdge", "maxLayers"]);
28
42
  const parameterAliases = {
29
43
  "image-enhance-standard": { targetLongEdge: "resolution" },
@@ -34,8 +48,8 @@ export function canvasRemoteControlArguments(model, value) {
34
48
  for (const [name, argument] of Object.entries(value)) {
35
49
  const aliases = parameterAliases[model];
36
50
  const key = aliases && Object.hasOwn(aliases, name) ? aliases[name] : name;
37
- const remoteValue = key === "max_layers" && typeof argument === "number" ? String(argument) : argument;
38
- if (parameters.has(key) && parameters.get(key) !== remoteValue) {
51
+ const remoteValue = model === "image-layers-smart" && key === "max_layers" && typeof argument === "number" ? String(argument) : argument;
52
+ if (parameters.has(key) && !isDeepStrictEqual(parameters.get(key), remoteValue)) {
39
53
  throw new ToolInputError("conflicting_arguments", "/arguments/" + name);
40
54
  }
41
55
  parameters.set(key, remoteValue);
@@ -45,6 +59,8 @@ export function canvasRemoteControlArguments(model, value) {
45
59
  export function canvasInputSchema(id, fields) {
46
60
  const schema = contractDocument(`tool.call/models/${id}.schema.json`);
47
61
  schema.additionalProperties = id !== "image-matting-standard";
62
+ if (id === "image-matting-standard")
63
+ return schema;
48
64
  if (id === "image-text-edit") {
49
65
  const edits = schema.properties.replacements;
50
66
  delete edits.minItems;
@@ -61,14 +77,31 @@ export function canvasInputSchema(id, fields) {
61
77
  continue;
62
78
  const property = schema.properties[publicName] ?? { type: "string" };
63
79
  if (field.options)
64
- property.enum = field.options.map(option => option.value);
80
+ property.enum = field.options.map(({ value }) => {
81
+ if (publicName !== "targetLongEdge")
82
+ return value;
83
+ const pixels = Number(value);
84
+ if (!Number.isSafeInteger(pixels) || pixels <= 0 || String(pixels) !== value)
85
+ throw new Error("invalid resolution option");
86
+ return pixels;
87
+ });
65
88
  if (field.minimum !== undefined)
66
89
  property.minimum = Math.max(Number(property.minimum ?? -Infinity), field.minimum);
67
90
  if (field.maximum !== undefined)
68
91
  property.maximum = Math.min(Number(property.maximum ?? Infinity), field.maximum);
69
- if (field.default !== undefined)
70
- property.default = field.default;
71
- if (field.description)
92
+ if (field.default !== undefined) {
93
+ if (publicName === "targetLongEdge" && property.enum) {
94
+ const pixels = Number(field.default);
95
+ if (property.enum.includes(pixels))
96
+ property.default = pixels;
97
+ }
98
+ else
99
+ property.default = field.default;
100
+ }
101
+ // A live prose label may list fewer tiers than the current sellable SKUs.
102
+ if (publicName === "targetLongEdge" && property.enum)
103
+ property.description = `目标长边像素,可选 ${property.enum.join("、")}。`;
104
+ else if (field.description)
72
105
  property.description = field.description;
73
106
  schema.properties[publicName] = property;
74
107
  if (field.required && !schema.required.includes(publicName))
@@ -90,7 +123,7 @@ export function schemaParameters(schema, fields) {
90
123
  ...(property.maximum === undefined ? {} : { maximum: property.maximum }),
91
124
  ...(raw?.step === undefined ? {} : { step: raw.step }),
92
125
  ...(property.default === undefined ? {} : { default: property.default }),
93
- ...(property.enum ? { options: raw?.options ?? property.enum.map(value => ({ value })) } : {}) };
126
+ ...(property.enum ? { options: raw?.options ?? property.enum.map(value => ({ value: String(value) })) } : {}) };
94
127
  });
95
128
  }
96
129
  export function canvasModel(raw, binding, configuration, english = false) {
@@ -99,24 +132,24 @@ export function canvasModel(raw, binding, configuration, english = false) {
99
132
  const copy = english ? englishCanvasCopy(model, inputSchema) : undefined;
100
133
  const result = { ...raw, tool, model, title: copy?.title ?? title,
101
134
  usageDescription: copy?.usageDescription ?? {
102
- "image-edit-standard": "选区白色处理、黑色保护;mask 为与转正原图同尺寸的全不透明二值 PNG。CLI 在服务边界转换蒙版方向,向服务请求保持原图尺寸。",
135
+ "image-edit-standard": "选区白色处理、黑色保护;mask 为与转正原图同尺寸的全不透明二值 PNG。CLI 按服务约定反转蒙版黑白,向服务请求保持原图尺寸。",
103
136
  "image-edit-smart": "按指令重绘,可能改变细节。可选 mask 在 CLI 内绘为青色边界提示,不能保证选区外像素不变;referenceImages 只提供参考,不作为蒙版。",
104
137
  "image-matting-standard": "保留源图可见像素,不能补全遮挡部分;交付真实 alpha PNG,默认保持源图尺寸,可选裁到主体边界。",
105
138
  "image-matting-smart": "先按指令重绘,再自动分割为透明 PNG;可补全遮挡,也可能改变主体细节。可选 mask 是视觉边界提示。已包含透明后处理,无需再次标准抠图。",
106
139
  "image-remove-standard": "白色选区内消除,黑色保护;mask 是与转正原图同尺寸的不透明二值 PNG,向服务请求保持原图尺寸。",
107
140
  "image-remove-smart": "按指令消除内容,单张目标图;可选 mask 是青色边界提示,不作为第二张参考图,也不保证选区外像素不变。",
108
141
  "image-enhance-standard": "targetLongEdge 指定请求的最长边像素,按原比例处理;值域与步长来自实时目录。",
109
- "image-enhance-smart": "生成式清晰修复,可能重新生成纹理、文字或人物细节;需要按用户允许的变化范围验收。",
142
+ "image-enhance-smart": "生成式清晰修复,可能重新生成纹理、文字或人物细节,不保证原细节完全不变。",
110
143
  "image-expand-standard": "canvas/placement 以自动转正后的原图自然像素计。画布左上角为原点,x向右、y向下;原图不得缩放或超出画布,向服务请求目标画布尺寸。",
111
144
  "image-expand-smart": "按自然尺寸和像素坐标放置原图、补绘外围;智能输出采用目标比例,像素尺寸由当前分辨率选项决定,可能改变原图细节。",
112
- "image-text-edit": "replacements 用完整原文匹配;空 to 表示删除。重复原文无法指定某一次出现;核对其他文字是否保持。",
145
+ "image-text-edit": "replacements 用完整原文匹配;空 to 表示删除。重复原文无法指定某一次出现;实际文字与版式以返回图片为准。",
113
146
  "image-ocr": "返回 application/json 内嵌资源,内容为 image{uri,width,height} 和 blocks[{bbox:[left,top,right,bottom],category,text?}];坐标以返回识别图的左上角为原点,单位像素。",
114
- "image-layers-layout": "输入按比例缩小到3000×3000范围内,不放大小图。返回原生模板 JSON 资源及图层类型数量摘要;文字/图片/矢量的实际可编辑程度以模板图层为准,字体可能替换。不是PSD。通过已发现的 Editor 导入能力使用模板。",
115
- "image-layers-smart": "输入按比例缩小到3000×3000范围内,不放大小图;处理后总像素不得低于512×512。把图片拆为独立物件图层,返回原生模板 JSON 及图层摘要;maxLayers 是图层数量上限,按当前远端计费组件计价。不是逐字OCR或PSD。",
116
- "image-vectorize": "返回 SVG 资源;实际矢量内容、形状、颜色和细节重建效果由调用者查看。",
147
+ "image-layers-layout": "用于拆分版式元素,例如海报的标题、正文和底图。输入按比例缩小到3000×3000范围内,不放大小图。返回原生模板 JSON 资源及图层类型数量摘要;文字/图片/矢量的实际可编辑程度以模板图层为准,字体可能替换。不是PSD。通过已发现的 Editor 导入能力使用模板。",
148
+ "image-layers-smart": "用于分开照片中的物件和背景,例如商品与周围的摆件。输入按比例缩小到3000×3000范围内,不放大小图;服务要求处理后宽×高至少262144总像素(512×512),不是每条边都至少512。把图片拆为独立物件图层,返回原生模板 JSON 及图层摘要;maxLayers 是图层数量上限,按当前远端计费组件计价。不是逐字OCR或PSD。",
149
+ "image-vectorize": "返回 SVG 资源;形状、颜色和细节可能重建,实际矢量内容以返回文件为准。",
117
150
  "video-edit-smart": "从原视频推导时长与比例;原片与全部参考视频的合计时长不超过15秒。audioEnabled 控制输出是否有音轨,不承诺原音轨内容不变。智能处理可能改动画面与声音。",
118
- "video-enhance-standard": "标准视频超分,从实际输入时长计费(向上取整秒),请求保持原视频。实际时长、画面及原声保持情况由调用者查看。",
119
- "video-enhance-smart": "生成式视频修复,请求时长取输入最接近整数秒(2–30秒),可能改动画面细节。实际时长、声音内容和同步情况由调用者查看。"
151
+ "video-enhance-standard": "标准视频超分,从实际输入时长计费(向上取整秒),请求保持原视频;实际时长、画面及原声以返回视频为准。",
152
+ "video-enhance-smart": "生成式视频修复,请求时长取输入最接近整数秒(2–30秒),可能改动画面细节;实际时长、声音内容和同步以返回视频为准。"
120
153
  }[model],
121
154
  parameters: schemaParameters(inputSchema, raw.parameters),
122
155
  inputSchema: inputSchema,
@@ -27,6 +27,8 @@ export function canvasPricingSupported(model, configuration) {
27
27
  const components = canvasBillingComponents(configuration);
28
28
  if (!components)
29
29
  return false;
30
+ if (model === "image-enhance-standard" && !components.length && configuration.fixedResolutionPrices)
31
+ return true;
30
32
  const expected = {
31
33
  "image-enhance-standard": { resolution: "METERED" },
32
34
  "image-layers-smart": { max_layers: "METERED" },
@@ -45,6 +47,12 @@ export function hasCanvasMetering(model) {
45
47
  export function estimateCanvasCost(model, quantities) {
46
48
  if (!model.cost || !model.execution)
47
49
  return model.cost;
50
+ const fixed = model.execution.configuration.fixedResolutionPrices;
51
+ if (fixed) {
52
+ const resolution = quantities.resolution;
53
+ const price = resolution !== undefined && Number.isSafeInteger(resolution) ? fixed[resolution] : undefined;
54
+ return price === undefined ? model.cost : { unit: "gaodou", minimum: price, maximum: price };
55
+ }
48
56
  const components = canvasBillingComponents(model.execution.configuration);
49
57
  if (!components)
50
58
  return undefined;
@@ -64,6 +72,10 @@ export function estimateCanvasCost(model, quantities) {
64
72
  return { unit: "gaodou", minimum, maximum };
65
73
  }
66
74
  export function canvasPricingDescription(model, english) {
75
+ if (model.execution?.configuration.fixedResolutionPrices)
76
+ return english
77
+ ? " usage.cost estimates the requested tier at its current catalog price, or uses the available price range for an unlisted tier. The service determines the actual charge."
78
+ : " usage.cost 按所选档位的目录价格估算,其他长边值使用当前报价区间。实际扣费由服务端确定。";
67
79
  if (!hasCanvasMetering(model) || !model.cost || !model.execution)
68
80
  return "";
69
81
  const names = english
@@ -1,6 +1,6 @@
1
1
  import { canvasModelBindings } from "./canvas-models.js";
2
- import { canvasContent, imageResult, link, ocrResult, templateResult, vectorResult } from "./canvas-results.js";
3
- import { createCanvasVideo } from "./canvas-video.js";
2
+ import { canvasContent, ocrResult, templateResult } from "./canvas-results.js";
3
+ import { presentToolContent } from "./tool-output.js";
4
4
  import { queryToolkitResult } from "./canvas-tool-adapter.js";
5
5
  import { queryToolResult } from "./tool-api-adapter.js";
6
6
  import { createMattingRights } from "./matting-billing.js";
@@ -10,59 +10,42 @@ export async function recoverCanvasTool(progress, context, dependencies) {
10
10
  const pipeline = progress.toolPipeline;
11
11
  if (!canvasModelBindings.some(binding => binding[1] === pipeline.model))
12
12
  throw new RemoteProtocolError();
13
- const unknown = (content = pipeline.partialContent) => ({ state: "unknown",
14
- ...(content ? { content } : {}) });
13
+ const saved = pipeline.partialContent ? { content: pipeline.partialContent, fromCheckpoint: true } : {};
14
+ const unknown = () => ({ state: "unknown", ...saved });
15
15
  if (pipeline.stage === "complete" && pipeline.partialContent)
16
- return { state: "complete", content: pipeline.partialContent };
16
+ return { state: "complete", content: pipeline.partialContent, fromCheckpoint: true };
17
+ if (!["dify", "toolkit", "sync"].includes(pipeline.protocol))
18
+ return unknown();
17
19
  if (pipeline.model === "image-matting-standard") {
18
20
  if (pipeline.settlement && pipeline.partialContent) {
19
21
  const { contentId, refIds } = pipeline.settlement;
20
22
  const result = await createMattingRights(dependencies)("/open/editor/mattings/check-deducted/v2", `content_id=${encodeURIComponent(contentId)}&ref_ids=${encodeURIComponent(refIds.join(","))}&image_quality=standard`, context);
21
23
  // Zero outstanding rights confirms this record is deliverable; it says nothing about the actual debit.
22
24
  if (result.used_count === 0)
23
- return { state: "complete", content: pipeline.partialContent };
25
+ return { state: "complete", content: pipeline.partialContent, fromCheckpoint: true };
24
26
  }
25
27
  return unknown();
26
28
  }
27
29
  if (!progress.remoteTaskId || pipeline.protocol === "sync")
28
30
  return unknown();
29
31
  const response = pipeline.protocol === "toolkit"
30
- ? await queryToolkitResult(dependencies.transport, progress.remoteTaskId, context)
31
- : await queryToolResult(dependencies.transport, { ...context.access, signal: context.signal, taskId: progress.remoteTaskId, normalize: canvasContent });
32
+ ? await queryToolkitResult(dependencies.transport, progress.remoteTaskId, context, dependencies.onUnrepresented)
33
+ : await queryToolResult(dependencies.transport, { ...context.access, signal: context.signal, taskId: progress.remoteTaskId, normalize: canvasContent, onUnrepresented: dependencies.onUnrepresented });
32
34
  if (response.state === "failed")
33
35
  throw response.error;
34
36
  if (response.state === "pending")
35
37
  return { state: "pending" };
36
38
  // A smart matting generation is only intermediate; recovery must not submit its segmentation.
37
39
  if (pipeline.requiresFinalization)
38
- return unknown(response.content);
40
+ return { state: "unknown", content: response.content };
39
41
  const { model, verification } = pipeline;
40
42
  let content;
41
43
  if (model === "image-ocr") {
42
- if (!verification?.ocr)
43
- throw new RemoteProtocolError();
44
- content = ocrResult(response.content, verification.ocr);
44
+ content = verification?.ocr ? ocrResult(response.content, verification.ocr) : response.content;
45
45
  }
46
46
  else if (model.startsWith("image-layers-"))
47
47
  content = await templateResult(response.content, dependencies.media, context.signal, dependencies.english);
48
- else if (model === "image-vectorize")
49
- content = await vectorResult(response.content, dependencies.media, context.signal);
50
- else if (model.startsWith("video-")) {
51
- const resource = response.content.find(item => item.type === "resource_link");
52
- if (!resource || resource.type !== "resource_link")
53
- throw new RemoteProtocolError();
54
- let output;
55
- try {
56
- output = await createCanvasVideo(dependencies.media)(resource.uri, context.signal);
57
- }
58
- catch (cause) {
59
- if (context.signal.aborted)
60
- throw context.signal.reason;
61
- throw new RemoteProtocolError({}, cause, "VIDEO_OUTPUT_INVALID");
62
- }
63
- content = link(resource.uri, `result.${output.format}`, output.format === "mov" ? "video/quicktime" : `video/${output.format}`);
64
- }
65
48
  else
66
- content = await imageResult(response.content, dependencies.media, context.signal);
49
+ content = presentToolContent(response.content, model.startsWith("video-") ? "video" : "image", dependencies.onMissingMedia);
67
50
  return { state: "complete", content };
68
51
  }