@insmind/cli 2.1.0 → 2.1.2

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 (122) hide show
  1. package/README.md +30 -0
  2. package/contracts/operations/agent.send/input.schema.json +1 -77
  3. package/contracts/operations/dam.folder.list/input.schema.json +0 -1
  4. package/contracts/operations/dam.folder.list/output.schema.json +1 -2
  5. package/contracts/operations/dam.list/input.schema.json +3 -6
  6. package/contracts/operations/dam.list/output.schema.json +1 -2
  7. package/contracts/operations/dam.search/input.schema.json +3 -6
  8. package/contracts/operations/dam.search/output.schema.json +1 -2
  9. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
  10. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
  11. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
  12. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
  13. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  14. package/dist/bin/postinstall.js +22 -6
  15. package/dist/bin/sync-skill.js +33 -0
  16. package/dist/bin/task-worker.js +2 -2
  17. package/dist/src/bootstrap/create-cli.js +13 -6
  18. package/dist/src/bootstrap/create-runtime.js +103 -29
  19. package/dist/src/bootstrap/run-task-worker.js +6 -2
  20. package/dist/src/bootstrap/validators.js +87 -151
  21. package/dist/src/cli/action-binding.js +14 -37
  22. package/dist/src/cli/agent-commands.js +13 -13
  23. package/dist/src/cli/auth-commands.js +2 -1
  24. package/dist/src/cli/creation-help.js +9 -0
  25. package/dist/src/cli/dam-commands.js +10 -14
  26. package/dist/src/cli/editor-commands.js +16 -12
  27. package/dist/src/cli/errors.js +84 -26
  28. package/dist/src/cli/host-input.js +62 -5
  29. package/dist/src/cli/model-commands.js +9 -3
  30. package/dist/src/cli/observed-errors.js +7 -3
  31. package/dist/src/cli/org-commands.js +3 -1
  32. package/dist/src/cli/presenter.js +4 -5
  33. package/dist/src/cli/task-commands.js +6 -2
  34. package/dist/src/cli/tool-commands.js +12 -11
  35. package/dist/src/contracts/creation-input.js +20 -17
  36. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  37. package/dist/src/features/agent/creative-protocol.js +8 -29
  38. package/dist/src/features/agent/resource-authorizer.js +25 -17
  39. package/dist/src/features/agent/result-reader.js +31 -14
  40. package/dist/src/features/agent/use-cases.js +6 -31
  41. package/dist/src/features/auth/credential-store.js +1 -0
  42. package/dist/src/features/credits/use-cases.js +55 -28
  43. package/dist/src/features/dam/asset-projection.js +3 -6
  44. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  45. package/dist/src/features/dam/object-storage.js +2 -1
  46. package/dist/src/features/dam/repository-catalog.js +30 -21
  47. package/dist/src/features/dam/use-cases.js +14 -9
  48. package/dist/src/features/editor/bridge-client.js +0 -2
  49. package/dist/src/features/editor/bridge-process.js +3 -2
  50. package/dist/src/features/editor/public-url.js +1 -36
  51. package/dist/src/features/editor/session-state.js +1 -0
  52. package/dist/src/features/editor/session.js +3 -2
  53. package/dist/src/features/editor/use-cases.js +27 -2
  54. package/dist/src/features/org/org-service.js +10 -1
  55. package/dist/src/features/org/use-cases.js +18 -4
  56. package/dist/src/features/task/process-owner.js +54 -0
  57. package/dist/src/features/task/store.js +102 -32
  58. package/dist/src/features/task/task-background.js +8 -4
  59. package/dist/src/features/task/use-cases.js +184 -84
  60. package/dist/src/features/tool/argument-paths.js +14 -0
  61. package/dist/src/features/tool/canvas-copy.js +28 -15
  62. package/dist/src/features/tool/canvas-matting.js +123 -0
  63. package/dist/src/features/tool/canvas-media.js +102 -55
  64. package/dist/src/features/tool/canvas-models.js +66 -33
  65. package/dist/src/features/tool/canvas-pricing.js +12 -0
  66. package/dist/src/features/tool/canvas-recovery.js +13 -30
  67. package/dist/src/features/tool/canvas-results.js +92 -93
  68. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  69. package/dist/src/features/tool/canvas-video.js +44 -37
  70. package/dist/src/features/tool/catalog.js +2 -23
  71. package/dist/src/features/tool/dynamic-schema.js +42 -46
  72. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  73. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  74. package/dist/src/features/tool/resource-authorizer.js +11 -3
  75. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  76. package/dist/src/features/tool/tool-definitions.js +23 -0
  77. package/dist/src/features/tool/tool-errors.js +25 -0
  78. package/dist/src/features/tool/tool-output.js +15 -0
  79. package/dist/src/features/tool/use-cases.js +74 -98
  80. package/dist/src/features/update/package-manager.js +124 -0
  81. package/dist/src/features/update/update-service.js +195 -55
  82. package/dist/src/platform/detached-spawn.js +9 -0
  83. package/dist/src/platform/file-lock.js +12 -4
  84. package/dist/src/platform/input-uri.js +23 -1
  85. package/dist/src/platform/local-json-file.js +97 -15
  86. package/dist/src/platform/media-type.js +46 -0
  87. package/dist/src/platform/open-browser.js +5 -2
  88. package/dist/src/platform/public-url.js +35 -0
  89. package/dist/src/platform/remote-error-evidence.js +33 -6
  90. package/dist/src/platform/resource-auth-key.js +35 -1
  91. package/dist/src/platform/safe-upload-file.js +38 -44
  92. package/dist/src/platform/schema-compiler.js +16 -0
  93. package/dist/src/platform/signature.js +2 -2
  94. package/dist/src/platform/signed-http-transport.js +4 -1
  95. package/dist/src/platform/url-safety.js +6 -1
  96. package/dist/src/platform/webm-header.js +41 -0
  97. package/dist/src/platform/windows-acl/LICENSE-mingw-w64 +43 -0
  98. package/dist/src/platform/windows-acl/arm64.node +0 -0
  99. package/dist/src/platform/windows-acl/ia32.node +0 -0
  100. package/dist/src/platform/windows-acl/x64.node +0 -0
  101. package/dist/src/platform/windows-host-job/arm64.exe +0 -0
  102. package/dist/src/platform/windows-host-job/ia32.exe +0 -0
  103. package/dist/src/platform/windows-host-job/sha256.json +7 -0
  104. package/dist/src/platform/windows-host-job/x64.exe +0 -0
  105. package/dist/src/platform/windows-private-state.js +72 -0
  106. package/dist/src/product/config.js +1 -1
  107. package/dist/src/telemetry/command-route.js +38 -0
  108. package/dist/src/telemetry/command-routes.json +1 -0
  109. package/dist/src/telemetry/failure-summary.js +3 -3
  110. package/dist/src/telemetry/invocation.js +1 -2
  111. package/dist/src/telemetry/process-errors.js +17 -33
  112. package/dist/src/telemetry/sanitize.js +19 -4
  113. package/dist/src/telemetry/sls-sink.js +45 -20
  114. package/package.json +4 -4
  115. package/skills/insmind-cli/SKILL.md +18 -5
  116. package/skills/insmind-cli/references/agent.md +9 -4
  117. package/skills/insmind-cli/references/creation.md +3 -1
  118. package/skills/insmind-cli/references/editor.md +7 -5
  119. package/skills/insmind-cli/references/errors.md +20 -9
  120. package/skills/insmind-cli/references/matting.md +3 -5
  121. package/skills/insmind-cli/references/media-tools.md +10 -4
  122. 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
