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