@insmind/cli 1.9.1 → 2.1.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/README.md +5 -0
- package/contracts/operations/credits.get/input.schema.json +8 -0
- package/contracts/operations/credits.get/output.schema.json +92 -0
- package/contracts/operations/credits.usage.get/input.schema.json +17 -0
- package/contracts/operations/credits.usage.get/output.schema.json +46 -0
- package/contracts/operations/credits.usage.list/input.schema.json +27 -0
- package/contracts/operations/credits.usage.list/output.schema.json +135 -0
- package/dist/bin/insmind-cli.js +2 -2
- package/dist/src/bootstrap/create-cli.js +28 -24
- package/dist/src/bootstrap/create-runtime.js +31 -18
- package/dist/src/bootstrap/run-task-worker.js +2 -1
- package/dist/src/bootstrap/validators.js +7 -2
- package/dist/src/cli/action-binding.js +42 -13
- package/dist/src/cli/agent-commands.js +8 -12
- package/dist/src/cli/credits-command.js +127 -16
- package/dist/src/cli/dam-commands.js +3 -2
- package/dist/src/cli/editor-commands.js +10 -5
- package/dist/src/cli/host-input.js +34 -0
- package/dist/src/cli/model-commands.js +4 -3
- package/dist/src/cli/presenter.js +4 -0
- package/dist/src/cli/tool-commands.js +7 -9
- package/dist/src/cli/update-command.js +24 -1
- package/dist/src/contracts/creation-input.js +20 -0
- package/dist/src/features/agent/creative-protocol.js +12 -14
- 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/sso-service.js +6 -4
- package/dist/src/features/auth/use-cases.js +2 -1
- package/dist/src/features/credits/amount.js +51 -0
- package/dist/src/features/credits/response.js +11 -0
- package/dist/src/features/credits/use-cases.js +174 -31
- package/dist/src/features/dam/file-downloader.js +2 -1
- package/dist/src/features/dam/use-cases.js +7 -7
- 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 +26 -12
- package/dist/src/features/task/use-cases.js +97 -82
- 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 +29 -64
- 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 +2 -2
- package/dist/src/features/tool/use-cases.js +24 -35
- package/dist/src/features/update/check-schema.js +17 -0
- package/dist/src/features/update/host-receipt.js +30 -0
- package/dist/src/features/update/notice-output.js +30 -0
- package/dist/src/features/update/update-lock.js +80 -0
- package/dist/src/features/update/update-notification.js +129 -240
- package/dist/src/platform/json-input.js +1 -1
- package/dist/src/platform/safe-upload-file.js +6 -0
- package/dist/src/platform/signature.js +3 -1
- package/dist/src/platform/signed-http-transport.js +34 -32
- package/dist/src/telemetry/host-diagnostics.js +2 -2
- package/dist/src/telemetry/invocation.js +87 -24
- package/dist/src/telemetry/process-errors.js +36 -3
- package/dist/src/telemetry/sls-sink.js +7 -10
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +2 -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
- package/skills/insmind-cli/references/update.md +2 -0
|
@@ -77,55 +77,67 @@ export function createTaskUseCases(dependencies) {
|
|
|
77
77
|
telemetry?.annotate({ warning_codes: ["AGENT_USAGE_MODEL_MISSING"] });
|
|
78
78
|
await warn("task.usage_warning", text("已保留创作结果和服务端确认的实际费用;部分计费明细缺少模型标识,未推断模型或费用。请勿重复提交创作。", "The creation result and confirmed actual charges are retained. Some charge details have no model identifier; no model or fee was inferred. Do not submit the creation again."));
|
|
79
79
|
}
|
|
80
|
-
|
|
80
|
+
// Persist the first observation before enqueue. A later reader retries only unacknowledged facts.
|
|
81
|
+
async function enqueuePending(scope, record) {
|
|
82
|
+
for (const item of record.telemetry?.steps ?? []) {
|
|
83
|
+
if (item.enqueued || !await telemetry?.emit(item.event))
|
|
84
|
+
continue;
|
|
85
|
+
item.enqueued = true;
|
|
86
|
+
try {
|
|
87
|
+
await dependencies.store.update(scope, record.task.taskId, stored => {
|
|
88
|
+
const existing = stored.telemetry?.steps.find(row => row.event.step === item.event.step);
|
|
89
|
+
if (existing)
|
|
90
|
+
existing.enqueued = true;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
catch { /* The queue already has the stable key. A later read may enqueue it again. */ }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async function fact(scope, record, step, at, outcome = "success", error) {
|
|
81
97
|
if (!telemetry || !record.telemetry)
|
|
82
98
|
return;
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
99
|
+
const current = telemetry.creationContext();
|
|
100
|
+
const { parameters, ...origin } = record.telemetry.context;
|
|
101
|
+
const creating = current.operation === origin.operation;
|
|
102
|
+
const event = { ...origin, event_name: "command_step", step, outcome,
|
|
103
|
+
command_kind: "creation", mode: "execute", process_role: current.process_role, occurred_at_ms: at,
|
|
104
|
+
record_seq: step === "request_sent" ? 2 : step === "result_received" ? 3 : 4,
|
|
105
|
+
...(step === "request_sent" && creating && current.tool_name ? { tool_name: current.tool_name } : {}),
|
|
106
|
+
...(step === "request_sent" && creating && current.model_id ? { model_id: current.model_id } : {}),
|
|
107
|
+
...(creating && current.content_id ? { content_id: current.content_id } : {}),
|
|
108
|
+
...(record.progress.remoteTaskId ? { task_id: record.progress.remoteTaskId } : {}),
|
|
109
|
+
...(creating && current.dify_task_id ? { dify_task_id: current.dify_task_id } : {}),
|
|
110
|
+
...(step === "request_sent" && (current.parameters ?? parameters) ? { parameters: current.parameters ?? parameters } : {}),
|
|
111
|
+
...(error === undefined ? {} : telemetry.taskFailure(error)),
|
|
112
|
+
...(step !== "request_sent" && record.task.result ? { result_types: resultTypes(record.task.result) } : {}) };
|
|
113
|
+
function observe(stored) {
|
|
114
|
+
const facts = stored.telemetry;
|
|
115
|
+
if (!facts)
|
|
96
116
|
return;
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
117
|
+
for (const item of record.telemetry?.steps ?? []) {
|
|
118
|
+
if (!facts.steps.some(saved => saved.event.step === item.event.step))
|
|
119
|
+
facts.steps.push(item);
|
|
120
|
+
}
|
|
121
|
+
if (facts.steps.some(row => row.event.step === step))
|
|
122
|
+
return;
|
|
123
|
+
if (step === "result_received" && !facts.steps.some(row => row.event.step === "request_sent"))
|
|
124
|
+
return;
|
|
125
|
+
if (step === "delivered" && !facts.steps.some(row => row.event.step === "result_received" && row.event.outcome === outcome))
|
|
126
|
+
return;
|
|
127
|
+
if (step === "request_sent") {
|
|
128
|
+
facts.context = { ...origin, ...(event.content_id ? { content_id: event.content_id } : {}), ...(event.tool_name ? { tool_name: event.tool_name } : {}), ...(event.model_id ? { model_id: event.model_id } : {}) };
|
|
129
|
+
}
|
|
130
|
+
facts.steps.push({ event, enqueued: false });
|
|
131
|
+
}
|
|
105
132
|
try {
|
|
106
|
-
const updated = await
|
|
107
|
-
stored.telemetry ??= { context };
|
|
108
|
-
const states = stored.telemetry.states ??= [];
|
|
109
|
-
// A stale caller cannot overwrite the first immutable revision.
|
|
110
|
-
event = make(states);
|
|
111
|
-
if (event && !states.some(e => e.task_revision === event.task_revision))
|
|
112
|
-
states.push(event);
|
|
113
|
-
stored.telemetry.context = context;
|
|
114
|
-
}));
|
|
133
|
+
const updated = await dependencies.store.update(scope, record.task.taskId, observe);
|
|
115
134
|
if (updated.telemetry)
|
|
116
135
|
record.telemetry = updated.telemetry;
|
|
117
|
-
writeConfirmed = true;
|
|
118
136
|
}
|
|
119
137
|
catch {
|
|
120
|
-
|
|
121
|
-
event = make(states);
|
|
122
|
-
if (event && !states.some(e => e.task_revision === event.task_revision))
|
|
123
|
-
states.push(event);
|
|
124
|
-
}
|
|
125
|
-
if (event) {
|
|
126
|
-
telemetry.annotate({ task_state_revision: event.task_revision, task_state_write_confirmed: writeConfirmed });
|
|
127
|
-
await telemetry.emit(event);
|
|
138
|
+
observe(record);
|
|
128
139
|
}
|
|
140
|
+
await enqueuePending(scope, record);
|
|
129
141
|
}
|
|
130
142
|
function summary(record) {
|
|
131
143
|
const { result: _result, partialResult: _partial, ...task } = record.task;
|
|
@@ -146,9 +158,9 @@ export function createTaskUseCases(dependencies) {
|
|
|
146
158
|
};
|
|
147
159
|
if (telemetry) {
|
|
148
160
|
telemetry.annotate({ cli_task_id: record.task.taskId, execution_mode: input.executionMode ?? "sync", result_state: "running" });
|
|
149
|
-
record.telemetry = { context: { ...telemetry.creationContext(), operation: input.operation,
|
|
161
|
+
record.telemetry = { steps: [], context: { ...(input.origin ?? telemetry.creationContext()), operation: input.operation,
|
|
150
162
|
cli_task_id: record.task.taskId, execution_mode: input.executionMode ?? "sync",
|
|
151
|
-
...(dependencies.creationVersion ? { cli_version: dependencies.creationVersion } : {}),
|
|
163
|
+
...(dependencies.creationVersion && !input.origin ? { cli_version: dependencies.creationVersion } : {}),
|
|
152
164
|
...(input.state.account ? { account_id: input.state.account.id } : {}), organization_id: input.state.organization.id } };
|
|
153
165
|
}
|
|
154
166
|
// Wind belongs to execution; result queries never call it.
|
|
@@ -230,7 +242,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
230
242
|
const result = await input.run(async (progress) => {
|
|
231
243
|
if (progress.dispatchedAt !== undefined) {
|
|
232
244
|
dispatched = true;
|
|
233
|
-
await fact(scope, record, "
|
|
245
|
+
await fact(scope, record, "request_sent", progress.dispatchedAt);
|
|
234
246
|
await analyticsFact("started");
|
|
235
247
|
return;
|
|
236
248
|
}
|
|
@@ -258,7 +270,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
258
270
|
await stage("task.validate", async () => { finish(record, result); });
|
|
259
271
|
telemetry?.annotate({ result_state: record.task.state });
|
|
260
272
|
if (record.task.state === "completed") {
|
|
261
|
-
await fact(scope, record, "
|
|
273
|
+
await fact(scope, record, "result_received", dependencies.now().getTime());
|
|
262
274
|
await analyticsFact("completed");
|
|
263
275
|
}
|
|
264
276
|
try {
|
|
@@ -299,8 +311,11 @@ export function createTaskUseCases(dependencies) {
|
|
|
299
311
|
if (detail && diagnostic !== "LOCAL_WAIT_INTERRUPTED")
|
|
300
312
|
record.task.note = redactSensitiveText(detail);
|
|
301
313
|
telemetry?.annotate({ result_state: record.task.state });
|
|
302
|
-
if (dispatched &&
|
|
303
|
-
await fact(scope, record, "
|
|
314
|
+
if (dispatched && record.task.state === "failed") {
|
|
315
|
+
await fact(scope, record, "result_received", dependencies.now().getTime(), "failure", error);
|
|
316
|
+
if (input.executionMode !== "async")
|
|
317
|
+
pendingOutput = { scope, record, rejected: true, error };
|
|
318
|
+
}
|
|
304
319
|
await stage("task.persist", save).catch(() => undefined);
|
|
305
320
|
if (error instanceof TaskStoreError && error.context)
|
|
306
321
|
error.context.result_state = record.task.state;
|
|
@@ -336,16 +351,9 @@ export function createTaskUseCases(dependencies) {
|
|
|
336
351
|
let record = await stage("task.read", () => dependencies.store.read(scope, id));
|
|
337
352
|
if (!record)
|
|
338
353
|
throw new TaskNotFoundError(text(`当前身份中没有该任务。请执行 ${commandName} task list 查找。`, `No task was found in the current identity context. Use ${commandName} task list to find it.`));
|
|
339
|
-
if (
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
if (!reason)
|
|
343
|
-
return;
|
|
344
|
-
stored.failureCorrection = { reason, correctedAt: dependencies.now().toISOString(),
|
|
345
|
-
previousRevision: stored.telemetry?.states?.at(-1)?.task_revision };
|
|
346
|
-
stored.task = { ...stored.task, state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.") };
|
|
347
|
-
}));
|
|
348
|
-
}
|
|
354
|
+
if (record.telemetry)
|
|
355
|
+
telemetry?.annotate({ creation_trace_id: record.telemetry.context.trace_id });
|
|
356
|
+
await enqueuePending(scope, record);
|
|
349
357
|
record = withoutResourceKeys(record);
|
|
350
358
|
telemetry?.annotate({ diagnostic_summary: {
|
|
351
359
|
...(record.progress.contextId ? { agentContextId: record.progress.contextId } : {}),
|
|
@@ -359,8 +367,11 @@ export function createTaskUseCases(dependencies) {
|
|
|
359
367
|
return result;
|
|
360
368
|
}
|
|
361
369
|
const task = summary(record);
|
|
362
|
-
if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
|
|
370
|
+
if (task.state === "failed" || (task.state === "running" && !record.progress.detached)) {
|
|
371
|
+
if (record.telemetry?.steps.some(item => item.event.step === "result_received" && item.event.outcome === "failure"))
|
|
372
|
+
pendingOutput = { scope, record, rejected: true };
|
|
363
373
|
return task;
|
|
374
|
+
}
|
|
364
375
|
const { failure, usageModelMissing, ...recovered } = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
|
|
365
376
|
if (usageModelMissing)
|
|
366
377
|
record.progress.agentUsageModelMissing = true;
|
|
@@ -369,18 +380,23 @@ export function createTaskUseCases(dependencies) {
|
|
|
369
380
|
if (result.state === "unknown" && task.note) {
|
|
370
381
|
result.note = [...new Set([task.note, recovered.note].filter(Boolean))].join(" ");
|
|
371
382
|
}
|
|
372
|
-
if (result.state === "completed" && result.result) {
|
|
373
|
-
await stage("task.validate", async () => { dependencies.validateResult?.(result.result); });
|
|
374
|
-
}
|
|
375
|
-
if (result.state === "completed" || result.state === "failed") {
|
|
376
|
-
record.task = withoutResourceKeys(result);
|
|
377
|
-
await fact(scope, record, result.state === "completed" ? "success" : "failed", dependencies.now().getTime(), failure);
|
|
378
|
-
}
|
|
379
|
-
telemetry?.annotate({ result_state: result.state });
|
|
380
|
-
// Store merging protects terminal results and facts against stale heartbeats.
|
|
381
383
|
if (result.state === "completed" || result.state === "failed") {
|
|
384
|
+
await stage("task.validate", async () => {
|
|
385
|
+
if (result.state === "completed") {
|
|
386
|
+
if (!result.result)
|
|
387
|
+
throw new RemoteProtocolError({}, undefined, "TASK_RESULT_MISSING");
|
|
388
|
+
dependencies.validateResult?.(result.result);
|
|
389
|
+
}
|
|
390
|
+
else if (!failure) {
|
|
391
|
+
throw new RemoteProtocolError({}, undefined, "TASK_FAILURE_EVIDENCE_MISSING");
|
|
392
|
+
}
|
|
393
|
+
});
|
|
382
394
|
result.updatedAt = dependencies.now().toISOString();
|
|
383
395
|
record.task = withoutResourceKeys(result);
|
|
396
|
+
await fact(scope, record, "result_received", dependencies.now().getTime(), result.state === "completed" ? "success" : "failure", failure);
|
|
397
|
+
if (result.state === "failed")
|
|
398
|
+
pendingOutput = { scope, record, rejected: true };
|
|
399
|
+
// Store merging protects terminal results and facts against stale heartbeats.
|
|
384
400
|
try {
|
|
385
401
|
await stage("task.persist", () => dependencies.store.write(scope, record));
|
|
386
402
|
}
|
|
@@ -390,30 +406,29 @@ export function createTaskUseCases(dependencies) {
|
|
|
390
406
|
await cacheWarning(id);
|
|
391
407
|
}
|
|
392
408
|
}
|
|
409
|
+
telemetry?.annotate({ result_state: result.state });
|
|
393
410
|
if (result.state === "completed" && result.result)
|
|
394
411
|
pendingOutput = { scope, record };
|
|
395
412
|
if (result.result ?? result.partialResult)
|
|
396
413
|
await usageWarning(id, record.progress.agentUsageModelMissing === true);
|
|
397
414
|
return result;
|
|
398
415
|
},
|
|
399
|
-
async
|
|
416
|
+
async workerStopped(state, id, error, reportedByWorker) {
|
|
417
|
+
const scope = taskScope(state);
|
|
418
|
+
const record = await dependencies.store.read(scope, id);
|
|
419
|
+
if (!record?.telemetry || record.telemetry.context.trace_id !== telemetry?.traceId)
|
|
420
|
+
return;
|
|
421
|
+
for (const { event } of record.telemetry.steps)
|
|
422
|
+
telemetry.observeStep(event.step);
|
|
423
|
+
if (reportedByWorker && record.telemetry.steps.some(({ event }) => event.step === "result_received" && event.outcome === "failure")) {
|
|
424
|
+
pendingOutput = { scope, record, rejected: true, error };
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
async outputCompleted(error) {
|
|
400
428
|
const output = pendingOutput;
|
|
401
429
|
pendingOutput = undefined;
|
|
402
|
-
if (output)
|
|
403
|
-
await fact(output.scope, output.record, "
|
|
430
|
+
if (output && (error === undefined || error === output.error))
|
|
431
|
+
await fact(output.scope, output.record, "delivered", dependencies.now().getTime(), output.rejected ? "failure" : "success");
|
|
404
432
|
}
|
|
405
433
|
};
|
|
406
434
|
}
|
|
407
|
-
function recoverableFalseFailure(record) {
|
|
408
|
-
if (record.task.state !== "failed" || record.task.result)
|
|
409
|
-
return;
|
|
410
|
-
const terminal = record.telemetry?.states?.findLast(event => ["failed", "success", "completed"].includes(event.result_state));
|
|
411
|
-
if (terminal?.result_state !== "failed")
|
|
412
|
-
return;
|
|
413
|
-
if (terminal.diagnostic_reason === "LOCAL_WAIT_INTERRUPTED")
|
|
414
|
-
return "LOCAL_WAIT_INTERRUPTED";
|
|
415
|
-
if (record.task.operation === "tool.call" && (terminal.diagnostic_reason === "TASK_QUERY_FAILED"
|
|
416
|
-
|| terminal.failure_stage === "task.query" && terminal.remote_error_code === "12020704"))
|
|
417
|
-
return "TASK_QUERY_FAILED";
|
|
418
|
-
return undefined;
|
|
419
|
-
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { englishCanvasCopy } from "./canvas-copy.js";
|
|
2
2
|
import { canvasPricingDescription } from "./canvas-pricing.js";
|
|
3
3
|
import { contractDocument } from "../../contracts/schema.js";
|
|
4
|
+
import { ToolInputError } from "./catalog.js";
|
|
4
5
|
/** Service protocol bindings, not a local inventory of available models. MNS supplies availability. */
|
|
5
6
|
export const canvasModelBindings = [
|
|
6
7
|
["image.edit", "image-edit-standard", "canvas-quick-image-edit", "canvas-image-edit", "标准改图"],
|
|
@@ -29,13 +30,29 @@ const parameterAliases = {
|
|
|
29
30
|
"image-layers-smart": { maxLayers: "max_layers" }
|
|
30
31
|
};
|
|
31
32
|
export function canvasRemoteControlArguments(model, value) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
33
|
+
const parameters = new Map();
|
|
34
|
+
for (const [name, argument] of Object.entries(value)) {
|
|
35
|
+
const aliases = parameterAliases[model];
|
|
36
|
+
const key = aliases && Object.hasOwn(aliases, name) ? aliases[name] : name;
|
|
37
|
+
const remoteValue = key === "max_layers" && typeof argument === "number" ? String(argument) : argument;
|
|
38
|
+
if (parameters.has(key) && parameters.get(key) !== remoteValue) {
|
|
39
|
+
throw new ToolInputError("conflicting_arguments", "/arguments/" + name);
|
|
40
|
+
}
|
|
41
|
+
parameters.set(key, remoteValue);
|
|
42
|
+
}
|
|
43
|
+
return Object.fromEntries(parameters);
|
|
36
44
|
}
|
|
37
45
|
export function canvasInputSchema(id, fields) {
|
|
38
46
|
const schema = contractDocument(`tool.call/models/${id}.schema.json`);
|
|
47
|
+
schema.additionalProperties = id !== "image-matting-standard";
|
|
48
|
+
if (id === "image-text-edit") {
|
|
49
|
+
const edits = schema.properties.replacements;
|
|
50
|
+
delete edits.minItems;
|
|
51
|
+
edits.items.additionalProperties = true;
|
|
52
|
+
const from = edits.items.properties.from;
|
|
53
|
+
delete from.minLength;
|
|
54
|
+
delete from.pattern;
|
|
55
|
+
}
|
|
39
56
|
// Schema supplies the stable roles and nesting. Only executable controls are read from current MNS metadata.
|
|
40
57
|
for (const field of fields) {
|
|
41
58
|
const publicName = Object.entries(parameterAliases[id] ?? {}).find(([, remote]) => remote === field.name)?.[0] ?? field.name;
|
|
@@ -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,6 +1,5 @@
|
|
|
1
1
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
2
2
|
import addFormatsImport, {} from "ajv-formats";
|
|
3
|
-
import { canvasControlParameterNames } from "./canvas-models.js";
|
|
4
3
|
import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
|
|
5
4
|
import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
|
|
6
5
|
import { ToolInputError } from "./catalog.js";
|
|
@@ -89,7 +88,7 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
|
|
|
89
88
|
type: "object",
|
|
90
89
|
properties,
|
|
91
90
|
required: ["model"],
|
|
92
|
-
additionalProperties:
|
|
91
|
+
additionalProperties: true,
|
|
93
92
|
allOf: models.map(model => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
|
|
94
93
|
then: buildModelArgumentsSchema(model) }))
|
|
95
94
|
};
|
|
@@ -116,76 +115,42 @@ export function buildModelArgumentsSchema(model) {
|
|
|
116
115
|
.filter((parameter) => parameter.required)
|
|
117
116
|
.map((parameter) => parameter.name)
|
|
118
117
|
],
|
|
119
|
-
additionalProperties:
|
|
118
|
+
additionalProperties: true
|
|
120
119
|
};
|
|
121
120
|
}
|
|
122
121
|
const ajv = new Ajv2020({ allErrors: true, strict: true });
|
|
123
122
|
const addFormats = addFormatsImport;
|
|
124
123
|
addFormats(ajv);
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const
|
|
124
|
+
/** Enforce structure that the CLI actually reads or transforms. Business controls go to the service. */
|
|
125
|
+
export function assertModelArguments(model, value) {
|
|
126
|
+
const published = buildModelArgumentsSchema(model);
|
|
127
|
+
const properties = { model: published.properties.model };
|
|
128
|
+
const required = ["model"];
|
|
130
129
|
for (const parameter of model.parameters) {
|
|
131
|
-
if (parameter.
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
properties[parameter.name] = buildModelArgumentsSchema(model).properties[parameter.name];
|
|
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);
|
|
134
|
+
}
|
|
137
135
|
}
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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);
|
|
148
152
|
if (!validate(value)) {
|
|
149
|
-
const issues = validationIssues(validate.errors, value,
|
|
153
|
+
const issues = validationIssues(validate.errors, value, schema);
|
|
150
154
|
throw Object.assign(new ToolInputError("model_parameters", "/arguments", issues), { diagnosticSummary: inputValidationSummary(issues, value, "/arguments") });
|
|
151
155
|
}
|
|
152
|
-
const stepIssues = sliderStepIssues(model, value);
|
|
153
|
-
if (stepIssues.length) {
|
|
154
|
-
throw Object.assign(new ToolInputError("model_parameters", "/arguments", stepIssues), { diagnosticSummary: inputValidationSummary(stepIssues, value, "/arguments") });
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
function sliderStepIssues(model, value) {
|
|
158
|
-
const issues = [];
|
|
159
|
-
for (const parameter of model.parameters) {
|
|
160
|
-
if (parameter.step === undefined || !Object.hasOwn(value, parameter.name))
|
|
161
|
-
continue;
|
|
162
|
-
const candidate = value[parameter.name];
|
|
163
|
-
const minimum = parameter.minimum;
|
|
164
|
-
let valid = false;
|
|
165
|
-
if (typeof candidate === "number" && minimum !== undefined && parameter.step > 0) {
|
|
166
|
-
const steps = (candidate - minimum) / parameter.step;
|
|
167
|
-
const nearestStep = Math.round(steps);
|
|
168
|
-
const expected = minimum + nearestStep * parameter.step;
|
|
169
|
-
const tolerance = Number.EPSILON * Math.max(1, Math.abs(candidate), Math.abs(expected), Math.abs(minimum), Math.abs(nearestStep * parameter.step)) * 2;
|
|
170
|
-
valid = Math.abs(candidate - expected) <= tolerance;
|
|
171
|
-
}
|
|
172
|
-
if (!valid)
|
|
173
|
-
issues.push({
|
|
174
|
-
field: `/${parameter.name.replace(/~/gu, "~0").replace(/\//gu, "~1")}`.slice(0, 256),
|
|
175
|
-
rule: "step",
|
|
176
|
-
message: minimum === undefined || parameter.step <= 0
|
|
177
|
-
? "must match the model's slider configuration"
|
|
178
|
-
: `must be ${minimum} plus a whole number of steps of ${parameter.step}`
|
|
179
|
-
});
|
|
180
|
-
if (issues.length === 8)
|
|
181
|
-
break;
|
|
182
|
-
}
|
|
183
|
-
return issues;
|
|
184
|
-
}
|
|
185
|
-
export function modelControlArgumentsAreValid(model, value) {
|
|
186
|
-
return typeof value === "object"
|
|
187
|
-
&& value !== null
|
|
188
|
-
&& !Array.isArray(value)
|
|
189
|
-
&& controlArgumentsValidator(model)(value)
|
|
190
|
-
&& sliderStepIssues(model, value).length === 0;
|
|
191
156
|
}
|
|
@@ -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 } }),
|
|
@@ -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);
|
|
@@ -327,7 +327,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
327
327
|
}, parseIntent);
|
|
328
328
|
return {
|
|
329
329
|
...intent,
|
|
330
|
-
arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
|
|
330
|
+
arguments: { ...withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters), ...invocation.explicitArguments }
|
|
331
331
|
};
|
|
332
332
|
});
|
|
333
333
|
signal.throwIfAborted();
|