pi-web-ui 0.115.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 +65 -2
- package/bin/device-hub-cli.mjs +26 -3
- package/bin/pi-web-ui.mjs +159 -71
- package/dist/server/agent-service-daemon.js +136 -8
- package/dist/server/agent-service.js +594 -159
- package/dist/server/canvas/canvas-workspace.js +18 -86
- package/dist/server/client-state.js +52 -8
- package/dist/server/compaction-markers.js +43 -24
- package/dist/server/dangling-tools.js +172 -16
- package/dist/server/device-center/bot-execution.js +77 -2
- package/dist/server/device-center/collab-service.js +61 -12
- package/dist/server/device-center/collab-tool.js +482 -21
- 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 +17 -7
- package/dist/server/device-center/execution-instructions.js +2 -1
- package/dist/server/device-center/execution-settings.js +138 -25
- package/dist/server/device-center/executor.js +51 -6
- package/dist/server/device-center/file-sync.js +14 -13
- package/dist/server/device-center/group-context-message.js +3 -1
- package/dist/server/device-center/group-context.js +73 -3
- package/dist/server/device-center/hub-conversations.js +71 -6
- 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-locks.js +320 -0
- package/dist/server/device-center/hub-page.js +16 -35
- 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-webhooks.js +165 -0
- package/dist/server/device-center/hub.js +1531 -305
- package/dist/server/device-center/integration-verification.js +113 -0
- package/dist/server/device-center/local-hub.js +8 -3
- 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 +181 -13
- package/dist/server/device-center/main.js +4 -1
- package/dist/server/device-center/partition-log.js +330 -0
- 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 +475 -42
- package/dist/server/device-center/store.js +366 -89
- 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-scheduler.js +48 -3
- 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/transfers.js +41 -15
- 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 +29 -3
- package/dist/server/dsh/dsh-agent-service.js +9 -2
- package/dist/server/engine-probe.js +112 -1
- package/dist/server/global-loader.js +119 -19
- package/dist/server/index.js +159 -17
- package/dist/server/managed.js +2 -0
- package/dist/server/model-admin.js +48 -6
- package/dist/server/model-enrich.js +10 -1
- package/dist/server/patch-node-pty.js +3 -2
- package/dist/server/patch-remote-catalog.js +3 -2
- package/dist/server/plugins.js +64 -7
- package/dist/server/preset-fields.js +17 -1
- package/dist/server/preset-share.js +1 -0
- package/dist/server/prompt-composer.js +39 -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/reasoning-registry.js +207 -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/startup-banner.js +35 -0
- package/dist/server/subagents.js +2 -1
- package/dist/server/tool-manager.js +17 -9
- package/dist/server/transcript-prepare.js +73 -0
- package/dist/server/unauthorized-page.js +319 -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 +959 -0
- package/docs/device-center.md +34 -20
- package/package.json +4 -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-BYzPgmoq.js → BgTasksModal-BjNRIUIc.js} +1 -1
- package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0zuU8FE.js} +1 -1
- package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-BWvdmJ0M.js} +3 -3
- package/web/dist/assets/{CanvasStudio-BCUeEf25.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-BLP1Su5G.js +1 -0
- package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
- package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
- package/web/dist/assets/{Dropdown-CGXD0DfT.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-mevF-ySi.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-qL99FN_F.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-LHwkS2jV.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-DE5-gEtI.js → PiSetupModal-BX5rUuoI.js} +1 -1
- package/web/dist/assets/{ProviderOAuthControls-6UMARucA.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-CTp_BZ4S.js → TerminalPanel-D4By_RVc.js} +2 -2
- package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-lZw8-i3j.js} +2 -2
- package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
- package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
- package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-BY6ojmle.js} +1 -1
- package/web/dist/assets/{desktop-kjBoE3Nu.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-C8mNgghx.js → plugin-host-Dn8Dd6SC.js} +1 -1
- package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
- package/web/dist/assets/{theme-BXGpyTMh.js → theme-D_bihpdN.js} +1 -1
- package/web/dist/index.html +11 -11
- package/web/dist/sw.js +1 -1
- package/dist/server/patch-turn-end-boundary.js +0 -77
- package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
- package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
- package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
- package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
- package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
- package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
- package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
- package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
- package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
- package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
- package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
- package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
- package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
- package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
- package/web/dist/assets/index-CsFs_HMb.css +0 -1
- package/web/dist/assets/index-DHeeHS_l.js +0 -85
- package/web/dist/assets/index-DTZch8uz.js +0 -85
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
import { mkdir, readFile, open, rename, unlink } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { PartitionedAppendLog } from "./partition-log.js";
|
|
4
|
+
import { HubTransactionLog, } from "./hub-transaction-log.js";
|
|
3
5
|
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
4
6
|
import { projectConversationState, reconcileConversationState, } from "./task-state.js";
|
|
5
|
-
export const taskPending = (task) => !isTerminal(task.status) ||
|
|
7
|
+
export const taskPending = (task) => !isTerminal(task.status) ||
|
|
8
|
+
!!(task.cancelRequested && !task.stopConfirmed) ||
|
|
9
|
+
(task.recoveryUntil !== undefined && task.recoveryUntil > Date.now());
|
|
10
|
+
/** Contract authority and captured evidence survive automatic retention until explicit room data reset. */
|
|
11
|
+
export const taskHasImmutableEvidence = (task) => !!task.contract ||
|
|
12
|
+
!!task.artifact ||
|
|
13
|
+
task.artifactProduced === true ||
|
|
14
|
+
(task.executionMode === "code" && task.executionCompleted === true);
|
|
6
15
|
export const isTerminal = (status) => ["completed", "failed", "interrupted"].includes(status);
|
|
7
16
|
export const hashSecret = (secret) => createHash("sha256").update(secret).digest("hex");
|
|
8
17
|
export function secretMatches(secret, hash) {
|
|
@@ -18,7 +27,257 @@ export function publicTask(task) {
|
|
|
18
27
|
const { leaseToken: _token, ...visible } = task;
|
|
19
28
|
return visible;
|
|
20
29
|
}
|
|
21
|
-
/**
|
|
30
|
+
/** Rows kept per room when replaying append logs; mirrors the group retention the Hub enforces. */
|
|
31
|
+
export const HUB_LOG_RETENTION = 500;
|
|
32
|
+
function createHubLogs(dataDir) {
|
|
33
|
+
const root = join(dataDir, "hub-log");
|
|
34
|
+
return {
|
|
35
|
+
messages: new PartitionedAppendLog({
|
|
36
|
+
dir: join(root, "messages"),
|
|
37
|
+
partition: (message) => message.roomId,
|
|
38
|
+
id: (message) => message.id,
|
|
39
|
+
retention: HUB_LOG_RETENTION,
|
|
40
|
+
}),
|
|
41
|
+
tasks: new PartitionedAppendLog({
|
|
42
|
+
dir: join(root, "tasks"),
|
|
43
|
+
partition: (task) => task.roomId,
|
|
44
|
+
id: (task) => task.id,
|
|
45
|
+
retention: HUB_LOG_RETENTION,
|
|
46
|
+
// Retain live work and immutable code evidence across checkpoint compaction and restarts.
|
|
47
|
+
protect: (task) => taskPending(task) || taskHasImmutableEvidence(task),
|
|
48
|
+
}),
|
|
49
|
+
conversationMessages: new PartitionedAppendLog({
|
|
50
|
+
dir: join(root, "conversation-messages"),
|
|
51
|
+
partition: (message) => message.conversationId,
|
|
52
|
+
id: (message) => message.id,
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function emptyHubState() {
|
|
57
|
+
return {
|
|
58
|
+
version: 2,
|
|
59
|
+
checkpointSeq: 0,
|
|
60
|
+
conversations: [],
|
|
61
|
+
conversationMessages: [],
|
|
62
|
+
deliveries: [],
|
|
63
|
+
reviews: [],
|
|
64
|
+
deliveryReceipts: [],
|
|
65
|
+
integrations: [],
|
|
66
|
+
accounts: [],
|
|
67
|
+
devices: [],
|
|
68
|
+
bots: [],
|
|
69
|
+
sessions: [],
|
|
70
|
+
rooms: [],
|
|
71
|
+
messages: [],
|
|
72
|
+
tasks: [],
|
|
73
|
+
receipts: [],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Tasks/messages are partitioned by room; conversations may reference a room row that no longer exists. */
|
|
77
|
+
function roomPartitionsOf(state) {
|
|
78
|
+
return new Set([
|
|
79
|
+
...state.rooms.map((room) => room.id),
|
|
80
|
+
...state.conversations.map((conversation) => conversation.roomId),
|
|
81
|
+
]);
|
|
82
|
+
}
|
|
83
|
+
/** Merge log rows with rows still inlined by an older Hub; inline rows win (they are the older baseline). */
|
|
84
|
+
function mergeRows(stored, inline) {
|
|
85
|
+
if (!inline.length)
|
|
86
|
+
return [...stored];
|
|
87
|
+
if (!stored.length)
|
|
88
|
+
return [...inline];
|
|
89
|
+
const merged = new Map();
|
|
90
|
+
for (const row of inline)
|
|
91
|
+
merged.set(row.id, row);
|
|
92
|
+
for (const row of stored)
|
|
93
|
+
if (!merged.has(row.id))
|
|
94
|
+
merged.set(row.id, row);
|
|
95
|
+
return [...merged.values()];
|
|
96
|
+
}
|
|
97
|
+
function computeCollectionDiff(oldRows, newRows) {
|
|
98
|
+
const oldMap = new Map();
|
|
99
|
+
for (const row of oldRows) {
|
|
100
|
+
oldMap.set(row.id, JSON.stringify(row));
|
|
101
|
+
}
|
|
102
|
+
const upsert = [];
|
|
103
|
+
const newIds = new Set();
|
|
104
|
+
for (const row of newRows) {
|
|
105
|
+
newIds.add(row.id);
|
|
106
|
+
const serialized = JSON.stringify(row);
|
|
107
|
+
if (oldMap.get(row.id) !== serialized) {
|
|
108
|
+
upsert.push(row);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const deleteIds = [];
|
|
112
|
+
for (const row of oldRows) {
|
|
113
|
+
if (!newIds.has(row.id)) {
|
|
114
|
+
deleteIds.push(row.id);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return { upsert, deleteIds };
|
|
118
|
+
}
|
|
119
|
+
function applyCollectionDiff(target, diff) {
|
|
120
|
+
const deleteSet = new Set(diff.deleteIds);
|
|
121
|
+
let i = 0;
|
|
122
|
+
while (i < target.length) {
|
|
123
|
+
if (deleteSet.has(target[i].id)) {
|
|
124
|
+
target.splice(i, 1);
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
i++;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const indexMap = new Map();
|
|
131
|
+
for (let j = 0; j < target.length; j++) {
|
|
132
|
+
indexMap.set(target[j].id, j);
|
|
133
|
+
}
|
|
134
|
+
for (const item of diff.upsert) {
|
|
135
|
+
const existingIndex = indexMap.get(item.id);
|
|
136
|
+
if (existingIndex !== undefined) {
|
|
137
|
+
target[existingIndex] = item;
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
target.push(item);
|
|
141
|
+
indexMap.set(item.id, target.length - 1);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function extractIndexState(state) {
|
|
146
|
+
const { messages: _m, tasks: _t, conversationMessages: _cm, ...index } = state;
|
|
147
|
+
return index;
|
|
148
|
+
}
|
|
149
|
+
async function persistIndexTo(indexPath, state, checkpointSeq) {
|
|
150
|
+
const temporary = `${indexPath}.${randomUUID()}.tmp`;
|
|
151
|
+
const index = {
|
|
152
|
+
...state,
|
|
153
|
+
messages: [],
|
|
154
|
+
tasks: [],
|
|
155
|
+
conversationMessages: [],
|
|
156
|
+
checkpointSeq,
|
|
157
|
+
};
|
|
158
|
+
delete index.checkpointSeqRaw;
|
|
159
|
+
try {
|
|
160
|
+
const file = await open(temporary, "wx", 0o600);
|
|
161
|
+
try {
|
|
162
|
+
await file.writeFile(JSON.stringify(index));
|
|
163
|
+
await file.sync();
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
await file.close();
|
|
167
|
+
}
|
|
168
|
+
await rename(temporary, indexPath);
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
await unlink(temporary).catch((error) => {
|
|
172
|
+
if (error.code !== "ENOENT")
|
|
173
|
+
throw error;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
async function loadHubFiles(dataDir, options = {}) {
|
|
178
|
+
if (!options.readOnly) {
|
|
179
|
+
await mkdir(dataDir, { recursive: true, mode: 0o700 });
|
|
180
|
+
}
|
|
181
|
+
let state;
|
|
182
|
+
let checkpointSeq = 0;
|
|
183
|
+
try {
|
|
184
|
+
const rawText = await readFile(join(dataDir, "device-hub.json"), "utf8");
|
|
185
|
+
const rawJson = JSON.parse(rawText);
|
|
186
|
+
checkpointSeq = typeof rawJson.checkpointSeq === "number" ? rawJson.checkpointSeq : 0;
|
|
187
|
+
state = rawJson;
|
|
188
|
+
delete state.checkpointSeq;
|
|
189
|
+
if (state.version !== 2 ||
|
|
190
|
+
![
|
|
191
|
+
state.accounts,
|
|
192
|
+
state.devices,
|
|
193
|
+
state.bots,
|
|
194
|
+
state.sessions,
|
|
195
|
+
state.rooms,
|
|
196
|
+
state.messages,
|
|
197
|
+
state.tasks,
|
|
198
|
+
state.receipts,
|
|
199
|
+
].every(Array.isArray)) {
|
|
200
|
+
throw new Error("Invalid device hub store");
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
if (error.code !== "ENOENT")
|
|
205
|
+
throw error;
|
|
206
|
+
state = emptyHubState();
|
|
207
|
+
delete state.checkpointSeq;
|
|
208
|
+
}
|
|
209
|
+
state.conversations ??= [];
|
|
210
|
+
state.conversationMessages ??= [];
|
|
211
|
+
state.deliveries ??= [];
|
|
212
|
+
state.reviews ??= [];
|
|
213
|
+
state.deliveryReceipts ??= [];
|
|
214
|
+
state.integrations ??= [];
|
|
215
|
+
if (![
|
|
216
|
+
state.conversations,
|
|
217
|
+
state.conversationMessages,
|
|
218
|
+
state.deliveries,
|
|
219
|
+
state.reviews,
|
|
220
|
+
state.deliveryReceipts,
|
|
221
|
+
state.integrations,
|
|
222
|
+
].every(Array.isArray))
|
|
223
|
+
throw new Error("Invalid conversation store");
|
|
224
|
+
// Read the WAL before loading/sweeping projections: a committed parent may not be in the old index yet.
|
|
225
|
+
const wal = new HubTransactionLog({ walPath: join(dataDir, "hub-wal.jsonl") });
|
|
226
|
+
const { records } = await wal.readTransactions({ readOnly: options.readOnly });
|
|
227
|
+
const unprojectedRecords = records.filter((record) => record.seq > checkpointSeq);
|
|
228
|
+
const logs = createHubLogs(dataDir);
|
|
229
|
+
const roomPartitions = roomPartitionsOf(state);
|
|
230
|
+
const conversations = new Set(state.conversations.map((conversation) => conversation.id));
|
|
231
|
+
for (const record of unprojectedRecords) {
|
|
232
|
+
for (const partition of roomPartitionsOf(record.index))
|
|
233
|
+
roomPartitions.add(partition);
|
|
234
|
+
for (const conversation of record.index.conversations)
|
|
235
|
+
conversations.add(conversation.id);
|
|
236
|
+
}
|
|
237
|
+
// Logs are the authority; inline rows only exist in files written before the split (or by an older Hub).
|
|
238
|
+
const storedMessages = await logs.messages.load(roomPartitions, options);
|
|
239
|
+
const storedTasks = await logs.tasks.load(roomPartitions, options);
|
|
240
|
+
const storedConversationMessages = await logs.conversationMessages.load(conversations, options);
|
|
241
|
+
const legacy = state.messages.length > 0 || state.tasks.length > 0 || state.conversationMessages.length > 0;
|
|
242
|
+
state.messages = mergeRows(storedMessages, state.messages);
|
|
243
|
+
state.tasks = mergeRows(storedTasks, state.tasks);
|
|
244
|
+
state.conversationMessages = mergeRows(storedConversationMessages, state.conversationMessages);
|
|
245
|
+
if (unprojectedRecords.length > 0) {
|
|
246
|
+
for (const record of unprojectedRecords) {
|
|
247
|
+
const { checkpointSeq: _recSeq, ...indexProps } = record.index;
|
|
248
|
+
Object.assign(state, indexProps);
|
|
249
|
+
applyCollectionDiff(state.messages, record.diff.messages);
|
|
250
|
+
applyCollectionDiff(state.tasks, record.diff.tasks);
|
|
251
|
+
applyCollectionDiff(state.conversationMessages, record.diff.conversationMessages);
|
|
252
|
+
checkpointSeq = record.seq;
|
|
253
|
+
}
|
|
254
|
+
// Catch-up projection: if not read-only, project recovered uncommitted states to logs and index checkpoint
|
|
255
|
+
if (!options.readOnly) {
|
|
256
|
+
const recoveryRooms = roomPartitionsOf(state);
|
|
257
|
+
const recoveryConversations = new Set(state.conversations.map((conversation) => conversation.id));
|
|
258
|
+
// Projection order: 1. commit logs
|
|
259
|
+
await logs.messages.commit(state.messages, recoveryRooms);
|
|
260
|
+
await logs.tasks.commit(state.tasks, recoveryRooms);
|
|
261
|
+
await logs.conversationMessages.commit(state.conversationMessages, recoveryConversations);
|
|
262
|
+
// Projection order: 2. commit index checkpoint
|
|
263
|
+
await persistIndexTo(join(dataDir, "device-hub.json"), state, checkpointSeq);
|
|
264
|
+
// 3. checkpoint WAL
|
|
265
|
+
await wal.checkpoint(checkpointSeq);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
// Legacy state is a baseline, not evidence that historical transitions were observed.
|
|
269
|
+
for (const conversation of state.conversations) {
|
|
270
|
+
conversation.taskState = projectConversationState(state, conversation);
|
|
271
|
+
conversation.events ??= [];
|
|
272
|
+
}
|
|
273
|
+
return { state, logs, wal, checkpointSeq, legacy };
|
|
274
|
+
}
|
|
275
|
+
/** Read the durable state without open() side effects (no interrupt marking); used by tests and tooling. */
|
|
276
|
+
export async function readPersistedHub(dataDir) {
|
|
277
|
+
// Read-only: never sweep orphan files or repair tails or mutate checkpoints from an inspection path.
|
|
278
|
+
return (await loadHubFiles(dataDir, { sweep: false, readOnly: true })).state;
|
|
279
|
+
}
|
|
280
|
+
/** A single process owns a data directory. The fsynced WAL is the transaction commit point. */
|
|
22
281
|
export class DeviceHubStore {
|
|
23
282
|
state;
|
|
24
283
|
listeners = new Set();
|
|
@@ -30,85 +289,62 @@ export class DeviceHubStore {
|
|
|
30
289
|
}
|
|
31
290
|
tail = Promise.resolve();
|
|
32
291
|
path;
|
|
33
|
-
|
|
292
|
+
logs;
|
|
293
|
+
wal;
|
|
294
|
+
logDir;
|
|
295
|
+
lastSeq;
|
|
296
|
+
checkpointSeq;
|
|
297
|
+
projectionFailed = false;
|
|
298
|
+
lastProjectionError;
|
|
299
|
+
constructor(dataDir, state, logs, wal, checkpointSeq) {
|
|
34
300
|
this.path = join(dataDir, "device-hub.json");
|
|
301
|
+
this.logDir = join(dataDir, "hub-log");
|
|
35
302
|
this.state = state;
|
|
303
|
+
this.logs = logs;
|
|
304
|
+
this.wal = wal;
|
|
305
|
+
this.checkpointSeq = checkpointSeq;
|
|
306
|
+
this.lastSeq = checkpointSeq;
|
|
36
307
|
}
|
|
37
|
-
static async open(dataDir) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
308
|
+
static async open(dataDir, options = {}) {
|
|
309
|
+
const { state, logs, wal, checkpointSeq, legacy } = await loadHubFiles(dataDir);
|
|
310
|
+
const store = new DeviceHubStore(dataDir, state, logs, wal, checkpointSeq);
|
|
311
|
+
// Move collections that older Hubs kept inline into their append logs. Logs are written first so
|
|
312
|
+
// an interrupted migration can be retried from the still-inline index without losing rows.
|
|
313
|
+
if (legacy)
|
|
314
|
+
await store.migrateInlineCollections();
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
const recoveryGraceMs = 60_000;
|
|
317
|
+
const tasksToInterrupt = state.tasks.filter((task) => {
|
|
318
|
+
if (isTerminal(task.status))
|
|
319
|
+
return false;
|
|
320
|
+
if (options.retainUnleasedQueued) {
|
|
321
|
+
if (task.status === "running")
|
|
322
|
+
return true;
|
|
323
|
+
if (task.status === "queued" && (task.leaseToken || task.leaseGeneration !== undefined))
|
|
324
|
+
return true;
|
|
325
|
+
return false;
|
|
54
326
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
throw error;
|
|
59
|
-
state = {
|
|
60
|
-
version: 2,
|
|
61
|
-
conversations: [],
|
|
62
|
-
conversationMessages: [],
|
|
63
|
-
deliveries: [],
|
|
64
|
-
reviews: [],
|
|
65
|
-
deliveryReceipts: [],
|
|
66
|
-
integrations: [],
|
|
67
|
-
accounts: [],
|
|
68
|
-
devices: [],
|
|
69
|
-
bots: [],
|
|
70
|
-
sessions: [],
|
|
71
|
-
rooms: [],
|
|
72
|
-
messages: [],
|
|
73
|
-
tasks: [],
|
|
74
|
-
receipts: [],
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
state.conversations ??= [];
|
|
78
|
-
state.conversationMessages ??= [];
|
|
79
|
-
state.deliveries ??= [];
|
|
80
|
-
state.reviews ??= [];
|
|
81
|
-
state.deliveryReceipts ??= [];
|
|
82
|
-
state.integrations ??= [];
|
|
83
|
-
if (![
|
|
84
|
-
state.conversations,
|
|
85
|
-
state.conversationMessages,
|
|
86
|
-
state.deliveries,
|
|
87
|
-
state.reviews,
|
|
88
|
-
state.deliveryReceipts,
|
|
89
|
-
state.integrations,
|
|
90
|
-
].every(Array.isArray))
|
|
91
|
-
throw new Error("Invalid conversation store");
|
|
92
|
-
// Legacy state is a baseline, not evidence that historical transitions were observed.
|
|
93
|
-
for (const conversation of state.conversations) {
|
|
94
|
-
conversation.taskState = projectConversationState(state, conversation);
|
|
95
|
-
conversation.events ??= [];
|
|
96
|
-
}
|
|
97
|
-
const store = new DeviceHubStore(dataDir, state);
|
|
98
|
-
if (state.tasks.some((task) => !isTerminal(task.status))) {
|
|
99
|
-
const now = Date.now();
|
|
100
|
-
const recoveryGraceMs = 60_000;
|
|
327
|
+
return true;
|
|
328
|
+
});
|
|
329
|
+
if (tasksToInterrupt.length > 0) {
|
|
101
330
|
await store.transact((draft) => {
|
|
102
|
-
for (const task of draft.tasks)
|
|
103
|
-
if (
|
|
331
|
+
for (const task of draft.tasks) {
|
|
332
|
+
if (isTerminal(task.status))
|
|
333
|
+
continue;
|
|
334
|
+
const shouldInterrupt = options.retainUnleasedQueued
|
|
335
|
+
? task.status === "running" ||
|
|
336
|
+
(task.status === "queued" && (task.leaseToken || task.leaseGeneration !== undefined))
|
|
337
|
+
: true;
|
|
338
|
+
if (shouldInterrupt) {
|
|
104
339
|
task.status = "interrupted";
|
|
105
340
|
task.report = "Hub restarted before execution was confirmed; submit a new turn to retry.";
|
|
106
341
|
task.updatedAt = now;
|
|
107
|
-
if (task.leaseToken) {
|
|
342
|
+
if (task.leaseToken || task.leaseGeneration !== undefined) {
|
|
108
343
|
// Retain recovery grace window for active leases to claim on reconnect!
|
|
109
344
|
task.recoveryUntil = now + recoveryGraceMs;
|
|
110
345
|
}
|
|
111
346
|
}
|
|
347
|
+
}
|
|
112
348
|
});
|
|
113
349
|
}
|
|
114
350
|
return store;
|
|
@@ -132,6 +368,9 @@ export class DeviceHubStore {
|
|
|
132
368
|
}
|
|
133
369
|
async transact(update) {
|
|
134
370
|
const operation = this.tail.then(async () => {
|
|
371
|
+
if (this.wal.isPoisoned()) {
|
|
372
|
+
throw new Error("Store is poisoned due to previous WAL rollback failure; operations halted");
|
|
373
|
+
}
|
|
135
374
|
const draft = structuredClone(this.state);
|
|
136
375
|
const result = update(draft);
|
|
137
376
|
if (result && (typeof result === "object" || typeof result === "function") && "then" in result) {
|
|
@@ -143,8 +382,17 @@ export class DeviceHubStore {
|
|
|
143
382
|
if (typeof reconcileConversationState === "function") {
|
|
144
383
|
reconcileConversationState(this.state, draft);
|
|
145
384
|
}
|
|
146
|
-
|
|
147
|
-
|
|
385
|
+
// Reject uncloneable results before commit and detach returned evidence before any I/O awaits.
|
|
386
|
+
const detachedResult = structuredClone(result);
|
|
387
|
+
// Sequence and diff calculation
|
|
388
|
+
const nextSeq = this.lastSeq + 1;
|
|
389
|
+
const diff = {
|
|
390
|
+
messages: computeCollectionDiff(this.state.messages, draft.messages),
|
|
391
|
+
tasks: computeCollectionDiff(this.state.tasks, draft.tasks),
|
|
392
|
+
conversationMessages: computeCollectionDiff(this.state.conversationMessages, draft.conversationMessages),
|
|
393
|
+
};
|
|
394
|
+
// Keep the public hook before the commit point so tests can inject a pre-commit failure.
|
|
395
|
+
await this.persist(draft, nextSeq, diff);
|
|
148
396
|
for (const listener of this.listeners) {
|
|
149
397
|
try {
|
|
150
398
|
listener();
|
|
@@ -153,32 +401,61 @@ export class DeviceHubStore {
|
|
|
153
401
|
/* notification cannot roll back a committed transaction */
|
|
154
402
|
}
|
|
155
403
|
}
|
|
156
|
-
return
|
|
404
|
+
return detachedResult;
|
|
157
405
|
});
|
|
158
406
|
this.tail = operation.catch(() => { });
|
|
159
407
|
return operation;
|
|
160
408
|
}
|
|
161
|
-
/**
|
|
162
|
-
|
|
163
|
-
|
|
409
|
+
/**
|
|
410
|
+
* Kept as a method so I/O failures can be injected without replacing transaction semantics.
|
|
411
|
+
* WAL append is the commit point. Projection failures retain WAL for retry/recovery and cannot reject a commit.
|
|
412
|
+
*/
|
|
413
|
+
async persist(state, checkpointSeq = this.lastSeq, diff) {
|
|
414
|
+
// Detach accepted evidence before the first asynchronous write. A caller may
|
|
415
|
+
// retain its transaction inputs, but cannot subsequently rewrite durable facts.
|
|
416
|
+
state = structuredClone(state);
|
|
417
|
+
if (diff)
|
|
418
|
+
diff = structuredClone(diff);
|
|
419
|
+
if (this.projectionFailed) {
|
|
420
|
+
this.logs.messages.invalidateCache();
|
|
421
|
+
this.logs.tasks.invalidateCache();
|
|
422
|
+
this.logs.conversationMessages.invalidateCache();
|
|
423
|
+
}
|
|
424
|
+
if (diff) {
|
|
425
|
+
await this.wal.append(checkpointSeq, extractIndexState(state), diff);
|
|
426
|
+
this.state = state;
|
|
427
|
+
this.lastSeq = checkpointSeq;
|
|
428
|
+
}
|
|
164
429
|
try {
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
await file.close();
|
|
172
|
-
}
|
|
173
|
-
await rename(temporary, this.path);
|
|
430
|
+
await this.commitLogs(state);
|
|
431
|
+
await this.persistIndex(state, checkpointSeq);
|
|
432
|
+
await this.wal.checkpoint(checkpointSeq);
|
|
433
|
+
this.checkpointSeq = checkpointSeq;
|
|
434
|
+
this.projectionFailed = false;
|
|
435
|
+
this.lastProjectionError = undefined;
|
|
174
436
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
437
|
+
catch (projectionError) {
|
|
438
|
+
this.projectionFailed = true;
|
|
439
|
+
this.lastProjectionError = projectionError;
|
|
440
|
+
if (!diff)
|
|
441
|
+
throw projectionError;
|
|
180
442
|
}
|
|
181
443
|
}
|
|
444
|
+
async commitLogs(state) {
|
|
445
|
+
const rooms = roomPartitionsOf(state);
|
|
446
|
+
const conversations = new Set(state.conversations.map((conversation) => conversation.id));
|
|
447
|
+
await this.logs.messages.commit(state.messages, rooms);
|
|
448
|
+
await this.logs.tasks.commit(state.tasks, rooms);
|
|
449
|
+
await this.logs.conversationMessages.commit(state.conversationMessages, conversations);
|
|
450
|
+
}
|
|
451
|
+
/** One-time upgrade from Hubs that inlined messages/tasks/transcripts in the index file. */
|
|
452
|
+
async migrateInlineCollections() {
|
|
453
|
+
await this.commitLogs(this.state);
|
|
454
|
+
await this.persistIndex(this.state, this.checkpointSeq);
|
|
455
|
+
}
|
|
456
|
+
async persistIndex(state, checkpointSeq = this.checkpointSeq) {
|
|
457
|
+
await persistIndexTo(this.path, state, checkpointSeq);
|
|
458
|
+
}
|
|
182
459
|
async close() {
|
|
183
460
|
await this.tail;
|
|
184
461
|
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { parseReportMetadata } from "./report-metadata.js";
|
|
3
|
+
import { deviceTaskFailure } from "./task-error.js";
|
|
4
|
+
import { boundTaskReport } from "./task-report.js";
|
|
5
|
+
import { validateDeviceArtifact } from "./work-contract.js";
|
|
6
|
+
export const TASK_OUTCOME_ERROR_BYTES = 4 * 1024;
|
|
7
|
+
export function deepFreeze(obj) {
|
|
8
|
+
if (obj === null || typeof obj !== "object" || Object.isFrozen(obj))
|
|
9
|
+
return obj;
|
|
10
|
+
Object.freeze(obj);
|
|
11
|
+
for (const key of Object.keys(obj)) {
|
|
12
|
+
deepFreeze(obj[key]);
|
|
13
|
+
}
|
|
14
|
+
return obj;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Deterministically compute outcome fingerprint digest (first 16 hex chars of SHA-256).
|
|
18
|
+
* Pure function shared between Hub and Device endpoints to guarantee ACK binding.
|
|
19
|
+
* When artifactDigest or execution/artifact proof facts are provided, they are incorporated
|
|
20
|
+
* into the digest payload while preserving backward-compatibility for legacy 6-tuple payloads.
|
|
21
|
+
*/
|
|
22
|
+
export function computeOutcomeFingerprint(taskId, attemptId, status, report, error, reportMetadata, artifactDigest, executionCompleted, artifactProduced) {
|
|
23
|
+
const hasProofOrArtifact = artifactDigest !== undefined || executionCompleted !== undefined || artifactProduced !== undefined;
|
|
24
|
+
const payload = [
|
|
25
|
+
taskId,
|
|
26
|
+
attemptId,
|
|
27
|
+
status,
|
|
28
|
+
report ?? "",
|
|
29
|
+
error ?? "",
|
|
30
|
+
reportMetadata === undefined ? null : parseReportMetadata(reportMetadata),
|
|
31
|
+
...(hasProofOrArtifact ? [artifactDigest ?? null, executionCompleted ?? null, artifactProduced ?? null] : []),
|
|
32
|
+
];
|
|
33
|
+
return createHash("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 16);
|
|
34
|
+
}
|
|
35
|
+
/** Compatibility for outcomes persisted or sent by older devices. */
|
|
36
|
+
export function computeLegacyOutcomeFingerprint(taskId, attemptId, status, report, error, reportMetadata) {
|
|
37
|
+
return createHash("sha256")
|
|
38
|
+
.update(`${taskId}:${attemptId}:${status}:${report ?? ""}:${error ?? ""}${reportMetadata ? JSON.stringify(reportMetadata) : ""}`)
|
|
39
|
+
.digest("hex")
|
|
40
|
+
.slice(0, 16);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Normalize raw outcome fields (bounding report length, sanitizing error, canonicalizing metadata,
|
|
44
|
+
* validating optional device artifact, and recording independent execution/artifact facts)
|
|
45
|
+
* and generate deterministic fingerprint.
|
|
46
|
+
*/
|
|
47
|
+
export function normalizeTaskOutcome(taskId, attemptId, outcome) {
|
|
48
|
+
const safeReport = outcome.report ? boundTaskReport(outcome.report) : undefined;
|
|
49
|
+
const safeError = outcome.error
|
|
50
|
+
? boundTaskReport(deviceTaskFailure(outcome.error), TASK_OUTCOME_ERROR_BYTES)
|
|
51
|
+
: undefined;
|
|
52
|
+
const reportMetadata = outcome.reportMetadata === undefined ? undefined : parseReportMetadata(outcome.reportMetadata);
|
|
53
|
+
let validArtifact;
|
|
54
|
+
if (outcome.artifact !== undefined) {
|
|
55
|
+
const res = validateDeviceArtifact(outcome.artifact);
|
|
56
|
+
if (!res.valid) {
|
|
57
|
+
throw new Error(`Invalid device artifact: ${res.reason}`);
|
|
58
|
+
}
|
|
59
|
+
// Deep clone and freeze to prevent caller alias mutation from corrupting recorded evidence
|
|
60
|
+
validArtifact = deepFreeze(structuredClone(res.artifact));
|
|
61
|
+
}
|
|
62
|
+
if (outcome.executionCompleted !== undefined && typeof outcome.executionCompleted !== "boolean") {
|
|
63
|
+
throw new Error("Execution proof 'executionCompleted' must be a boolean when present");
|
|
64
|
+
}
|
|
65
|
+
if (outcome.artifactProduced !== undefined && typeof outcome.artifactProduced !== "boolean") {
|
|
66
|
+
throw new Error("Artifact proof 'artifactProduced' must be a boolean when present");
|
|
67
|
+
}
|
|
68
|
+
const executionCompleted = outcome.executionCompleted;
|
|
69
|
+
const artifactProduced = outcome.artifactProduced;
|
|
70
|
+
const fingerprint = computeOutcomeFingerprint(taskId, attemptId, outcome.status, safeReport, safeError, reportMetadata, validArtifact?.digest, executionCompleted, artifactProduced);
|
|
71
|
+
return {
|
|
72
|
+
status: outcome.status,
|
|
73
|
+
report: safeReport,
|
|
74
|
+
error: safeError,
|
|
75
|
+
reportMetadata,
|
|
76
|
+
artifact: validArtifact,
|
|
77
|
+
executionCompleted,
|
|
78
|
+
artifactProduced,
|
|
79
|
+
fingerprint,
|
|
80
|
+
};
|
|
81
|
+
}
|