@insmind/cli 1.7.1 → 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 +61 -25
- package/dist/src/bootstrap/validators.js +1 -1
- package/dist/src/cli/action-binding.js +3 -0
- package/dist/src/cli/agent-commands.js +1 -0
- package/dist/src/cli/errors.js +43 -10
- package/dist/src/cli/model-commands.js +7 -4
- package/dist/src/cli/observed-errors.js +13 -5
- package/dist/src/cli/task-commands.js +1 -1
- package/dist/src/cli/tool-commands.js +3 -1
- 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/auth/sso-service.js +13 -4
- package/dist/src/features/dam/dam-api-adapter.js +1 -0
- package/dist/src/features/dam/file-downloader.js +23 -2
- package/dist/src/features/task/store.js +8 -4
- package/dist/src/features/task/use-cases.js +14 -11
- 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 +52 -23
- 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 +24 -5
- package/dist/src/features/tool/use-cases.js +28 -3
- package/dist/src/features/update/update-service.js +4 -2
- package/dist/src/platform/file-lock.js +12 -0
- package/dist/src/platform/local-json-file.js +19 -5
- package/dist/src/platform/safe-upload-file.js +18 -10
- package/dist/src/platform/schema-issues.js +47 -2
- package/dist/src/platform/text-output.js +17 -4
- package/dist/src/product/config.js +12 -1
- package/dist/src/telemetry/failure-summary.js +18 -0
- 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 +2 -2
|
@@ -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;
|
|
@@ -63,24 +70,32 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
|
|
|
63
70
|
const properties = {
|
|
64
71
|
model: {
|
|
65
72
|
type: "string",
|
|
73
|
+
enum: models.map(model => model.model),
|
|
66
74
|
description: modelDescription
|
|
67
75
|
}
|
|
68
76
|
};
|
|
69
77
|
for (const model of models) {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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);
|
|
74
85
|
}
|
|
75
86
|
}
|
|
76
87
|
return {
|
|
77
88
|
type: "object",
|
|
78
89
|
properties,
|
|
79
90
|
required: ["model"],
|
|
80
|
-
additionalProperties: false
|
|
91
|
+
additionalProperties: false,
|
|
92
|
+
allOf: models.map(model => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
|
|
93
|
+
then: buildModelArgumentsSchema(model) }))
|
|
81
94
|
};
|
|
82
95
|
}
|
|
83
96
|
export function buildModelArgumentsSchema(model) {
|
|
97
|
+
if (model.inputSchema)
|
|
98
|
+
return structuredClone(model.inputSchema);
|
|
84
99
|
const properties = {
|
|
85
100
|
model: {
|
|
86
101
|
type: "string",
|
|
@@ -114,9 +129,10 @@ function controlArgumentsValidator(model) {
|
|
|
114
129
|
for (const parameter of model.parameters) {
|
|
115
130
|
if (parameter.name === "prompt"
|
|
116
131
|
|| parameter.type === "uri"
|
|
117
|
-
|| parameter.type === "uri[]"
|
|
132
|
+
|| parameter.type === "uri[]"
|
|
133
|
+
|| (model.execution?.kind === "canvas" && !canvasControlParameterNames.has(parameter.name)))
|
|
118
134
|
continue;
|
|
119
|
-
properties[parameter.name] =
|
|
135
|
+
properties[parameter.name] = buildModelArgumentsSchema(model).properties[parameter.name];
|
|
120
136
|
}
|
|
121
137
|
return ajv.compile({
|
|
122
138
|
type: "object",
|
|
@@ -129,30 +145,43 @@ export function assertModelArguments(model, value) {
|
|
|
129
145
|
const validate = validator(model);
|
|
130
146
|
if (!validate(value))
|
|
131
147
|
throw new ToolInputError("model_parameters", "/arguments", validationIssues(validate.errors));
|
|
132
|
-
|
|
133
|
-
|
|
148
|
+
const stepIssues = sliderStepIssues(model, value);
|
|
149
|
+
if (stepIssues.length) {
|
|
150
|
+
throw new ToolInputError("model_parameters", "/arguments", stepIssues);
|
|
134
151
|
}
|
|
135
152
|
}
|
|
136
|
-
function
|
|
137
|
-
|
|
153
|
+
function sliderStepIssues(model, value) {
|
|
154
|
+
const issues = [];
|
|
155
|
+
for (const parameter of model.parameters) {
|
|
138
156
|
if (parameter.step === undefined || !Object.hasOwn(value, parameter.name))
|
|
139
|
-
|
|
157
|
+
continue;
|
|
140
158
|
const candidate = value[parameter.name];
|
|
141
159
|
const minimum = parameter.minimum;
|
|
142
|
-
|
|
143
|
-
|
|
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;
|
|
144
167
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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;
|
|
151
180
|
}
|
|
152
181
|
export function modelControlArgumentsAreValid(model, value) {
|
|
153
182
|
return typeof value === "object"
|
|
154
183
|
&& value !== null
|
|
155
184
|
&& !Array.isArray(value)
|
|
156
185
|
&& controlArgumentsValidator(model)(value)
|
|
157
|
-
&&
|
|
186
|
+
&& sliderStepIssues(model, value).length === 0;
|
|
158
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,17 @@ 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
|
+
}
|
|
148
|
+
export class ToolTaskCanceledError extends Error {
|
|
149
|
+
diagnosticReason = "TASK_CANCELED";
|
|
150
|
+
constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
|
|
151
|
+
}
|
|
141
152
|
export async function queryToolResult(transport, request) {
|
|
142
153
|
try {
|
|
143
154
|
return pollResult(await safePost(transport, {
|
|
@@ -146,10 +157,10 @@ export async function queryToolResult(transport, request) {
|
|
|
146
157
|
signal: request.signal,
|
|
147
158
|
path: "/gdesign/tool/v1/dify/process/batch",
|
|
148
159
|
body: { task_ids: [request.taskId] }
|
|
149
|
-
}), request.taskId, request.onDifyTaskId);
|
|
160
|
+
}), request.taskId, request.onDifyTaskId, request.normalize);
|
|
150
161
|
}
|
|
151
162
|
catch (error) {
|
|
152
|
-
if (isInterruption(error, request.signal))
|
|
163
|
+
if (isInterruption(error, request.signal) || error instanceof ToolTaskCanceledError)
|
|
153
164
|
throw error;
|
|
154
165
|
const evidence = error instanceof RemoteRequestError || error instanceof RemoteProtocolError
|
|
155
166
|
? { ...(error.remoteCode === undefined ? {} : { remoteCode: error.remoteCode }),
|
|
@@ -185,7 +196,7 @@ function isJsonRpcError(value) {
|
|
|
185
196
|
&& typeof value.error.message === "string"
|
|
186
197
|
&& value.error.message.trim() !== "";
|
|
187
198
|
}
|
|
188
|
-
function pollResult(value, taskId, onDifyTaskId) {
|
|
199
|
+
function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolContent) {
|
|
189
200
|
if (!Array.isArray(value))
|
|
190
201
|
return protocolFailure(value);
|
|
191
202
|
const item = value.find((candidate) => isRecord(candidate) && candidate.task_id === taskId);
|
|
@@ -244,10 +255,16 @@ function pollResult(value, taskId, onDifyTaskId) {
|
|
|
244
255
|
if (!Array.isArray(content)) {
|
|
245
256
|
return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
|
|
246
257
|
}
|
|
258
|
+
// Only the structured task envelope is authoritative. Text containing a
|
|
259
|
+
// cancellation message is ordinary content and does not change task state.
|
|
260
|
+
if (content.length === 1 && isRecord(content[0]) && content[0].type === "task"
|
|
261
|
+
&& isRecord(content[0].task) && content[0].task.status === "CANCELED"
|
|
262
|
+
&& content[0].task.id === taskId)
|
|
263
|
+
throw new ToolTaskCanceledError();
|
|
247
264
|
try {
|
|
248
265
|
return {
|
|
249
266
|
state: "complete",
|
|
250
|
-
content: content.map(
|
|
267
|
+
content: content.map(normalize),
|
|
251
268
|
...(difyTaskId === undefined ? {} : { difyTaskId })
|
|
252
269
|
};
|
|
253
270
|
}
|
|
@@ -288,6 +305,8 @@ export function createToolApiAdapter(dependencies) {
|
|
|
288
305
|
const sleep = dependencies.sleep ?? defaultSleep;
|
|
289
306
|
async function submit({ invocation, access, signal, observe }) {
|
|
290
307
|
signal.throwIfAborted();
|
|
308
|
+
if (invocation.kind === "canvas")
|
|
309
|
+
throw new RemoteProtocolError({}, undefined, "TOOL_ADAPTER_MISSING");
|
|
291
310
|
const managedContentId = contentId(createContentId());
|
|
292
311
|
const resolved = invocation.kind === "direct"
|
|
293
312
|
? { name: invocation.name, arguments: invocation.arguments }
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
|
|
2
2
|
import { findToolModel, defaultToolDefinitions, projectModelDetail, projectModelList, projectToolList, ToolInputError } from "./catalog.js";
|
|
3
3
|
import { assertModelArguments, buildToolArgumentsSchema } from "./dynamic-schema.js";
|
|
4
|
+
import { hasCanvasMetering } from "./canvas-pricing.js";
|
|
4
5
|
const mediaTypes = {
|
|
5
6
|
avif: "image/avif",
|
|
6
7
|
gif: "image/gif",
|
|
@@ -66,6 +67,17 @@ export function createToolUseCases(dependencies) {
|
|
|
66
67
|
throw new ToolInputError("model_required", "/arguments/model");
|
|
67
68
|
const selected = findToolModel(catalog, input.name, modelName);
|
|
68
69
|
assertModelArguments(selected, input.arguments);
|
|
70
|
+
if (selected.execution?.kind === "canvas") {
|
|
71
|
+
for (const parameter of selected.parameters) {
|
|
72
|
+
const value = input.arguments[parameter.name];
|
|
73
|
+
const uris = parameter.type === "uri[]" ? value
|
|
74
|
+
: parameter.type === "uri" && typeof value === "string" ? [value] : undefined;
|
|
75
|
+
for (const [index, uri] of (uris ?? []).entries()) {
|
|
76
|
+
if (!uri.startsWith("file:"))
|
|
77
|
+
remoteMedia(uri, parameter.type === "uri[]" ? `${parameter.name}/${index}` : parameter.name);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
69
81
|
return selected;
|
|
70
82
|
});
|
|
71
83
|
const { model: ignoredModel, ...parameters } = input.arguments;
|
|
@@ -75,6 +87,11 @@ export function createToolUseCases(dependencies) {
|
|
|
75
87
|
model_id: model.model,
|
|
76
88
|
parameters
|
|
77
89
|
});
|
|
90
|
+
if (model.execution?.kind === "canvas") {
|
|
91
|
+
const usage = { model: model.model, ...(model.cost === undefined || hasCanvasMetering(model) ? {} : { cost: model.cost }) };
|
|
92
|
+
await observe?.({ toolUsage: usage, generation: { tool: model.tool, model: model.model } });
|
|
93
|
+
return { invocation: { kind: "canvas", model, arguments: input.arguments }, usage };
|
|
94
|
+
}
|
|
78
95
|
const prompt = [];
|
|
79
96
|
const requestParameters = {};
|
|
80
97
|
const directArguments = {};
|
|
@@ -166,14 +183,22 @@ export function createToolUseCases(dependencies) {
|
|
|
166
183
|
return projectModelList(await load(access, signal), input.tool, dependencies.tools ?? defaultToolDefinitions);
|
|
167
184
|
},
|
|
168
185
|
async getModel({ input, access, signal }) {
|
|
169
|
-
return projectModelDetail(await load(access, signal), input.model);
|
|
186
|
+
return projectModelDetail(await load(access, signal), input.model, input.tool);
|
|
170
187
|
},
|
|
171
188
|
async getArgumentsSchema({ name, access, signal }) {
|
|
172
189
|
return buildToolArgumentsSchema(await load(access, signal), name, dependencies.modelDescription);
|
|
173
190
|
},
|
|
174
191
|
async call(input) {
|
|
175
|
-
const
|
|
176
|
-
const
|
|
192
|
+
const prepared = await prepare(input);
|
|
193
|
+
const { invocation } = prepared;
|
|
194
|
+
let usage = prepared.usage;
|
|
195
|
+
const observe = async (progress) => {
|
|
196
|
+
if (progress.toolUsage)
|
|
197
|
+
usage = progress.toolUsage;
|
|
198
|
+
await input.observe?.(progress);
|
|
199
|
+
};
|
|
200
|
+
const observer = invocation.kind === "canvas" ? observe : input.observe;
|
|
201
|
+
const content = await dependencies.execution.execute({ invocation, access: input.access, signal: input.signal, ...(observer ? { observe: observer } : {}) });
|
|
177
202
|
return { content, usage };
|
|
178
203
|
},
|
|
179
204
|
async submit(input) {
|
|
@@ -9,10 +9,12 @@ import { readInstallationOwner } from "../../platform/installation-owner.js";
|
|
|
9
9
|
export class UpdateError extends Error {
|
|
10
10
|
code;
|
|
11
11
|
nextSteps;
|
|
12
|
-
|
|
12
|
+
diagnosticReason;
|
|
13
|
+
constructor(code, message, nextSteps, cause, diagnosticReason) {
|
|
13
14
|
super(message, { cause });
|
|
14
15
|
this.code = code;
|
|
15
16
|
this.nextSteps = nextSteps;
|
|
17
|
+
this.diagnosticReason = diagnosticReason;
|
|
16
18
|
this.name = "UpdateError";
|
|
17
19
|
}
|
|
18
20
|
get details() {
|
|
@@ -73,7 +75,7 @@ export function createUpdateService(options) {
|
|
|
73
75
|
? "This insMind CLI installation is managed by WorkBuddy."
|
|
74
76
|
: "此 gd-cli 由 WorkBuddy 连接器管理。", [insmind
|
|
75
77
|
? "Update the insMind connector in WorkBuddy."
|
|
76
|
-
: "请在 WorkBuddy 中更新「稿定」连接器。"]);
|
|
78
|
+
: "请在 WorkBuddy 中更新「稿定」连接器。"], undefined, "UPDATE_MANAGED_BY_HOST");
|
|
77
79
|
}
|
|
78
80
|
if (owner === "invalid") {
|
|
79
81
|
throw new UpdateError("UPDATE_FAILED", insmind
|