@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,61 @@
1
+ // Product copy only. Executable constraints stay in the shared formal Schema.
2
+ const copy = {
3
+ "image-edit-standard": ["Standard image edit", "White mask pixels are processed; black pixels are protected. Supply an opaque binary PNG matching the auto-oriented source. The CLI converts service-specific mask polarity and requests source dimensions."],
4
+ "image-edit-smart": ["Smart image edit", "Generative editing can change details. An optional mask is rendered as a cyan outline on the target image; referenceImages are references, never a mask. Inspect changes outside the selection."],
5
+ "image-matting-standard": ["Standard background removal", "Preserves visible source pixels without reconstructing occluded parts. Returns a real alpha PNG at source dimensions unless cropToSubject is enabled."],
6
+ "image-matting-smart": ["Smart subject extraction", "Redraws the requested subject, then segments the redraw into a transparent PNG. Hidden details are generated guesses. An optional mask is a visual boundary cue. Transparent postprocessing is included; do not pay for another standard matting call."],
7
+ "image-remove-standard": ["Standard object removal", "Remove within white mask pixels; black pixels are protected. The opaque binary PNG mask must match the auto-oriented source. Source dimensions are requested from the service."],
8
+ "image-remove-smart": ["Smart object removal", "Remove objects from one target image using instructions. An optional mask is rendered as a cyan outline, not sent as another reference image. Inspect changes outside the selection."],
9
+ "image-enhance-standard": ["Standard image upscale", "targetLongEdge specifies the output's longest edge in pixels while retaining aspect ratio. Bounds and steps come from the current catalog."],
10
+ "image-enhance-smart": ["Smart image restoration", "Generative restoration may reconstruct textures, text, faces or product details. Check the user's permitted changes against the actual result."],
11
+ "image-expand-standard": ["Standard image expansion", "canvas and placement use auto-oriented source pixels. Origin is top-left; x goes right and y down. The original must fit without scaling. The target canvas dimensions are requested from the service."],
12
+ "image-expand-smart": ["Smart image expansion", "Place the source at natural size and expand its surroundings. Output uses the target aspect ratio; pixel dimensions follow the live resolution setting. Source details can change."],
13
+ "image-text-edit": ["Image text replacement", "replacements match complete original text. An empty to deletes it. Repeated text cannot be targeted by occurrence. Verify all unchanged text."],
14
+ "image-ocr": ["Image text recognition", "Returns an embedded application/json resource: image{uri,width,height}, blocks[{bbox:[left,top,right,bottom],category,text?}]. Coordinates use the returned recognition image's top-left origin in pixels."],
15
+ "image-layers-layout": ["Layout decomposition", "Fits the source within 3000×3000 pixels without enlargement. Returns native template JSON and actual element counts, not PSD. Editability depends on the returned layers; fonts may be substituted. Use a discovered Editor import capability to open the template."],
16
+ "image-layers-smart": ["Smart layer decomposition", "Fits the source within 3000×3000 pixels without enlargement; the prepared image must have at least 512×512 total pixels. Returns native template JSON and layer counts, not PSD or word-by-word OCR. maxLayers is an upper bound. Pricing uses current remote metered components."],
17
+ "image-vectorize": ["Image to SVG", "Returns an SVG resource. The caller inspects actual vector contents, reconstructed shapes, colors and details."],
18
+ "video-edit-smart": ["Smart video edit", "Duration and ratio come from the actual source. Reference videos including the source total at most 15 seconds. audioEnabled controls audio presence, not preservation of the original sound."],
19
+ "video-enhance-standard": ["Standard video upscale", "Uses ceil(actual seconds) for billing and requests preservation of the source video. The caller inspects actual duration, visuals and soundtrack preservation."],
20
+ "video-enhance-smart": ["Smart video restoration", "Generative restoration requests the source duration rounded to 2–30 seconds and may change details. The caller inspects actual duration, sound content and synchronization."]
21
+ };
22
+ export function englishCanvasCopy(model, schema) {
23
+ const descriptions = {
24
+ image: "One HTTP(S) or CLI file:// source image URI.",
25
+ video: "One HTTP(S) or CLI file:// source video URI.",
26
+ mask: "Fully opaque PNG containing only pure black and white, matching the auto-oriented source. White processes, black protects. White must be nonempty; all-white selects the entire image.",
27
+ cropToSubject: "Crop to the nonzero alpha subject bounds. Default keeps the final source dimensions.",
28
+ canvas: "Target canvas width and height in natural source pixels.",
29
+ placement: "Source top-left position in canvas pixels: x right, y down. No source scaling.",
30
+ referenceImages: "Additional image references, separate from the target image and mask.",
31
+ referenceVideos: "Additional reference videos. The source video remains first.",
32
+ referenceAudios: "Additional audio references.",
33
+ replacements: "Complete original/new text pairs. Empty to means delete; duplicate from entries are rejected.",
34
+ from: "The complete original text to replace, including punctuation and spaces.",
35
+ to: "Replacement text. An empty string deletes the matched original text.",
36
+ targetLongEdge: "Output's longest edge in pixels; aspect ratio is retained.",
37
+ maxLayers: "Requested layer count upper bound, not an exact output count."
38
+ };
39
+ for (const [name, property] of Object.entries(schema.properties)) {
40
+ if (descriptions[name])
41
+ property.description = descriptions[name];
42
+ if (property.items?.format === "uri")
43
+ property.items.description = "HTTP(S) or CLI file:// asset URI.";
44
+ for (const [child, field] of Object.entries(property.items?.properties ?? {})) {
45
+ if (descriptions[child])
46
+ field.description = descriptions[child];
47
+ }
48
+ }
49
+ if (model.endsWith("-smart") && schema.properties.mask) {
50
+ schema.properties.mask.description = "Fully opaque PNG containing only pure black and white, matching the auto-oriented source. Nonempty white pixels identify the target; all-white selects the entire image. The CLI converts this to a visual boundary cue, which cannot guarantee unchanged pixels outside the selection.";
51
+ }
52
+ if (model === "video-edit-smart") {
53
+ schema.properties.video.description = "Source video to edit, referenced as 视频1 in the prompt. HTTP(S) or CLI file:// URI.";
54
+ schema.properties.prompt.description = "The user's prompt is kept verbatim; the CLI only prefixes media bindings. Reference the source as 视频1, referenceVideos from 视频2, referenceImages from 图1, and referenceAudios from 音频1, each in array order. The CLI adds original filename-to-label bindings before uploading changes filenames.";
55
+ schema.properties.referenceImages.description = "Reference images, numbered 图1, 图2, etc. in array order.";
56
+ schema.properties.referenceVideos.description = "Reference videos, numbered 视频2, 视频3, etc.; 视频1 is always the source. The source and all reference videos combined must not exceed 15 seconds.";
57
+ schema.properties.referenceAudios.description = "Reference audio, numbered 音频1, 音频2, etc. in array order.";
58
+ }
59
+ const [title, usageDescription] = copy[model];
60
+ return { title, usageDescription };
61
+ }
@@ -0,0 +1,193 @@
1
+ import { readFile, mkdtemp, writeFile, rm } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { inspectUploadFile } from "../../platform/safe-upload-file.js";
6
+ import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
7
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
8
+ import { ToolInputError } from "./catalog.js";
9
+ export function createCanvasMedia(dependencies) {
10
+ async function read(uri, signal, limit = 64 * 1024 * 1024) {
11
+ signal.throwIfAborted();
12
+ if (uri.startsWith("file:")) {
13
+ const file = await inspectUploadFile({ url: uri, signal });
14
+ if (file.size > limit)
15
+ throw new ToolInputError("media_too_large", "/arguments");
16
+ return readFile(file.filePath, { signal });
17
+ }
18
+ let url = parseSafeRemoteAssetUrl(uri);
19
+ for (let redirects = 0; redirects <= 5; redirects++) {
20
+ const response = await dependencies.fetch(url, { redirect: "manual", signal });
21
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
22
+ const location = response.headers.get("location");
23
+ await response.body?.cancel();
24
+ if (!location || redirects === 5)
25
+ throw new RemoteProtocolError();
26
+ url = parseSafeRemoteAssetUrl(new URL(location, url).href);
27
+ continue;
28
+ }
29
+ if (!response.ok || !response.body)
30
+ throw new RemoteProtocolError();
31
+ if (Number(response.headers.get("content-length")) > limit) {
32
+ await response.body.cancel();
33
+ throw new ToolInputError("media_too_large", "/arguments");
34
+ }
35
+ const reader = response.body.getReader();
36
+ const chunks = [];
37
+ let size = 0;
38
+ try {
39
+ while (true) {
40
+ const { value, done } = await reader.read();
41
+ if (done)
42
+ break;
43
+ size += value.byteLength;
44
+ if (size > limit)
45
+ throw new ToolInputError("media_too_large", "/arguments");
46
+ chunks.push(Buffer.from(value));
47
+ }
48
+ }
49
+ finally {
50
+ await reader.cancel().catch(() => undefined);
51
+ reader.releaseLock();
52
+ }
53
+ return Buffer.concat(chunks);
54
+ }
55
+ throw new RemoteProtocolError();
56
+ }
57
+ async function image(uri, signal) {
58
+ try {
59
+ const { default: sharp } = await import("sharp");
60
+ const raw = await read(uri, signal);
61
+ const metadata = await sharp(raw, { limitInputPixels: 64 * 1024 * 1024 }).metadata();
62
+ if ((metadata.pages ?? 1) !== 1)
63
+ throw new ToolInputError("animated_image_not_supported", "/arguments/image");
64
+ const { data, info } = await sharp(raw).autoOrient().png().toBuffer({ resolveWithObject: true });
65
+ return { bytes: data, width: info.width, height: info.height };
66
+ }
67
+ catch (cause) {
68
+ if (signal.aborted)
69
+ throw signal.reason;
70
+ if (cause instanceof ToolInputError)
71
+ throw cause;
72
+ throw new ToolInputError("image_decode_failed", "/arguments/image", [], cause);
73
+ }
74
+ }
75
+ async function upload(bytes, extension, access, signal) {
76
+ const directory = await mkdtemp(join(tmpdir(), "gd-cli-media-"));
77
+ try {
78
+ const path = join(directory, `asset.${extension}`);
79
+ await writeFile(path, bytes, { mode: 0o600, signal });
80
+ return (await dependencies.uploader.upload({ url: pathToFileURL(path).href }, access, signal)).url;
81
+ }
82
+ finally {
83
+ await rm(directory, { recursive: true, force: true });
84
+ }
85
+ }
86
+ async function mask(uri, source, signal) {
87
+ const { default: sharp } = await import("sharp");
88
+ const bytes = await read(uri, signal);
89
+ const metadata = await sharp(bytes).metadata();
90
+ if (metadata.format !== "png" || metadata.width !== source.width || metadata.height !== source.height
91
+ || (metadata.orientation !== undefined && metadata.orientation !== 1)) {
92
+ throw new ToolInputError("mask_geometry_or_format", "/arguments/mask");
93
+ }
94
+ const { data, info } = await sharp(bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
95
+ const mono = Buffer.alloc(info.width * info.height);
96
+ let selected = false;
97
+ for (let i = 0; i < mono.length; i++) {
98
+ const offset = i * 4;
99
+ const value = data[offset];
100
+ if ((value !== 0 && value !== 255) || data[offset + 1] !== value || data[offset + 2] !== value || data[offset + 3] !== 255) {
101
+ throw new ToolInputError("mask_requires_opaque_binary_png", "/arguments/mask");
102
+ }
103
+ mono[i] = value;
104
+ selected ||= value === 255;
105
+ }
106
+ if (!selected)
107
+ throw new ToolInputError("mask_empty_selection", "/arguments/mask");
108
+ return mono;
109
+ }
110
+ async function uploadFile(uri, access, signal) {
111
+ // Keep the actual input extension/MIME for audio references instead of renaming every file .mp3.
112
+ await read(uri, signal);
113
+ return (await dependencies.uploader.upload({ url: uri }, access, signal)).url;
114
+ }
115
+ return { read, image, upload, uploadFile, mask };
116
+ }
117
+ export async function maskPng(mask, width, height, invert = false) {
118
+ const { default: sharp } = await import("sharp");
119
+ return sharp(invert ? Buffer.from(mask.map(value => 255 - value)) : mask, { raw: { width, height, channels: 1 } }).png().toBuffer();
120
+ }
121
+ export async function outlineImage(source, mask) {
122
+ const { default: sharp } = await import("sharp");
123
+ const { width, height } = source;
124
+ const { data } = await sharp(source.bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
125
+ const radius = Math.max(1, Math.round(Math.max(width, height) / 600));
126
+ for (let y = 0; y < height; y++)
127
+ for (let x = 0; x < width; x++) {
128
+ const index = y * width + x;
129
+ if (mask[index] !== 255)
130
+ continue;
131
+ let boundary = false;
132
+ for (const [dx, dy] of [[-radius, 0], [radius, 0], [0, -radius], [0, radius]]) {
133
+ const nx = x + dx;
134
+ const ny = y + dy;
135
+ if (nx < 0 || nx >= width || ny < 0 || ny >= height || mask[ny * width + nx] !== 255) {
136
+ boundary = true;
137
+ break;
138
+ }
139
+ }
140
+ if (boundary) {
141
+ const offset = index * 4;
142
+ data[offset] = 0;
143
+ data[offset + 1] = 255;
144
+ data[offset + 2] = 255;
145
+ data[offset + 3] = 255;
146
+ }
147
+ }
148
+ return sharp(data, { raw: { width, height, channels: 4 } }).png().toBuffer();
149
+ }
150
+ export function expansionGeometry(source, canvas, placement) {
151
+ const { width, height } = canvas;
152
+ const { x, y } = placement;
153
+ if (width > 4096 || height > 4096 || width * height > 16 * 1024 * 1024
154
+ || x + source.width > width || y + source.height > height
155
+ || (width === source.width && height === source.height)) {
156
+ throw new ToolInputError("expansion_geometry", "/arguments/canvas");
157
+ }
158
+ return { outer: [width, height], corners: [[x, y], [x + source.width, y], [x + source.width, y + source.height], [x, y + source.height]] };
159
+ }
160
+ export async function expansionImage(source, canvas, placement) {
161
+ const { default: sharp } = await import("sharp");
162
+ expansionGeometry(source, canvas, placement);
163
+ const flattened = await sharp(source.bytes).flatten({ background: "white" }).png().toBuffer();
164
+ return sharp({ create: { ...canvas, channels: 3, background: { r: 0, g: 255, b: 0 } } })
165
+ .composite([{ input: flattened, left: placement.x, top: placement.y }]).png().toBuffer();
166
+ }
167
+ export async function composeMatting(source, segmentation, channel, crop) {
168
+ const { default: sharp } = await import("sharp");
169
+ const metadata = await sharp(segmentation).metadata();
170
+ if (channel === "alpha" && metadata.hasAlpha !== true)
171
+ throw new RemoteProtocolError({}, undefined, "MATTING_ALPHA_MISSING");
172
+ const alpha = await sharp(segmentation).autoOrient().resize(source.width, source.height, { fit: "fill" })
173
+ .ensureAlpha().extractChannel(channel === "alpha" ? 3 : 0).raw().toBuffer();
174
+ const { data } = await sharp(source.bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
175
+ let left = source.width, top = source.height, right = -1, bottom = -1;
176
+ for (let i = 0; i < alpha.length; i++) {
177
+ const value = Math.round(alpha[i] * data[i * 4 + 3] / 255);
178
+ data[i * 4 + 3] = value;
179
+ if (value > 0) {
180
+ const x = i % source.width;
181
+ const y = Math.floor(i / source.width);
182
+ left = Math.min(left, x);
183
+ top = Math.min(top, y);
184
+ right = Math.max(right, x);
185
+ bottom = Math.max(bottom, y);
186
+ }
187
+ }
188
+ let pipeline = sharp(data, { raw: { width: source.width, height: source.height, channels: 4 } });
189
+ // An empty segmentation has no subject bounds; preserve its full transparent canvas.
190
+ if (crop && right >= 0)
191
+ pipeline = pipeline.extract({ left, top, width: right - left + 1, height: bottom - top + 1 });
192
+ return pipeline.png().toBuffer();
193
+ }
@@ -0,0 +1,109 @@
1
+ import { englishCanvasCopy } from "./canvas-copy.js";
2
+ import { canvasPricingDescription } from "./canvas-pricing.js";
3
+ import { contractDocument } from "../../contracts/schema.js";
4
+ /** Service protocol bindings, not a local inventory of available models. MNS supplies availability. */
5
+ export const canvasModelBindings = [
6
+ ["image.edit", "image-edit-standard", "canvas-quick-image-edit", "canvas-image-edit", "标准改图"],
7
+ ["image.edit", "image-edit-smart", "canvas-smart-image-edit", "canvas-image-edit", "智能改图"],
8
+ ["image.matting", "image-matting-standard", "old_matting", "canvas-image-matting", "标准抠图"],
9
+ ["image.matting", "image-matting-smart", "canvas-smart-matting", "canvas-image-matting", "智能抠图"],
10
+ ["image.remove", "image-remove-standard", "canvas-quick-image-remove", "canvas-image-remove", "标准消除"],
11
+ ["image.remove", "image-remove-smart", "canvas-image-remove-smart", "canvas-image-remove", "智能消除"],
12
+ ["image.enhance", "image-enhance-standard", "eval-tencent-mps-super-resolution", "canvas-image-enhance", "标准超分"],
13
+ ["image.enhance", "image-enhance-smart", "canvas-image-enhance-generative", "canvas-image-enhance", "智能修复"],
14
+ ["image.expand", "image-expand-standard", "outpainting-pro", "canvas-image-expand", "标准扩图"],
15
+ ["image.expand", "image-expand-smart", "canvas-image-expand-sunburst", "canvas-image-expand", "智能扩图"],
16
+ ["image.text_edit", "image-text-edit", "TextEdit", "TextEdit", "图片改字"],
17
+ ["image.ocr", "image-ocr", "new-image-ocr", "new-image-ocr", "文字识别"],
18
+ ["image.layers", "image-layers-layout", "codia", "special-agent-tools", "图文分层"],
19
+ ["image.layers", "image-layers-smart", "seedream-layer-decomposition", "special-agent-tools", "智能分层"],
20
+ ["image.vectorize", "image-vectorize", "eval-recraft-vectorize", "canvas-image-vectorize", "图片转矢量"],
21
+ ["video.edit", "video-edit-smart", "canvas-video-edit-smart", "canvas-video-edit", "智能改视频"],
22
+ ["video.enhance", "video-enhance-standard", "canvas-video-enhance-fast", "canvas-video-enhance", "标准视频超分"],
23
+ ["video.enhance", "video-enhance-smart", "canvas-video-enhance-smart", "canvas-video-enhance", "智能视频修复"]
24
+ ];
25
+ export const canvasSceneCodes = [...new Set(canvasModelBindings.map(binding => binding[3]))];
26
+ export const canvasControlParameterNames = new Set(["quality", "resolution", "audioEnabled", "targetLongEdge", "maxLayers"]);
27
+ const parameterAliases = {
28
+ "image-enhance-standard": { targetLongEdge: "resolution" },
29
+ "image-layers-smart": { maxLayers: "max_layers" }
30
+ };
31
+ export function canvasRemoteControlArguments(model, value) {
32
+ return Object.fromEntries(Object.entries(value).map(([name, argument]) => {
33
+ const remoteName = parameterAliases[model]?.[name] ?? name;
34
+ return [remoteName, remoteName === "max_layers" ? String(argument) : argument];
35
+ }));
36
+ }
37
+ export function canvasInputSchema(id, fields) {
38
+ const schema = contractDocument(`tool.call/models/${id}.schema.json`);
39
+ // Schema supplies the stable roles and nesting. Only executable controls are read from current MNS metadata.
40
+ for (const field of fields) {
41
+ const publicName = Object.entries(parameterAliases[id] ?? {}).find(([, remote]) => remote === field.name)?.[0] ?? field.name;
42
+ if (!canvasControlParameterNames.has(publicName)
43
+ || (id.startsWith("image-layers-") && publicName === "resolution"))
44
+ continue;
45
+ const property = schema.properties[publicName] ?? { type: "string" };
46
+ if (field.options)
47
+ property.enum = field.options.map(option => option.value);
48
+ if (field.minimum !== undefined)
49
+ property.minimum = Math.max(Number(property.minimum ?? -Infinity), field.minimum);
50
+ if (field.maximum !== undefined)
51
+ property.maximum = Math.min(Number(property.maximum ?? Infinity), field.maximum);
52
+ if (field.default !== undefined)
53
+ property.default = field.default;
54
+ if (field.description)
55
+ property.description = field.description;
56
+ schema.properties[publicName] = property;
57
+ if (field.required && !schema.required.includes(publicName))
58
+ schema.required.push(publicName);
59
+ }
60
+ return schema;
61
+ }
62
+ export function schemaParameters(schema, fields) {
63
+ return Object.entries(schema.properties).filter(([name]) => name !== "model").map(([name, property]) => {
64
+ const type = property.format === "uri" ? "uri"
65
+ : property.type === "array" && property.items?.format === "uri" ? "uri[]"
66
+ : property.type ?? "object";
67
+ const raw = fields.find(field => field.name === name
68
+ || (name === "targetLongEdge" && field.name === "resolution")
69
+ || (name === "maxLayers" && field.name === "max_layers"));
70
+ return { name, type, required: schema.required.includes(name),
71
+ ...(property.description ? { description: property.description } : {}),
72
+ ...(property.minimum === undefined ? {} : { minimum: property.minimum }),
73
+ ...(property.maximum === undefined ? {} : { maximum: property.maximum }),
74
+ ...(raw?.step === undefined ? {} : { step: raw.step }),
75
+ ...(property.default === undefined ? {} : { default: property.default }),
76
+ ...(property.enum ? { options: raw?.options ?? property.enum.map(value => ({ value })) } : {}) };
77
+ });
78
+ }
79
+ export function canvasModel(raw, binding, configuration, english = false) {
80
+ const [tool, model, code, , title] = binding;
81
+ const inputSchema = canvasInputSchema(model, raw.parameters);
82
+ const copy = english ? englishCanvasCopy(model, inputSchema) : undefined;
83
+ const result = { ...raw, tool, model, title: copy?.title ?? title,
84
+ usageDescription: copy?.usageDescription ?? {
85
+ "image-edit-standard": "选区白色处理、黑色保护;mask 为与转正原图同尺寸的全不透明二值 PNG。CLI 在服务边界转换蒙版方向,向服务请求保持原图尺寸。",
86
+ "image-edit-smart": "按指令重绘,可能改变细节。可选 mask 在 CLI 内绘为青色边界提示,不能保证选区外像素不变;referenceImages 只提供参考,不作为蒙版。",
87
+ "image-matting-standard": "保留源图可见像素,不能补全遮挡部分;交付真实 alpha PNG,默认保持源图尺寸,可选裁到主体边界。",
88
+ "image-matting-smart": "先按指令重绘,再自动分割为透明 PNG;可补全遮挡,也可能改变主体细节。可选 mask 是视觉边界提示。已包含透明后处理,无需再次标准抠图。",
89
+ "image-remove-standard": "白色选区内消除,黑色保护;mask 是与转正原图同尺寸的不透明二值 PNG,向服务请求保持原图尺寸。",
90
+ "image-remove-smart": "按指令消除内容,单张目标图;可选 mask 是青色边界提示,不作为第二张参考图,也不保证选区外像素不变。",
91
+ "image-enhance-standard": "targetLongEdge 指定请求的最长边像素,按原比例处理;值域与步长来自实时目录。",
92
+ "image-enhance-smart": "生成式清晰修复,可能重新生成纹理、文字或人物细节;需要按用户允许的变化范围验收。",
93
+ "image-expand-standard": "canvas/placement 以自动转正后的原图自然像素计。画布左上角为原点,x向右、y向下;原图不得缩放或超出画布,向服务请求目标画布尺寸。",
94
+ "image-expand-smart": "按自然尺寸和像素坐标放置原图、补绘外围;智能输出采用目标比例,像素尺寸由当前分辨率选项决定,可能改变原图细节。",
95
+ "image-text-edit": "replacements 用完整原文匹配;空 to 表示删除。重复原文无法指定某一次出现;核对其他文字是否保持。",
96
+ "image-ocr": "返回 application/json 内嵌资源,内容为 image{uri,width,height} 和 blocks[{bbox:[left,top,right,bottom],category,text?}];坐标以返回识别图的左上角为原点,单位像素。",
97
+ "image-layers-layout": "输入按比例缩小到3000×3000范围内,不放大小图。返回原生模板 JSON 资源及图层类型数量摘要;文字/图片/矢量的实际可编辑程度以模板图层为准,字体可能替换。不是PSD。通过已发现的 Editor 导入能力使用模板。",
98
+ "image-layers-smart": "输入按比例缩小到3000×3000范围内,不放大小图;处理后总像素不得低于512×512。把图片拆为独立物件图层,返回原生模板 JSON 及图层摘要;maxLayers 是图层数量上限,按当前远端计费组件计价。不是逐字OCR或PSD。",
99
+ "image-vectorize": "返回 SVG 资源;实际矢量内容、形状、颜色和细节重建效果由调用者查看。",
100
+ "video-edit-smart": "从原视频推导时长与比例;原片与全部参考视频的合计时长不超过15秒。audioEnabled 控制输出是否有音轨,不承诺原音轨内容不变。智能处理可能改动画面与声音。",
101
+ "video-enhance-standard": "标准视频超分,从实际输入时长计费(向上取整秒),请求保持原视频。实际时长、画面及原声保持情况由调用者查看。",
102
+ "video-enhance-smart": "生成式视频修复,请求时长取输入最接近整数秒(2–30秒),可能改动画面细节。实际时长、声音内容和同步情况由调用者查看。"
103
+ }[model],
104
+ parameters: schemaParameters(inputSchema, raw.parameters),
105
+ inputSchema: inputSchema,
106
+ execution: { kind: "canvas", code, configuration } };
107
+ result.usageDescription += canvasPricingDescription(result, english);
108
+ return result;
109
+ }
@@ -0,0 +1,81 @@
1
+ /** Only the currently verified SKU-priced component protocol is executable. */
2
+ export function canvasBillingComponents(configuration) {
3
+ const raw = configuration.billingComponents;
4
+ if (raw === undefined || Array.isArray(raw) && raw.length === 0)
5
+ return [];
6
+ if (!Array.isArray(raw))
7
+ return undefined;
8
+ const result = [];
9
+ for (const item of raw) {
10
+ if (!item || typeof item !== "object" || Array.isArray(item))
11
+ return undefined;
12
+ const value = item;
13
+ if (value.price_source !== "SKU" || typeof value.parameter_key !== "string"
14
+ || !["FIXED", "METERED", "DURATION"].includes(String(value.quantity_mode))
15
+ || !Number.isSafeInteger(value.min_quantity) || Number(value.min_quantity) < 0
16
+ || value.max_quantity !== null && (!Number.isSafeInteger(value.max_quantity) || Number(value.max_quantity) < Number(value.min_quantity)))
17
+ return undefined;
18
+ if (value.quantity_mode === "METERED" && !["resolution", "time", "duration", "max_layers"].includes(value.parameter_key)
19
+ || value.quantity_mode === "DURATION" && value.parameter_key !== "video_urls")
20
+ return undefined;
21
+ result.push(value);
22
+ }
23
+ return result;
24
+ }
25
+ /** A missing component is not evidence that a known metered service became a fixed-price service. */
26
+ export function canvasPricingSupported(model, configuration) {
27
+ const components = canvasBillingComponents(configuration);
28
+ if (!components)
29
+ return false;
30
+ const expected = {
31
+ "image-enhance-standard": { resolution: "METERED" },
32
+ "image-layers-smart": { max_layers: "METERED" },
33
+ "video-enhance-standard": { time: "METERED" },
34
+ "video-edit-smart": { duration: "METERED", video_urls: "DURATION" },
35
+ "video-enhance-smart": { duration: "METERED", video_urls: "DURATION" }
36
+ };
37
+ const required = expected[model] ?? {};
38
+ return Object.entries(required).every(([key, mode]) => components.some(component => component.parameter_key === key && component.quantity_mode === mode))
39
+ && components.every(component => component.quantity_mode === "FIXED" || required[component.parameter_key] === component.quantity_mode);
40
+ }
41
+ export function hasCanvasMetering(model) {
42
+ return Boolean(model.execution && canvasBillingComponents(model.execution.configuration)?.some(component => component.quantity_mode !== "FIXED"));
43
+ }
44
+ /** A directory estimate for this input, never a debit receipt. Quantities are already normalized by the media adapter. */
45
+ export function estimateCanvasCost(model, quantities) {
46
+ if (!model.cost || !model.execution)
47
+ return model.cost;
48
+ const components = canvasBillingComponents(model.execution.configuration);
49
+ if (!components)
50
+ return undefined;
51
+ if (components.length === 0)
52
+ return model.cost;
53
+ let total = 0;
54
+ for (const component of components) {
55
+ const quantity = component.quantity_mode === "FIXED" ? 1 : quantities[component.parameter_key];
56
+ if (quantity === undefined || !Number.isSafeInteger(quantity) || quantity < 0)
57
+ return undefined;
58
+ total += component.quantity_mode === "FIXED" ? 1
59
+ : Math.max(0, Math.min(quantity, component.max_quantity ?? quantity) - component.min_quantity);
60
+ }
61
+ const minimum = model.cost.minimum * total, maximum = model.cost.maximum * total;
62
+ if (!Number.isSafeInteger(minimum) || !Number.isSafeInteger(maximum))
63
+ return undefined;
64
+ return { unit: "gaodou", minimum, maximum };
65
+ }
66
+ export function canvasPricingDescription(model, english) {
67
+ if (!hasCanvasMetering(model) || !model.cost || !model.execution)
68
+ return "";
69
+ const names = english
70
+ ? { resolution: "target long edge", time: "rounded-up source seconds", duration: "requested output seconds", video_urls: "rounded total reference-video seconds", max_layers: "requested layer upper bound" }
71
+ : { resolution: "目标长边", time: "向上取整的源视频秒数", duration: "请求的输出秒数", video_urls: "全部输入视频总时长四舍五入秒数", max_layers: "请求图层上限" };
72
+ const formula = canvasBillingComponents(model.execution.configuration).map(component => {
73
+ if (component.quantity_mode === "FIXED")
74
+ return "1";
75
+ const quantity = names[component.parameter_key] ?? component.parameter_key;
76
+ return `max(0, min(${quantity}, ${component.max_quantity ?? "∞"}) - ${component.min_quantity})`;
77
+ }).join(" + ");
78
+ return english
79
+ ? ` SKU unit price range: ${model.cost.minimum}–${model.cost.maximum} points; multiply by (${formula}). The call's usage.cost estimates this input from the catalog; it is not an actual debit.`
80
+ : ` SKU 单价范围 ${model.cost.minimum}–${model.cost.maximum} 稿豆,乘以(${formula})。调用的 usage.cost 按本次输入计算目录预估,不是实际扣款。`;
81
+ }
@@ -0,0 +1,68 @@
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";
4
+ import { queryToolkitResult } from "./canvas-tool-adapter.js";
5
+ import { queryToolResult } from "./tool-api-adapter.js";
6
+ import { createMattingRights } from "./matting-billing.js";
7
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
8
+ /** Read-only recovery. This module deliberately has no uploader or generation port. */
9
+ export async function recoverCanvasTool(progress, context, dependencies) {
10
+ const pipeline = progress.toolPipeline;
11
+ if (!canvasModelBindings.some(binding => binding[1] === pipeline.model))
12
+ throw new RemoteProtocolError();
13
+ const unknown = (content = pipeline.partialContent) => ({ state: "unknown",
14
+ ...(content ? { content } : {}) });
15
+ if (pipeline.stage === "complete" && pipeline.partialContent)
16
+ return { state: "complete", content: pipeline.partialContent };
17
+ if (pipeline.model === "image-matting-standard") {
18
+ if (pipeline.settlement && pipeline.partialContent) {
19
+ const { contentId, refIds } = pipeline.settlement;
20
+ 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
+ // Zero outstanding rights confirms this record is deliverable; it says nothing about the actual debit.
22
+ if (result.used_count === 0)
23
+ return { state: "complete", content: pipeline.partialContent };
24
+ }
25
+ return unknown();
26
+ }
27
+ if (!progress.remoteTaskId || pipeline.protocol === "sync")
28
+ return unknown();
29
+ 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
+ if (response.state === "failed")
33
+ throw response.error;
34
+ if (response.state === "pending")
35
+ return { state: "pending" };
36
+ // A smart matting generation is only intermediate; recovery must not submit its segmentation.
37
+ if (pipeline.requiresFinalization)
38
+ return unknown(response.content);
39
+ const { model, verification } = pipeline;
40
+ let content;
41
+ if (model === "image-ocr") {
42
+ if (!verification?.ocr)
43
+ throw new RemoteProtocolError();
44
+ content = ocrResult(response.content, verification.ocr);
45
+ }
46
+ else if (model.startsWith("image-layers-"))
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
+ else
66
+ content = await imageResult(response.content, dependencies.media, context.signal);
67
+ return { state: "complete", content };
68
+ }