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.
Files changed (224) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/bin/pi-web-ui.mjs +90 -8
  3. package/dist/gh-comment-781.md +5 -0
  4. package/dist/server/agent-service-daemon.js +522 -32
  5. package/dist/server/agent-service.js +954 -402
  6. package/dist/server/canvas/canvas-dispatch.js +13 -1
  7. package/dist/server/client-state.js +42 -2
  8. package/dist/server/communicate-tool.js +2 -0
  9. package/dist/server/conversation-communication.js +14 -0
  10. package/dist/server/conversation-identity.js +27 -0
  11. package/dist/server/device-center/approval-summary.js +31 -0
  12. package/dist/server/device-center/bot-catalog.js +21 -7
  13. package/dist/server/device-center/bot-execution.js +100 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +362 -13
  16. package/dist/server/device-center/collab-tool.js +824 -13
  17. package/dist/server/device-center/connector.js +359 -23
  18. package/dist/server/device-center/desktop-page.js +22 -16
  19. package/dist/server/device-center/device-integration.js +595 -0
  20. package/dist/server/device-center/execution-guides.js +32 -0
  21. package/dist/server/device-center/execution-instructions.js +20 -0
  22. package/dist/server/device-center/execution-settings.js +213 -0
  23. package/dist/server/device-center/execution-system-prompt.js +38 -0
  24. package/dist/server/device-center/execution-workspace.js +20 -0
  25. package/dist/server/device-center/executor.js +392 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +186 -96
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +210 -0
  30. package/dist/server/device-center/group-context.js +179 -0
  31. package/dist/server/device-center/group-events.js +136 -0
  32. package/dist/server/device-center/group-plan-guard.js +138 -0
  33. package/dist/server/device-center/hub-conversations.js +233 -0
  34. package/dist/server/device-center/hub-deliveries.js +277 -0
  35. package/dist/server/device-center/hub-integration.js +451 -0
  36. package/dist/server/device-center/hub-locks.js +320 -0
  37. package/dist/server/device-center/hub-page.js +13 -33
  38. package/dist/server/device-center/hub-webhooks.js +165 -0
  39. package/dist/server/device-center/hub.js +2379 -107
  40. package/dist/server/device-center/human-interaction.js +232 -0
  41. package/dist/server/device-center/integration-errors.js +25 -0
  42. package/dist/server/device-center/local-hub.js +20 -1
  43. package/dist/server/device-center/local-page.js +17 -0
  44. package/dist/server/device-center/local.js +430 -41
  45. package/dist/server/device-center/main.js +11 -1
  46. package/dist/server/device-center/partition-log.js +293 -0
  47. package/dist/server/device-center/path-portal.js +11 -3
  48. package/dist/server/device-center/relay.js +364 -35
  49. package/dist/server/device-center/report-metadata.js +66 -0
  50. package/dist/server/device-center/report-upload.js +63 -0
  51. package/dist/server/device-center/runtime.js +598 -41
  52. package/dist/server/device-center/smoke-preview.js +3 -0
  53. package/dist/server/device-center/store.js +203 -41
  54. package/dist/server/device-center/task-context-budget.js +161 -0
  55. package/dist/server/device-center/task-journal.js +385 -0
  56. package/dist/server/device-center/task-plan.js +33 -0
  57. package/dist/server/device-center/task-progress.js +141 -0
  58. package/dist/server/device-center/task-recovery.js +452 -0
  59. package/dist/server/device-center/task-report-outbox.js +216 -0
  60. package/dist/server/device-center/task-report.js +384 -0
  61. package/dist/server/device-center/task-scheduler.js +445 -0
  62. package/dist/server/device-center/task-state.js +333 -0
  63. package/dist/server/device-center/transfer-stream.js +1006 -0
  64. package/dist/server/device-center/transfers.js +841 -8
  65. package/dist/server/dispatch-domain-handlers.js +35 -6
  66. package/dist/server/dsh/dsh-agent-service.js +6 -0
  67. package/dist/server/durable/durable-capabilities.js +11 -0
  68. package/dist/server/engine-probe.js +112 -1
  69. package/dist/server/global-loader.js +119 -19
  70. package/dist/server/goal-service.js +10 -5
  71. package/dist/server/index.js +222 -29
  72. package/dist/server/managed.js +2 -0
  73. package/dist/server/markers/builtins/services.js +123 -0
  74. package/dist/server/markers/builtins/todo.js +189 -0
  75. package/dist/server/markers-list-tool.js +34 -0
  76. package/dist/server/message-deletion.js +40 -0
  77. package/dist/server/message-window.js +9 -0
  78. package/dist/server/model-admin.js +48 -6
  79. package/dist/server/model-enrich.js +10 -1
  80. package/dist/server/orchestrator.js +109 -0
  81. package/dist/server/patch-executable-lookup.js +396 -0
  82. package/dist/server/payload-limits.js +2 -0
  83. package/dist/server/plugin-llm.js +100 -9
  84. package/dist/server/plugins.js +65 -7
  85. package/dist/server/preset-fields.js +24 -0
  86. package/dist/server/preset-share.js +2 -0
  87. package/dist/server/prompt-base-store.js +85 -0
  88. package/dist/server/prompt-composer.js +44 -2
  89. package/dist/server/protocol-version.js +1 -1
  90. package/dist/server/protocol.js +2 -2
  91. package/dist/server/reasoning-registry.js +207 -0
  92. package/dist/server/remote-ssh-service.js +22 -9
  93. package/dist/server/resolve-global-sdk.js +2 -0
  94. package/dist/server/session-search.js +1 -1
  95. package/dist/server/settings-service.js +90 -39
  96. package/dist/server/skill-content-filler.js +29 -8
  97. package/dist/server/skill-tool.js +12 -3
  98. package/dist/server/startup-banner.js +35 -0
  99. package/dist/server/subagent-helpers.js +4 -1
  100. package/dist/server/subagents.js +52 -37
  101. package/dist/server/system-prompt-soul.js +41 -0
  102. package/dist/server/tool-host-factories.js +1 -0
  103. package/dist/server/tool-manager.js +17 -9
  104. package/dist/server/unauthorized-page.js +319 -0
  105. package/dist/server/univer-service.js +448 -0
  106. package/dist/server/universal/drivers/dsh-driver.js +379 -0
  107. package/dist/server/universal/universal-session.js +5 -0
  108. package/dist/server/webui-context.js +25 -5
  109. package/dist/test-artifact.md +9 -0
  110. package/dist/test-preview-modal.md +11 -0
  111. package/dist/test-report.html +20 -0
  112. package/docs/README.md +94 -0
  113. package/docs/architecture-plugins.md +946 -0
  114. package/docs/device-center.md +106 -12
  115. package/docs/dsh-engine.md +10 -10
  116. package/extensions/webui.ts +43 -1
  117. package/package.json +2 -1
  118. package/themes/aetheris.css +5 -0
  119. package/themes/ayu-light.css +6 -0
  120. package/themes/bases/flow-base.css +68 -68
  121. package/themes/catppuccin-latte.css +6 -0
  122. package/themes/catppuccin.css +6 -0
  123. package/themes/claude-code-dark.css +5 -0
  124. package/themes/codex.css +6 -0
  125. package/themes/cyberpunk.css +6 -0
  126. package/themes/dark-teal.css +6 -1
  127. package/themes/dazzle.css +6 -0
  128. package/themes/everforest-light.css +6 -0
  129. package/themes/flow-light.css +8 -1
  130. package/themes/flow.css +6 -1
  131. package/themes/geist.css +6 -0
  132. package/themes/gruvbox-light.css +6 -0
  133. package/themes/kanagawa-lotus.css +6 -0
  134. package/themes/md-preview.css +6 -0
  135. package/themes/mist.css +6 -0
  136. package/themes/nord.css +6 -0
  137. package/themes/one-dark.css +6 -0
  138. package/themes/paper.css +6 -0
  139. package/themes/rose-pine-dawn.css +6 -0
  140. package/themes/sakura.css +6 -0
  141. package/themes/solarized-light.css +6 -0
  142. package/themes/tokyo-night.css +6 -0
  143. package/themes/translucent.css +6 -0
  144. package/themes/transparent.css +6 -0
  145. package/themes/vs-code-dark.css +5 -0
  146. package/themes/wallpaper-flow.css +5 -1
  147. package/themes/wallpaper-obsidian.css +6 -0
  148. package/themes/white.css +6 -0
  149. package/themes/zhujian-dark.css +6 -1
  150. package/themes/zhujian.css +6 -1
  151. package/themes/zhupi-dark.css +6 -1
  152. package/themes/zhupi.css +6 -1
  153. package/web/dist/.build-assets.json +1 -1
  154. package/web/dist/assets/BgTasksModal-BDoOpj-F.js +1 -0
  155. package/web/dist/assets/BgTasksModal-C0i3O1FT.js +1 -0
  156. package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-B8thymBN.js} +3 -3
  157. package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-zSxyIx1R.js} +3 -3
  158. package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
  159. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
  160. package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
  161. package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
  162. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
  163. package/web/dist/assets/Dropdown-C4LIhshN.js +1 -0
  164. package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
  165. package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
  166. package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +1 -0
  167. package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +1 -0
  168. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
  169. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
  170. package/web/dist/assets/HintTip-c6d0TJoh.js +1 -0
  171. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
  172. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
  173. package/web/dist/assets/PiSetupModal-BmMrrgB9.js +1 -0
  174. package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +1 -0
  175. package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
  176. package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
  177. package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
  178. package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
  179. package/web/dist/assets/TerminalPanel-0CYvD72B.js +3 -0
  180. package/web/dist/assets/TerminalPanel-DDavKvFr.js +3 -0
  181. package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +1 -0
  182. package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +1 -0
  183. package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
  184. package/web/dist/assets/canvas-client-CUnXlQYX.js +1 -0
  185. package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-aAKpvKJV.js} +1 -1
  186. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  187. package/web/dist/assets/index-C6DwztqE.css +1 -0
  188. package/web/dist/assets/index-CuN802Sj.js +93 -0
  189. package/web/dist/assets/index-EH5Fw9fa.js +93 -0
  190. package/web/dist/assets/plugin-host-BRWib9DF.js +1 -0
  191. package/web/dist/assets/remote-ssh-client-CfYSMEZg.js +1 -0
  192. package/web/dist/assets/theme-D2l_mLNo.js +1 -0
  193. package/web/dist/index.html +10 -9
  194. package/web/dist/sw.js +1 -1
  195. package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
  196. package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
  197. package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
  198. package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
  199. package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
  200. package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
  201. package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
  202. package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
  203. package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
  204. package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
  205. package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
  206. package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
  207. package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
  208. package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
  209. package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
  210. package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
  211. package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
  212. package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
  213. package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
  214. package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
  215. package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
  216. package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
  217. package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
  218. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  219. package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
  220. package/web/dist/assets/index-DK3F5ZJo.js +0 -85
  221. package/web/dist/assets/index-DQMii2he.js +0 -85
  222. package/web/dist/assets/index-vwBnwzkr.css +0 -1
  223. package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
  224. package/web/dist/assets/theme-D2DMH6tH.js +0 -1
