pi-web-ui 0.114.3 → 0.116.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 +62 -1
- package/bin/pi-web-ui.mjs +90 -8
- package/dist/gh-comment-781.md +5 -0
- package/dist/server/agent-service-daemon.js +522 -32
- package/dist/server/agent-service.js +954 -402
- package/dist/server/canvas/canvas-dispatch.js +13 -1
- package/dist/server/client-state.js +42 -2
- package/dist/server/communicate-tool.js +2 -0
- package/dist/server/conversation-communication.js +14 -0
- package/dist/server/conversation-identity.js +27 -0
- package/dist/server/device-center/approval-summary.js +31 -0
- package/dist/server/device-center/bot-catalog.js +21 -7
- package/dist/server/device-center/bot-execution.js +100 -9
- package/dist/server/device-center/bot-presets.js +46 -0
- package/dist/server/device-center/collab-service.js +362 -13
- package/dist/server/device-center/collab-tool.js +824 -13
- package/dist/server/device-center/connector.js +359 -23
- package/dist/server/device-center/desktop-page.js +22 -16
- package/dist/server/device-center/device-integration.js +595 -0
- package/dist/server/device-center/execution-guides.js +32 -0
- package/dist/server/device-center/execution-instructions.js +20 -0
- package/dist/server/device-center/execution-settings.js +213 -0
- package/dist/server/device-center/execution-system-prompt.js +38 -0
- package/dist/server/device-center/execution-workspace.js +20 -0
- package/dist/server/device-center/executor.js +392 -40
- package/dist/server/device-center/file-sync-paths.js +171 -0
- package/dist/server/device-center/file-sync.js +186 -96
- package/dist/server/device-center/group-context-delta.js +37 -0
- package/dist/server/device-center/group-context-message.js +210 -0
- package/dist/server/device-center/group-context.js +179 -0
- package/dist/server/device-center/group-events.js +136 -0
- package/dist/server/device-center/group-plan-guard.js +138 -0
- package/dist/server/device-center/hub-conversations.js +233 -0
- package/dist/server/device-center/hub-deliveries.js +277 -0
- package/dist/server/device-center/hub-integration.js +451 -0
- package/dist/server/device-center/hub-locks.js +320 -0
- package/dist/server/device-center/hub-page.js +13 -33
- package/dist/server/device-center/hub-webhooks.js +165 -0
- package/dist/server/device-center/hub.js +2379 -107
- package/dist/server/device-center/human-interaction.js +232 -0
- package/dist/server/device-center/integration-errors.js +25 -0
- package/dist/server/device-center/local-hub.js +20 -1
- package/dist/server/device-center/local-page.js +17 -0
- package/dist/server/device-center/local.js +430 -41
- package/dist/server/device-center/main.js +11 -1
- package/dist/server/device-center/partition-log.js +293 -0
- package/dist/server/device-center/path-portal.js +11 -3
- package/dist/server/device-center/relay.js +364 -35
- package/dist/server/device-center/report-metadata.js +66 -0
- package/dist/server/device-center/report-upload.js +63 -0
- package/dist/server/device-center/runtime.js +598 -41
- package/dist/server/device-center/smoke-preview.js +3 -0
- package/dist/server/device-center/store.js +203 -41
- package/dist/server/device-center/task-context-budget.js +161 -0
- package/dist/server/device-center/task-journal.js +385 -0
- package/dist/server/device-center/task-plan.js +33 -0
- package/dist/server/device-center/task-progress.js +141 -0
- package/dist/server/device-center/task-recovery.js +452 -0
- package/dist/server/device-center/task-report-outbox.js +216 -0
- package/dist/server/device-center/task-report.js +384 -0
- package/dist/server/device-center/task-scheduler.js +445 -0
- package/dist/server/device-center/task-state.js +333 -0
- package/dist/server/device-center/transfer-stream.js +1006 -0
- package/dist/server/device-center/transfers.js +841 -8
- package/dist/server/dispatch-domain-handlers.js +35 -6
- package/dist/server/dsh/dsh-agent-service.js +6 -0
- package/dist/server/durable/durable-capabilities.js +11 -0
- package/dist/server/engine-probe.js +112 -1
- package/dist/server/global-loader.js +119 -19
- package/dist/server/goal-service.js +10 -5
- package/dist/server/index.js +222 -29
- package/dist/server/managed.js +2 -0
- package/dist/server/markers/builtins/services.js +123 -0
- package/dist/server/markers/builtins/todo.js +189 -0
- package/dist/server/markers-list-tool.js +34 -0
- package/dist/server/message-deletion.js +40 -0
- package/dist/server/message-window.js +9 -0
- package/dist/server/model-admin.js +48 -6
- package/dist/server/model-enrich.js +10 -1
- package/dist/server/orchestrator.js +109 -0
- package/dist/server/patch-executable-lookup.js +396 -0
- package/dist/server/payload-limits.js +2 -0
- package/dist/server/plugin-llm.js +100 -9
- package/dist/server/plugins.js +65 -7
- package/dist/server/preset-fields.js +24 -0
- package/dist/server/preset-share.js +2 -0
- package/dist/server/prompt-base-store.js +85 -0
- package/dist/server/prompt-composer.js +44 -2
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/protocol.js +2 -2
- package/dist/server/reasoning-registry.js +207 -0
- package/dist/server/remote-ssh-service.js +22 -9
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/session-search.js +1 -1
- package/dist/server/settings-service.js +90 -39
- package/dist/server/skill-content-filler.js +29 -8
- package/dist/server/skill-tool.js +12 -3
- package/dist/server/startup-banner.js +35 -0
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagents.js +52 -37
- package/dist/server/system-prompt-soul.js +41 -0
- package/dist/server/tool-host-factories.js +1 -0
- package/dist/server/tool-manager.js +17 -9
- package/dist/server/unauthorized-page.js +319 -0
- package/dist/server/univer-service.js +448 -0
- package/dist/server/universal/drivers/dsh-driver.js +379 -0
- package/dist/server/universal/universal-session.js +5 -0
- package/dist/server/webui-context.js +25 -5
- package/dist/test-artifact.md +9 -0
- package/dist/test-preview-modal.md +11 -0
- package/dist/test-report.html +20 -0
- package/docs/README.md +94 -0
- package/docs/architecture-plugins.md +946 -0
- package/docs/device-center.md +106 -12
- package/docs/dsh-engine.md +10 -10
- package/extensions/webui.ts +43 -1
- package/package.json +2 -1
- package/themes/aetheris.css +5 -0
- package/themes/ayu-light.css +6 -0
- package/themes/bases/flow-base.css +68 -68
- package/themes/catppuccin-latte.css +6 -0
- package/themes/catppuccin.css +6 -0
- package/themes/claude-code-dark.css +5 -0
- package/themes/codex.css +6 -0
- package/themes/cyberpunk.css +6 -0
- package/themes/dark-teal.css +6 -1
- package/themes/dazzle.css +6 -0
- package/themes/everforest-light.css +6 -0
- package/themes/flow-light.css +8 -1
- package/themes/flow.css +6 -1
- package/themes/geist.css +6 -0
- package/themes/gruvbox-light.css +6 -0
- package/themes/kanagawa-lotus.css +6 -0
- package/themes/md-preview.css +6 -0
- package/themes/mist.css +6 -0
- package/themes/nord.css +6 -0
- package/themes/one-dark.css +6 -0
- package/themes/paper.css +6 -0
- package/themes/rose-pine-dawn.css +6 -0
- package/themes/sakura.css +6 -0
- package/themes/solarized-light.css +6 -0
- package/themes/tokyo-night.css +6 -0
- package/themes/translucent.css +6 -0
- package/themes/transparent.css +6 -0
- package/themes/vs-code-dark.css +5 -0
- package/themes/wallpaper-flow.css +5 -1
- package/themes/wallpaper-obsidian.css +6 -0
- package/themes/white.css +6 -0
- package/themes/zhujian-dark.css +6 -1
- package/themes/zhujian.css +6 -1
- package/themes/zhupi-dark.css +6 -1
- package/themes/zhupi.css +6 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BDoOpj-F.js +1 -0
- package/web/dist/assets/BgTasksModal-C0i3O1FT.js +1 -0
- package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-B8thymBN.js} +3 -3
- package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-zSxyIx1R.js} +3 -3
- package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
- package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
- package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
- package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
- package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
- package/web/dist/assets/Dropdown-C4LIhshN.js +1 -0
- package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
- package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
- package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +1 -0
- package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +1 -0
- package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
- package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
- package/web/dist/assets/HintTip-c6d0TJoh.js +1 -0
- package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
- package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
- package/web/dist/assets/PiSetupModal-BmMrrgB9.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +1 -0
- package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
- package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
- package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
- package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
- package/web/dist/assets/TerminalPanel-0CYvD72B.js +3 -0
- package/web/dist/assets/TerminalPanel-DDavKvFr.js +3 -0
- package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +1 -0
- package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +1 -0
- package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
- package/web/dist/assets/canvas-client-CUnXlQYX.js +1 -0
- package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-aAKpvKJV.js} +1 -1
- package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
- package/web/dist/assets/index-C6DwztqE.css +1 -0
- package/web/dist/assets/index-CuN802Sj.js +93 -0
- package/web/dist/assets/index-EH5Fw9fa.js +93 -0
- package/web/dist/assets/plugin-host-BRWib9DF.js +1 -0
- package/web/dist/assets/remote-ssh-client-CfYSMEZg.js +1 -0
- package/web/dist/assets/theme-D2l_mLNo.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
- package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
- package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
- package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
- package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
- package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
- package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
- package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
- package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
- package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
- package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
- package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
- package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
- package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
- package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
- package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
- package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
- package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
- package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
- package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
- package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
- package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
- package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
- package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
- package/web/dist/assets/index-DK3F5ZJo.js +0 -85
- package/web/dist/assets/index-DQMii2he.js +0 -85
- package/web/dist/assets/index-vwBnwzkr.css +0 -1
- package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
- package/web/dist/assets/theme-D2DMH6tH.js +0 -1
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { writeAtomicSync } from "../atomic-file.js";
|
|
5
|
+
import { deviceTaskFailure } from "./task-error.js";
|
|
6
|
+
import { boundTaskReport } from "./task-report.js";
|
|
7
|
+
import { parseReportMetadata } from "./report-metadata.js";
|
|
8
|
+
export function computeOutcomeFingerprint(taskId, attemptId, status, report, error, reportMetadata) {
|
|
9
|
+
return createHash("sha256")
|
|
10
|
+
.update(`${taskId}:${attemptId}:${status}:${report ?? ""}:${error ?? ""}${reportMetadata ? JSON.stringify(reportMetadata) : ""}`)
|
|
11
|
+
.digest("hex")
|
|
12
|
+
.slice(0, 16);
|
|
13
|
+
}
|
|
14
|
+
export const TASK_RECOVERY_DEFAULTS = {
|
|
15
|
+
maxInactivityMs: 20 * 60 * 1000, // 20 minutes without activity (human waits pause this)
|
|
16
|
+
maxDurationMs: 0, // 0 = unbounded overall duration by default (honors long-running jobs)
|
|
17
|
+
renewIntervalMs: 15 * 1000, // 15 seconds lease heartbeat
|
|
18
|
+
recoveryWindowMs: 60 * 1000, // 60 seconds grace window after Hub restart
|
|
19
|
+
};
|
|
20
|
+
export const TASK_OUTBOX_LIMITS = {
|
|
21
|
+
maxEntries: 128,
|
|
22
|
+
maxTotalBytes: 2 * 1024 * 1024, // 2 MiB bounded durable storage budget
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Durable Task Recovery Manager:
|
|
26
|
+
* 1. Transactional Outbox for completed/failed/interrupted results.
|
|
27
|
+
* 2. Active lease registration with activity tracking and bounded life.
|
|
28
|
+
* 3. Safe crash/restart detection: never blindly re-runs side effects; safely interrupts orphans.
|
|
29
|
+
*/
|
|
30
|
+
export class TaskRecoveryManager {
|
|
31
|
+
outboxPath;
|
|
32
|
+
leasesPath;
|
|
33
|
+
deviceId;
|
|
34
|
+
hubUrl;
|
|
35
|
+
maxInactivityMs;
|
|
36
|
+
maxDurationMs;
|
|
37
|
+
outbox = new Map();
|
|
38
|
+
activeLeases = new Map();
|
|
39
|
+
haltedOrphans = [];
|
|
40
|
+
outboxLoadError = false;
|
|
41
|
+
leasesLoadError = false;
|
|
42
|
+
constructor(options) {
|
|
43
|
+
this.deviceId = options.deviceId;
|
|
44
|
+
this.hubUrl = options.hubUrl;
|
|
45
|
+
this.maxInactivityMs = options.maxInactivityMs ?? TASK_RECOVERY_DEFAULTS.maxInactivityMs;
|
|
46
|
+
this.maxDurationMs = options.maxDurationMs ?? TASK_RECOVERY_DEFAULTS.maxDurationMs;
|
|
47
|
+
if (options.dataDir) {
|
|
48
|
+
this.outboxPath = join(options.dataDir, "task-recovery-outbox.json");
|
|
49
|
+
this.leasesPath = join(options.dataDir, "task-active-leases.json");
|
|
50
|
+
}
|
|
51
|
+
this.loadOutbox();
|
|
52
|
+
this.loadAndDetectOrphanLeases(options.onHaltOrphaned);
|
|
53
|
+
}
|
|
54
|
+
leaseKey(taskId, attemptId) {
|
|
55
|
+
return `${taskId}:${attemptId}`;
|
|
56
|
+
}
|
|
57
|
+
loadOutbox() {
|
|
58
|
+
if (!this.outboxPath)
|
|
59
|
+
return;
|
|
60
|
+
try {
|
|
61
|
+
const raw = readFileSync(this.outboxPath, "utf8");
|
|
62
|
+
const data = JSON.parse(raw);
|
|
63
|
+
if (!Array.isArray(data))
|
|
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);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (error.code === "ENOENT") {
|
|
96
|
+
return; // Truly non-existent file is clean startup
|
|
97
|
+
}
|
|
98
|
+
// Fail-closed on ANY error (syntax, schema, permission): disallow overwriting
|
|
99
|
+
this.outboxLoadError = true;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
persistOutboxSync(entries) {
|
|
103
|
+
if (!this.outboxPath)
|
|
104
|
+
return;
|
|
105
|
+
if (this.outboxLoadError)
|
|
106
|
+
throw new Error("Outbox persistence blocked: corrupted storage was preserved");
|
|
107
|
+
const text = JSON.stringify(entries, null, 2) + "\n";
|
|
108
|
+
writeAtomicSync(this.outboxPath, text, { mode: 0o600 });
|
|
109
|
+
}
|
|
110
|
+
persistLeasesSync(entries) {
|
|
111
|
+
if (!this.leasesPath)
|
|
112
|
+
return;
|
|
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 });
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Detect uncompleted leases from a previous process crash/restart.
|
|
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)
|
|
126
|
+
return;
|
|
127
|
+
let stored = [];
|
|
128
|
+
try {
|
|
129
|
+
const raw = readFileSync(this.leasesPath, "utf8");
|
|
130
|
+
const parsed = JSON.parse(raw);
|
|
131
|
+
if (!Array.isArray(parsed))
|
|
132
|
+
throw new Error("Invalid leases data root");
|
|
133
|
+
const seenKeys = new Set();
|
|
134
|
+
for (const x of parsed) {
|
|
135
|
+
if (!x ||
|
|
136
|
+
typeof x !== "object" ||
|
|
137
|
+
typeof x.taskId !== "string" ||
|
|
138
|
+
x.taskId.length > 128 ||
|
|
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);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
if (error.code === "ENOENT") {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
this.leasesLoadError = true;
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (stored.length > 0) {
|
|
170
|
+
const now = Date.now();
|
|
171
|
+
const newOutboxEntries = [];
|
|
172
|
+
for (const lease of stored) {
|
|
173
|
+
this.haltedOrphans.push(lease);
|
|
174
|
+
try {
|
|
175
|
+
onHaltOrphaned?.(lease);
|
|
176
|
+
}
|
|
177
|
+
catch { }
|
|
178
|
+
const outboxKey = this.leaseKey(lease.taskId, lease.attemptId);
|
|
179
|
+
const existingOutbox = this.outbox.get(outboxKey);
|
|
180
|
+
// If outbox already has a terminal outcome (e.g. completed before crash), NEVER overwrite it!
|
|
181
|
+
if (!existingOutbox) {
|
|
182
|
+
const outboxEntry = {
|
|
183
|
+
id: outboxKey,
|
|
184
|
+
taskId: lease.taskId,
|
|
185
|
+
attemptId: lease.attemptId,
|
|
186
|
+
botId: lease.botId,
|
|
187
|
+
deviceId: this.deviceId,
|
|
188
|
+
roomId: lease.roomId,
|
|
189
|
+
status: "interrupted",
|
|
190
|
+
report: "Execution safely halted on device process restart to prevent duplicate side effects.",
|
|
191
|
+
error: "Device process restarted during execution",
|
|
192
|
+
createdAt: now,
|
|
193
|
+
updatedAt: now,
|
|
194
|
+
attempts: 0,
|
|
195
|
+
};
|
|
196
|
+
newOutboxEntries.push(outboxEntry);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
// Atomic disk commit first: write empty leases, then write augmented outbox
|
|
200
|
+
this.persistLeasesSync([]);
|
|
201
|
+
const combinedOutbox = [...Array.from(this.outbox.values()), ...newOutboxEntries];
|
|
202
|
+
this.persistOutboxSync(combinedOutbox);
|
|
203
|
+
// After successful disk commit, update in-memory maps
|
|
204
|
+
for (const entry of newOutboxEntries) {
|
|
205
|
+
this.outbox.set(entry.id, entry);
|
|
206
|
+
}
|
|
207
|
+
this.activeLeases.clear();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/** Get list of orphaned tasks halted at process startup. */
|
|
211
|
+
getHaltedOrphans() {
|
|
212
|
+
return structuredClone(this.haltedOrphans);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Record a newly running task lease.
|
|
216
|
+
*/
|
|
217
|
+
recordTaskStart(lease) {
|
|
218
|
+
const now = Date.now();
|
|
219
|
+
const record = {
|
|
220
|
+
...lease,
|
|
221
|
+
activitySequence: lease.activitySequence ?? 0,
|
|
222
|
+
startedAt: lease.startedAt ?? now,
|
|
223
|
+
lastActivityAt: now,
|
|
224
|
+
lastRenewedActivityAt: now,
|
|
225
|
+
};
|
|
226
|
+
const nextEntries = [...Array.from(this.activeLeases.values()), record];
|
|
227
|
+
this.persistLeasesSync(nextEntries);
|
|
228
|
+
this.activeLeases.set(this.leaseKey(record.taskId, record.attemptId), record);
|
|
229
|
+
return structuredClone(record);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Record verified local activity (LLM streaming or tool invocation).
|
|
233
|
+
*/
|
|
234
|
+
recordActivity(taskId, attemptId) {
|
|
235
|
+
const record = this.activeLeases.get(this.leaseKey(taskId, attemptId));
|
|
236
|
+
if (!record)
|
|
237
|
+
return false;
|
|
238
|
+
record.lastActivityAt = Date.now();
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Remove active lease when task ends locally.
|
|
243
|
+
*/
|
|
244
|
+
removeActiveLease(taskId, attemptId) {
|
|
245
|
+
const key = this.leaseKey(taskId, attemptId);
|
|
246
|
+
if (this.activeLeases.has(key)) {
|
|
247
|
+
const next = Array.from(this.activeLeases.values()).filter((l) => this.leaseKey(l.taskId, l.attemptId) !== key);
|
|
248
|
+
this.persistLeasesSync(next);
|
|
249
|
+
this.activeLeases.delete(key);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Get an active lease by taskId and attemptId.
|
|
254
|
+
*/
|
|
255
|
+
getActiveLease(taskId, attemptId) {
|
|
256
|
+
const lease = this.activeLeases.get(this.leaseKey(taskId, attemptId));
|
|
257
|
+
return lease ? structuredClone(lease) : undefined;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Get all active leases (used for reconnection claim).
|
|
261
|
+
*/
|
|
262
|
+
getActiveLeases() {
|
|
263
|
+
return structuredClone(Array.from(this.activeLeases.values()));
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Prepare claim payload for all running tasks upon reconnection.
|
|
267
|
+
*/
|
|
268
|
+
prepareClaims() {
|
|
269
|
+
const claims = [];
|
|
270
|
+
for (const lease of this.activeLeases.values()) {
|
|
271
|
+
claims.push({
|
|
272
|
+
taskId: lease.taskId,
|
|
273
|
+
attemptId: lease.attemptId,
|
|
274
|
+
botId: lease.botId,
|
|
275
|
+
leaseToken: lease.leaseToken,
|
|
276
|
+
leaseGeneration: lease.leaseGeneration,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
return claims;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Prepare heartbeat renewal frames for tasks with verified recent activity.
|
|
283
|
+
* monotonic activity progression: only true if new activity occurred since last renewal.
|
|
284
|
+
*/
|
|
285
|
+
prepareLeaseRenews(options) {
|
|
286
|
+
const now = Date.now();
|
|
287
|
+
const renews = [];
|
|
288
|
+
for (const lease of this.activeLeases.values()) {
|
|
289
|
+
const isWaitingHuman = options?.waitingForHumanTaskIds?.has(lease.taskId) ?? false;
|
|
290
|
+
// Human wait pauses inactivity expiration
|
|
291
|
+
const inactive = !isWaitingHuman && now - lease.lastActivityAt > this.maxInactivityMs;
|
|
292
|
+
const totalExceeded = this.maxDurationMs > 0 && now - lease.startedAt > this.maxDurationMs;
|
|
293
|
+
if (!inactive && !totalExceeded) {
|
|
294
|
+
const hasNewActivity = lease.lastActivityAt > lease.lastRenewedActivityAt;
|
|
295
|
+
if (hasNewActivity) {
|
|
296
|
+
lease.lastRenewedActivityAt = lease.lastActivityAt;
|
|
297
|
+
lease.activitySequence = (lease.activitySequence ?? 0) + 1;
|
|
298
|
+
}
|
|
299
|
+
renews.push({
|
|
300
|
+
taskId: lease.taskId,
|
|
301
|
+
attemptId: lease.attemptId,
|
|
302
|
+
botId: lease.botId,
|
|
303
|
+
leaseToken: lease.leaseToken,
|
|
304
|
+
leaseGeneration: lease.leaseGeneration,
|
|
305
|
+
activitySequence: lease.activitySequence,
|
|
306
|
+
hasActivity: hasNewActivity,
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return renews;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Check whether a task has timed out due to inactivity or hard duration ceiling.
|
|
314
|
+
*/
|
|
315
|
+
checkTaskTimeout(taskId, attemptId, isWaitingHuman = false) {
|
|
316
|
+
const lease = this.activeLeases.get(this.leaseKey(taskId, attemptId));
|
|
317
|
+
if (!lease)
|
|
318
|
+
return { expired: false };
|
|
319
|
+
const now = Date.now();
|
|
320
|
+
if (!isWaitingHuman && now - lease.lastActivityAt > this.maxInactivityMs) {
|
|
321
|
+
return {
|
|
322
|
+
expired: true,
|
|
323
|
+
reason: `Task lease expired: no activity for ${Math.round(this.maxInactivityMs / 1000)}s`,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
if (this.maxDurationMs > 0 && now - lease.startedAt > this.maxDurationMs) {
|
|
327
|
+
return {
|
|
328
|
+
expired: true,
|
|
329
|
+
reason: `Task hard execution ceiling exceeded (${Math.round(this.maxDurationMs / 1000)}s)`,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
return { expired: false };
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Bounded capacity reservation guard: fail-closed before starting new execution
|
|
336
|
+
* if the recovery outbox has reached its budget ceiling, preserving existing results.
|
|
337
|
+
*/
|
|
338
|
+
hasOutboxCapacity() {
|
|
339
|
+
if (this.outbox.size >= TASK_OUTBOX_LIMITS.maxEntries) {
|
|
340
|
+
return {
|
|
341
|
+
available: false,
|
|
342
|
+
reason: `Recovery outbox reached maximum capacity (${TASK_OUTBOX_LIMITS.maxEntries} entries). Reconnect to Hub to flush pending outcomes before starting new tasks.`,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
let totalBytes = 0;
|
|
346
|
+
for (const entry of this.outbox.values()) {
|
|
347
|
+
totalBytes += Buffer.byteLength(JSON.stringify(entry));
|
|
348
|
+
}
|
|
349
|
+
if (totalBytes >= TASK_OUTBOX_LIMITS.maxTotalBytes) {
|
|
350
|
+
return {
|
|
351
|
+
available: false,
|
|
352
|
+
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.`,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
return { available: true };
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Enqueue task terminal outcome into durable outbox.
|
|
359
|
+
* First write disk synchronously; throw on error so execution doesn't falsely succeed.
|
|
360
|
+
* Idempotent: identical (taskId, attemptId, status) returns existing; conflicting rejects.
|
|
361
|
+
*/
|
|
362
|
+
recordTaskFinish(task, outcome) {
|
|
363
|
+
const now = Date.now();
|
|
364
|
+
const safeReport = outcome.report ? boundTaskReport(outcome.report) : undefined;
|
|
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);
|
|
368
|
+
const key = this.leaseKey(task.id, task.attemptId);
|
|
369
|
+
const existing = this.outbox.get(key);
|
|
370
|
+
if (existing) {
|
|
371
|
+
const targetDeviceId = task.deviceId || this.deviceId;
|
|
372
|
+
if (existing.fingerprint === fingerprint &&
|
|
373
|
+
existing.botId === task.botId &&
|
|
374
|
+
existing.deviceId === targetDeviceId &&
|
|
375
|
+
existing.roomId === task.roomId &&
|
|
376
|
+
JSON.stringify(existing.reportMetadata) === JSON.stringify(reportMetadata)) {
|
|
377
|
+
return structuredClone(existing);
|
|
378
|
+
}
|
|
379
|
+
existing.status = outcome.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);
|
|
389
|
+
}
|
|
390
|
+
const entry = {
|
|
391
|
+
id: key,
|
|
392
|
+
taskId: task.id,
|
|
393
|
+
attemptId: task.attemptId,
|
|
394
|
+
botId: task.botId,
|
|
395
|
+
deviceId: task.deviceId || this.deviceId,
|
|
396
|
+
roomId: task.roomId,
|
|
397
|
+
status: outcome.status,
|
|
398
|
+
reportMetadata,
|
|
399
|
+
report: safeReport,
|
|
400
|
+
error: safeError,
|
|
401
|
+
fingerprint,
|
|
402
|
+
createdAt: now,
|
|
403
|
+
updatedAt: now,
|
|
404
|
+
attempts: 0,
|
|
405
|
+
};
|
|
406
|
+
// Transactional write: first stage next entries and commit to disk
|
|
407
|
+
const nextOutbox = [...Array.from(this.outbox.values()), entry];
|
|
408
|
+
this.persistOutboxSync(nextOutbox);
|
|
409
|
+
// Disk succeeded; update memory
|
|
410
|
+
this.outbox.set(entry.id, entry);
|
|
411
|
+
// Clean active lease
|
|
412
|
+
this.removeActiveLease(task.id, task.attemptId);
|
|
413
|
+
return structuredClone(entry);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* List all pending outbox entries waiting for Hub ACK.
|
|
417
|
+
*/
|
|
418
|
+
getPendingOutbox() {
|
|
419
|
+
return structuredClone(Array.from(this.outbox.values()));
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Mark attempt sent to Hub for backoff/tracking.
|
|
423
|
+
*/
|
|
424
|
+
markOutboxAttempt(id) {
|
|
425
|
+
const entry = this.outbox.get(id);
|
|
426
|
+
if (entry) {
|
|
427
|
+
const updated = { ...entry, attempts: entry.attempts + 1, updatedAt: Date.now() };
|
|
428
|
+
const next = Array.from(this.outbox.values()).map((e) => (e.id === id ? updated : e));
|
|
429
|
+
this.persistOutboxSync(next);
|
|
430
|
+
this.outbox.set(id, updated);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Acknowledge outbox entry upon receiving task_result_ack from Hub.
|
|
435
|
+
* Binds fingerprint to prevent mismatched outcome clearing wrong entry.
|
|
436
|
+
*/
|
|
437
|
+
ackOutbox(taskId, attemptId, fingerprint) {
|
|
438
|
+
const next = Array.from(this.outbox.values()).filter((e) => !(e.taskId === taskId && e.attemptId === attemptId && (!fingerprint || e.fingerprint === fingerprint)));
|
|
439
|
+
if (next.length !== this.outbox.size) {
|
|
440
|
+
this.persistOutboxSync(next);
|
|
441
|
+
for (const [id, entry] of this.outbox) {
|
|
442
|
+
if (entry.taskId === taskId &&
|
|
443
|
+
entry.attemptId === attemptId &&
|
|
444
|
+
(!fingerprint || entry.fingerprint === fingerprint)) {
|
|
445
|
+
this.outbox.delete(id);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return true;
|
|
449
|
+
}
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { writeJsonAtomicSync } from "../atomic-file.js";
|
|
5
|
+
import { createTaskReportStore, MAX_TASK_FULL_REPORT_BYTES } from "./task-report.js";
|
|
6
|
+
import { checkedUrl } from "./relay.js";
|
|
7
|
+
export const REPORT_OUTBOX_MAX_ENTRIES = 128;
|
|
8
|
+
export const REPORT_OUTBOX_MAX_BYTES = 64 * 1024 * 1024;
|
|
9
|
+
const ACCEPTED_RETENTION = 32;
|
|
10
|
+
const errors = new Set(["Report exceeds 4 MiB quota", "Executor supplied no full report", "Report upload pending"]);
|
|
11
|
+
const bindingKeys = ["id", "attemptId", "roomId", "botId"];
|
|
12
|
+
function binding(task) {
|
|
13
|
+
for (const field of bindingKeys)
|
|
14
|
+
if (typeof task[field] !== "string" || !task[field] || task[field].length > 256)
|
|
15
|
+
throw new Error("Invalid report binding");
|
|
16
|
+
if (task.botRevision !== undefined && (!Number.isSafeInteger(task.botRevision) || task.botRevision < 1))
|
|
17
|
+
throw new Error("Invalid report Bot revision");
|
|
18
|
+
return {
|
|
19
|
+
id: task.id,
|
|
20
|
+
attemptId: task.attemptId,
|
|
21
|
+
roomId: task.roomId,
|
|
22
|
+
botId: task.botId,
|
|
23
|
+
...(task.botRevision ? { botRevision: task.botRevision } : {}),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function validEntry(value) {
|
|
27
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
28
|
+
return false;
|
|
29
|
+
const e = value;
|
|
30
|
+
try {
|
|
31
|
+
binding(e);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
const allowed = new Set([
|
|
37
|
+
...bindingKeys,
|
|
38
|
+
"botRevision",
|
|
39
|
+
"reportRef",
|
|
40
|
+
"sha256",
|
|
41
|
+
"totalBytes",
|
|
42
|
+
"uploadPending",
|
|
43
|
+
"missing",
|
|
44
|
+
"rejected",
|
|
45
|
+
"lastError",
|
|
46
|
+
]);
|
|
47
|
+
return (Object.keys(e).every((key) => allowed.has(key)) &&
|
|
48
|
+
Number.isSafeInteger(e.totalBytes) &&
|
|
49
|
+
e.totalBytes >= 0 &&
|
|
50
|
+
["uploadPending", "missing", "rejected"].every((key) => typeof e[key] === "boolean") &&
|
|
51
|
+
(e.sha256 === undefined || /^[a-f0-9]{64}$/.test(e.sha256)) &&
|
|
52
|
+
(e.reportRef === undefined || /^[a-f0-9]{32,64}$/.test(e.reportRef)) &&
|
|
53
|
+
(e.lastError === undefined || errors.has(e.lastError)) &&
|
|
54
|
+
(!e.uploadPending || (!e.rejected && !!e.sha256 && e.totalBytes <= MAX_TASK_FULL_REPORT_BYTES)) &&
|
|
55
|
+
(e.rejected || e.missing || (!!e.sha256 && !!e.reportRef)));
|
|
56
|
+
}
|
|
57
|
+
/** Separate from terminal-result ACKs: a result never acknowledges report bytes. */
|
|
58
|
+
export function createTaskReportOutbox(dataDir, deviceId, hubUrl = "") {
|
|
59
|
+
const scope = { deviceId, hubUrl: hubUrl ? checkedUrl(hubUrl).href.replace(/\/$/, "") : "" };
|
|
60
|
+
const scopeKey = createHash("sha256").update(JSON.stringify(scope)).digest("hex").slice(0, 32);
|
|
61
|
+
// Scope both the queue and report bytes, so rebinding never replays another Hub's reports.
|
|
62
|
+
const scopedDir = dataDir ? join(dataDir, "task-report-outboxes", scopeKey) : undefined;
|
|
63
|
+
const store = scopedDir ? createTaskReportStore(scopedDir, "device") : undefined;
|
|
64
|
+
const file = scopedDir ? join(scopedDir, "outbox.json") : undefined;
|
|
65
|
+
let entries = [];
|
|
66
|
+
const memory = new Map();
|
|
67
|
+
const key = (task) => `${task.id}:${task.attemptId}`;
|
|
68
|
+
const bytes = (items) => items.reduce((sum, e) => sum + (e.rejected ? 0 : e.totalBytes), 0);
|
|
69
|
+
if (file) {
|
|
70
|
+
try {
|
|
71
|
+
const document = JSON.parse(readFileSync(file, "utf8"));
|
|
72
|
+
if (document.version !== 1 ||
|
|
73
|
+
document.deviceId !== scope.deviceId ||
|
|
74
|
+
document.hubUrl !== scope.hubUrl ||
|
|
75
|
+
!Array.isArray(document.entries) ||
|
|
76
|
+
!document.entries.every(validEntry) ||
|
|
77
|
+
document.entries.length > REPORT_OUTBOX_MAX_ENTRIES ||
|
|
78
|
+
bytes(document.entries) > REPORT_OUTBOX_MAX_BYTES ||
|
|
79
|
+
new Set(document.entries.map(key)).size !== document.entries.length)
|
|
80
|
+
throw new Error("Invalid report outbox");
|
|
81
|
+
entries = document.entries;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (error.code !== "ENOENT")
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function update(entry) {
|
|
89
|
+
if (!validEntry(entry))
|
|
90
|
+
throw new Error("Invalid report outbox entry");
|
|
91
|
+
const next = entries.filter((e) => key(e) !== key(entry)).concat(entry);
|
|
92
|
+
const removable = next.filter((e) => !e.uploadPending && !e.missing && !e.rejected && key(e) !== key(entry));
|
|
93
|
+
const removed = [];
|
|
94
|
+
while (removable.length &&
|
|
95
|
+
(next.length > REPORT_OUTBOX_MAX_ENTRIES ||
|
|
96
|
+
bytes(next) > REPORT_OUTBOX_MAX_BYTES ||
|
|
97
|
+
next.filter((e) => !e.uploadPending && !e.missing && !e.rejected).length > ACCEPTED_RETENTION)) {
|
|
98
|
+
const old = removable.shift();
|
|
99
|
+
next.splice(next.indexOf(old), 1);
|
|
100
|
+
removed.push(old);
|
|
101
|
+
}
|
|
102
|
+
if (next.length > REPORT_OUTBOX_MAX_ENTRIES || bytes(next) > REPORT_OUTBOX_MAX_BYTES)
|
|
103
|
+
throw new Error("Report outbox capacity exceeded; pending reports retained");
|
|
104
|
+
// Delete bytes before dropping their registry entry; a failed cleanup stays discoverable.
|
|
105
|
+
for (const old of removed) {
|
|
106
|
+
store?.removeReport(old.id, old.attemptId, deviceId, old.roomId);
|
|
107
|
+
memory.delete(key(old));
|
|
108
|
+
}
|
|
109
|
+
if (file)
|
|
110
|
+
writeJsonAtomicSync(file, { version: 1, ...scope, entries: next });
|
|
111
|
+
entries = next;
|
|
112
|
+
return { ...entry };
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
capture(taskInput, text) {
|
|
116
|
+
const task = binding(taskInput);
|
|
117
|
+
let meta;
|
|
118
|
+
const totalBytes = Buffer.byteLength(text);
|
|
119
|
+
const sha256 = createHash("sha256").update(text).digest("hex");
|
|
120
|
+
const previous = entries.find((e) => key(e) === key(task));
|
|
121
|
+
if (previous &&
|
|
122
|
+
(previous.roomId !== task.roomId ||
|
|
123
|
+
previous.botId !== task.botId ||
|
|
124
|
+
previous.botRevision !== task.botRevision ||
|
|
125
|
+
(previous.sha256 && previous.sha256 !== sha256)))
|
|
126
|
+
throw new Error("Report attempt content or binding conflict");
|
|
127
|
+
if (previous && previous.sha256 === sha256 && !previous.missing)
|
|
128
|
+
return { ...previous };
|
|
129
|
+
if (totalBytes > MAX_TASK_FULL_REPORT_BYTES)
|
|
130
|
+
return update({
|
|
131
|
+
...task,
|
|
132
|
+
sha256,
|
|
133
|
+
totalBytes,
|
|
134
|
+
uploadPending: false,
|
|
135
|
+
missing: true,
|
|
136
|
+
rejected: true,
|
|
137
|
+
lastError: "Report exceeds 4 MiB quota",
|
|
138
|
+
});
|
|
139
|
+
// Commit intent first; recovery can read the store if interrupted after its atomic write.
|
|
140
|
+
update({
|
|
141
|
+
...task,
|
|
142
|
+
reportRef: store
|
|
143
|
+
? createHash("sha256").update(`${task.id}:${task.attemptId}`).digest("hex").slice(0, 32)
|
|
144
|
+
: sha256,
|
|
145
|
+
sha256,
|
|
146
|
+
totalBytes,
|
|
147
|
+
uploadPending: true,
|
|
148
|
+
missing: true,
|
|
149
|
+
rejected: false,
|
|
150
|
+
});
|
|
151
|
+
meta = store?.saveFullReport(task.id, task.attemptId, task.roomId, deviceId, text);
|
|
152
|
+
if (!store)
|
|
153
|
+
memory.set(key(task), text);
|
|
154
|
+
return update({
|
|
155
|
+
...task,
|
|
156
|
+
reportRef: meta?.storageLocation.reportRef ?? sha256,
|
|
157
|
+
sha256,
|
|
158
|
+
totalBytes,
|
|
159
|
+
uploadPending: true,
|
|
160
|
+
missing: false,
|
|
161
|
+
rejected: false,
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
get(task) {
|
|
165
|
+
const entry = entries.find((e) => key(e) === key(task));
|
|
166
|
+
return entry ? { ...entry } : undefined;
|
|
167
|
+
},
|
|
168
|
+
markMissing(taskInput) {
|
|
169
|
+
const task = binding(taskInput);
|
|
170
|
+
const previous = entries.find((e) => key(e) === key(task));
|
|
171
|
+
return previous
|
|
172
|
+
? { ...previous }
|
|
173
|
+
: update({
|
|
174
|
+
...task,
|
|
175
|
+
totalBytes: 0,
|
|
176
|
+
uploadPending: false,
|
|
177
|
+
missing: true,
|
|
178
|
+
rejected: false,
|
|
179
|
+
lastError: "Executor supplied no full report",
|
|
180
|
+
});
|
|
181
|
+
},
|
|
182
|
+
pending() {
|
|
183
|
+
return entries.filter((e) => e.uploadPending && !e.rejected).map((e) => ({ ...e }));
|
|
184
|
+
},
|
|
185
|
+
read(entry) {
|
|
186
|
+
let text = memory.get(key(entry));
|
|
187
|
+
if (store) {
|
|
188
|
+
let offset = 0;
|
|
189
|
+
const parts = [];
|
|
190
|
+
do {
|
|
191
|
+
const page = store.getReport(entry.id, entry.attemptId, deviceId, entry.roomId, { offset, limit: 262144 });
|
|
192
|
+
if (!page || page.text === undefined)
|
|
193
|
+
throw new Error("Local full report missing");
|
|
194
|
+
parts.push(page.text);
|
|
195
|
+
if (!page.hasMore)
|
|
196
|
+
break;
|
|
197
|
+
if (!page.nextOffset || page.nextOffset <= offset)
|
|
198
|
+
throw new Error("Invalid local report pagination");
|
|
199
|
+
offset = page.nextOffset;
|
|
200
|
+
} while (offset < entry.totalBytes);
|
|
201
|
+
text = parts.join("");
|
|
202
|
+
}
|
|
203
|
+
if (text === undefined ||
|
|
204
|
+
Buffer.byteLength(text) !== entry.totalBytes ||
|
|
205
|
+
createHash("sha256").update(text).digest("hex") !== entry.sha256)
|
|
206
|
+
throw new Error("Local full report is missing or failed integrity verification");
|
|
207
|
+
return text;
|
|
208
|
+
},
|
|
209
|
+
accepted(entry) {
|
|
210
|
+
return update({ ...entry, uploadPending: false, missing: false, lastError: undefined });
|
|
211
|
+
},
|
|
212
|
+
failed(entry, _error) {
|
|
213
|
+
return update({ ...entry, uploadPending: true, lastError: "Report upload pending" });
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|