pi-web-ui 0.114.2 → 0.115.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 +55 -1
- package/bin/pi-web-ui.mjs +69 -7
- package/dist/server/agent-service-daemon.js +440 -32
- package/dist/server/agent-service.js +878 -383
- package/dist/server/canvas/canvas-dispatch.js +13 -1
- package/dist/server/client-state.js +25 -0
- package/dist/server/communicate-tool.js +2 -0
- package/dist/server/context-usage.js +105 -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 +72 -9
- package/dist/server/device-center/bot-presets.js +46 -0
- package/dist/server/device-center/collab-service.js +328 -10
- package/dist/server/device-center/collab-tool.js +738 -12
- 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 +19 -0
- package/dist/server/device-center/execution-settings.js +100 -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 +389 -40
- package/dist/server/device-center/file-sync-paths.js +171 -0
- package/dist/server/device-center/file-sync.js +180 -91
- package/dist/server/device-center/group-context-delta.js +37 -0
- package/dist/server/device-center/group-context-message.js +208 -0
- package/dist/server/device-center/group-context.js +109 -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 +178 -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.js +1544 -80
- 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 +18 -0
- package/dist/server/device-center/local.js +356 -40
- package/dist/server/device-center/main.js +11 -1
- 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 +549 -41
- package/dist/server/device-center/store.js +66 -3
- 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 +400 -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 +815 -8
- package/dist/server/dispatch-domain-handlers.js +21 -3
- package/dist/server/dsh/dsh-agent-service.js +6 -0
- package/dist/server/goal-service.js +10 -5
- package/dist/server/index.js +89 -13
- package/dist/server/message-deletion.js +40 -0
- package/dist/server/message-window.js +9 -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 +1 -0
- 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 +5 -2
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/protocol.js +2 -2
- 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/subagent-helpers.js +4 -1
- package/dist/server/subagents.js +50 -36
- package/dist/server/tool-host-factories.js +1 -0
- package/dist/server/universal/universal-session.js +5 -0
- package/dist/server/webui-context.js +25 -5
- package/docs/README.md +94 -0
- package/docs/device-center.md +100 -12
- package/docs/dsh-engine.md +10 -10
- package/extensions/webui.ts +43 -1
- package/package.json +1 -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-BYzPgmoq.js +1 -0
- package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
- package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
- package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
- package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
- package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
- package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
- package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
- package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
- package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
- package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
- package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
- package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
- package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
- package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
- package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
- package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
- package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
- package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
- package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
- package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
- package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
- package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
- package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
- package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
- package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
- package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
- package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
- package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
- package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
- package/web/dist/assets/index-CsFs_HMb.css +1 -0
- package/web/dist/assets/index-DHeeHS_l.js +85 -0
- package/web/dist/assets/index-DTZch8uz.js +85 -0
- package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
- package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
- package/web/dist/assets/theme-BXGpyTMh.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
- package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
- package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
- package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
- package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
- package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
- package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
- package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
- package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
- package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
- package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
- package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
- package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
- package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
- package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
- package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
- package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
- package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
- package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
- package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
- package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
- package/web/dist/assets/index-Cdh3sibd.js +0 -85
- package/web/dist/assets/index-DDZMv6LO.css +0 -1
- package/web/dist/assets/index-DWw_SxRq.js +0 -85
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
- package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Filter out thought/reasoning fragments.
|
|
3
|
+
* Drops open or closed thought blocks entirely. If an open tag exists without closure,
|
|
4
|
+
* the trailing fragment is discarded to prevent streaming leaks.
|
|
5
|
+
*/
|
|
6
|
+
export function sanitizeTextForJournal(input) {
|
|
7
|
+
if (!input)
|
|
8
|
+
return "";
|
|
9
|
+
let text = input;
|
|
10
|
+
// Drop closed thought tags
|
|
11
|
+
text = text.replace(/<thought[\s\S]*?<\/thought>/gi, "");
|
|
12
|
+
text = text.replace(/<thinking[\s\S]*?<\/thinking>/gi, "");
|
|
13
|
+
// Drop unclosed trailing thought tags (streaming fragment)
|
|
14
|
+
text = text.replace(/<(thought|thinking)[\s\S]*$/gi, "");
|
|
15
|
+
// Drop credential/token patterns (best-effort defense in depth)
|
|
16
|
+
text = text.replace(/((?:bearer|token|key|secret|password|passwd|credential|auth|api[-_]?key)[\s:="']{1,4})([A-Za-z0-9_\-./+=]{8,})/gi, "$1[REDACTED]");
|
|
17
|
+
text = text.replace(/-----BEGIN[A-Z0-9\s_-]+PRIVATE KEY-----[\s\S]*?-----END[A-Z0-9\s_-]+PRIVATE KEY-----/gi, "[REDACTED PRIVATE KEY]");
|
|
18
|
+
return text.trim();
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Sanitize tool parameters into safe structural summaries.
|
|
22
|
+
* Never outputs raw commands, raw file contents, or raw sensitive file paths.
|
|
23
|
+
*/
|
|
24
|
+
export function sanitizeToolParameters(toolName, params) {
|
|
25
|
+
if (!params || typeof params !== "object" || Array.isArray(params))
|
|
26
|
+
return;
|
|
27
|
+
const input = params;
|
|
28
|
+
const result = {};
|
|
29
|
+
if (toolName === "bash" || toolName === "terminal") {
|
|
30
|
+
if (typeof input.command === "string") {
|
|
31
|
+
result.commandLength = input.command.length;
|
|
32
|
+
result.action = "run_shell_command";
|
|
33
|
+
}
|
|
34
|
+
if (typeof input.timeout === "number")
|
|
35
|
+
result.timeout = input.timeout;
|
|
36
|
+
}
|
|
37
|
+
else if (toolName === "read") {
|
|
38
|
+
if (typeof input.path === "string") {
|
|
39
|
+
const ext = input.path.split(".").pop();
|
|
40
|
+
result.fileType = ext ? `.${ext.slice(0, 8)}` : "file";
|
|
41
|
+
result.action = "read_file";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
else if (toolName === "write" || toolName === "edit" || toolName === "edit_soft") {
|
|
45
|
+
if (typeof input.path === "string") {
|
|
46
|
+
const ext = input.path.split(".").pop();
|
|
47
|
+
result.fileType = ext ? `.${ext.slice(0, 8)}` : "file";
|
|
48
|
+
result.action = toolName === "write" ? "write_file" : "edit_file";
|
|
49
|
+
}
|
|
50
|
+
if (typeof input.content === "string") {
|
|
51
|
+
result.contentBytes = Buffer.byteLength(input.content, "utf8");
|
|
52
|
+
}
|
|
53
|
+
if (Array.isArray(input.edits)) {
|
|
54
|
+
result.editCount = input.edits.length;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
// Generic tool summary: count parameters without exposing unknown values
|
|
59
|
+
result.parameterCount = Object.keys(input).length;
|
|
60
|
+
result.action = `invoke_${toolName}`;
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
export function summarizeToolOutput(toolName, output, isError = false) {
|
|
65
|
+
const byteLen = Buffer.byteLength(output, "utf8");
|
|
66
|
+
if (isError) {
|
|
67
|
+
return `[${toolName} failed: ${byteLen} bytes error output]`;
|
|
68
|
+
}
|
|
69
|
+
if (toolName === "read") {
|
|
70
|
+
return `[read completed: ${byteLen} bytes read]`;
|
|
71
|
+
}
|
|
72
|
+
if (toolName === "write" || toolName === "edit" || toolName === "edit_soft") {
|
|
73
|
+
return `[${toolName} completed: ${byteLen} bytes written]`;
|
|
74
|
+
}
|
|
75
|
+
if (toolName === "bash" || toolName === "terminal") {
|
|
76
|
+
return `[${toolName} completed: ${byteLen} bytes output]`;
|
|
77
|
+
}
|
|
78
|
+
return `[${toolName} completed: ${byteLen} bytes output]`;
|
|
79
|
+
}
|
|
80
|
+
/** Project tool lifecycle with strict parameter and credential redaction. */
|
|
81
|
+
export function projectToolLifecycle(value) {
|
|
82
|
+
if (!value || typeof value !== "object")
|
|
83
|
+
return;
|
|
84
|
+
const val = value;
|
|
85
|
+
if (typeof val.toolName !== "string" || !/^[A-Za-z0-9_.:-]{1,80}$/.test(val.toolName))
|
|
86
|
+
return;
|
|
87
|
+
const phase = ["start", "progress", "end", "failed"].includes(val.phase) ? val.phase : "progress";
|
|
88
|
+
const lifecycle = {
|
|
89
|
+
toolName: val.toolName,
|
|
90
|
+
phase,
|
|
91
|
+
};
|
|
92
|
+
if (typeof val.callId === "string" && val.callId.length <= 64)
|
|
93
|
+
lifecycle.callId = val.callId;
|
|
94
|
+
if (typeof val.summary === "string") {
|
|
95
|
+
lifecycle.summary = sanitizeTextForJournal(val.summary).slice(0, 256);
|
|
96
|
+
}
|
|
97
|
+
if (val.parameters) {
|
|
98
|
+
const safeParams = sanitizeToolParameters(val.toolName, val.parameters);
|
|
99
|
+
if (safeParams && Object.keys(safeParams).length > 0)
|
|
100
|
+
lifecycle.parametersPreview = safeParams;
|
|
101
|
+
}
|
|
102
|
+
if (typeof val.output === "string") {
|
|
103
|
+
// Never leak raw read/bash/write outputs or environment secrets; emit safe structural summary
|
|
104
|
+
lifecycle.outputSnippet = summarizeToolOutput(val.toolName, val.output, phase === "failed");
|
|
105
|
+
}
|
|
106
|
+
if (typeof val.durationMs === "number" && Number.isFinite(val.durationMs) && val.durationMs >= 0) {
|
|
107
|
+
lifecycle.durationMs = Math.round(val.durationMs);
|
|
108
|
+
}
|
|
109
|
+
return lifecycle;
|
|
110
|
+
}
|
|
111
|
+
/** Project explicitly allowed fields; never spread tool arguments or approval payloads. */
|
|
112
|
+
export function projectTaskActivity(value) {
|
|
113
|
+
if (!value || typeof value !== "object")
|
|
114
|
+
return;
|
|
115
|
+
const input = value;
|
|
116
|
+
if (!["model", "tool", "waiting"].includes(input.phase))
|
|
117
|
+
return;
|
|
118
|
+
let safeText;
|
|
119
|
+
if (typeof input.text === "string") {
|
|
120
|
+
const sanitized = sanitizeTextForJournal(input.text);
|
|
121
|
+
safeText = Buffer.from(sanitized)
|
|
122
|
+
.subarray(0, 2048)
|
|
123
|
+
.toString("utf8")
|
|
124
|
+
.replace(/\uFFFD$/u, "");
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
phase: input.phase,
|
|
128
|
+
...(safeText !== undefined ? { text: safeText } : {}),
|
|
129
|
+
...(typeof input.toolName === "string" && /^[A-Za-z0-9_.:-]{1,80}$/.test(input.toolName)
|
|
130
|
+
? { toolName: input.toolName }
|
|
131
|
+
: {}),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
export function validTaskProgress(value) {
|
|
135
|
+
return (!!projectTaskActivity(value) &&
|
|
136
|
+
[value.taskId, value.botId, value.attemptId].every((id) => typeof id === "string" && id.length > 0 && id.length <= 128) &&
|
|
137
|
+
Number.isSafeInteger(value.sequence) &&
|
|
138
|
+
value.sequence > 0 &&
|
|
139
|
+
(value.text === undefined || (typeof value.text === "string" && Buffer.byteLength(value.text) <= 2048)) &&
|
|
140
|
+
(value.toolName === undefined || /^[A-Za-z0-9_.:-]{1,80}$/.test(value.toolName)));
|
|
141
|
+
}
|
|
@@ -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
|
+
}
|