@@ -0,0 +1,3 @@
1
+ // Temporary local preview runner; removed after browser validation.
2
+ import { startDeviceHub } from "./main.js";
3
+ await startDeviceHub({ ...process.env, PI_DEVICE_HUB_PUBLIC_URL: "http://127.0.0.1:18970", PI_DEVICE_HUB_DEVICE_DOMAIN: "devices.localhost:18970", PI_DEVICE_HUB_PORT: "18970", PI_DEVICE_HUB_DATA_DIR: process.env.TEMP + "/pi-device-hub-browser-preview", PI_DEVICE_HUB_ALLOW_REGISTRATION: "1" });
@@ -1,6 +1,9 @@
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";
3
4
  import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
5
+ import { projectConversationState, reconcileConversationState, } from "./task-state.js";
6
+ export const taskPending = (task) => !isTerminal(task.status) || !!(task.cancelRequested && !task.stopConfirmed);
4
7
  export const isTerminal = (status) => ["completed", "failed", "interrupted"].includes(status);
5
8
  export const hashSecret = (secret) => createHash("sha256").update(secret).digest("hex");
6
9
  export function secretMatches(secret, hash) {
@@ -12,56 +15,178 @@ export function publicDevice(device) {
12
15
  const { credentialHash: _hash, uiCredentialHash: _uiHash, ...visible } = device;
13
16
  return visible;
14
17
  }
15
- /** A single process owns a data directory. Transactions publish only after atomic replacement. */
18
+ export function publicTask(task) {
19
+ const { leaseToken: _token, ...visible } = task;
20
+ return visible;
21
+ }
22
+ /** Rows kept per room when replaying append logs; mirrors the group retention the Hub enforces. */
23
+ export const HUB_LOG_RETENTION = 500;
24
+ function createHubLogs(dataDir) {
25
+ const root = join(dataDir, "hub-log");
26
+ return {
27
+ messages: new PartitionedAppendLog({
28
+ dir: join(root, "messages"),
29
+ partition: (message) => message.roomId,
30
+ id: (message) => message.id,
31
+ retention: HUB_LOG_RETENTION,
32
+ }),
33
+ tasks: new PartitionedAppendLog({
34
+ dir: join(root, "tasks"),
35
+ partition: (task) => task.roomId,
36
+ id: (task) => task.id,
37
+ retention: HUB_LOG_RETENTION,
38
+ // Load-time retention must never drop work that is still queued, running or awaiting a stop.
39
+ protect: (task) => taskPending(task),
40
+ }),
41
+ conversationMessages: new PartitionedAppendLog({
42
+ dir: join(root, "conversation-messages"),
43
+ partition: (message) => message.conversationId,
44
+ id: (message) => message.id,
45
+ }),
46
+ };
47
+ }
48
+ function emptyHubState() {
49
+ return {
50
+ version: 2,
51
+ conversations: [],
52
+ conversationMessages: [],
53
+ deliveries: [],
54
+ reviews: [],
55
+ deliveryReceipts: [],
56
+ integrations: [],
57
+ accounts: [],
58
+ devices: [],
59
+ bots: [],
60
+ sessions: [],
61
+ rooms: [],
62
+ messages: [],
63
+ tasks: [],
64
+ receipts: [],
65
+ };
66
+ }
67
+ /** Tasks/messages are partitioned by room; conversations may reference a room row that no longer exists. */
68
+ function roomPartitionsOf(state) {
69
+ return new Set([
70
+ ...state.rooms.map((room) => room.id),
71
+ ...state.conversations.map((conversation) => conversation.roomId),
72
+ ]);
73
+ }
74
+ /** Merge log rows with rows still inlined by an older Hub; inline rows win (they are the older baseline). */
75
+ function mergeRows(stored, inline) {
76
+ if (!inline.length)
77
+ return [...stored];
78
+ if (!stored.length)
79
+ return [...inline];
80
+ const merged = new Map();
81
+ for (const row of inline)
82
+ merged.set(row.id, row);
83
+ for (const row of stored)
84
+ if (!merged.has(row.id))
85
+ merged.set(row.id, row);
86
+ return [...merged.values()];
87
+ }
88
+ async function loadHubFiles(dataDir, options = {}) {
89
+ await mkdir(dataDir, { recursive: true, mode: 0o700 });
90
+ let state;
91
+ try {
92
+ state = JSON.parse(await readFile(join(dataDir, "device-hub.json"), "utf8"));
93
+ if (state.version !== 2 ||
94
+ ![
95
+ state.accounts,
96
+ state.devices,
97
+ state.bots,
98
+ state.sessions,
99
+ state.rooms,
100
+ state.messages,
101
+ state.tasks,
102
+ state.receipts,
103
+ ].every(Array.isArray)) {
104
+ throw new Error("Invalid device hub store");
105
+ }
106
+ }
107
+ catch (error) {
108
+ if (error.code !== "ENOENT")
109
+ throw error;
110
+ state = emptyHubState();
111
+ }
112
+ state.conversations ??= [];
113
+ state.conversationMessages ??= [];
114
+ state.deliveries ??= [];
115
+ state.reviews ??= [];
116
+ state.deliveryReceipts ??= [];
117
+ state.integrations ??= [];
118
+ if (![
119
+ state.conversations,
120
+ state.conversationMessages,
121
+ state.deliveries,
122
+ state.reviews,
123
+ state.deliveryReceipts,
124
+ state.integrations,
125
+ ].every(Array.isArray))
126
+ throw new Error("Invalid conversation store");
127
+ const logs = createHubLogs(dataDir);
128
+ const roomPartitions = roomPartitionsOf(state);
129
+ const conversations = new Set(state.conversations.map((conversation) => conversation.id));
130
+ // Logs are the authority; inline rows only exist in files written before the split (or by an older Hub).
131
+ const storedMessages = await logs.messages.load(roomPartitions, options);
132
+ const storedTasks = await logs.tasks.load(roomPartitions, options);
133
+ const storedConversationMessages = await logs.conversationMessages.load(conversations, options);
134
+ const legacy = state.messages.length > 0 || state.tasks.length > 0 || state.conversationMessages.length > 0;
135
+ state.messages = mergeRows(storedMessages, state.messages);
136
+ state.tasks = mergeRows(storedTasks, state.tasks);
137
+ state.conversationMessages = mergeRows(storedConversationMessages, state.conversationMessages);
138
+ // Legacy state is a baseline, not evidence that historical transitions were observed.
139
+ for (const conversation of state.conversations) {
140
+ conversation.taskState = projectConversationState(state, conversation);
141
+ conversation.events ??= [];
142
+ }
143
+ return { state, logs, legacy };
144
+ }
145
+ /** Read the durable state without open() side effects (no interrupt marking); used by tests and tooling. */
146
+ export async function readPersistedHub(dataDir) {
147
+ // Read-only: never sweep orphan files or repair tails from an inspection path.
148
+ return (await loadHubFiles(dataDir, { sweep: false })).state;
149
+ }
150
+ /** A single process owns a data directory. Transactions publish only after the index replacement. */
16
151
  export class DeviceHubStore {
17
152
  state;
153
+ listeners = new Set();
154
+ subscribe(listener) {
155
+ this.listeners.add(listener);
156
+ return () => {
157
+ this.listeners.delete(listener);
158
+ };
159
+ }
18
160
  tail = Promise.resolve();
19
161
  path;
20
- constructor(dataDir, state) {
162
+ logs;
163
+ logDir;
164
+ constructor(dataDir, state, logs) {
21
165
  this.path = join(dataDir, "device-hub.json");
166
+ this.logDir = join(dataDir, "hub-log");
22
167
  this.state = state;
168
+ this.logs = logs;
23
169
  }
24
170
  static async open(dataDir) {
25
- await mkdir(dataDir, { recursive: true, mode: 0o700 });
26
- let state;
27
- try {
28
- state = JSON.parse(await readFile(join(dataDir, "device-hub.json"), "utf8"));
29
- if (state.version !== 2 ||
30
- ![
31
- state.accounts,
32
- state.devices,
33
- state.bots,
34
- state.sessions,
35
- state.rooms,
36
- state.messages,
37
- state.tasks,
38
- state.receipts,
39
- ].every(Array.isArray)) {
40
- throw new Error("Invalid device hub store");
41
- }
42
- }
43
- catch (error) {
44
- if (error.code !== "ENOENT")
45
- throw error;
46
- state = {
47
- version: 2,
48
- accounts: [],
49
- devices: [],
50
- bots: [],
51
- sessions: [],
52
- rooms: [],
53
- messages: [],
54
- tasks: [],
55
- receipts: [],
56
- };
57
- }
58
- const store = new DeviceHubStore(dataDir, state);
59
- if (state.tasks.some((task) => task.status === "running")) {
171
+ const { state, logs, legacy } = await loadHubFiles(dataDir);
172
+ const store = new DeviceHubStore(dataDir, state, logs);
173
+ // Move collections that older Hubs kept inline into their append logs. Logs are written first so
174
+ // an interrupted migration can be retried from the still-inline index without losing rows.
175
+ if (legacy)
176
+ await store.migrateInlineCollections();
177
+ if (state.tasks.some((task) => !isTerminal(task.status))) {
178
+ const now = Date.now();
179
+ const recoveryGraceMs = 60_000;
60
180
  await store.transact((draft) => {
61
181
  for (const task of draft.tasks)
62
- if (task.status === "running") {
182
+ if (!isTerminal(task.status)) {
63
183
  task.status = "interrupted";
64
- task.updatedAt = Date.now();
184
+ task.report = "Hub restarted before execution was confirmed; submit a new turn to retry.";
185
+ task.updatedAt = now;
186
+ if (task.leaseToken) {
187
+ // Retain recovery grace window for active leases to claim on reconnect!
188
+ task.recoveryUntil = now + recoveryGraceMs;
189
+ }
65
190
  }
66
191
  });
67
192
  }
@@ -88,20 +213,57 @@ export class DeviceHubStore {
88
213
  const operation = this.tail.then(async () => {
89
214
  const draft = structuredClone(this.state);
90
215
  const result = update(draft);
216
+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result) {
217
+ // Transactions only reserve/commit state. External work runs between transactions.
218
+ // Drain a rejected accidental async callback without publishing its detached draft.
219
+ void Promise.resolve(result).catch(() => { });
220
+ throw new Error("Hub transactions require a synchronous update");
221
+ }
222
+ if (typeof reconcileConversationState === "function") {
223
+ reconcileConversationState(this.state, draft);
224
+ }
91
225
  await this.persist(draft);
92
226
  this.state = draft;
227
+ for (const listener of this.listeners) {
228
+ try {
229
+ listener();
230
+ }
231
+ catch {
232
+ /* notification cannot roll back a committed transaction */
233
+ }
234
+ }
93
235
  return structuredClone(result);
94
236
  });
95
237
  this.tail = operation.catch(() => { });
96
238
  return operation;
97
239
  }
98
- /** Kept as a method so I/O failures can be injected without replacing transaction semantics. */
240
+ /**
241
+ * Kept as a method so I/O failures can be injected without replacing transaction semantics.
242
+ * The index is replaced first, then the append logs: a log row always describes durable index state.
243
+ */
99
244
  async persist(state) {
245
+ await this.persistIndex(state);
246
+ await this.commitLogs(state);
247
+ }
248
+ async commitLogs(state) {
249
+ const rooms = roomPartitionsOf(state);
250
+ const conversations = new Set(state.conversations.map((conversation) => conversation.id));
251
+ await this.logs.messages.commit(state.messages, rooms);
252
+ await this.logs.tasks.commit(state.tasks, rooms);
253
+ await this.logs.conversationMessages.commit(state.conversationMessages, conversations);
254
+ }
255
+ /** One-time upgrade from Hubs that inlined messages/tasks/transcripts in the index file. */
256
+ async migrateInlineCollections() {
257
+ await this.commitLogs(this.state);
258
+ await this.persistIndex(this.state);
259
+ }
260
+ async persistIndex(state) {
100
261
  const temporary = `${this.path}.${randomUUID()}.tmp`;
262
+ const index = { ...state, messages: [], tasks: [], conversationMessages: [] };
101
263
  try {
102
264
  const file = await open(temporary, "wx", 0o600);
103
265
  try {
104
- await file.writeFile(JSON.stringify(state));
266
+ await file.writeFile(JSON.stringify(index));
105
267
  await file.sync();
106
268
  }
107
269
  finally {
@@ -0,0 +1,161 @@
1
+ /** Select optional reference data only. Current task text, handoff and runtime state never pass through here. */
2
+ export function selectTaskContext(source, budget = 12 * 1024) {
3
+ if (!Number.isSafeInteger(budget) || budget < 0)
4
+ throw new RangeError("Task context budget must be a nonnegative safe integer");
5
+ const state = {
6
+ revision: source.revision,
7
+ objective: source.objective,
8
+ currentTaskId: source.currentTaskId,
9
+ phase: source.phase,
10
+ ...(source.blocker
11
+ ? {
12
+ blocker: {
13
+ attentionId: source.blocker.attentionId,
14
+ taskId: source.blocker.taskId,
15
+ question: source.blocker.question,
16
+ },
17
+ }
18
+ : {}),
19
+ decisions: [],
20
+ artifacts: [],
21
+ };
22
+ const selection = {
23
+ budgetBytes: budget,
24
+ bytes: 0,
25
+ overflow: 0,
26
+ omitted: {
27
+ decisions: source.decisions.length,
28
+ artifacts: source.artifacts.length,
29
+ latestRequest: Number(!!source.latestRequest),
30
+ lastOutcome: Number(!!source.lastOutcome),
31
+ reported: Number(!!source.reported),
32
+ reportedConstraints: source.reported?.constraints.length ?? 0,
33
+ reportedProgress: Number(!!source.reported?.progress),
34
+ reportedBlockers: source.reported?.blockers.length ?? 0,
35
+ reportedNextSteps: source.reported?.nextSteps.length ?? 0,
36
+ },
37
+ textTruncated: {
38
+ objective: false,
39
+ blocker: false,
40
+ decisionQuestions: source.decisions.filter((d) => d.questionTruncated).length,
41
+ decisionAnswers: source.decisions.filter((d) => d.answerTruncated).length,
42
+ },
43
+ lookup: "Optional reference snapshot. Use device_collab task_state for full canonical state, omitted constraints/decisions and current revision before acting.",
44
+ };
45
+ const measure = () => {
46
+ // bytes counts itself, so settle its decimal width before comparing the budget.
47
+ let bytes;
48
+ do {
49
+ bytes = selection.bytes;
50
+ selection.bytes = Buffer.byteLength(JSON.stringify({ taskState: state, taskStateSelection: selection }), "utf8");
51
+ } while (bytes !== selection.bytes);
52
+ };
53
+ measure();
54
+ if (selection.bytes > budget) {
55
+ selection.overflow = 1;
56
+ measure();
57
+ return { state, selection };
58
+ }
59
+ const admit = (apply, undo) => {
60
+ apply();
61
+ measure();
62
+ if (selection.bytes <= budget)
63
+ return true;
64
+ undo();
65
+ measure();
66
+ return false;
67
+ };
68
+ // Newest human decisions first; each question/answer pair is indivisible.
69
+ for (const d of [...source.decisions].reverse()) {
70
+ const decision = {
71
+ attentionId: d.attentionId,
72
+ messageId: d.messageId,
73
+ taskId: d.taskId,
74
+ ...(d.question !== undefined ? { question: d.question } : {}),
75
+ ...(d.answer !== undefined ? { answer: d.answer } : {}),
76
+ ...(d.questionTruncated !== undefined ? { questionTruncated: d.questionTruncated } : {}),
77
+ ...(d.answerTruncated !== undefined ? { answerTruncated: d.answerTruncated } : {}),
78
+ };
79
+ admit(() => {
80
+ state.decisions.unshift(decision);
81
+ selection.omitted.decisions--;
82
+ }, () => {
83
+ state.decisions.shift();
84
+ selection.omitted.decisions++;
85
+ });
86
+ }
87
+ const report = source.reported;
88
+ if (report) {
89
+ const included = admit(() => {
90
+ state.reported = {
91
+ taskId: report.taskId,
92
+ botId: report.botId,
93
+ updatedAt: report.updatedAt,
94
+ provenance: report.provenance,
95
+ constraints: [],
96
+ progress: "",
97
+ blockers: [],
98
+ nextSteps: [],
99
+ };
100
+ selection.omitted.reported--;
101
+ }, () => {
102
+ delete state.reported;
103
+ selection.omitted.reported++;
104
+ });
105
+ if (included) {
106
+ const selected = state.reported;
107
+ for (const key of ["constraints", "blockers", "nextSteps"]) {
108
+ const count = {
109
+ constraints: "reportedConstraints",
110
+ blockers: "reportedBlockers",
111
+ nextSteps: "reportedNextSteps",
112
+ }[key];
113
+ for (const text of report[key])
114
+ admit(() => {
115
+ selected[key].push(text);
116
+ selection.omitted[count]--;
117
+ }, () => {
118
+ selected[key].pop();
119
+ selection.omitted[count]++;
120
+ });
121
+ }
122
+ if (report.progress)
123
+ admit(() => {
124
+ selected.progress = report.progress;
125
+ selection.omitted.reportedProgress--;
126
+ }, () => {
127
+ selected.progress = "";
128
+ selection.omitted.reportedProgress++;
129
+ });
130
+ }
131
+ }
132
+ if (source.latestRequest) {
133
+ const { taskId, sourceId, text } = source.latestRequest;
134
+ admit(() => {
135
+ state.latestRequest = { taskId, sourceId, text };
136
+ selection.omitted.latestRequest--;
137
+ }, () => {
138
+ delete state.latestRequest;
139
+ selection.omitted.latestRequest++;
140
+ });
141
+ }
142
+ if (source.lastOutcome) {
143
+ const { taskId, status, text } = source.lastOutcome;
144
+ admit(() => {
145
+ state.lastOutcome = { taskId, status, ...(text !== undefined ? { text } : {}) };
146
+ selection.omitted.lastOutcome--;
147
+ }, () => {
148
+ delete state.lastOutcome;
149
+ selection.omitted.lastOutcome++;
150
+ });
151
+ }
152
+ for (const { deliveryId, taskId } of source.artifacts)
153
+ admit(() => {
154
+ state.artifacts.push({ deliveryId, taskId });
155
+ selection.omitted.artifacts--;
156
+ }, () => {
157
+ state.artifacts.pop();
158
+ selection.omitted.artifacts++;
159
+ });
160
+ return { state, selection };
161
+ }