@insmind/cli 1.9.0 → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/insmind-cli.js +31 -24
- package/dist/bin/task-worker.js +4 -1
- package/dist/src/analytics/device.js +2 -2
- package/dist/src/bootstrap/create-cli.js +7 -0
- package/dist/src/bootstrap/create-runtime.js +3 -7
- package/dist/src/bootstrap/run-task-worker.js +5 -1
- package/dist/src/bootstrap/validators.js +11 -4
- package/dist/src/cli/dam-commands.js +3 -3
- package/dist/src/cli/errors.js +60 -12
- package/dist/src/cli/observed-errors.js +3 -1
- package/dist/src/features/agent/creative-agent-adapter.js +37 -11
- package/dist/src/features/agent/creative-protocol.js +9 -5
- package/dist/src/features/agent/creative-stream.js +54 -6
- package/dist/src/features/agent/result-reader.js +3 -1
- package/dist/src/features/auth/credential-store.js +6 -10
- package/dist/src/features/auth/sso-service.js +22 -6
- package/dist/src/features/auth/state.js +6 -0
- package/dist/src/features/auth/use-cases.js +90 -32
- 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/input.js +23 -0
- package/dist/src/features/dam/use-cases.js +32 -22
- package/dist/src/features/task/store.js +5 -5
- package/dist/src/features/task/task-background.js +67 -19
- package/dist/src/features/task/use-cases.js +34 -6
- package/dist/src/features/tool/canvas-media.js +82 -27
- package/dist/src/features/tool/dynamic-schema.js +8 -4
- package/dist/src/features/tool/matting-billing.js +38 -26
- package/dist/src/features/tool/tool-api-adapter.js +17 -14
- package/dist/src/platform/file-lock.js +58 -15
- package/dist/src/platform/input-uri.js +105 -0
- 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 +18 -4
- package/dist/src/platform/schema-issues.js +18 -0
- package/dist/src/platform/signed-http-transport.js +77 -16
- 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 +24 -3
- package/dist/src/telemetry/process-errors.js +2 -1
- package/dist/src/telemetry/sls-sink.js +66 -18
- package/package.json +4 -4
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { fork } from "node:child_process";
|
|
2
2
|
import { safeFailureSummary } from "../../telemetry/failure-summary.js";
|
|
3
|
+
import { validTaskId } from "./store.js";
|
|
3
4
|
function diagnosticToken(value, pattern) {
|
|
4
5
|
return typeof value === "string" && pattern.test(value) ? value : undefined;
|
|
5
6
|
}
|
|
@@ -65,55 +66,102 @@ export class TaskBackgroundError extends Error {
|
|
|
65
66
|
this.diagnostics = safe;
|
|
66
67
|
}
|
|
67
68
|
}
|
|
69
|
+
export function taskWorkerUnavailableError(options) {
|
|
70
|
+
const diagnosticSummary = {
|
|
71
|
+
workerPhase: options.phase,
|
|
72
|
+
...(options.pid === undefined ? {} : { workerPid: options.pid }),
|
|
73
|
+
...(options.exitCode === undefined ? {} : { workerExitCode: options.exitCode }),
|
|
74
|
+
...(options.signal === undefined ? {} : { workerSignal: options.signal })
|
|
75
|
+
};
|
|
76
|
+
const diagnostics = taskWorkerDiagnostics(options.cause ?? new Error("Background process unavailable."), {
|
|
77
|
+
outcome: "failure", diagnosticReason: "TASK_WORKER_UNAVAILABLE", diagnosticSummary
|
|
78
|
+
}, `worker.${options.phase}`);
|
|
79
|
+
const systemCode = diagnostics.causes?.find(cause => cause.system_code)?.system_code;
|
|
80
|
+
if (systemCode)
|
|
81
|
+
diagnostics.diagnostic_summary = safeFailureSummary({ ...diagnosticSummary, systemCode }) ?? {};
|
|
82
|
+
return new TaskBackgroundError({
|
|
83
|
+
code: "TASK_WORKER_UNAVAILABLE",
|
|
84
|
+
message: options.product === "insmind"
|
|
85
|
+
? "The background process did not return a receipt. Check task list/get before submitting again."
|
|
86
|
+
: "后台进程未返回受理回执。请先用 task list/get 查询,勿重复提交。",
|
|
87
|
+
...(options.taskId && validTaskId(options.taskId) ? { details: { cli_task_id: options.taskId } } : {})
|
|
88
|
+
}, 1, diagnostics);
|
|
89
|
+
}
|
|
68
90
|
export function createTaskBackgroundLauncher(options) {
|
|
69
91
|
return {
|
|
70
92
|
submit(job, signal, started) {
|
|
71
93
|
signal.throwIfAborted();
|
|
72
94
|
return new Promise((resolve, reject) => {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
95
|
+
let child;
|
|
96
|
+
try {
|
|
97
|
+
child = (options.fork ?? fork)(options.workerPath, [], {
|
|
98
|
+
detached: true,
|
|
99
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
100
|
+
execArgv: [],
|
|
101
|
+
env: { ...process.env, ...options.env }
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (cause) {
|
|
105
|
+
reject(taskWorkerUnavailableError({ product: job.product, phase: "spawn", cause }));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
79
108
|
let settled = false;
|
|
109
|
+
let taskId;
|
|
110
|
+
let disconnectTimer;
|
|
80
111
|
const finish = (result) => {
|
|
81
112
|
if (settled)
|
|
82
113
|
return;
|
|
83
114
|
settled = true;
|
|
115
|
+
clearTimeout(disconnectTimer);
|
|
84
116
|
signal.removeEventListener("abort", aborted);
|
|
85
117
|
// The one-task worker owns the request after handoff, including when
|
|
86
118
|
// the caller is interrupted or loses the receipt.
|
|
87
|
-
|
|
88
|
-
child.
|
|
119
|
+
try {
|
|
120
|
+
if (child.connected)
|
|
121
|
+
child.disconnect();
|
|
122
|
+
}
|
|
123
|
+
catch { /* Teardown cannot replace the receipt or original failure. */ }
|
|
89
124
|
child.unref();
|
|
90
125
|
if (result instanceof Error)
|
|
91
126
|
reject(result);
|
|
92
127
|
else
|
|
93
128
|
resolve(result);
|
|
94
129
|
};
|
|
95
|
-
const unavailable = () => finish(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}));
|
|
130
|
+
const unavailable = (phase, cause, exitCode, signal) => finish(taskWorkerUnavailableError({ product: job.product, phase, cause,
|
|
131
|
+
...(child.pid === undefined ? {} : { pid: child.pid }),
|
|
132
|
+
...(taskId === undefined ? {} : { taskId }),
|
|
133
|
+
...(exitCode === null || exitCode === undefined ? {} : { exitCode }),
|
|
134
|
+
...(signal ? { signal } : {}) }));
|
|
101
135
|
const aborted = () => finish(signal.reason instanceof Error ? signal.reason : new Error("SIGINT"));
|
|
102
|
-
child.on("error", unavailable);
|
|
103
|
-
child.once("exit", unavailable);
|
|
136
|
+
child.on("error", cause => unavailable(child.pid === undefined ? "spawn" : taskId ? "before_accepted" : "before_started", cause));
|
|
137
|
+
child.once("exit", (code, signal) => unavailable(taskId ? "before_accepted" : "before_started", undefined, code, signal));
|
|
138
|
+
child.once("disconnect", () => {
|
|
139
|
+
if (settled)
|
|
140
|
+
return;
|
|
141
|
+
// Node can close IPC just before emitting exit. Allow that terminal
|
|
142
|
+
// event a bounded turn so its actual code/signal is not lost.
|
|
143
|
+
disconnectTimer = setTimeout(() => unavailable("ipc_disconnect"), 100);
|
|
144
|
+
});
|
|
104
145
|
child.on("message", (message) => {
|
|
105
146
|
if (settled)
|
|
106
147
|
return;
|
|
107
|
-
if (message.type === "started")
|
|
148
|
+
if (message.type === "started") {
|
|
149
|
+
taskId = message.task.taskId;
|
|
108
150
|
started(message.task);
|
|
151
|
+
}
|
|
109
152
|
else if (message.type === "accepted")
|
|
110
153
|
finish(message.task);
|
|
111
154
|
else if (message.type === "error")
|
|
112
155
|
finish(new TaskBackgroundError(message.failure, message.exitCode, message.diagnostics));
|
|
113
156
|
});
|
|
114
157
|
signal.addEventListener("abort", aborted, { once: true });
|
|
115
|
-
|
|
116
|
-
|
|
158
|
+
try {
|
|
159
|
+
child.send(job, error => { if (error)
|
|
160
|
+
unavailable("ipc_send", error); });
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
unavailable("ipc_send", error);
|
|
164
|
+
}
|
|
117
165
|
});
|
|
118
166
|
}
|
|
119
167
|
};
|
|
@@ -58,13 +58,24 @@ export function createTaskUseCases(dependencies) {
|
|
|
58
58
|
const telemetry = dependencies.telemetry;
|
|
59
59
|
let pendingOutput;
|
|
60
60
|
const warnedTasks = new Set();
|
|
61
|
+
const warnedUsageTasks = new Set();
|
|
61
62
|
const stage = (name, run) => telemetry ? telemetry.stage(name, run) : run();
|
|
62
|
-
function
|
|
63
|
+
async function warn(stageName, message) {
|
|
64
|
+
await stage(stageName, async () => { (dependencies.warning ?? dependencies.notice)(message); }).catch(() => undefined);
|
|
65
|
+
}
|
|
66
|
+
async function cacheWarning(id) {
|
|
63
67
|
if (warnedTasks.has(id))
|
|
64
68
|
return;
|
|
65
69
|
warnedTasks.add(id);
|
|
66
70
|
telemetry?.annotate({ warning_codes: ["TASK_CACHE_UNAVAILABLE"] });
|
|
67
|
-
(
|
|
71
|
+
await warn("task.cache_warning", text(`任务 ${id} 的本地记录未能保存,task get 可能无法恢复。请保留本次输出,不要重新提交创作。`, `The local record for task ${id} could not be saved; task get may not recover it. Keep this output and do not submit the creation again.`));
|
|
72
|
+
}
|
|
73
|
+
async function usageWarning(id, incomplete) {
|
|
74
|
+
if (!incomplete || warnedUsageTasks.has(id))
|
|
75
|
+
return;
|
|
76
|
+
warnedUsageTasks.add(id);
|
|
77
|
+
telemetry?.annotate({ warning_codes: ["AGENT_USAGE_MODEL_MISSING"] });
|
|
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."));
|
|
68
79
|
}
|
|
69
80
|
async function fact(scope, record, state, at, error) {
|
|
70
81
|
if (!telemetry || !record.telemetry)
|
|
@@ -185,6 +196,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
185
196
|
if (error instanceof TaskStoreError)
|
|
186
197
|
error.context = { cli_task_id: record.task.taskId, phase,
|
|
187
198
|
request_sent: dispatched, accepted: record.progress.accepted === true || !!record.progress.remoteTaskId,
|
|
199
|
+
acceptance_durable: durableAcceptance,
|
|
188
200
|
result_state: record.task.state };
|
|
189
201
|
return error;
|
|
190
202
|
}
|
|
@@ -223,6 +235,10 @@ export function createTaskUseCases(dependencies) {
|
|
|
223
235
|
return;
|
|
224
236
|
}
|
|
225
237
|
Object.assign(record.progress, withoutResourceKeys(progress));
|
|
238
|
+
telemetry?.annotate({ diagnostic_summary: {
|
|
239
|
+
...(progress.contextId ? { agentContextId: progress.contextId } : {}),
|
|
240
|
+
...(progress.localMessageId ? { localMessageId: progress.localMessageId } : {})
|
|
241
|
+
} });
|
|
226
242
|
if (progress.contextId)
|
|
227
243
|
record.task.contextId = progress.contextId;
|
|
228
244
|
try {
|
|
@@ -232,7 +248,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
232
248
|
if (!(error instanceof LocalFileError) || !dispatched || (input.executionMode === "async" && !durableAcceptance)) {
|
|
233
249
|
throw storageContext(error, dispatched ? "after_dispatch" : "before_dispatch");
|
|
234
250
|
}
|
|
235
|
-
cacheWarning(record.task.taskId);
|
|
251
|
+
await cacheWarning(record.task.taskId);
|
|
236
252
|
return;
|
|
237
253
|
}
|
|
238
254
|
durableAcceptance ||= record.progress.accepted === true || !!record.progress.remoteTaskId;
|
|
@@ -252,7 +268,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
252
268
|
if (!(error instanceof LocalFileError) || record.task.state !== "completed" || input.executionMode === "async") {
|
|
253
269
|
throw storageContext(error, "final_persist");
|
|
254
270
|
}
|
|
255
|
-
cacheWarning(record.task.taskId);
|
|
271
|
+
await cacheWarning(record.task.taskId);
|
|
256
272
|
}
|
|
257
273
|
return { task: record.task, result, record };
|
|
258
274
|
}
|
|
@@ -286,6 +302,8 @@ export function createTaskUseCases(dependencies) {
|
|
|
286
302
|
if (dispatched && !observationOnly && record.task.state !== "completed")
|
|
287
303
|
await fact(scope, record, "failed", dependencies.now().getTime(), error);
|
|
288
304
|
await stage("task.persist", save).catch(() => undefined);
|
|
305
|
+
if (error instanceof TaskStoreError && error.context)
|
|
306
|
+
error.context.result_state = record.task.state;
|
|
289
307
|
throw error;
|
|
290
308
|
}
|
|
291
309
|
}
|
|
@@ -301,6 +319,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
301
319
|
if (input.executionMode !== "async") {
|
|
302
320
|
pendingOutput = { scope: taskScope(input.state), record: execution.record };
|
|
303
321
|
}
|
|
322
|
+
await usageWarning(execution.task.taskId, execution.record.progress.agentUsageModelMissing === true);
|
|
304
323
|
return execution.result;
|
|
305
324
|
},
|
|
306
325
|
async submit(input) {
|
|
@@ -328,16 +347,23 @@ export function createTaskUseCases(dependencies) {
|
|
|
328
347
|
}));
|
|
329
348
|
}
|
|
330
349
|
record = withoutResourceKeys(record);
|
|
350
|
+
telemetry?.annotate({ diagnostic_summary: {
|
|
351
|
+
...(record.progress.contextId ? { agentContextId: record.progress.contextId } : {}),
|
|
352
|
+
...(record.progress.localMessageId ? { localMessageId: record.progress.localMessageId } : {})
|
|
353
|
+
} });
|
|
331
354
|
telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
|
|
332
355
|
if (record.task.state === "completed" && record.task.result) {
|
|
333
356
|
const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };
|
|
334
357
|
pendingOutput = { scope, record };
|
|
358
|
+
await usageWarning(id, record.progress.agentUsageModelMissing === true);
|
|
335
359
|
return result;
|
|
336
360
|
}
|
|
337
361
|
const task = summary(record);
|
|
338
362
|
if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
|
|
339
363
|
return task;
|
|
340
|
-
const { failure, ...recovered } = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
|
|
364
|
+
const { failure, usageModelMissing, ...recovered } = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
|
|
365
|
+
if (usageModelMissing)
|
|
366
|
+
record.progress.agentUsageModelMissing = true;
|
|
341
367
|
const { note: _note, ...metadata } = task;
|
|
342
368
|
const result = { ...metadata, ...recovered };
|
|
343
369
|
if (result.state === "unknown" && task.note) {
|
|
@@ -361,11 +387,13 @@ export function createTaskUseCases(dependencies) {
|
|
|
361
387
|
catch (error) {
|
|
362
388
|
if (!(error instanceof LocalFileError) || result.state !== "completed" || !result.result)
|
|
363
389
|
throw error;
|
|
364
|
-
cacheWarning(id);
|
|
390
|
+
await cacheWarning(id);
|
|
365
391
|
}
|
|
366
392
|
}
|
|
367
393
|
if (result.state === "completed" && result.result)
|
|
368
394
|
pendingOutput = { scope, record };
|
|
395
|
+
if (result.result ?? result.partialResult)
|
|
396
|
+
await usageWarning(id, record.progress.agentUsageModelMissing === true);
|
|
369
397
|
return result;
|
|
370
398
|
},
|
|
371
399
|
async outputCompleted() {
|
|
@@ -2,62 +2,115 @@ import { readFile, mkdtemp, writeFile, rm } from "node:fs/promises";
|
|
|
2
2
|
import { tmpdir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
|
-
import { inspectUploadFile } from "../../platform/safe-upload-file.js";
|
|
5
|
+
import { inspectUploadFile, LocalFileInputError } from "../../platform/safe-upload-file.js";
|
|
6
|
+
import { uriShape } from "../../platform/input-uri.js";
|
|
6
7
|
import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
|
|
7
8
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
9
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
8
10
|
import { ToolInputError } from "./catalog.js";
|
|
11
|
+
function responseDiagnostics(url, redirectCount, headers) {
|
|
12
|
+
const requestId = ["x-request-id", "x-gd-request-id", "request-id"]
|
|
13
|
+
.map(name => headers?.get(name)).find((value) => typeof value === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value));
|
|
14
|
+
return {
|
|
15
|
+
...(url.hostname.length <= 253 ? { mediaHost: url.hostname } : {}),
|
|
16
|
+
redirectCount, mediaBytesRead: 0, ...(requestId ? { requestId } : {})
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function mediaFailure(phase, summary, status, cause) {
|
|
20
|
+
return new RemoteRequestError(status, false, {}, cause, `MEDIA_${phase.toUpperCase()}_FAILED`, { ...summary, mediaPhase: phase });
|
|
21
|
+
}
|
|
9
22
|
export function createCanvasMedia(dependencies) {
|
|
10
|
-
async function
|
|
23
|
+
async function readWithEvidence(uri, signal, limit = 64 * 1024 * 1024) {
|
|
11
24
|
signal.throwIfAborted();
|
|
12
25
|
if (uri.startsWith("file:")) {
|
|
13
26
|
const file = await inspectUploadFile({ url: uri, signal });
|
|
14
27
|
if (file.size > limit)
|
|
15
28
|
throw new ToolInputError("media_too_large", "/arguments");
|
|
16
|
-
|
|
29
|
+
try {
|
|
30
|
+
const bytes = await readFile(file.filePath, { signal });
|
|
31
|
+
return { bytes, summary: { ...uriShape(uri), mediaPhase: "read", mediaBytesRead: bytes.length } };
|
|
32
|
+
}
|
|
33
|
+
catch (cause) {
|
|
34
|
+
if (signal.aborted)
|
|
35
|
+
throw signal.reason;
|
|
36
|
+
throw new LocalFileInputError(cause, "file_read_failed", { ...uriShape(uri), mediaPhase: "read" });
|
|
37
|
+
}
|
|
17
38
|
}
|
|
18
39
|
let url = parseSafeRemoteAssetUrl(uri);
|
|
19
40
|
for (let redirects = 0; redirects <= 5; redirects++) {
|
|
20
|
-
|
|
41
|
+
let response;
|
|
42
|
+
try {
|
|
43
|
+
response = await dependencies.fetch(url, { redirect: "manual", signal });
|
|
44
|
+
}
|
|
45
|
+
catch (cause) {
|
|
46
|
+
if (signal.aborted)
|
|
47
|
+
throw signal.reason;
|
|
48
|
+
throw mediaFailure("request", responseDiagnostics(url, redirects), undefined, cause);
|
|
49
|
+
}
|
|
50
|
+
signal.throwIfAborted();
|
|
51
|
+
const summary = responseDiagnostics(url, redirects, response.headers);
|
|
21
52
|
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
22
53
|
const location = response.headers.get("location");
|
|
23
|
-
await response.body?.cancel();
|
|
54
|
+
await response.body?.cancel().catch(() => undefined);
|
|
24
55
|
if (!location || redirects === 5)
|
|
25
|
-
throw
|
|
26
|
-
|
|
56
|
+
throw mediaFailure("redirect", summary, response.status);
|
|
57
|
+
try {
|
|
58
|
+
url = parseSafeRemoteAssetUrl(new URL(location, url).href);
|
|
59
|
+
}
|
|
60
|
+
catch (cause) {
|
|
61
|
+
throw mediaFailure("redirect", summary, response.status, cause);
|
|
62
|
+
}
|
|
27
63
|
continue;
|
|
28
64
|
}
|
|
29
|
-
if (!response.ok
|
|
30
|
-
|
|
65
|
+
if (!response.ok) {
|
|
66
|
+
await response.body?.cancel().catch(() => undefined);
|
|
67
|
+
throw mediaFailure("request", summary, response.status);
|
|
68
|
+
}
|
|
69
|
+
if (!response.body)
|
|
70
|
+
throw mediaFailure("read", summary, response.status);
|
|
31
71
|
if (Number(response.headers.get("content-length")) > limit) {
|
|
32
|
-
await response.body.cancel();
|
|
33
|
-
throw new ToolInputError("media_too_large", "/arguments");
|
|
72
|
+
await response.body.cancel().catch(() => undefined);
|
|
73
|
+
throw Object.assign(new ToolInputError("media_too_large", "/arguments"), { diagnosticSummary: { ...summary, mediaPhase: "read" } });
|
|
34
74
|
}
|
|
35
|
-
const reader = response.body.getReader();
|
|
36
75
|
const chunks = [];
|
|
37
76
|
let size = 0;
|
|
38
77
|
try {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
78
|
+
const reader = response.body.getReader();
|
|
79
|
+
try {
|
|
80
|
+
while (true) {
|
|
81
|
+
const { value, done } = await reader.read();
|
|
82
|
+
if (done)
|
|
83
|
+
break;
|
|
84
|
+
size += value.byteLength;
|
|
85
|
+
if (size > limit)
|
|
86
|
+
throw new ToolInputError("media_too_large", "/arguments");
|
|
87
|
+
chunks.push(Buffer.from(value));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
await reader.cancel().catch(() => undefined);
|
|
92
|
+
reader.releaseLock();
|
|
47
93
|
}
|
|
48
94
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
95
|
+
catch (cause) {
|
|
96
|
+
if (signal.aborted)
|
|
97
|
+
throw signal.reason;
|
|
98
|
+
const evidence = { ...summary, mediaPhase: "read", mediaBytesRead: Math.min(size, 64 * 1024 * 1024) };
|
|
99
|
+
if (cause instanceof ToolInputError)
|
|
100
|
+
throw Object.assign(cause, { diagnosticSummary: evidence });
|
|
101
|
+
throw mediaFailure("read", evidence, response.status, cause);
|
|
52
102
|
}
|
|
53
|
-
return Buffer.concat(chunks);
|
|
103
|
+
return { bytes: Buffer.concat(chunks), summary: { ...summary, mediaPhase: "read", mediaBytesRead: size }, status: response.status };
|
|
54
104
|
}
|
|
55
|
-
throw
|
|
105
|
+
throw mediaFailure("redirect", responseDiagnostics(url, 5));
|
|
106
|
+
}
|
|
107
|
+
async function read(uri, signal, limit) {
|
|
108
|
+
return (await readWithEvidence(uri, signal, limit)).bytes;
|
|
56
109
|
}
|
|
57
110
|
async function image(uri, signal) {
|
|
111
|
+
const { bytes: raw, summary, status } = await readWithEvidence(uri, signal);
|
|
58
112
|
try {
|
|
59
113
|
const { default: sharp } = await import("sharp");
|
|
60
|
-
const raw = await read(uri, signal);
|
|
61
114
|
const metadata = await sharp(raw, { limitInputPixels: 64 * 1024 * 1024 }).metadata();
|
|
62
115
|
if ((metadata.pages ?? 1) !== 1)
|
|
63
116
|
throw new ToolInputError("animated_image_not_supported", "/arguments/image");
|
|
@@ -69,7 +122,9 @@ export function createCanvasMedia(dependencies) {
|
|
|
69
122
|
throw signal.reason;
|
|
70
123
|
if (cause instanceof ToolInputError)
|
|
71
124
|
throw cause;
|
|
72
|
-
throw new ToolInputError("image_decode_failed", "/arguments/image", [], cause)
|
|
125
|
+
throw Object.assign(new ToolInputError("image_decode_failed", "/arguments/image", [], cause), {
|
|
126
|
+
...(status === undefined ? {} : { status }), diagnosticSummary: { ...summary, mediaPhase: "decode" }
|
|
127
|
+
});
|
|
73
128
|
}
|
|
74
129
|
}
|
|
75
130
|
async function upload(bytes, extension, access, signal) {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
2
2
|
import addFormatsImport, {} from "ajv-formats";
|
|
3
3
|
import { canvasControlParameterNames } from "./canvas-models.js";
|
|
4
|
-
import { validationIssues } from "../../platform/schema-issues.js";
|
|
4
|
+
import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
|
|
5
|
+
import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
|
|
5
6
|
import { ToolInputError } from "./catalog.js";
|
|
6
7
|
function parameterSchema(parameter, includeBounds = false) {
|
|
7
8
|
const common = {
|
|
@@ -143,11 +144,14 @@ function controlArgumentsValidator(model) {
|
|
|
143
144
|
}
|
|
144
145
|
export function assertModelArguments(model, value) {
|
|
145
146
|
const validate = validator(model);
|
|
146
|
-
|
|
147
|
-
|
|
147
|
+
canonicalizeInputFileUris(value, validate.schema);
|
|
148
|
+
if (!validate(value)) {
|
|
149
|
+
const issues = validationIssues(validate.errors, value, validate.schema);
|
|
150
|
+
throw Object.assign(new ToolInputError("model_parameters", "/arguments", issues), { diagnosticSummary: inputValidationSummary(issues, value, "/arguments") });
|
|
151
|
+
}
|
|
148
152
|
const stepIssues = sliderStepIssues(model, value);
|
|
149
153
|
if (stepIssues.length) {
|
|
150
|
-
throw new ToolInputError("model_parameters", "/arguments", stepIssues);
|
|
154
|
+
throw Object.assign(new ToolInputError("model_parameters", "/arguments", stepIssues), { diagnosticSummary: inputValidationSummary(stepIssues, value, "/arguments") });
|
|
151
155
|
}
|
|
152
156
|
}
|
|
153
157
|
function sliderStepIssues(model, value) {
|
|
@@ -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))
|
|
@@ -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;
|
|
@@ -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,7 +324,7 @@ 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
330
|
arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
|
|
@@ -331,7 +334,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
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 });
|