@insmind/cli 2.1.0 → 2.1.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/agent.send/input.schema.json +1 -77
- package/contracts/operations/dam.folder.list/input.schema.json +0 -1
- package/contracts/operations/dam.folder.list/output.schema.json +1 -2
- package/contracts/operations/dam.list/input.schema.json +3 -6
- package/contracts/operations/dam.list/output.schema.json +1 -2
- package/contracts/operations/dam.search/input.schema.json +3 -6
- package/contracts/operations/dam.search/output.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
- package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
- package/dist/bin/postinstall.js +22 -6
- package/dist/bin/task-worker.js +2 -2
- package/dist/src/bootstrap/create-cli.js +13 -6
- package/dist/src/bootstrap/create-runtime.js +98 -28
- package/dist/src/bootstrap/run-task-worker.js +6 -2
- package/dist/src/bootstrap/validators.js +1 -1
- package/dist/src/cli/action-binding.js +14 -37
- package/dist/src/cli/agent-commands.js +11 -11
- package/dist/src/cli/auth-commands.js +2 -1
- package/dist/src/cli/creation-help.js +9 -0
- package/dist/src/cli/dam-commands.js +10 -14
- package/dist/src/cli/editor-commands.js +7 -5
- package/dist/src/cli/errors.js +81 -22
- package/dist/src/cli/host-input.js +64 -5
- package/dist/src/cli/model-commands.js +9 -3
- package/dist/src/cli/observed-errors.js +7 -3
- package/dist/src/cli/org-commands.js +3 -1
- package/dist/src/cli/task-commands.js +6 -2
- package/dist/src/cli/tool-commands.js +12 -11
- package/dist/src/features/agent/creative-agent-adapter.js +6 -2
- package/dist/src/features/agent/creative-protocol.js +8 -29
- package/dist/src/features/agent/resource-authorizer.js +25 -17
- package/dist/src/features/agent/result-reader.js +31 -14
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/credits/use-cases.js +55 -28
- package/dist/src/features/dam/asset-projection.js +3 -6
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/repository-catalog.js +30 -21
- package/dist/src/features/dam/use-cases.js +12 -7
- package/dist/src/features/editor/bridge-client.js +0 -2
- package/dist/src/features/editor/public-url.js +1 -36
- package/dist/src/features/editor/session.js +3 -2
- package/dist/src/features/editor/use-cases.js +27 -2
- package/dist/src/features/org/org-service.js +10 -1
- package/dist/src/features/org/use-cases.js +18 -4
- package/dist/src/features/task/process-owner.js +54 -0
- package/dist/src/features/task/store.js +37 -10
- package/dist/src/features/task/task-background.js +5 -2
- package/dist/src/features/task/use-cases.js +184 -84
- package/dist/src/features/tool/argument-paths.js +14 -0
- package/dist/src/features/tool/canvas-copy.js +28 -15
- package/dist/src/features/tool/canvas-matting.js +123 -0
- package/dist/src/features/tool/canvas-media.js +100 -52
- package/dist/src/features/tool/canvas-models.js +66 -33
- package/dist/src/features/tool/canvas-pricing.js +12 -0
- package/dist/src/features/tool/canvas-recovery.js +13 -30
- package/dist/src/features/tool/canvas-results.js +79 -87
- package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
- package/dist/src/features/tool/canvas-video.js +44 -37
- package/dist/src/features/tool/dynamic-schema.js +39 -40
- package/dist/src/features/tool/ffprobe-executable.js +21 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
- package/dist/src/features/tool/resource-authorizer.js +11 -3
- package/dist/src/features/tool/tool-api-adapter.js +73 -82
- package/dist/src/features/tool/tool-errors.js +25 -0
- package/dist/src/features/tool/tool-output.js +15 -0
- package/dist/src/features/tool/use-cases.js +74 -98
- package/dist/src/features/update/update-service.js +95 -21
- package/dist/src/platform/media-type.js +46 -0
- package/dist/src/platform/public-url.js +35 -0
- package/dist/src/platform/remote-error-evidence.js +33 -6
- package/dist/src/platform/resource-auth-key.js +35 -1
- package/dist/src/platform/safe-upload-file.js +36 -41
- package/dist/src/platform/signature.js +2 -2
- package/dist/src/platform/signed-http-transport.js +4 -1
- package/dist/src/platform/url-safety.js +6 -1
- package/dist/src/platform/webm-header.js +41 -0
- package/dist/src/telemetry/command-route.js +38 -0
- package/dist/src/telemetry/command-routes.json +1 -0
- package/dist/src/telemetry/failure-summary.js +1 -1
- package/dist/src/telemetry/invocation.js +1 -2
- package/dist/src/telemetry/process-errors.js +17 -33
- package/dist/src/telemetry/sanitize.js +19 -4
- package/dist/src/telemetry/sls-sink.js +8 -0
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +18 -5
- package/skills/insmind-cli/references/agent.md +9 -4
- package/skills/insmind-cli/references/creation.md +3 -1
- package/skills/insmind-cli/references/editor.md +7 -5
- package/skills/insmind-cli/references/errors.md +20 -9
- package/skills/insmind-cli/references/matting.md +3 -5
- package/skills/insmind-cli/references/media-tools.md +10 -4
- package/skills/insmind-cli/references/tool.md +9 -15
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
2
2
|
import addFormatsImport, {} from "ajv-formats";
|
|
3
3
|
import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
|
|
4
|
+
import { unavailableCanvasMediaRoles } from "./canvas-models.js";
|
|
4
5
|
import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
|
|
5
6
|
import { ToolInputError } from "./catalog.js";
|
|
6
7
|
function parameterSchema(parameter, includeBounds = false) {
|
|
@@ -36,33 +37,6 @@ function parameterSchema(parameter, includeBounds = false) {
|
|
|
36
37
|
...common
|
|
37
38
|
};
|
|
38
39
|
}
|
|
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
|
-
}
|
|
43
|
-
return left.type === right.type
|
|
44
|
-
&& left.format === right.format
|
|
45
|
-
&& left.items?.format === right.items?.format;
|
|
46
|
-
}
|
|
47
|
-
function mergeSchema(current, next) {
|
|
48
|
-
if (!sameShape(current, next)) {
|
|
49
|
-
const variants = current.anyOf ?? [current];
|
|
50
|
-
return variants.some((variant) => sameShape(variant, next))
|
|
51
|
-
? current
|
|
52
|
-
: { anyOf: [...variants, next] };
|
|
53
|
-
}
|
|
54
|
-
if (current.enum === undefined || next.enum === undefined) {
|
|
55
|
-
if (current.enum === undefined)
|
|
56
|
-
return current;
|
|
57
|
-
const { enum: ignored, ...unrestricted } = current;
|
|
58
|
-
void ignored;
|
|
59
|
-
return unrestricted;
|
|
60
|
-
}
|
|
61
|
-
return {
|
|
62
|
-
...current,
|
|
63
|
-
enum: [...new Set([...current.enum, ...next.enum])]
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
40
|
export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要调用的模型机器标识;取值来自 model list。") {
|
|
67
41
|
const models = catalog.models.filter((model) => model.tool === tool);
|
|
68
42
|
if (models.length === 0)
|
|
@@ -74,14 +48,21 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
|
|
|
74
48
|
description: modelDescription
|
|
75
49
|
}
|
|
76
50
|
};
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
51
|
+
const branches = models.map(buildModelArgumentsSchema);
|
|
52
|
+
const fieldNames = new Set(branches.flatMap(branch => Object.keys(branch.properties)));
|
|
53
|
+
for (const name of fieldNames) {
|
|
54
|
+
if (name === "model")
|
|
55
|
+
continue;
|
|
56
|
+
const fields = branches.flatMap(branch => branch.properties[name] ? [branch.properties[name]] : []);
|
|
57
|
+
const field = fields[0];
|
|
58
|
+
// An open sibling may accept a completely different value at this key.
|
|
59
|
+
// Its presence in the index must not restrict the selected model.
|
|
60
|
+
if (branches.some(branch => !Object.hasOwn(branch.properties, name) && branch.additionalProperties)) {
|
|
61
|
+
properties[name] = field.description ? { description: field.description } : {};
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
const variants = [...new Map(fields.map(item => [JSON.stringify(item), item])).values()];
|
|
65
|
+
properties[name] = variants.length === 1 ? field : { anyOf: variants };
|
|
85
66
|
}
|
|
86
67
|
}
|
|
87
68
|
return {
|
|
@@ -89,14 +70,24 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
|
|
|
89
70
|
properties,
|
|
90
71
|
required: ["model"],
|
|
91
72
|
additionalProperties: true,
|
|
92
|
-
allOf: models.map(model => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
|
|
93
|
-
then:
|
|
73
|
+
allOf: models.map((model, i) => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
|
|
74
|
+
then: branches[i] }))
|
|
94
75
|
};
|
|
95
76
|
}
|
|
96
77
|
export function buildModelArgumentsSchema(model) {
|
|
97
|
-
|
|
98
|
-
|
|
78
|
+
const managed = model.execution?.kind === "canvas" ? ["content_id", "contentid", "async"] : ["content_id", "contentid"];
|
|
79
|
+
if (model.inputSchema) {
|
|
80
|
+
const schema = structuredClone(model.inputSchema);
|
|
81
|
+
const unavailable = model.execution?.kind === "canvas" ? unavailableCanvasMediaRoles(schema) : [];
|
|
82
|
+
if (schema.additionalProperties)
|
|
83
|
+
for (const [name, detail] of Object.entries(model.optionalControls ?? {})) {
|
|
84
|
+
if (!Object.hasOwn(schema.properties, name) && ![...managed, ...unavailable].includes(name))
|
|
85
|
+
Object.defineProperty(schema.properties, name, { value: detail, enumerable: true, writable: true, configurable: true });
|
|
86
|
+
}
|
|
87
|
+
return { ...schema, propertyNames: { not: { enum: [...managed, ...unavailable] } } };
|
|
88
|
+
}
|
|
99
89
|
const properties = {
|
|
90
|
+
...Object.fromEntries(Object.entries(model.optionalControls ?? {}).filter(([key]) => !managed.includes(key))),
|
|
100
91
|
model: {
|
|
101
92
|
type: "string",
|
|
102
93
|
const: model.model,
|
|
@@ -115,7 +106,8 @@ export function buildModelArgumentsSchema(model) {
|
|
|
115
106
|
.filter((parameter) => parameter.required)
|
|
116
107
|
.map((parameter) => parameter.name)
|
|
117
108
|
],
|
|
118
|
-
additionalProperties: true
|
|
109
|
+
additionalProperties: true,
|
|
110
|
+
propertyNames: { not: { enum: managed } }
|
|
119
111
|
};
|
|
120
112
|
}
|
|
121
113
|
const ajv = new Ajv2020({ allErrors: true, strict: true });
|
|
@@ -124,6 +116,11 @@ addFormats(ajv);
|
|
|
124
116
|
/** Enforce structure that the CLI actually reads or transforms. Business controls go to the service. */
|
|
125
117
|
export function assertModelArguments(model, value) {
|
|
126
118
|
const published = buildModelArgumentsSchema(model);
|
|
119
|
+
if (value && typeof value === "object") {
|
|
120
|
+
const blocked = published.propertyNames?.not.enum.find(key => Object.hasOwn(value, key));
|
|
121
|
+
if (blocked)
|
|
122
|
+
throw new ToolInputError(["content_id", "contentid"].includes(blocked) ? "reserved_argument" : "unmapped_argument", "/arguments/" + blocked);
|
|
123
|
+
}
|
|
127
124
|
const properties = { model: published.properties.model };
|
|
128
125
|
const required = ["model"];
|
|
129
126
|
for (const parameter of model.parameters) {
|
|
@@ -134,6 +131,8 @@ export function assertModelArguments(model, value) {
|
|
|
134
131
|
}
|
|
135
132
|
}
|
|
136
133
|
if (model.execution?.kind === "canvas") {
|
|
134
|
+
if (["image-edit-standard", "image-remove-standard"].includes(model.model))
|
|
135
|
+
required.push("mask");
|
|
137
136
|
for (const key of ["canvas", "placement", "cropToSubject"]) {
|
|
138
137
|
if (published.properties[key])
|
|
139
138
|
properties[key] = published.properties[key];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, chmod, copyFile, lstat } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
/** The caller supplies the installed platform binary and its fresh per-video work directory. */
|
|
5
|
+
export async function resolveFfprobeExecutable(installed, directory) {
|
|
6
|
+
try {
|
|
7
|
+
await access(installed, constants.X_OK);
|
|
8
|
+
return installed;
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
if (!(error instanceof Error && "code" in error && error.code === "EACCES"))
|
|
12
|
+
throw error;
|
|
13
|
+
if (!(await lstat(installed)).isFile())
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
// Sandboxed npm installs can skip the platform package's postinstall chmod.
|
|
17
|
+
const executable = join(directory, "ffprobe");
|
|
18
|
+
await copyFile(installed, executable, constants.COPYFILE_EXCL);
|
|
19
|
+
await chmod(executable, 0o700);
|
|
20
|
+
return executable;
|
|
21
|
+
}
|
|
@@ -77,7 +77,7 @@ function collectScenes(raw) {
|
|
|
77
77
|
}
|
|
78
78
|
return scenes;
|
|
79
79
|
}
|
|
80
|
-
function parameter(value) {
|
|
80
|
+
function parameter(value, optionalControls) {
|
|
81
81
|
const field = record(value);
|
|
82
82
|
if (field === undefined)
|
|
83
83
|
throw new Error("invalid parameter");
|
|
@@ -91,15 +91,20 @@ function parameter(value) {
|
|
|
91
91
|
? "number"
|
|
92
92
|
: multiUriKeys.has(name)
|
|
93
93
|
? "uri[]"
|
|
94
|
-
: name === "start_frame" || name === "end_frame" || sourceType === "IMAGE"
|
|
94
|
+
: name === "start_frame" || name === "end_frame" || sourceType === "IMAGE" || sourceType === "VIDEO"
|
|
95
95
|
? "uri"
|
|
96
96
|
: sourceType === "NUMBER"
|
|
97
97
|
? "number"
|
|
98
98
|
: sourceType === "TEXT" || sourceType === "INPUT" || sourceType === "SELECT"
|
|
99
99
|
? "string"
|
|
100
100
|
: undefined;
|
|
101
|
-
if (type === undefined)
|
|
102
|
-
|
|
101
|
+
if (type === undefined) {
|
|
102
|
+
if (field.required === true)
|
|
103
|
+
throw new Error("unsupported required parameter");
|
|
104
|
+
const description = text(field.description) ?? text(field.label);
|
|
105
|
+
optionalControls[name] = description ? { description } : {};
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
103
108
|
let minimum;
|
|
104
109
|
let maximum;
|
|
105
110
|
let step;
|
|
@@ -131,7 +136,11 @@ function parameter(value) {
|
|
|
131
136
|
if (options.length === 0)
|
|
132
137
|
throw new Error("empty options");
|
|
133
138
|
}
|
|
134
|
-
const
|
|
139
|
+
const rawDescription = text(field.description) ?? text(field.label);
|
|
140
|
+
// MNS documents the service's wire encoding. Public URI-list inputs are native arrays.
|
|
141
|
+
const description = type === "uri[]" ? rawDescription
|
|
142
|
+
?.replace(/JSON 数组的字符串/gu, "原生 JSON 数组")
|
|
143
|
+
.replace(/(?:例如|如)\s*(?:\\*["“])?\[.*?\](?:\\*["”])*/gu, '例如 ["https://example.com/media.png"]') : rawDescription;
|
|
135
144
|
const defaultValue = field.default_value;
|
|
136
145
|
const hasDefault = defaultValue !== undefined
|
|
137
146
|
&& defaultValue !== null
|
|
@@ -156,6 +165,26 @@ function range(values, unit) {
|
|
|
156
165
|
const bounds = { minimum: Math.min(...values), maximum: Math.max(...values) };
|
|
157
166
|
return unit === "gaodou" ? { unit, ...bounds } : { unit, ...bounds };
|
|
158
167
|
}
|
|
168
|
+
/** With a single SELECT SKU dimension, the MNS code is <model>_<key><option value>. */
|
|
169
|
+
function fixedUpscalePrices(code, settings, parameters, skus) {
|
|
170
|
+
const dimensions = settings.map(record).filter(field => field?.sku_enable === true);
|
|
171
|
+
const dimension = dimensions[0];
|
|
172
|
+
const options = parameters.find(field => field.name === "resolution")?.options;
|
|
173
|
+
if (dimensions.length !== 1 || dimension?.key !== "resolution" || dimension.type !== "SELECT" || !options?.length)
|
|
174
|
+
return;
|
|
175
|
+
const optionCodes = new Map(options.map(({ value }) => [code + "_resolution" + value, value]));
|
|
176
|
+
if (optionCodes.size !== options.length)
|
|
177
|
+
return;
|
|
178
|
+
const prices = {};
|
|
179
|
+
for (const sku of skus) {
|
|
180
|
+
const choice = typeof sku.code === "string" ? optionCodes.get(sku.code) : undefined;
|
|
181
|
+
if (!choice || !/^[1-9]\d*$/u.test(choice) || !Number.isSafeInteger(Number(choice)) || Object.hasOwn(prices, choice)
|
|
182
|
+
|| sku.usage_unit !== "FIXED" || typeof sku.point_cost !== "number" || !Number.isFinite(sku.point_cost) || sku.point_cost < 0)
|
|
183
|
+
return;
|
|
184
|
+
prices[choice] = sku.point_cost;
|
|
185
|
+
}
|
|
186
|
+
return prices;
|
|
187
|
+
}
|
|
159
188
|
function normalizeModel(value, scenes, english = false) {
|
|
160
189
|
const item = record(value);
|
|
161
190
|
const model = record(item?.model);
|
|
@@ -182,8 +211,9 @@ function normalizeModel(value, scenes, english = false) {
|
|
|
182
211
|
const settings = JSON.parse(model.input_field_settings);
|
|
183
212
|
if (!Array.isArray(settings))
|
|
184
213
|
throw new Error("invalid settings");
|
|
214
|
+
const optionalControls = Object.create(null);
|
|
185
215
|
const parameters = settings
|
|
186
|
-
.map(parameter)
|
|
216
|
+
.map(item => parameter(item, optionalControls))
|
|
187
217
|
.filter((item) => item !== undefined);
|
|
188
218
|
const description = cleanText(model.description);
|
|
189
219
|
const usageDescription = cleanText(model.tool_description);
|
|
@@ -216,6 +246,7 @@ function normalizeModel(value, scenes, english = false) {
|
|
|
216
246
|
...(usageDescription === undefined ? {} : { usageDescription }),
|
|
217
247
|
...(outputMediaTypes.length === 0 ? {} : { outputMediaTypes }),
|
|
218
248
|
parameters,
|
|
249
|
+
...(Object.keys(optionalControls).length ? { optionalControls } : {}),
|
|
219
250
|
...(cost?.unit === "gaodou" ? { cost } : {}),
|
|
220
251
|
...(estimatedTime?.unit === "second" ? { estimatedTime } : {}),
|
|
221
252
|
sceneSort: scene.sort,
|
|
@@ -231,24 +262,30 @@ function normalizeModel(value, scenes, english = false) {
|
|
|
231
262
|
&& (binding[3] === match.code || binding[0] === match.tool));
|
|
232
263
|
if (!binding)
|
|
233
264
|
continue; // A category association is insufficient to execute an unknown protocol.
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
265
|
+
const billingComponents = item.billing_components;
|
|
266
|
+
const fixedResolutionPrices = binding[1] === "image-enhance-standard"
|
|
267
|
+
&& (billingComponents === undefined || Array.isArray(billingComponents) && billingComponents.length === 0)
|
|
268
|
+
? fixedUpscalePrices(code, settings, parameters, activeSkus) : undefined;
|
|
269
|
+
// When MNS identifies every live SKU by its resolution, use only its listed tiers for automatic selection.
|
|
270
|
+
const resolutionField = binding[1] === "image-layers-smart" ? settings.map(record).find(field => field?.key === "resolution") : undefined;
|
|
271
|
+
const options = Array.isArray(resolutionField?.options) ? resolutionField.options.map(option => text(record(option)?.value)) : [];
|
|
272
|
+
const liveTiers = activeSkus.map(sku => options.find(value => value && sku.code === code + "_resolution" + value));
|
|
273
|
+
const configuration = { fields: settings,
|
|
274
|
+
...(options.length && liveTiers.every((tier) => !!tier) ? { layerTiers: [...new Set(liveTiers)] } : {}), ...(billingComponents === undefined ? {} : { billingComponents }),
|
|
275
|
+
...(fixedResolutionPrices ? { fixedResolutionPrices } : {}) };
|
|
276
|
+
// The layer component caps an estimate; Toolkit does not consume the quote.
|
|
277
|
+
// With no usable quote, the same listed model can still execute.
|
|
278
|
+
const canQuote = cost && canvasPricingSupported(binding[1], configuration)
|
|
279
|
+
&& !(binding[1] === "image-layers-smart" && settings.some(value => record(value)?.key === "max_layers" && record(value)?.sku_enable === true));
|
|
280
|
+
// Standard matting actually settles this quantity. Other execution protocols never consume a quote.
|
|
281
|
+
if (binding[1] === "image-matting-standard" && (!canQuote || cost?.minimum !== cost?.maximum))
|
|
282
|
+
throw new Error("matting settlement price unavailable");
|
|
283
|
+
const bindingParameters = fixedResolutionPrices ? parameters.map(field => field.name === "resolution" && field.options
|
|
284
|
+
? { ...field, options: field.options.filter(({ value }) => Object.hasOwn(fixedResolutionPrices, value)) } : field) : parameters;
|
|
285
|
+
const listed = { ...normalized, parameters: bindingParameters, sceneSort: match.sort };
|
|
286
|
+
if (!canQuote)
|
|
287
|
+
delete listed.cost;
|
|
288
|
+
result.push(canvasModel(listed, binding, configuration, english));
|
|
252
289
|
}
|
|
253
290
|
return result;
|
|
254
291
|
}
|
|
@@ -7,8 +7,14 @@ export async function authorizeToolResources(output, authorizer, access, signal)
|
|
|
7
7
|
if (part.type === "resource_link")
|
|
8
8
|
references.push({ index, uri: part.uri, mediaType: part.mimeType ?? "application/octet-stream" });
|
|
9
9
|
else if (output.usage.model === "image-ocr" && part.type === "resource") {
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
try {
|
|
11
|
+
const ocr = readOcrPayload(part.resource.text);
|
|
12
|
+
references.push({ index, uri: ocr.image.uri, mediaType: "image/jpeg", ocr });
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
if (!(error instanceof RemoteProtocolError))
|
|
16
|
+
throw error; // An independent JSON attachment is not an OCR document.
|
|
17
|
+
}
|
|
12
18
|
}
|
|
13
19
|
}
|
|
14
20
|
if (!references.length)
|
|
@@ -17,13 +23,15 @@ export async function authorizeToolResources(output, authorizer, access, signal)
|
|
|
17
23
|
const authorized = await authorizer.authorize({
|
|
18
24
|
message: { contextId: "resource-authorization", parts: [parts[0], ...parts.slice(1)] },
|
|
19
25
|
usage: { cost: { unit: "gaodou", amount: 0 }, items: [] }
|
|
20
|
-
}, access, signal);
|
|
26
|
+
}, access, signal, undefined, output.content.length > references.length);
|
|
21
27
|
const content = [...output.content];
|
|
22
28
|
for (const [index, reference] of references.entries()) {
|
|
23
29
|
const part = content[reference.index];
|
|
24
30
|
const authorizedPart = authorized.message.parts[index];
|
|
25
31
|
if (!authorizedPart || !("url" in authorizedPart))
|
|
26
32
|
throw new RemoteProtocolError();
|
|
33
|
+
if (authorizedPart.url === reference.uri)
|
|
34
|
+
continue;
|
|
27
35
|
if (part.type === "resource_link")
|
|
28
36
|
content[reference.index] = { ...part, uri: authorizedPart.url };
|
|
29
37
|
else if (part.type === "resource" && reference.ocr)
|
|
@@ -3,7 +3,10 @@ import { randomInt } from "node:crypto";
|
|
|
3
3
|
import { setTimeout as delay } from "node:timers/promises";
|
|
4
4
|
import { RemoteRequestError, withResponseDiagnostics } from "../../platform/signed-http-transport.js";
|
|
5
5
|
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
6
|
+
import { ToolTaskFailedError, ToolTaskCanceledError } from "./tool-errors.js";
|
|
6
7
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
8
|
+
export { ToolTaskFailedError, ToolTaskCanceledError, ToolInsufficientCreditsError } from "./tool-errors.js";
|
|
9
|
+
import { mediaFilename } from "../../platform/media-type.js";
|
|
7
10
|
const MAX_JAVA_LONG = 9223372036854775807n;
|
|
8
11
|
function isRecord(value) {
|
|
9
12
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -14,35 +17,35 @@ function fail() {
|
|
|
14
17
|
function protocolFailure(value) {
|
|
15
18
|
throw new RemoteProtocolError(remoteErrorEvidence(value));
|
|
16
19
|
}
|
|
20
|
+
function contentId(value) {
|
|
21
|
+
if (!/^\d+$/u.test(value))
|
|
22
|
+
return fail();
|
|
23
|
+
const numeric = BigInt(value);
|
|
24
|
+
if (numeric > MAX_JAVA_LONG)
|
|
25
|
+
return fail();
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
17
28
|
function nonBlank(value) {
|
|
18
29
|
if (typeof value !== "string" || value.trim() === "")
|
|
19
|
-
return
|
|
30
|
+
return protocolFailure(value);
|
|
20
31
|
return value;
|
|
21
32
|
}
|
|
22
33
|
function parseRecord(value) {
|
|
23
34
|
try {
|
|
24
35
|
const parsed = JSON.parse(value);
|
|
25
36
|
if (!isRecord(parsed))
|
|
26
|
-
return
|
|
37
|
+
return protocolFailure(value);
|
|
27
38
|
return parsed;
|
|
28
39
|
}
|
|
29
40
|
catch (error) {
|
|
30
|
-
if (error instanceof
|
|
41
|
+
if (error instanceof RemoteProtocolError)
|
|
31
42
|
throw error;
|
|
32
|
-
return
|
|
43
|
+
return protocolFailure(value);
|
|
33
44
|
}
|
|
34
45
|
}
|
|
35
|
-
function contentId(value) {
|
|
36
|
-
if (!/^\d+$/u.test(value))
|
|
37
|
-
return fail();
|
|
38
|
-
const numeric = BigInt(value);
|
|
39
|
-
if (numeric > MAX_JAVA_LONG)
|
|
40
|
-
return fail();
|
|
41
|
-
return value;
|
|
42
|
-
}
|
|
43
46
|
function parseIntent(value) {
|
|
44
47
|
if (!isRecord(value))
|
|
45
|
-
return
|
|
48
|
+
return protocolFailure(value);
|
|
46
49
|
return {
|
|
47
50
|
name: nonBlank(value.name),
|
|
48
51
|
arguments: parseRecord(nonBlank(value.arguments))
|
|
@@ -64,6 +67,8 @@ function withoutEmptyOptionalMedia(value, optionalMediaParameters) {
|
|
|
64
67
|
return normalized;
|
|
65
68
|
}
|
|
66
69
|
function submittedTask(value) {
|
|
70
|
+
if (isRecord(value) && isJsonRpcError(value))
|
|
71
|
+
throw new ToolTaskFailedError(remoteErrorEvidence(value));
|
|
67
72
|
if (!isRecord(value) || !isRecord(value.result))
|
|
68
73
|
return protocolFailure(value);
|
|
69
74
|
if (value.result.isError === true) {
|
|
@@ -76,78 +81,55 @@ function submittedTask(value) {
|
|
|
76
81
|
}
|
|
77
82
|
return value.task_id;
|
|
78
83
|
}
|
|
79
|
-
function resourceName(uri) {
|
|
80
|
-
let url;
|
|
81
|
-
try {
|
|
82
|
-
url = new URL(uri);
|
|
83
|
-
}
|
|
84
|
-
catch {
|
|
85
|
-
return protocolFailure(uri);
|
|
86
|
-
}
|
|
87
|
-
const segment = url.pathname.split("/").filter(Boolean).at(-1);
|
|
88
|
-
if (segment === undefined)
|
|
89
|
-
return protocolFailure(uri);
|
|
90
|
-
try {
|
|
91
|
-
const decoded = decodeURIComponent(segment);
|
|
92
|
-
if (decoded.trim() === "")
|
|
93
|
-
return protocolFailure(uri);
|
|
94
|
-
return decoded;
|
|
95
|
-
}
|
|
96
|
-
catch {
|
|
97
|
-
return protocolFailure(uri);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
84
|
export function normalizeToolContent(value) {
|
|
101
85
|
if (!isRecord(value))
|
|
102
86
|
return protocolFailure(value);
|
|
103
|
-
if (value.type === "text")
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
return { type: "text", text: value.text };
|
|
108
|
-
}
|
|
109
|
-
if (value.type !== "resource" || !isRecord(value.resource)) {
|
|
110
|
-
return protocolFailure(value);
|
|
111
|
-
}
|
|
112
|
-
if ("blob" in value.resource || ("text" in value.resource && value.resource.text !== ""))
|
|
113
|
-
return protocolFailure(value);
|
|
114
|
-
if (typeof value.resource.uri !== "string" || value.resource.uri.trim() === "") {
|
|
87
|
+
if (value.type === "text")
|
|
88
|
+
return { type: "text", text: nonBlank(value.text) };
|
|
89
|
+
const item = value.type === "resource_link" ? value : value.type === "resource" && isRecord(value.resource) ? value.resource : undefined;
|
|
90
|
+
if (!item)
|
|
115
91
|
return protocolFailure(value);
|
|
92
|
+
const uri = nonBlank(item.uri);
|
|
93
|
+
let url;
|
|
94
|
+
try {
|
|
95
|
+
url = new URL(uri);
|
|
116
96
|
}
|
|
117
|
-
|
|
118
|
-
const mimeType = value.resource.mimeType;
|
|
119
|
-
if (mimeType !== undefined && (typeof mimeType !== "string" || mimeType.trim() === "")) {
|
|
97
|
+
catch {
|
|
120
98
|
return protocolFailure(value);
|
|
121
99
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
uri,
|
|
125
|
-
name: resourceName(uri),
|
|
126
|
-
...(mimeType === undefined ? {} : { mimeType })
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
export class ToolTaskFailedError extends Error {
|
|
130
|
-
remoteCode;
|
|
131
|
-
remoteBody;
|
|
132
|
-
diagnosticReason;
|
|
133
|
-
constructor(evidence = {}) {
|
|
134
|
-
super("稿定工具任务执行失败。");
|
|
135
|
-
this.name = "ToolTaskFailedError";
|
|
136
|
-
this.remoteCode = evidence.remoteCode;
|
|
137
|
-
this.remoteBody = evidence.remoteBody;
|
|
138
|
-
this.diagnosticReason = evidence.diagnosticReason;
|
|
100
|
+
const mimeType = typeof item.mimeType === "string" && item.mimeType.trim() ? item.mimeType : undefined;
|
|
101
|
+
if (mimeType === "application/json" && typeof item.text === "string" && item.text.trim()) {
|
|
102
|
+
return { type: "resource", resource: { uri, mimeType, text: item.text } };
|
|
139
103
|
}
|
|
104
|
+
return { type: "resource_link", uri,
|
|
105
|
+
name: typeof item.name === "string" && item.name.trim() ? item.name : mediaFilename(url),
|
|
106
|
+
...(mimeType ? { mimeType } : {}) };
|
|
140
107
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
108
|
+
/** Nullable slots do not invalidate their siblings; unsupported parts are observable, never a fabricated success. */
|
|
109
|
+
export function normalizeToolItems(items, normalize = normalizeToolContent, onUnrepresented) {
|
|
110
|
+
const parts = [];
|
|
111
|
+
let unsupported = false;
|
|
112
|
+
for (const item of items) {
|
|
113
|
+
if (item == null || isRecord(item) && item.type === "text" && (item.text == null || typeof item.text === "string" && !item.text.trim()))
|
|
114
|
+
continue;
|
|
115
|
+
try {
|
|
116
|
+
const part = normalize(item);
|
|
117
|
+
parts.push(part);
|
|
118
|
+
if (part.type === "resource_link" && isRecord(item) && item.type === "resource" && isRecord(item.resource)
|
|
119
|
+
&& typeof item.resource.text === "string" && item.resource.text.trim())
|
|
120
|
+
parts.push({ type: "text", text: item.resource.text });
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
if (!(error instanceof RemoteProtocolError))
|
|
124
|
+
throw error;
|
|
125
|
+
unsupported = true;
|
|
126
|
+
}
|
|
146
127
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
128
|
+
if (!parts.length)
|
|
129
|
+
return protocolFailure(items);
|
|
130
|
+
if (unsupported)
|
|
131
|
+
onUnrepresented?.();
|
|
132
|
+
return parts;
|
|
151
133
|
}
|
|
152
134
|
export async function queryToolResult(transport, request) {
|
|
153
135
|
let difyTaskId;
|
|
@@ -158,7 +140,7 @@ export async function queryToolResult(transport, request) {
|
|
|
158
140
|
signal: request.signal,
|
|
159
141
|
path: "/gdesign/tool/v1/dify/process/batch",
|
|
160
142
|
body: { task_ids: [request.taskId] }
|
|
161
|
-
}, value => pollResult(value, request.taskId, id => { difyTaskId = id; request.onDifyTaskId?.(id); }, request.normalize));
|
|
143
|
+
}, value => pollResult(value, request.taskId, id => { difyTaskId = id; request.onDifyTaskId?.(id); }, request.normalize, request.onUnrepresented));
|
|
162
144
|
}
|
|
163
145
|
catch (error) {
|
|
164
146
|
if (isInterruption(error, request.signal) || error instanceof ToolTaskCanceledError)
|
|
@@ -199,7 +181,7 @@ function isJsonRpcError(value) {
|
|
|
199
181
|
&& typeof value.error.message === "string"
|
|
200
182
|
&& value.error.message.trim() !== "";
|
|
201
183
|
}
|
|
202
|
-
function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolContent) {
|
|
184
|
+
function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolContent, onUnrepresented) {
|
|
203
185
|
if (!Array.isArray(value))
|
|
204
186
|
return protocolFailure(value);
|
|
205
187
|
const item = value.find((candidate) => isRecord(candidate) && candidate.task_id === taskId);
|
|
@@ -267,7 +249,7 @@ function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolConten
|
|
|
267
249
|
try {
|
|
268
250
|
return {
|
|
269
251
|
state: "complete",
|
|
270
|
-
content: content
|
|
252
|
+
content: normalizeToolItems(content, normalize, onUnrepresented),
|
|
271
253
|
...(difyTaskId === undefined ? {} : { difyTaskId })
|
|
272
254
|
};
|
|
273
255
|
}
|
|
@@ -303,6 +285,11 @@ async function defaultSleep(milliseconds, signal) {
|
|
|
303
285
|
function defaultContentId() {
|
|
304
286
|
return (BigInt(Date.now()) * 100000n + BigInt(randomInt(100_000))).toString();
|
|
305
287
|
}
|
|
288
|
+
const encodedMediaLists = new Set(["image_urls", "video_urls", "audio_urls", "reference_images", "file_urls"]);
|
|
289
|
+
function encodeMediaLists(arguments_) {
|
|
290
|
+
return Object.fromEntries(Object.entries(arguments_).map(([name, value]) => [name,
|
|
291
|
+
encodedMediaLists.has(name) && Array.isArray(value) ? JSON.stringify(value) : value]));
|
|
292
|
+
}
|
|
306
293
|
export function createToolApiAdapter(dependencies) {
|
|
307
294
|
const createContentId = dependencies.contentIdFactory ?? defaultContentId;
|
|
308
295
|
const sleep = dependencies.sleep ?? defaultSleep;
|
|
@@ -310,6 +297,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
310
297
|
signal.throwIfAborted();
|
|
311
298
|
if (invocation.kind === "canvas")
|
|
312
299
|
throw new RemoteProtocolError({}, undefined, "TOOL_ADAPTER_MISSING");
|
|
300
|
+
dependencies.telemetry.annotate({ execution_protocol: "dify" });
|
|
313
301
|
const managedContentId = contentId(createContentId());
|
|
314
302
|
const resolved = invocation.kind === "direct"
|
|
315
303
|
? { name: invocation.name, arguments: invocation.arguments }
|
|
@@ -343,7 +331,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
343
331
|
method: "tools/call",
|
|
344
332
|
params: {
|
|
345
333
|
name: resolved.name,
|
|
346
|
-
arguments: { ...resolved.arguments, content_id: managedContentId }
|
|
334
|
+
arguments: { ...encodeMediaLists(resolved.arguments), content_id: managedContentId }
|
|
347
335
|
}
|
|
348
336
|
},
|
|
349
337
|
credential: access.credential,
|
|
@@ -367,7 +355,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
367
355
|
let poll;
|
|
368
356
|
try {
|
|
369
357
|
poll = await queryToolResult(dependencies.transport, {
|
|
370
|
-
taskId, credential: access.credential, organizationId: access.organizationId, signal,
|
|
358
|
+
taskId, credential: access.credential, organizationId: access.organizationId, signal, onUnrepresented: dependencies.onUnrepresented,
|
|
371
359
|
onDifyTaskId: id => dependencies.telemetry.annotate({ dify_task_id: id })
|
|
372
360
|
});
|
|
373
361
|
transientFailures = 0;
|
|
@@ -388,8 +376,11 @@ export function createToolApiAdapter(dependencies) {
|
|
|
388
376
|
}
|
|
389
377
|
if (poll.state === "failed")
|
|
390
378
|
throw poll.error;
|
|
391
|
-
if (poll.state === "complete")
|
|
392
|
-
|
|
379
|
+
if (poll.state === "complete") {
|
|
380
|
+
if (input.invocation.kind === "canvas")
|
|
381
|
+
throw new RemoteProtocolError();
|
|
382
|
+
return dependencies.verifyOutput ? dependencies.verifyOutput(poll.content, input.invocation.mediaKind, input) : poll.content;
|
|
383
|
+
}
|
|
393
384
|
await sleep(2_000, signal);
|
|
394
385
|
}
|
|
395
386
|
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export class ToolTaskFailedError extends Error {
|
|
2
|
+
remoteCode;
|
|
3
|
+
remoteBody;
|
|
4
|
+
diagnosticReason;
|
|
5
|
+
imagePixelRequirement;
|
|
6
|
+
constructor(evidence = {}) {
|
|
7
|
+
super("稿定工具任务执行失败。");
|
|
8
|
+
this.name = "ToolTaskFailedError";
|
|
9
|
+
this.remoteCode = evidence.remoteCode;
|
|
10
|
+
this.remoteBody = evidence.remoteBody;
|
|
11
|
+
this.imagePixelRequirement = evidence.imagePixelRequirement;
|
|
12
|
+
this.diagnosticReason = evidence.diagnosticReason;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export class ToolInsufficientCreditsError extends ToolTaskFailedError {
|
|
16
|
+
diagnosticReason = "INSUFFICIENT_CREDITS";
|
|
17
|
+
constructor() {
|
|
18
|
+
super();
|
|
19
|
+
this.name = "ToolInsufficientCreditsError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export class ToolTaskCanceledError extends Error {
|
|
23
|
+
diagnosticReason = "TASK_CANCELED";
|
|
24
|
+
constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
|
|
25
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { concreteMediaType, mediaTypeFromFilename } from "../../platform/media-type.js";
|
|
2
|
+
import { authorizeToolResources } from "./resource-authorizer.js";
|
|
3
|
+
/** Metadata can explain what was returned. Delivering a URL never requires opening it here. */
|
|
4
|
+
export function presentToolContent(content, kind, onMissingMedia) {
|
|
5
|
+
if (!content.some(part => part.type === "resource_link" &&
|
|
6
|
+
(concreteMediaType(part.mimeType) ?? mediaTypeFromFilename(part.name))?.startsWith(kind + "/")))
|
|
7
|
+
onMissingMedia?.(kind);
|
|
8
|
+
return content;
|
|
9
|
+
}
|
|
10
|
+
export function createToolOutputVerifier(authorizer, onMissingMedia) {
|
|
11
|
+
return async (content, kind, { access, signal }) => {
|
|
12
|
+
const authorized = await authorizeToolResources({ content, usage: { model: "" } }, authorizer, access, signal);
|
|
13
|
+
return presentToolContent(authorized.content, kind, onMissingMedia);
|
|
14
|
+
};
|
|
15
|
+
}
|