pi-web-ui 0.116.0 → 0.117.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/CHANGELOG.md +38 -4
- package/bin/device-hub-cli.mjs +26 -3
- package/bin/pi-web-ui.mjs +138 -70
- package/dist/server/agent-service-daemon.js +52 -6
- package/dist/server/agent-service.js +495 -141
- package/dist/server/canvas/canvas-workspace.js +18 -86
- package/dist/server/client-state.js +35 -6
- package/dist/server/compaction-markers.js +43 -24
- package/dist/server/dangling-tools.js +172 -16
- package/dist/server/device-center/bot-execution.js +48 -1
- package/dist/server/device-center/collab-service.js +26 -8
- package/dist/server/device-center/collab-tool.js +394 -18
- package/dist/server/device-center/connector.js +107 -37
- package/dist/server/device-center/delivery-authority.js +98 -0
- package/dist/server/device-center/delivery-subject.js +30 -0
- package/dist/server/device-center/device-integration.js +453 -183
- package/dist/server/device-center/execution-guides.js +15 -5
- package/dist/server/device-center/executor.js +47 -5
- package/dist/server/device-center/hub-conversations.js +14 -4
- package/dist/server/device-center/hub-deliveries.js +120 -15
- package/dist/server/device-center/hub-integration.js +655 -334
- package/dist/server/device-center/hub-page.js +5 -4
- package/dist/server/device-center/hub-setup.js +23 -1
- package/dist/server/device-center/hub-transaction-log.js +197 -0
- package/dist/server/device-center/hub.js +772 -354
- package/dist/server/device-center/integration-verification.js +113 -0
- package/dist/server/device-center/local-hub.js +6 -2
- package/dist/server/device-center/local-publication.js +423 -0
- package/dist/server/device-center/local-verification-job.js +97 -0
- package/dist/server/device-center/local-verification.js +274 -0
- package/dist/server/device-center/local.js +107 -12
- package/dist/server/device-center/main.js +4 -1
- package/dist/server/device-center/partition-log.js +62 -25
- package/dist/server/device-center/publication-journal.js +312 -0
- package/dist/server/device-center/publish-intent.js +379 -0
- package/dist/server/device-center/relay.js +134 -24
- package/dist/server/device-center/runtime.js +426 -42
- package/dist/server/device-center/store.js +225 -47
- package/dist/server/device-center/task-outcome.js +81 -0
- package/dist/server/device-center/task-recovery.js +603 -178
- package/dist/server/device-center/task-settlement.js +353 -0
- package/dist/server/device-center/task-workspace.js +443 -0
- package/dist/server/device-center/verification-limits.js +10 -0
- package/dist/server/device-center/work-contract.js +995 -0
- package/dist/server/dispatch-domain-handlers.js +15 -0
- package/dist/server/dsh/dsh-agent-service.js +9 -2
- package/dist/server/index.js +26 -1
- package/dist/server/patch-node-pty.js +3 -2
- package/dist/server/patch-remote-catalog.js +3 -2
- package/dist/server/preset-fields.js +17 -1
- package/dist/server/preset-share.js +1 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/quick-ask-settings.js +28 -0
- package/dist/server/quick-ask.js +164 -0
- package/dist/server/resolve-global-sdk.js +61 -11
- package/dist/server/scheduler-tasks.js +35 -8
- package/dist/server/session-list-scan.js +223 -0
- package/dist/server/session-open.js +93 -0
- package/dist/server/session-parser.js +4 -0
- package/dist/server/session-scan.js +90 -38
- package/dist/server/settings-service.js +9 -1
- package/dist/server/soft-cap.js +5 -0
- package/dist/server/transcript-prepare.js +73 -0
- package/dist/server/universal/drivers/claude-code.js +98 -34
- package/dist/server/universal/universal-session.js +4 -0
- package/dist/server/workspace-handle.js +428 -0
- package/docs/architecture-plugins.md +18 -5
- package/docs/device-center.md +30 -22
- package/package.json +3 -4
- package/plugin-sdk/README.md +16 -8
- package/plugin-sdk/client.d.ts +27 -0
- package/plugin-sdk/client.mjs +82 -0
- package/plugin-sdk/index.d.ts +10 -0
- package/plugin-sdk/index.mjs +4 -683
- package/plugin-sdk/package.json +15 -4
- package/plugin-sdk/testing.d.ts +10 -0
- package/plugin-sdk/testing.mjs +566 -0
- package/themes/flow-cristallo.css +168 -0
- package/themes/flow-ink.css +169 -0
- package/themes/flow-obsidian.css +169 -0
- package/themes/flow-zurich.css +169 -0
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
- package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
- package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
- package/web/dist/assets/{CanvasStudio-zSxyIx1R.js → CanvasStudio-VQFjmTGq.js} +3 -3
- package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
- package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
- package/web/dist/assets/{DeviceExecutionSettings-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
- package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
- package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
- package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CQtstPGv.js} +1 -1
- package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
- package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
- package/web/dist/assets/{GlobalSearchModal-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-F7fNimKk.js → GlobalSearchModal-DGv_WINq.js} +1 -1
- package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
- package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
- package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-ChTW8o1m.js} +1 -1
- package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
- package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
- package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
- package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
- package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
- package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
- package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
- package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
- package/web/dist/assets/{TerminalPanel-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
- package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
- package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
- package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
- package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
- package/web/dist/assets/{desktop-aAKpvKJV.js → desktop-CV6KKp9R.js} +1 -1
- package/web/dist/assets/index-BawF7ZP5.js +397 -0
- package/web/dist/assets/index-BoGCoq5X.js +397 -0
- package/web/dist/assets/index-CVW9FoY2.css +1 -0
- package/web/dist/assets/{plugin-host-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
- package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
- package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
- package/web/dist/index.html +11 -11
- package/web/dist/sw.js +1 -1
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/device-center/local-page.js +0 -17
- package/dist/server/device-center/smoke-preview.js +0 -3
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/patch-turn-end-boundary.js +0 -77
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
- package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
- package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
- package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
- package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
- package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
- package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
- package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
- package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
- package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
- package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
- package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
- package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
- package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
- package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
- package/web/dist/assets/index-C6DwztqE.css +0 -1
- package/web/dist/assets/index-CuN802Sj.js +0 -93
- package/web/dist/assets/index-EH5Fw9fa.js +0 -93
|
@@ -1,16 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { readFileSync } from "node:fs";
|
|
1
|
+
import { readFileSync, unlinkSync } from "node:fs";
|
|
3
2
|
import { join } from "node:path";
|
|
4
3
|
import { writeAtomicSync } from "../atomic-file.js";
|
|
5
|
-
import { deviceTaskFailure } from "./task-error.js";
|
|
6
|
-
import { boundTaskReport } from "./task-report.js";
|
|
7
4
|
import { parseReportMetadata } from "./report-metadata.js";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
5
|
+
import { TASK_REPORT_BYTES } from "./task-report.js";
|
|
6
|
+
import { computeOutcomeFingerprint, computeLegacyOutcomeFingerprint, normalizeTaskOutcome, TASK_OUTCOME_ERROR_BYTES, } from "./task-outcome.js";
|
|
7
|
+
import { validateDeviceArtifact } from "./work-contract.js";
|
|
8
|
+
export { computeOutcomeFingerprint, normalizeTaskOutcome };
|
|
9
|
+
export const TASK_QUARANTINE_LIMITS = { maxEntries: 128, maxTotalBytes: 2 * 1024 * 1024 };
|
|
10
|
+
/** Includes both outcome budgets, active leases and serialization overhead. */
|
|
11
|
+
export const TASK_RECOVERY_STATE_MAX_BYTES = 8 * 1024 * 1024;
|
|
14
12
|
export const TASK_RECOVERY_DEFAULTS = {
|
|
15
13
|
maxInactivityMs: 20 * 60 * 1000, // 20 minutes without activity (human waits pause this)
|
|
16
14
|
maxDurationMs: 0, // 0 = unbounded overall duration by default (honors long-running jobs)
|
|
@@ -21,152 +19,361 @@ export const TASK_OUTBOX_LIMITS = {
|
|
|
21
19
|
maxEntries: 128,
|
|
22
20
|
maxTotalBytes: 2 * 1024 * 1024, // 2 MiB bounded durable storage budget
|
|
23
21
|
};
|
|
22
|
+
// Reserve worst-case JSON escaping, artifact patchBase64, plus bounded identity and metadata overhead before execution.
|
|
23
|
+
export const TASK_ARTIFACT_WORST_CASE_BYTES = 256 * 1024;
|
|
24
|
+
export const TASK_OUTBOX_RESERVATION_BYTES = 6 * (TASK_REPORT_BYTES + TASK_OUTCOME_ERROR_BYTES) + 16 * 1024 + TASK_ARTIFACT_WORST_CASE_BYTES;
|
|
25
|
+
function validateOutboxItem(item, deviceId) {
|
|
26
|
+
if (!item ||
|
|
27
|
+
typeof item !== "object" ||
|
|
28
|
+
typeof item.id !== "string" ||
|
|
29
|
+
!item.id ||
|
|
30
|
+
item.id.length > 257 ||
|
|
31
|
+
typeof item.taskId !== "string" ||
|
|
32
|
+
!item.taskId ||
|
|
33
|
+
item.taskId.length > 128 ||
|
|
34
|
+
typeof item.attemptId !== "string" ||
|
|
35
|
+
!item.attemptId ||
|
|
36
|
+
item.attemptId.length > 128 ||
|
|
37
|
+
typeof item.botId !== "string" ||
|
|
38
|
+
!item.botId ||
|
|
39
|
+
item.botId.length > 128 ||
|
|
40
|
+
item.deviceId !== deviceId ||
|
|
41
|
+
!["completed", "failed", "interrupted"].includes(item.status) ||
|
|
42
|
+
!Number.isSafeInteger(item.createdAt) ||
|
|
43
|
+
item.createdAt <= 0 ||
|
|
44
|
+
!Number.isSafeInteger(item.updatedAt) ||
|
|
45
|
+
!Number.isSafeInteger(item.attempts)) {
|
|
46
|
+
throw new Error("Invalid outbox item schema");
|
|
47
|
+
}
|
|
48
|
+
const entry = item;
|
|
49
|
+
if (entry.id !== `${entry.taskId}:${entry.attemptId}` ||
|
|
50
|
+
(entry.report !== undefined && typeof entry.report !== "string") ||
|
|
51
|
+
(entry.error !== undefined && typeof entry.error !== "string"))
|
|
52
|
+
throw new Error("Invalid outbox identity or content");
|
|
53
|
+
if (entry.reportMetadata !== undefined) {
|
|
54
|
+
entry.reportMetadata = parseReportMetadata(entry.reportMetadata);
|
|
55
|
+
}
|
|
56
|
+
if (entry.artifact !== undefined) {
|
|
57
|
+
const res = validateDeviceArtifact(entry.artifact);
|
|
58
|
+
if (!res.valid)
|
|
59
|
+
throw new Error(`Invalid outbox artifact: ${res.reason}`);
|
|
60
|
+
}
|
|
61
|
+
if (entry.leaseToken !== undefined && (typeof entry.leaseToken !== "string" || entry.leaseToken.length > 128)) {
|
|
62
|
+
throw new Error("Invalid outbox leaseToken");
|
|
63
|
+
}
|
|
64
|
+
if (entry.leaseGeneration !== undefined &&
|
|
65
|
+
(!Number.isSafeInteger(entry.leaseGeneration) || entry.leaseGeneration < 1)) {
|
|
66
|
+
throw new Error("Invalid outbox leaseGeneration");
|
|
67
|
+
}
|
|
68
|
+
if (entry.hubUrl !== undefined && (typeof entry.hubUrl !== "string" || entry.hubUrl.length > 512)) {
|
|
69
|
+
throw new Error("Invalid outbox hubUrl");
|
|
70
|
+
}
|
|
71
|
+
const hasProofOrArtifact = entry.artifact !== undefined || entry.executionCompleted !== undefined || entry.artifactProduced !== undefined;
|
|
72
|
+
const fingerprint = computeOutcomeFingerprint(entry.taskId, entry.attemptId, entry.status, entry.report, entry.error, entry.reportMetadata, entry.artifact?.digest, entry.executionCompleted, entry.artifactProduced);
|
|
73
|
+
if (hasProofOrArtifact) {
|
|
74
|
+
// 当有新字段时必须且只能匹配 canonical 指纹,禁止降级到旧指纹
|
|
75
|
+
if (entry.fingerprint !== undefined && entry.fingerprint !== fingerprint) {
|
|
76
|
+
throw new Error("Invalid outbox outcome fingerprint (proof bound artifact requires canonical fingerprint)");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
// 仅在无 artifact / proof 的旧项中允许 legacy 指纹
|
|
81
|
+
const legacyFingerprint = computeLegacyOutcomeFingerprint(entry.taskId, entry.attemptId, entry.status, entry.report, entry.error, entry.reportMetadata);
|
|
82
|
+
if (entry.fingerprint !== undefined &&
|
|
83
|
+
entry.fingerprint !== fingerprint &&
|
|
84
|
+
entry.fingerprint !== legacyFingerprint) {
|
|
85
|
+
throw new Error("Invalid outbox outcome fingerprint");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
entry.fingerprint ??= fingerprint;
|
|
89
|
+
return entry;
|
|
90
|
+
}
|
|
91
|
+
function validateLeaseItem(item, deviceId) {
|
|
92
|
+
if (!item ||
|
|
93
|
+
typeof item !== "object" ||
|
|
94
|
+
typeof item.taskId !== "string" ||
|
|
95
|
+
!item.taskId ||
|
|
96
|
+
item.taskId.length > 128 ||
|
|
97
|
+
typeof item.attemptId !== "string" ||
|
|
98
|
+
!item.attemptId ||
|
|
99
|
+
item.attemptId.length > 128 ||
|
|
100
|
+
typeof item.botId !== "string" ||
|
|
101
|
+
!item.botId ||
|
|
102
|
+
item.botId.length > 128 ||
|
|
103
|
+
typeof item.roomId !== "string" ||
|
|
104
|
+
!item.roomId ||
|
|
105
|
+
item.roomId.length > 128 ||
|
|
106
|
+
typeof item.leaseToken !== "string" ||
|
|
107
|
+
!item.leaseToken ||
|
|
108
|
+
item.leaseToken.length > 128 ||
|
|
109
|
+
!Number.isSafeInteger(item.leaseGeneration) ||
|
|
110
|
+
item.deviceId !== deviceId ||
|
|
111
|
+
!Number.isSafeInteger(item.startedAt) ||
|
|
112
|
+
item.startedAt <= 0 ||
|
|
113
|
+
!Number.isSafeInteger(item.lastActivityAt) ||
|
|
114
|
+
!Number.isSafeInteger(item.lastRenewedActivityAt)) {
|
|
115
|
+
throw new Error("Invalid lease item schema");
|
|
116
|
+
}
|
|
117
|
+
const lease = item;
|
|
118
|
+
if (lease.hubUrl !== undefined && (typeof lease.hubUrl !== "string" || lease.hubUrl.length > 512)) {
|
|
119
|
+
throw new Error("Invalid lease hubUrl");
|
|
120
|
+
}
|
|
121
|
+
return lease;
|
|
122
|
+
}
|
|
24
123
|
/**
|
|
25
124
|
* Durable Task Recovery Manager:
|
|
26
|
-
* 1.
|
|
27
|
-
* 2.
|
|
28
|
-
* 3.
|
|
125
|
+
* 1. Single unified versioned recovery state file for active leases & terminal outbox.
|
|
126
|
+
* 2. Atomic disk commit guarantees lease removal and terminal outcome entry happen in a single transaction.
|
|
127
|
+
* 3. Double-crash safe recovery: never blindly re-runs side effects; safely interrupts orphans and preserves outcomes.
|
|
128
|
+
* 4. Outcome immutability: identical retry is idempotent; conflicting outcome is strictly rejected.
|
|
129
|
+
* 5. ACK binding: strictly requires matching outcome fingerprint to clear outbox.
|
|
130
|
+
* 6. Hub fencing & isolation: leases carry leaseToken & generation into TaskOutboxEntry; entries are isolated per hubUrl.
|
|
29
131
|
*/
|
|
30
132
|
export class TaskRecoveryManager {
|
|
31
|
-
|
|
32
|
-
|
|
133
|
+
statePath;
|
|
134
|
+
legacyOutboxPath;
|
|
135
|
+
legacyLeasesPath;
|
|
33
136
|
deviceId;
|
|
34
137
|
hubUrl;
|
|
35
138
|
maxInactivityMs;
|
|
36
139
|
maxDurationMs;
|
|
37
140
|
outbox = new Map();
|
|
38
141
|
activeLeases = new Map();
|
|
142
|
+
otherHubOutbox = [];
|
|
143
|
+
otherHubLeases = [];
|
|
39
144
|
haltedOrphans = [];
|
|
40
|
-
|
|
41
|
-
|
|
145
|
+
loadError = false;
|
|
146
|
+
quarantine = [];
|
|
42
147
|
constructor(options) {
|
|
43
148
|
this.deviceId = options.deviceId;
|
|
44
149
|
this.hubUrl = options.hubUrl;
|
|
45
150
|
this.maxInactivityMs = options.maxInactivityMs ?? TASK_RECOVERY_DEFAULTS.maxInactivityMs;
|
|
46
151
|
this.maxDurationMs = options.maxDurationMs ?? TASK_RECOVERY_DEFAULTS.maxDurationMs;
|
|
47
152
|
if (options.dataDir) {
|
|
48
|
-
this.
|
|
49
|
-
this.
|
|
153
|
+
this.statePath = join(options.dataDir, "task-recovery-state.json");
|
|
154
|
+
this.legacyOutboxPath = join(options.dataDir, "task-recovery-outbox.json");
|
|
155
|
+
this.legacyLeasesPath = join(options.dataDir, "task-active-leases.json");
|
|
50
156
|
}
|
|
51
|
-
this.
|
|
52
|
-
|
|
157
|
+
this.loadStateAndMigrate(options.onHaltOrphaned);
|
|
158
|
+
}
|
|
159
|
+
get outboxLoadError() {
|
|
160
|
+
return this.loadError;
|
|
161
|
+
}
|
|
162
|
+
get leasesLoadError() {
|
|
163
|
+
return this.loadError;
|
|
53
164
|
}
|
|
54
165
|
leaseKey(taskId, attemptId) {
|
|
55
166
|
return `${taskId}:${attemptId}`;
|
|
56
167
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
throw new Error("Invalid outbox data root");
|
|
65
|
-
const seenKeys = new Set();
|
|
66
|
-
for (const item of data) {
|
|
67
|
-
if (!item ||
|
|
68
|
-
typeof item !== "object" ||
|
|
69
|
-
typeof item.id !== "string" ||
|
|
70
|
-
item.id.length > 128 ||
|
|
71
|
-
typeof item.taskId !== "string" ||
|
|
72
|
-
item.taskId.length > 128 ||
|
|
73
|
-
typeof item.attemptId !== "string" ||
|
|
74
|
-
item.attemptId.length > 128 ||
|
|
75
|
-
typeof item.botId !== "string" ||
|
|
76
|
-
item.botId.length > 128 ||
|
|
77
|
-
item.deviceId !== this.deviceId ||
|
|
78
|
-
!["completed", "failed", "interrupted"].includes(item.status) ||
|
|
79
|
-
!Number.isSafeInteger(item.createdAt) ||
|
|
80
|
-
item.createdAt <= 0 ||
|
|
81
|
-
!Number.isSafeInteger(item.updatedAt) ||
|
|
82
|
-
!Number.isSafeInteger(item.attempts)) {
|
|
83
|
-
throw new Error("Invalid outbox item schema");
|
|
84
|
-
}
|
|
85
|
-
if (item.reportMetadata !== undefined)
|
|
86
|
-
item.reportMetadata = parseReportMetadata(item.reportMetadata);
|
|
87
|
-
const key = item.id;
|
|
88
|
-
if (seenKeys.has(key))
|
|
89
|
-
throw new Error("Duplicate outbox key");
|
|
90
|
-
seenKeys.add(key);
|
|
91
|
-
this.outbox.set(key, item);
|
|
168
|
+
matchesHub(entryHubUrl) {
|
|
169
|
+
return this.hubUrl === entryHubUrl;
|
|
170
|
+
}
|
|
171
|
+
cleanupLegacyFiles() {
|
|
172
|
+
if (this.legacyOutboxPath) {
|
|
173
|
+
try {
|
|
174
|
+
unlinkSync(this.legacyOutboxPath);
|
|
92
175
|
}
|
|
176
|
+
catch { }
|
|
93
177
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
178
|
+
if (this.legacyLeasesPath) {
|
|
179
|
+
try {
|
|
180
|
+
unlinkSync(this.legacyLeasesPath);
|
|
97
181
|
}
|
|
98
|
-
|
|
99
|
-
this.outboxLoadError = true;
|
|
182
|
+
catch { }
|
|
100
183
|
}
|
|
101
184
|
}
|
|
102
|
-
|
|
103
|
-
if (!this.
|
|
185
|
+
writeStateToDiskSync(state) {
|
|
186
|
+
if (!this.statePath)
|
|
104
187
|
return;
|
|
105
|
-
if (this.
|
|
188
|
+
if (this.loadError) {
|
|
106
189
|
throw new Error("Outbox persistence blocked: corrupted storage was preserved");
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
if (this.leasesLoadError)
|
|
114
|
-
throw new Error("Active leases persistence blocked: corrupted storage was preserved");
|
|
115
|
-
const text = JSON.stringify(entries, null, 2) + "\n";
|
|
116
|
-
writeAtomicSync(this.leasesPath, text, { mode: 0o600 });
|
|
190
|
+
}
|
|
191
|
+
// v2 prevents older readers from silently discarding archived terminal evidence.
|
|
192
|
+
const text = JSON.stringify({ ...state, version: 2, quarantine: state.quarantine ?? this.quarantine }, null, 2) + "\n";
|
|
193
|
+
if (Buffer.byteLength(text) > TASK_RECOVERY_STATE_MAX_BYTES)
|
|
194
|
+
throw new Error("Recovery state capacity exceeded; evidence retained");
|
|
195
|
+
writeAtomicSync(this.statePath, text, { mode: 0o600, fsync: true });
|
|
117
196
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
* Explicit safety requirement: NEVER blindly rerun side-effects!
|
|
121
|
-
* Mark orphaned tasks as safely interrupted and stage them into Outbox,
|
|
122
|
-
* EXCEPT if an existing completed/terminal outcome is already in Outbox.
|
|
123
|
-
*/
|
|
124
|
-
loadAndDetectOrphanLeases(onHaltOrphaned) {
|
|
125
|
-
if (!this.leasesPath)
|
|
197
|
+
loadStateAndMigrate(onHaltOrphaned) {
|
|
198
|
+
if (!this.statePath)
|
|
126
199
|
return;
|
|
127
|
-
let
|
|
200
|
+
let loadedState = null;
|
|
201
|
+
// 1. Try reading the unified state file
|
|
128
202
|
try {
|
|
129
|
-
const raw = readFileSync(this.
|
|
203
|
+
const raw = readFileSync(this.statePath, "utf8");
|
|
204
|
+
if (Buffer.byteLength(raw) > TASK_RECOVERY_STATE_MAX_BYTES)
|
|
205
|
+
throw new Error("Recovery state capacity exceeded");
|
|
130
206
|
const parsed = JSON.parse(raw);
|
|
131
|
-
if (!
|
|
132
|
-
throw new Error("Invalid
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
typeof x.attemptId !== "string" ||
|
|
140
|
-
x.attemptId.length > 128 ||
|
|
141
|
-
typeof x.botId !== "string" ||
|
|
142
|
-
x.botId.length > 128 ||
|
|
143
|
-
typeof x.roomId !== "string" ||
|
|
144
|
-
x.roomId.length > 128 ||
|
|
145
|
-
typeof x.leaseToken !== "string" ||
|
|
146
|
-
x.leaseToken.length > 128 ||
|
|
147
|
-
!Number.isSafeInteger(x.leaseGeneration) ||
|
|
148
|
-
x.deviceId !== this.deviceId ||
|
|
149
|
-
!Number.isSafeInteger(x.startedAt) ||
|
|
150
|
-
x.startedAt <= 0 ||
|
|
151
|
-
!Number.isSafeInteger(x.lastActivityAt) ||
|
|
152
|
-
!Number.isSafeInteger(x.lastRenewedActivityAt)) {
|
|
153
|
-
throw new Error("Invalid lease item schema");
|
|
154
|
-
}
|
|
155
|
-
const key = this.leaseKey(x.taskId, x.attemptId);
|
|
156
|
-
if (seenKeys.has(key))
|
|
157
|
-
throw new Error("Duplicate active lease key");
|
|
158
|
-
seenKeys.add(key);
|
|
159
|
-
stored.push(x);
|
|
207
|
+
if (!parsed || typeof parsed !== "object" || ![1, 2].includes(parsed.version)) {
|
|
208
|
+
throw new Error("Invalid recovery state file version or root");
|
|
209
|
+
}
|
|
210
|
+
if (typeof parsed.deviceId !== "string" || parsed.deviceId !== this.deviceId) {
|
|
211
|
+
throw new Error("Invalid recovery state file deviceId binding");
|
|
212
|
+
}
|
|
213
|
+
if (!Array.isArray(parsed.outbox) || !Array.isArray(parsed.activeLeases)) {
|
|
214
|
+
throw new Error("Invalid recovery state file collections");
|
|
160
215
|
}
|
|
216
|
+
if (parsed.version === 2) {
|
|
217
|
+
if (!Array.isArray(parsed.quarantine))
|
|
218
|
+
throw new Error("Invalid quarantine collection");
|
|
219
|
+
const seen = new Set();
|
|
220
|
+
const archive = parsed.quarantine.map((item) => {
|
|
221
|
+
if (!item ||
|
|
222
|
+
!["terminal_conflict", "attempt_expired", "legacy_lease_missing"].includes(item.reasonCode) ||
|
|
223
|
+
!Number.isSafeInteger(item.quarantinedAt) ||
|
|
224
|
+
item.quarantinedAt < 0)
|
|
225
|
+
throw new Error("Invalid quarantined outcome");
|
|
226
|
+
const outcome = validateOutboxItem(item.outcome, this.deviceId);
|
|
227
|
+
const key = JSON.stringify([outcome.hubUrl, outcome.id]);
|
|
228
|
+
if (seen.has(key))
|
|
229
|
+
throw new Error("Duplicate quarantined outcome");
|
|
230
|
+
seen.add(key);
|
|
231
|
+
return { outcome, reasonCode: item.reasonCode, quarantinedAt: item.quarantinedAt };
|
|
232
|
+
});
|
|
233
|
+
if (archive.length > TASK_QUARANTINE_LIMITS.maxEntries ||
|
|
234
|
+
Buffer.byteLength(JSON.stringify(archive)) > TASK_QUARANTINE_LIMITS.maxTotalBytes)
|
|
235
|
+
throw new Error("Quarantine capacity exceeded");
|
|
236
|
+
this.quarantine = archive;
|
|
237
|
+
}
|
|
238
|
+
else if (parsed.quarantine !== undefined)
|
|
239
|
+
throw new Error("Unexpected v1 quarantine");
|
|
240
|
+
const seenOutboxKeys = new Set();
|
|
241
|
+
const validOutbox = [];
|
|
242
|
+
for (const item of parsed.outbox) {
|
|
243
|
+
const entry = validateOutboxItem(item, this.deviceId);
|
|
244
|
+
entry.hubUrl ??= typeof parsed.hubUrl === "string" ? parsed.hubUrl : this.hubUrl;
|
|
245
|
+
const scopedKey = JSON.stringify([entry.hubUrl, entry.id]);
|
|
246
|
+
if (seenOutboxKeys.has(scopedKey) ||
|
|
247
|
+
this.quarantine.some((item) => JSON.stringify([item.outcome.hubUrl, item.outcome.id]) === scopedKey))
|
|
248
|
+
throw new Error("Duplicate outbox or quarantined key in state file");
|
|
249
|
+
seenOutboxKeys.add(scopedKey);
|
|
250
|
+
validOutbox.push(entry);
|
|
251
|
+
}
|
|
252
|
+
const seenLeaseKeys = new Set();
|
|
253
|
+
const validLeases = [];
|
|
254
|
+
for (const item of parsed.activeLeases) {
|
|
255
|
+
const lease = validateLeaseItem(item, this.deviceId);
|
|
256
|
+
lease.hubUrl ??= typeof parsed.hubUrl === "string" ? parsed.hubUrl : this.hubUrl;
|
|
257
|
+
const key = JSON.stringify([lease.hubUrl, this.leaseKey(lease.taskId, lease.attemptId)]);
|
|
258
|
+
if (seenLeaseKeys.has(key))
|
|
259
|
+
throw new Error("Duplicate active lease key in state file");
|
|
260
|
+
seenLeaseKeys.add(key);
|
|
261
|
+
validLeases.push(lease);
|
|
262
|
+
}
|
|
263
|
+
loadedState = {
|
|
264
|
+
version: 1,
|
|
265
|
+
deviceId: this.deviceId,
|
|
266
|
+
hubUrl: typeof parsed.hubUrl === "string" ? parsed.hubUrl : this.hubUrl,
|
|
267
|
+
outbox: validOutbox,
|
|
268
|
+
activeLeases: validLeases,
|
|
269
|
+
};
|
|
270
|
+
// Best-effort cleanup of any remaining legacy files
|
|
271
|
+
this.cleanupLegacyFiles();
|
|
161
272
|
}
|
|
162
273
|
catch (error) {
|
|
163
274
|
if (error.code === "ENOENT") {
|
|
275
|
+
loadedState = null;
|
|
276
|
+
}
|
|
277
|
+
else {
|
|
278
|
+
// State file exists but is corrupted: FAIL CLOSED and forbid overwrites
|
|
279
|
+
this.loadError = true;
|
|
164
280
|
return;
|
|
165
281
|
}
|
|
166
|
-
this.leasesLoadError = true;
|
|
167
|
-
return;
|
|
168
282
|
}
|
|
169
|
-
|
|
283
|
+
// 2. If unified state does not exist, migrate from legacy 2 files if present
|
|
284
|
+
if (loadedState === null) {
|
|
285
|
+
let legacyOutbox = [];
|
|
286
|
+
let legacyLeases = [];
|
|
287
|
+
let hasLegacy = false;
|
|
288
|
+
if (this.legacyOutboxPath) {
|
|
289
|
+
try {
|
|
290
|
+
const raw = readFileSync(this.legacyOutboxPath, "utf8");
|
|
291
|
+
hasLegacy = true;
|
|
292
|
+
const parsed = JSON.parse(raw);
|
|
293
|
+
if (!Array.isArray(parsed))
|
|
294
|
+
throw new Error("Invalid legacy outbox root");
|
|
295
|
+
const seenKeys = new Set();
|
|
296
|
+
for (const item of parsed) {
|
|
297
|
+
const entry = validateOutboxItem(item, this.deviceId);
|
|
298
|
+
if (seenKeys.has(entry.id))
|
|
299
|
+
throw new Error("Duplicate outbox key in legacy file");
|
|
300
|
+
seenKeys.add(entry.id);
|
|
301
|
+
entry.hubUrl ??= this.hubUrl;
|
|
302
|
+
legacyOutbox.push(entry);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
if (error.code !== "ENOENT") {
|
|
307
|
+
this.loadError = true;
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (this.legacyLeasesPath) {
|
|
313
|
+
try {
|
|
314
|
+
const raw = readFileSync(this.legacyLeasesPath, "utf8");
|
|
315
|
+
hasLegacy = true;
|
|
316
|
+
const parsed = JSON.parse(raw);
|
|
317
|
+
if (!Array.isArray(parsed))
|
|
318
|
+
throw new Error("Invalid legacy leases root");
|
|
319
|
+
const seenKeys = new Set();
|
|
320
|
+
for (const item of parsed) {
|
|
321
|
+
const lease = validateLeaseItem(item, this.deviceId);
|
|
322
|
+
const key = this.leaseKey(lease.taskId, lease.attemptId);
|
|
323
|
+
if (seenKeys.has(key))
|
|
324
|
+
throw new Error("Duplicate active lease key in legacy file");
|
|
325
|
+
seenKeys.add(key);
|
|
326
|
+
lease.hubUrl ??= this.hubUrl;
|
|
327
|
+
legacyLeases.push(lease);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
if (error.code !== "ENOENT") {
|
|
332
|
+
this.loadError = true;
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (this.loadError)
|
|
338
|
+
return;
|
|
339
|
+
loadedState = {
|
|
340
|
+
version: 1,
|
|
341
|
+
deviceId: this.deviceId,
|
|
342
|
+
hubUrl: this.hubUrl,
|
|
343
|
+
outbox: legacyOutbox,
|
|
344
|
+
activeLeases: legacyLeases,
|
|
345
|
+
};
|
|
346
|
+
if (hasLegacy) {
|
|
347
|
+
try {
|
|
348
|
+
this.writeStateToDiskSync(loadedState);
|
|
349
|
+
this.cleanupLegacyFiles();
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
this.loadError = true;
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
// Partition entries by hubUrl isolation
|
|
358
|
+
for (const entry of loadedState.outbox) {
|
|
359
|
+
if (this.matchesHub(entry.hubUrl)) {
|
|
360
|
+
this.outbox.set(entry.id, entry);
|
|
361
|
+
}
|
|
362
|
+
else {
|
|
363
|
+
this.otherHubOutbox.push(entry);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
for (const lease of loadedState.activeLeases) {
|
|
367
|
+
if (this.matchesHub(lease.hubUrl)) {
|
|
368
|
+
this.activeLeases.set(this.leaseKey(lease.taskId, lease.attemptId), lease);
|
|
369
|
+
}
|
|
370
|
+
else {
|
|
371
|
+
this.otherHubLeases.push(lease);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// 3. Crash detection: detect orphaned active leases for current hub from prior crash/restart
|
|
375
|
+
if (this.activeLeases.size > 0) {
|
|
376
|
+
const stored = Array.from(this.activeLeases.values());
|
|
170
377
|
const now = Date.now();
|
|
171
378
|
const newOutboxEntries = [];
|
|
172
379
|
for (const lease of stored) {
|
|
@@ -177,30 +384,43 @@ export class TaskRecoveryManager {
|
|
|
177
384
|
catch { }
|
|
178
385
|
const outboxKey = this.leaseKey(lease.taskId, lease.attemptId);
|
|
179
386
|
const existingOutbox = this.outbox.get(outboxKey);
|
|
180
|
-
// If outbox already has a terminal outcome
|
|
387
|
+
// If outbox already has a terminal outcome, NEVER overwrite it!
|
|
181
388
|
if (!existingOutbox) {
|
|
389
|
+
const report = "Execution safely halted on device process restart to prevent duplicate side effects.";
|
|
390
|
+
const error = "Device process restarted during execution";
|
|
391
|
+
const fingerprint = computeOutcomeFingerprint(lease.taskId, lease.attemptId, "interrupted", report, error);
|
|
182
392
|
const outboxEntry = {
|
|
183
393
|
id: outboxKey,
|
|
184
394
|
taskId: lease.taskId,
|
|
185
395
|
attemptId: lease.attemptId,
|
|
186
396
|
botId: lease.botId,
|
|
187
397
|
deviceId: this.deviceId,
|
|
398
|
+
hubUrl: lease.hubUrl ?? this.hubUrl,
|
|
188
399
|
roomId: lease.roomId,
|
|
189
400
|
status: "interrupted",
|
|
190
|
-
report
|
|
191
|
-
error
|
|
401
|
+
report,
|
|
402
|
+
error,
|
|
403
|
+
fingerprint,
|
|
192
404
|
createdAt: now,
|
|
193
405
|
updatedAt: now,
|
|
194
406
|
attempts: 0,
|
|
407
|
+
leaseToken: lease.leaseToken,
|
|
408
|
+
leaseGeneration: lease.leaseGeneration,
|
|
195
409
|
};
|
|
196
410
|
newOutboxEntries.push(outboxEntry);
|
|
197
411
|
}
|
|
198
412
|
}
|
|
199
|
-
// Atomic disk commit
|
|
200
|
-
this.
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
413
|
+
// Atomic disk commit: empty activeLeases, augmented outbox in one shot, preserving other Hubs
|
|
414
|
+
const allOutbox = [...this.otherHubOutbox, ...Array.from(this.outbox.values()), ...newOutboxEntries];
|
|
415
|
+
const allLeases = [...this.otherHubLeases];
|
|
416
|
+
const nextState = {
|
|
417
|
+
version: 1,
|
|
418
|
+
deviceId: this.deviceId,
|
|
419
|
+
hubUrl: this.hubUrl,
|
|
420
|
+
outbox: allOutbox,
|
|
421
|
+
activeLeases: allLeases,
|
|
422
|
+
};
|
|
423
|
+
this.writeStateToDiskSync(nextState);
|
|
204
424
|
for (const entry of newOutboxEntries) {
|
|
205
425
|
this.outbox.set(entry.id, entry);
|
|
206
426
|
}
|
|
@@ -213,19 +433,74 @@ export class TaskRecoveryManager {
|
|
|
213
433
|
}
|
|
214
434
|
/**
|
|
215
435
|
* Record a newly running task lease.
|
|
436
|
+
* Rejects if (taskId, attemptId) has already been finalized in Outbox.
|
|
437
|
+
* Rejects if an active lease is already registered for this task attempt.
|
|
438
|
+
* Validates inputs before persisting to disk to prevent state corruption.
|
|
216
439
|
*/
|
|
217
440
|
recordTaskStart(lease) {
|
|
441
|
+
// Strict pre-validation: reject invalid inputs BEFORE touching disk state
|
|
442
|
+
if (!lease ||
|
|
443
|
+
typeof lease !== "object" ||
|
|
444
|
+
typeof lease.taskId !== "string" ||
|
|
445
|
+
!lease.taskId ||
|
|
446
|
+
lease.taskId.length > 128 ||
|
|
447
|
+
typeof lease.attemptId !== "string" ||
|
|
448
|
+
!lease.attemptId ||
|
|
449
|
+
lease.attemptId.length > 128 ||
|
|
450
|
+
typeof lease.botId !== "string" ||
|
|
451
|
+
!lease.botId ||
|
|
452
|
+
lease.botId.length > 128 ||
|
|
453
|
+
typeof lease.roomId !== "string" ||
|
|
454
|
+
!lease.roomId ||
|
|
455
|
+
lease.roomId.length > 128 ||
|
|
456
|
+
typeof lease.leaseToken !== "string" ||
|
|
457
|
+
!lease.leaseToken ||
|
|
458
|
+
lease.leaseToken.length > 128 ||
|
|
459
|
+
(lease.leaseGeneration !== undefined && !Number.isSafeInteger(lease.leaseGeneration)) ||
|
|
460
|
+
(lease.deviceId && lease.deviceId !== this.deviceId)) {
|
|
461
|
+
throw new Error("Invalid task lease parameters for recordTaskStart");
|
|
462
|
+
}
|
|
463
|
+
const key = this.leaseKey(lease.taskId, lease.attemptId);
|
|
464
|
+
if (this.outbox.has(key) ||
|
|
465
|
+
this.quarantine.some((item) => this.matchesHub(item.outcome.hubUrl) && item.outcome.id === key)) {
|
|
466
|
+
throw new Error(`Cannot start task: outcome for task ${lease.taskId} attempt ${lease.attemptId} already finalized in outbox`);
|
|
467
|
+
}
|
|
468
|
+
// Reject conflicting concurrent or prior attempts for the same taskId in active leases
|
|
469
|
+
for (const [existingKey, existingLease] of this.activeLeases) {
|
|
470
|
+
if (existingLease.taskId === lease.taskId) {
|
|
471
|
+
if (existingKey === key) {
|
|
472
|
+
throw new Error(`Task lease already active for task ${lease.taskId} attempt ${lease.attemptId}`);
|
|
473
|
+
}
|
|
474
|
+
throw new Error(`Conflicting attempt active for task ${lease.taskId}: existing=${existingLease.attemptId}, new=${lease.attemptId}`);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (lease.hubUrl !== undefined && lease.hubUrl !== this.hubUrl)
|
|
478
|
+
throw new Error("Task lease Hub identity mismatch");
|
|
479
|
+
const capacity = this.hasOutboxCapacity();
|
|
480
|
+
if (!capacity.available)
|
|
481
|
+
throw new Error(capacity.reason);
|
|
218
482
|
const now = Date.now();
|
|
219
483
|
const record = {
|
|
220
484
|
...lease,
|
|
485
|
+
deviceId: this.deviceId,
|
|
486
|
+
hubUrl: lease.hubUrl ?? this.hubUrl,
|
|
221
487
|
activitySequence: lease.activitySequence ?? 0,
|
|
222
488
|
startedAt: lease.startedAt ?? now,
|
|
223
489
|
lastActivityAt: now,
|
|
224
490
|
lastRenewedActivityAt: now,
|
|
225
491
|
};
|
|
226
|
-
const
|
|
227
|
-
this.
|
|
228
|
-
this.
|
|
492
|
+
const nextLeases = [...Array.from(this.activeLeases.values()), record];
|
|
493
|
+
const allOutbox = [...this.otherHubOutbox, ...Array.from(this.outbox.values())];
|
|
494
|
+
const allLeases = [...this.otherHubLeases, ...nextLeases];
|
|
495
|
+
const state = {
|
|
496
|
+
version: 1,
|
|
497
|
+
deviceId: this.deviceId,
|
|
498
|
+
hubUrl: this.hubUrl,
|
|
499
|
+
outbox: allOutbox,
|
|
500
|
+
activeLeases: allLeases,
|
|
501
|
+
};
|
|
502
|
+
this.writeStateToDiskSync(state);
|
|
503
|
+
this.activeLeases.set(key, record);
|
|
229
504
|
return structuredClone(record);
|
|
230
505
|
}
|
|
231
506
|
/**
|
|
@@ -244,8 +519,17 @@ export class TaskRecoveryManager {
|
|
|
244
519
|
removeActiveLease(taskId, attemptId) {
|
|
245
520
|
const key = this.leaseKey(taskId, attemptId);
|
|
246
521
|
if (this.activeLeases.has(key)) {
|
|
247
|
-
const
|
|
248
|
-
this.
|
|
522
|
+
const nextLeases = Array.from(this.activeLeases.values()).filter((l) => this.leaseKey(l.taskId, l.attemptId) !== key);
|
|
523
|
+
const allOutbox = [...this.otherHubOutbox, ...Array.from(this.outbox.values())];
|
|
524
|
+
const allLeases = [...this.otherHubLeases, ...nextLeases];
|
|
525
|
+
const state = {
|
|
526
|
+
version: 1,
|
|
527
|
+
deviceId: this.deviceId,
|
|
528
|
+
hubUrl: this.hubUrl,
|
|
529
|
+
outbox: allOutbox,
|
|
530
|
+
activeLeases: allLeases,
|
|
531
|
+
};
|
|
532
|
+
this.writeStateToDiskSync(state);
|
|
249
533
|
this.activeLeases.delete(key);
|
|
250
534
|
}
|
|
251
535
|
}
|
|
@@ -257,13 +541,14 @@ export class TaskRecoveryManager {
|
|
|
257
541
|
return lease ? structuredClone(lease) : undefined;
|
|
258
542
|
}
|
|
259
543
|
/**
|
|
260
|
-
* Get all active leases (used for reconnection claim).
|
|
544
|
+
* Get all active leases for current Hub (used for reconnection claim).
|
|
261
545
|
*/
|
|
262
546
|
getActiveLeases() {
|
|
263
547
|
return structuredClone(Array.from(this.activeLeases.values()));
|
|
264
548
|
}
|
|
265
549
|
/**
|
|
266
550
|
* Prepare claim payload for all running tasks upon reconnection.
|
|
551
|
+
* Strictly isolated to current Hub.
|
|
267
552
|
*/
|
|
268
553
|
prepareClaims() {
|
|
269
554
|
const claims = [];
|
|
@@ -287,7 +572,6 @@ export class TaskRecoveryManager {
|
|
|
287
572
|
const renews = [];
|
|
288
573
|
for (const lease of this.activeLeases.values()) {
|
|
289
574
|
const isWaitingHuman = options?.waitingForHumanTaskIds?.has(lease.taskId) ?? false;
|
|
290
|
-
// Human wait pauses inactivity expiration
|
|
291
575
|
const inactive = !isWaitingHuman && now - lease.lastActivityAt > this.maxInactivityMs;
|
|
292
576
|
const totalExceeded = this.maxDurationMs > 0 && now - lease.startedAt > this.maxDurationMs;
|
|
293
577
|
if (!inactive && !totalExceeded) {
|
|
@@ -336,7 +620,9 @@ export class TaskRecoveryManager {
|
|
|
336
620
|
* if the recovery outbox has reached its budget ceiling, preserving existing results.
|
|
337
621
|
*/
|
|
338
622
|
hasOutboxCapacity() {
|
|
339
|
-
|
|
623
|
+
const reservations = this.activeLeases.size + this.otherHubLeases.length;
|
|
624
|
+
const totalEntries = this.outbox.size + this.otherHubOutbox.length + reservations;
|
|
625
|
+
if (totalEntries >= TASK_OUTBOX_LIMITS.maxEntries) {
|
|
340
626
|
return {
|
|
341
627
|
available: false,
|
|
342
628
|
reason: `Recovery outbox reached maximum capacity (${TASK_OUTBOX_LIMITS.maxEntries} entries). Reconnect to Hub to flush pending outcomes before starting new tasks.`,
|
|
@@ -346,7 +632,10 @@ export class TaskRecoveryManager {
|
|
|
346
632
|
for (const entry of this.outbox.values()) {
|
|
347
633
|
totalBytes += Buffer.byteLength(JSON.stringify(entry));
|
|
348
634
|
}
|
|
349
|
-
|
|
635
|
+
for (const entry of this.otherHubOutbox) {
|
|
636
|
+
totalBytes += Buffer.byteLength(JSON.stringify(entry));
|
|
637
|
+
}
|
|
638
|
+
if (totalBytes + (reservations + 1) * TASK_OUTBOX_RESERVATION_BYTES > TASK_OUTBOX_LIMITS.maxTotalBytes) {
|
|
350
639
|
return {
|
|
351
640
|
available: false,
|
|
352
641
|
reason: `Recovery outbox reached byte budget (${Math.round(TASK_OUTBOX_LIMITS.maxTotalBytes / 1024)} KiB). Reconnect to Hub to flush pending outcomes before starting new tasks.`,
|
|
@@ -356,36 +645,63 @@ export class TaskRecoveryManager {
|
|
|
356
645
|
}
|
|
357
646
|
/**
|
|
358
647
|
* Enqueue task terminal outcome into durable outbox.
|
|
359
|
-
*
|
|
360
|
-
*
|
|
648
|
+
* Atomically writes to unified state file and removes active lease in a single transaction.
|
|
649
|
+
* Enforces outcome immutability: identical outcome is idempotent; conflicting outcome is rejected.
|
|
650
|
+
* Carries leaseToken & leaseGeneration for Hub fencing.
|
|
361
651
|
*/
|
|
362
652
|
recordTaskFinish(task, outcome) {
|
|
653
|
+
if (!task ||
|
|
654
|
+
typeof task !== "object" ||
|
|
655
|
+
typeof task.id !== "string" ||
|
|
656
|
+
!task.id ||
|
|
657
|
+
task.id.length > 128 ||
|
|
658
|
+
typeof task.attemptId !== "string" ||
|
|
659
|
+
!task.attemptId ||
|
|
660
|
+
task.attemptId.length > 128 ||
|
|
661
|
+
typeof task.botId !== "string" ||
|
|
662
|
+
!task.botId ||
|
|
663
|
+
task.botId.length > 128) {
|
|
664
|
+
throw new Error("Invalid task parameters for recordTaskFinish");
|
|
665
|
+
}
|
|
666
|
+
if (task.hubUrl !== undefined && task.hubUrl !== this.hubUrl)
|
|
667
|
+
throw new Error("Task outcome Hub identity mismatch");
|
|
363
668
|
const now = Date.now();
|
|
364
|
-
const
|
|
365
|
-
const safeError = outcome.error ? deviceTaskFailure(outcome.error) : undefined;
|
|
366
|
-
const reportMetadata = outcome.reportMetadata === undefined ? undefined : parseReportMetadata(outcome.reportMetadata);
|
|
367
|
-
const fingerprint = computeOutcomeFingerprint(task.id, task.attemptId, outcome.status, safeReport, safeError, reportMetadata);
|
|
669
|
+
const normalized = normalizeTaskOutcome(task.id, task.attemptId, outcome);
|
|
368
670
|
const key = this.leaseKey(task.id, task.attemptId);
|
|
369
|
-
const
|
|
671
|
+
const activeLease = this.activeLeases.get(key);
|
|
672
|
+
const leaseToken = task.leaseToken ?? activeLease?.leaseToken;
|
|
673
|
+
const leaseGeneration = task.leaseGeneration ?? activeLease?.leaseGeneration;
|
|
674
|
+
const hubUrl = task.hubUrl ?? activeLease?.hubUrl ?? this.hubUrl;
|
|
675
|
+
const contractDigest = task.contractDigest ?? activeLease?.contractDigest;
|
|
676
|
+
const manifestDigest = task.manifestDigest ?? activeLease?.manifestDigest;
|
|
677
|
+
const existing = this.outbox.get(key) ??
|
|
678
|
+
this.quarantine.find((item) => this.matchesHub(item.outcome.hubUrl) && item.outcome.id === key)?.outcome;
|
|
370
679
|
if (existing) {
|
|
371
680
|
const targetDeviceId = task.deviceId || this.deviceId;
|
|
372
|
-
|
|
681
|
+
// Strict immutability: identical retry is idempotent; conflicting outcome is rejected.
|
|
682
|
+
// Lease fields must also be identical to prevent cross-generation outcome aliasing.
|
|
683
|
+
const leaseTokenMatches = leaseToken === undefined || existing.leaseToken === leaseToken;
|
|
684
|
+
const leaseGenMatches = leaseGeneration === undefined || existing.leaseGeneration === leaseGeneration;
|
|
685
|
+
const artifactMatches = existing.artifact?.digest === normalized.artifact?.digest;
|
|
686
|
+
const proofMatches = existing.executionCompleted === normalized.executionCompleted &&
|
|
687
|
+
existing.artifactProduced === normalized.artifactProduced;
|
|
688
|
+
if (existing.report === normalized.report &&
|
|
689
|
+
existing.error === normalized.error &&
|
|
690
|
+
existing.status === normalized.status &&
|
|
373
691
|
existing.botId === task.botId &&
|
|
374
692
|
existing.deviceId === targetDeviceId &&
|
|
375
|
-
existing.roomId === task.roomId &&
|
|
376
|
-
JSON.stringify(existing.reportMetadata) === JSON.stringify(reportMetadata)
|
|
693
|
+
(task.roomId === undefined || existing.roomId === task.roomId) &&
|
|
694
|
+
JSON.stringify(existing.reportMetadata) === JSON.stringify(normalized.reportMetadata) &&
|
|
695
|
+
leaseTokenMatches &&
|
|
696
|
+
leaseGenMatches &&
|
|
697
|
+
artifactMatches &&
|
|
698
|
+
proofMatches) {
|
|
699
|
+
if (this.activeLeases.has(key)) {
|
|
700
|
+
this.removeActiveLease(task.id, task.attemptId);
|
|
701
|
+
}
|
|
377
702
|
return structuredClone(existing);
|
|
378
703
|
}
|
|
379
|
-
existing.status
|
|
380
|
-
existing.report = safeReport;
|
|
381
|
-
existing.error = safeError;
|
|
382
|
-
existing.reportMetadata = reportMetadata;
|
|
383
|
-
existing.fingerprint = fingerprint;
|
|
384
|
-
existing.updatedAt = now;
|
|
385
|
-
const nextOutbox = Array.from(this.outbox.values());
|
|
386
|
-
this.persistOutboxSync(nextOutbox);
|
|
387
|
-
this.removeActiveLease(task.id, task.attemptId);
|
|
388
|
-
return structuredClone(existing);
|
|
704
|
+
throw new Error(`Task outcome conflict: outcome for task ${task.id} attempt ${task.attemptId} already finalized with status=${existing.status}, fingerprint=${existing.fingerprint} (attempted status=${normalized.status}, fingerprint=${normalized.fingerprint})`);
|
|
389
705
|
}
|
|
390
706
|
const entry = {
|
|
391
707
|
id: key,
|
|
@@ -393,31 +709,67 @@ export class TaskRecoveryManager {
|
|
|
393
709
|
attemptId: task.attemptId,
|
|
394
710
|
botId: task.botId,
|
|
395
711
|
deviceId: task.deviceId || this.deviceId,
|
|
712
|
+
hubUrl,
|
|
396
713
|
roomId: task.roomId,
|
|
397
|
-
status:
|
|
398
|
-
reportMetadata,
|
|
399
|
-
report:
|
|
400
|
-
error:
|
|
401
|
-
fingerprint,
|
|
714
|
+
status: normalized.status,
|
|
715
|
+
reportMetadata: normalized.reportMetadata,
|
|
716
|
+
report: normalized.report,
|
|
717
|
+
error: normalized.error,
|
|
718
|
+
fingerprint: normalized.fingerprint,
|
|
719
|
+
artifact: normalized.artifact,
|
|
720
|
+
executionCompleted: normalized.executionCompleted,
|
|
721
|
+
artifactProduced: normalized.artifactProduced,
|
|
722
|
+
contractDigest,
|
|
723
|
+
manifestDigest,
|
|
402
724
|
createdAt: now,
|
|
403
725
|
updatedAt: now,
|
|
404
726
|
attempts: 0,
|
|
727
|
+
leaseToken,
|
|
728
|
+
leaseGeneration,
|
|
405
729
|
};
|
|
406
|
-
|
|
730
|
+
validateOutboxItem(entry, this.deviceId);
|
|
731
|
+
if (activeLease &&
|
|
732
|
+
(activeLease.botId !== entry.botId ||
|
|
733
|
+
(task.roomId !== undefined && activeLease.roomId !== task.roomId) ||
|
|
734
|
+
activeLease.leaseToken !== leaseToken ||
|
|
735
|
+
activeLease.leaseGeneration !== leaseGeneration))
|
|
736
|
+
throw new Error("Task outcome lease identity mismatch");
|
|
737
|
+
// Transactional commit: add outbox and remove active lease atomically in unified state
|
|
407
738
|
const nextOutbox = [...Array.from(this.outbox.values()), entry];
|
|
408
|
-
this.
|
|
739
|
+
const allPending = [...this.otherHubOutbox, ...nextOutbox];
|
|
740
|
+
if (allPending.length > TASK_OUTBOX_LIMITS.maxEntries ||
|
|
741
|
+
allPending.reduce((bytes, pending) => bytes + Buffer.byteLength(JSON.stringify(pending)), 0) >
|
|
742
|
+
TASK_OUTBOX_LIMITS.maxTotalBytes)
|
|
743
|
+
throw new Error("Recovery outbox capacity exceeded; outcome lease retained");
|
|
744
|
+
const nextLeases = Array.from(this.activeLeases.values()).filter((l) => this.leaseKey(l.taskId, l.attemptId) !== key);
|
|
745
|
+
const allOutbox = [...this.otherHubOutbox, ...nextOutbox];
|
|
746
|
+
const allLeases = [...this.otherHubLeases, ...nextLeases];
|
|
747
|
+
const state = {
|
|
748
|
+
version: 1,
|
|
749
|
+
deviceId: this.deviceId,
|
|
750
|
+
hubUrl: this.hubUrl,
|
|
751
|
+
outbox: allOutbox,
|
|
752
|
+
activeLeases: allLeases,
|
|
753
|
+
};
|
|
754
|
+
this.writeStateToDiskSync(state);
|
|
409
755
|
// Disk succeeded; update memory
|
|
410
756
|
this.outbox.set(entry.id, entry);
|
|
411
|
-
|
|
412
|
-
this.removeActiveLease(task.id, task.attemptId);
|
|
757
|
+
this.activeLeases.delete(key);
|
|
413
758
|
return structuredClone(entry);
|
|
414
759
|
}
|
|
415
760
|
/**
|
|
416
|
-
* List all pending outbox entries waiting for Hub ACK.
|
|
761
|
+
* List all pending outbox entries waiting for Hub ACK for the current Hub.
|
|
417
762
|
*/
|
|
418
763
|
getPendingOutbox() {
|
|
419
764
|
return structuredClone(Array.from(this.outbox.values()));
|
|
420
765
|
}
|
|
766
|
+
/**
|
|
767
|
+
* Find a pending outbox entry by taskId and attemptId.
|
|
768
|
+
*/
|
|
769
|
+
getPendingOutboxEntry(taskId, attemptId) {
|
|
770
|
+
const entry = this.outbox.get(this.leaseKey(taskId, attemptId));
|
|
771
|
+
return entry ? structuredClone(entry) : undefined;
|
|
772
|
+
}
|
|
421
773
|
/**
|
|
422
774
|
* Mark attempt sent to Hub for backoff/tracking.
|
|
423
775
|
*/
|
|
@@ -425,28 +777,101 @@ export class TaskRecoveryManager {
|
|
|
425
777
|
const entry = this.outbox.get(id);
|
|
426
778
|
if (entry) {
|
|
427
779
|
const updated = { ...entry, attempts: entry.attempts + 1, updatedAt: Date.now() };
|
|
428
|
-
const
|
|
429
|
-
this.
|
|
780
|
+
const nextOutbox = Array.from(this.outbox.values()).map((e) => (e.id === id ? updated : e));
|
|
781
|
+
const allOutbox = [...this.otherHubOutbox, ...nextOutbox];
|
|
782
|
+
const allLeases = [...this.otherHubLeases, ...Array.from(this.activeLeases.values())];
|
|
783
|
+
const state = {
|
|
784
|
+
version: 1,
|
|
785
|
+
deviceId: this.deviceId,
|
|
786
|
+
hubUrl: this.hubUrl,
|
|
787
|
+
outbox: allOutbox,
|
|
788
|
+
activeLeases: allLeases,
|
|
789
|
+
};
|
|
790
|
+
this.writeStateToDiskSync(state);
|
|
430
791
|
this.outbox.set(id, updated);
|
|
431
792
|
}
|
|
432
793
|
}
|
|
794
|
+
/** Durable rejected evidence remains inspectable and never participates in automatic replay. */
|
|
795
|
+
getQuarantinedOutcomes() {
|
|
796
|
+
return structuredClone(this.quarantine.filter((item) => this.matchesHub(item.outcome.hubUrl)));
|
|
797
|
+
}
|
|
798
|
+
quarantineOutbox(taskId, attemptId, fingerprint, reasonCode, status, artifactDigest) {
|
|
799
|
+
if (this.loadError ||
|
|
800
|
+
typeof reasonCode !== "string" ||
|
|
801
|
+
!["terminal_conflict", "attempt_expired", "legacy_lease_missing"].includes(reasonCode))
|
|
802
|
+
return false;
|
|
803
|
+
const key = this.leaseKey(taskId, attemptId);
|
|
804
|
+
const outcome = this.outbox.get(key);
|
|
805
|
+
if (!outcome ||
|
|
806
|
+
typeof fingerprint !== "string" ||
|
|
807
|
+
fingerprint !== outcome.fingerprint ||
|
|
808
|
+
status !== outcome.status ||
|
|
809
|
+
artifactDigest !== outcome.artifact?.digest)
|
|
810
|
+
return false;
|
|
811
|
+
const next = [
|
|
812
|
+
...this.quarantine,
|
|
813
|
+
{
|
|
814
|
+
outcome: structuredClone(outcome),
|
|
815
|
+
reasonCode: reasonCode,
|
|
816
|
+
quarantinedAt: Date.now(),
|
|
817
|
+
},
|
|
818
|
+
];
|
|
819
|
+
if (next.length > TASK_QUARANTINE_LIMITS.maxEntries ||
|
|
820
|
+
Buffer.byteLength(JSON.stringify(next)) > TASK_QUARANTINE_LIMITS.maxTotalBytes)
|
|
821
|
+
return false;
|
|
822
|
+
// Commit archive + removal together. Keep all active leases and other hubs intact.
|
|
823
|
+
this.writeStateToDiskSync({
|
|
824
|
+
version: 2,
|
|
825
|
+
deviceId: this.deviceId,
|
|
826
|
+
hubUrl: this.hubUrl,
|
|
827
|
+
outbox: [...this.otherHubOutbox, ...Array.from(this.outbox.values()).filter((e) => e.id !== key)],
|
|
828
|
+
activeLeases: [...this.otherHubLeases, ...Array.from(this.activeLeases.values())],
|
|
829
|
+
quarantine: next,
|
|
830
|
+
});
|
|
831
|
+
this.quarantine = next;
|
|
832
|
+
this.outbox.delete(key);
|
|
833
|
+
return true;
|
|
834
|
+
}
|
|
433
835
|
/**
|
|
434
836
|
* Acknowledge outbox entry upon receiving task_result_ack from Hub.
|
|
435
|
-
*
|
|
837
|
+
* Strictly requires matching outcome fingerprint; rejects clearing without or with mismatched fingerprint.
|
|
436
838
|
*/
|
|
437
|
-
ackOutbox(taskId, attemptId, fingerprint) {
|
|
438
|
-
const
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
this.outbox.delete(id);
|
|
446
|
-
}
|
|
839
|
+
ackOutbox(taskId, attemptId, fingerprint, extra) {
|
|
840
|
+
const key = this.leaseKey(taskId, attemptId);
|
|
841
|
+
const entry = this.outbox.get(key);
|
|
842
|
+
if (!entry)
|
|
843
|
+
return false;
|
|
844
|
+
if (entry.fingerprint) {
|
|
845
|
+
if (!fingerprint || entry.fingerprint !== fingerprint) {
|
|
846
|
+
return false;
|
|
447
847
|
}
|
|
448
|
-
return true;
|
|
449
848
|
}
|
|
450
|
-
|
|
849
|
+
else if (fingerprint) {
|
|
850
|
+
return false;
|
|
851
|
+
}
|
|
852
|
+
if (extra?.status !== undefined && entry.status !== extra.status)
|
|
853
|
+
return false;
|
|
854
|
+
if (extra?.artifactDigest !== undefined && entry.artifact?.digest !== extra.artifactDigest) {
|
|
855
|
+
return false;
|
|
856
|
+
}
|
|
857
|
+
if (extra?.contractDigest !== undefined && entry.contractDigest !== extra.contractDigest) {
|
|
858
|
+
return false;
|
|
859
|
+
}
|
|
860
|
+
if (extra?.manifestDigest !== undefined && entry.manifestDigest !== extra.manifestDigest) {
|
|
861
|
+
return false;
|
|
862
|
+
}
|
|
863
|
+
const nextOutbox = Array.from(this.outbox.values()).filter((e) => e.id !== key);
|
|
864
|
+
const allOutbox = [...this.otherHubOutbox, ...nextOutbox];
|
|
865
|
+
const allLeases = [...this.otherHubLeases, ...Array.from(this.activeLeases.values())];
|
|
866
|
+
const state = {
|
|
867
|
+
version: 1,
|
|
868
|
+
deviceId: this.deviceId,
|
|
869
|
+
hubUrl: this.hubUrl,
|
|
870
|
+
outbox: allOutbox,
|
|
871
|
+
activeLeases: allLeases,
|
|
872
|
+
};
|
|
873
|
+
this.writeStateToDiskSync(state);
|
|
874
|
+
this.outbox.delete(key);
|
|
875
|
+
return true;
|
|
451
876
|
}
|
|
452
877
|
}
|