+ }
@@ -1,10 +1,10 @@
1
1
  import { readFile, mkdtemp, writeFile, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
- import { pathToFileURL } from "node:url";
5
4
  import { inspectUploadFile, LocalFileInputError } from "../../platform/safe-upload-file.js";
6
- import { uriShape } from "../../platform/input-uri.js";
7
- import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
5
+ import { fileUriFromLocalPath, uriShape } from "../../platform/input-uri.js";
6
+ import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
7
+ import { isFilemsResource, withFilemsAuthKey } from "../../platform/resource-auth-key.js";
8
8
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
9
9
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
10
10
  import { ToolInputError } from "./catalog.js";
@@ -20,6 +20,8 @@ function mediaFailure(phase, summary, status, cause) {
20
20
  return new RemoteRequestError(status, false, {}, cause, `MEDIA_${phase.toUpperCase()}_FAILED`, { ...summary, mediaPhase: phase });
21
21
  }
22
22
  export function createCanvasMedia(dependencies) {
23
+ // Scoped to this call's identity. A later consumer of the same asset must receive the URL that actually worked.
24
+ const renewed = new Map();
23
25
  async function readWithEvidence(uri, signal, limit = 64 * 1024 * 1024) {
24
26
  signal.throwIfAborted();
25
27
  if (uri.startsWith("file:")) {
@@ -37,7 +39,27 @@ export function createCanvasMedia(dependencies) {
37
39
  }
38
40
  }
39
41
  let url = parseSafeRemoteAssetUrl(uri);
40
- for (let redirects = 0; redirects <= 5; redirects++) {
42
+ const protectedOrigin = isFilemsResource(url);
43
+ let authKey;
44
+ let freshKey;
45
+ let redirects = 0;
46
+ while (redirects <= 5) {
47
+ if (protectedOrigin) {
48
+ const existing = url.searchParams.get("auth_key");
49
+ if (existing?.trim())
50
+ authKey = existing;
51
+ else {
52
+ if (!authKey) {
53
+ const filems = dependencies.filems;
54
+ if (!filems)
55
+ throw new RemoteProtocolError({}, undefined, "RESOURCE_AUTH_REQUIRED");
56
+ authKey = await filems.authKeys.getAuthKey(filems.access, signal);
57
+ freshKey = authKey;
58
+ signal.throwIfAborted();
59
+ }
60
+ url = new URL(withFilemsAuthKey(url.href, authKey));
61
+ }
62
+ }
41
63
  let response;
42
64
  try {
43
65
  response = await dependencies.fetch(url, { redirect: "manual", signal });
@@ -49,13 +71,27 @@ export function createCanvasMedia(dependencies) {
49
71
  }
50
72
  signal.throwIfAborted();
51
73
  const summary = responseDiagnostics(url, redirects, response.headers);
74
+ if (response.status === 403 && protectedOrigin && freshKey === undefined && dependencies.filems) {
75
+ await response.body?.cancel().catch(() => undefined);
76
+ const { authKeys, access } = dependencies.filems;
77
+ authKey = await authKeys.getAuthKey(access, signal);
78
+ signal.throwIfAborted();
79
+ freshKey = authKey;
80
+ url = new URL(withFilemsAuthKey(url.href, authKey));
81
+ continue; // Retry only this GET. A second 403 follows the normal error path.
82
+ }
52
83
  if ([301, 302, 303, 307, 308].includes(response.status)) {
53
84
  const location = response.headers.get("location");
54
85
  await response.body?.cancel().catch(() => undefined);
55
86
  if (!location || redirects === 5)
56
87
  throw mediaFailure("redirect", summary, response.status);
57
88
  try {
58
- url = parseSafeRemoteAssetUrl(new URL(location, url).href);
89
+ const next = parseSafeRemoteAssetUrl(new URL(location, url).href);
90
+ // A FileMS key may follow a same-origin path, never a cross-origin redirect in either direction.
91
+ if (next.origin !== url.origin && (protectedOrigin || isFilemsResource(next)))
92
+ throw new UrlSafetyError();
93
+ url = next;
94
+ redirects++;
59
95
  }
60
96
  catch (cause) {
61
97
  throw mediaFailure("redirect", summary, response.status, cause);
@@ -100,6 +136,8 @@ export function createCanvasMedia(dependencies) {
100
136
  throw Object.assign(cause, { diagnosticSummary: evidence });
101
137
  throw mediaFailure("read", evidence, response.status, cause);
102
138
  }
139
+ if (freshKey !== undefined)
140
+ renewed.set(uri, withFilemsAuthKey(uri, freshKey));
103
141
  return { bytes: Buffer.concat(chunks), summary: { ...summary, mediaPhase: "read", mediaBytesRead: size }, status: response.status };
104
142
  }
105
143
  throw mediaFailure("redirect", responseDiagnostics(url, 5));
@@ -132,82 +170,88 @@ export function createCanvasMedia(dependencies) {
132
170
  try {
133
171
  const path = join(directory, `asset.${extension}`);
134
172
  await writeFile(path, bytes, { mode: 0o600, signal });
135
- return (await dependencies.uploader.upload({ url: pathToFileURL(path).href }, access, signal)).url;
173
+ return (await dependencies.uploader.upload({ url: fileUriFromLocalPath(path) }, access, signal)).url;
136
174
  }
137
175
  finally {
138
176
  await rm(directory, { recursive: true, force: true });
139
177
  }
140
178
  }
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
179
  async function uploadFile(uri, access, signal) {
166
180
  // Keep the actual input extension/MIME for audio references instead of renaming every file .mp3.
167
- await read(uri, signal);
168
181
  return (await dependencies.uploader.upload({ url: uri }, access, signal)).url;
169
182
  }
170
- return { read, image, upload, uploadFile, mask };
183
+ return { read, image, upload, uploadFile, deliveryUri: (uri) => renewed.get(uri) ?? uri };
184
+ }
185
+ /** A media limit reached while retrieving a result is a delivery failure, not a user input error. */
186
+ export async function readOutputMedia(media, uri, signal) {
187
+ try {
188
+ return await media.read(uri, signal);
189
+ }
190
+ catch (cause) {
191
+ signal.throwIfAborted();
192
+ if (!(cause instanceof ToolInputError))
193
+ throw cause;
194
+ throw new RemoteProtocolError({}, cause, cause.reason === "media_too_large" ? "TOOL_OUTPUT_MEDIA_TOO_LARGE" : "TOOL_OUTPUT_READ_FAILED");
195
+ }
196
+ }
197
+ function maskConversionError(cause) {
198
+ return new ToolInputError("mask_geometry_or_format", "/arguments/mask", [], cause);
171
199
  }
172
- export async function maskPng(mask, width, height, invert = false) {
200
+ async function selectionImage(bytes) {
173
201
  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();
202
+ try {
203
+ const image = sharp(bytes, { limitInputPixels: 64 * 1024 * 1024 });
204
+ const { pages } = await image.metadata();
205
+ if ((pages ?? 1) === 1)
206
+ return image.autoOrient();
207
+ }
208
+ catch (cause) {
209
+ throw maskConversionError(cause);
210
+ }
211
+ // Both local transforms produce a single frame. Never silently drop extra frames.
212
+ throw maskConversionError();
213
+ }
214
+ export async function invertSelectionMask(bytes) {
215
+ const image = await selectionImage(bytes);
216
+ return image.negate({ alpha: false }).png().toBuffer().catch(cause => { throw maskConversionError(cause); });
175
217
  }
176
- export async function outlineImage(source, mask) {
218
+ export async function outlineImage(source, selection) {
177
219
  const { default: sharp } = await import("sharp");
178
220
  const { width, height } = source;
221
+ const image = await selectionImage(selection);
222
+ const { data: mask, info } = await image.flatten({ background: "black" }).greyscale().raw()
223
+ .toBuffer({ resolveWithObject: true }).catch(cause => { throw maskConversionError(cause); });
224
+ if (info.width !== width || info.height !== height)
225
+ throw maskConversionError();
179
226
  const { data } = await sharp(source.bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
180
227
  const radius = Math.max(1, Math.round(Math.max(width, height) / 600));
181
228
  for (let y = 0; y < height; y++)
182
229
  for (let x = 0; x < width; x++) {
183
230
  const index = y * width + x;
184
- if (mask[index] !== 255)
231
+ const center = mask[index];
232
+ if (!center)
185
233
  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
- }
234
+ // Draw the inside edge of the supplied selection, keeping its coverage at soft edges.
235
+ 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);
236
+ const coverage = (center - neighbor) / 255;
237
+ if (!coverage)
238
+ continue;
239
+ const offset = index * 4;
240
+ const sourceAlpha = (1 - coverage) * data[offset + 3] / 255;
241
+ const alpha = coverage + sourceAlpha;
242
+ data[offset] = Math.round(data[offset] * sourceAlpha / alpha);
243
+ data[offset + 1] = Math.round((255 * coverage + data[offset + 1] * sourceAlpha) / alpha);
244
+ data[offset + 2] = Math.round((255 * coverage + data[offset + 2] * sourceAlpha) / alpha);
245
+ data[offset + 3] = Math.round(255 * alpha);
202
246
  }
203
247
  return sharp(data, { raw: { width, height, channels: 4 } }).png().toBuffer();
204
248
  }
205
249
  export function expansionGeometry(source, canvas, placement) {
206
250
  const { width, height } = canvas;
207
251
  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)) {
252
+ if (![width, height].every(n => Number.isSafeInteger(n) && n > 0)
253
+ || ![x, y].every(n => Number.isSafeInteger(n) && n >= 0)
254
+ || x + source.width > width || y + source.height > height) {
211
255
  throw new ToolInputError("expansion_geometry", "/arguments/canvas");
212
256
  }
213
257
  return { outer: [width, height], corners: [[x, y], [x + source.width, y], [x + source.width, y + source.height], [x, y + source.height]] };
@@ -215,6 +259,9 @@ export function expansionGeometry(source, canvas, placement) {
215
259
  export async function expansionImage(source, canvas, placement) {
216
260
  const { default: sharp } = await import("sharp");
217
261
  expansionGeometry(source, canvas, placement);
262
+ if (canvas.width > 4096 || canvas.height > 4096 || canvas.width * canvas.height > 16 * 1024 * 1024) {
263
+ throw new ToolInputError("expansion_canvas_too_large", "/arguments/canvas");
264
+ }
218
265
  const flattened = await sharp(source.bytes).flatten({ background: "white" }).png().toBuffer();
219
266
  return sharp({ create: { ...canvas, channels: 3, background: { r: 0, g: 255, b: 0 } } })
220
267
  .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