@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
|
@@ -1,16 +1,10 @@
|
|
|
1
1
|
import { resolve } from "node:path";
|
|
2
2
|
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { DamAssetNotDownloadableError } from "./dam-api-adapter.js";
|
|
4
|
+
import { DamInputError, normalizeDamAssetId } from "./input.js";
|
|
5
|
+
import { damAssetSourcePresent } from "./asset-projection.js";
|
|
3
6
|
import { DamOperationUnconfirmedError } from "./operation-executor.js";
|
|
4
|
-
export
|
|
5
|
-
reason;
|
|
6
|
-
field;
|
|
7
|
-
constructor(reason = "invalid_value", field) {
|
|
8
|
-
super("DAM 输入不可用。");
|
|
9
|
-
this.reason = reason;
|
|
10
|
-
this.field = field;
|
|
11
|
-
this.name = "DamInputError";
|
|
12
|
-
}
|
|
13
|
-
}
|
|
7
|
+
export { DamInputError } from "./input.js";
|
|
14
8
|
export class DamRepositoryNotFoundError extends Error {
|
|
15
9
|
constructor() {
|
|
16
10
|
super("当前组织没有可用的 DAM 资源库。");
|
|
@@ -37,8 +31,7 @@ function assertOptionalNonblank(value, field) {
|
|
|
37
31
|
invalid("nonblank", field);
|
|
38
32
|
}
|
|
39
33
|
function assertAssetId(value, field = "asset_id") {
|
|
40
|
-
|
|
41
|
-
invalid("id_required_not_url", field);
|
|
34
|
+
normalizeDamAssetId(value, field);
|
|
42
35
|
}
|
|
43
36
|
function assertRepositorySelection(input) {
|
|
44
37
|
if (input.repositoryId !== undefined && !nonblank(input.repositoryId))
|
|
@@ -124,11 +117,11 @@ export function createDamUseCases(dependencies) {
|
|
|
124
117
|
access: input.access,
|
|
125
118
|
signal: input.signal
|
|
126
119
|
};
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
120
|
+
if (input.operation === "move") {
|
|
121
|
+
const current = await dependencies.telemetry.stage("resolve", () => entryLocation(locationRequest));
|
|
122
|
+
if (current.repositoryId === targetRepositoryId && current.folderId === input.request.targetFolderId)
|
|
123
|
+
invalid("already_in_target", "targetFolderId");
|
|
124
|
+
}
|
|
132
125
|
const execution = await dependencies.telemetry.stage("wait", () => (dependencies.operations.execute({
|
|
133
126
|
operation: input.operation,
|
|
134
127
|
context: { entry_id: input.request.entry_id, repository_id: targetRepositoryId, folder_id: input.request.targetFolderId },
|
|
@@ -275,7 +268,7 @@ export function createDamUseCases(dependencies) {
|
|
|
275
268
|
},
|
|
276
269
|
async download({ input, access, signal }) {
|
|
277
270
|
signal.throwIfAborted();
|
|
278
|
-
|
|
271
|
+
input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
|
|
279
272
|
assertOptionalNonblank(input.outputDir, "outputDir");
|
|
280
273
|
const [repository] = await dependencies.telemetry.stage("repository", () => (resolveRepositories({
|
|
281
274
|
...(input.repositoryId === undefined ? {} : { repositoryId: input.repositoryId })
|
|
@@ -284,12 +277,27 @@ export function createDamUseCases(dependencies) {
|
|
|
284
277
|
throw new DamRepositoryNotFoundError();
|
|
285
278
|
const detail = await dependencies.telemetry.stage("resolve", () => (dependencies.api.getAsset({ assetId: input.asset_id, access, signal })));
|
|
286
279
|
signal.throwIfAborted();
|
|
287
|
-
const urls = await dependencies.telemetry.stage("download", () =>
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
280
|
+
const urls = await dependencies.telemetry.stage("download", async () => {
|
|
281
|
+
try {
|
|
282
|
+
const urls = await dependencies.api.getDownloadUrls({ assetId: input.asset_id, repositoryId: repository.id, access, signal });
|
|
283
|
+
if (!urls.some(url => url.trim() !== ""))
|
|
284
|
+
throw new DamAssetNotDownloadableError({ downloadUrlCount: 0 });
|
|
285
|
+
return urls;
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
if (error instanceof Error) {
|
|
289
|
+
const existing = "diagnosticSummary" in error && error.diagnosticSummary && typeof error.diagnosticSummary === "object" ? error.diagnosticSummary : {};
|
|
290
|
+
Object.assign(error, { diagnosticSummary: {
|
|
291
|
+
...existing, downloadPhase: "url_lookup", assetType: detail.type ?? "unknown",
|
|
292
|
+
...(detail.format && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,31}$/u.test(detail.format) ? { assetFormat: detail.format } : {}),
|
|
293
|
+
assetSourcePresent: damAssetSourcePresent(detail),
|
|
294
|
+
...(/^[A-Za-z0-9._:-]{1,128}$/u.test(repository.id) ? { selectedRepositoryId: repository.id } : {}),
|
|
295
|
+
...(detail.repository_id && /^[A-Za-z0-9._:-]{1,128}$/u.test(detail.repository_id) ? { actualRepositoryId: detail.repository_id } : {})
|
|
296
|
+
} });
|
|
297
|
+
}
|
|
298
|
+
throw error;
|
|
299
|
+
}
|
|
300
|
+
});
|
|
293
301
|
signal.throwIfAborted();
|
|
294
302
|
const files = await dependencies.telemetry.stage("persist", () => (dependencies.downloader.download({
|
|
295
303
|
urls,
|
|
@@ -305,11 +313,11 @@ export function createDamUseCases(dependencies) {
|
|
|
305
313
|
},
|
|
306
314
|
async rename({ input, access, signal }) {
|
|
307
315
|
signal.throwIfAborted();
|
|
308
|
-
|
|
316
|
+
input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
|
|
309
317
|
if (input.kind !== "asset" && input.kind !== "folder")
|
|
310
318
|
invalid("asset_or_folder", "kind");
|
|
311
|
-
if (!nonblank(input.title)
|
|
312
|
-
invalid("
|
|
319
|
+
if (!nonblank(input.title))
|
|
320
|
+
invalid("nonblank", "title");
|
|
313
321
|
const [repository] = await dependencies.telemetry.stage("repository", () => (resolveRepositories({
|
|
314
322
|
...(input.repositoryId === undefined ? {} : { repositoryId: input.repositoryId })
|
|
315
323
|
}, access, signal)));
|
|
@@ -370,6 +378,7 @@ export function createDamUseCases(dependencies) {
|
|
|
370
378
|
},
|
|
371
379
|
async move({ input, access, signal }) {
|
|
372
380
|
signal.throwIfAborted();
|
|
381
|
+
input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
|
|
373
382
|
const operation = await entryOperation({ operation: "move", request: input, access, signal });
|
|
374
383
|
try {
|
|
375
384
|
await dependencies.telemetry.stage("verify", async () => {
|
|
@@ -406,6 +415,7 @@ export function createDamUseCases(dependencies) {
|
|
|
406
415
|
},
|
|
407
416
|
async copy({ input, access, signal }) {
|
|
408
417
|
signal.throwIfAborted();
|
|
418
|
+
input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
|
|
409
419
|
const operation = await entryOperation({ operation: "copy", request: input, access, signal });
|
|
410
420
|
const result = {
|
|
411
421
|
source_entry_id: input.entry_id,
|
|
@@ -421,7 +431,7 @@ export function createDamUseCases(dependencies) {
|
|
|
421
431
|
},
|
|
422
432
|
async get({ input, access, signal }) {
|
|
423
433
|
signal.throwIfAborted();
|
|
424
|
-
|
|
434
|
+
input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
|
|
425
435
|
return dependencies.telemetry.stage("request", async () => {
|
|
426
436
|
const result = await dependencies.api.getAsset({
|
|
427
437
|
assetId: input.asset_id,
|
|
@@ -462,7 +472,7 @@ export function createDamUseCases(dependencies) {
|
|
|
462
472
|
},
|
|
463
473
|
async delete({ input, access, signal }) {
|
|
464
474
|
signal.throwIfAborted();
|
|
465
|
-
|
|
475
|
+
input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
|
|
466
476
|
const [repository] = await dependencies.telemetry.stage("repository", () => (resolveRepositories({
|
|
467
477
|
...(input.repositoryId === undefined ? {} : { repositoryId: input.repositoryId })
|
|
468
478
|
}, access, signal)));
|
|
@@ -34,7 +34,7 @@ export function createEditorBridgeClient(options) {
|
|
|
34
34
|
async rpc(method, payload, signal) {
|
|
35
35
|
const value = await request("/rpc", "POST", { method, ...(payload === undefined ? {} : { payload }) }, signal);
|
|
36
36
|
if (!isRecord(value) ||
|
|
37
|
-
(!hasExactKeys(value, []) && !
|
|
37
|
+
(!hasExactKeys(value, []) && (!Object.hasOwn(value, "result") || Object.hasOwn(value, "error")))) {
|
|
38
38
|
throw invalidResponse();
|
|
39
39
|
}
|
|
40
40
|
return value.result;
|
|
@@ -22,7 +22,9 @@ export function createEditorUseCases(dependencies) {
|
|
|
22
22
|
return result;
|
|
23
23
|
},
|
|
24
24
|
async snapshot({ signal }) {
|
|
25
|
-
const
|
|
25
|
+
const raw = await dependencies.session.rpc("snapshot", undefined, signal);
|
|
26
|
+
const result = raw && typeof raw === "object" && "elements" in raw && "selectedIds" in raw
|
|
27
|
+
? { elements: raw.elements, selectedIds: raw.selectedIds } : raw;
|
|
26
28
|
validate.snapshot(result);
|
|
27
29
|
return result;
|
|
28
30
|
},
|
|
@@ -50,14 +52,10 @@ export function createEditorUseCases(dependencies) {
|
|
|
50
52
|
},
|
|
51
53
|
async save({ signal }) {
|
|
52
54
|
const raw = await dependencies.session.rpc("save", undefined, signal);
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const result = {
|
|
56
|
-
...raw,
|
|
57
|
-
url: toPublicEditorUrl(url).href
|
|
58
|
-
};
|
|
55
|
+
const result = raw && typeof raw === "object" && "workId" in raw && "url" in raw
|
|
56
|
+
? { workId: raw.workId, url: raw.url } : raw;
|
|
59
57
|
validate.save(result);
|
|
60
|
-
return result;
|
|
58
|
+
return { workId: result.workId, url: toPublicEditorUrl(safeEditorResultUrl(result.url)).href };
|
|
61
59
|
}
|
|
62
60
|
};
|
|
63
61
|
}
|
|
@@ -113,19 +113,19 @@ export function createOrgUseCases(dependencies) {
|
|
|
113
113
|
}
|
|
114
114
|
const records = await dependencies.org.list(input.credential, input.signal);
|
|
115
115
|
const record = records.find((candidate) => candidate.id === organizationId);
|
|
116
|
-
if (!record
|
|
116
|
+
if (!record)
|
|
117
117
|
return null;
|
|
118
118
|
const bound = await bind(input.credential, record, input.signal);
|
|
119
119
|
return {
|
|
120
120
|
id: bound.id,
|
|
121
|
-
name: record.realName,
|
|
121
|
+
name: record.realName || record.id,
|
|
122
122
|
...(bound.bindExpiresAt ? { bindExpiresAt: bound.bindExpiresAt } : {})
|
|
123
123
|
};
|
|
124
124
|
}
|
|
125
125
|
catch (error) {
|
|
126
126
|
if (isInterruption(error, input.signal))
|
|
127
127
|
throw input.signal.reason;
|
|
128
|
-
if (isExpectedAuthorizationFailure(error))
|
|
128
|
+
if (dependencies.singleOrganizationName === undefined && isExpectedAuthorizationFailure(error))
|
|
129
129
|
return null;
|
|
130
130
|
throw error;
|
|
131
131
|
}
|
|
@@ -31,35 +31,37 @@ export async function syncBundledSkills(skills, options = {}) {
|
|
|
31
31
|
}
|
|
32
32
|
targetResults.push(current);
|
|
33
33
|
for (const target of targets.slice(1)) {
|
|
34
|
-
|
|
35
|
-
|
|
34
|
+
try {
|
|
35
|
+
current = await inspectTarget(target, skill, canonical.path, platform);
|
|
36
|
+
if (current.status === "conflict" || current.status === "broken") {
|
|
37
|
+
targetResults.push(current);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (current.status === "missing") {
|
|
41
|
+
current = await createLinkOrCopy(skill, target, canonical.path, {
|
|
42
|
+
platform,
|
|
43
|
+
createLink: options.createLink ?? symlink
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
else if (current.status === "outdated") {
|
|
47
|
+
await replaceManagedDirectory(skill, target.path, true);
|
|
48
|
+
current = installed(target, "copy", true);
|
|
49
|
+
}
|
|
36
50
|
targetResults.push(current);
|
|
37
|
-
throw new Error(current.reason ?? "Agent host Skill conflict");
|
|
38
51
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
platform,
|
|
42
|
-
createLink: options.createLink ?? symlink
|
|
43
|
-
});
|
|
52
|
+
catch (error) {
|
|
53
|
+
targetResults.push({ host: target.host, path: target.path, status: "conflict", changed: false, reason: message(error) });
|
|
44
54
|
}
|
|
45
|
-
else if (current.status === "outdated") {
|
|
46
|
-
await replaceManagedDirectory(skill, target.path, true);
|
|
47
|
-
current = installed(target, "copy", true);
|
|
48
|
-
}
|
|
49
|
-
targetResults.push(current);
|
|
50
55
|
}
|
|
56
|
+
const conflict = targetResults.find(target => target.status === "conflict" || target.status === "broken");
|
|
57
|
+
if (conflict)
|
|
58
|
+
throw new Error(conflict.reason ?? conflict.path);
|
|
51
59
|
results.push(syncResult(skill, targetResults));
|
|
52
60
|
}
|
|
53
61
|
catch (error) {
|
|
54
|
-
const active = targets[
|
|
55
|
-
if (active && !targetResults.some(
|
|
56
|
-
targetResults.push({
|
|
57
|
-
host: active.host,
|
|
58
|
-
path: active.path,
|
|
59
|
-
status: "conflict",
|
|
60
|
-
changed: false,
|
|
61
|
-
reason: message(error)
|
|
62
|
-
});
|
|
62
|
+
const active = targetResults.find(target => target.status === "conflict" || target.status === "broken") ?? targets[0];
|
|
63
|
+
if (active && !targetResults.some(target => target.host === active.host)) {
|
|
64
|
+
targetResults.push({ host: active.host, path: active.path, status: "conflict", changed: false, reason: message(error) });
|
|
63
65
|
}
|
|
64
66
|
results.push(syncResult(skill, targetResults));
|
|
65
67
|
throw new SkillSyncError(`Agent Skill ${skill.skill} 同步失败${active ? ` (${active.path})` : ""}: ${message(error)}`, results);
|
|
@@ -16,14 +16,14 @@ export function taskScope(state) {
|
|
|
16
16
|
])).digest("hex");
|
|
17
17
|
}
|
|
18
18
|
export function createTaskStore(options) {
|
|
19
|
-
const root = join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd", "tasks");
|
|
19
|
+
const root = join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd", "tasks", "v6");
|
|
20
20
|
function file(scope, id) {
|
|
21
21
|
if (!/^[a-f0-9]{64}$/u.test(scope) || !validTaskId(id))
|
|
22
22
|
throw new LocalFileError(undefined);
|
|
23
|
-
return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json
|
|
23
|
+
return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json`, role: "task" });
|
|
24
24
|
}
|
|
25
25
|
const store = {
|
|
26
|
-
async read(scope, id) {
|
|
26
|
+
async read(scope, id, summaryOnly = false) {
|
|
27
27
|
const stateFile = file(scope, id);
|
|
28
28
|
try {
|
|
29
29
|
const stat = await lstat(join(root, scope, `${id}.json`));
|
|
@@ -47,12 +47,27 @@ export function createTaskStore(options) {
|
|
|
47
47
|
if (record.version !== 1 || record.task.taskId !== id || !record.progress
|
|
48
48
|
|| typeof record.progress !== "object" || Array.isArray(record.progress))
|
|
49
49
|
throw new Error();
|
|
50
|
+
if (summaryOnly && options.validateSummary) {
|
|
51
|
+
const { result, partialResult, ...summary } = record.task;
|
|
52
|
+
options.validateSummary(summary);
|
|
53
|
+
record.task = summary;
|
|
54
|
+
return record;
|
|
55
|
+
}
|
|
50
56
|
options.validate(record.task);
|
|
57
|
+
if (record.telemetry) {
|
|
58
|
+
const { context, steps } = record.telemetry;
|
|
59
|
+
if (context?.schema_version !== "6" || !context.trace_id || !Array.isArray(steps)
|
|
60
|
+
|| steps.some(item => typeof item?.enqueued !== "boolean" || item.event?.event_name !== "command_step"
|
|
61
|
+
|| item.event.schema_version !== "6" || item.event.trace_id !== context.trace_id
|
|
62
|
+
|| !["request_sent", "result_received", "delivered"].includes(item.event.step))) {
|
|
63
|
+
throw new Error("Invalid task telemetry");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
51
66
|
for (const key of ["contextId", "localMessageId", "remoteTaskId"]) {
|
|
52
67
|
if (record.progress[key] !== undefined && typeof record.progress[key] !== "string")
|
|
53
68
|
throw new Error();
|
|
54
69
|
}
|
|
55
|
-
for (const key of ["submissionStarted", "detached", "accepted"]) {
|
|
70
|
+
for (const key of ["submissionStarted", "detached", "accepted", "agentUsageModelMissing"]) {
|
|
56
71
|
if (record.progress[key] !== undefined && typeof record.progress[key] !== "boolean")
|
|
57
72
|
throw new Error();
|
|
58
73
|
}
|
|
@@ -68,27 +83,26 @@ export function createTaskStore(options) {
|
|
|
68
83
|
const previous = await store.read(scope, record.task.taskId);
|
|
69
84
|
if (previous) {
|
|
70
85
|
record.progress = { ...previous.progress, ...record.progress };
|
|
71
|
-
for (const key of ["accepted", "submissionStarted", "detached"]) {
|
|
86
|
+
for (const key of ["accepted", "submissionStarted", "detached", "agentUsageModelMissing"]) {
|
|
72
87
|
if (previous.progress[key])
|
|
73
88
|
record.progress[key] = true;
|
|
74
89
|
}
|
|
75
90
|
if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed"))
|
|
76
91
|
record.task = previous.task;
|
|
77
|
-
if (previous.failureCorrection)
|
|
78
|
-
record.failureCorrection = previous.failureCorrection;
|
|
79
92
|
if (previous.analytics)
|
|
80
93
|
record.analytics = { ...record.analytics, ...previous.analytics };
|
|
81
|
-
if (previous.telemetry)
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
};
|
|
94
|
+
if (previous.telemetry) {
|
|
95
|
+
const steps = [...previous.telemetry.steps];
|
|
96
|
+
for (const item of record.telemetry?.steps ?? []) {
|
|
97
|
+
if (!steps.some(saved => saved.event.step === item.event.step))
|
|
98
|
+
steps.push(item);
|
|
99
|
+
}
|
|
100
|
+
record.telemetry = { ...previous.telemetry, steps };
|
|
101
|
+
}
|
|
88
102
|
}
|
|
89
103
|
options.validate(record.task);
|
|
90
104
|
await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
|
|
91
|
-
});
|
|
105
|
+
}, { action: "task_write" });
|
|
92
106
|
},
|
|
93
107
|
async update(scope, id, change) {
|
|
94
108
|
file(scope, id);
|
|
@@ -100,7 +114,7 @@ export function createTaskStore(options) {
|
|
|
100
114
|
options.validate(record.task);
|
|
101
115
|
await file(scope, id).writeTextAtomically(`${JSON.stringify(record)}\n`);
|
|
102
116
|
return record;
|
|
103
|
-
});
|
|
117
|
+
}, { action: "task_update" });
|
|
104
118
|
},
|
|
105
119
|
async list(scope) {
|
|
106
120
|
let names;
|
|
@@ -116,7 +130,7 @@ export function createTaskStore(options) {
|
|
|
116
130
|
for (const name of names) {
|
|
117
131
|
if (!name.endsWith(".json") || !validTaskId(name.slice(0, -5)))
|
|
118
132
|
continue;
|
|
119
|
-
const record = await store.read(scope, name.slice(0, -5));
|
|
133
|
+
const record = await store.read(scope, name.slice(0, -5), true);
|
|
120
134
|
if (record)
|
|
121
135
|
records.push(record);
|
|
122
136
|
}
|
|
@@ -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
|
};
|