@insmind/cli 1.9.0 → 2.0.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/dist/bin/insmind-cli.js +32 -25
- package/dist/bin/task-worker.js +4 -1
- package/dist/src/analytics/device.js +2 -2
- package/dist/src/bootstrap/create-cli.js +10 -8
- package/dist/src/bootstrap/create-runtime.js +29 -23
- package/dist/src/bootstrap/run-task-worker.js +7 -2
- package/dist/src/bootstrap/validators.js +15 -6
- package/dist/src/cli/action-binding.js +39 -0
- package/dist/src/cli/agent-commands.js +8 -12
- package/dist/src/cli/dam-commands.js +6 -5
- package/dist/src/cli/editor-commands.js +10 -5
- package/dist/src/cli/errors.js +60 -12
- package/dist/src/cli/host-input.js +34 -0
- package/dist/src/cli/model-commands.js +4 -3
- package/dist/src/cli/observed-errors.js +3 -1
- package/dist/src/cli/tool-commands.js +7 -9
- package/dist/src/contracts/creation-input.js +20 -0
- package/dist/src/features/agent/creative-agent-adapter.js +37 -11
- package/dist/src/features/agent/creative-protocol.js +21 -19
- package/dist/src/features/agent/creative-stream.js +54 -6
- package/dist/src/features/agent/result-reader.js +3 -1
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/auth/access-policy.js +1 -3
- package/dist/src/features/auth/credential-store.js +6 -10
- package/dist/src/features/auth/sso-service.js +28 -10
- package/dist/src/features/auth/state.js +6 -0
- package/dist/src/features/auth/use-cases.js +91 -32
- package/dist/src/features/credits/use-cases.js +1 -1
- package/dist/src/features/dam/asset-projection.js +10 -1
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/file-downloader.js +2 -1
- package/dist/src/features/dam/input.js +23 -0
- package/dist/src/features/dam/use-cases.js +39 -29
- package/dist/src/features/editor/bridge-client.js +1 -1
- package/dist/src/features/editor/use-cases.js +6 -8
- package/dist/src/features/org/use-cases.js +3 -3
- package/dist/src/features/skill/installer.js +24 -22
- package/dist/src/features/task/store.js +31 -17
- package/dist/src/features/task/task-background.js +67 -19
- package/dist/src/features/task/use-cases.js +131 -88
- package/dist/src/features/tool/canvas-media.js +82 -27
- package/dist/src/features/tool/canvas-models.js +21 -4
- package/dist/src/features/tool/canvas-tool-adapter.js +29 -20
- package/dist/src/features/tool/canvas-video.js +2 -4
- package/dist/src/features/tool/dynamic-schema.js +32 -63
- package/dist/src/features/tool/matting-billing.js +38 -26
- package/dist/src/features/tool/mns-catalog-adapter.js +9 -2
- package/dist/src/features/tool/scene-catalog-adapter.js +0 -1
- package/dist/src/features/tool/tool-api-adapter.js +19 -16
- package/dist/src/features/tool/use-cases.js +24 -35
- package/dist/src/platform/file-lock.js +58 -15
- package/dist/src/platform/input-uri.js +105 -0
- package/dist/src/platform/json-input.js +1 -1
- package/dist/src/platform/local-json-file.js +7 -4
- package/dist/src/platform/remote-error-evidence.js +23 -1
- package/dist/src/platform/safe-upload-file.js +24 -4
- package/dist/src/platform/schema-issues.js +18 -0
- package/dist/src/platform/signed-http-transport.js +95 -37
- package/dist/src/platform/text-output.js +55 -13
- package/dist/src/telemetry/failure-summary.js +53 -2
- package/dist/src/telemetry/host-diagnostics.js +95 -0
- package/dist/src/telemetry/invocation.js +107 -23
- package/dist/src/telemetry/process-errors.js +38 -4
- package/dist/src/telemetry/sls-sink.js +71 -26
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +1 -0
- package/skills/insmind-cli/references/editor.md +1 -1
- package/skills/insmind-cli/references/generation-constraints.md +3 -1
- package/skills/insmind-cli/references/tool.md +2 -3
|
@@ -160,12 +160,21 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
160
160
|
const configuration = model.execution.configuration;
|
|
161
161
|
async function quote(quantities) {
|
|
162
162
|
const cost = estimateCanvasCost(model, quantities);
|
|
163
|
-
if (
|
|
164
|
-
|
|
165
|
-
await context.observe?.({ toolUsage: { model: id, cost } });
|
|
163
|
+
if (cost)
|
|
164
|
+
await context.observe?.({ toolUsage: { model: id, cost } });
|
|
166
165
|
}
|
|
167
166
|
const fields = Array.isArray(configuration.fields) ? configuration.fields.filter(record) : [];
|
|
168
167
|
const backend = {};
|
|
168
|
+
const extra = Object.entries(args).filter(([key]) => key !== "model" && !model.parameters.some(field => field.name === key));
|
|
169
|
+
// Dedicated adapters translate public fields; generic fields can travel only on an actual service request.
|
|
170
|
+
function serviceArguments() {
|
|
171
|
+
for (const [key] of extra) {
|
|
172
|
+
if (["content_id", "contentid", "async", "model"].includes(key) || (Object.hasOwn(backend, key) && backend[key] !== args[key])) {
|
|
173
|
+
throw new ToolInputError("managed_argument", "/arguments/" + key);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return { ...Object.fromEntries(extra), ...backend };
|
|
177
|
+
}
|
|
169
178
|
for (const field of fields)
|
|
170
179
|
if (["model", "async"].includes(String(field.key)) && field.default_value !== undefined)
|
|
171
180
|
backend[String(field.key)] = field.default_value;
|
|
@@ -181,15 +190,10 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
181
190
|
const sourceUri = args.video;
|
|
182
191
|
const source = await probe(sourceUri, context.signal);
|
|
183
192
|
const rounded = Math.round(source.duration);
|
|
184
|
-
if (id !== "video-enhance-standard" && (rounded < 2 || rounded > 30)
|
|
185
|
-
|| id === "video-edit-smart" && source.duration > 15)
|
|
186
|
-
throw new ToolInputError("video_duration_unsupported", "/arguments/video");
|
|
187
193
|
const references = args.referenceVideos ?? [];
|
|
188
194
|
let total = source.duration;
|
|
189
195
|
for (const reference of references)
|
|
190
196
|
total += (await probe(reference, context.signal)).duration;
|
|
191
|
-
if (id === "video-edit-smart" && total > 15)
|
|
192
|
-
throw new ToolInputError("reference_video_duration_exceeded", "/arguments/referenceVideos");
|
|
193
197
|
await quote({ time: Math.ceil(source.duration), duration: rounded, video_urls: Math.round(total) });
|
|
194
198
|
async function remote(uri) {
|
|
195
199
|
if (!uri.startsWith("file:"))
|
|
@@ -220,7 +224,7 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
220
224
|
}
|
|
221
225
|
backend.content_id = await contentId(context);
|
|
222
226
|
await pipeline(context, id, "submitted", false, "dify");
|
|
223
|
-
const content = await call(code,
|
|
227
|
+
const content = await call(code, serviceArguments(), context);
|
|
224
228
|
const uri = oneResource(content);
|
|
225
229
|
let output;
|
|
226
230
|
try {
|
|
@@ -243,14 +247,19 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
243
247
|
throw new ToolInputError("matting_billing_contract_unavailable", "/model");
|
|
244
248
|
if (model.cost === undefined || model.cost.minimum !== model.cost.maximum)
|
|
245
249
|
throw new ToolInputError("matting_quote_unavailable", "/model");
|
|
250
|
+
if (extra.length)
|
|
251
|
+
throw new ToolInputError("unmapped_argument", "/arguments/" + extra[0][0]);
|
|
246
252
|
return dependencies.standardMatting(source, context, model.cost.maximum, () => segment(source, context, args.cropToSubject === true));
|
|
247
253
|
}
|
|
248
254
|
if (id === "image-text-edit") {
|
|
249
255
|
const replacements = args.replacements;
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
256
|
+
backend.text = JSON.stringify(replacements.map(({ from, to, ...fields }, index) => {
|
|
257
|
+
for (const key of ["origin", "new"]) {
|
|
258
|
+
if (Object.hasOwn(fields, key))
|
|
259
|
+
throw new ToolInputError("managed_argument", `/arguments/replacements/${index}/${key}`);
|
|
260
|
+
}
|
|
261
|
+
return { ...fields, origin: from, new: to === "" ? "REMOVE_TEXT" : to };
|
|
262
|
+
}));
|
|
254
263
|
}
|
|
255
264
|
if (id === "image-ocr" || id === "image-text-edit") {
|
|
256
265
|
const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).flatten({ background: "white" }).jpeg().toBuffer();
|
|
@@ -262,8 +271,6 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
262
271
|
const info = await sharp(bytes).metadata();
|
|
263
272
|
source = { bytes, width: info.width, height: info.height };
|
|
264
273
|
}
|
|
265
|
-
if (id === "image-layers-smart" && source.width * source.height < 512 * 512)
|
|
266
|
-
throw new ToolInputError("layers_input_too_small", "/arguments/image");
|
|
267
274
|
await quote({ resolution: args.targetLongEdge, max_layers: args.maxLayers });
|
|
268
275
|
let prepared = source.bytes;
|
|
269
276
|
if (selection && id.endsWith("-smart"))
|
|
@@ -291,14 +298,16 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
291
298
|
backend.url = image;
|
|
292
299
|
backend.type = id === "image-layers-smart" ? "seedream" : "codia";
|
|
293
300
|
if (id === "image-layers-smart") {
|
|
294
|
-
|
|
301
|
+
if (args.maxLayers !== undefined)
|
|
302
|
+
backend.max_layers = typeof args.maxLayers === "number" ? String(args.maxLayers) : args.maxLayers;
|
|
295
303
|
const resolutionField = fields.find(field => field.key === "resolution");
|
|
296
304
|
const options = resolutionField?.options;
|
|
297
305
|
const onlyTwoK = resolutionField?.default_value === "2K" && Array.isArray(options)
|
|
298
306
|
&& options.length === 1 && record(options[0]) && options[0].value === "2K";
|
|
299
|
-
|
|
307
|
+
if (args.resolution === undefined)
|
|
308
|
+
backend.resolution = onlyTwoK || source.width * source.height > 1280 * 720 ? "2K" : "1K";
|
|
300
309
|
const field = fields.find(field => field.key === "seedream_model");
|
|
301
|
-
if (field?.default_value !== undefined)
|
|
310
|
+
if (args.seedream_model === undefined && field?.default_value !== undefined)
|
|
302
311
|
backend.seedream_model = nonblank(field.default_value);
|
|
303
312
|
}
|
|
304
313
|
}
|
|
@@ -312,7 +321,7 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
312
321
|
backend.prompt = args.prompt;
|
|
313
322
|
if (selection && id.endsWith("-smart"))
|
|
314
323
|
backend.prompt = `仅处理青色边界标注的区域,移除青色标记。${backend.prompt ?? ""}`;
|
|
315
|
-
if (id === "image-enhance-standard")
|
|
324
|
+
if (id === "image-enhance-standard" && args.targetLongEdge !== undefined)
|
|
316
325
|
backend.resolution = args.targetLongEdge;
|
|
317
326
|
if (Array.isArray(args.referenceImages)) {
|
|
318
327
|
const references = await Promise.all(args.referenceImages.map(async (uri) => {
|
|
@@ -328,7 +337,7 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
328
337
|
if (id === "image-remove-standard")
|
|
329
338
|
backend.contentid = backend.content_id;
|
|
330
339
|
await pipeline(context, id, "submitted", isMatting, protocol, undefined, id === "image-ocr" ? { ocr: { uri: image, width: source.width, height: source.height } } : undefined);
|
|
331
|
-
const content = await call(code,
|
|
340
|
+
const content = await call(code, serviceArguments(), context, protocol);
|
|
332
341
|
if (id === "image-matting-smart") {
|
|
333
342
|
await pipeline(context, id, "segmenting", true, "sync", content);
|
|
334
343
|
const generated = await media.image(oneResource(content), context.signal);
|
|
@@ -49,10 +49,8 @@ export function createCanvasVideo(media) {
|
|
|
49
49
|
const duration = Number(stream?.duration ?? result.format?.duration);
|
|
50
50
|
const width = Number(stream?.width);
|
|
51
51
|
const height = Number(stream?.height);
|
|
52
|
-
const [numerator, denominator] = String(stream?.avg_frame_rate).split("/").map(Number);
|
|
53
|
-
const frameDuration = denominator / numerator;
|
|
54
52
|
if (!stream || !Number.isFinite(duration) || duration <= 0 || !Number.isInteger(width) || width <= 0
|
|
55
|
-
|| !Number.isInteger(height) || height <= 0
|
|
53
|
+
|| !Number.isInteger(height) || height <= 0) {
|
|
56
54
|
throw new ToolInputError("video_metadata_invalid", "/arguments/video");
|
|
57
55
|
}
|
|
58
56
|
const decoded = await run(probe.path, ["-v", "error", "-protocol_whitelist", "file", "-format_whitelist", "mov,matroska,webm",
|
|
@@ -60,7 +58,7 @@ export function createCanvasVideo(media) {
|
|
|
60
58
|
const frames = JSON.parse(decoded.stdout);
|
|
61
59
|
if (!frames.frames?.some(frame => frame.media_type === "video"))
|
|
62
60
|
throw new ToolInputError("video_decode_failed", "/arguments/video");
|
|
63
|
-
return { duration, width, height,
|
|
61
|
+
return { duration, width, height, hasAudio: result.streams.some(stream => stream.codec_type === "audio"), format };
|
|
64
62
|
}
|
|
65
63
|
catch (cause) {
|
|
66
64
|
if (signal.aborted)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
2
2
|
import addFormatsImport, {} from "ajv-formats";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
|
|
4
|
+
import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
|
|
5
5
|
import { ToolInputError } from "./catalog.js";
|
|
6
6
|
function parameterSchema(parameter, includeBounds = false) {
|
|
7
7
|
const common = {
|
|
@@ -88,7 +88,7 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
|
|
|
88
88
|
type: "object",
|
|
89
89
|
properties,
|
|
90
90
|
required: ["model"],
|
|
91
|
-
additionalProperties:
|
|
91
|
+
additionalProperties: true,
|
|
92
92
|
allOf: models.map(model => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
|
|
93
93
|
then: buildModelArgumentsSchema(model) }))
|
|
94
94
|
};
|
|
@@ -115,73 +115,42 @@ export function buildModelArgumentsSchema(model) {
|
|
|
115
115
|
.filter((parameter) => parameter.required)
|
|
116
116
|
.map((parameter) => parameter.name)
|
|
117
117
|
],
|
|
118
|
-
additionalProperties:
|
|
118
|
+
additionalProperties: true
|
|
119
119
|
};
|
|
120
120
|
}
|
|
121
121
|
const ajv = new Ajv2020({ allErrors: true, strict: true });
|
|
122
122
|
const addFormats = addFormatsImport;
|
|
123
123
|
addFormats(ajv);
|
|
124
|
-
|
|
125
|
-
return ajv.compile(buildModelArgumentsSchema(model));
|
|
126
|
-
}
|
|
127
|
-
function controlArgumentsValidator(model) {
|
|
128
|
-
const properties = {};
|
|
129
|
-
for (const parameter of model.parameters) {
|
|
130
|
-
if (parameter.name === "prompt"
|
|
131
|
-
|| parameter.type === "uri"
|
|
132
|
-
|| parameter.type === "uri[]"
|
|
133
|
-
|| (model.execution?.kind === "canvas" && !canvasControlParameterNames.has(parameter.name)))
|
|
134
|
-
continue;
|
|
135
|
-
properties[parameter.name] = buildModelArgumentsSchema(model).properties[parameter.name];
|
|
136
|
-
}
|
|
137
|
-
return ajv.compile({
|
|
138
|
-
type: "object",
|
|
139
|
-
properties,
|
|
140
|
-
required: [],
|
|
141
|
-
additionalProperties: false
|
|
142
|
-
});
|
|
143
|
-
}
|
|
124
|
+
/** Enforce structure that the CLI actually reads or transforms. Business controls go to the service. */
|
|
144
125
|
export function assertModelArguments(model, value) {
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const stepIssues = sliderStepIssues(model, value);
|
|
149
|
-
if (stepIssues.length) {
|
|
150
|
-
throw new ToolInputError("model_parameters", "/arguments", stepIssues);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
function sliderStepIssues(model, value) {
|
|
154
|
-
const issues = [];
|
|
126
|
+
const published = buildModelArgumentsSchema(model);
|
|
127
|
+
const properties = { model: published.properties.model };
|
|
128
|
+
const required = ["model"];
|
|
155
129
|
for (const parameter of model.parameters) {
|
|
156
|
-
if (parameter.
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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;
|
|
130
|
+
if (parameter.type === "uri" || parameter.type === "uri[]") {
|
|
131
|
+
properties[parameter.name] = parameterSchema(parameter);
|
|
132
|
+
if (model.execution?.kind === "canvas" && ["image", "video"].includes(parameter.name))
|
|
133
|
+
required.push(parameter.name);
|
|
167
134
|
}
|
|
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
135
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
136
|
+
if (model.execution?.kind === "canvas") {
|
|
137
|
+
for (const key of ["canvas", "placement", "cropToSubject"]) {
|
|
138
|
+
if (published.properties[key])
|
|
139
|
+
properties[key] = published.properties[key];
|
|
140
|
+
if (published.required.includes(key))
|
|
141
|
+
required.push(key);
|
|
142
|
+
}
|
|
143
|
+
if (model.model === "image-text-edit") {
|
|
144
|
+
properties.replacements = { type: "array", items: { type: "object", required: ["from", "to"],
|
|
145
|
+
properties: { from: { type: "string" }, to: { type: "string" } } } };
|
|
146
|
+
required.push("replacements");
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const schema = { type: "object", properties, required };
|
|
150
|
+
const validate = ajv.compile(schema);
|
|
151
|
+
canonicalizeInputFileUris(value, schema);
|
|
152
|
+
if (!validate(value)) {
|
|
153
|
+
const issues = validationIssues(validate.errors, value, schema);
|
|
154
|
+
throw Object.assign(new ToolInputError("model_parameters", "/arguments", issues), { diagnosticSummary: inputValidationSummary(issues, value, "/arguments") });
|
|
155
|
+
}
|
|
187
156
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { constants, createPublicKey, publicEncrypt, randomBytes, verify } from "node:crypto";
|
|
2
|
+
import { withResponseDiagnostics } from "../../platform/signed-http-transport.js";
|
|
2
3
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
3
4
|
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
4
5
|
import { record } from "./canvas-results.js";
|
|
@@ -25,19 +26,21 @@ export function encryptMattingParameters(text, key = serviceKey) {
|
|
|
25
26
|
export function createMattingRights(dependencies) {
|
|
26
27
|
const { transport } = dependencies;
|
|
27
28
|
return async function rights(path, parameters, context) {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
29
|
+
return withResponseDiagnostics(async (onResponse) => {
|
|
30
|
+
const code = `0.${randomBytes(12).readBigUInt64BE().toString()}`;
|
|
31
|
+
const plaintext = `gaoding?key=${randomBytes(18).toString("base64url")}×tamp=${Date.now()}&verify_code=${code}&${parameters}`;
|
|
32
|
+
const result = await transport.postJson({ path, body: { data: encryptMattingParameters(plaintext, dependencies.key ?? serviceKey) },
|
|
33
|
+
...context.access, signal: context.signal, onResponse });
|
|
34
|
+
if (!record(result))
|
|
35
|
+
throw new RemoteProtocolError();
|
|
36
|
+
if (result.code !== undefined && result.code !== 0 && result.code !== "0")
|
|
37
|
+
throw new ToolTaskFailedError(remoteErrorEvidence(result));
|
|
38
|
+
if (typeof result.export_permit !== "string" || !verify("RSA-SHA256", Buffer.from(code), dependencies.key ?? serviceKey, Buffer.from(result.export_permit, "base64"))
|
|
39
|
+
|| typeof result.used_count !== "number" || !Number.isFinite(result.used_count) || result.used_count < 0) {
|
|
40
|
+
throw new RemoteProtocolError({}, undefined, "MATTING_BILLING_VERIFICATION_FAILED");
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
});
|
|
41
44
|
};
|
|
42
45
|
}
|
|
43
46
|
export function createStandardMatting(dependencies) {
|
|
@@ -49,19 +52,28 @@ export function createStandardMatting(dependencies) {
|
|
|
49
52
|
if (quote.need_deduct !== undefined && typeof quote.need_deduct !== "boolean")
|
|
50
53
|
throw new RemoteProtocolError();
|
|
51
54
|
if (quote.need_deduct === true || quote.need_deduct === undefined && Number(quote.used_count) > 0) {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
55
|
+
await withResponseDiagnostics(async (onResponse) => {
|
|
56
|
+
const balances = await transport.getJson({ path: "/trade/rights-overview", query: { goods_type_enums: "GAODOU" }, ...context.access, signal: context.signal, onResponse });
|
|
57
|
+
if (!Array.isArray(balances))
|
|
58
|
+
throw new RemoteProtocolError();
|
|
59
|
+
const item = balances.find(item => record(item) && item.goods_type_enum === "GAODOU" && item.identifier === "GAODOU");
|
|
60
|
+
if (!record(item))
|
|
61
|
+
throw new RemoteProtocolError();
|
|
62
|
+
const value = (raw) => { if ((typeof raw !== "number" && typeof raw !== "string") || raw === "" || !Number.isFinite(Number(raw)))
|
|
63
|
+
throw new RemoteProtocolError(); return Number(raw); };
|
|
64
|
+
const total = value(item.total), used = value(item.used), pending = value(item.wait);
|
|
65
|
+
const accountAvailable = total - used - pending;
|
|
66
|
+
const memberLimit = item.member_period_limit === undefined || item.member_period_limit === null ? undefined : value(item.member_period_limit);
|
|
67
|
+
const memberUsed = memberLimit === undefined ? undefined : value(item.member_period_used ?? 0);
|
|
68
|
+
const available = memberLimit === undefined ? accountAvailable : Math.min(accountAvailable, memberLimit - memberUsed);
|
|
69
|
+
if (available < Number(quote.used_count))
|
|
70
|
+
throw Object.assign(new ToolInsufficientCreditsError(), {
|
|
71
|
+
diagnosticSummary: { quotaDecisionSource: "cli_precheck", quotaUnit: "gaodou",
|
|
72
|
+
quotaLimitScope: memberLimit !== undefined && memberLimit - memberUsed < accountAvailable ? "member_period" : "account",
|
|
73
|
+
quotaTotal: total, quotaUsed: used, quotaPending: pending, quotaAvailable: available, quotaRequired: Number(quote.used_count),
|
|
74
|
+
...(memberLimit === undefined ? {} : { quotaMemberLimit: memberLimit, quotaMemberUsed: memberUsed }) }
|
|
75
|
+
});
|
|
76
|
+
});
|
|
65
77
|
}
|
|
66
78
|
const repositories = await recordTransport.getJson({ path: "/tb-dam/repositories", ...context.access, signal: context.signal });
|
|
67
79
|
if (!Array.isArray(repositories))
|
|
@@ -187,8 +187,15 @@ function normalizeModel(value, scenes, english = false) {
|
|
|
187
187
|
.filter((item) => item !== undefined);
|
|
188
188
|
const description = cleanText(model.description);
|
|
189
189
|
const usageDescription = cleanText(model.tool_description);
|
|
190
|
-
|
|
191
|
-
|
|
190
|
+
let mimeTypes = model.output_mime_types;
|
|
191
|
+
if (typeof mimeTypes === "string") {
|
|
192
|
+
try {
|
|
193
|
+
mimeTypes = JSON.parse(mimeTypes);
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
mimeTypes = undefined;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
192
199
|
const outputMediaTypes = Array.isArray(mimeTypes)
|
|
193
200
|
? mimeTypes.map(text).filter((item) => item !== undefined) : [];
|
|
194
201
|
const costs = activeSkus
|
|
@@ -15,7 +15,6 @@ export function createSceneCatalogAdapter(dependencies) {
|
|
|
15
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
16
|
if (cost === undefined) {
|
|
17
17
|
catalog.warnings.push(dependencies.english ? `Current pricing is unavailable for ${binding[1]}.` : `${binding[1]} 的当前报价不可用。`);
|
|
18
|
-
continue;
|
|
19
18
|
}
|
|
20
19
|
const raw = { tool: binding[0], model: code, title: binding[4], sceneSort: 0, modelSort: 0, parameters: [],
|
|
21
20
|
...(cost === undefined ? {} : { cost: { unit: "gaodou", minimum: cost, maximum: cost } }),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isInterruption } from "../../platform/interruption.js";
|
|
2
2
|
import { randomInt } from "node:crypto";
|
|
3
3
|
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
-
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
4
|
+
import { RemoteRequestError, withResponseDiagnostics } from "../../platform/signed-http-transport.js";
|
|
5
5
|
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
6
6
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
7
7
|
const MAX_JAVA_LONG = 9223372036854775807n;
|
|
@@ -109,7 +109,7 @@ export function normalizeToolContent(value) {
|
|
|
109
109
|
if (value.type !== "resource" || !isRecord(value.resource)) {
|
|
110
110
|
return protocolFailure(value);
|
|
111
111
|
}
|
|
112
|
-
if ("blob" in value.resource || "text" in value.resource)
|
|
112
|
+
if ("blob" in value.resource || ("text" in value.resource && value.resource.text !== ""))
|
|
113
113
|
return protocolFailure(value);
|
|
114
114
|
if (typeof value.resource.uri !== "string" || value.resource.uri.trim() === "") {
|
|
115
115
|
return protocolFailure(value);
|
|
@@ -150,18 +150,21 @@ export class ToolTaskCanceledError extends Error {
|
|
|
150
150
|
constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
|
|
151
151
|
}
|
|
152
152
|
export async function queryToolResult(transport, request) {
|
|
153
|
+
let difyTaskId;
|
|
153
154
|
try {
|
|
154
|
-
return
|
|
155
|
+
return await safePost(transport, {
|
|
155
156
|
credential: request.credential,
|
|
156
157
|
...(request.organizationId === undefined ? {} : { organizationId: request.organizationId }),
|
|
157
158
|
signal: request.signal,
|
|
158
159
|
path: "/gdesign/tool/v1/dify/process/batch",
|
|
159
160
|
body: { task_ids: [request.taskId] }
|
|
160
|
-
}
|
|
161
|
+
}, value => pollResult(value, request.taskId, id => { difyTaskId = id; request.onDifyTaskId?.(id); }, request.normalize));
|
|
161
162
|
}
|
|
162
163
|
catch (error) {
|
|
163
164
|
if (isInterruption(error, request.signal) || error instanceof ToolTaskCanceledError)
|
|
164
165
|
throw error;
|
|
166
|
+
if (error instanceof ToolTaskFailedError)
|
|
167
|
+
return failedPoll(error, difyTaskId);
|
|
165
168
|
const evidence = error instanceof RemoteRequestError || error instanceof RemoteProtocolError
|
|
166
169
|
? { ...(error.remoteCode === undefined ? {} : { remoteCode: error.remoteCode }),
|
|
167
170
|
...(error.remoteBody === undefined ? {} : { remoteBody: error.remoteBody }) } : {};
|
|
@@ -232,15 +235,15 @@ function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolConten
|
|
|
232
235
|
if (typeof difyTaskId === "string")
|
|
233
236
|
onDifyTaskId?.(difyTaskId);
|
|
234
237
|
if (Object.prototype.hasOwnProperty.call(inner, "error")) {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
+
if (isJsonRpcError(inner))
|
|
239
|
+
throw new ToolTaskFailedError(remoteErrorEvidence(inner));
|
|
240
|
+
throw new RemoteProtocolError(remoteErrorEvidence(inner));
|
|
238
241
|
}
|
|
239
242
|
if (!isRecord(inner.result)) {
|
|
240
243
|
return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
|
|
241
244
|
}
|
|
242
245
|
if (inner.result.isError === true) {
|
|
243
|
-
|
|
246
|
+
throw new ToolTaskFailedError(remoteErrorEvidence(inner));
|
|
244
247
|
}
|
|
245
248
|
if (inner.result.isError !== false) {
|
|
246
249
|
return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
|
|
@@ -274,14 +277,14 @@ function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolConten
|
|
|
274
277
|
throw error;
|
|
275
278
|
}
|
|
276
279
|
}
|
|
277
|
-
async function safePost(transport, request) {
|
|
280
|
+
async function safePost(transport, request, interpret) {
|
|
278
281
|
try {
|
|
279
|
-
return await transport.postJson(request);
|
|
282
|
+
return await withResponseDiagnostics(async (onResponse) => interpret(await transport.postJson({ ...request, onResponse })));
|
|
280
283
|
}
|
|
281
284
|
catch (error) {
|
|
282
285
|
if (isInterruption(error, request.signal))
|
|
283
286
|
throw request.signal.reason;
|
|
284
|
-
if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
|
|
287
|
+
if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError || error instanceof ToolTaskCanceledError)
|
|
285
288
|
throw error;
|
|
286
289
|
throw new RemoteRequestError(undefined, false, {}, error);
|
|
287
290
|
}
|
|
@@ -311,7 +314,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
311
314
|
const resolved = invocation.kind === "direct"
|
|
312
315
|
? { name: invocation.name, arguments: invocation.arguments }
|
|
313
316
|
: await dependencies.telemetry.stage("intent", async () => {
|
|
314
|
-
const intent =
|
|
317
|
+
const intent = await safePost(dependencies.transport, {
|
|
315
318
|
path: "/ai-agent/v1/tool-intent",
|
|
316
319
|
body: {
|
|
317
320
|
prompt: invocation.prompt,
|
|
@@ -321,17 +324,17 @@ export function createToolApiAdapter(dependencies) {
|
|
|
321
324
|
credential: access.credential,
|
|
322
325
|
organizationId: access.organizationId,
|
|
323
326
|
signal
|
|
324
|
-
})
|
|
327
|
+
}, parseIntent);
|
|
325
328
|
return {
|
|
326
329
|
...intent,
|
|
327
|
-
arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
|
|
330
|
+
arguments: { ...withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters), ...invocation.explicitArguments }
|
|
328
331
|
};
|
|
329
332
|
});
|
|
330
333
|
signal.throwIfAborted();
|
|
331
334
|
await observe?.({ submissionStarted: true });
|
|
332
335
|
const taskId = await dependencies.telemetry.stage("submit", async () => {
|
|
333
336
|
dependencies.telemetry.annotate({ content_id: managedContentId });
|
|
334
|
-
return
|
|
337
|
+
return safePost(dependencies.transport, {
|
|
335
338
|
path: "/gdesign/tool/v1/dify/call_async",
|
|
336
339
|
...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
|
|
337
340
|
body: {
|
|
@@ -346,7 +349,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
346
349
|
credential: access.credential,
|
|
347
350
|
organizationId: access.organizationId,
|
|
348
351
|
signal
|
|
349
|
-
})
|
|
352
|
+
}, submittedTask);
|
|
350
353
|
});
|
|
351
354
|
await observe?.({ remoteTaskId: taskId });
|
|
352
355
|
dependencies.telemetry.annotate({ task_id: taskId });
|
|
@@ -93,47 +93,35 @@ export function createToolUseCases(dependencies) {
|
|
|
93
93
|
return { invocation: { kind: "canvas", model, arguments: input.arguments }, usage };
|
|
94
94
|
}
|
|
95
95
|
const prompt = [];
|
|
96
|
-
|
|
97
|
-
|
|
96
|
+
if (Object.hasOwn(parameters, "content_id"))
|
|
97
|
+
throw new ToolInputError("managed_argument", "/arguments/content_id");
|
|
98
|
+
const requestParameters = { ...parameters };
|
|
99
|
+
const directArguments = { ...parameters };
|
|
98
100
|
const prepare = async () => {
|
|
101
|
+
if (typeof parameters.prompt === "string") {
|
|
102
|
+
prompt.push({ type: "text", content: parameters.prompt });
|
|
103
|
+
delete requestParameters.prompt;
|
|
104
|
+
}
|
|
99
105
|
for (const parameter of model.parameters) {
|
|
100
|
-
|
|
101
|
-
const value = input.arguments[parameter.name];
|
|
102
|
-
if (value === undefined)
|
|
103
|
-
continue;
|
|
104
|
-
if (parameter.type === "string") {
|
|
105
|
-
if (parameter.name === "prompt") {
|
|
106
|
-
prompt.push({ type: "text", content: value });
|
|
107
|
-
directArguments[parameter.name] = value;
|
|
108
|
-
}
|
|
109
|
-
else {
|
|
110
|
-
requestParameters[parameter.name] = value;
|
|
111
|
-
directArguments[parameter.name] = value;
|
|
112
|
-
}
|
|
106
|
+
if (parameter.type !== "uri" && parameter.type !== "uri[]")
|
|
113
107
|
continue;
|
|
114
|
-
|
|
115
|
-
if (
|
|
116
|
-
requestParameters[parameter.name] = value;
|
|
117
|
-
directArguments[parameter.name] = value;
|
|
108
|
+
const value = parameters[parameter.name];
|
|
109
|
+
if (value === undefined)
|
|
118
110
|
continue;
|
|
119
|
-
|
|
120
|
-
const
|
|
121
|
-
for (const mediaUrl of values) {
|
|
111
|
+
const urls = [];
|
|
112
|
+
for (const url of (Array.isArray(value) ? value : [value])) {
|
|
122
113
|
signal.throwIfAborted();
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
name: parameter.name
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
else {
|
|
134
|
-
prompt.push(remoteMedia(mediaUrl, parameter.name));
|
|
135
|
-
}
|
|
114
|
+
const media = url.startsWith("file:")
|
|
115
|
+
? await dependencies.uploader.upload({ url }, access, signal).then(upload => ({
|
|
116
|
+
type: "media", url: upload.url, mime: upload.mediaType, name: parameter.name
|
|
117
|
+
}))
|
|
118
|
+
: remoteMedia(url, parameter.name);
|
|
119
|
+
prompt.push(media);
|
|
120
|
+
urls.push(media.url);
|
|
136
121
|
}
|
|
122
|
+
// Preserve scalar/array semantics after converting local files to service URLs.
|
|
123
|
+
directArguments[parameter.name] = parameter.type === "uri[]" ? urls : urls[0];
|
|
124
|
+
delete requestParameters[parameter.name];
|
|
137
125
|
}
|
|
138
126
|
};
|
|
139
127
|
const hasLocalMedia = model.parameters.some((parameter) => {
|
|
@@ -158,6 +146,7 @@ export function createToolUseCases(dependencies) {
|
|
|
158
146
|
model: model.model,
|
|
159
147
|
prompt,
|
|
160
148
|
parameters: requestParameters,
|
|
149
|
+
explicitArguments: directArguments,
|
|
161
150
|
optionalMediaParameters: model.parameters
|
|
162
151
|
.filter((parameter) => ((parameter.type === "uri" || parameter.type === "uri[]")
|
|
163
152
|
&& !parameter.required))
|