@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.
- 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/src/bootstrap/create-runtime.js +50 -23
- package/dist/src/cli/agent-commands.js +1 -0
- package/dist/src/cli/errors.js +3 -3
- package/dist/src/cli/model-commands.js +6 -3
- package/dist/src/cli/tool-commands.js +2 -0
- package/dist/src/contracts/schema.js +4 -1
- package/dist/src/features/agent/creative-protocol.js +22 -5
- package/dist/src/features/agent/resource-authorizer.js +1 -0
- package/dist/src/features/agent/use-cases.js +15 -5
- package/dist/src/features/task/use-cases.js +4 -3
- package/dist/src/features/tool/canvas-copy.js +61 -0
- package/dist/src/features/tool/canvas-media.js +193 -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 +48 -22
- package/dist/src/features/tool/matting-billing.js +103 -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 +13 -4
- package/dist/src/features/tool/use-cases.js +28 -3
- package/dist/src/product/config.js +12 -1
- 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
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { buildModelArgumentsSchema } from "./dynamic-schema.js";
|
|
2
|
+
import { hasCanvasMetering } from "./canvas-pricing.js";
|
|
1
3
|
export const defaultToolDefinitions = [
|
|
2
4
|
{
|
|
3
5
|
name: "image.generate",
|
|
@@ -8,7 +10,18 @@ export const defaultToolDefinitions = [
|
|
|
8
10
|
name: "video.generate",
|
|
9
11
|
title: "视频生成",
|
|
10
12
|
description: "使用已发布的视频模型,根据文本及可选图片、视频或音频生成视频。"
|
|
11
|
-
}
|
|
13
|
+
},
|
|
14
|
+
{ name: "image.edit", title: "图片改图", description: "修改原图内容;标准模型使用选区,智能模型可按指令修改。" },
|
|
15
|
+
{ name: "image.matting", title: "图片抠图", description: "标准抠图保留源像素;智能抠图先重绘补全再分割。最终交付透明 PNG。" },
|
|
16
|
+
{ name: "image.remove", title: "图片消除", description: "移除指定对象并补齐背景。" },
|
|
17
|
+
{ name: "image.enhance", title: "图片变清晰", description: "标准超分或生成式修复;智能修复可能改变细节。" },
|
|
18
|
+
{ name: "image.expand", title: "图片扩图", description: "按目标画布和原图位置补绘外围。" },
|
|
19
|
+
{ name: "image.text_edit", title: "图片改字", description: "按原文替换或删除图片文字,不承诺定位重复原文中的某一次。" },
|
|
20
|
+
{ name: "image.ocr", title: "图片文字识别", description: "返回实际识别图尺寸、文字、类别和像素坐标。" },
|
|
21
|
+
{ name: "image.layers", title: "图片图文分层", description: "交付原生稿定模板 JSON,保留图层结构。" },
|
|
22
|
+
{ name: "image.vectorize", title: "图片转矢量", description: "将位图转换为 SVG。" },
|
|
23
|
+
{ name: "video.edit", title: "视频修改", description: "按原视频修改内容,时长由真实素材推导。" },
|
|
24
|
+
{ name: "video.enhance", title: "视频变清晰", description: "标准超分或生成式视频修复。" }
|
|
12
25
|
];
|
|
13
26
|
export class ToolInputError extends Error {
|
|
14
27
|
reason;
|
|
@@ -37,7 +50,7 @@ function summary(model) {
|
|
|
37
50
|
model: model.model,
|
|
38
51
|
title: model.title,
|
|
39
52
|
...(model.description === undefined ? {} : { description: model.description }),
|
|
40
|
-
...(model.cost === undefined ? {} : { cost: model.cost }),
|
|
53
|
+
...(model.cost === undefined || hasCanvasMetering(model) ? {} : { cost: model.cost }),
|
|
41
54
|
...(model.estimatedTime === undefined ? {} : { estimatedTime: model.estimatedTime })
|
|
42
55
|
};
|
|
43
56
|
}
|
|
@@ -57,14 +70,21 @@ export function projectModelList(catalog, tool, tools = defaultToolDefinitions)
|
|
|
57
70
|
.map(summary)
|
|
58
71
|
};
|
|
59
72
|
}
|
|
60
|
-
export function findModel(catalog, model) {
|
|
61
|
-
const
|
|
62
|
-
if (
|
|
63
|
-
|
|
64
|
-
|
|
73
|
+
export function findModel(catalog, model, tool) {
|
|
74
|
+
const matches = catalog.models.filter(candidate => candidate.model === model);
|
|
75
|
+
if (tool !== undefined)
|
|
76
|
+
return findToolModel(catalog, tool, model);
|
|
77
|
+
const legacy = matches.find(candidate => candidate.tool === "image.generate" || candidate.tool === "video.generate");
|
|
78
|
+
if (legacy)
|
|
79
|
+
return legacy;
|
|
80
|
+
if (matches.length === 1)
|
|
81
|
+
return matches[0];
|
|
82
|
+
if (matches.length > 1)
|
|
83
|
+
throw new ToolInputError("model_tool_required", "/tool");
|
|
84
|
+
throw new ToolInputError("model_not_found", "/model");
|
|
65
85
|
}
|
|
66
|
-
export function projectModelDetail(catalog, model) {
|
|
67
|
-
const found = findModel(catalog, model);
|
|
86
|
+
export function projectModelDetail(catalog, model, tool) {
|
|
87
|
+
const found = findModel(catalog, model, tool);
|
|
68
88
|
return {
|
|
69
89
|
...summary(found),
|
|
70
90
|
...(found.usageDescription === undefined
|
|
@@ -73,12 +93,14 @@ export function projectModelDetail(catalog, model) {
|
|
|
73
93
|
...(found.outputMediaTypes === undefined
|
|
74
94
|
? {}
|
|
75
95
|
: { outputMediaTypes: found.outputMediaTypes }),
|
|
76
|
-
parameters: found.parameters
|
|
96
|
+
parameters: found.parameters,
|
|
97
|
+
inputSchema: { ...buildModelArgumentsSchema(found) }
|
|
77
98
|
};
|
|
78
99
|
}
|
|
79
100
|
export function findToolModel(catalog, tool, model) {
|
|
80
|
-
const found =
|
|
81
|
-
if (found
|
|
82
|
-
throw new ToolInputError(
|
|
101
|
+
const found = catalog.models.find(candidate => candidate.model === model && candidate.tool === tool);
|
|
102
|
+
if (!found)
|
|
103
|
+
throw new ToolInputError(catalog.models.some(candidate => candidate.model === model)
|
|
104
|
+
? "model_tool_mismatch" : "model_not_found", "/model");
|
|
83
105
|
return found;
|
|
84
106
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
2
2
|
import addFormatsImport, {} from "ajv-formats";
|
|
3
|
+
import { canvasControlParameterNames } from "./canvas-models.js";
|
|
3
4
|
import { validationIssues } from "../../platform/schema-issues.js";
|
|
4
5
|
import { ToolInputError } from "./catalog.js";
|
|
5
6
|
function parameterSchema(parameter, includeBounds = false) {
|
|
@@ -12,9 +13,9 @@ function parameterSchema(parameter, includeBounds = false) {
|
|
|
12
13
|
if (parameter.type === "uri[]") {
|
|
13
14
|
return { type: "array", items: { type: "string", format: "uri" }, ...common };
|
|
14
15
|
}
|
|
15
|
-
if (parameter.type === "number") {
|
|
16
|
+
if (parameter.type === "number" || parameter.type === "integer") {
|
|
16
17
|
return {
|
|
17
|
-
type:
|
|
18
|
+
type: parameter.type,
|
|
18
19
|
...(includeBounds && parameter.minimum !== undefined
|
|
19
20
|
? { minimum: parameter.minimum }
|
|
20
21
|
: {}),
|
|
@@ -24,6 +25,9 @@ function parameterSchema(parameter, includeBounds = false) {
|
|
|
24
25
|
...common
|
|
25
26
|
};
|
|
26
27
|
}
|
|
28
|
+
if (["boolean", "object", "array"].includes(parameter.type)) {
|
|
29
|
+
return { type: parameter.type, ...common };
|
|
30
|
+
}
|
|
27
31
|
return {
|
|
28
32
|
type: "string",
|
|
29
33
|
...(parameter.options === undefined
|
|
@@ -33,6 +37,9 @@ function parameterSchema(parameter, includeBounds = false) {
|
|
|
33
37
|
};
|
|
34
38
|
}
|
|
35
39
|
function sameShape(left, right) {
|
|
40
|
+
if (left.type === "object" || left.type === "array" || right.type === "object" || right.type === "array") {
|
|
41
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
42
|
+
}
|
|
36
43
|
return left.type === right.type
|
|
37
44
|
&& left.format === right.format
|
|
38
45
|
&& left.items?.format === right.items?.format;
|
|
@@ -68,10 +75,13 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
|
|
|
68
75
|
}
|
|
69
76
|
};
|
|
70
77
|
for (const model of models) {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
78
|
+
const selected = model.inputSchema ? buildModelArgumentsSchema(model).properties
|
|
79
|
+
: Object.fromEntries(model.parameters.map(parameter => [parameter.name, parameterSchema(parameter)]));
|
|
80
|
+
for (const [name, next] of Object.entries(selected)) {
|
|
81
|
+
if (name === "model")
|
|
82
|
+
continue;
|
|
83
|
+
const current = properties[name];
|
|
84
|
+
properties[name] = current === undefined ? next : mergeSchema(current, next);
|
|
75
85
|
}
|
|
76
86
|
}
|
|
77
87
|
return {
|
|
@@ -84,6 +94,8 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
|
|
|
84
94
|
};
|
|
85
95
|
}
|
|
86
96
|
export function buildModelArgumentsSchema(model) {
|
|
97
|
+
if (model.inputSchema)
|
|
98
|
+
return structuredClone(model.inputSchema);
|
|
87
99
|
const properties = {
|
|
88
100
|
model: {
|
|
89
101
|
type: "string",
|
|
@@ -117,9 +129,10 @@ function controlArgumentsValidator(model) {
|
|
|
117
129
|
for (const parameter of model.parameters) {
|
|
118
130
|
if (parameter.name === "prompt"
|
|
119
131
|
|| parameter.type === "uri"
|
|
120
|
-
|| parameter.type === "uri[]"
|
|
132
|
+
|| parameter.type === "uri[]"
|
|
133
|
+
|| (model.execution?.kind === "canvas" && !canvasControlParameterNames.has(parameter.name)))
|
|
121
134
|
continue;
|
|
122
|
-
properties[parameter.name] =
|
|
135
|
+
properties[parameter.name] = buildModelArgumentsSchema(model).properties[parameter.name];
|
|
123
136
|
}
|
|
124
137
|
return ajv.compile({
|
|
125
138
|
type: "object",
|
|
@@ -132,30 +145,43 @@ export function assertModelArguments(model, value) {
|
|
|
132
145
|
const validate = validator(model);
|
|
133
146
|
if (!validate(value))
|
|
134
147
|
throw new ToolInputError("model_parameters", "/arguments", validationIssues(validate.errors));
|
|
135
|
-
|
|
136
|
-
|
|
148
|
+
const stepIssues = sliderStepIssues(model, value);
|
|
149
|
+
if (stepIssues.length) {
|
|
150
|
+
throw new ToolInputError("model_parameters", "/arguments", stepIssues);
|
|
137
151
|
}
|
|
138
152
|
}
|
|
139
|
-
function
|
|
140
|
-
|
|
153
|
+
function sliderStepIssues(model, value) {
|
|
154
|
+
const issues = [];
|
|
155
|
+
for (const parameter of model.parameters) {
|
|
141
156
|
if (parameter.step === undefined || !Object.hasOwn(value, parameter.name))
|
|
142
|
-
|
|
157
|
+
continue;
|
|
143
158
|
const candidate = value[parameter.name];
|
|
144
159
|
const minimum = parameter.minimum;
|
|
145
|
-
|
|
146
|
-
|
|
160
|
+
let valid = false;
|
|
161
|
+
if (typeof candidate === "number" && minimum !== undefined && parameter.step > 0) {
|
|
162
|
+
const steps = (candidate - minimum) / parameter.step;
|
|
163
|
+
const nearestStep = Math.round(steps);
|
|
164
|
+
const expected = minimum + nearestStep * parameter.step;
|
|
165
|
+
const tolerance = Number.EPSILON * Math.max(1, Math.abs(candidate), Math.abs(expected), Math.abs(minimum), Math.abs(nearestStep * parameter.step)) * 2;
|
|
166
|
+
valid = Math.abs(candidate - expected) <= tolerance;
|
|
147
167
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
168
|
+
if (!valid)
|
|
169
|
+
issues.push({
|
|
170
|
+
field: `/${parameter.name.replace(/~/gu, "~0").replace(/\//gu, "~1")}`.slice(0, 256),
|
|
171
|
+
rule: "step",
|
|
172
|
+
message: minimum === undefined || parameter.step <= 0
|
|
173
|
+
? "must match the model's slider configuration"
|
|
174
|
+
: `must be ${minimum} plus a whole number of steps of ${parameter.step}`
|
|
175
|
+
});
|
|
176
|
+
if (issues.length === 8)
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
return issues;
|
|
154
180
|
}
|
|
155
181
|
export function modelControlArgumentsAreValid(model, value) {
|
|
156
182
|
return typeof value === "object"
|
|
157
183
|
&& value !== null
|
|
158
184
|
&& !Array.isArray(value)
|
|
159
185
|
&& controlArgumentsValidator(model)(value)
|
|
160
|
-
&&
|
|
186
|
+
&& sliderStepIssues(model, value).length === 0;
|
|
161
187
|
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { constants, createPublicKey, publicEncrypt, randomBytes, verify } from "node:crypto";
|
|
2
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
3
|
+
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
4
|
+
import { record } from "./canvas-results.js";
|
|
5
|
+
import { ToolTaskFailedError, ToolInsufficientCreditsError } from "./tool-api-adapter.js";
|
|
6
|
+
// Public verification/encryption key used by the existing matting rights service.
|
|
7
|
+
const serviceKey = `-----BEGIN RSA PUBLIC KEY-----
|
|
8
|
+
MIGJAoGBANVv3G1++sfQjoTLN6pOU0ooMzAdRf3W1SItK1MJbXcg6tdBRTfvraso
|
|
9
|
+
4MBNJ6TDOKB2ffO7MtaFHHCo2mxS7/WQF1IJbojXzXt35pja+SsMnuI+050Piwwy
|
|
10
|
+
O/YHzh9Idr3qaXCzOnkfs6JNOKT50pp4xs3b0U5ZXytg4eRTQ1eXAgMBAAE=
|
|
11
|
+
-----END RSA PUBLIC KEY-----`;
|
|
12
|
+
/** NodeRSA's OAEP/SHA-1 chunking, retained at the service boundary. */
|
|
13
|
+
export function encryptMattingParameters(text, key = serviceKey) {
|
|
14
|
+
const publicKey = createPublicKey(key);
|
|
15
|
+
const keyBytes = Math.ceil(publicKey.asymmetricKeyDetails.modulusLength / 8);
|
|
16
|
+
const data = Buffer.from(text);
|
|
17
|
+
const blocks = Math.ceil(data.length / (keyBytes - 42));
|
|
18
|
+
const blockSize = Math.ceil(data.length / blocks);
|
|
19
|
+
const encrypted = [];
|
|
20
|
+
for (let offset = 0; offset < data.length; offset += blockSize) {
|
|
21
|
+
encrypted.push(publicEncrypt({ key: publicKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha1" }, data.subarray(offset, offset + blockSize)));
|
|
22
|
+
}
|
|
23
|
+
return Buffer.concat(encrypted).toString("base64");
|
|
24
|
+
}
|
|
25
|
+
export function createMattingRights(dependencies) {
|
|
26
|
+
const { transport } = dependencies;
|
|
27
|
+
return async function rights(path, parameters, context) {
|
|
28
|
+
const code = `0.${randomBytes(12).readBigUInt64BE().toString()}`;
|
|
29
|
+
const plaintext = `gaoding?key=${randomBytes(18).toString("base64url")}×tamp=${Date.now()}&verify_code=${code}&${parameters}`;
|
|
30
|
+
const result = await transport.postJson({ path, body: { data: encryptMattingParameters(plaintext, dependencies.key ?? serviceKey) },
|
|
31
|
+
...context.access, signal: context.signal });
|
|
32
|
+
if (!record(result))
|
|
33
|
+
throw new RemoteProtocolError();
|
|
34
|
+
if (result.code !== undefined && result.code !== 0 && result.code !== "0")
|
|
35
|
+
throw new ToolTaskFailedError(remoteErrorEvidence(result));
|
|
36
|
+
if (typeof result.export_permit !== "string" || !verify("RSA-SHA256", Buffer.from(code), dependencies.key ?? serviceKey, Buffer.from(result.export_permit, "base64"))
|
|
37
|
+
|| typeof result.used_count !== "number" || !Number.isFinite(result.used_count) || result.used_count < 0) {
|
|
38
|
+
throw new RemoteProtocolError({}, undefined, "MATTING_BILLING_VERIFICATION_FAILED");
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export function createStandardMatting(dependencies) {
|
|
44
|
+
const { transport, media, recordTransport } = dependencies;
|
|
45
|
+
const rights = createMattingRights(dependencies);
|
|
46
|
+
return async (source, context, useCount, compute) => {
|
|
47
|
+
const precheck = () => rights("/open/editor/mattings/billing/precheck/v2", `use_count=${useCount}&image_quality=standard`, context);
|
|
48
|
+
const quote = await precheck();
|
|
49
|
+
if (quote.need_deduct !== undefined && typeof quote.need_deduct !== "boolean")
|
|
50
|
+
throw new RemoteProtocolError();
|
|
51
|
+
if (quote.need_deduct === true || quote.need_deduct === undefined && Number(quote.used_count) > 0) {
|
|
52
|
+
const balances = await transport.getJson({ path: "/trade/rights-overview", query: { goods_type_enums: "GAODOU" }, ...context.access, signal: context.signal });
|
|
53
|
+
if (!Array.isArray(balances))
|
|
54
|
+
throw new RemoteProtocolError();
|
|
55
|
+
const item = balances.find(item => record(item) && item.goods_type_enum === "GAODOU" && item.identifier === "GAODOU");
|
|
56
|
+
if (!record(item))
|
|
57
|
+
throw new RemoteProtocolError();
|
|
58
|
+
const value = (raw) => { if ((typeof raw !== "number" && typeof raw !== "string") || raw === "" || !Number.isFinite(Number(raw)))
|
|
59
|
+
throw new RemoteProtocolError(); return Number(raw); };
|
|
60
|
+
let available = value(item.total) - value(item.used) - value(item.wait);
|
|
61
|
+
if (item.member_period_limit !== undefined && item.member_period_limit !== null)
|
|
62
|
+
available = Math.min(available, value(item.member_period_limit) - value(item.member_period_used ?? 0));
|
|
63
|
+
if (available < Number(quote.used_count))
|
|
64
|
+
throw new ToolInsufficientCreditsError();
|
|
65
|
+
}
|
|
66
|
+
const repositories = await recordTransport.getJson({ path: "/tb-dam/repositories", ...context.access, signal: context.signal });
|
|
67
|
+
if (!Array.isArray(repositories))
|
|
68
|
+
throw new RemoteProtocolError();
|
|
69
|
+
const draft = repositories.find(item => record(item) && item.type === 6);
|
|
70
|
+
if (!record(draft) || typeof draft.repository_id !== "string")
|
|
71
|
+
throw new RemoteProtocolError({}, undefined, "MATTING_DRAFT_REPOSITORY_MISSING");
|
|
72
|
+
const computation = await compute();
|
|
73
|
+
await context.observe?.({ toolPipeline: { protocol: "sync", model: "image-matting-standard", stage: "recording", requiresFinalization: true, partialContent: computation.content } });
|
|
74
|
+
const inputUri = await media.upload(source.bytes, "png", context.access, context.signal);
|
|
75
|
+
const base = { title: "CLI 抠图", description: "CLI 标准抠图", type: "matting", preview_lock: 0, dpi: 72, remark: "", content: "",
|
|
76
|
+
preview: { source_preview: { url: inputUri, width: source.width, height: source.height } }, pri_classify: "MATERIAL", content_format: "gdmatting",
|
|
77
|
+
url: inputUri, repository_id: draft.repository_id, is_hide: true, un_record_recent: true };
|
|
78
|
+
const postRecord = async (body) => {
|
|
79
|
+
const result = await recordTransport.postJson({ path: "/tb-dam/editors/template", body, ...context.access, signal: context.signal });
|
|
80
|
+
if (!record(result) || typeof result.id !== "string" || !result.id)
|
|
81
|
+
throw new RemoteProtocolError({}, undefined, "MATTING_RECORD_INVALID");
|
|
82
|
+
return result.id;
|
|
83
|
+
};
|
|
84
|
+
const refId = await postRecord({ ...base, type: "image" });
|
|
85
|
+
const { width, height } = source;
|
|
86
|
+
const template = { version: "2.16.5", type: "matting", global: { source: "koutu", unit: "px", dpi: 72, showWatermark: false },
|
|
87
|
+
layouts: [{ elements: [{ type: "image", metaInfo: { thirdParty: { matting: { id: refId, refId } } } }] }],
|
|
88
|
+
refs: { [refId]: { id: refId, sourceImage: inputUri, imageHeight: height, imageWidth: width, featheringRadius: 2, lines: [], hairLines: [],
|
|
89
|
+
hairDropColors: [], hairKeepColors: [], pen: [], backgroundColor: null, recoArea: [], recoLines: [], scene: computation.scene,
|
|
90
|
+
crop: { scale: 1, top: 0, left: 0, width, height }, shadow: { offsetX: 0, offsetY: 0, blur: 0, color: "rgba(0,0,0,0)" },
|
|
91
|
+
background: { color: null, image: null, position: ["center", "center"], size: "cover", repeat: "no-repeat" }, outline: [],
|
|
92
|
+
filter: { url: "", strong: 1, name: "", id: 0 }, filename: "CLI 抠图", transform: { rotate: 0 } } } };
|
|
93
|
+
const contentId = await postRecord({ ...base, width, height, origin_url: new URL(inputUri).origin + new URL(inputUri).pathname, content: JSON.stringify(template) });
|
|
94
|
+
const settlement = { contentId, refIds: [refId] };
|
|
95
|
+
await context.observe?.({ toolPipeline: { protocol: "sync", model: "image-matting-standard", stage: "settling", requiresFinalization: true,
|
|
96
|
+
partialContent: computation.content, settlement } });
|
|
97
|
+
await precheck();
|
|
98
|
+
// Never retry this write: an uncertain response must be reconciled through the original record.
|
|
99
|
+
await rights("/open/editor/mattings/complete/v2", `content_id=${contentId}&ref_ids=${refId}&image_quality=standard`, context);
|
|
100
|
+
// The adapter records the validated final result; late cache errors must not discard it.
|
|
101
|
+
return computation.content;
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
2
|
+
import { defaultToolDefinitions } from "./catalog.js";
|
|
3
|
+
import { canvasModel, canvasModelBindings, canvasSceneCodes } from "./canvas-models.js";
|
|
4
|
+
import { canvasPricingSupported } from "./canvas-pricing.js";
|
|
2
5
|
export const ROOT_SCENE_CODES = [
|
|
3
6
|
"image-model-art",
|
|
4
7
|
"AI-video-generation"
|
|
5
8
|
];
|
|
9
|
+
export const CATALOG_SCENE_CODES = [...ROOT_SCENE_CODES, ...canvasSceneCodes];
|
|
6
10
|
const rootTools = {
|
|
7
11
|
"image-model-art": "image.generate",
|
|
8
12
|
"AI-video-generation": "video.generate"
|
|
9
13
|
};
|
|
10
|
-
const toolOrder =
|
|
11
|
-
"image.generate": 0,
|
|
12
|
-
"video.generate": 1
|
|
13
|
-
};
|
|
14
|
+
const toolOrder = Object.fromEntries(defaultToolDefinitions.map((tool, index) => [tool.name, index]));
|
|
14
15
|
const multiUriKeys = new Set([
|
|
15
16
|
"image_urls",
|
|
16
17
|
"reference_images",
|
|
@@ -61,8 +62,19 @@ function collectScenes(raw) {
|
|
|
61
62
|
scenes.push({ code: rootCode, tool: rootTools[rootCode], sort: number(root.sort) });
|
|
62
63
|
}
|
|
63
64
|
}
|
|
64
|
-
|
|
65
|
-
|
|
65
|
+
for (const rootCode of canvasSceneCodes) {
|
|
66
|
+
const root = roots.get(rootCode);
|
|
67
|
+
if (!root)
|
|
68
|
+
continue;
|
|
69
|
+
const binding = canvasModelBindings.find(binding => binding[3] === rootCode);
|
|
70
|
+
scenes.push({ code: rootCode, tool: binding[0], sort: number(root.sort) });
|
|
71
|
+
// Canvas pickers include first-level children; generic generation keeps its existing root membership.
|
|
72
|
+
for (const child of roots.values()) {
|
|
73
|
+
if (child.parent_id === root.id && child !== root) {
|
|
74
|
+
scenes.push({ code: requiredText(child.code), tool: binding[0], sort: number(child.sort) });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
66
78
|
return scenes;
|
|
67
79
|
}
|
|
68
80
|
function parameter(value) {
|
|
@@ -144,7 +156,7 @@ function range(values, unit) {
|
|
|
144
156
|
const bounds = { minimum: Math.min(...values), maximum: Math.max(...values) };
|
|
145
157
|
return unit === "gaodou" ? { unit, ...bounds } : { unit, ...bounds };
|
|
146
158
|
}
|
|
147
|
-
function normalizeModel(value, scenes) {
|
|
159
|
+
function normalizeModel(value, scenes, english = false) {
|
|
148
160
|
const item = record(value);
|
|
149
161
|
const model = record(item?.model);
|
|
150
162
|
if (item === undefined || model === undefined || !Array.isArray(item.skus)) {
|
|
@@ -152,7 +164,7 @@ function normalizeModel(value, scenes) {
|
|
|
152
164
|
}
|
|
153
165
|
const activeSkus = item.skus.map(record).filter((sku) => sku !== undefined && sku.status === 1);
|
|
154
166
|
if (activeSkus.length === 0)
|
|
155
|
-
return
|
|
167
|
+
return [];
|
|
156
168
|
const code = requiredText(model.code);
|
|
157
169
|
const title = requiredText(model.name);
|
|
158
170
|
if (!Array.isArray(model.scene_categories))
|
|
@@ -164,7 +176,7 @@ function normalizeModel(value, scenes) {
|
|
|
164
176
|
|| left.sort - right.sort);
|
|
165
177
|
const scene = matches[0];
|
|
166
178
|
if (scene === undefined)
|
|
167
|
-
return
|
|
179
|
+
return [];
|
|
168
180
|
if (typeof model.input_field_settings !== "string")
|
|
169
181
|
throw new Error("missing settings");
|
|
170
182
|
const settings = JSON.parse(model.input_field_settings);
|
|
@@ -175,9 +187,10 @@ function normalizeModel(value, scenes) {
|
|
|
175
187
|
.filter((item) => item !== undefined);
|
|
176
188
|
const description = cleanText(model.description);
|
|
177
189
|
const usageDescription = cleanText(model.tool_description);
|
|
178
|
-
const
|
|
179
|
-
? model.output_mime_types
|
|
180
|
-
|
|
190
|
+
const mimeTypes = typeof model.output_mime_types === "string"
|
|
191
|
+
? JSON.parse(model.output_mime_types) : model.output_mime_types;
|
|
192
|
+
const outputMediaTypes = Array.isArray(mimeTypes)
|
|
193
|
+
? mimeTypes.map(text).filter((item) => item !== undefined) : [];
|
|
181
194
|
const costs = activeSkus
|
|
182
195
|
.map((sku) => sku.point_cost)
|
|
183
196
|
.filter((value) => typeof value === "number"
|
|
@@ -188,7 +201,7 @@ function normalizeModel(value, scenes) {
|
|
|
188
201
|
&& Number.isFinite(value) && value >= 0);
|
|
189
202
|
const cost = range(costs, "gaodou");
|
|
190
203
|
const estimatedTime = range(times, "second");
|
|
191
|
-
|
|
204
|
+
const normalized = {
|
|
192
205
|
tool: scene.tool,
|
|
193
206
|
model: code,
|
|
194
207
|
title,
|
|
@@ -201,6 +214,36 @@ function normalizeModel(value, scenes) {
|
|
|
201
214
|
sceneSort: scene.sort,
|
|
202
215
|
modelSort: number(model.sort)
|
|
203
216
|
};
|
|
217
|
+
const result = [];
|
|
218
|
+
for (const match of matches) {
|
|
219
|
+
if (ROOT_SCENE_CODES.some(root => root === match.code)) {
|
|
220
|
+
result.push({ ...normalized, tool: match.tool, sceneSort: match.sort });
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const binding = canvasModelBindings.find(binding => binding[2] === code
|
|
224
|
+
&& (binding[3] === match.code || binding[0] === match.tool));
|
|
225
|
+
if (!binding)
|
|
226
|
+
continue; // A category association is insufficient to execute an unknown protocol.
|
|
227
|
+
if (!cost)
|
|
228
|
+
throw new Error("canvas pricing unavailable");
|
|
229
|
+
if (!canvasPricingSupported(binding[1], { billingComponents: item.billing_components }))
|
|
230
|
+
throw new Error("canvas component pricing unsupported");
|
|
231
|
+
if (binding[1] === "image-layers-smart") {
|
|
232
|
+
const components = Array.isArray(item.billing_components) ? item.billing_components.map(record) : [];
|
|
233
|
+
if (settings.some(value => record(value)?.key === "max_layers" && record(value)?.sku_enable === true)
|
|
234
|
+
|| !components.some(component => component?.parameter_key === "max_layers"
|
|
235
|
+
&& component.quantity_mode === "METERED" && component.price_source === "SKU"
|
|
236
|
+
&& (component.min_quantity === undefined || component.min_quantity === null || component.min_quantity === 0)
|
|
237
|
+
&& (component.max_quantity === undefined || component.max_quantity === null || Number(component.max_quantity) >= 17))) {
|
|
238
|
+
throw new Error("layer metered pricing unavailable");
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
result.push(canvasModel({ ...normalized, sceneSort: match.sort }, binding, {
|
|
242
|
+
fields: settings,
|
|
243
|
+
...(item.billing_components === undefined ? {} : { billingComponents: item.billing_components })
|
|
244
|
+
}, english));
|
|
245
|
+
}
|
|
246
|
+
return result;
|
|
204
247
|
}
|
|
205
248
|
export function createMnsCatalogAdapter(dependencies) {
|
|
206
249
|
return {
|
|
@@ -209,7 +252,7 @@ export function createMnsCatalogAdapter(dependencies) {
|
|
|
209
252
|
try {
|
|
210
253
|
const rawScenes = await dependencies.transport.getJson({
|
|
211
254
|
path: "/mns/scene-categories",
|
|
212
|
-
query: { codes:
|
|
255
|
+
query: { codes: CATALOG_SCENE_CODES.join(",") },
|
|
213
256
|
credential: access.credential,
|
|
214
257
|
organizationId: access.organizationId,
|
|
215
258
|
signal
|
|
@@ -217,6 +260,8 @@ export function createMnsCatalogAdapter(dependencies) {
|
|
|
217
260
|
if (!Array.isArray(rawScenes))
|
|
218
261
|
throw new Error("invalid scene response");
|
|
219
262
|
const scenes = collectScenes(rawScenes);
|
|
263
|
+
if (scenes.length === 0)
|
|
264
|
+
return { models: [], warnings: [] };
|
|
220
265
|
const rawModels = await dependencies.transport.getJson({
|
|
221
266
|
path: "/mns/models",
|
|
222
267
|
query: { codes: scenes.map((scene) => scene.code).join(",") },
|
|
@@ -232,11 +277,13 @@ export function createMnsCatalogAdapter(dependencies) {
|
|
|
232
277
|
let invalidCount = 0;
|
|
233
278
|
for (const rawModel of rawModels) {
|
|
234
279
|
try {
|
|
235
|
-
const model
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
280
|
+
for (const model of normalizeModel(rawModel, sceneMap, dependencies.english)) {
|
|
281
|
+
const key = `${model.tool}\0${model.model}`;
|
|
282
|
+
if (seen.has(key))
|
|
283
|
+
continue;
|
|
284
|
+
seen.add(key);
|
|
285
|
+
models.push(model);
|
|
286
|
+
}
|
|
240
287
|
}
|
|
241
288
|
catch {
|
|
242
289
|
invalidCount += 1;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readOcrPayload } from "./canvas-results.js";
|
|
2
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
3
|
+
/** Reauthorize both top-level media and the OCR image reference, without interpreting arbitrary text as URLs. */
|
|
4
|
+
export async function authorizeToolResources(output, authorizer, access, signal) {
|
|
5
|
+
const references = [];
|
|
6
|
+
for (const [index, part] of output.content.entries()) {
|
|
7
|
+
if (part.type === "resource_link")
|
|
8
|
+
references.push({ index, uri: part.uri, mediaType: part.mimeType ?? "application/octet-stream" });
|
|
9
|
+
else if (output.usage.model === "image-ocr" && part.type === "resource") {
|
|
10
|
+
const ocr = readOcrPayload(part.resource.text);
|
|
11
|
+
references.push({ index, uri: ocr.image.uri, mediaType: "image/jpeg", ocr });
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
if (!references.length)
|
|
15
|
+
return output;
|
|
16
|
+
const parts = references.map(reference => ({ url: reference.uri, mediaType: reference.mediaType }));
|
|
17
|
+
const authorized = await authorizer.authorize({
|
|
18
|
+
message: { contextId: "resource-authorization", parts: [parts[0], ...parts.slice(1)] },
|
|
19
|
+
usage: { cost: { unit: "gaodou", amount: 0 }, items: [] }
|
|
20
|
+
}, access, signal);
|
|
21
|
+
const content = [...output.content];
|
|
22
|
+
for (const [index, reference] of references.entries()) {
|
|
23
|
+
const part = content[reference.index];
|
|
24
|
+
const authorizedPart = authorized.message.parts[index];
|
|
25
|
+
if (!authorizedPart || !("url" in authorizedPart))
|
|
26
|
+
throw new RemoteProtocolError();
|
|
27
|
+
if (part.type === "resource_link")
|
|
28
|
+
content[reference.index] = { ...part, uri: authorizedPart.url };
|
|
29
|
+
else if (part.type === "resource" && reference.ocr)
|
|
30
|
+
content[reference.index] = { ...part, resource: { ...part.resource,
|
|
31
|
+
text: JSON.stringify({ ...reference.ocr, image: { ...reference.ocr.image, uri: authorizedPart.url } }) } };
|
|
32
|
+
}
|
|
33
|
+
return { ...output, content };
|
|
34
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { canvasModel, canvasModelBindings } from "./canvas-models.js";
|
|
2
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
3
|
+
import { record } from "./canvas-results.js";
|
|
4
|
+
const bindingForCode = (code) => canvasModelBindings.find(binding => binding[2] === code)[1];
|
|
5
|
+
/** Legacy scenes have fixed protocols, unlike the MNS model pickers. Availability is read separately. */
|
|
6
|
+
export function createSceneCatalogAdapter(dependencies) {
|
|
7
|
+
return { async load(input) {
|
|
8
|
+
const catalog = await dependencies.catalog.load(input);
|
|
9
|
+
for (const code of ["TextEdit", "new-image-ocr"]) {
|
|
10
|
+
try {
|
|
11
|
+
const scene = await dependencies.transport.getJson({ path: `/gdesign/tool/manage/scenes/code/${code}`, ...input.access, signal: input.signal });
|
|
12
|
+
if (!record(scene) || scene.scene_code !== code || scene.status !== 1)
|
|
13
|
+
continue;
|
|
14
|
+
const binding = canvasModelBindings.find(binding => binding[2] === code);
|
|
15
|
+
const cost = scene.is_free === true ? 0 : typeof scene.point_rights === "number" && Number.isFinite(scene.point_rights) && scene.point_rights >= 0 ? scene.point_rights : undefined;
|
|
16
|
+
if (cost === undefined) {
|
|
17
|
+
catalog.warnings.push(dependencies.english ? `Current pricing is unavailable for ${binding[1]}.` : `${binding[1]} 的当前报价不可用。`);
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
const raw = { tool: binding[0], model: code, title: binding[4], sceneSort: 0, modelSort: 0, parameters: [],
|
|
21
|
+
...(cost === undefined ? {} : { cost: { unit: "gaodou", minimum: cost, maximum: cost } }),
|
|
22
|
+
outputMediaTypes: code === "new-image-ocr" ? ["application/json"] : ["image/jpeg", "image/png"] };
|
|
23
|
+
catalog.models.push(canvasModel(raw, binding, {}, dependencies.english));
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
input.signal.throwIfAborted();
|
|
27
|
+
if (error instanceof RemoteRequestError && error.status === 404)
|
|
28
|
+
continue;
|
|
29
|
+
// Do not misreport a network failure as a published offline state.
|
|
30
|
+
catalog.warnings.push(dependencies.english ? `Unable to verify the current availability of ${bindingForCode(code)}.` : `暂时无法核实 ${bindingForCode(code)} 的当前可用性。`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return catalog;
|
|
34
|
+
} };
|
|
35
|
+
}
|
|
@@ -97,7 +97,7 @@ function resourceName(uri) {
|
|
|
97
97
|
return protocolFailure(uri);
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
|
-
function
|
|
100
|
+
export function normalizeToolContent(value) {
|
|
101
101
|
if (!isRecord(value))
|
|
102
102
|
return protocolFailure(value);
|
|
103
103
|
if (value.type === "text") {
|
|
@@ -138,6 +138,13 @@ export class ToolTaskFailedError extends Error {
|
|
|
138
138
|
this.diagnosticReason = evidence.diagnosticReason;
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
|
+
export class ToolInsufficientCreditsError extends ToolTaskFailedError {
|
|
142
|
+
diagnosticReason = "INSUFFICIENT_CREDITS";
|
|
143
|
+
constructor() {
|
|
144
|
+
super();
|
|
145
|
+
this.name = "ToolInsufficientCreditsError";
|
|
146
|
+
}
|
|
147
|
+
}
|
|
141
148
|
export class ToolTaskCanceledError extends Error {
|
|
142
149
|
diagnosticReason = "TASK_CANCELED";
|
|
143
150
|
constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
|
|
@@ -150,7 +157,7 @@ export async function queryToolResult(transport, request) {
|
|
|
150
157
|
signal: request.signal,
|
|
151
158
|
path: "/gdesign/tool/v1/dify/process/batch",
|
|
152
159
|
body: { task_ids: [request.taskId] }
|
|
153
|
-
}), request.taskId, request.onDifyTaskId);
|
|
160
|
+
}), request.taskId, request.onDifyTaskId, request.normalize);
|
|
154
161
|
}
|
|
155
162
|
catch (error) {
|
|
156
163
|
if (isInterruption(error, request.signal) || error instanceof ToolTaskCanceledError)
|
|
@@ -189,7 +196,7 @@ function isJsonRpcError(value) {
|
|
|
189
196
|
&& typeof value.error.message === "string"
|
|
190
197
|
&& value.error.message.trim() !== "";
|
|
191
198
|
}
|
|
192
|
-
function pollResult(value, taskId, onDifyTaskId) {
|
|
199
|
+
function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolContent) {
|
|
193
200
|
if (!Array.isArray(value))
|
|
194
201
|
return protocolFailure(value);
|
|
195
202
|
const item = value.find((candidate) => isRecord(candidate) && candidate.task_id === taskId);
|
|
@@ -257,7 +264,7 @@ function pollResult(value, taskId, onDifyTaskId) {
|
|
|
257
264
|
try {
|
|
258
265
|
return {
|
|
259
266
|
state: "complete",
|
|
260
|
-
content: content.map(
|
|
267
|
+
content: content.map(normalize),
|
|
261
268
|
...(difyTaskId === undefined ? {} : { difyTaskId })
|
|
262
269
|
};
|
|
263
270
|
}
|
|
@@ -298,6 +305,8 @@ export function createToolApiAdapter(dependencies) {
|
|
|
298
305
|
const sleep = dependencies.sleep ?? defaultSleep;
|
|
299
306
|
async function submit({ invocation, access, signal, observe }) {
|
|
300
307
|
signal.throwIfAborted();
|
|
308
|
+
if (invocation.kind === "canvas")
|
|
309
|
+
throw new RemoteProtocolError({}, undefined, "TOOL_ADAPTER_MISSING");
|
|
301
310
|
const managedContentId = contentId(createContentId());
|
|
302
311
|
const resolved = invocation.kind === "direct"
|
|
303
312
|
? { name: invocation.name, arguments: invocation.arguments }
|