pi-web-ui 0.114.3 → 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.
Files changed (194) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/bin/pi-web-ui.mjs +69 -7
  3. package/dist/server/agent-service-daemon.js +440 -32
  4. package/dist/server/agent-service.js +849 -378
  5. package/dist/server/canvas/canvas-dispatch.js +13 -1
  6. package/dist/server/client-state.js +25 -0
  7. package/dist/server/communicate-tool.js +2 -0
  8. package/dist/server/conversation-communication.js +14 -0
  9. package/dist/server/conversation-identity.js +27 -0
  10. package/dist/server/device-center/approval-summary.js +31 -0
  11. package/dist/server/device-center/bot-catalog.js +21 -7
  12. package/dist/server/device-center/bot-execution.js +72 -9
  13. package/dist/server/device-center/bot-presets.js +46 -0
  14. package/dist/server/device-center/collab-service.js +328 -10
  15. package/dist/server/device-center/collab-tool.js +738 -12
  16. package/dist/server/device-center/connector.js +359 -23
  17. package/dist/server/device-center/desktop-page.js +22 -16
  18. package/dist/server/device-center/device-integration.js +595 -0
  19. package/dist/server/device-center/execution-guides.js +32 -0
  20. package/dist/server/device-center/execution-instructions.js +19 -0
  21. package/dist/server/device-center/execution-settings.js +100 -0
  22. package/dist/server/device-center/execution-system-prompt.js +38 -0
  23. package/dist/server/device-center/execution-workspace.js +20 -0
  24. package/dist/server/device-center/executor.js +389 -40
  25. package/dist/server/device-center/file-sync-paths.js +171 -0
  26. package/dist/server/device-center/file-sync.js +180 -91
  27. package/dist/server/device-center/group-context-delta.js +37 -0
  28. package/dist/server/device-center/group-context-message.js +208 -0
  29. package/dist/server/device-center/group-context.js +109 -0
  30. package/dist/server/device-center/group-events.js +136 -0
  31. package/dist/server/device-center/group-plan-guard.js +138 -0
  32. package/dist/server/device-center/hub-conversations.js +178 -0
  33. package/dist/server/device-center/hub-deliveries.js +277 -0
  34. package/dist/server/device-center/hub-integration.js +451 -0
  35. package/dist/server/device-center/hub.js +1544 -80
  36. package/dist/server/device-center/human-interaction.js +232 -0
  37. package/dist/server/device-center/integration-errors.js +25 -0
  38. package/dist/server/device-center/local-hub.js +18 -0
  39. package/dist/server/device-center/local.js +356 -40
  40. package/dist/server/device-center/main.js +11 -1
  41. package/dist/server/device-center/path-portal.js +11 -3
  42. package/dist/server/device-center/relay.js +364 -35
  43. package/dist/server/device-center/report-metadata.js +66 -0
  44. package/dist/server/device-center/report-upload.js +63 -0
  45. package/dist/server/device-center/runtime.js +549 -41
  46. package/dist/server/device-center/store.js +66 -3
  47. package/dist/server/device-center/task-context-budget.js +161 -0
  48. package/dist/server/device-center/task-journal.js +385 -0
  49. package/dist/server/device-center/task-plan.js +33 -0
  50. package/dist/server/device-center/task-progress.js +141 -0
  51. package/dist/server/device-center/task-recovery.js +452 -0
  52. package/dist/server/device-center/task-report-outbox.js +216 -0
  53. package/dist/server/device-center/task-report.js +384 -0
  54. package/dist/server/device-center/task-scheduler.js +400 -0
  55. package/dist/server/device-center/task-state.js +333 -0
  56. package/dist/server/device-center/transfer-stream.js +1006 -0
  57. package/dist/server/device-center/transfers.js +815 -8
  58. package/dist/server/dispatch-domain-handlers.js +21 -3
  59. package/dist/server/dsh/dsh-agent-service.js +6 -0
  60. package/dist/server/goal-service.js +10 -5
  61. package/dist/server/index.js +89 -13
  62. package/dist/server/message-deletion.js +40 -0
  63. package/dist/server/message-window.js +9 -0
  64. package/dist/server/patch-executable-lookup.js +396 -0
  65. package/dist/server/payload-limits.js +2 -0
  66. package/dist/server/plugin-llm.js +100 -9
  67. package/dist/server/plugins.js +1 -0
  68. package/dist/server/preset-fields.js +24 -0
  69. package/dist/server/preset-share.js +2 -0
  70. package/dist/server/prompt-base-store.js +85 -0
  71. package/dist/server/prompt-composer.js +5 -2
  72. package/dist/server/protocol-version.js +1 -1
  73. package/dist/server/protocol.js +2 -2
  74. package/dist/server/remote-ssh-service.js +22 -9
  75. package/dist/server/resolve-global-sdk.js +2 -0
  76. package/dist/server/session-search.js +1 -1
  77. package/dist/server/settings-service.js +90 -39
  78. package/dist/server/skill-content-filler.js +29 -8
  79. package/dist/server/skill-tool.js +12 -3
  80. package/dist/server/subagent-helpers.js +4 -1
  81. package/dist/server/subagents.js +50 -36
  82. package/dist/server/tool-host-factories.js +1 -0
  83. package/dist/server/universal/universal-session.js +5 -0
  84. package/dist/server/webui-context.js +25 -5
  85. package/docs/README.md +94 -0
  86. package/docs/device-center.md +100 -12
  87. package/docs/dsh-engine.md +10 -10
  88. package/extensions/webui.ts +43 -1
  89. package/package.json +1 -1
  90. package/themes/aetheris.css +5 -0
  91. package/themes/ayu-light.css +6 -0
  92. package/themes/bases/flow-base.css +68 -68
  93. package/themes/catppuccin-latte.css +6 -0
  94. package/themes/catppuccin.css +6 -0
  95. package/themes/claude-code-dark.css +5 -0
  96. package/themes/codex.css +6 -0
  97. package/themes/cyberpunk.css +6 -0
  98. package/themes/dark-teal.css +6 -1
  99. package/themes/dazzle.css +6 -0
  100. package/themes/everforest-light.css +6 -0
  101. package/themes/flow-light.css +8 -1
  102. package/themes/flow.css +6 -1
  103. package/themes/geist.css +6 -0
  104. package/themes/gruvbox-light.css +6 -0
  105. package/themes/kanagawa-lotus.css +6 -0
  106. package/themes/md-preview.css +6 -0
  107. package/themes/mist.css +6 -0
  108. package/themes/nord.css +6 -0
  109. package/themes/one-dark.css +6 -0
  110. package/themes/paper.css +6 -0
  111. package/themes/rose-pine-dawn.css +6 -0
  112. package/themes/sakura.css +6 -0
  113. package/themes/solarized-light.css +6 -0
  114. package/themes/tokyo-night.css +6 -0
  115. package/themes/translucent.css +6 -0
  116. package/themes/transparent.css +6 -0
  117. package/themes/vs-code-dark.css +5 -0
  118. package/themes/wallpaper-flow.css +5 -1
  119. package/themes/wallpaper-obsidian.css +6 -0
  120. package/themes/white.css +6 -0
  121. package/themes/zhujian-dark.css +6 -1
  122. package/themes/zhujian.css +6 -1
  123. package/themes/zhupi-dark.css +6 -1
  124. package/themes/zhupi.css +6 -1
  125. package/web/dist/.build-assets.json +1 -1
  126. package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
  127. package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
  128. package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-BCUeEf25.js} +3 -3
  129. package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-DNmDNBod.js} +3 -3
  130. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
  131. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
  132. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
  133. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
  134. package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
  135. package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
  136. package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
  137. package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
  138. package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
  139. package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
  140. package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
  141. package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
  142. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
  143. package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
  144. package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
  145. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
  146. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
  147. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
  148. package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
  149. package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
  150. package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
  151. package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
  152. package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
  153. package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
  154. package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
  155. package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-kjBoE3Nu.js} +1 -1
  156. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  157. package/web/dist/assets/index-CsFs_HMb.css +1 -0
  158. package/web/dist/assets/index-DHeeHS_l.js +85 -0
  159. package/web/dist/assets/index-DTZch8uz.js +85 -0
  160. package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
  161. package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
  162. package/web/dist/assets/theme-BXGpyTMh.js +1 -0
  163. package/web/dist/index.html +10 -9
  164. package/web/dist/sw.js +1 -1
  165. package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
  166. package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
  167. package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
  168. package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
  169. package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
  170. package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
  171. package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
  172. package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
  173. package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
  174. package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
  175. package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
  176. package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
  177. package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
  178. package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
  179. package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
  180. package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
  181. package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
  182. package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
  183. package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
  184. package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
  185. package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
  186. package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
  187. package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
  188. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  189. package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
  190. package/web/dist/assets/index-DK3F5ZJo.js +0 -85
  191. package/web/dist/assets/index-DQMii2he.js +0 -85
  192. package/web/dist/assets/index-vwBnwzkr.css +0 -1
  193. package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
  194. package/web/dist/assets/theme-D2DMH6tH.js +0 -1
@@ -1,8 +1,21 @@
1
1
  import express from "express";
2
+ import { validInteractionAnswer, validInteractionProjection } from "./human-interaction.js";
3
+ import { createGroupEvents } from "./group-events.js";
4
+ import { createTaskJournalManager } from "./task-journal.js";
5
+ import { createTaskReportStore, MAX_TASK_FULL_REPORT_BYTES } from "./task-report.js";
6
+ import { TASK_REPORT_UPLOAD_JSON_BYTES } from "../payload-limits.js";
7
+ import { parseReportMetadata, mergeTaskReportMetadata, reportUploadMetadata } from "./report-metadata.js";
8
+ import { buildDeterministicTaskSummary, queryTaskReportChunk } from "./task-state.js";
9
+ import { addDelivery, addReview, deliveryHistory, deliverySummary } from "./hub-deliveries.js";
10
+ import { hubPrepareIntegration, hubVerifyIntegration, hubConfirmIntegration, hubCancelIntegration, listIntegrations, } from "./hub-integration.js";
2
11
  import { createServer } from "node:http";
3
12
  import { randomBytes, randomUUID } from "node:crypto";
4
- import { DeviceHubStore, hashSecret, isTerminal, publicDevice, secretMatches } from "./store.js";
13
+ import { DeviceHubStore, hashSecret, isTerminal, taskPending, publicDevice, publicTask, secretMatches, } from "./store.js";
14
+ import { atomicApproveGroupPlan } from "./group-plan-guard.js";
15
+ import { validateTaskPlan } from "./task-plan.js";
16
+ import { GROUP_RETENTION_LIMIT, groupHistoryPage, groupTaskContext } from "./group-context.js";
5
17
  import { createAccountAuth, hashPassword, verifyPassword, SESSION_TTL, HubRateLimiter } from "./hub-auth.js";
