@insmind/cli 2.0.0 → 2.1.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/README.md +5 -0
- package/contracts/operations/agent.send/input.schema.json +1 -77
- package/contracts/operations/credits.get/input.schema.json +8 -0
- package/contracts/operations/credits.get/output.schema.json +92 -0
- package/contracts/operations/credits.usage.get/input.schema.json +17 -0
- package/contracts/operations/credits.usage.get/output.schema.json +46 -0
- package/contracts/operations/credits.usage.list/input.schema.json +27 -0
- package/contracts/operations/credits.usage.list/output.schema.json +135 -0
- package/contracts/operations/dam.folder.list/input.schema.json +0 -1
- package/contracts/operations/dam.folder.list/output.schema.json +1 -2
- package/contracts/operations/dam.list/input.schema.json +3 -6
- package/contracts/operations/dam.list/output.schema.json +1 -2
- package/contracts/operations/dam.search/input.schema.json +3 -6
- package/contracts/operations/dam.search/output.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
- package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
- package/dist/bin/postinstall.js +22 -6
- package/dist/bin/task-worker.js +2 -2
- package/dist/src/bootstrap/create-cli.js +31 -15
- package/dist/src/bootstrap/create-runtime.js +103 -30
- package/dist/src/bootstrap/run-task-worker.js +6 -2
- package/dist/src/bootstrap/validators.js +4 -1
- package/dist/src/cli/action-binding.js +17 -50
- package/dist/src/cli/agent-commands.js +11 -11
- package/dist/src/cli/auth-commands.js +2 -1
- package/dist/src/cli/creation-help.js +9 -0
- package/dist/src/cli/credits-command.js +127 -16
- package/dist/src/cli/dam-commands.js +10 -14
- package/dist/src/cli/editor-commands.js +7 -5
- package/dist/src/cli/errors.js +81 -22
- package/dist/src/cli/host-input.js +64 -5
- package/dist/src/cli/model-commands.js +9 -3
- package/dist/src/cli/observed-errors.js +7 -3
- package/dist/src/cli/org-commands.js +3 -1
- package/dist/src/cli/presenter.js +4 -0
- package/dist/src/cli/task-commands.js +6 -2
- package/dist/src/cli/tool-commands.js +12 -11
- package/dist/src/cli/update-command.js +24 -1
- package/dist/src/features/agent/creative-agent-adapter.js +6 -2
- package/dist/src/features/agent/creative-protocol.js +8 -29
- package/dist/src/features/agent/resource-authorizer.js +25 -17
- package/dist/src/features/agent/result-reader.js +31 -14
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/credits/amount.js +51 -0
- package/dist/src/features/credits/response.js +11 -0
- package/dist/src/features/credits/use-cases.js +200 -30
- package/dist/src/features/dam/asset-projection.js +3 -6
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/repository-catalog.js +30 -21
- package/dist/src/features/dam/use-cases.js +12 -7
- package/dist/src/features/editor/bridge-client.js +0 -2
- package/dist/src/features/editor/public-url.js +1 -36
- package/dist/src/features/editor/session.js +3 -2
- package/dist/src/features/editor/use-cases.js +27 -2
- package/dist/src/features/org/org-service.js +10 -1
- package/dist/src/features/org/use-cases.js +18 -4
- package/dist/src/features/task/process-owner.js +54 -0
- package/dist/src/features/task/store.js +37 -10
- package/dist/src/features/task/task-background.js +5 -2
- package/dist/src/features/task/use-cases.js +184 -84
- package/dist/src/features/tool/argument-paths.js +14 -0
- package/dist/src/features/tool/canvas-copy.js +28 -15
- package/dist/src/features/tool/canvas-matting.js +123 -0
- package/dist/src/features/tool/canvas-media.js +100 -52
- package/dist/src/features/tool/canvas-models.js +66 -33
- package/dist/src/features/tool/canvas-pricing.js +12 -0
- package/dist/src/features/tool/canvas-recovery.js +13 -30
- package/dist/src/features/tool/canvas-results.js +79 -87
- package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
- package/dist/src/features/tool/canvas-video.js +44 -37
- package/dist/src/features/tool/dynamic-schema.js +39 -40
- package/dist/src/features/tool/ffprobe-executable.js +21 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
- package/dist/src/features/tool/resource-authorizer.js +11 -3
- package/dist/src/features/tool/tool-api-adapter.js +73 -82
- package/dist/src/features/tool/tool-errors.js +25 -0
- package/dist/src/features/tool/tool-output.js +15 -0
- package/dist/src/features/tool/use-cases.js +74 -98
- package/dist/src/features/update/check-schema.js +17 -0
- package/dist/src/features/update/host-receipt.js +30 -0
- package/dist/src/features/update/notice-output.js +30 -0
- package/dist/src/features/update/update-lock.js +80 -0
- package/dist/src/features/update/update-notification.js +129 -240
- package/dist/src/features/update/update-service.js +95 -21
- package/dist/src/platform/media-type.js +46 -0
- package/dist/src/platform/public-url.js +35 -0
- package/dist/src/platform/remote-error-evidence.js +33 -6
- package/dist/src/platform/resource-auth-key.js +35 -1
- package/dist/src/platform/safe-upload-file.js +36 -41
- package/dist/src/platform/signature.js +3 -1
- package/dist/src/platform/signed-http-transport.js +14 -6
- package/dist/src/platform/url-safety.js +6 -1
- package/dist/src/platform/webm-header.js +41 -0
- package/dist/src/telemetry/command-route.js +38 -0
- package/dist/src/telemetry/command-routes.json +1 -0
- package/dist/src/telemetry/failure-summary.js +1 -1
- package/dist/src/telemetry/invocation.js +1 -2
- package/dist/src/telemetry/process-errors.js +17 -33
- package/dist/src/telemetry/sanitize.js +19 -4
- package/dist/src/telemetry/sls-sink.js +8 -0
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +19 -5
- package/skills/insmind-cli/references/agent.md +9 -4
- package/skills/insmind-cli/references/creation.md +3 -1
- package/skills/insmind-cli/references/editor.md +7 -5
- package/skills/insmind-cli/references/errors.md +20 -9
- package/skills/insmind-cli/references/matting.md +3 -5
- package/skills/insmind-cli/references/media-tools.md +10 -4
- package/skills/insmind-cli/references/tool.md +9 -15
- package/skills/insmind-cli/references/update.md +2 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { resolve } from "node:path";
|
|
2
2
|
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
3
4
|
import { DamAssetNotDownloadableError } from "./dam-api-adapter.js";
|
|
4
5
|
import { DamInputError, normalizeDamAssetId } from "./input.js";
|
|
5
6
|
import { damAssetSourcePresent } from "./asset-projection.js";
|
|
@@ -19,8 +20,8 @@ function nonblank(value) {
|
|
|
19
20
|
return value !== undefined && value.trim() !== "";
|
|
20
21
|
}
|
|
21
22
|
function assertPageSize(value) {
|
|
22
|
-
if (value !== undefined && (!Number.
|
|
23
|
-
invalid("
|
|
23
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1))
|
|
24
|
+
invalid("positive_integer", "pageSize");
|
|
24
25
|
}
|
|
25
26
|
function assertPage(value) {
|
|
26
27
|
if (value !== undefined && (!Number.isInteger(value) || value < 1))
|
|
@@ -97,8 +98,6 @@ export function createDamUseCases(dependencies) {
|
|
|
97
98
|
invalid("nonblank", "targetFolderId");
|
|
98
99
|
assertOptionalNonblank(input.repositoryId, "repositoryId");
|
|
99
100
|
assertOptionalNonblank(input.targetRepositoryId, "targetRepositoryId");
|
|
100
|
-
if (input.kind === "folder" && input.entry_id === input.targetFolderId)
|
|
101
|
-
invalid("cannot_target_self", "targetFolderId");
|
|
102
101
|
}
|
|
103
102
|
async function entryOperation(input) {
|
|
104
103
|
assertEntryOperationInput(input.request);
|
|
@@ -110,6 +109,9 @@ export function createDamUseCases(dependencies) {
|
|
|
110
109
|
if (sourceRepository === undefined)
|
|
111
110
|
throw new DamRepositoryNotFoundError();
|
|
112
111
|
const targetRepositoryId = input.request.targetRepositoryId ?? sourceRepository.id;
|
|
112
|
+
if (input.request.kind === "folder" && input.request.entry_id === input.request.targetFolderId
|
|
113
|
+
&& targetRepositoryId === sourceRepository.id)
|
|
114
|
+
invalid("cannot_target_self", "targetFolderId");
|
|
113
115
|
const locationRequest = {
|
|
114
116
|
entryId: input.request.entry_id,
|
|
115
117
|
kind: input.request.kind,
|
|
@@ -165,13 +167,16 @@ export function createDamUseCases(dependencies) {
|
|
|
165
167
|
if (input.repositoryId !== undefined)
|
|
166
168
|
return [{ id: input.repositoryId }];
|
|
167
169
|
signal.throwIfAborted();
|
|
168
|
-
const available = await dependencies.repositories.list({ access, signal });
|
|
170
|
+
const available = await dependencies.repositories.list({ access, signal, allowPartial: input.allRepositories === true });
|
|
169
171
|
signal.throwIfAborted();
|
|
170
172
|
if (available.length === 0)
|
|
171
173
|
throw new DamRepositoryNotFoundError();
|
|
174
|
+
const preferred = available.find(repository => repository.is_default);
|
|
175
|
+
if (!input.allRepositories && !preferred)
|
|
176
|
+
throw new RemoteProtocolError({}, undefined, "DAM_DEFAULT_REPOSITORY_UNKNOWN");
|
|
172
177
|
const selected = input.allRepositories === true
|
|
173
178
|
? available
|
|
174
|
-
: [
|
|
179
|
+
: [preferred];
|
|
175
180
|
return selected.map((repository) => ({
|
|
176
181
|
id: repository.repository_id,
|
|
177
182
|
...(repository.name === undefined ? {} : { name: repository.name })
|
|
@@ -180,7 +185,7 @@ export function createDamUseCases(dependencies) {
|
|
|
180
185
|
return {
|
|
181
186
|
async repositoryList({ access, signal }) {
|
|
182
187
|
signal.throwIfAborted();
|
|
183
|
-
const repositories = await dependencies.repositories.list({ access, signal });
|
|
188
|
+
const repositories = await dependencies.repositories.list({ access, signal, allowPartial: true });
|
|
184
189
|
signal.throwIfAborted();
|
|
185
190
|
if (repositories.length === 0)
|
|
186
191
|
throw new DamRepositoryNotFoundError();
|
|
@@ -19,7 +19,6 @@ export function createEditorBridgeClient(options) {
|
|
|
19
19
|
async health(signal) {
|
|
20
20
|
const value = await request("/health", "GET", undefined, signal);
|
|
21
21
|
if (!isRecord(value) ||
|
|
22
|
-
!hasExactKeys(value, ["status", "pageConnected", "protocolVersion"]) ||
|
|
23
22
|
value.status !== "ok" ||
|
|
24
23
|
typeof value.pageConnected !== "boolean" ||
|
|
25
24
|
typeof value.protocolVersion !== "number") {
|
|
@@ -42,7 +41,6 @@ export function createEditorBridgeClient(options) {
|
|
|
42
41
|
async disconnect(signal) {
|
|
43
42
|
const value = await request("/disconnect", "POST", {}, signal);
|
|
44
43
|
if (!isRecord(value) ||
|
|
45
|
-
!hasExactKeys(value, ["status"]) ||
|
|
46
44
|
value.status !== "disconnected") {
|
|
47
45
|
throw invalidResponse();
|
|
48
46
|
}
|
|
@@ -1,36 +1 @@
|
|
|
1
|
-
|
|
2
|
-
const PRIVATE_SEGMENTS = new Set([
|
|
3
|
-
"token",
|
|
4
|
-
"signature",
|
|
5
|
-
"secret",
|
|
6
|
-
"password",
|
|
7
|
-
"credential",
|
|
8
|
-
"credentials"
|
|
9
|
-
]);
|
|
10
|
-
const PRIVATE_FOCUSED_KEYS = new Set([
|
|
11
|
-
"focused-editor-token",
|
|
12
|
-
"focused-editor-port"
|
|
13
|
-
]);
|
|
14
|
-
export function toPublicEditorUrl(input) {
|
|
15
|
-
const output = new URL(input.href);
|
|
16
|
-
removePrivateParameters(output.searchParams);
|
|
17
|
-
const fragment = output.hash.slice(1);
|
|
18
|
-
if (fragment.includes("=") || fragment.includes("&")) {
|
|
19
|
-
const parameters = new URLSearchParams(fragment);
|
|
20
|
-
removePrivateParameters(parameters);
|
|
21
|
-
output.hash = parameters.toString();
|
|
22
|
-
}
|
|
23
|
-
return output;
|
|
24
|
-
}
|
|
25
|
-
function removePrivateParameters(parameters) {
|
|
26
|
-
for (const key of new Set(parameters.keys())) {
|
|
27
|
-
if (isPrivateKey(key))
|
|
28
|
-
parameters.delete(key);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
function isPrivateKey(key) {
|
|
32
|
-
const lower = key.toLowerCase();
|
|
33
|
-
if (isSensitiveKey(key) || PRIVATE_FOCUSED_KEYS.has(lower))
|
|
34
|
-
return true;
|
|
35
|
-
return lower.split(/[-_.]+/u).some((part) => PRIVATE_SEGMENTS.has(part));
|
|
36
|
-
}
|
|
1
|
+
export { filterUrlParameters as toPublicEditorUrl } from "../../platform/public-url.js";
|
|
@@ -206,11 +206,12 @@ function resolveTarget(value, createUrl, workUrl, restrictTargets) {
|
|
|
206
206
|
return url;
|
|
207
207
|
}
|
|
208
208
|
function buildHandoffUrl(target, state) {
|
|
209
|
-
const url = new
|
|
210
|
-
|
|
209
|
+
const url = toPublicEditorUrl(target, new Set(["focused-editor-token", "focused-editor-port"]));
|
|
210
|
+
const handshake = new URLSearchParams({
|
|
211
211
|
"focused-editor-port": String(state.port),
|
|
212
212
|
"focused-editor-token": state.token
|
|
213
213
|
}).toString();
|
|
214
|
+
url.hash = url.hash ? url.hash.slice(1) + "&" + handshake : handshake;
|
|
214
215
|
return url;
|
|
215
216
|
}
|
|
216
217
|
function abortableSleep(milliseconds, signal) {
|
|
@@ -23,8 +23,33 @@ export function createEditorUseCases(dependencies) {
|
|
|
23
23
|
},
|
|
24
24
|
async snapshot({ signal }) {
|
|
25
25
|
const raw = await dependencies.session.rpc("snapshot", undefined, signal);
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
if (!raw || typeof raw !== "object" || !("elements" in raw) || !Array.isArray(raw.elements) || !("selectedIds" in raw))
|
|
27
|
+
throw new OutputContractError();
|
|
28
|
+
const elements = [];
|
|
29
|
+
let skipped = 0;
|
|
30
|
+
for (const item of raw.elements) {
|
|
31
|
+
if (item && typeof item === "object") {
|
|
32
|
+
const keys = item._type === "shape" ? ["_type", "id", "shapeType", "x", "y", "w", "h", "text", "fill", "stroke"]
|
|
33
|
+
: item._type === "connector" ? ["_type", "id", "fromId", "toId", "lineType", "color"] : [];
|
|
34
|
+
const projected = Object.fromEntries(keys.filter(k => Object.hasOwn(item, k)).map(k => [k, item[k]]));
|
|
35
|
+
const one = { elements: [projected], selectedIds: [] };
|
|
36
|
+
try {
|
|
37
|
+
validate.snapshot(one);
|
|
38
|
+
elements.push(one.elements[0]);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (!(error instanceof OutputContractError))
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
skipped++;
|
|
47
|
+
}
|
|
48
|
+
if (skipped && !elements.length)
|
|
49
|
+
throw new OutputContractError();
|
|
50
|
+
if (skipped)
|
|
51
|
+
dependencies.onPartial?.(skipped);
|
|
52
|
+
const result = { elements, selectedIds: raw.selectedIds };
|
|
28
53
|
validate.snapshot(result);
|
|
29
54
|
return result;
|
|
30
55
|
},
|
|
@@ -16,13 +16,22 @@ export function createOrgService(dependencies) {
|
|
|
16
16
|
throw new OrganizationResponseError();
|
|
17
17
|
const records = [];
|
|
18
18
|
const seen = new Set();
|
|
19
|
+
let unreadable = 0;
|
|
19
20
|
for (const item of raw) {
|
|
20
21
|
const record = normalizeOrganization(item);
|
|
21
|
-
if (!record
|
|
22
|
+
if (!record) {
|
|
23
|
+
unreadable++;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (seen.has(record.id))
|
|
22
27
|
continue;
|
|
23
28
|
seen.add(record.id);
|
|
24
29
|
records.push(record);
|
|
25
30
|
}
|
|
31
|
+
if (unreadable && !records.length)
|
|
32
|
+
throw new OrganizationResponseError();
|
|
33
|
+
if (unreadable)
|
|
34
|
+
dependencies.onPartial?.(unreadable);
|
|
26
35
|
return records;
|
|
27
36
|
}
|
|
28
37
|
};
|
|
@@ -82,14 +82,28 @@ export function createOrgUseCases(dependencies) {
|
|
|
82
82
|
async switchOrganization(input) {
|
|
83
83
|
input.signal.throwIfAborted();
|
|
84
84
|
dependencies.telemetry.annotate({ account_id: input.state.account?.id });
|
|
85
|
-
const records = await dependencies.telemetry.stage("list", () =>
|
|
85
|
+
const records = await dependencies.telemetry.stage("list", async () => {
|
|
86
|
+
try {
|
|
87
|
+
return await dependencies.org.list(input.state.credential, input.signal);
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
input.signal.throwIfAborted();
|
|
91
|
+
if (input.organizationId === undefined || !isExpectedAuthorizationFailure(error))
|
|
92
|
+
throw error;
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
});
|
|
86
96
|
const { record, selectedId } = await dependencies.telemetry.stage("select", async () => {
|
|
87
97
|
const selectedId = input.organizationId === undefined
|
|
88
98
|
? await selectOrganization(records, input.select)
|
|
89
99
|
: requiredSelection(input.organizationId);
|
|
90
|
-
|
|
91
|
-
if (!record)
|
|
92
|
-
|
|
100
|
+
let record = records.find((candidate) => candidate.id === selectedId);
|
|
101
|
+
if (!record) {
|
|
102
|
+
if (input.organizationId === undefined)
|
|
103
|
+
throw new OrganizationInvalidError();
|
|
104
|
+
// The bind endpoint validates current membership; the discovery list is not an authorization decision.
|
|
105
|
+
record = { id: selectedId, realName: null, publicName: `组织 ${selectedId}` };
|
|
106
|
+
}
|
|
93
107
|
return { record, selectedId };
|
|
94
108
|
});
|
|
95
109
|
dependencies.telemetry.annotate({ parameters: { organizationId: selectedId } });
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
// If the OS cannot supply a start identity, an active worker renews its lease.
|
|
5
|
+
// An old PID alone must never keep a crashed worker's claim indefinitely.
|
|
6
|
+
const LEASE_MS = 60_000;
|
|
7
|
+
let ownGeneration;
|
|
8
|
+
function processGeneration(pid) {
|
|
9
|
+
try {
|
|
10
|
+
if (process.platform === "linux") {
|
|
11
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
12
|
+
// comm may contain spaces and parentheses. Fields after its final ')' start with field 3.
|
|
13
|
+
const startTicks = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
|
|
14
|
+
if (!startTicks || !/^\d+$/u.test(startTicks))
|
|
15
|
+
return;
|
|
16
|
+
return `${readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim()}:${startTicks}`;
|
|
17
|
+
}
|
|
18
|
+
const win = process.platform === "win32";
|
|
19
|
+
const command = win ? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "/bin/ps";
|
|
20
|
+
const stamp = execFileSync(command, win
|
|
21
|
+
? ["-NoProfile", "-NonInteractive", "-Command", `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`]
|
|
22
|
+
: ["-p", String(pid), "-o", "lstart="], {
|
|
23
|
+
encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 700, windowsHide: true,
|
|
24
|
+
env: { ...process.env, LC_ALL: "C", TZ: "UTC" }
|
|
25
|
+
}).trim();
|
|
26
|
+
return stamp || undefined;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function taskProcessGeneration(pid = process.pid) {
|
|
33
|
+
if (pid !== process.pid)
|
|
34
|
+
return processGeneration(pid);
|
|
35
|
+
if (ownGeneration === undefined)
|
|
36
|
+
ownGeneration = processGeneration(process.pid) ?? null;
|
|
37
|
+
return ownGeneration ?? undefined;
|
|
38
|
+
}
|
|
39
|
+
export function taskProcessAlive(pid, generation, heartbeatAtMs) {
|
|
40
|
+
if (!Number.isSafeInteger(pid) || !pid || pid <= 0)
|
|
41
|
+
return false;
|
|
42
|
+
try {
|
|
43
|
+
process.kill(pid, 0);
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error instanceof Error && "code" in error && error.code === "ESRCH")
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
if (generation && pid === process.pid)
|
|
50
|
+
return generation === taskProcessGeneration();
|
|
51
|
+
if (Number.isFinite(heartbeatAtMs) && Math.abs(Date.now() - heartbeatAtMs) < LEASE_MS)
|
|
52
|
+
return true;
|
|
53
|
+
return !!generation && generation === processGeneration(pid);
|
|
54
|
+
}
|
|
@@ -9,6 +9,19 @@ export class TaskStoreError extends LocalFileError {
|
|
|
9
9
|
constructor(cause) { super(cause); this.name = "TaskStoreError"; }
|
|
10
10
|
}
|
|
11
11
|
export const validTaskId = (id) => /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/iu.test(id);
|
|
12
|
+
function mergeProgress(previous, incoming) {
|
|
13
|
+
const progress = { ...previous, ...incoming };
|
|
14
|
+
for (const key of ["accepted", "submissionStarted", "detached", "agentUsageModelMissing", "agentUsageAmountMissing"]) {
|
|
15
|
+
if (previous[key])
|
|
16
|
+
progress[key] = true;
|
|
17
|
+
}
|
|
18
|
+
// A stale reader or heartbeat cannot roll back child receipts or a saved final PNG.
|
|
19
|
+
const previousCheckpoint = previous.toolPipeline?.checkpoint;
|
|
20
|
+
if (previous.toolPipeline && previousCheckpoint !== undefined && previousCheckpoint >= (incoming.toolPipeline?.checkpoint ?? 0)) {
|
|
21
|
+
progress.toolPipeline = previous.toolPipeline;
|
|
22
|
+
}
|
|
23
|
+
return progress;
|
|
24
|
+
}
|
|
12
25
|
export function taskScope(state) {
|
|
13
26
|
return createHash("sha256").update(JSON.stringify([
|
|
14
27
|
state.account ? ["account", state.account.id] : ["credential", state.credential.accessKey],
|
|
@@ -47,6 +60,10 @@ export function createTaskStore(options) {
|
|
|
47
60
|
if (record.version !== 1 || record.task.taskId !== id || !record.progress
|
|
48
61
|
|| typeof record.progress !== "object" || Array.isArray(record.progress))
|
|
49
62
|
throw new Error();
|
|
63
|
+
if (Object.hasOwn(record.progress, "toolRun") && !["completed", "failed"].includes(record.task.state)) {
|
|
64
|
+
record.task.state = "unknown";
|
|
65
|
+
delete record.task.note;
|
|
66
|
+
}
|
|
50
67
|
if (summaryOnly && options.validateSummary) {
|
|
51
68
|
const { result, partialResult, ...summary } = record.task;
|
|
52
69
|
options.validateSummary(summary);
|
|
@@ -67,7 +84,7 @@ export function createTaskStore(options) {
|
|
|
67
84
|
if (record.progress[key] !== undefined && typeof record.progress[key] !== "string")
|
|
68
85
|
throw new Error();
|
|
69
86
|
}
|
|
70
|
-
for (const key of ["submissionStarted", "detached", "accepted", "agentUsageModelMissing"]) {
|
|
87
|
+
for (const key of ["submissionStarted", "detached", "accepted", "agentUsageModelMissing", "agentUsageAmountMissing"]) {
|
|
71
88
|
if (record.progress[key] !== undefined && typeof record.progress[key] !== "boolean")
|
|
72
89
|
throw new Error();
|
|
73
90
|
}
|
|
@@ -82,13 +99,10 @@ export function createTaskStore(options) {
|
|
|
82
99
|
await withFileLock(join(root, scope, `${record.task.taskId}.lock`), async () => {
|
|
83
100
|
const previous = await store.read(scope, record.task.taskId);
|
|
84
101
|
if (previous) {
|
|
85
|
-
record.progress =
|
|
86
|
-
|
|
87
|
-
if (previous.progress[key])
|
|
88
|
-
record.progress[key] = true;
|
|
89
|
-
}
|
|
90
|
-
if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed"))
|
|
102
|
+
record.progress = mergeProgress(previous.progress, record.progress);
|
|
103
|
+
if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed")) {
|
|
91
104
|
record.task = previous.task;
|
|
105
|
+
}
|
|
92
106
|
if (previous.analytics)
|
|
93
107
|
record.analytics = { ...record.analytics, ...previous.analytics };
|
|
94
108
|
if (previous.telemetry) {
|
|
@@ -127,12 +141,25 @@ export function createTaskStore(options) {
|
|
|
127
141
|
throw new LocalFileError(error, undefined, "io", { operation: "list", step: "directory_read" });
|
|
128
142
|
}
|
|
129
143
|
const records = [];
|
|
144
|
+
const corrupt = [];
|
|
130
145
|
for (const name of names) {
|
|
131
146
|
if (!name.endsWith(".json") || !validTaskId(name.slice(0, -5)))
|
|
132
147
|
continue;
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
148
|
+
try {
|
|
149
|
+
const record = await store.read(scope, name.slice(0, -5), true);
|
|
150
|
+
if (record)
|
|
151
|
+
records.push(record);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
if (!(error instanceof LocalFileError) || error.reason !== "invalid_data")
|
|
155
|
+
throw error;
|
|
156
|
+
corrupt.push(error);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (corrupt.length) {
|
|
160
|
+
if (!records.length)
|
|
161
|
+
throw corrupt[0];
|
|
162
|
+
options.onUnreadableRecords?.(corrupt.length);
|
|
136
163
|
}
|
|
137
164
|
return records.sort((a, b) => b.task.createdAt.localeCompare(a.task.createdAt)
|
|
138
165
|
|| a.task.taskId.localeCompare(b.task.taskId));
|
|
@@ -89,7 +89,7 @@ export function taskWorkerUnavailableError(options) {
|
|
|
89
89
|
}
|
|
90
90
|
export function createTaskBackgroundLauncher(options) {
|
|
91
91
|
return {
|
|
92
|
-
submit(job, signal, started) {
|
|
92
|
+
submit(job, signal, started, observeReceipt) {
|
|
93
93
|
signal.throwIfAborted();
|
|
94
94
|
return new Promise((resolve, reject) => {
|
|
95
95
|
let child;
|
|
@@ -145,9 +145,12 @@ export function createTaskBackgroundLauncher(options) {
|
|
|
145
145
|
child.on("message", (message) => {
|
|
146
146
|
if (settled)
|
|
147
147
|
return;
|
|
148
|
+
if (message.type !== "error" && message.execution_protocol && ["dify", "toolkit", "sync"].includes(message.execution_protocol)) {
|
|
149
|
+
observeReceipt?.({ execution_protocol: message.execution_protocol });
|
|
150
|
+
}
|
|
148
151
|
if (message.type === "started") {
|
|
149
152
|
taskId = message.task.taskId;
|
|
150
|
-
started(message.task);
|
|
153
|
+
started(message.task, diagnosticToken(message.creationTraceId, /^[0-9a-f]{32}$/u));
|
|
151
154
|
}
|
|
152
155
|
else if (message.type === "accepted")
|
|
153
156
|
finish(message.task);
|