@insmind/cli 2.1.5 → 2.1.7
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/dist/shared/model-catalog/fields.js +114 -0
- package/dist/shared/model-catalog/index.js +3 -0
- package/dist/shared/model-catalog/inline-schema.js +72 -0
- package/dist/shared/model-catalog/schema.js +80 -0
- package/dist/src/bootstrap/create-runtime.js +37 -17
- package/dist/src/cli/errors.js +2 -2
- package/dist/src/cli/task-commands.js +1 -1
- package/dist/src/features/auth/sso-service.js +1 -1
- package/dist/src/features/task/use-cases.js +9 -2
- package/dist/src/features/tool/canvas-copy.js +2 -2
- package/dist/src/features/tool/canvas-matting.js +37 -70
- package/dist/src/features/tool/canvas-media.js +69 -63
- package/dist/src/features/tool/canvas-models.js +3 -3
- package/dist/src/features/tool/canvas-recovery.js +17 -5
- package/dist/src/features/tool/canvas-results.js +13 -43
- package/dist/src/features/tool/canvas-tool-adapter.js +81 -63
- package/dist/src/features/tool/dynamic-schema.js +5 -90
- package/dist/src/features/tool/matting-billing.js +3 -73
- package/dist/src/features/tool/mns-catalog-adapter.js +1 -98
- package/dist/src/features/tool/resource-authorizer.js +10 -0
- package/dist/src/features/tool/tool-api-adapter.js +1 -1
- package/dist/src/features/tool/tool-errors.js +0 -7
- package/dist/src/platform/http-user-agent.js +8 -0
- package/package.json +7 -4
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
export const mediaListParameterNames = new Set([
|
|
2
|
+
"image_urls",
|
|
3
|
+
"reference_images",
|
|
4
|
+
"file_urls",
|
|
5
|
+
"video_urls",
|
|
6
|
+
"audio_urls"
|
|
7
|
+
]);
|
|
8
|
+
function record(value) {
|
|
9
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
10
|
+
? value
|
|
11
|
+
: undefined;
|
|
12
|
+
}
|
|
13
|
+
function text(value) {
|
|
14
|
+
if (typeof value !== "string")
|
|
15
|
+
return undefined;
|
|
16
|
+
const trimmed = value.trim();
|
|
17
|
+
return trimmed || undefined;
|
|
18
|
+
}
|
|
19
|
+
function requiredText(value) {
|
|
20
|
+
const result = text(value);
|
|
21
|
+
if (result === undefined)
|
|
22
|
+
throw new Error("invalid string");
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
function machineText(value) {
|
|
26
|
+
if (typeof value !== "string" || !value.trim())
|
|
27
|
+
throw new Error("invalid machine value");
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
export function cleanCatalogText(value) {
|
|
31
|
+
const result = text(value);
|
|
32
|
+
if (result === undefined)
|
|
33
|
+
return undefined;
|
|
34
|
+
return text(result.replace(/\{icon:\{[^{}]*\}\}/g, ""));
|
|
35
|
+
}
|
|
36
|
+
export function normalizeParameter(value, optionalControls) {
|
|
37
|
+
const field = record(value);
|
|
38
|
+
if (field === undefined)
|
|
39
|
+
throw new Error("invalid parameter");
|
|
40
|
+
if (field.is_open !== true)
|
|
41
|
+
return undefined;
|
|
42
|
+
const name = machineText(field.key);
|
|
43
|
+
const sourceType = requiredText(field.type);
|
|
44
|
+
const type = sourceType === "SLIDER"
|
|
45
|
+
? "number"
|
|
46
|
+
: mediaListParameterNames.has(name)
|
|
47
|
+
? "uri[]"
|
|
48
|
+
: name === "start_frame" || name === "end_frame" || sourceType === "IMAGE" || sourceType === "VIDEO"
|
|
49
|
+
? "uri"
|
|
50
|
+
: sourceType === "NUMBER"
|
|
51
|
+
? "number"
|
|
52
|
+
: sourceType === "TEXT" || sourceType === "INPUT" || sourceType === "SELECT"
|
|
53
|
+
? "string"
|
|
54
|
+
: undefined;
|
|
55
|
+
if (type === undefined) {
|
|
56
|
+
if (field.required === true)
|
|
57
|
+
throw new Error("unsupported required parameter");
|
|
58
|
+
const description = text(field.description) ?? text(field.label);
|
|
59
|
+
Object.defineProperty(optionalControls, name, { value: description ? { description } : {}, enumerable: true, configurable: true, writable: true });
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
let minimum;
|
|
63
|
+
let maximum;
|
|
64
|
+
let step;
|
|
65
|
+
if (sourceType === "SLIDER" || sourceType === "NUMBER") {
|
|
66
|
+
const declaredStep = sourceType === "SLIDER" ? field.step : undefined;
|
|
67
|
+
if ([field.min, field.max, declaredStep].some(value => value !== undefined
|
|
68
|
+
&& (typeof value !== "number" || !Number.isFinite(value)))
|
|
69
|
+
|| typeof field.min === "number" && typeof field.max === "number" && field.min > field.max
|
|
70
|
+
|| typeof declaredStep === "number" && declaredStep <= 0) {
|
|
71
|
+
throw new Error("invalid numeric constraints");
|
|
72
|
+
}
|
|
73
|
+
minimum = field.min;
|
|
74
|
+
maximum = field.max;
|
|
75
|
+
step = declaredStep;
|
|
76
|
+
}
|
|
77
|
+
let options;
|
|
78
|
+
if (sourceType === "SELECT") {
|
|
79
|
+
if (!Array.isArray(field.options))
|
|
80
|
+
throw new Error("invalid options");
|
|
81
|
+
options = field.options.map((value) => {
|
|
82
|
+
const option = record(value);
|
|
83
|
+
if (option === undefined)
|
|
84
|
+
throw new Error("invalid option");
|
|
85
|
+
const label = text(option.label);
|
|
86
|
+
return {
|
|
87
|
+
value: machineText(option.value),
|
|
88
|
+
...(label === undefined ? {} : { label })
|
|
89
|
+
};
|
|
90
|
+
});
|
|
91
|
+
if (options.length === 0)
|
|
92
|
+
throw new Error("empty options");
|
|
93
|
+
}
|
|
94
|
+
const rawDescription = text(field.description) ?? text(field.label);
|
|
95
|
+
// MNS documents the service's wire encoding. Public URI-list inputs are native arrays.
|
|
96
|
+
const description = type === "uri[]" ? rawDescription
|
|
97
|
+
?.replace(/JSON 数组的字符串/gu, "原生 JSON 数组")
|
|
98
|
+
.replace(/(?:例如|如)\s*(?:\\*["“])?\[.*?\](?:\\*["”])*/gu, '例如 ["https://example.com/media.png"]') : rawDescription;
|
|
99
|
+
const defaultValue = field.default_value;
|
|
100
|
+
const hasDefault = defaultValue !== undefined;
|
|
101
|
+
return {
|
|
102
|
+
name,
|
|
103
|
+
type,
|
|
104
|
+
required: field.required === true,
|
|
105
|
+
...(minimum === undefined ? {} : { minimum }),
|
|
106
|
+
...(maximum === undefined ? {} : { maximum }),
|
|
107
|
+
...(step === undefined ? {} : { step }),
|
|
108
|
+
...(description === undefined ? {} : { description }),
|
|
109
|
+
...(hasDefault
|
|
110
|
+
? { default: defaultValue }
|
|
111
|
+
: {}),
|
|
112
|
+
...(options === undefined ? {} : { options })
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const schemaMaps = new Set(["properties", "patternProperties", "dependentSchemas"]);
|
|
2
|
+
const schemaLists = new Set(["allOf", "anyOf", "oneOf"]);
|
|
3
|
+
const schemaValues = new Set(["additionalProperties", "unevaluatedProperties", "propertyNames", "items",
|
|
4
|
+
"contains", "not", "if", "then", "else", "unevaluatedItems", "contentSchema"]);
|
|
5
|
+
function schema(value) {
|
|
6
|
+
if (typeof value === "boolean")
|
|
7
|
+
return value;
|
|
8
|
+
if (value && typeof value === "object" && !Array.isArray(value))
|
|
9
|
+
return value;
|
|
10
|
+
throw new Error("Expected a JSON Schema object or boolean");
|
|
11
|
+
}
|
|
12
|
+
/** Expand local JSON pointers without relaxing validation or interpreting example data as schemas. */
|
|
13
|
+
export function inlineSchemaReferences(input) {
|
|
14
|
+
function resolve(ref) {
|
|
15
|
+
if (ref === "#")
|
|
16
|
+
return input;
|
|
17
|
+
if (!ref.startsWith("#/"))
|
|
18
|
+
throw new Error("Only local JSON pointer references can be expanded: " + ref);
|
|
19
|
+
let value = input;
|
|
20
|
+
for (const part of decodeURIComponent(ref.slice(2)).split("/")) {
|
|
21
|
+
const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
22
|
+
if (!value || typeof value !== "object" || !Object.hasOwn(value, key))
|
|
23
|
+
throw new Error("Unresolved schema reference: " + ref);
|
|
24
|
+
value = value[key];
|
|
25
|
+
}
|
|
26
|
+
return schema(value);
|
|
27
|
+
}
|
|
28
|
+
function visit(value, stack) {
|
|
29
|
+
if (typeof value === "boolean")
|
|
30
|
+
return value;
|
|
31
|
+
if ("$dynamicRef" in value || "$recursiveRef" in value || "$recursiveAnchor" in value || "$anchor" in value || "$dynamicAnchor" in value)
|
|
32
|
+
throw new Error("Dynamic or anchored schema references require a separate adapter");
|
|
33
|
+
if ("prefixItems" in value || Array.isArray(value.items))
|
|
34
|
+
throw new Error("Tuple schemas cannot be represented by this host schema adapter");
|
|
35
|
+
const entries = [];
|
|
36
|
+
for (const [key, child] of Object.entries(value)) {
|
|
37
|
+
if (["$ref", "$defs", "definitions"].includes(key))
|
|
38
|
+
continue;
|
|
39
|
+
if (key === "$id" && value !== input)
|
|
40
|
+
throw new Error("Nested schema resource identifiers cannot be inlined");
|
|
41
|
+
if (schemaMaps.has(key)) {
|
|
42
|
+
const fields = schema(child);
|
|
43
|
+
if (typeof fields === "boolean")
|
|
44
|
+
throw new Error("Expected a schema map: " + key);
|
|
45
|
+
entries.push([key, Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, visit(schema(field), stack)]))]);
|
|
46
|
+
}
|
|
47
|
+
else if (schemaLists.has(key)) {
|
|
48
|
+
if (!Array.isArray(child))
|
|
49
|
+
throw new Error("Expected a schema list: " + key);
|
|
50
|
+
entries.push([key, child.map(item => visit(schema(item), stack))]);
|
|
51
|
+
}
|
|
52
|
+
else if (schemaValues.has(key))
|
|
53
|
+
entries.push([key, visit(schema(child), stack)]);
|
|
54
|
+
else
|
|
55
|
+
entries.push([key, structuredClone(child)]);
|
|
56
|
+
}
|
|
57
|
+
const siblings = Object.fromEntries(entries);
|
|
58
|
+
if (value.$ref === undefined)
|
|
59
|
+
return siblings;
|
|
60
|
+
if (typeof value.$ref !== "string")
|
|
61
|
+
throw new Error("Expected a string schema reference");
|
|
62
|
+
if (stack.includes(value.$ref))
|
|
63
|
+
throw new Error("Circular schema reference: " + value.$ref);
|
|
64
|
+
const target = visit(resolve(value.$ref), [...stack, value.$ref]);
|
|
65
|
+
// A $ref and its sibling keywords both apply in 2020-12. Object spread alone
|
|
66
|
+
// would overwrite duplicate constraints, such as two different enum lists.
|
|
67
|
+
if (!Object.keys(siblings).length)
|
|
68
|
+
return target;
|
|
69
|
+
return { ...siblings, allOf: [...(siblings.allOf ?? []), target] };
|
|
70
|
+
}
|
|
71
|
+
return visit(input, []);
|
|
72
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
export function parameterSchema(parameter, includeBounds = false) {
|
|
2
|
+
const common = {
|
|
3
|
+
...(parameter.description === undefined ? {} : { description: parameter.description }),
|
|
4
|
+
...(parameter.default === undefined ? {} : { default: parameter.default })
|
|
5
|
+
};
|
|
6
|
+
if (parameter.type === "uri")
|
|
7
|
+
return { type: "string", format: "uri", ...common };
|
|
8
|
+
if (parameter.type === "uri[]") {
|
|
9
|
+
return { type: "array", items: { type: "string", format: "uri" }, ...common };
|
|
10
|
+
}
|
|
11
|
+
if (parameter.type === "number" || parameter.type === "integer") {
|
|
12
|
+
return {
|
|
13
|
+
type: parameter.type,
|
|
14
|
+
...(includeBounds && parameter.minimum !== undefined
|
|
15
|
+
? { minimum: parameter.minimum }
|
|
16
|
+
: {}),
|
|
17
|
+
...(includeBounds && parameter.maximum !== undefined
|
|
18
|
+
? { maximum: parameter.maximum }
|
|
19
|
+
: {}),
|
|
20
|
+
...common
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
if (["boolean", "object", "array"].includes(parameter.type)) {
|
|
24
|
+
return { type: parameter.type, ...common };
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
type: "string",
|
|
28
|
+
...(parameter.options === undefined
|
|
29
|
+
? {}
|
|
30
|
+
: { enum: parameter.options.map((option) => option.value) }),
|
|
31
|
+
...common
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function buildToolArgumentsSchema(models, modelDescription = "要调用的模型机器标识;取值来自 model list。") {
|
|
35
|
+
const properties = {
|
|
36
|
+
model: {
|
|
37
|
+
type: "string",
|
|
38
|
+
enum: models.map(model => model.model),
|
|
39
|
+
description: modelDescription
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const branches = models.map(model => model.schema);
|
|
43
|
+
const fieldNames = new Set(branches.flatMap(branch => Object.keys(branch.properties)));
|
|
44
|
+
for (const name of fieldNames) {
|
|
45
|
+
if (name === "model")
|
|
46
|
+
continue;
|
|
47
|
+
const fields = branches.flatMap(branch => Object.hasOwn(branch.properties, name) ? [branch.properties[name]] : []);
|
|
48
|
+
const field = fields[0];
|
|
49
|
+
// An open sibling may accept a completely different value at this key.
|
|
50
|
+
// Its presence in the index must not restrict the selected model.
|
|
51
|
+
if (branches.some(branch => !Object.hasOwn(branch.properties, name) && branch.additionalProperties)) {
|
|
52
|
+
Object.defineProperty(properties, name, { value: field.description ? { description: field.description } : {}, enumerable: true });
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
const variants = [...new Map(fields.map(item => [JSON.stringify(item), item])).values()];
|
|
56
|
+
Object.defineProperty(properties, name, { value: variants.length === 1 ? field : { anyOf: variants }, enumerable: true });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
type: "object",
|
|
61
|
+
properties,
|
|
62
|
+
required: ["model"],
|
|
63
|
+
additionalProperties: true,
|
|
64
|
+
allOf: models.map((model, i) => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
|
|
65
|
+
then: branches[i] }))
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export function buildParameterModelSchema(model, managed = ["content_id", "contentid"]) {
|
|
69
|
+
const properties = {
|
|
70
|
+
...Object.fromEntries(Object.entries(model.optionalControls ?? {}).filter(([key]) => !managed.includes(key))),
|
|
71
|
+
model: { type: "string", const: model.model, description: "要调用的模型机器标识。" }
|
|
72
|
+
};
|
|
73
|
+
for (const parameter of model.parameters) {
|
|
74
|
+
Object.defineProperty(properties, parameter.name, { value: parameterSchema(parameter, true),
|
|
75
|
+
enumerable: true, writable: true, configurable: true });
|
|
76
|
+
}
|
|
77
|
+
return { type: "object", properties,
|
|
78
|
+
required: ["model", ...model.parameters.filter(parameter => parameter.required).map(parameter => parameter.name)],
|
|
79
|
+
additionalProperties: true, propertyNames: { not: { enum: [...managed] } } };
|
|
80
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { httpUserAgent } from "../platform/http-user-agent.js";
|
|
1
2
|
import { canvasModelBindings } from "../features/tool/canvas-models.js";
|
|
2
3
|
import { createWindAnalytics } from "../analytics/wind.js";
|
|
3
4
|
import { taskScope } from "../features/task/store.js";
|
|
@@ -43,7 +44,6 @@ import { createCanvasToolAdapter } from "../features/tool/canvas-tool-adapter.js
|
|
|
43
44
|
import { recoverCanvasTool } from "../features/tool/canvas-recovery.js";
|
|
44
45
|
import { authorizeToolResources } from "../features/tool/resource-authorizer.js";
|
|
45
46
|
import { createCanvasMedia } from "../features/tool/canvas-media.js";
|
|
46
|
-
import { createStandardMatting } from "../features/tool/matting-billing.js";
|
|
47
47
|
import { createToolUseCases } from "../features/tool/use-cases.js";
|
|
48
48
|
import { createOrgUseCases } from "../features/org/use-cases.js";
|
|
49
49
|
import { createOrgService } from "../features/org/org-service.js";
|
|
@@ -86,12 +86,16 @@ export function createProductionRuntime(options = {}) {
|
|
|
86
86
|
...(environmentLocale === undefined ? {} : { environment: environmentLocale }),
|
|
87
87
|
...(localSystemLocale === undefined ? {} : { system: localSystemLocale })
|
|
88
88
|
});
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
"
|
|
92
|
-
"
|
|
93
|
-
|
|
94
|
-
|
|
89
|
+
const userAgent = httpUserAgent(product.commandName, primarySkill.version);
|
|
90
|
+
const businessHeaders = {
|
|
91
|
+
"User-Agent": userAgent,
|
|
92
|
+
...(product.id === "insmind" ? {
|
|
93
|
+
"X-Locale": locale.locale,
|
|
94
|
+
"X-Language": locale.language,
|
|
95
|
+
"X-Market": locale.market,
|
|
96
|
+
"X-Legal-Region": locale.legalRegion
|
|
97
|
+
} : {})
|
|
98
|
+
};
|
|
95
99
|
const now = options.now ?? (() => new Date());
|
|
96
100
|
const telemetryEnvironment = options.telemetryEnvironment ?? (env.CLI_TELEMETRY_ENV === "test" ? "test" : "production");
|
|
97
101
|
const host = hostTelemetryContext(env);
|
|
@@ -149,35 +153,35 @@ export function createProductionRuntime(options = {}) {
|
|
|
149
153
|
fetch,
|
|
150
154
|
now,
|
|
151
155
|
traceparent: () => telemetry.traceparent(),
|
|
152
|
-
|
|
156
|
+
businessHeaders
|
|
153
157
|
});
|
|
154
158
|
const creditsTransport = createSignedHttpTransport({
|
|
155
159
|
baseUrl: endpoints.creditsApi,
|
|
156
160
|
fetch,
|
|
157
161
|
now,
|
|
158
162
|
traceparent: () => telemetry.traceparent(),
|
|
159
|
-
|
|
163
|
+
businessHeaders
|
|
160
164
|
});
|
|
161
165
|
const agentTransport = createSignedHttpTransport({
|
|
162
166
|
baseUrl: endpoints.agentApi,
|
|
163
167
|
fetch,
|
|
164
168
|
now,
|
|
165
169
|
traceparent: () => telemetry.traceparent(),
|
|
166
|
-
|
|
170
|
+
businessHeaders
|
|
167
171
|
});
|
|
168
172
|
const mnsTransport = createSignedHttpTransport({
|
|
169
173
|
baseUrl: endpoints.mnsApi,
|
|
170
174
|
fetch,
|
|
171
175
|
now,
|
|
172
176
|
traceparent: () => telemetry.traceparent(),
|
|
173
|
-
|
|
177
|
+
businessHeaders
|
|
174
178
|
});
|
|
175
179
|
const toolTransport = createSignedHttpTransport({
|
|
176
180
|
baseUrl: endpoints.toolApi,
|
|
177
181
|
fetch,
|
|
178
182
|
now,
|
|
179
183
|
traceparent: () => telemetry.traceparent(),
|
|
180
|
-
|
|
184
|
+
businessHeaders
|
|
181
185
|
});
|
|
182
186
|
const damTransport = createSignedHttpTransport({
|
|
183
187
|
baseUrl: endpoints.damApi,
|
|
@@ -185,11 +189,12 @@ export function createProductionRuntime(options = {}) {
|
|
|
185
189
|
now,
|
|
186
190
|
channelId: "32",
|
|
187
191
|
traceparent: () => telemetry.traceparent(),
|
|
188
|
-
|
|
192
|
+
businessHeaders
|
|
189
193
|
});
|
|
190
194
|
const sso = createSsoService({
|
|
191
195
|
ssoApi: endpoints.ssoApi,
|
|
192
196
|
clientId: product.deviceClientId,
|
|
197
|
+
userAgent,
|
|
193
198
|
traceparent: () => telemetry.traceparent(),
|
|
194
199
|
fetch,
|
|
195
200
|
now
|
|
@@ -309,7 +314,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
309
314
|
now,
|
|
310
315
|
channelId: "32",
|
|
311
316
|
traceparent: () => telemetry.traceparent(),
|
|
312
|
-
|
|
317
|
+
businessHeaders
|
|
313
318
|
}) });
|
|
314
319
|
const onPartialResourceFailure = (error) => {
|
|
315
320
|
if (!(error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
|
|
@@ -373,8 +378,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
373
378
|
const verifyToolOutput = createToolOutputVerifier(resourceAuthorizer, onMissingMedia);
|
|
374
379
|
const canvasTools = createCanvasToolAdapter({
|
|
375
380
|
transport: toolTransport, recordTransport: damTransport, resourceAuthorizer, telemetry, media: canvasMedia, onMissingMedia, onUnrepresented, english: product.id === "insmind",
|
|
376
|
-
fallback: createToolApiAdapter({ transport: toolTransport, telemetry, onUnrepresented, verifyOutput: verifyToolOutput })
|
|
377
|
-
standardMatting: createStandardMatting({ transport: toolTransport, recordTransport: damTransport, media: canvasMedia() })
|
|
381
|
+
fallback: createToolApiAdapter({ transport: toolTransport, telemetry, onUnrepresented, verifyOutput: verifyToolOutput })
|
|
378
382
|
});
|
|
379
383
|
const taskFailureNote = (error, operation = telemetry.creationContext().operation) => {
|
|
380
384
|
const outcome = mapCliError(error, { aborted: false, product, operation, failureStage: telemetry.failureStage(error) });
|
|
@@ -408,6 +412,21 @@ export function createProductionRuntime(options = {}) {
|
|
|
408
412
|
text,
|
|
409
413
|
failureNote: taskFailureNote,
|
|
410
414
|
recovery: {
|
|
415
|
+
async checkpointPartial(progress, state, signal) {
|
|
416
|
+
const pipeline = progress.toolPipeline;
|
|
417
|
+
if (pipeline?.model !== "image-matting-smart" || !pipeline.requiresFinalization || !pipeline.partialContent || !progress.toolUsage)
|
|
418
|
+
return;
|
|
419
|
+
const partial = toolOutputWithBillingUnit({ content: pipeline.partialContent, usage: progress.toolUsage }, product.billingUnit);
|
|
420
|
+
try {
|
|
421
|
+
return await authorizeTaskResult(partial, state, signal);
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
signal.throwIfAborted();
|
|
425
|
+
if (!onPartialResourceFailure(error))
|
|
426
|
+
throw error;
|
|
427
|
+
return partial;
|
|
428
|
+
}
|
|
429
|
+
},
|
|
411
430
|
async authorize(result, state, signal, progress) {
|
|
412
431
|
const authorized = await authorizeTaskResult(result, state, signal);
|
|
413
432
|
const tool = progress?.generation?.tool ?? canvasModelBindings.find(binding => binding[1] === progress?.toolPipeline?.model)?.[0];
|
|
@@ -449,7 +468,8 @@ export function createProductionRuntime(options = {}) {
|
|
|
449
468
|
try {
|
|
450
469
|
recovered = await telemetry.stage("task.query", () => recoverCanvasTool(progress, {
|
|
451
470
|
access: { credential: state.credential, organizationId: state.organization.id }, signal
|
|
452
|
-
}, { transport: toolTransport, onMissingMedia, onUnrepresented,
|
|
471
|
+
}, { transport: toolTransport, onMissingMedia, onUnrepresented,
|
|
472
|
+
onDifyTaskId: id => telemetry.annotate({ dify_task_id: id }) }));
|
|
453
473
|
}
|
|
454
474
|
catch (error) {
|
|
455
475
|
if (!(error instanceof ToolTaskFailedError) && !(error instanceof ToolTaskCanceledError))
|
package/dist/src/cli/errors.js
CHANGED
|
@@ -10,7 +10,7 @@ import { SsoRequestError } from "../features/auth/sso-service.js";
|
|
|
10
10
|
import { AuthorizedAccountContextMissingError, BrowserOpenError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
|
|
11
11
|
import { AgentInputError } from "../features/agent/use-cases.js";
|
|
12
12
|
import { ToolInputError } from "../features/tool/catalog.js";
|
|
13
|
-
import { ToolTaskFailedError, ToolTaskCanceledError
|
|
13
|
+
import { ToolTaskFailedError, ToolTaskCanceledError } from "../features/tool/tool-errors.js";
|
|
14
14
|
import { AgentAuditRejectedError } from "../features/agent/creative-protocol.js";
|
|
15
15
|
import { isContentReviewRejection } from "../features/task/creation-refusal.js";
|
|
16
16
|
import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
|
|
@@ -209,7 +209,7 @@ function mapBaseCliError(error, options) {
|
|
|
209
209
|
return failure("USAGE_ERROR", "Invalid command or arguments. See --help.", 2);
|
|
210
210
|
return failure("USAGE_ERROR", "命令或参数无效,请查看 --help。", 2);
|
|
211
211
|
}
|
|
212
|
-
if (
|
|
212
|
+
if (options.product?.id !== "insmind" && options.operation === "tool.call" && isInsufficientCreditsError(error)) {
|
|
213
213
|
return failure("INSUFFICIENT_CREDITS", text("当前可用额度不足,本次生成未能完成。", "Available credits are insufficient; this creation could not complete."), 1, refusalSteps);
|
|
214
214
|
}
|
|
215
215
|
if (isContentReviewRejection(error, { product: options.product?.id ?? "gaoding", operation: options.operation })) {
|
|
@@ -36,7 +36,7 @@ export function registerTaskCommands(program, runtime) {
|
|
|
36
36
|
text("completed 时读取 result。tool.call 返回 content,agent.send 返回 message.parts。重发成品时原样复制本次结果里的完整链接,包括查询参数和签名。若本轮返回文本或补充问题,向用户转述或提问。", "On completed, read result.content for tool.call or result.message.parts for agent.send. When resending an asset, copy the complete link from this result, including its query parameters and signature. Relay text or questions to the user when that is what the turn returned."),
|
|
37
37
|
text("若稿定资源链接已过期,再查原 taskId 可刷新结构化资源的下载授权。第三方链接和正文按原样返回,CLI 不能替第三方续签。", "If a Gaoding file link has expired, query the original taskId for fresh access to structured assets. Third-party URLs and prose are returned unchanged; the CLI cannot renew another provider's signature."),
|
|
38
38
|
text("failed 时向用户说明 note 中的原因。只有错误明确说明尚未派发,才按提示修正并再调用。服务已明确拒绝时,换模型也会发起一次新创作,须有用户补充的需求或另做一次的授权。受理后状态为 unknown 时保留原 ID 核查。", "On failed, relay the cause from note. Correct and retry an input when the error confirms the request was never dispatched. After a definite service refusal, switching models starts another creation and requires a revised request or authorization from the user. On unknown after acceptance, keep and check the original ID."),
|
|
39
|
-
text("unknown
|
|
39
|
+
text("unknown 表示无法确认本次执行终态。failed 或 unknown 中的 partialResult 可交付为中间产物,例如智能抠图的重绘图;请同时说明尚未完成的步骤。", "unknown means completion cannot be confirmed. A partialResult on failed or unknown can be shared as an intermediate result, such as a smart cutout redraw. Explain which step remains incomplete."),
|
|
40
40
|
text("读取本地状态不请求组织绑定;查询远端进度或获取下载授权仍需联网授权。查询请求失败不代表生成失败,可用原 taskId 重查。", "Local status reads do not bind the organization. Remote progress and download authorization still require network access. A failed query does not mean generation failed; query the same taskId again."),
|
|
41
41
|
text("查询得到完整结果但最终缓存保存失败时仍返回结果和退出码 0;请保留 stderr 警告所指的输出,后续可能无法恢复。", "A complete result is delivered with exit code 0 if only final cache persistence fails; keep the output as warned on stderr because later recovery may be unavailable."),
|
|
42
42
|
text("最终错误为 stderr 中的 JSON error 对象;stderr 也可能有进度和警告,中断不代表远端任务取消。", "The final error is a JSON error object on stderr, which may also contain progress and warnings. Interruption does not mean the remote task was cancelled."),
|
|
@@ -93,7 +93,7 @@ export function createSsoService(options) {
|
|
|
93
93
|
try {
|
|
94
94
|
const response = await options.fetch(url, {
|
|
95
95
|
method,
|
|
96
|
-
headers: { Accept: "application/json", ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
|
|
96
|
+
headers: { Accept: "application/json", ...(options.userAgent ? { "User-Agent": options.userAgent } : {}), ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
|
|
97
97
|
signal: AbortSignal.any([
|
|
98
98
|
signal,
|
|
99
99
|
timeoutSignal
|
|
@@ -444,11 +444,18 @@ export function createTaskUseCases(dependencies) {
|
|
|
444
444
|
await usageWarning(id, record.progress.agentUsageModelMissing === true, record.progress.agentUsageAmountMissing === true);
|
|
445
445
|
return result;
|
|
446
446
|
}
|
|
447
|
+
const { checkpointPartial } = dependencies.recovery;
|
|
448
|
+
const withFailedPartialResult = async (task) => {
|
|
449
|
+
if (task.state !== "failed" || !checkpointPartial)
|
|
450
|
+
return task;
|
|
451
|
+
const partialResult = await stage("task.authorize", () => checkpointPartial(record.progress, state, signal));
|
|
452
|
+
return partialResult ? { ...task, partialResult } : task;
|
|
453
|
+
};
|
|
447
454
|
const task = summary(record);
|
|
448
455
|
if (task.state === "failed" || (task.state === "running" && !record.progress.detached)) {
|
|
449
456
|
if (record.telemetry?.steps.some(item => item.event.step === "result_received" && item.event.outcome === "failure"))
|
|
450
457
|
pendingOutput = { scope, record, rejected: true };
|
|
451
|
-
return task;
|
|
458
|
+
return withFailedPartialResult(task);
|
|
452
459
|
}
|
|
453
460
|
let recoveredFromCache = false;
|
|
454
461
|
const { failure, usageModelMissing, usageAmountMissing, ...recovered } = await stage("task.recover", async () => {
|
|
@@ -509,7 +516,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
509
516
|
pendingOutput = { scope, record };
|
|
510
517
|
if (result.result ?? result.partialResult)
|
|
511
518
|
await usageWarning(id, record.progress.agentUsageModelMissing === true, record.progress.agentUsageAmountMissing === true);
|
|
512
|
-
return result;
|
|
519
|
+
return withFailedPartialResult(result);
|
|
513
520
|
},
|
|
514
521
|
async workerStopped(state, id, error, reportedByWorker) {
|
|
515
522
|
const scope = taskScope(state);
|
|
@@ -12,8 +12,8 @@ const copy = {
|
|
|
12
12
|
"image-expand-smart": ["Smart image expansion", "Place the source at natural size and expand its surroundings. Output uses the target aspect ratio; pixel dimensions follow the live resolution setting. Source details can change."],
|
|
13
13
|
"image-text-edit": ["Image text replacement", "replacements match complete original text. An empty to deletes it. Repeated text cannot be targeted by occurrence; actual text and layout are determined by the returned image."],
|
|
14
14
|
"image-ocr": ["Image text recognition", "Returns an embedded application/json resource: image{uri,width,height}, blocks[{bbox:[left,top,right,bottom],category,text?}]. Coordinates use the returned recognition image's top-left origin in pixels."],
|
|
15
|
-
"image-layers-layout": ["Layout decomposition", "For separating layout elements such as poster headlines, body text and background. Fits the source within 3000×3000 pixels without enlargement. Returns native template JSON and
|
|
16
|
-
"image-layers-smart": ["Smart layer decomposition", "For separating objects in a photo from each other and the background, such as a product and surrounding props. Fits the source within 3000×3000 pixels without enlargement; the service requires width × height of at least 262144 total pixels (512×512), not a 512-pixel minimum for each edge. Returns native template JSON and
|
|
15
|
+
"image-layers-layout": ["Layout decomposition", "For separating layout elements such as poster headlines, body text and background. Fits the source within 3000×3000 pixels without enlargement. Returns native template JSON and any accompanying service notes, not PSD. Editability depends on the returned layers; fonts may be substituted. Use a discovered Editor import capability to open the template."],
|
|
16
|
+
"image-layers-smart": ["Smart layer decomposition", "For separating objects in a photo from each other and the background, such as a product and surrounding props. Fits the source within 3000×3000 pixels without enlargement; the service requires width × height of at least 262144 total pixels (512×512), not a 512-pixel minimum for each edge. Returns native template JSON and any accompanying service notes, not PSD or word-by-word OCR. maxLayers is an upper bound. Pricing uses current remote metered components."],
|
|
17
17
|
"image-vectorize": ["Image to SVG", "Returns an SVG resource. Shapes, colors and details may be reconstructed; actual vector contents are determined by the returned file."],
|
|
18
18
|
"video-edit-smart": ["Smart video edit", "Duration and ratio come from the actual source. Reference videos including the source total at most 15 seconds. audioEnabled controls audio presence, not preservation of the original sound."],
|
|
19
19
|
"video-enhance-standard": ["Standard video upscale", "Uses ceil(actual seconds) for billing and requests preservation of the source video. Actual duration, visuals and soundtrack are determined by the returned video."],
|