18
+ import { establishConversation, advanceConversationTask, nextConversationTask, recordConversationTurn, conversationStatus, queueParentResult, conversationPage, trimConversationHistory, } from "./hub-conversations.js";
6
19
  class HttpError extends Error {
7
20
  status;
8
21
  constructor(status, message) {
@@ -41,8 +54,7 @@ function handoff(value) {
41
54
  }
42
55
  const token = () => randomBytes(32).toString("base64url");
43
56
  const PAIR_TTL = 10 * 60 * 1000;
44
- const HISTORY = 500;
45
- /** Does not listen. The caller may attach a relay, root page and additional routes before listening. */
57
+ const HISTORY = GROUP_RETENTION_LIMIT;
46
58
  export async function createDeviceHub(options) {
47
59
  const origin = new URL(options.publicUrl);
48
60
  if (!["http:", "https:"].includes(origin.protocol) ||
@@ -65,6 +77,9 @@ export async function createDeviceHub(options) {
65
77
  throw new Error("Device domain must be independent of hub domain");
66
78
  }
67
79
  const store = await DeviceHubStore.open(options.dataDir);
80
+ const taskJournalManager = createTaskJournalManager(options.dataDir);
81
+ const taskReportStore = createTaskReportStore(options.dataDir, "hub");
82
+ const groupEvents = createGroupEvents(store, taskJournalManager);
68
83
  const auth = createAccountAuth(store, options.publicUrl);
69
84
  const getAccount = (req) => auth.getAccount(req);
70
85
  async function authenticateAgent(req) {
@@ -107,10 +122,21 @@ export async function createDeviceHub(options) {
107
122
  if (req.method === "POST" && !agentWrites.allow("user:" + device.id))
108
123
  fail(429, "Too many user writes");
109
124
  const suffix = req.path.slice("/api/device-user".length);
110
- if (!((req.method === "GET" && (["/devices", "/bots", "/rooms"].includes(suffix) || /^\/rooms\/[^/]+$/.test(suffix))) ||
125
+ const conversationRoute = /^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:messages|stop|deliveries|reviews|task-state|evidence|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)?$/.test(suffix);
126
+ const taskRoute = /^\/rooms\/[^/]+\/tasks\/[^/]+(?:\/(?:journal|report))?$/.test(suffix);
127
+ if (!((req.method === "GET" &&
128
+ (conversationRoute ||
129
+ taskRoute ||
130
+ /^\/rooms\/[^/]+\/(?:events|interactions|transfers)$/.test(suffix) ||
131
+ /^\/rooms\/[^/]+\/transfers\/[^/]+\/preview$/.test(suffix) ||
132
+ ["/devices", "/bots", "/rooms"].includes(suffix) ||
133
+ /^\/rooms\/[^/]+$/.test(suffix))) ||
111
134
  (req.method === "POST" &&
112
135
  (suffix === "/rooms" ||
113
- /^\/rooms\/[^/]+\/(messages|rename|members|delete)$/.test(suffix) ||
136
+ conversationRoute ||
137
+ /^\/rooms\/[^/]+\/(messages|rename|members|clear|delete|interactions|canvas)$/.test(suffix) ||
138
+ /^\/rooms\/[^/]+\/tasks\/[^/]+\/approve-plan$/.test(suffix) ||
139
+ /^\/rooms\/[^/]+\/transfers(?:\/start|\/[^/]+(?:\/(?:apply|abort|resume))?)?$/.test(suffix) ||
114
140
  /^\/devices\/[^/]+\/open$/.test(suffix)))))
115
141
  fail(404, "User route missing");
116
142
  users.set(req, { device, account: { id: owner.id, username: owner.username } });
@@ -123,12 +149,19 @@ export async function createDeviceHub(options) {
123
149
  const agent = await authenticateAgent(req);
124
150
  if (!agent)
125
151
  fail(401, "Device authentication required");
126
- if (["POST", "PUT"].includes(req.method) && !agentWrites.allow(agent.device.id))
152
+ const isReportUpload = req.method === "POST" && /^\/api\/agent\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(req.path);
153
+ if (["POST", "PUT"].includes(req.method) && !isReportUpload && !agentWrites.allow(agent.device.id))
127
154
  fail(429, "Too many device writes");
128
155
  agents.set(req, agent);
129
156
  const suffix = req.path.slice("/api/agent".length);
130
- if ((req.method === "GET" && (["/devices", "/bots", "/rooms"].includes(suffix) || /^\/rooms\/[^/]+$/.test(suffix))) ||
131
- (req.method === "POST" && (suffix === "/rooms" || /^\/rooms\/[^/]+\/messages$/.test(suffix))))
157
+ if ((req.method === "GET" &&
158
+ (["/devices", "/bots", "/rooms"].includes(suffix) ||
159
+ /^\/rooms\/[^/]+(?:\/history)?$/.test(suffix) ||
160
+ /^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:task-state|evidence))?)?$/.test(suffix))) ||
161
+ (req.method === "POST" &&
162
+ (suffix === "/rooms" ||
163
+ /^\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(suffix) ||
164
+ /^\/rooms\/[^/]+\/(?:messages|conversations(?:\/[^/]+\/(?:messages|stop|deliveries|reviews|attention|task-state|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)$/.test(suffix))))
132
165
  req.url = req.url.replace("/api/agent/", "/api/");
133
166
  else if (!((suffix === "/transfers" && req.method === "POST") || (suffix === "/bots" && req.method === "PUT")))
134
167
  fail(404, "Agent route missing");
@@ -145,9 +178,16 @@ export async function createDeviceHub(options) {
145
178
  next();
146
179
  });
147
180
  const json = express.json({ limit: "32kb", strict: true });
181
+ const reportJson = express.json({ limit: TASK_REPORT_UPLOAD_JSON_BYTES, strict: true });
182
+ const reportWrites = new HubRateLimiter(4096, 60000);
148
183
  app.use((req, res, next) => {
149
184
  if (agents.has(req) && req.path === "/api/agent/transfers")
150
185
  return next();
186
+ if (agents.has(req) && req.method === "POST" && /^\/api\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(req.path)) {
187
+ if (!reportWrites.allow(agents.get(req).device.id))
188
+ return res.status(429).json({ error: "Too many report chunks" });
189
+ return reportJson(req, res, next);
190
+ }
151
191
  json(req, res, next);
152
192
  });
153
193
  const loginLimit = new HubRateLimiter(10, 60000);
@@ -318,8 +358,11 @@ export async function createDeviceHub(options) {
318
358
  draft.devices = draft.devices.filter((device) => device.id !== id);
319
359
  const removedBots = new Set(draft.bots.filter((b) => b.deviceId === id).map((b) => b.id));
320
360
  draft.bots = draft.bots.filter((b) => b.deviceId !== id);
321
- for (const room of draft.rooms)
361
+ for (const room of draft.rooms) {
322
362
  room.botIds = room.botIds.filter((botId) => !removedBots.has(botId));
363
+ if (room.primaryBotId && removedBots.has(room.primaryBotId))
364
+ delete room.primaryBotId;
365
+ }
323
366
  for (const task of draft.tasks)
324
367
  if (task.deviceId === id && !isTerminal(task.status)) {
325
368
  task.status = "interrupted";
@@ -376,7 +419,19 @@ export async function createDeviceHub(options) {
376
419
  !Number.isSafeInteger(b.revision) ||
377
420
  b.revision < 1)
378
421
  fail(400, "Invalid Bot registration");
379
- return { id, name, description: b.description, enabled: b.enabled, revision: b.revision };
422
+ if (b.tools !== undefined &&
423
+ (!Array.isArray(b.tools) ||
424
+ b.tools.length > 256 ||
425
+ b.tools.some((name) => typeof name !== "string" || !name.trim() || name.length > 128)))
426
+ fail(400, "Invalid Bot tools");
427
+ return {
428
+ id,
429
+ name,
430
+ description: b.description,
431
+ enabled: b.enabled,
432
+ revision: b.revision,
433
+ ...(b.tools === undefined ? {} : { tools: [...new Set(b.tools)] }),
434
+ };
380
435
  });
381
436
  const bots = await store.transact((draft) => {
382
437
  if (!draft.devices.some((d) => d.id === device.id && d.accountId === owner.id))
@@ -395,7 +450,10 @@ export async function createDeviceHub(options) {
395
450
  if (previous &&
396
451
  (row.revision < previous.revision ||
397
452
  (row.revision === previous.revision &&
398
- ["name", "description", "enabled"].some((k) => previous[k] !== row[k]))))
453
+ (["name", "description", "enabled"].some((k) => previous[k] !== row[k]) ||
454
+ (row.tools !== undefined &&
455
+ previous.tools !== undefined &&
456
+ JSON.stringify(previous.tools) !== JSON.stringify(row.tools))))))
399
457
  fail(409, "Bot revision is stale");
400
458
  if (previous)
401
459
  Object.assign(previous, row, { updatedAt: Date.now() });
@@ -439,12 +497,122 @@ export async function createDeviceHub(options) {
439
497
  fail(400, "Invalid room Bot");
440
498
  if (draft.rooms.filter((r) => r.accountId === owner.id).length >= 100)
441
499
  fail(409, "Room capacity reached");
442
- const room = { id: randomUUID(), accountId: owner.id, name, botIds, createdAt: Date.now() };
500
+ const primaryBotId = req.body?.primaryBotId == null ? undefined : text(req.body.primaryBotId, 128);
501
+ if (primaryBotId && !botIds.includes(primaryBotId))
502
+ fail(400, "Primary Bot must be a room member");
503
+ const room = { id: randomUUID(), accountId: owner.id, name, botIds, primaryBotId, createdAt: Date.now() };
443
504
  draft.rooms.push(room);
444
505
  return room;
445
506
  });
446
507
  res.status(201).json({ room });
447
508
  });
509
+ const humanInteractions = new Map();
510
+ function liveInteractions(roomId, accountId) {
511
+ const state = store.snapshot();
512
+ for (const [key, items] of humanInteractions) {
513
+ const task = state.tasks.find((t) => t.id === key);
514
+ if (!task ||
515
+ task.cancelRequested ||
516
+ !(task.status === "running" || (task.status === "queued" && deliveredTasks.has(task.id))) ||
517
+ items.some((i) => i.attemptId !== task.attemptId))
518
+ humanInteractions.delete(key);
519
+ }
520
+ return [...humanInteractions.values()]
521
+ .flat()
522
+ .filter((i) => i.roomId === roomId &&
523
+ state.tasks.some((t) => t.id === i.taskId && t.accountId === accountId) &&
524
+ (i.deadline === undefined || i.deadline > Date.now()) &&
525
+ (options.isOnline?.(i.deviceId) ?? true));
526
+ }
527
+ function acceptInteractions(deviceId, event) {
528
+ const state = store.snapshot();
529
+ const task = state.tasks.find((t) => t.id === event.taskId && t.deviceId === deviceId && t.attemptId === event.attemptId && t.botId === event.botId);
530
+ const room = task &&
531
+ state.rooms.find((r) => r.id === task.roomId && r.accountId === task.accountId && r.botIds.includes(task.botId));
532
+ if (!task ||
533
+ !room ||
534
+ task.cancelRequested ||
535
+ !(task.status === "running" || (task.status === "queued" && deliveredTasks.has(task.id))) ||
536
+ state.devices.find((d) => d.id === deviceId)?.accountId !== task.accountId ||
537
+ !validInteractionProjection(event.items, {
538
+ taskId: task.id,
539
+ attemptId: task.attemptId,
540
+ roomId: task.roomId,
541
+ botId: task.botId,
542
+ deviceId,
543
+ }))
544
+ return;
545
+ if (event.items.length) {
546
+ if (!humanInteractions.has(task.id) && humanInteractions.size >= 128)
547
+ return;
548
+ humanInteractions.set(task.id, structuredClone(event.items));
549
+ }
550
+ else
551
+ humanInteractions.delete(task.id);
552
+ groupEvents.invalidate(task.roomId);
553
+ }
554
+ app.get("/api/rooms/:id/interactions", (req, res) => {
555
+ const owner = account(req);
556
+ if (agents.has(req))
557
+ fail(403, "Human interaction requires a user session");
558
+ if (!store.snapshot().rooms.some((r) => r.id === req.params.id && r.accountId === owner.id))
559
+ fail(404, "Room missing");
560
+ res.setHeader("Cache-Control", "no-store");
561
+ res.json({ interactions: liveInteractions(req.params.id, owner.id) });
562
+ });
563
+ app.post("/api/rooms/:id/interactions", async (req, res) => {
564
+ const owner = account(req);
565
+ if (agents.has(req))
566
+ fail(403, "Human interaction requires a user session");
567
+ if (!validInteractionAnswer(req.body))
568
+ fail(400, "Invalid interaction answer");
569
+ const item = liveInteractions(req.params.id, owner.id).find((i) => i.id === req.body.interactionId && i.taskId === req.body.taskId && i.attemptId === req.body.attemptId);
570
+ if (!item)
571
+ fail(409, "Interaction expired");
572
+ if (!(await options.relay?.answerInteraction?.(item.deviceId, req.body)))
573
+ fail(409, "Executor rejected or did not acknowledge the answer");
574
+ humanInteractions.set(item.taskId, (humanInteractions.get(item.taskId) ?? []).filter((i) => i.id !== item.id));
575
+ groupEvents.invalidate(item.roomId);
576
+ res.json({ forwarded: true });
577
+ });
578
+ app.post("/api/rooms/:id/canvas", async (req, res) => {
579
+ const owner = account(req);
580
+ if (agents.has(req))
581
+ fail(403, "Canvas binding requires a user session");
582
+ const raw = req.body?.binding;
583
+ if (!req.body ||
584
+ Object.keys(req.body).some((key) => key !== "binding") ||
585
+ (raw !== null &&
586
+ (!raw ||
587
+ typeof raw !== "object" ||
588
+ Array.isArray(raw) ||
589
+ Object.keys(raw).some((key) => !["deviceId", "graphId", "cwd", "title"].includes(key)) ||
590
+ typeof raw.deviceId !== "string" ||
591
+ typeof raw.graphId !== "string" ||
592
+ !/^[A-Za-z0-9._-]{1,64}$/.test(raw.graphId) ||
593
+ typeof raw.cwd !== "string" ||
594
+ !raw.cwd.trim() ||
595
+ raw.cwd.length > 4096 ||
596
+ typeof raw.title !== "string" ||
597
+ raw.title.length > 200)))
598
+ fail(400, "Invalid canvas binding");
599
+ const binding = raw === null
600
+ ? undefined
601
+ : { deviceId: raw.deviceId, graphId: raw.graphId, cwd: raw.cwd.trim(), title: raw.title };
602
+ let room;
603
+ await store.transact((state) => {
604
+ room = state.rooms.find((item) => item.id === req.params.id && item.accountId === owner.id);
605
+ if (!room)
606
+ fail(404, "Room missing");
607
+ if (binding &&
608
+ (!state.devices.some((device) => device.id === binding.deviceId && device.accountId === owner.id) ||
609
+ !state.bots.some((bot) => bot.deviceId === binding.deviceId && bot.accountId === owner.id && room.botIds.includes(bot.id))))
610
+ fail(403, "Canvas device must host a Bot in this group");
611
+ room.canvasBinding = binding;
612
+ });
613
+ groupEvents.invalidate(String(req.params.id));
614
+ res.json({ room });
615
+ });
448
616
  app.get("/api/rooms/:id", (req, res) => {
449
617
  const state = store.snapshot(), room = state.rooms.find((r) => r.id === req.params.id && r.accountId === account(req).id);
450
618
  if (!room ||
@@ -464,10 +632,302 @@ export async function createDeviceHub(options) {
464
632
  ?.name,
465
633
  })),
466
634
  messages: state.messages.filter((m) => m.roomId === room.id),
467
- tasks: state.tasks.filter((t) => t.roomId === room.id),
635
+ tasks: state.tasks.filter((t) => t.roomId === room.id).map(publicTask),
636
+ });
637
+ });
638
+ app.get("/api/rooms/:id/events", (req, res) => {
639
+ groupEvents.connect(account(req).id, String(req.params.id), res, users.get(req)?.device.id);
640
+ });
641
+ // === Task Details, Journal, and Reports ===
642
+ app.get("/api/rooms/:id/tasks/:taskId", (req, res) => {
643
+ const acc = account(req);
644
+ const state = store.snapshot();
645
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === acc.id);
646
+ if (!room)
647
+ fail(404, "Room missing");
648
+ const task = state.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === acc.id);
649
+ if (!task)
650
+ fail(404, "Task missing");
651
+ const bot = state.bots.find((b) => b.id === task.botId && b.accountId === acc.id);
652
+ const device = state.devices.find((d) => d.id === task.deviceId && d.accountId === acc.id);
653
+ const reportMeta = mergeTaskReportMetadata(task, taskReportStore.getReportMeta(task.id, task.attemptId, acc.id, room.id));
654
+ const interactions = state.interactions
655
+ ? state.interactions.filter((i) => i.taskId === task.id)
656
+ : [];
657
+ const deliveries = state.deliveries
658
+ ? state.deliveries.filter((d) => d.taskId === task.id)
659
+ : [];
660
+ res.json({
661
+ task: {
662
+ id: task.id,
663
+ roomId: task.roomId,
664
+ accountId: task.accountId,
665
+ deviceId: task.deviceId,
666
+ botId: task.botId,
667
+ botName: bot?.name,
668
+ deviceName: device?.name,
669
+ text: task.text,
670
+ status: task.status,
671
+ createdAt: task.createdAt,
672
+ updatedAt: task.updatedAt,
673
+ attemptId: task.attemptId,
674
+ parentTaskId: task.parentTaskId,
675
+ conversationId: task.conversationId,
676
+ report: task.report,
677
+ },
678
+ reportMeta,
679
+ interactionCount: interactions.length,
680
+ interactions: interactions.map((i) => ({
681
+ id: i.id,
682
+ kind: i.kind,
683
+ question: i.question,
684
+ resolved: !!i.decision || !!i.cancelled,
685
+ decision: i.decision,
686
+ })),
687
+ journalUnavailable: groupEvents.isJournalUnavailable(task.id, task.attemptId),
688
+ deliveries: deliveries.map((d) => ({
689
+ id: d.id,
690
+ commit: d.commit,
691
+ branch: d.branch,
692
+ summary: d.summary,
693
+ passed: d.checks?.every((c) => c.status === "passed") ?? true,
694
+ })),
695
+ });
696
+ });
697
+ app.post("/api/rooms/:id/tasks/:taskId/approve-plan", async (req, res) => {
698
+ const acc = account(req);
699
+ if (agents.has(req)) {
700
+ fail(403, "Plan approval is restricted to human users; Bots cannot self-approve");
701
+ }
702
+ const user = users.get(req)?.device;
703
+ const approverName = user ? `${acc.username} · ${user.name}` : acc.username;
704
+ const { plan, nextTask } = await store.transact((draft) => {
705
+ const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === acc.id);
706
+ if (!room)
707
+ fail(404, "Room missing");
708
+ const task = draft.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === acc.id);
709
+ if (!task)
710
+ fail(404, "Task missing");
711
+ if (!task.planOnly || !task.plan)
712
+ fail(400, "Task does not have a plan to approve");
713
+ if (task.status !== "completed" || task.cancelRequested)
714
+ fail(409, "Planning task must finish before approval");
715
+ if (!validateTaskPlan(task.plan))
716
+ fail(409, "Plan steps are invalid");
717
+ if (validBot(draft, task.botId, acc.id)?.revision !== task.botRevision)
718
+ fail(409, "Plan Bot configuration changed");
719
+ if (!room.botIds.includes(task.botId))
720
+ fail(409, "Plan Bot is no longer a room member");
721
+ const result = atomicApproveGroupPlan(task.plan, approverName);
722
+ if (!result.ok)
723
+ fail(409, result.error);
724
+ task.plan = result.plan;
725
+ task.updatedAt = Date.now();
726
+ const conversation = task.conversationId
727
+ ? draft.conversations.find((c) => c.id === task.conversationId && c.roomId === room.id && c.accountId === acc.id)
728
+ : undefined;
729
+ if (!conversation || conversation.closed)
730
+ fail(409, "Plan conversation unavailable");
731
+ if ((task.dispatchDepth ?? 0) + 1 > 8)
732
+ fail(409, "Dispatch depth exhausted");
733
+ const root = draft.tasks.find((t) => t.id === (task.rootTaskId ?? task.id));
734
+ if (!root)
735
+ fail(409, "Dispatch root expired");
736
+ if (root) {
737
+ if ((root.dispatchCount ?? 0) >= 16)
738
+ fail(409, "Dispatch budget exhausted");
739
+ root.dispatchCount = (root.dispatchCount ?? 0) + 1;
740
+ }
741
+ const now = Date.now();
742
+ const nextTaskId = randomUUID();
743
+ const nextAttemptId = randomUUID();
744
+ const nextTask = {
745
+ id: nextTaskId,
746
+ rootTaskId: task.rootTaskId ?? task.id,
747
+ parentTaskId: task.id,
748
+ dispatchDepth: (task.dispatchDepth ?? 0) + 1,
749
+ attemptId: nextAttemptId,
750
+ roomId: room.id,
751
+ accountId: acc.id,
752
+ botId: task.botId,
753
+ deviceId: task.deviceId,
754
+ botRevision: task.botRevision,
755
+ text: `Approved plan for: ${task.text}\n\n${task.plan.steps.map((step) => `${step.id}. ${step.title}${step.description ? ` — ${step.description}` : ""}`).join("\n")}\n\nBegin execution of these approved steps.`,
756
+ status: "queued",
757
+ createdAt: now,
758
+ updatedAt: now,
759
+ planOnly: false,
760
+ resume: Boolean(conversation),
761
+ ...(conversation ? { conversationId: conversation.id } : {}),
762
+ };
763
+ draft.tasks.push(nextTask);
764
+ if (conversation) {
765
+ advanceConversationTask(draft, conversation, nextTask);
766
+ conversation.updatedAt = now;
767
+ }
768
+ const idempotencyKey = randomUUID();
769
+ const fingerprint = hashSecret(`approve-plan:${task.id}:${nextTaskId}:${now}`);
770
+ recordConversationTurn(draft, nextTask, idempotencyKey, fingerprint);
771
+ const message = {
772
+ id: randomUUID(),
773
+ roomId: room.id,
774
+ accountId: acc.id,
775
+ text: `Approved plan for task ${task.id}. Beginning execution.`,
776
+ sender: {
777
+ type: "human",
778
+ id: acc.id,
779
+ name: approverName,
780
+ ...(user ? { sourceDeviceId: user.id } : {}),
781
+ },
782
+ createdAt: now,
783
+ taskIds: [nextTaskId],
784
+ targetBotIds: [task.botId],
785
+ ...(conversation ? { conversationId: conversation.id, conversationIds: [conversation.id] } : {}),
786
+ };
787
+ draft.messages.push(message);
788
+ return { plan: task.plan, nextTask };
468
789
  });
