@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
|
@@ -3,13 +3,35 @@ import * as nodeFileSystem from "node:fs/promises";
|
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
4
|
import { setTimeout as delay } from "node:timers/promises";
|
|
5
5
|
const localTurns = new Map();
|
|
6
|
-
const
|
|
6
|
+
const actions = new Set(["task_write", "task_update", "sls_queue", "analytics_device"]);
|
|
7
|
+
const localOwners = new Map();
|
|
8
|
+
function lockTimeout(startedAt, contenderId, phase, owners = [], action) {
|
|
9
|
+
const owner = owners[0];
|
|
10
|
+
const now = Date.now();
|
|
11
|
+
return Object.assign(new Error("Local state lock timed out."), {
|
|
12
|
+
code: "LOCAL_LOCK_TIMEOUT",
|
|
13
|
+
diagnosticSummary: {
|
|
14
|
+
lockWaitMs: Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, now - startedAt)),
|
|
15
|
+
lockWaitPhase: phase,
|
|
16
|
+
...(owner ? { lockWaitScope: owner.pid === process.pid ? "same_process" : "cross_process",
|
|
17
|
+
lockOwnerPid: owner.pid, lockOwnerId: owner.id,
|
|
18
|
+
...(owner.alive ? { lockOwnerAlive: true } : {}),
|
|
19
|
+
...(owner.action ? { lockOwnerAction: owner.action } : {}),
|
|
20
|
+
...(owner.startedAtMs !== undefined ? { lockOwnerStartedAtMs: owner.startedAtMs, lockOwnerAgeMs: Math.max(0, now - owner.startedAtMs) } : {}),
|
|
21
|
+
...(owner.acquiredAtMs !== undefined ? { lockOwnerAcquiredAtMs: owner.acquiredAtMs, lockOwnerHeldMs: Math.max(0, now - owner.acquiredAtMs) } : {}) } : {}),
|
|
22
|
+
...(action ? { lockContenderAction: action } : {}),
|
|
23
|
+
lockOwnerCount: Math.min(100_000, owners.length), lockContenderPid: process.pid, lockContenderId: contenderId
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
7
27
|
/** Same-process waiters queue before creating bakery owners. Separate processes
|
|
8
28
|
* still coordinate through unique owner files and retain the two-second budget. */
|
|
9
29
|
export async function withFileLock(path, run, options = {}) {
|
|
30
|
+
const startedAt = Date.now();
|
|
31
|
+
const contenderId = randomUUID();
|
|
10
32
|
const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
|
|
11
33
|
if (Date.now() >= deadline)
|
|
12
|
-
throw lockTimeout();
|
|
34
|
+
throw lockTimeout(startedAt, contenderId, "local_queue", [], options.action);
|
|
13
35
|
const key = resolve(path);
|
|
14
36
|
const previous = localTurns.get(key) ?? Promise.resolve();
|
|
15
37
|
let release;
|
|
@@ -19,14 +41,22 @@ export async function withFileLock(path, run, options = {}) {
|
|
|
19
41
|
let timer;
|
|
20
42
|
try {
|
|
21
43
|
await new Promise((ready, reject) => {
|
|
22
|
-
timer = setTimeout(() =>
|
|
44
|
+
timer = setTimeout(() => {
|
|
45
|
+
const owner = localOwners.get(key);
|
|
46
|
+
reject(lockTimeout(startedAt, contenderId, "local_queue", owner ? [owner] : [], options.action));
|
|
47
|
+
}, Math.max(0, deadline - Date.now()));
|
|
23
48
|
void previous.then(ready);
|
|
24
49
|
});
|
|
25
50
|
clearTimeout(timer);
|
|
26
|
-
|
|
51
|
+
const owner = { id: contenderId, pid: process.pid, alive: true, startedAtMs: startedAt,
|
|
52
|
+
...(options.action ? { action: options.action } : {}) };
|
|
53
|
+
localOwners.set(key, owner);
|
|
54
|
+
return await acquireFileLock(path, async () => { owner.acquiredAtMs = Date.now(); return run(); }, { ...options, deadline }, { startedAt, contenderId });
|
|
27
55
|
}
|
|
28
56
|
finally {
|
|
29
57
|
clearTimeout(timer);
|
|
58
|
+
if (localOwners.get(key)?.id === contenderId)
|
|
59
|
+
localOwners.delete(key);
|
|
30
60
|
release();
|
|
31
61
|
// A timed-out waiter cannot let a new caller bypass a still-active predecessor.
|
|
32
62
|
void tail.then(() => { if (localTurns.get(key) === tail)
|
|
@@ -34,26 +64,30 @@ export async function withFileLock(path, run, options = {}) {
|
|
|
34
64
|
}
|
|
35
65
|
}
|
|
36
66
|
/** Unique owners avoid deleting a new writer during concurrent crash recovery. */
|
|
37
|
-
async function acquireFileLock(path, run, options) {
|
|
67
|
+
async function acquireFileLock(path, run, options, identity) {
|
|
38
68
|
const fileSystem = options.fileSystem ?? nodeFileSystem;
|
|
39
69
|
const { mkdir, open, readFile, readdir, unlink, chmod, rename } = fileSystem;
|
|
40
70
|
const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
|
|
41
71
|
if (Date.now() >= deadline)
|
|
42
|
-
throw lockTimeout();
|
|
72
|
+
throw lockTimeout(identity.startedAt, identity.contenderId, "owner_files", [], options.action);
|
|
43
73
|
const directory = `${path}.d`;
|
|
44
74
|
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
45
75
|
await chmod(directory, 0o700);
|
|
46
|
-
const name = `${process.pid}-${
|
|
76
|
+
const name = `${process.pid}-${identity.contenderId}.json`;
|
|
47
77
|
const ownPath = join(directory, name);
|
|
48
78
|
async function contenders() {
|
|
49
79
|
const found = [];
|
|
50
80
|
for (const entry of await readdir(directory)) {
|
|
51
|
-
const match = /^(\d+)-[a-f0-9-]{
|
|
81
|
+
const match = /^(\d+)-([a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12})\.json$/u.exec(entry);
|
|
52
82
|
if (!match)
|
|
53
83
|
continue;
|
|
54
84
|
const pid = Number(match[1]);
|
|
85
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
86
|
+
continue;
|
|
87
|
+
let alive;
|
|
55
88
|
try {
|
|
56
89
|
process.kill(pid, 0);
|
|
90
|
+
alive = true;
|
|
57
91
|
}
|
|
58
92
|
catch (error) {
|
|
59
93
|
if (error instanceof Error && "code" in error && error.code === "ESRCH") {
|
|
@@ -64,13 +98,21 @@ async function acquireFileLock(path, run, options) {
|
|
|
64
98
|
try {
|
|
65
99
|
const text = await readFile(join(directory, entry), "utf8");
|
|
66
100
|
let ticket = null;
|
|
101
|
+
let action;
|
|
102
|
+
let startedAtMs;
|
|
67
103
|
try {
|
|
68
|
-
const
|
|
104
|
+
const record = JSON.parse(text);
|
|
105
|
+
const value = record.ticket;
|
|
69
106
|
if (typeof value === "number" && Number.isSafeInteger(value) && value > 0)
|
|
70
107
|
ticket = value;
|
|
108
|
+
if (typeof record.action === "string" && actions.has(record.action))
|
|
109
|
+
action = record.action;
|
|
110
|
+
if (typeof record.startedAtMs === "number" && Number.isSafeInteger(record.startedAtMs) && record.startedAtMs >= 0 && record.startedAtMs <= Date.now())
|
|
111
|
+
startedAtMs = record.startedAtMs;
|
|
71
112
|
}
|
|
72
113
|
catch { /* The owner has opened its choosing file but not written it yet. */ }
|
|
73
|
-
found.push({ name: entry, ticket })
|
|
114
|
+
found.push({ name: entry, id: match[2], pid, ticket, ...(alive ? { alive } : {}),
|
|
115
|
+
...(action ? { action } : {}), ...(startedAtMs === undefined ? {} : { startedAtMs }) });
|
|
74
116
|
}
|
|
75
117
|
catch (error) {
|
|
76
118
|
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
@@ -88,16 +130,17 @@ async function acquireFileLock(path, run, options) {
|
|
|
88
130
|
// Empty/partial owner files already mean "choosing" to readers. Write in
|
|
89
131
|
// place because Windows can reject replacement while another reader is open.
|
|
90
132
|
await handle.truncate(0);
|
|
91
|
-
await handle.write(JSON.stringify({ ticket }), 0, "utf8");
|
|
133
|
+
await handle.write(JSON.stringify({ ticket, startedAtMs: identity.startedAt, ...(options.action ? { action: options.action } : {}) }), 0, "utf8");
|
|
92
134
|
await handle.close();
|
|
135
|
+
let owners = [];
|
|
93
136
|
for (;;) {
|
|
94
137
|
if (Date.now() >= deadline)
|
|
95
|
-
throw lockTimeout();
|
|
96
|
-
|
|
138
|
+
throw lockTimeout(identity.startedAt, identity.contenderId, "owner_files", owners, options.action);
|
|
139
|
+
owners = (await contenders()).filter(owner => owner.name !== name
|
|
97
140
|
&& (owner.ticket === null || owner.ticket < ticket || (owner.ticket === ticket && owner.name < name)));
|
|
98
|
-
if (!
|
|
141
|
+
if (!owners.length) {
|
|
99
142
|
if (Date.now() >= deadline)
|
|
100
|
-
throw lockTimeout();
|
|
143
|
+
throw lockTimeout(identity.startedAt, identity.contenderId, "owner_files", owners, options.action);
|
|
101
144
|
return await run();
|
|
102
145
|
}
|
|
103
146
|
await delay(10);
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** Structural evidence for an already rejected URI; never include its value. */
|
|
2
|
+
export function uriIssue(value) {
|
|
3
|
+
if (/[\u0000-\u001f\u007f-\u009f]/u.test(value))
|
|
4
|
+
return "control_character";
|
|
5
|
+
if (/%(?![A-Fa-f0-9]{2})/u.test(value))
|
|
6
|
+
return "invalid_percent_encoding";
|
|
7
|
+
if (!/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value))
|
|
8
|
+
return "missing_scheme";
|
|
9
|
+
if (value.includes("\\"))
|
|
10
|
+
return "backslash";
|
|
11
|
+
if (/\s/u.test(value))
|
|
12
|
+
return "whitespace";
|
|
13
|
+
if (/[^\u0000-\u007f]/u.test(value))
|
|
14
|
+
return "non_ascii";
|
|
15
|
+
if (/^file:\/\/[A-Za-z]:/iu.test(value))
|
|
16
|
+
return "file_authority_drive";
|
|
17
|
+
if (/^file:\/{3}[A-Za-z]\|/iu.test(value))
|
|
18
|
+
return "file_drive_separator";
|
|
19
|
+
if (/^https?:/iu.test(value)) {
|
|
20
|
+
const authority = /^https?:\/\/([^/?#]*)/iu.exec(value)?.[1];
|
|
21
|
+
if (!authority || !authority.split("@").at(-1))
|
|
22
|
+
return "missing_host";
|
|
23
|
+
try {
|
|
24
|
+
new URL(value);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return "invalid_host";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (/^file:/iu.test(value) && /[?#]/u.test(value))
|
|
31
|
+
return "file_uri_components";
|
|
32
|
+
return "other_format";
|
|
33
|
+
}
|
|
34
|
+
/** URI shape only: no path, host, credentials, query values or input text. */
|
|
35
|
+
export function uriShape(value) {
|
|
36
|
+
const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/u.exec(value)?.[1]?.toLowerCase();
|
|
37
|
+
const localPath = value.replace(/^file:\/*/iu, "");
|
|
38
|
+
const windowsDrive = /^[A-Za-z]:[\\/]/u.test(localPath) ? "valid"
|
|
39
|
+
: (process.platform === "win32" && /^file:\/{2,3}[A-Za-z][\\/]/iu.test(value)) ? "missing_colon" : "none";
|
|
40
|
+
return {
|
|
41
|
+
uriScheme: scheme === undefined ? "none" : ["file", "http", "https"].includes(scheme) ? scheme : "other",
|
|
42
|
+
uriHasNonAscii: /[^\u0000-\u007f]/u.test(value),
|
|
43
|
+
uriHasWhitespace: /\s/u.test(value),
|
|
44
|
+
uriHasControlChars: /[\u0000-\u001f\u007f-\u009f]/u.test(value),
|
|
45
|
+
uriHasBackslash: value.includes("\\"),
|
|
46
|
+
uriHasPercentEncoding: /%[A-Fa-f0-9]{2}/u.test(value),
|
|
47
|
+
uriHasQuery: value.includes("?"),
|
|
48
|
+
uriHasFragment: value.includes("#"),
|
|
49
|
+
uriHasCredentials: /^[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#]*@/u.test(value),
|
|
50
|
+
uriWindowsDrive: windowsDrive
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** Canonicalize explicit file URIs, without repairing paths or losing filename spaces. */
|
|
54
|
+
export function canonicalFileUri(value) {
|
|
55
|
+
if (!/^file:\//iu.test(value) || /[\\\u0000-\u001f\u007f-\u009f]/u.test(value)
|
|
56
|
+
|| /^file:\/\/[A-Za-z]:/iu.test(value) || /^file:\/{3}[A-Za-z]\|/iu.test(value))
|
|
57
|
+
return undefined;
|
|
58
|
+
try {
|
|
59
|
+
const url = new URL(value.replace(/ /gu, "%20"));
|
|
60
|
+
if (url.protocol !== "file:" || url.username || url.password || url.search || url.hash)
|
|
61
|
+
return undefined;
|
|
62
|
+
// URL accepts malformed escapes, whereas fileURLToPath cannot read them.
|
|
63
|
+
decodeURIComponent(url.pathname);
|
|
64
|
+
return url.href;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Normalize only schema-declared URI fields; never inspect or rewrite free text. */
|
|
71
|
+
export function canonicalizeInputFileUris(value, schema) {
|
|
72
|
+
const root = schema;
|
|
73
|
+
const record = (node) => !!node && typeof node === "object" && !Array.isArray(node);
|
|
74
|
+
const resolve = (reference) => reference.startsWith("#/")
|
|
75
|
+
? reference.slice(2).split("/").reduce((node, key) => {
|
|
76
|
+
const name = key.replace(/~1/gu, "/").replace(/~0/gu, "~");
|
|
77
|
+
return record(node) && Object.hasOwn(node, name) ? node[name] : undefined;
|
|
78
|
+
}, root) : undefined;
|
|
79
|
+
const visit = (input, node, depth) => {
|
|
80
|
+
if (!record(node) || depth > 64)
|
|
81
|
+
return input;
|
|
82
|
+
if (typeof node.$ref === "string")
|
|
83
|
+
input = visit(input, resolve(node.$ref), depth + 1);
|
|
84
|
+
for (const keyword of ["allOf", "anyOf", "oneOf"]) {
|
|
85
|
+
const branches = node[keyword];
|
|
86
|
+
if (Array.isArray(branches))
|
|
87
|
+
for (const branch of branches)
|
|
88
|
+
input = visit(input, branch, depth + 1);
|
|
89
|
+
}
|
|
90
|
+
if (node.format === "uri" && typeof input === "string")
|
|
91
|
+
return canonicalFileUri(input) ?? input;
|
|
92
|
+
if (Array.isArray(input) && record(node.items)) {
|
|
93
|
+
for (let index = 0; index < input.length; index++)
|
|
94
|
+
input[index] = visit(input[index], node.items, depth + 1);
|
|
95
|
+
}
|
|
96
|
+
else if (record(input) && record(node.properties)) {
|
|
97
|
+
for (const [key, child] of Object.entries(node.properties)) {
|
|
98
|
+
if (Object.hasOwn(input, key))
|
|
99
|
+
input[key] = visit(input[key], child, depth + 1);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return input;
|
|
103
|
+
};
|
|
104
|
+
visit(value, schema, 0);
|
|
105
|
+
}
|
|
@@ -5,12 +5,15 @@ export class LocalFileError extends Error {
|
|
|
5
5
|
file;
|
|
6
6
|
reason;
|
|
7
7
|
diagnostic;
|
|
8
|
+
diagnosticSummary;
|
|
8
9
|
constructor(cause, file, reason = "io", diagnostic) {
|
|
9
10
|
super("无法访问本地状态文件。", { cause });
|
|
10
11
|
this.file = file;
|
|
11
12
|
this.reason = reason;
|
|
12
13
|
this.diagnostic = diagnostic;
|
|
13
14
|
this.name = "LocalFileError";
|
|
15
|
+
this.diagnosticSummary = { localProcessPid: process.pid, localParentPid: process.ppid,
|
|
16
|
+
...(diagnostic?.role ? { localFileRole: diagnostic.role } : {}) };
|
|
14
17
|
}
|
|
15
18
|
}
|
|
16
19
|
export function createLocalJsonFile(options) {
|
|
@@ -36,7 +39,7 @@ export function createLocalJsonFile(options) {
|
|
|
36
39
|
return null;
|
|
37
40
|
failed = true;
|
|
38
41
|
primaryError = cause;
|
|
39
|
-
throw new LocalFileError(cause, options.filename, "io", { operation: "read", step });
|
|
42
|
+
throw new LocalFileError(cause, options.filename, "io", { operation: "read", step, ...(options.role ? { role: options.role } : {}) });
|
|
40
43
|
}
|
|
41
44
|
finally {
|
|
42
45
|
try {
|
|
@@ -45,7 +48,7 @@ export function createLocalJsonFile(options) {
|
|
|
45
48
|
catch (cause) {
|
|
46
49
|
throw new LocalFileError(failed
|
|
47
50
|
? new AggregateError([primaryError, cause], "Cannot read and close local state.", { cause: primaryError })
|
|
48
|
-
: cause, options.filename, "io", { operation: "read", step: failed ? step : "close" });
|
|
51
|
+
: cause, options.filename, "io", { operation: "read", step: failed ? step : "close", ...(options.role ? { role: options.role } : {}) });
|
|
49
52
|
}
|
|
50
53
|
}
|
|
51
54
|
},
|
|
@@ -74,7 +77,7 @@ export function createLocalJsonFile(options) {
|
|
|
74
77
|
catch (cause) {
|
|
75
78
|
await handle?.close().catch(() => undefined);
|
|
76
79
|
await fileSystem.unlink(temporaryPath).catch(() => undefined);
|
|
77
|
-
throw new LocalFileError(cause, options.filename, "io", { operation: "write", step });
|
|
80
|
+
throw new LocalFileError(cause, options.filename, "io", { operation: "write", step, ...(options.role ? { role: options.role } : {}) });
|
|
78
81
|
}
|
|
79
82
|
},
|
|
80
83
|
async remove() {
|
|
@@ -83,7 +86,7 @@ export function createLocalJsonFile(options) {
|
|
|
83
86
|
}
|
|
84
87
|
catch (cause) {
|
|
85
88
|
if (!isMissing(cause))
|
|
86
|
-
throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step: "unlink" });
|
|
89
|
+
throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step: "unlink", ...(options.role ? { role: options.role } : {}) });
|
|
87
90
|
}
|
|
88
91
|
}
|
|
89
92
|
};
|
|
@@ -3,7 +3,7 @@ const maximumLength = 8_192;
|
|
|
3
3
|
const truncationMarker = "[TRUNCATED]";
|
|
4
4
|
export function remoteErrorEvidence(value) {
|
|
5
5
|
const normalized = parseJson(value);
|
|
6
|
-
const remoteCode = topLevelCode(normalized) ?? jsonRpcErrorCode(normalized);
|
|
6
|
+
const remoteCode = topLevelCode(normalized) ?? jsonRpcErrorCode(normalized) ?? mcpErrorContentCode(normalized);
|
|
7
7
|
const diagnosticReason = imageAuditTimeout(normalized, remoteCode);
|
|
8
8
|
const sanitized = sanitize(normalized);
|
|
9
9
|
if (sanitized === undefined) {
|
|
@@ -47,6 +47,28 @@ function jsonRpcErrorCode(value) {
|
|
|
47
47
|
}
|
|
48
48
|
return normalizeCode(record.error.code);
|
|
49
49
|
}
|
|
50
|
+
function mcpErrorContentCode(value) {
|
|
51
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
52
|
+
return undefined;
|
|
53
|
+
const result = value.result;
|
|
54
|
+
if (result === null || typeof result !== "object" || Array.isArray(result))
|
|
55
|
+
return undefined;
|
|
56
|
+
const record = result;
|
|
57
|
+
// Only MCP's explicit error result is a trusted error boundary. Ordinary
|
|
58
|
+
// assistant replies and arbitrary nested objects never provide error codes.
|
|
59
|
+
if (record.isError !== true || !Array.isArray(record.content))
|
|
60
|
+
return undefined;
|
|
61
|
+
for (const item of record.content.slice(0, 32)) {
|
|
62
|
+
if (item === null || typeof item !== "object" || item.type !== "text"
|
|
63
|
+
|| typeof item.text !== "string" || item.text.length > maximumLength)
|
|
64
|
+
continue;
|
|
65
|
+
const error = parseJson(item.text);
|
|
66
|
+
const code = topLevelCode(error) ?? jsonRpcErrorCode(error);
|
|
67
|
+
if (code !== undefined)
|
|
68
|
+
return code;
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
50
72
|
function normalizeCode(code) {
|
|
51
73
|
if (typeof code === "string")
|
|
52
74
|
return redactRemoteText(code);
|
|
@@ -2,11 +2,14 @@ import { isInterruption } from "./interruption.js";
|
|
|
2
2
|
import { open, realpath, stat } from "node:fs/promises";
|
|
3
3
|
import { basename, extname, sep } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { canonicalFileUri, uriShape } from "./input-uri.js";
|
|
5
6
|
export class LocalFileInputError extends Error {
|
|
6
7
|
reason;
|
|
7
|
-
|
|
8
|
+
diagnosticSummary;
|
|
9
|
+
constructor(cause, reason = "file_read_failed", diagnosticSummary = {}) {
|
|
8
10
|
super("本地文件不可用于上传。", { cause });
|
|
9
11
|
this.reason = reason;
|
|
12
|
+
this.diagnosticSummary = diagnosticSummary;
|
|
10
13
|
this.name = "LocalFileInputError";
|
|
11
14
|
}
|
|
12
15
|
}
|
|
@@ -83,6 +86,12 @@ function detectedFormat(header) {
|
|
|
83
86
|
return "webp";
|
|
84
87
|
if (header.length >= 12 && header.subarray(4, 8).toString("ascii") === "ftyp") {
|
|
85
88
|
const brand = header.subarray(8, 12).toString("ascii");
|
|
89
|
+
if (["isom", "iso2", "iso5", "iso6", "mp41", "mp42", "avc1", "dash"].includes(brand))
|
|
90
|
+
return "mp4";
|
|
91
|
+
if (brand === "qt ")
|
|
92
|
+
return "mov";
|
|
93
|
+
if (brand === "M4V ")
|
|
94
|
+
return "m4v";
|
|
86
95
|
if (brand === "avif" || brand === "avis")
|
|
87
96
|
return "avif";
|
|
88
97
|
if (["heic", "heix", "hevc", "hevx"].includes(brand))
|
|
@@ -106,7 +115,16 @@ async function readHeader(filePath, signal) {
|
|
|
106
115
|
export async function inspectUploadFile(input) {
|
|
107
116
|
input.signal.throwIfAborted();
|
|
108
117
|
try {
|
|
109
|
-
|
|
118
|
+
let requestedPath;
|
|
119
|
+
try {
|
|
120
|
+
const url = canonicalFileUri(input.url);
|
|
121
|
+
if (url === undefined)
|
|
122
|
+
throw new TypeError("Invalid local file URI.");
|
|
123
|
+
requestedPath = fileURLToPath(url);
|
|
124
|
+
}
|
|
125
|
+
catch (cause) {
|
|
126
|
+
throw new LocalFileInputError(cause, "invalid_file_uri");
|
|
127
|
+
}
|
|
110
128
|
if (input.allowSensitivePath !== true)
|
|
111
129
|
assertSafePath(requestedPath);
|
|
112
130
|
const filePath = await realpath(requestedPath);
|
|
@@ -148,8 +166,10 @@ export async function inspectUploadFile(input) {
|
|
|
148
166
|
catch (error) {
|
|
149
167
|
if (isInterruption(error, input.signal))
|
|
150
168
|
throw input.signal.reason;
|
|
151
|
-
if (error instanceof LocalFileInputError)
|
|
169
|
+
if (error instanceof LocalFileInputError) {
|
|
170
|
+
Object.assign(error.diagnosticSummary, uriShape(input.url));
|
|
152
171
|
throw error;
|
|
153
|
-
|
|
172
|
+
}
|
|
173
|
+
throw new LocalFileInputError(error, "file_read_failed", uriShape(input.url));
|
|
154
174
|
}
|
|
155
175
|
}
|
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
import { uriIssue, uriShape } from "./input-uri.js";
|
|
2
|
+
export function inputValidationSummary(issues, input, prefix = "") {
|
|
3
|
+
const issue = issues[0];
|
|
4
|
+
if (!issue)
|
|
5
|
+
return {};
|
|
6
|
+
const value = issue.field === "/" ? input : issue.field.slice(1).split("/").reduce((node, key) => {
|
|
7
|
+
const name = key.replace(/~1/gu, "/").replace(/~0/gu, "~");
|
|
8
|
+
return node && typeof node === "object" && Object.hasOwn(node, name) ? node[name] : undefined;
|
|
9
|
+
}, input);
|
|
10
|
+
// additionalProperty names are supplied by the caller; report their parent.
|
|
11
|
+
const field = `${prefix}${issue.rule === "additionalProperties" ? issue.field.replace(/\/[^/]*$/u, "") : issue.field}` || "/";
|
|
12
|
+
return {
|
|
13
|
+
...(/^\/[A-Za-z0-9_./~-]*$/u.test(field) && field.length <= 256 ? { inputField: field } : {}),
|
|
14
|
+
inputRule: issue.rule,
|
|
15
|
+
inputValueType: value === null ? "null" : Array.isArray(value) ? "array" : typeof value,
|
|
16
|
+
...(issue.rule === "format" && typeof value === "string" ? { ...uriShape(value), uriIssue: uriIssue(value) } : {})
|
|
17
|
+
};
|
|
18
|
+
}
|
|
1
19
|
export function validationIssues(errors, value, schema) {
|
|
2
20
|
let selected = errors ?? [];
|
|
3
21
|
const at = (root, pointer) => pointer.replace(/^#\/?/u, "").split("/").filter(Boolean)
|
|
@@ -2,13 +2,45 @@ import { isInterruption } from "./interruption.js";
|
|
|
2
2
|
import { remoteErrorEvidence } from "./remote-error-evidence.js";
|
|
3
3
|
import { RemoteProtocolError } from "./remote-protocol.js";
|
|
4
4
|
import { canonicalizeQuery, signRequest } from "./signature.js";
|
|
5
|
+
/** Bind adapter interpretation errors to this response, never to a later request. */
|
|
6
|
+
export async function withResponseDiagnostics(run, correlation = {}) {
|
|
7
|
+
let receipt;
|
|
8
|
+
try {
|
|
9
|
+
return await run((status, summary) => { receipt = { status, ...(summary ? { summary } : {}) }; });
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
try {
|
|
13
|
+
if ((receipt || Object.keys(correlation).length) && error instanceof Error && Object.isExtensible(error)) {
|
|
14
|
+
const previous = error;
|
|
15
|
+
let nestedResponse = false;
|
|
16
|
+
const seen = new Set();
|
|
17
|
+
for (let cause = error.cause; cause instanceof Error && seen.size < 10 && !seen.has(cause); cause = cause.cause) {
|
|
18
|
+
seen.add(cause);
|
|
19
|
+
if ("status" in cause && typeof cause.status === "number") {
|
|
20
|
+
nestedResponse = true;
|
|
21
|
+
break;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const related = !nestedResponse && (previous.status === undefined || previous.status === receipt?.status)
|
|
25
|
+
&& (!previous.diagnosticSummary?.requestId || !receipt?.summary?.requestId || previous.diagnosticSummary.requestId === receipt.summary.requestId);
|
|
26
|
+
const response = related ? receipt : undefined;
|
|
27
|
+
// Existing evidence belongs to the primary failure (e.g. a nested request).
|
|
28
|
+
Object.assign(error, { ...(response ? { status: previous.status ?? response.status } : {}),
|
|
29
|
+
diagnosticSummary: { ...correlation, ...response?.summary, ...previous.diagnosticSummary } });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch { /* Diagnostics cannot replace the original failure. */ }
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
5
36
|
export class RemoteRequestError extends Error {
|
|
6
37
|
status;
|
|
7
38
|
transient;
|
|
8
39
|
remoteCode;
|
|
9
40
|
remoteBody;
|
|
10
41
|
diagnosticReason;
|
|
11
|
-
|
|
42
|
+
diagnosticSummary;
|
|
43
|
+
constructor(status, transient = false, evidence = {}, cause, diagnosticReason, diagnosticSummary) {
|
|
12
44
|
super(status === undefined ? "无法连接稿定服务。" : `稿定服务请求失败(HTTP ${status})。`, { cause });
|
|
13
45
|
this.name = "RemoteRequestError";
|
|
14
46
|
this.status = status;
|
|
@@ -16,7 +48,16 @@ export class RemoteRequestError extends Error {
|
|
|
16
48
|
this.remoteCode = evidence.remoteCode;
|
|
17
49
|
this.remoteBody = evidence.remoteBody;
|
|
18
50
|
this.diagnosticReason = diagnosticReason ?? evidence.diagnosticReason;
|
|
51
|
+
this.diagnosticSummary = diagnosticSummary;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function responseDiagnostics(response) {
|
|
55
|
+
for (const header of ["x-request-id", "x-gd-request-id", "request-id"]) {
|
|
56
|
+
const requestId = response.headers.get(header);
|
|
57
|
+
if (requestId && /^[A-Za-z0-9._:-]{1,128}$/u.test(requestId))
|
|
58
|
+
return { requestId };
|
|
19
59
|
}
|
|
60
|
+
return undefined;
|
|
20
61
|
}
|
|
21
62
|
const TRANSIENT_NETWORK_CODES = new Set([
|
|
22
63
|
"ECONNRESET",
|
|
@@ -75,48 +116,63 @@ export function createSignedHttpTransport(options) {
|
|
|
75
116
|
headers["Content-Type"] = "application/json";
|
|
76
117
|
if (request.organizationId !== undefined)
|
|
77
118
|
headers["X-Org-Id"] = request.organizationId;
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
])
|
|
119
|
+
const requestTimeoutMs = timeout ? options.timeoutMs ?? 30_000 : undefined;
|
|
120
|
+
const timeoutSignal = requestTimeoutMs === undefined ? undefined : AbortSignal.timeout(requestTimeoutMs);
|
|
121
|
+
const signal = timeoutSignal
|
|
122
|
+
? AbortSignal.any([request.signal, timeoutSignal])
|
|
83
123
|
: request.signal;
|
|
84
124
|
signal.throwIfAborted();
|
|
125
|
+
const startedAt = Date.now();
|
|
126
|
+
const diagnostics = () => ({
|
|
127
|
+
requestDurationMs: Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, Date.now() - startedAt)),
|
|
128
|
+
...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),
|
|
129
|
+
abortSource: request.signal.aborted ? "caller" : timeoutSignal?.aborted ? "request_timeout" : "none"
|
|
130
|
+
});
|
|
85
131
|
let dispatched;
|
|
86
132
|
try {
|
|
87
133
|
// Invoke fetch at this boundary; diagnostic persistence never gates dispatch.
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
seenResponses.add(response);
|
|
104
|
-
return received;
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
finally {
|
|
134
|
+
const pending = options.fetch(url, {
|
|
135
|
+
method,
|
|
136
|
+
headers,
|
|
137
|
+
...(body === undefined ? {} : { body }),
|
|
138
|
+
signal
|
|
139
|
+
}).then(response => {
|
|
140
|
+
// Capture ownership facts before waiting for unrelated dispatch diagnostics.
|
|
141
|
+
const received = {
|
|
142
|
+
response,
|
|
143
|
+
bodyUsedAtReceipt: response.bodyUsed,
|
|
144
|
+
bodyLockedAtReceipt: response.body?.locked ?? false,
|
|
145
|
+
reusedResponse: seenResponses.has(response),
|
|
146
|
+
diagnostics: () => ({ ...diagnostics(), ...responseDiagnostics(response) })
|
|
147
|
+
};
|
|
148
|
+
seenResponses.add(response);
|
|
108
149
|
try {
|
|
109
|
-
|
|
150
|
+
request.onResponse?.(response.status, received.diagnostics());
|
|
110
151
|
}
|
|
111
|
-
catch { /*
|
|
152
|
+
catch { /* Receipt diagnostics only. */ }
|
|
153
|
+
return received;
|
|
154
|
+
});
|
|
155
|
+
try {
|
|
156
|
+
dispatched = request.onDispatch?.(options.now().getTime()).catch(() => undefined);
|
|
112
157
|
}
|
|
158
|
+
catch { /* Diagnostic only. */ }
|
|
113
159
|
const [received] = await Promise.all([pending, dispatched]);
|
|
114
160
|
return received;
|
|
115
161
|
}
|
|
116
162
|
catch (error) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
163
|
+
// A rejected fetch must not overtake persistence of the dispatch that caused it.
|
|
164
|
+
await dispatched;
|
|
165
|
+
const diagnosticSummary = diagnostics();
|
|
166
|
+
if (isInterruption(error, request.signal)) {
|
|
167
|
+
const reason = request.signal.reason;
|
|
168
|
+
try {
|
|
169
|
+
if (reason instanceof Error && Object.isExtensible(reason))
|
|
170
|
+
Object.assign(reason, { diagnosticSummary });
|
|
171
|
+
}
|
|
172
|
+
catch { /* Preserve the original interruption. */ }
|
|
173
|
+
throw reason;
|
|
174
|
+
}
|
|
175
|
+
throw new RemoteRequestError(undefined, isTransientNetworkFailure(error), {}, error, undefined, diagnosticSummary);
|
|
120
176
|
}
|
|
121
177
|
}
|
|
122
178
|
async function readText(received) {
|
|
@@ -136,7 +192,7 @@ export function createSignedHttpTransport(options) {
|
|
|
136
192
|
: summary.bodyLockedBeforeRead ? "RESPONSE_BODY_LOCKED" : "RESPONSE_BODY_READ_FAILED";
|
|
137
193
|
throw new RemoteRequestError(response.status, false, {
|
|
138
194
|
remoteBody: JSON.stringify(summary)
|
|
139
|
-
}, error, diagnosticReason);
|
|
195
|
+
}, error, diagnosticReason, { ...received.diagnostics(), ...summary });
|
|
140
196
|
}
|
|
141
197
|
}
|
|
142
198
|
async function json(received) {
|
|
@@ -144,17 +200,19 @@ export function createSignedHttpTransport(options) {
|
|
|
144
200
|
const body = await readText(received);
|
|
145
201
|
const evidence = remoteErrorEvidence(body);
|
|
146
202
|
if (!response.ok)
|
|
147
|
-
throw new RemoteRequestError(response.status, false, evidence);
|
|
203
|
+
throw new RemoteRequestError(response.status, false, evidence, undefined, undefined, received.diagnostics());
|
|
148
204
|
try {
|
|
149
205
|
return JSON.parse(body);
|
|
150
206
|
}
|
|
151
207
|
catch (error) {
|
|
152
|
-
throw new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID")
|
|
208
|
+
throw Object.assign(new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID"), {
|
|
209
|
+
status: response.status, diagnosticSummary: received.diagnostics()
|
|
210
|
+
});
|
|
153
211
|
}
|
|
154
212
|
}
|
|
155
213
|
async function getJsonResponse(request) {
|
|
156
214
|
const received = await send("GET", request, "application/json", undefined, true);
|
|
157
|
-
return { body: await json(received), headers: received.response.headers };
|
|
215
|
+
return { body: await json(received), headers: received.response.headers, status: received.response.status };
|
|
158
216
|
}
|
|
159
217
|
return {
|
|
160
218
|
async getJson(request) {
|
|
@@ -172,10 +230,10 @@ export function createSignedHttpTransport(options) {
|
|
|
172
230
|
const { response } = received;
|
|
173
231
|
if (!response.ok) {
|
|
174
232
|
const body = await readText(received);
|
|
175
|
-
throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body));
|
|
233
|
+
throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body), undefined, undefined, received.diagnostics());
|
|
176
234
|
}
|
|
177
235
|
if (!response.body)
|
|
178
|
-
throw new RemoteRequestError(response.status);
|
|
236
|
+
throw new RemoteRequestError(response.status, false, {}, undefined, "RESPONSE_BODY_MISSING", received.diagnostics());
|
|
179
237
|
return response.body;
|
|
180
238
|
}
|
|
181
239
|
};
|