790
+ res.json({ ok: true, plan, nextTaskId: nextTask.id });
791
+ void drainConversation(nextTask.conversationId).catch(() => { });
469
792
  });
470
- for (const operation of ["rename", "members", "delete"]) {
793
+ app.get("/api/rooms/:id/tasks/:taskId/journal", async (req, res) => {
794
+ const acc = account(req);
795
+ const state = store.snapshot();
796
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === acc.id);
797
+ if (!room)
798
+ fail(404, "Room missing");
799
+ const task = state.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === acc.id);
800
+ if (!task)
801
+ fail(404, "Task missing");
802
+ const cursor = typeof req.query.cursor === "string" ? req.query.cursor : undefined;
803
+ const limit = typeof req.query.limit === "string" ? parseInt(req.query.limit, 10) : undefined;
804
+ const direction = req.query.direction === "backward" ? "backward" : "forward";
805
+ const page = await taskJournalManager.getPage(task.id, acc.id, room.id, { cursor, limit, direction });
806
+ // The task exists but never wrote a journal segment (queued, failed before the first progress
807
+ // event, or created before the journal existed). An empty audit trail is a valid state, not a
808
+ // missing resource: 404 here made every such task render as a broken panel in the UI.
809
+ if (!page)
810
+ return res.json({
811
+ taskId: task.id,
812
+ items: [],
813
+ hasMore: false,
814
+ totalEvents: 0,
815
+ truncated: false,
816
+ droppedCount: 0,
817
+ journalUnavailable: groupEvents.isJournalUnavailable(task.id, task.attemptId),
818
+ });
819
+ res.json(page);
820
+ });
821
+ app.get("/api/rooms/:id/tasks/:taskId/report", (req, res) => {
822
+ const acc = account(req);
823
+ const state = store.snapshot();
824
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === acc.id);
825
+ if (!room)
826
+ fail(404, "Room missing");
827
+ const task = state.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === acc.id);
828
+ if (!task)
829
+ fail(404, "Task missing");
830
+ const offset = typeof req.query.offset === "string" ? parseInt(req.query.offset, 10) : undefined;
831
+ const limit = typeof req.query.limit === "string" ? parseInt(req.query.limit, 10) : undefined;
832
+ const chunkIndex = typeof req.query.chunkIndex === "string" ? parseInt(req.query.chunkIndex, 10) : undefined;
833
+ if (chunkIndex !== undefined && Number.isSafeInteger(chunkIndex)) {
834
+ const chunkData = taskReportStore.getReportChunk(task.id, task.attemptId, acc.id, room.id, chunkIndex);
835
+ if (!chunkData)
836
+ fail(404, "Report chunk missing");
837
+ return res.json({ ...chunkData, meta: mergeTaskReportMetadata(task, chunkData.meta) });
838
+ }
839
+ const reportData = taskReportStore.getReport(task.id, task.attemptId, acc.id, room.id, { offset, limit });
840
+ if (!reportData)
841
+ return res.json({ meta: mergeTaskReportMetadata(task, null) });
842
+ res.json({ ...reportData, meta: mergeTaskReportMetadata(task, reportData.meta) });
843
+ });
844
+ app.post("/api/rooms/:id/tasks/:taskId/report", async (req, res) => {
845
+ const agent = agents.get(req);
846
+ if (!agent)
847
+ fail(403, "Agent authentication required for report upload");
848
+ const state = store.snapshot();
849
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === agent.account.id);
850
+ if (!room)
851
+ fail(404, "Room missing");
852
+ const task = state.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === agent.account.id);
853
+ if (!task)
854
+ fail(404, "Task missing");
855
+ if (task.deviceId !== agent.device.id)
856
+ fail(403, "Only assigned execution device may upload reports");
857
+ const body = req.body ?? {};
858
+ if (body.taskId !== task.id || body.attemptId !== task.attemptId)
859
+ fail(409, "Attempt mismatch");
860
+ if (body.botId !== task.botId)
861
+ fail(409, "Bot mismatch");
862
+ if (!Number.isSafeInteger(body.totalBytes) || body.totalBytes < 0 || body.totalBytes > MAX_TASK_FULL_REPORT_BYTES)
863
+ fail(413, "Full report exceeds 4 MiB quota");
864
+ if (typeof body.fullSha256 !== "string" || !/^[a-f0-9]{64}$/.test(body.fullSha256))
865
+ fail(400, "Missing full report hash");
866
+ const bot = state.bots.find((b) => b.id === task.botId && b.accountId === agent.account.id && b.deviceId === agent.device.id);
867
+ if (!bot || !bot.enabled || bot.revision !== task.botRevision)
868
+ fail(409, "Bot revision changed");
869
+ if (typeof body.text !== "string")
870
+ fail(400, "Missing report text");
871
+ const chunkIndex = typeof body.chunkIndex === "number" ? body.chunkIndex : 0;
872
+ const totalChunks = typeof body.totalChunks === "number" ? body.totalChunks : 1;
873
+ try {
874
+ const meta = taskReportStore.appendReportChunk({
875
+ taskId: task.id,
876
+ attemptId: task.attemptId,
877
+ chunkIndex,
878
+ totalChunks,
879
+ text: body.text,
880
+ sha256: typeof body.sha256 === "string" ? body.sha256 : undefined,
881
+ fullSha256: body.fullSha256,
882
+ totalBytes: body.totalBytes,
883
+ isFinal: !!body.isFinal,
884
+ }, room.id, agent.account.id);
885
+ if (meta.complete && (meta.sha256 !== body.fullSha256 || meta.totalBytes !== body.totalBytes))
886
+ fail(409, "Assembled full report integrity mismatch");
887
+ await store.transact((draft) => {
888
+ const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
889
+ if (!current)
890
+ fail(409, "Report attempt no longer exists");
891
+ current.reportMetadata = {
892
+ sha256: meta.complete ? meta.sha256 : body.fullSha256,
893
+ totalBytes: body.totalBytes,
894
+ missing: false,
895
+ rejected: false,
896
+ uploadPending: !meta.complete,
897
+ ...(!meta.complete ? { publicError: "report_upload_pending" } : {}),
898
+ };
899
+ });
900
+ res.json({ meta: { ...meta, uploadPending: !meta.complete, missing: false } });
901
+ }
902
+ catch (cause) {
903
+ if (cause?.name === "TaskReportQuotaError") {
904
+ fail(413, cause.message);
905
+ }
906
+ else if (cause?.name === "TaskReportConflictError") {
907
+ fail(409, cause.message);
908
+ }
909
+ else {
910
+ fail(400, cause?.message ?? "Invalid report chunk");
911
+ }
912
+ }
913
+ });
914
+ app.get("/api/rooms/:id/history", (req, res) => {
915
+ const agent = agents.get(req);
916
+ if (!agent)
917
+ fail(403, "Agent authentication required");
918
+ const state = store.snapshot();
919
+ const room = state.rooms.find((entry) => entry.id === req.params.id && entry.accountId === agent.account.id);
920
+ const source = state.bots.find((bot) => bot.id === req.query.sourceBotId &&
921
+ bot.deviceId === agent.device.id &&
922
+ bot.accountId === agent.account.id &&
923
+ bot.enabled);
924
+ if (!room || !source || !room.botIds.includes(source.id))
925
+ fail(404, "Room missing");
926
+ if (req.query.before !== undefined && typeof req.query.before !== "string")
927
+ fail(400, "Invalid history cursor");
928
+ res.json(groupHistoryPage(room.id, state.messages, req.query.before));
929
+ });
930
+ for (const operation of ["rename", "members", "clear", "delete"]) {
471
931
  app.post(`/api/rooms/:id/${operation}`, async (req, res) => {
472
932
  const owner = account(req);
473
933
  const result = await store.transact((draft) => {
@@ -480,42 +940,473 @@ export async function createDeviceHub(options) {
480
940
  const members = ids(req.body?.botIds);
481
941
  if (!members.length || members.some((id) => !validBot(draft, id, owner.id)))
482
942
  fail(400, "Invalid room Bot");
483
- if (draft.tasks.some((t) => t.roomId === room.id && !isTerminal(t.status) && !members.includes(t.botId)))
943
+ if (draft.tasks.some((t) => t.roomId === room.id && taskPending(t) && !members.includes(t.botId)))
484
944
  throw Object.assign(new Error("Stop removed Bots' active tasks first"), {
485
945
  status: 409,
486
946
  code: "ACTIVE_TASKS",
487
947
  });
948
+ const primaryBotId = req.body?.primaryBotId === undefined
949
+ ? room.primaryBotId && members.includes(room.primaryBotId)
950
+ ? room.primaryBotId
951
+ : undefined
952
+ : req.body.primaryBotId === null
953
+ ? undefined
954
+ : text(req.body.primaryBotId, 128);
955
+ if (primaryBotId && !members.includes(primaryBotId))
956
+ fail(400, "Primary Bot must be a room member");
488
957
  room.botIds = members;
958
+ room.primaryBotId = primaryBotId;
489
959
  }
490
- if (operation === "delete") {
491
- if (draft.tasks.some((t) => t.roomId === room.id && !isTerminal(t.status)))
492
- throw Object.assign(new Error("Stop active tasks before deleting room"), {
960
+ if (operation === "delete" || operation === "clear") {
961
+ if (draft.tasks.some((t) => t.roomId === room.id && taskPending(t)))
962
+ throw Object.assign(new Error("Stop active tasks before clearing or deleting room"), {
493
963
  status: 409,
494
964
  code: "ACTIVE_TASKS",
495
965
  });
496
- draft.rooms = draft.rooms.filter((r) => r.id !== room.id);
966
+ if (operation === "delete")
967
+ draft.rooms = draft.rooms.filter((r) => r.id !== room.id);
497
968
  draft.messages = draft.messages.filter((m) => m.roomId !== room.id);
498
969
  draft.tasks = draft.tasks.filter((t) => t.roomId !== room.id);
499
970
  draft.receipts = draft.receipts.filter((r) => r.roomId !== room.id);
500
- return { deleted: true };
971
+ const removedConversations = new Set(draft.conversations.filter((c) => c.roomId === room.id).map((c) => c.id));
972
+ draft.conversations = draft.conversations.filter((c) => c.roomId !== room.id);
973
+ draft.deliveries = draft.deliveries.filter((d) => d.roomId !== room.id);
974
+ draft.reviews = draft.reviews.filter((r) => r.roomId !== room.id);
975
+ draft.deliveryReceipts = draft.deliveryReceipts.filter((r) => !removedConversations.has(r.conversationId));
976
+ draft.conversationMessages = draft.conversationMessages.filter((m) => !removedConversations.has(m.conversationId));
977
+ return operation === "delete" ? { deleted: true } : { cleared: true };
501
978
  }
502
979
  return { room };
503
980
  });
504
981
  res.json(result);
505
982
  });
506
983
  }
507
- app.post("/api/rooms/:id/messages", async (req, res) => {
984
+ for (const kind of ["deliveries", "reviews"]) {
985
+ app.post(`/api/rooms/:id/conversations/:conversationId/${kind}`, async (req, res) => {
986
+ const owner = account(req);
987
+ const record = await store.transact((draft) => {
988
+ const actor = { accountId: owner.id, bot: ownBot(req, draft) };
989
+ return (kind === "deliveries" ? addDelivery : addReview)(draft, req.params.id, req.params.conversationId, actor, req.body);
990
+ });
991
+ res.json(kind === "deliveries" ? { delivery: record } : { review: record });
992
+ });
993
+ }
994
+ app.get("/api/rooms/:id/conversations/:conversationId/integrations", (req, res) => {
995
+ const owner = account(req);
996
+ const snapshot = store.snapshot();
997
+ const conversation = snapshot.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
998
+ if (!conversation)
999
+ fail(404, "Conversation missing");
1000
+ res.json({ integrations: listIntegrations(snapshot, req.params.conversationId) });
1001
+ });
1002
+ app.post("/api/rooms/:id/conversations/:conversationId/integrations", async (req, res) => {
1003
+ const owner = account(req);
1004
+ const actor = { accountId: owner.id };
1005
+ if (!options.relay?.callDevice)
1006
+ fail(503, "Device relay unavailable");
1007
+ const driver = {
1008
+ callDeviceCommand: (id, a, p, opts) => options.relay.callDevice(id, a, p, opts),
1009
+ };
1010
+ const result = await hubPrepareIntegration(store, req.params.id, req.params.conversationId, actor, req.body ?? {}, driver);
1011
+ res.json({ integration: result });
1012
+ });
1013
+ app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/verify", async (req, res) => {
1014
+ const owner = account(req);
1015
+ const actor = { accountId: owner.id };
1016
+ if (!options.relay?.callDevice)
1017
+ fail(503, "Device relay unavailable");
1018
+ const driver = {
1019
+ callDeviceCommand: (id, a, p, opts) => options.relay.callDevice(id, a, p, opts),
1020
+ };
1021
+ const result = await hubVerifyIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, req.body ?? {}, driver);
1022
+ res.json({ integration: result });
1023
+ });
1024
+ app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/apply", async (req, res) => {
1025
+ const owner = account(req);
1026
+ const actor = { accountId: owner.id };
1027
+ if (!options.relay?.callDevice)
1028
+ fail(503, "Device relay unavailable");
1029
+ const driver = {
1030
+ callDeviceCommand: (id, a, p, opts) => options.relay.callDevice(id, a, p, opts),
1031
+ };
1032
+ const result = await hubConfirmIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, req.body ?? {}, driver);
1033
+ res.json({ integration: result });
1034
+ });
1035
+ app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/cancel", async (req, res) => {
1036
+ const owner = account(req);
1037
+ const actor = { accountId: owner.id };
1038
+ if (!options.relay?.callDevice)
1039
+ fail(503, "Device relay unavailable");
1040
+ const driver = {
1041
+ callDeviceCommand: (id, a, p, opts) => options.relay.callDevice(id, a, p, opts),
1042
+ };
1043
+ const result = await hubCancelIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, driver);
1044
+ res.json({ integration: result });
1045
+ });
1046
+ app.post("/api/rooms/:id/conversations/:conversationId/stop", async (req, res) => {
1047
+ const owner = account(req);
1048
+ const pending = await store.transact((draft) => {
1049
+ const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
1050
+ const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
1051
+ if (!conversation || !room)
1052
+ fail(404, "Conversation missing");
1053
+ const source = ownBot(req, draft);
1054
+ if (source && (!room.botIds.includes(source.id) || conversation.botId !== source.id))
1055
+ fail(403, "Bot may stop only its own conversation");
1056
+ conversation.closed = true;
1057
+ const tasks = draft.tasks.filter((t) => t.conversationId === conversation.id && taskPending(t));
1058
+ for (const task of tasks) {
1059
+ task.cancelRequested = true;
1060
+ if (task.status === "queued" && !deliveredTasks.has(task.id)) {
1061
+ task.stopConfirmed = true;
1062
+ task.status = "interrupted";
1063
+ task.updatedAt = Date.now();
1064
+ task.report = "Conversation stopped before delivery.";
1065
+ }
1066
+ }
1067
+ return tasks;
1068
+ });
1069
+ for (const task of pending) {
1070
+ if (task.stopConfirmed)
1071
+ continue;
1072
+ const confirmed = await options.relay
1073
+ ?.cancelTask?.(task.deviceId, task.id, task.attemptId)
1074
+ .catch(() => ({ stopped: false }));
1075
+ if (!confirmed?.stopped)
1076
+ continue;
1077
+ await store.transact((draft) => {
1078
+ const current = draft.tasks.find((t) => t.id === task.id && t.attemptId === task.attemptId);
1079
+ if (!current)
1080
+ return;
1081
+ current.stopConfirmed = true;
1082
+ current.status = "interrupted";
1083
+ current.updatedAt = Date.now();
1084
+ current.report = "Conversation stopped.";
1085
+ });
1086
+ }
1087
+ const remaining = store
1088
+ .snapshot()
1089
+ .tasks.filter((t) => t.conversationId === req.params.conversationId && taskPending(t));
1090
+ res.json({ stopped: remaining.length === 0, pending: remaining.length });
1091
+ });
1092
+ app.post("/api/rooms/:id/conversations/:conversationId/attention", async (req, res) => {
1093
+ const owner = account(req);
1094
+ const question = text(req.body?.question, 2000);
1095
+ const kind = req.body?.kind;
1096
+ if (kind !== "answer" && kind !== "decision")
1097
+ fail(400, "Invalid attention kind");
1098
+ const parentTaskId = text(req.body?.parentTaskId, 128);
1099
+ const result = await store.transact((draft) => {
1100
+ const source = ownBot(req, draft);
1101
+ if (!source)
1102
+ fail(403, "Bot authentication required");
1103
+ const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
1104
+ const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === room?.id && c.accountId === owner.id);
1105
+ const task = draft.tasks.find((t) => t.id === parentTaskId &&
1106
+ t.conversationId === conversation?.id &&
1107
+ t.botId === source.id &&
1108
+ t.status === "running" &&
1109
+ !t.cancelRequested);
1110
+ if (!room ||
1111
+ !room.botIds.includes(source.id) ||
1112
+ !conversation ||
1113
+ conversation.closed ||
1114
+ conversation.botId !== source.id ||
1115
+ !task ||
1116
+ conversation.latestTaskId !== task.id)
1117
+ fail(409, "Attention requires the current running Bot task");
1118
+ if (conversation.attention) {
1119
+ if (conversation.attention.taskId === task.id &&
1120
+ conversation.attention.question === question &&
1121
+ conversation.attention.kind === kind)
1122
+ return conversation.attention;
1123
+ fail(409, "An unanswered question already exists");
1124
+ }
1125
+ conversation.attention = { id: randomUUID(), taskId: task.id, kind, question, createdAt: Date.now() };
1126
+ return conversation.attention;
1127
+ });
1128
+ res.json({ attention: result });
1129
+ });
1130
+ app.get("/api/rooms/:id/conversations/:conversationId/task-state", (req, res) => {
1131
+ const state = store.snapshot();
1132
+ const owner = account(req);
1133
+ const room = state.rooms.find((entry) => entry.id === req.params.id && entry.accountId === owner.id);
1134
+ const agent = agents.get(req);
1135
+ if (!room ||
1136
+ (agent &&
1137
+ !state.bots.some((bot) => bot.id === req.query.sourceBotId &&
1138
+ bot.deviceId === agent.device.id &&
1139
+ bot.accountId === owner.id &&
1140
+ bot.enabled &&
1141
+ room.botIds.includes(bot.id))))
1142
+ fail(404, "Room missing");
1143
+ const conversation = state.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room.id && entry.accountId === owner.id);
1144
+ if (!conversation)
1145
+ fail(404, "Conversation missing");
1146
+ const allowedQueries = ["sourceBotId", "beforeSequence", "summaryOnly"];
1147
+ for (const q of Object.keys(req.query)) {
1148
+ if (!allowedQueries.includes(q))
1149
+ fail(400, `Unknown query parameter: ${q}`);
1150
+ }
1151
+ let events = conversation.events ?? [];
1152
+ if (req.query.beforeSequence !== undefined) {
1153
+ const seq = Number(req.query.beforeSequence);
1154
+ if (!Number.isSafeInteger(seq) || seq < 0)
1155
+ fail(400, "Invalid beforeSequence");
1156
+ events = events.filter((e) => e.sequence < seq);
1157
+ }
1158
+ if (req.query.summaryOnly !== undefined && !["true", "false"].includes(String(req.query.summaryOnly))) {
1159
+ fail(400, "Invalid summaryOnly parameter");
1160
+ }
1161
+ const summary = conversation.taskState ? buildDeterministicTaskSummary(conversation.taskState) : undefined;
1162
+ if (req.query.summaryOnly === "true") {
1163
+ res.json({ summary, taskState: conversation.taskState });
1164
+ return;
1165
+ }
1166
+ res.json({ taskState: conversation.taskState, events, ...(summary ? { summary } : {}) });
1167
+ });
1168
+ app.get("/api/rooms/:id/conversations/:conversationId/evidence", (req, res) => {
1169
+ const state = store.snapshot();
1170
+ const owner = account(req);
1171
+ const room = state.rooms.find((entry) => entry.id === req.params.id && entry.accountId === owner.id);
1172
+ const agent = agents.get(req);
1173
+ if (!room ||
1174
+ (agent &&
1175
+ !state.bots.some((bot) => bot.id === req.query.sourceBotId &&
1176
+ bot.deviceId === agent.device.id &&
1177
+ bot.accountId === owner.id &&
1178
+ bot.enabled &&
1179
+ room.botIds.includes(bot.id))))
1180
+ fail(404, "Room missing");
1181
+ const conversation = state.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room.id && entry.accountId === owner.id);
1182
+ if (!conversation)
1183
+ fail(404, "Conversation missing");
1184
+ const allowedQueries = ["sourceBotId", "taskId", "deliveryId", "offset", "limit", "expectedDigest", "digest"];
1185
+ for (const q of Object.keys(req.query)) {
1186
+ if (!allowedQueries.includes(q))
1187
+ fail(400, `Unknown query parameter: ${q}`);
1188
+ }
1189
+ let offset = 0;
1190
+ if (req.query.offset !== undefined) {
1191
+ offset = Number(req.query.offset);
1192
+ if (!Number.isSafeInteger(offset) || offset < 0)
1193
+ fail(400, "Invalid offset");
1194
+ }
1195
+ let limit = 8192;
1196
+ if (req.query.limit !== undefined) {
1197
+ limit = Number(req.query.limit);
1198
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 65536)
1199
+ fail(400, "Invalid limit");
1200
+ }
1201
+ const expectedDigest = typeof req.query.expectedDigest === "string"
1202
+ ? req.query.expectedDigest
1203
+ : typeof req.query.digest === "string"
1204
+ ? req.query.digest
1205
+ : undefined;
1206
+ const taskId = typeof req.query.taskId === "string" ? req.query.taskId : conversation.latestTaskId;
1207
+ const targetTask = state.tasks.find((t) => t.id === taskId && t.conversationId === conversation.id);
1208
+ const deliveryId = typeof req.query.deliveryId === "string" ? req.query.deliveryId : undefined;
1209
+ const targetDelivery = deliveryId
1210
+ ? state.deliveries.find((d) => d.id === deliveryId && d.conversationId === conversation.id)
1211
+ : undefined;
1212
+ let evidence;
1213
+ if (targetTask?.attemptId) {
1214
+ const reportResult = taskReportStore.getReport(targetTask.id, targetTask.attemptId, owner.id, room.id, {
1215
+ offset,
1216
+ limit,
1217
+ expectedDigest,
1218
+ revision: conversation.taskState?.revision,
1219
+ });
1220
+ if (reportResult?.versionMismatch) {
1221
+ fail(409, "Report version digest mismatch; start reading from offset 0 with new digest");
1222
+ }
1223
+ if (reportResult && reportResult.text !== undefined) {
1224
+ evidence = {
1225
+ taskId: targetTask.id,
1226
+ attemptId: targetTask.attemptId,
1227
+ revision: conversation.taskState?.revision,
1228
+ totalBytes: reportResult.meta.totalBytes,
1229
+ offset: reportResult.offset ?? offset,
1230
+ limit: reportResult.limit ?? limit,
1231
+ chunk: reportResult.text,
1232
+ hasMore: reportResult.hasMore ?? false,
1233
+ nextOffset: reportResult.nextOffset ?? null,
1234
+ isExcerpt: (reportResult.hasMore ?? false) || (reportResult.offset ?? 0) > 0,
1235
+ complete: reportResult.meta.complete,
1236
+ source: "full_report",
1237
+ reportRef: reportResult.meta.storageLocation.reportRef,
1238
+ digest: reportResult.digest ?? "",
1239
+ sha256: reportResult.sha256 ?? reportResult.meta.sha256 ?? "",
1240
+ };
1241
+ }
1242
+ }
1243
+ if (!evidence && targetTask?.report) {
1244
+ const chunk = queryTaskReportChunk(targetTask.id, targetTask.report, offset, limit, {
1245
+ attemptId: targetTask.attemptId,
1246
+ revision: conversation.taskState?.revision,
1247
+ source: "report_excerpt",
1248
+ complete: false,
1249
+ });
1250
+ if (expectedDigest && chunk.digest !== expectedDigest) {
1251
+ fail(409, "Report version digest mismatch; start reading from offset 0 with new digest");
1252
+ }
1253
+ evidence = chunk;
1254
+ }
1255
+ res.json({
1256
+ conversationId: conversation.id,
1257
+ taskId,
1258
+ ...(evidence ? { evidence } : {}),
1259
+ ...(targetDelivery ? { delivery: targetDelivery } : {}),
1260
+ summary: conversation.taskState ? buildDeterministicTaskSummary(conversation.taskState) : undefined,
1261
+ });
1262
+ });
1263
+ app.post("/api/rooms/:id/conversations/:conversationId/task-state", async (req, res) => {
1264
+ const owner = account(req);
1265
+ const body = req.body;
1266
+ if (!body ||
1267
+ typeof body !== "object" ||
1268
+ Array.isArray(body) ||
1269
+ Object.keys(body).some((key) => ![
1270
+ "sourceBotId",
1271
+ "parentTaskId",
1272
+ "expectedRevision",
1273
+ "constraints",
1274
+ "progress",
1275
+ "blockers",
1276
+ "nextSteps",
1277
+ ].includes(key)) ||
1278
+ !Number.isSafeInteger(body.expectedRevision) ||
1279
+ body.expectedRevision < 0)
1280
+ fail(400, "Invalid task state update");
1281
+ const parentTaskId = text(body.parentTaskId, 128);
1282
+ const changes = {};
1283
+ for (const key of ["constraints", "blockers", "nextSteps"]) {
1284
+ const value = body[key];
1285
+ if (value === undefined)
1286
+ continue;
1287
+ if (!Array.isArray(value) ||
1288
+ value.length > 20 ||
1289
+ value.some((item) => typeof item !== "string" || !item.trim() || item.length > 500))
1290
+ fail(400, "Invalid task state list");
1291
+ changes[key] = [...value];
1292
+ }
1293
+ if (body.progress !== undefined) {
1294
+ if (typeof body.progress !== "string" || body.progress.length > 2000)
1295
+ fail(400, "Invalid progress");
1296
+ changes.progress = body.progress;
1297
+ }
1298
+ if (!Object.keys(changes).length)
1299
+ fail(400, "Task state update is empty");
1300
+ const conversation = await store.transact((draft) => {
1301
+ const source = ownBot(req, draft);
1302
+ if (!source)
1303
+ fail(403, "Bot authentication required");
1304
+ const room = draft.rooms.find((entry) => entry.id === req.params.id && entry.accountId === owner.id);
1305
+ const current = draft.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room?.id && entry.accountId === owner.id);
1306
+ const task = draft.tasks.find((entry) => entry.id === parentTaskId &&
1307
+ entry.conversationId === current?.id &&
1308
+ entry.botId === source.id &&
1309
+ entry.status === "running" &&
1310
+ !entry.cancelRequested);
1311
+ if (!room ||
1312
+ !room.botIds.includes(source.id) ||
1313
+ !current ||
1314
+ current.closed ||
1315
+ current.botId !== source.id ||
1316
+ !task ||
1317
+ current.latestTaskId !== task.id ||
1318
+ !current.taskState)
1319
+ fail(409, "Task state update requires the current running Bot task");
1320
+ if (current.taskState.revision !== body.expectedRevision)
1321
+ fail(409, "Task state revision changed; read task_state again");
1322
+ const previous = current.taskState.reported;
1323
+ const next = {
1324
+ constraints: [],
1325
+ progress: "",
1326
+ blockers: [],
1327
+ nextSteps: [],
1328
+ ...previous,
1329
+ ...changes,
1330
+ taskId: task.id,
1331
+ botId: source.id,
1332
+ provenance: "bot_reported",
1333
+ updatedAt: previous?.updatedAt ?? Date.now(),
1334
+ };
1335
+ if (JSON.stringify(next) !== JSON.stringify(previous))
1336
+ next.updatedAt = Date.now();
1337
+ current.taskState.reported = next;
1338
+ return current;
1339
+ });
1340
+ res.json({ taskState: conversation.taskState, events: conversation.events ?? [] });
1341
+ });
1342
+ app.get(["/api/rooms/:id/conversations", "/api/rooms/:id/conversations/:conversationId"], (req, res) => {
1343
+ const state = store.snapshot();
1344
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === account(req).id);
1345
+ const agent = agents.get(req);
1346
+ if (!room ||
1347
+ (agent &&
1348
+ !state.bots.some((b) => b.id === req.query.sourceBotId &&
1349
+ b.deviceId === agent.device.id &&
1350
+ b.accountId === room.accountId &&
1351
+ b.enabled &&
1352
+ room.botIds.includes(b.id))))
1353
+ fail(404, "Room missing");
1354
+ const conversations = state.conversations
1355
+ .filter((c) => c.roomId === room.id && c.accountId === room.accountId)
1356
+ .sort((a, b) => b.updatedAt - a.updatedAt)
1357
+ .map((c) => ({
1358
+ ...c,
1359
+ status: conversationStatus(state, c),
1360
+ ...deliverySummary(state, c.id, !req.params.conversationId),
1361
+ }));
1362
+ if (!req.params.conversationId)
1363
+ return res.json({ conversations });
1364
+ const conversation = conversations.find((c) => c.id === req.params.conversationId);
1365
+ if (!conversation)
1366
+ fail(404, "Conversation missing");
1367
+ if (req.query.before !== undefined && typeof req.query.before !== "string")
1368
+ fail(400, "Invalid conversation cursor");
1369
+ res.json({
1370
+ conversation,
1371
+ ...conversationPage(state, conversation.id, req.query.before),
1372
+ ...deliveryHistory(state, conversation.id),
1373
+ });
1374
+ });
1375
+ app.post([
1376
+ "/api/rooms/:id/messages",
1377
+ "/api/rooms/:id/conversations",
1378
+ "/api/rooms/:id/conversations/:conversationId/messages",
1379
+ ], async (req, res) => {
508
1380
  const owner = account(req);
509
1381
  const content = text(req.body?.text);
510
- const targets = ids(req.body?.targetBotIds ?? []);
1382
+ const conversationApi = req.path.includes("/conversations");
1383
+ const conversationId = req.params.conversationId;
1384
+ const kind = req.body?.kind ?? "message";
1385
+ if (!["message", "request", "reply"].includes(kind))
1386
+ fail(400, "Invalid message kind");
1387
+ const requestId = req.body?.requestId === undefined
1388
+ ? kind === "request"
1389
+ ? randomUUID()
1390
+ : undefined
1391
+ : text(req.body.requestId, 128);
1392
+ if (kind === "reply" && !requestId)
1393
+ fail(400, "Reply requires requestId");
1394
+ const targets = ids(conversationApi ? (conversationId ? [] : [text(req.body?.targetBotId, 128)]) : (req.body?.targetBotIds ?? []));
511
1395
  const transfer = handoff(req.body?.handoff);
512
1396
  const parentTaskId = req.body?.parentTaskId === undefined ? undefined : text(req.body.parentTaskId, 128);
1397
+ const attentionId = req.body?.attentionId === undefined ? undefined : text(req.body.attentionId, 128);
513
1398
  const key = req.body?.idempotencyKey === undefined ? randomUUID() : text(req.body.idempotencyKey, 128);
1399
+ const planOnly = req.body?.planOnly === true;
514
1400
  const fingerprint = hashSecret(JSON.stringify({
515
1401
  content,
1402
+ attentionId,
516
1403
  targets,
1404
+ conversationId,
1405
+ kind,
1406
+ requestId: req.body?.requestId,
517
1407
  transfer,
518
1408
  parentTaskId,
1409
+ planOnly,
519
1410
  sourceDeviceId: (agents.get(req) ?? users.get(req))?.device.id,
520
1411
  sourceBotId: agents.has(req) ? req.body?.sourceBotId : undefined,
521
1412
  senderType: agents.has(req) ? "bot" : "human",
@@ -526,10 +1417,46 @@ export async function createDeviceHub(options) {
526
1417
  fail(404, "Room missing");
527
1418
  const source = ownBot(req, draft);
528
1419
  const userSource = users.get(req)?.device;
1420
+ let conversation = conversationId
1421
+ ? draft.conversations.find((c) => c.id === conversationId && c.roomId === room.id && c.accountId === owner.id)
1422
+ : undefined;
1423
+ if (conversationId && !conversation)
1424
+ fail(404, "Conversation missing");
1425
+ if (conversation?.closed)
1426
+ fail(409, "Conversation is closed");
1427
+ if (conversation) {
1428
+ const bot = validBot(draft, conversation.botId, owner.id);
1429
+ if (!bot || bot.revision !== conversation.botRevision || bot.deviceId !== conversation.deviceId)
1430
+ fail(409, "Conversation Bot configuration changed");
1431
+ targets.push(conversation.botId);
1432
+ }
529
1433
  if (source && !room.botIds.includes(source.id))
530
1434
  fail(403, "Source Bot is not a room member");
531
1435
  if (targets.some((id) => !room.botIds.includes(id) || !validBot(draft, id, owner.id)))
532
1436
  fail(400, "Invalid target Bot");
1437
+ if (source &&
1438
+ targets.length &&
1439
+ !draft.tasks.some((t) => t.id === parentTaskId &&
1440
+ t.botId === source.id &&
1441
+ t.accountId === owner.id &&
1442
+ t.roomId === room.id &&
1443
+ (t.status === "running" || isTerminal(t.status))))
1444
+ fail(400, "Device dispatch requires its own bound parent task");
1445
+ {
1446
+ const prior = draft.conversationMessages.find((m) => conversationId !== undefined &&
1447
+ m.conversationId === conversationId &&
1448
+ m.idempotencyKey === key &&
1449
+ draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id && c.accountId === owner.id));
1450
+ if (prior) {
1451
+ if (prior.fingerprint !== fingerprint)
1452
+ fail(409, "Idempotency key reused");
1453
+ return {
1454
+ message: draft.messages.find((m) => m.taskIds.includes(prior.taskId)),
1455
+ tasks: draft.tasks.filter((t) => t.id === prior.taskId),
1456
+ duplicate: true,
1457
+ };
1458
+ }
1459
+ }
533
1460
  const receipt = draft.receipts.find((r) => r.roomId === room.id && r.accountId === owner.id && r.key === key);
534
1461
  if (receipt) {
535
1462
  if (receipt.fingerprint !== fingerprint)
@@ -540,27 +1467,78 @@ export async function createDeviceHub(options) {
540
1467
  duplicate: true,
541
1468
  };
542
1469
  }
1470
+ // Resolve implicit human targets after replay detection so retries remain stable across configuration changes.
1471
+ if (!source && !conversationApi && !targets.length && room.primaryBotId) {
1472
+ if (!room.botIds.includes(room.primaryBotId) || !validBot(draft, room.primaryBotId, owner.id))
1473
+ fail(400, "Primary Bot is unavailable");
1474
+ targets.push(room.primaryBotId);
1475
+ const bot = validBot(draft, room.primaryBotId, owner.id);
1476
+ conversation = draft.conversations
1477
+ .filter((entry) => entry.roomId === room.id &&
1478
+ entry.accountId === owner.id &&
1479
+ entry.botId === bot.id &&
1480
+ !entry.closed &&
1481
+ entry.botRevision === bot.revision &&
1482
+ entry.deviceId === bot.deviceId)
1483
+ .sort((a, b) => b.updatedAt - a.updatedAt)[0];
1484
+ }
1485
+ if (attentionId) {
1486
+ if (source || !conversationId || !conversation || conversation.attention?.id !== attentionId)
1487
+ fail(409, "Question changed or already answered");
1488
+ delete conversation.attention;
1489
+ }
1490
+ if (kind === "reply") {
1491
+ const request = draft.conversationMessages.find((m) => m.kind === "request" &&
1492
+ m.requestId === requestId &&
1493
+ draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id && c.accountId === owner.id));
1494
+ const requestedConversation = draft.conversations.find((c) => c.id === request?.conversationId);
1495
+ if (!request ||
1496
+ !requestedConversation ||
1497
+ source?.id !== requestedConversation.botId ||
1498
+ !conversation ||
1499
+ conversation.botId !== request.sourceBotId ||
1500
+ conversation.id !== draft.tasks.find((t) => t.id === request.taskId)?.sourceConversationId ||
1501
+ draft.tasks.find((t) => t.id === parentTaskId)?.conversationId !== request.conversationId)
1502
+ fail(403, "Reply must address the original requester from the requested Bot");
1503
+ if (draft.tasks.some((t) => t.resultOfTaskId === request.taskId))
1504
+ fail(409, "Request already completed");
1505
+ if (draft.conversationMessages.some((m) => m.kind === "reply" &&
1506
+ m.requestId === requestId &&
1507
+ m.idempotencyKey !== key &&
1508
+ draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id)))
1509
+ fail(409, "Request already answered");
1510
+ }
543
1511
  if (parentTaskId &&
544
1512
  !draft.tasks.some((t) => t.id === parentTaskId &&
545
1513
  t.roomId === room.id &&
546
1514
  t.accountId === owner.id &&
547
1515
  (isTerminal(t.status) || (source?.id === t.botId && t.status === "running"))))
548
1516
  fail(400, "Parent task must be terminal or the source device's running task in this room");
1517
+ if (kind === "request" &&
1518
+ draft.conversationMessages.some((m) => m.kind === "request" &&
1519
+ m.requestId === requestId &&
1520
+ draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id)))
1521
+ fail(409, "Request ID already exists");
549
1522
  const parent = parentTaskId ? draft.tasks.find((t) => t.id === parentTaskId) : undefined;
550
1523
  if (source && targets.length && (!parent || parent.botId !== source.id))
551
1524
  fail(400, "Device dispatch requires its own running or terminal parent task");
1525
+ // Explicit human input grants a new lineage; autonomous work always inherits its real parent.
552
1526
  const root = parent ? draft.tasks.find((t) => t.id === (parent.rootTaskId ?? parent.id)) : undefined;
553
1527
  if (parent && targets.length && !root)
554
1528
  fail(409, "Dispatch root expired");
555
1529
  const depth = parent ? (parent.dispatchDepth ?? 0) + 1 : 0;
1530
+ if (planOnly && targets.some((id) => !validBot(draft, id, owner.id)?.tools?.includes("plan_update")))
1531
+ fail(409, "Planning requires plan_update authorization in each Bot tool allowlist");
556
1532
  if (targets.length && depth > 8)
557
1533
  fail(409, "Dispatch depth exhausted");
558
1534
  if (targets.length && (root?.dispatchCount ?? 0) + targets.length > 16)
559
1535
  fail(409, "Dispatch budget exhausted");
560
1536
  if (root && targets.length)
561
1537
  root.dispatchCount = (root.dispatchCount ?? 0) + targets.length;
562
- if (draft.tasks.filter((t) => t.roomId === room.id && !isTerminal(t.status)).length + targets.length > HISTORY)
1538
+ if (draft.tasks.filter((t) => t.roomId === room.id && taskPending(t)).length + targets.length > HISTORY)
563
1539
  fail(409, "Too many active tasks");
1540
+ if (!conversation && draft.conversations.filter((c) => c.roomId === room.id).length + targets.length > HISTORY)
1541
+ fail(409, "Conversation capacity reached; clear completed history first");
564
1542
  const now = Date.now();
565
1543
  const rootId = root?.id ?? randomUUID();
566
1544
  const tasks = targets.map((botId, index) => ({
@@ -579,9 +1557,26 @@ export async function createDeviceHub(options) {
579
1557
  status: "queued",
580
1558
  createdAt: now,
581
1559
  updatedAt: now,
1560
+ ...(planOnly ? { planOnly: true, plan: { state: "draft", steps: [] } } : {}),
582
1561
  ...(transfer ? { handoff: transfer } : {}),
583
1562
  ...(parentTaskId ? { parentTaskId } : {}),
584
1563
  }));
1564
+ for (const task of tasks) {
1565
+ task.kind = kind;
1566
+ task.sourceConversationId = parent?.conversationId;
1567
+ task.requestId = requestId;
1568
+ if (conversation) {
1569
+ task.conversationId = conversation.id;
1570
+ task.resume = true;
1571
+ advanceConversationTask(draft, conversation, task);
1572
+ conversation.rootTaskId = task.rootTaskId;
1573
+ conversation.updatedAt = now;
1574
+ conversation.dispatchDepth = depth;
1575
+ }
1576
+ else
1577
+ establishConversation(draft, task);
1578
+ recordConversationTurn(draft, task, key, fingerprint);
1579
+ }
585
1580
  const message = {
586
1581
  id: randomUUID(),
587
1582
  roomId: room.id,
@@ -598,7 +1593,11 @@ export async function createDeviceHub(options) {
598
1593
  createdAt: now,
599
1594
  taskIds: tasks.map((t) => t.id),
600
1595
  targetBotIds: targets,
1596
+ ...(tasks.length === 1 ? { conversationId: tasks[0].conversationId } : {}),
1597
+ ...(tasks.length ? { conversationIds: tasks.map((task) => task.conversationId) } : {}),
601
1598
  };
1599
+ // Freeze shared context before any recipient starts. Parallel answers cannot leak into siblings.
1600
+ const context = tasks.length ? groupTaskContext(room, draft.bots, draft.messages) : undefined;
602
1601
  draft.tasks.push(...tasks);
603
1602
  draft.messages.push(message);
604
1603
  draft.receipts.push({ accountId: owner.id, roomId: room.id, key, fingerprint, messageId: message.id });
@@ -607,60 +1606,28 @@ export async function createDeviceHub(options) {
607
1606
  draft.messages = draft.messages.filter((m) => !removed.has(m.id));
608
1607
  draft.receipts = draft.receipts.filter((r) => !removed.has(r.messageId));
609
1608
  const oldTasks = new Set(draft.tasks
610
- .filter((t) => t.roomId === room.id && isTerminal(t.status))
1609
+ .filter((t) => t.roomId === room.id &&
1610
+ isTerminal(t.status) &&
1611
+ !draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
611
1612
  .slice(0, -HISTORY)
612
1613
  .map((t) => t.id));
613
1614
  draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
614
- return { message, tasks, duplicate: false };
1615
+ trimConversationHistory(draft, room.id);
1616
+ return { message, tasks, duplicate: false, context };
615
1617
  });
616
- if (!result.duplicate) {
617
- for (const task of result.tasks) {
618
- const deliver = options.onTask ?? options.relay?.onTask;
619
- try {
620
- const latest = store.snapshot();
621
- if (validBot(latest, task.botId, task.accountId)?.revision !== task.botRevision ||
622
- !latest.rooms.some((r) => r.id === task.roomId && r.botIds.includes(task.botId)))
623
- throw new Error("Bot no longer available");
624
- if (!deliver || (await deliver(task.deviceId, task)) === false)
625
- throw new Error("Delivery rejected");
626
- }
627
- catch {
628
- await store.transact((draft) => {
629
- const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
630
- if (!current || isTerminal(current.status))
631
- return;
632
- const report = "Task delivery failed; submit a new request to retry.";
633
- current.status = "failed";
634
- current.updatedAt = Date.now();
635
- current.report = report;
636
- draft.messages.push({
637
- id: randomUUID(),
638
- roomId: current.roomId,
639
- accountId: current.accountId,
640
- text: report,
641
- sender: {
642
- type: "bot",
643
- id: current.botId,
644
- name: draft.bots.find((bot) => bot.id === current.botId)?.name ?? current.botId,
645
- sourceDeviceId: current.deviceId,
646
- },
647
- createdAt: current.updatedAt,
648
- taskIds: [current.id],
649
- });
650
- const remove = new Set(draft.messages
651
- .filter((message) => message.roomId === current.roomId)
652
- .slice(0, -HISTORY)
653
- .map((message) => message.id));
654
- draft.messages = draft.messages.filter((message) => !remove.has(message.id));
655
- draft.receipts = draft.receipts.filter((receipt) => !remove.has(receipt.messageId));
656
- });
657
- }
658
- }
659
- }
1618
+ if (!result.duplicate)
1619
+ for (const task of result.tasks)
1620
+ await deliverTask(task, result.context);
660
1621
  const state = store.snapshot();
661
1622
  res.json({
1623
+ ...(conversationApi
1624
+ ? {
1625
+ conversation: state.conversations.find((c) => c.id === result.tasks[0]?.conversationId),
1626
+ task: ((t) => (t ? publicTask(t) : undefined))(state.tasks.find((t) => t.id === result.tasks[0]?.id)),
1627
+ }
1628
+ : {}),
662
1629
  message: result.message,
663
- tasks: result.tasks.map((task) => state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId) ?? task),
1630
+ tasks: result.tasks.map((task) => publicTask(state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId) ?? task)),
664
1631
  });
665
1632
  });
666
1633
  for (const action of ["alias", "portal"])
@@ -754,6 +1721,118 @@ export async function createDeviceHub(options) {
754
1721
  return;
755
1722
  app(req, res);
756
1723
  });
1724
+ // Accepted queued tasks remain in flight until a terminal event, including asynchronous relay delivery.
1725
+ const deliveredTasks = new Set();
1726
+ async function drainConversation(conversationId) {
1727
+ if (!conversationId)
1728
+ return;
1729
+ const state = store.snapshot();
1730
+ const next = nextConversationTask(state, conversationId);
1731
+ if (!next || deliveredTasks.has(next.id))
1732
+ return;
1733
+ const room = state.rooms.find((entry) => entry.id === next.roomId);
1734
+ await deliverTask(next, room ? groupTaskContext(room, state.bots, state.messages) : undefined);
1735
+ }
1736
+ async function deliverTask(task, context) {
1737
+ if (deliveredTasks.has(task.id))
1738
+ return;
1739
+ if (task.conversationId && nextConversationTask(store.snapshot(), task.conversationId)?.id !== task.id)
1740
+ return;
1741
+ deliveredTasks.add(task.id);
1742
+ const deliver = options.onTask ?? options.relay?.onTask;
1743
+ try {
1744
+ const latest = store.snapshot();
1745
+ if (latest.tasks.find((t) => t.id === task.id)?.cancelRequested ||
1746
+ latest.conversations.find((c) => c.id === task.conversationId)?.closed ||
1747
+ validBot(latest, task.botId, task.accountId)?.revision !== task.botRevision ||
1748
+ !latest.rooms.some((r) => r.id === task.roomId && r.botIds.includes(task.botId)))
1749
+ throw new Error("Bot no longer available");
1750
+ await store.transact((draft) => {
1751
+ const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
1752
+ if (current) {
1753
+ current.leaseToken = randomUUID();
1754
+ current.leaseGeneration = (current.leaseGeneration ?? 0) + 1;
1755
+ current.lastHeartbeatAt = Date.now();
1756
+ task.leaseToken = current.leaseToken;
1757
+ task.leaseGeneration = current.leaseGeneration;
1758
+ }
1759
+ const conversation = draft.conversations.find((entry) => entry.id === task.conversationId);
1760
+ if (conversation && !conversation.closed) {
1761
+ conversation.latestTaskId = task.id;
1762
+ conversation.updatedAt = Date.now();
1763
+ }
1764
+ });
1765
+ const committed = store.snapshot();
1766
+ if (committed.tasks.find((entry) => entry.id === task.id)?.cancelRequested ||
1767
+ committed.conversations.find((entry) => entry.id === task.conversationId)?.closed)
1768
+ throw new Error("Conversation stopped before delivery");
1769
+ const taskState = committed.conversations.find((entry) => entry.id === task.conversationId)?.taskState;
1770
+ if (!deliver ||
1771
+ (await deliver(task.deviceId, {
1772
+ ...task,
1773
+ leaseToken: task.leaseToken,
1774
+ leaseGeneration: task.leaseGeneration,
1775
+ context,
1776
+ taskState,
1777
+ })) === false)
1778
+ throw new Error("Delivery rejected");
1779
+ }
1780
+ catch {
1781
+ const failure = await store.transact((draft) => {
1782
+ const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
1783
+ if (!current || isTerminal(current.status) || current.cancelRequested)
1784
+ return;
1785
+ const report = "Task delivery failed; submit a new request to retry.";
1786
+ current.status = "failed";
1787
+ current.updatedAt = Date.now();
1788
+ current.report = report;
1789
+ if (current.conversationId)
1790
+ draft.conversationMessages.push({
1791
+ id: randomUUID(),
1792
+ conversationId: current.conversationId,
1793
+ taskId: current.id,
1794
+ kind: "result",
1795
+ text: report,
1796
+ sourceBotId: current.botId,
1797
+ requestId: current.requestId,
1798
+ createdAt: current.updatedAt,
1799
+ });
1800
+ const room = draft.rooms.find((r) => r.id === current.roomId);
1801
+ const context = room ? groupTaskContext(room, draft.bots, draft.messages) : undefined;
1802
+ const wake = queueParentResult(draft, current);
1803
+ draft.messages.push({
1804
+ id: randomUUID(),
1805
+ roomId: current.roomId,
1806
+ accountId: current.accountId,
1807
+ text: report,
1808
+ sender: {
1809
+ type: "bot",
1810
+ id: current.botId,
1811
+ name: draft.bots.find((bot) => bot.id === current.botId)?.name ?? current.botId,
1812
+ sourceDeviceId: current.deviceId,
1813
+ },
1814
+ createdAt: current.updatedAt,
1815
+ taskIds: [current.id],
1816
+ });
1817
+ const remove = new Set(draft.messages
1818
+ .filter((message) => message.roomId === current.roomId)
1819
+ .slice(0, -HISTORY)
1820
+ .map((message) => message.id));
1821
+ draft.messages = draft.messages.filter((message) => !remove.has(message.id));
1822
+ draft.receipts = draft.receipts.filter((receipt) => !remove.has(receipt.messageId));
1823
+ trimConversationHistory(draft, current.roomId);
1824
+ return { wake, context };
1825
+ });
1826
+ if (failure?.wake)
1827
+ await deliverTask(failure.wake, failure.context);
1828
+ }
1829
+ finally {
1830
+ if (isTerminal(store.snapshot().tasks.find((entry) => entry.id === task.id)?.status ?? "interrupted")) {
1831
+ deliveredTasks.delete(task.id);
1832
+ await drainConversation(task.conversationId);
1833
+ }
1834
+ }
1835
+ }
757
1836
  async function acceptTaskEvent(deviceId, event) {
758
1837
  if (!event ||
759
1838
  typeof event.taskId !== "string" ||
@@ -761,10 +1840,24 @@ export async function createDeviceHub(options) {
761
1840
  typeof event.botId !== "string" ||
762
1841
  !["running", "completed", "failed", "interrupted"].includes(event.status))
763
1842
  fail(400, "Invalid task event");
764
- const report = event.report === undefined ? undefined : text(event.report);
1843
+ const report = event.report === undefined
1844
+ ? event.status === "failed"
1845
+ ? "Task execution failed without a report."
1846
+ : event.status === "interrupted"
1847
+ ? "Task execution was interrupted without a report."
1848
+ : undefined
1849
+ : text(event.report);
765
1850
  if (event.status === "completed" && !report)
766
1851
  fail(400, "Completed task requires agent report");
767
- return store.transact((draft) => {
1852
+ let reportMetadata;
1853
+ try {
1854
+ if (event.reportMetadata !== undefined)
1855
+ reportMetadata = parseReportMetadata(event.reportMetadata);
1856
+ }
1857
+ catch {
1858
+ fail(400, "Invalid report metadata");
1859
+ }
1860
+ const result = await store.transact((draft) => {
768
1861
  const device = draft.devices.find((d) => d.id === deviceId);
769
1862
  const task = draft.tasks.find((t) => t.id === event.taskId &&
770
1863
  t.deviceId === deviceId &&
@@ -776,15 +1869,33 @@ export async function createDeviceHub(options) {
776
1869
  fail(404, "Task missing");
777
1870
  if (event.status !== "interrupted" && (!bot.enabled || bot.revision !== task.botRevision))
778
1871
  fail(409, "Bot configuration changed");
1872
+ if (isTerminal(event.status)) {
1873
+ const stored = taskReportStore.getReportMeta(task.id, task.attemptId, task.accountId, task.roomId);
1874
+ task.reportMetadata = stored?.complete
1875
+ ? {
1876
+ sha256: stored.sha256,
1877
+ totalBytes: stored.totalBytes,
1878
+ missing: false,
1879
+ rejected: false,
1880
+ uploadPending: false,
1881
+ }
1882
+ : (reportMetadata ?? task.reportMetadata ?? reportUploadMetadata());
1883
+ }
779
1884
  if (task.status === event.status) {
780
- if (task.report !== report)
1885
+ if (task.report && report && task.report !== report)
781
1886
  fail(409, "Conflicting duplicate event");
782
- return task;
1887
+ return { task };
1888
+ }
1889
+ // Allow safe outbox replay or recovery adoption if task was marked interrupted during restart/disconnect
1890
+ const inRecovery = typeof task.recoveryUntil === "number" && Date.now() <= task.recoveryUntil;
1891
+ const canAdoptInterrupted = (inRecovery || task.status === "interrupted") && (event.status === "completed" || event.status === "failed");
1892
+ if (!canAdoptInterrupted) {
1893
+ if (isTerminal(task.status) ||
1894
+ (task.status === "queued" && event.status !== "running" && event.status !== "interrupted") ||
1895
+ (task.status === "running" && !isTerminal(event.status)))
1896
+ fail(409, "Invalid task transition");
783
1897
  }
784
- if (isTerminal(task.status) ||
785
- (task.status === "queued" && event.status !== "running" && event.status !== "interrupted") ||
786
- (task.status === "running" && !isTerminal(event.status)))
787
- fail(409, "Invalid task transition");
1898
+ delete task.recoveryUntil;
788
1899
  task.status = event.status;
789
1900
  task.updatedAt = Date.now();
790
1901
  if (report)
@@ -798,7 +1909,19 @@ export async function createDeviceHub(options) {
798
1909
  sender: { type: "bot", id: bot.id, name: bot.name, sourceDeviceId: deviceId },
799
1910
  createdAt: Date.now(),
800
1911
  taskIds: [task.id],
1912
+ conversationId: task.conversationId,
801
1913
  });
1914
+ if (task.conversationId)
1915
+ draft.conversationMessages.push({
1916
+ id: randomUUID(),
1917
+ conversationId: task.conversationId,
1918
+ taskId: task.id,
1919
+ kind: "result",
1920
+ text: report,
1921
+ sourceBotId: bot.id,
1922
+ requestId: task.requestId,
1923
+ createdAt: Date.now(),
1924
+ });
802
1925
  const remove = new Set(draft.messages
803
1926
  .filter((m) => m.roomId === task.roomId)
804
1927
  .slice(0, -HISTORY)
@@ -806,21 +1929,362 @@ export async function createDeviceHub(options) {
806
1929
  draft.messages = draft.messages.filter((m) => !remove.has(m.id));
807
1930
  draft.receipts = draft.receipts.filter((r) => !remove.has(r.messageId));
808
1931
  }
809
- return task;
1932
+ const room = draft.rooms.find((r) => r.id === task.roomId);
1933
+ const context = groupTaskContext(room, draft.bots, draft.messages);
1934
+ const wake = queueParentResult(draft, task);
1935
+ trimConversationHistory(draft, task.roomId);
1936
+ return { task, wake, context };
1937
+ });
1938
+ if (result?.task) {
1939
+ taskJournalManager
1940
+ .append(result.task.id, {
1941
+ botId: result.task.botId,
1942
+ attemptId: result.task.attemptId,
1943
+ type: "status",
1944
+ phase: event.status,
1945
+ summary: `Task ${event.status}${report ? ": " + report.slice(0, 100) : ""}`,
1946
+ output: report,
1947
+ }, { roomId: result.task.roomId, accountId: result.task.accountId })
1948
+ .catch((cause) => {
1949
+ console.warn(`[TaskJournal] Journal append failed for task ${result.task.id}:`, cause);
1950
+ });
1951
+ }
1952
+ if (isTerminal(result.task.status))
1953
+ deliveredTasks.delete(result.task.id);
1954
+ if (result.wake)
1955
+ await deliverTask(result.wake, result.context);
1956
+ await drainConversation(result.task.conversationId);
1957
+ return result.task;
1958
+ }
1959
+ // === Hub Restart Recovery Window ===
1960
+ const nowInit = Date.now();
1961
+ const recoveryGraceMs = 60_000;
1962
+ try {
1963
+ await store.transact((draft) => {
1964
+ for (const task of draft.tasks) {
1965
+ if (task.status === "running") {
1966
+ task.recoveryUntil = nowInit + recoveryGraceMs;
1967
+ }
1968
+ }
1969
+ });
1970
+ }
1971
+ catch (err) {
1972
+ console.error("DEBUG store.transact failed:", err);
1973
+ }
1974
+ let sweepInflight = false;
1975
+ const recoverySweepTimer = setInterval(() => {
1976
+ if (sweepInflight)
1977
+ return;
1978
+ const sweepNow = Date.now();
1979
+ const snapshot = store.snapshot();
1980
+ const hasDue = snapshot.tasks.some((t) => (t.recoveryUntil && sweepNow > t.recoveryUntil) ||
1981
+ (t.status === "running" && t.lastHeartbeatAt && sweepNow - t.lastHeartbeatAt > 30 * 60_000));
1982
+ if (!hasDue)
1983
+ return;
1984
+ sweepInflight = true;
1985
+ void (async () => {
1986
+ try {
1987
+ const settledWakes = [];
1988
+ await store.transact((draft) => {
1989
+ for (const task of draft.tasks) {
1990
+ const windowExpired = task.recoveryUntil && sweepNow > task.recoveryUntil;
1991
+ const leaseExpired = task.status === "running" && task.lastHeartbeatAt && sweepNow - task.lastHeartbeatAt > 30 * 60_000;
1992
+ if (windowExpired || leaseExpired) {
1993
+ delete task.recoveryUntil;
1994
+ if (task.status === "running") {
1995
+ task.status = "interrupted";
1996
+ task.updatedAt = sweepNow;
1997
+ const report = windowExpired
1998
+ ? "Hub restarted; recovery window expired without reconnect claim."
1999
+ : "Task lease expired due to prolonged inactivity.";
2000
+ task.report = report;
2001
+ const room = draft.rooms.find((r) => r.id === task.roomId);
2002
+ const context = room ? groupTaskContext(room, draft.bots, draft.messages) : undefined;
2003
+ const wake = queueParentResult(draft, task);
2004
+ trimConversationHistory(draft, task.roomId);
2005
+ settledWakes.push({ wake, context, conversationId: task.conversationId, taskId: task.id });
2006
+ }
2007
+ }
2008
+ }
2009
+ });
2010
+ for (const item of settledWakes) {
2011
+ deliveredTasks.delete(item.taskId);
2012
+ if (item.wake)
2013
+ await deliverTask(item.wake, item.context);
2014
+ await drainConversation(item.conversationId);
2015
+ }
2016
+ }
2017
+ catch {
2018
+ console.warn("[HubRecovery] Sweep transaction failed");
2019
+ }
2020
+ finally {
2021
+ sweepInflight = false;
2022
+ }
2023
+ })();
2024
+ }, 10_000);
2025
+ recoverySweepTimer.unref();
2026
+ async function claimTask(deviceId, claim) {
2027
+ if (!claim ||
2028
+ typeof claim.taskId !== "string" ||
2029
+ typeof claim.attemptId !== "string" ||
2030
+ typeof claim.botId !== "string" ||
2031
+ typeof claim.leaseToken !== "string" ||
2032
+ !claim.leaseToken) {
2033
+ return {
2034
+ taskId: claim?.taskId ?? "",
2035
+ attemptId: claim?.attemptId ?? "",
2036
+ accepted: false,
2037
+ reason: "Invalid claim payload or missing leaseToken",
2038
+ };
2039
+ }
2040
+ return await store.transact((draft) => {
2041
+ const device = draft.devices.find((d) => d.id === deviceId);
2042
+ const task = draft.tasks.find((t) => t.id === claim.taskId &&
2043
+ t.deviceId === deviceId &&
2044
+ t.botId === claim.botId &&
2045
+ t.attemptId === claim.attemptId &&
2046
+ t.accountId === device?.accountId);
2047
+ if (!task || !device) {
2048
+ return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Task not found" };
2049
+ }
2050
+ const inRecovery = typeof task.recoveryUntil === "number" && Date.now() <= task.recoveryUntil;
2051
+ const isDisconnectInterrupted = task.status === "interrupted" &&
2052
+ !task.cancelRequested &&
2053
+ !task.stopConfirmed &&
2054
+ Date.now() - task.updatedAt <= 60_000;
2055
+ if (isTerminal(task.status) && !inRecovery && !isDisconnectInterrupted) {
2056
+ return {
2057
+ taskId: claim.taskId,
2058
+ attemptId: claim.attemptId,
2059
+ accepted: false,
2060
+ reason: "Task already terminated",
2061
+ };
2062
+ }
2063
+ if (task.cancelRequested || task.stopConfirmed) {
2064
+ return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Task stop requested" };
2065
+ }
2066
+ const bot = draft.bots.find((b) => b.id === task.botId && b.deviceId === deviceId && b.accountId === device.accountId);
2067
+ if (!bot || !bot.enabled || bot.revision !== task.botRevision) {
2068
+ return {
2069
+ taskId: claim.taskId,
2070
+ attemptId: claim.attemptId,
2071
+ accepted: false,
2072
+ reason: "Bot configuration changed or disabled",
2073
+ };
2074
+ }
2075
+ const room = draft.rooms.find((r) => r.id === task.roomId && r.botIds.includes(task.botId));
2076
+ if (!room) {
2077
+ return {
2078
+ taskId: claim.taskId,
2079
+ attemptId: claim.attemptId,
2080
+ accepted: false,
2081
+ reason: "Bot no longer member of room",
2082
+ };
2083
+ }
2084
+ if (task.leaseToken !== claim.leaseToken) {
2085
+ return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Lease token mismatch" };
2086
+ }
2087
+ if (task.leaseGeneration !== undefined && claim.leaseGeneration !== task.leaseGeneration) {
2088
+ return {
2089
+ taskId: claim.taskId,
2090
+ attemptId: claim.attemptId,
2091
+ accepted: false,
2092
+ reason: "Lease generation mismatch",
2093
+ };
2094
+ }
2095
+ if (task.status !== "running" && !inRecovery && !isDisconnectInterrupted) {
2096
+ return {
2097
+ taskId: claim.taskId,
2098
+ attemptId: claim.attemptId,
2099
+ accepted: false,
2100
+ reason: "Task not running or recovery window closed",
2101
+ };
2102
+ }
2103
+ delete task.recoveryUntil;
2104
+ task.status = "running";
2105
+ task.updatedAt = Date.now();
2106
+ task.lastHeartbeatAt = Date.now();
2107
+ return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: true };
2108
+ });
2109
+ }
2110
+ async function renewTaskLease(deviceId, renew) {
2111
+ if (!renew ||
2112
+ typeof renew.taskId !== "string" ||
2113
+ typeof renew.attemptId !== "string" ||
2114
+ typeof renew.botId !== "string" ||
2115
+ typeof renew.leaseToken !== "string" ||
2116
+ !renew.leaseToken) {
2117
+ return {
2118
+ taskId: renew?.taskId ?? "",
2119
+ attemptId: renew?.attemptId ?? "",
2120
+ accepted: false,
2121
+ reason: "Invalid renew payload or missing leaseToken",
2122
+ };
2123
+ }
2124
+ return await store.transact((draft) => {
2125
+ const device = draft.devices.find((d) => d.id === deviceId);
2126
+ const task = draft.tasks.find((t) => t.id === renew.taskId &&
2127
+ t.deviceId === deviceId &&
2128
+ t.botId === renew.botId &&
2129
+ t.attemptId === renew.attemptId &&
2130
+ t.accountId === device?.accountId);
2131
+ if (!task || !device || task.status !== "running") {
2132
+ return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task not running" };
2133
+ }
2134
+ if (task.cancelRequested || task.stopConfirmed) {
2135
+ return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task stop requested" };
2136
+ }
2137
+ if (task.leaseToken !== renew.leaseToken) {
2138
+ return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Lease token mismatch" };
2139
+ }
2140
+ if (task.leaseGeneration !== undefined && renew.leaseGeneration !== task.leaseGeneration) {
2141
+ return {
2142
+ taskId: renew.taskId,
2143
+ attemptId: renew.attemptId,
2144
+ accepted: false,
2145
+ reason: "Lease generation mismatch",
2146
+ };
2147
+ }
2148
+ const bot = draft.bots.find((b) => b.id === task.botId && b.deviceId === deviceId && b.accountId === device.accountId);
2149
+ if (!bot || !bot.enabled || bot.revision !== task.botRevision) {
2150
+ return {
2151
+ taskId: renew.taskId,
2152
+ attemptId: renew.attemptId,
2153
+ accepted: false,
2154
+ reason: "Bot configuration changed or disabled",
2155
+ };
2156
+ }
2157
+ const room = draft.rooms.find((r) => r.id === task.roomId && r.botIds.includes(task.botId));
2158
+ if (!room) {
2159
+ return {
2160
+ taskId: renew.taskId,
2161
+ attemptId: renew.attemptId,
2162
+ accepted: false,
2163
+ reason: "Bot no longer member of room",
2164
+ };
2165
+ }
2166
+ const hasActiveInteraction = liveInteractions(task.roomId, task.accountId).some((i) => i.taskId === task.id);
2167
+ const now = Date.now();
2168
+ if (renew.hasActivity || hasActiveInteraction) {
2169
+ task.lastHeartbeatAt = now;
2170
+ task.updatedAt = now;
2171
+ }
2172
+ return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: true };
2173
+ });
2174
+ }
2175
+ const toolLifecycleSeqs = new Map();
2176
+ async function acceptTaskToolLifecycle(deviceId, frame) {
2177
+ const state = store.snapshot();
2178
+ const device = state.devices.find((d) => d.id === deviceId);
2179
+ const task = state.tasks.find((t) => t.id === frame.taskId &&
2180
+ t.deviceId === deviceId &&
2181
+ t.botId === frame.botId &&
2182
+ t.attemptId === frame.attemptId &&
2183
+ t.accountId === device?.accountId);
2184
+ if (!task || !device)
2185
+ return;
2186
+ const room = state.rooms.find((r) => r.id === task.roomId && r.accountId === task.accountId);
2187
+ if (!room)
2188
+ return;
2189
+ // Deduplicate and enforce monotonic sequence if provided
2190
+ if (typeof frame.sequence === "number" && Number.isSafeInteger(frame.sequence)) {
2191
+ const seqKey = `${task.id}:${task.attemptId}`;
2192
+ const prevSeq = toolLifecycleSeqs.get(seqKey);
2193
+ if (prevSeq !== undefined && frame.sequence <= prevSeq)
2194
+ return;
2195
+ toolLifecycleSeqs.set(seqKey, frame.sequence);
2196
+ }
2197
+ const typeMapping = {
2198
+ start: "tool_start",
2199
+ progress: "tool_progress",
2200
+ end: "tool_end",
2201
+ failed: "tool_failed",
2202
+ };
2203
+ const entryType = typeMapping[frame.phase] || "tool_progress";
2204
+ await taskJournalManager
2205
+ .append(task.id, {
2206
+ botId: task.botId,
2207
+ attemptId: task.attemptId,
2208
+ type: entryType,
2209
+ phase: "running",
2210
+ toolName: frame.toolName,
2211
+ toolCallId: frame.callId,
2212
+ summary: frame.summary,
2213
+ parametersPreview: frame.parametersPreview,
2214
+ output: frame.outputSnippet,
2215
+ }, { roomId: task.roomId, accountId: task.accountId })
2216
+ .catch((err) => {
2217
+ console.warn(`[TaskJournal] Tool lifecycle append error for ${task.id}:`, err);
2218
+ });
2219
+ }
2220
+ async function acceptTaskPlanReady(deviceId, frame) {
2221
+ if (!frame ||
2222
+ typeof frame.taskId !== "string" ||
2223
+ typeof frame.botId !== "string" ||
2224
+ typeof frame.attemptId !== "string")
2225
+ return false;
2226
+ const plan = validateTaskPlan(frame.plan);
2227
+ if (!plan)
2228
+ return false;
2229
+ return store.transact((draft) => {
2230
+ const device = draft.devices.find((d) => d.id === deviceId);
2231
+ const task = draft.tasks.find((t) => t.id === frame.taskId &&
2232
+ t.deviceId === deviceId &&
2233
+ t.botId === frame.botId &&
2234
+ t.attemptId === frame.attemptId &&
2235
+ t.accountId === device?.accountId);
2236
+ if (!device || !task)
2237
+ return false;
2238
+ const bot = draft.bots.find((b) => b.id === frame.botId && b.deviceId === deviceId && b.accountId === device.accountId);
2239
+ if (!bot || !bot.enabled || bot.revision !== task.botRevision)
2240
+ return false;
2241
+ const room = draft.rooms.find((r) => r.id === task.roomId && r.accountId === task.accountId && r.botIds.includes(bot.id));
2242
+ if (!room ||
2243
+ !task.planOnly ||
2244
+ task.status !== "running" ||
2245
+ task.plan?.state === "approved" ||
2246
+ (bot.tools && !bot.tools.includes("plan_update")))
2247
+ return false;
2248
+ if (task.plan?.state === "ready")
2249
+ return JSON.stringify(task.plan) === JSON.stringify(plan);
2250
+ task.plan = plan;
2251
+ task.updatedAt = Date.now();
2252
+ return true;
2253
+ });
2254
+ }
2255
+ async function onTaskDisconnect(deviceId, taskId, attemptId) {
2256
+ const now = Date.now();
2257
+ const recoveryGraceMs = 60_000;
2258
+ await store.transact((draft) => {
2259
+ const task = draft.tasks.find((t) => t.id === taskId && t.deviceId === deviceId && t.attemptId === attemptId);
2260
+ if (task && task.status === "running") {
2261
+ task.recoveryUntil = now + recoveryGraceMs;
2262
+ task.updatedAt = now;
2263
+ }
810
2264
  });
811
2265
  }
812
2266
  return {
813
2267
  app,
814
2268
  server,
815
2269
  store,
2270
+ claimTask,
2271
+ renewTaskLease,
2272
+ onTaskDisconnect,
816
2273
  getAccount,
817
- getRelayAccount: (req) => users.get(req)?.account ?? getAccount(req),
2274
+ getRelayAccount: (req) => users.get(req)?.account ?? getAccount(req) ?? undefined,
818
2275
  authenticateAgent,
819
2276
  acceptTaskEvent,
2277
+ acceptInteractions,
2278
+ acceptTaskProgress: groupEvents.accept,
2279
+ acceptTaskToolLifecycle,
2280
+ acceptTaskPlanReady,
820
2281
  setRelay(relay) {
821
2282
  options.relay = relay;
822
2283
  },
823
2284
  async close() {
2285
+ clearInterval(recoverySweepTimer);
2286
+ await groupEvents.close();
2287
+ await taskJournalManager.close();
824
2288
  pairs.clear();
825
2289
  if (server.listening)
826
2290
  await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));