pi-web-ui 0.114.3 → 0.116.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/bin/pi-web-ui.mjs +90 -8
  3. package/dist/gh-comment-781.md +5 -0
  4. package/dist/server/agent-service-daemon.js +522 -32
  5. package/dist/server/agent-service.js +954 -402
  6. package/dist/server/canvas/canvas-dispatch.js +13 -1
  7. package/dist/server/client-state.js +42 -2
  8. package/dist/server/communicate-tool.js +2 -0
  9. package/dist/server/conversation-communication.js +14 -0
  10. package/dist/server/conversation-identity.js +27 -0
  11. package/dist/server/device-center/approval-summary.js +31 -0
  12. package/dist/server/device-center/bot-catalog.js +21 -7
  13. package/dist/server/device-center/bot-execution.js +100 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +362 -13
  16. package/dist/server/device-center/collab-tool.js +824 -13
  17. package/dist/server/device-center/connector.js +359 -23
  18. package/dist/server/device-center/desktop-page.js +22 -16
  19. package/dist/server/device-center/device-integration.js +595 -0
  20. package/dist/server/device-center/execution-guides.js +32 -0
  21. package/dist/server/device-center/execution-instructions.js +20 -0
  22. package/dist/server/device-center/execution-settings.js +213 -0
  23. package/dist/server/device-center/execution-system-prompt.js +38 -0
  24. package/dist/server/device-center/execution-workspace.js +20 -0
  25. package/dist/server/device-center/executor.js +392 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +186 -96
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +210 -0
  30. package/dist/server/device-center/group-context.js +179 -0
  31. package/dist/server/device-center/group-events.js +136 -0
  32. package/dist/server/device-center/group-plan-guard.js +138 -0
  33. package/dist/server/device-center/hub-conversations.js +233 -0
  34. package/dist/server/device-center/hub-deliveries.js +277 -0
  35. package/dist/server/device-center/hub-integration.js +451 -0
  36. package/dist/server/device-center/hub-locks.js +320 -0
  37. package/dist/server/device-center/hub-page.js +13 -33
  38. package/dist/server/device-center/hub-webhooks.js +165 -0
  39. package/dist/server/device-center/hub.js +2379 -107
  40. package/dist/server/device-center/human-interaction.js +232 -0
  41. package/dist/server/device-center/integration-errors.js +25 -0
  42. package/dist/server/device-center/local-hub.js +20 -1
  43. package/dist/server/device-center/local-page.js +17 -0
  44. package/dist/server/device-center/local.js +430 -41
  45. package/dist/server/device-center/main.js +11 -1
  46. package/dist/server/device-center/partition-log.js +293 -0
  47. package/dist/server/device-center/path-portal.js +11 -3
  48. package/dist/server/device-center/relay.js +364 -35
  49. package/dist/server/device-center/report-metadata.js +66 -0
  50. package/dist/server/device-center/report-upload.js +63 -0
  51. package/dist/server/device-center/runtime.js +598 -41
  52. package/dist/server/device-center/smoke-preview.js +3 -0
  53. package/dist/server/device-center/store.js +203 -41
  54. package/dist/server/device-center/task-context-budget.js +161 -0
  55. package/dist/server/device-center/task-journal.js +385 -0
  56. package/dist/server/device-center/task-plan.js +33 -0
  57. package/dist/server/device-center/task-progress.js +141 -0
  58. package/dist/server/device-center/task-recovery.js +452 -0
  59. package/dist/server/device-center/task-report-outbox.js +216 -0
  60. package/dist/server/device-center/task-report.js +384 -0
  61. package/dist/server/device-center/task-scheduler.js +445 -0
  62. package/dist/server/device-center/task-state.js +333 -0
  63. package/dist/server/device-center/transfer-stream.js +1006 -0
  64. package/dist/server/device-center/transfers.js +841 -8
  65. package/dist/server/dispatch-domain-handlers.js +35 -6
  66. package/dist/server/dsh/dsh-agent-service.js +6 -0
  67. package/dist/server/durable/durable-capabilities.js +11 -0
  68. package/dist/server/engine-probe.js +112 -1
  69. package/dist/server/global-loader.js +119 -19
  70. package/dist/server/goal-service.js +10 -5
  71. package/dist/server/index.js +222 -29
  72. package/dist/server/managed.js +2 -0
  73. package/dist/server/markers/builtins/services.js +123 -0
  74. package/dist/server/markers/builtins/todo.js +189 -0
  75. package/dist/server/markers-list-tool.js +34 -0
  76. package/dist/server/message-deletion.js +40 -0
  77. package/dist/server/message-window.js +9 -0
  78. package/dist/server/model-admin.js +48 -6
  79. package/dist/server/model-enrich.js +10 -1
  80. package/dist/server/orchestrator.js +109 -0
  81. package/dist/server/patch-executable-lookup.js +396 -0
  82. package/dist/server/payload-limits.js +2 -0
  83. package/dist/server/plugin-llm.js +100 -9
  84. package/dist/server/plugins.js +65 -7
  85. package/dist/server/preset-fields.js +24 -0
  86. package/dist/server/preset-share.js +2 -0
  87. package/dist/server/prompt-base-store.js +85 -0
  88. package/dist/server/prompt-composer.js +44 -2
  89. package/dist/server/protocol-version.js +1 -1
  90. package/dist/server/protocol.js +2 -2
  91. package/dist/server/reasoning-registry.js +207 -0
  92. package/dist/server/remote-ssh-service.js +22 -9
  93. package/dist/server/resolve-global-sdk.js +2 -0
  94. package/dist/server/session-search.js +1 -1
  95. package/dist/server/settings-service.js +90 -39
  96. package/dist/server/skill-content-filler.js +29 -8
  97. package/dist/server/skill-tool.js +12 -3
  98. package/dist/server/startup-banner.js +35 -0
  99. package/dist/server/subagent-helpers.js +4 -1
  100. package/dist/server/subagents.js +52 -37
  101. package/dist/server/system-prompt-soul.js +41 -0
  102. package/dist/server/tool-host-factories.js +1 -0
  103. package/dist/server/tool-manager.js +17 -9
  104. package/dist/server/unauthorized-page.js +319 -0
  105. package/dist/server/univer-service.js +448 -0
  106. package/dist/server/universal/drivers/dsh-driver.js +379 -0
  107. package/dist/server/universal/universal-session.js +5 -0
  108. package/dist/server/webui-context.js +25 -5
  109. package/dist/test-artifact.md +9 -0
  110. package/dist/test-preview-modal.md +11 -0
  111. package/dist/test-report.html +20 -0
  112. package/docs/README.md +94 -0
  113. package/docs/architecture-plugins.md +946 -0
  114. package/docs/device-center.md +106 -12
  115. package/docs/dsh-engine.md +10 -10
  116. package/extensions/webui.ts +43 -1
  117. package/package.json +2 -1
  118. package/themes/aetheris.css +5 -0
  119. package/themes/ayu-light.css +6 -0
  120. package/themes/bases/flow-base.css +68 -68
  121. package/themes/catppuccin-latte.css +6 -0
  122. package/themes/catppuccin.css +6 -0
  123. package/themes/claude-code-dark.css +5 -0
  124. package/themes/codex.css +6 -0
  125. package/themes/cyberpunk.css +6 -0
  126. package/themes/dark-teal.css +6 -1
  127. package/themes/dazzle.css +6 -0
  128. package/themes/everforest-light.css +6 -0
  129. package/themes/flow-light.css +8 -1
  130. package/themes/flow.css +6 -1
  131. package/themes/geist.css +6 -0
  132. package/themes/gruvbox-light.css +6 -0
  133. package/themes/kanagawa-lotus.css +6 -0
  134. package/themes/md-preview.css +6 -0
  135. package/themes/mist.css +6 -0
  136. package/themes/nord.css +6 -0
  137. package/themes/one-dark.css +6 -0
  138. package/themes/paper.css +6 -0
  139. package/themes/rose-pine-dawn.css +6 -0
  140. package/themes/sakura.css +6 -0
  141. package/themes/solarized-light.css +6 -0
  142. package/themes/tokyo-night.css +6 -0
  143. package/themes/translucent.css +6 -0
  144. package/themes/transparent.css +6 -0
  145. package/themes/vs-code-dark.css +5 -0
  146. package/themes/wallpaper-flow.css +5 -1
  147. package/themes/wallpaper-obsidian.css +6 -0
  148. package/themes/white.css +6 -0
  149. package/themes/zhujian-dark.css +6 -1
  150. package/themes/zhujian.css +6 -1
  151. package/themes/zhupi-dark.css +6 -1
  152. package/themes/zhupi.css +6 -1
  153. package/web/dist/.build-assets.json +1 -1
  154. package/web/dist/assets/BgTasksModal-BDoOpj-F.js +1 -0
  155. package/web/dist/assets/BgTasksModal-C0i3O1FT.js +1 -0
  156. package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-B8thymBN.js} +3 -3
  157. package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-zSxyIx1R.js} +3 -3
  158. package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
  159. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
  160. package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
  161. package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
  162. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
  163. package/web/dist/assets/Dropdown-C4LIhshN.js +1 -0
  164. package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
  165. package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
  166. package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +1 -0
  167. package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +1 -0
  168. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
  169. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
  170. package/web/dist/assets/HintTip-c6d0TJoh.js +1 -0
  171. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
  172. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
  173. package/web/dist/assets/PiSetupModal-BmMrrgB9.js +1 -0
  174. package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +1 -0
  175. package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
  176. package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
  177. package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
  178. package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
  179. package/web/dist/assets/TerminalPanel-0CYvD72B.js +3 -0
  180. package/web/dist/assets/TerminalPanel-DDavKvFr.js +3 -0
  181. package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +1 -0
  182. package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +1 -0
  183. package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
  184. package/web/dist/assets/canvas-client-CUnXlQYX.js +1 -0
  185. package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-aAKpvKJV.js} +1 -1
  186. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  187. package/web/dist/assets/index-C6DwztqE.css +1 -0
  188. package/web/dist/assets/index-CuN802Sj.js +93 -0
  189. package/web/dist/assets/index-EH5Fw9fa.js +93 -0
  190. package/web/dist/assets/plugin-host-BRWib9DF.js +1 -0
  191. package/web/dist/assets/remote-ssh-client-CfYSMEZg.js +1 -0
  192. package/web/dist/assets/theme-D2l_mLNo.js +1 -0
  193. package/web/dist/index.html +10 -9
  194. package/web/dist/sw.js +1 -1
  195. package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
  196. package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
  197. package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
  198. package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
  199. package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
  200. package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
  201. package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
  202. package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
  203. package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
  204. package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
  205. package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
  206. package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
  207. package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
  208. package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
  209. package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
  210. package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
  211. package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
  212. package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
  213. package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
  214. package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
  215. package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
  216. package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
  217. package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
  218. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  219. package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
  220. package/web/dist/assets/index-DK3F5ZJo.js +0 -85
  221. package/web/dist/assets/index-DQMii2he.js +0 -85
  222. package/web/dist/assets/index-vwBnwzkr.css +0 -1
  223. package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
  224. package/web/dist/assets/theme-D2DMH6tH.js +0 -1
@@ -1,8 +1,26 @@
1
+ import { join } from "node:path";
1
2
  import express from "express";
3
+ import { validInteractionAnswer, validInteractionProjection } from "./human-interaction.js";
4
+ import { createGroupEvents } from "./group-events.js";
5
+ import { createTaskJournalManager } from "./task-journal.js";
6
+ import { createTaskReportStore, MAX_TASK_FULL_REPORT_BYTES } from "./task-report.js";
7
+ import { TASK_REPORT_UPLOAD_JSON_BYTES } from "../payload-limits.js";
8
+ import { parseReportMetadata, mergeTaskReportMetadata, reportUploadMetadata } from "./report-metadata.js";
9
+ import { buildDeterministicTaskSummary, queryTaskReportChunk } from "./task-state.js";
10
+ import { addDelivery, addReview, deliveryHistory, deliverySummary } from "./hub-deliveries.js";
11
+ import { hubPrepareIntegration, hubVerifyIntegration, hubConfirmIntegration, hubCancelIntegration, listIntegrations, } from "./hub-integration.js";
2
12
  import { createServer } from "node:http";
3
13
  import { randomBytes, randomUUID } from "node:crypto";
4
- import { DeviceHubStore, hashSecret, isTerminal, publicDevice, secretMatches } from "./store.js";
14
+ import { DeviceHubStore, hashSecret, isTerminal, taskPending, publicDevice, publicTask, secretMatches, } from "./store.js";
15
+ import { atomicApproveGroupPlan } from "./group-plan-guard.js";
16
+ import { computeAttenuatedTools } from "./bot-execution.js";
17
+ import { validateTaskPlan } from "./task-plan.js";
18
+ import { ALLOWED_WEBHOOK_EVENTS, createWebhookToken, dispatchGroupWebhook, isIncomingWebhookRequest, secureCompareTokens, testOutgoingWebhook, validateWebhookInput, } from "./hub-webhooks.js";
19
+ import { GROUP_RETENTION_LIMIT, groupHistoryPage, groupMentionTargets, groupTaskContext, } from "./group-context.js";
20
+ import { createHubLockManager, validateResourceLocks } from "./hub-locks.js";
5
21
  import { createAccountAuth, hashPassword, verifyPassword, SESSION_TTL, HubRateLimiter } from "./hub-auth.js";
22
+ import { establishConversation, advanceConversationTask, nextConversationTask, recordConversationTurn, conversationStatus, queueParentResult, conversationPage, trimConversationHistory, conversationStale, conversationHasAuditRecords, dropConversationRecords, trimClosedConversations, trimRoomReceipts, } from "./hub-conversations.js";
23
+ import { DEFAULT_EXECUTION_SETTINGS } from "./execution-settings.js";
6
24
  class HttpError extends Error {
7
25
  status;
8
26
  constructor(status, message) {
@@ -41,9 +59,12 @@ function handoff(value) {
41
59
  }
42
60
  const token = () => randomBytes(32).toString("base64url");
43
61
  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. */
62
+ const HISTORY = GROUP_RETENTION_LIMIT;
46
63
  export async function createDeviceHub(options) {
64
+ function currentSettings() {
65
+ return options.getSettings?.() ?? options.settings ?? DEFAULT_EXECUTION_SETTINGS;
66
+ }
67
+ const getHistoryLimit = () => currentSettings().groupRetentionLimit ?? GROUP_RETENTION_LIMIT;
47
68
  const origin = new URL(options.publicUrl);
48
69
  if (!["http:", "https:"].includes(origin.protocol) ||
49
70
  origin.pathname !== "/" ||
@@ -65,6 +86,9 @@ export async function createDeviceHub(options) {
65
86
  throw new Error("Device domain must be independent of hub domain");
66
87
  }
67
88
  const store = await DeviceHubStore.open(options.dataDir);
89
+ const taskJournalManager = createTaskJournalManager(options.dataDir);
90
+ const taskReportStore = createTaskReportStore(options.dataDir, "hub");
91
+ const groupEvents = createGroupEvents(store, taskJournalManager);
68
92
  const auth = createAccountAuth(store, options.publicUrl);
69
93
  const getAccount = (req) => auth.getAccount(req);
70
94
  async function authenticateAgent(req) {
@@ -107,11 +131,25 @@ export async function createDeviceHub(options) {
107
131
  if (req.method === "POST" && !agentWrites.allow("user:" + device.id))
108
132
  fail(429, "Too many user writes");
109
133
  const suffix = req.path.slice("/api/device-user".length);
110
- if (!((req.method === "GET" && (["/devices", "/bots", "/rooms"].includes(suffix) || /^\/rooms\/[^/]+$/.test(suffix))) ||
111
- (req.method === "POST" &&
134
+ const conversationRoute = /^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:messages|stop|deliveries|reviews|task-state|evidence|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)?$/.test(suffix);
135
+ const taskRoute = /^\/rooms\/[^/]+\/tasks\/[^/]+(?:\/(?:journal|report))?$/.test(suffix);
136
+ const webhookRoute = /^\/rooms\/[^/]+\/(?:webhooks(?:\/[^/]+(?:\/(?:delete|regenerate-token|test))?)?|hub-relay)$/.test(suffix);
137
+ if (!((req.method === "GET" &&
138
+ (conversationRoute ||
139
+ taskRoute ||
140
+ webhookRoute ||
141
+ /^\/rooms\/[^/]+\/(?:events|interactions|transfers|locks|blackboard)$/.test(suffix) ||
142
+ /^\/rooms\/[^/]+\/transfers\/[^/]+\/preview$/.test(suffix) ||
143
+ ["/devices", "/bots", "/rooms"].includes(suffix) ||
144
+ /^\/rooms\/[^/]+$/.test(suffix))) ||
145
+ (["POST", "PUT"].includes(req.method) &&
112
146
  (suffix === "/rooms" ||
113
- /^\/rooms\/[^/]+\/(messages|rename|members|delete)$/.test(suffix) ||
114
- /^\/devices\/[^/]+\/open$/.test(suffix)))))
147
+ conversationRoute ||
148
+ webhookRoute ||
149
+ /^\/rooms\/[^/]+\/(messages|rename|members|clear|delete|interactions|canvas|blackboard)$/.test(suffix) ||
150
+ /^\/rooms\/[^/]+\/tasks\/[^/]+\/approve-plan$/.test(suffix) ||
151
+ /^\/rooms\/[^/]+\/transfers(?:\/start|\/[^/]+(?:\/(?:apply|abort|resume))?)?$/.test(suffix) ||
152
+ /^\/devices\/[^/]+\/(open|remark)$/.test(suffix)))))
115
153
  fail(404, "User route missing");
116
154
  users.set(req, { device, account: { id: owner.id, username: owner.username } });
117
155
  req.url = req.url.replace("/api/device-user/", "/api/");
@@ -123,21 +161,30 @@ export async function createDeviceHub(options) {
123
161
  const agent = await authenticateAgent(req);
124
162
  if (!agent)
125
163
  fail(401, "Device authentication required");
126
- if (["POST", "PUT"].includes(req.method) && !agentWrites.allow(agent.device.id))
164
+ const isReportUpload = req.method === "POST" && /^\/api\/agent\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(req.path);
165
+ if (["POST", "PUT"].includes(req.method) && !isReportUpload && !agentWrites.allow(agent.device.id))
127
166
  fail(429, "Too many device writes");
128
167
  agents.set(req, agent);
129
168
  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))))
169
+ if ((req.method === "GET" &&
170
+ (["/devices", "/bots", "/rooms"].includes(suffix) ||
171
+ /^\/rooms\/[^/]+(?:\/(?:history|locks|blackboard))?$/.test(suffix) ||
172
+ /^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:task-state|evidence))?)?$/.test(suffix))) ||
173
+ (req.method === "POST" &&
174
+ (suffix === "/rooms" ||
175
+ /^\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(suffix) ||
176
+ /^\/rooms\/[^/]+\/(?:messages|blackboard|conversations(?:\/[^/]+\/(?:messages|stop|deliveries|reviews|attention|task-state|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)$/.test(suffix))) ||
177
+ (req.method === "PUT" && /^\/rooms\/[^/]+\/blackboard$/.test(suffix)))
132
178
  req.url = req.url.replace("/api/agent/", "/api/");
133
179
  else if (!((suffix === "/transfers" && req.method === "POST") || (suffix === "/bots" && req.method === "PUT")))
134
180
  fail(404, "Agent route missing");
135
181
  next();
136
182
  });
137
183
  app.use((req, res, next) => {
138
- if (req.headers.host !== origin.host)
184
+ if (!isIncomingWebhookRequest(req) && req.headers.host !== origin.host)
139
185
  return res.status(421).json({ error: "Host rejected" });
140
- if (!agents.has(req) &&
186
+ if (!isIncomingWebhookRequest(req) &&
187
+ !agents.has(req) &&
141
188
  !users.has(req) &&
142
189
  !["GET", "HEAD", "OPTIONS"].includes(req.method) &&
143
190
  req.headers.origin !== options.publicUrl)
@@ -145,9 +192,21 @@ export async function createDeviceHub(options) {
145
192
  next();
146
193
  });
147
194
  const json = express.json({ limit: "32kb", strict: true });
195
+ const blackboardJson = express.json({ limit: "512kb", strict: true });
196
+ const reportJson = express.json({ limit: TASK_REPORT_UPLOAD_JSON_BYTES, strict: true });
197
+ const reportWrites = new HubRateLimiter(4096, 60000);
148
198
  app.use((req, res, next) => {
149
199
  if (agents.has(req) && req.path === "/api/agent/transfers")
150
200
  return next();
201
+ if (agents.has(req) && req.method === "POST" && /^\/api\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(req.path)) {
202
+ if (!reportWrites.allow(agents.get(req).device.id))
203
+ return res.status(429).json({ error: "Too many report chunks" });
204
+ return reportJson(req, res, next);
205
+ }
206
+ if ((req.method === "PUT" || req.method === "POST") &&
207
+ /^\/api\/(?:agent\/)?rooms\/[^/]+\/blackboard$/.test(req.path)) {
208
+ return blackboardJson(req, res, next);
209
+ }
151
210
  json(req, res, next);
152
211
  });
153
212
  const loginLimit = new HubRateLimiter(10, 60000);
@@ -158,11 +217,17 @@ export async function createDeviceHub(options) {
158
217
  if (value.expiresAt <= Date.now())
159
218
  pairs.delete(key);
160
219
  };
220
+ const lockManager = createHubLockManager({
221
+ autoCleanupIntervalMs: 60000,
222
+ defaultTtlMs: currentSettings().resourceLockDefaultTtlMs,
223
+ persistPath: options.dataDir ? join(options.dataDir, "hub-locks.json") : undefined,
224
+ });
161
225
  const ip = (req) => req.socket.remoteAddress ?? "unknown";
162
226
  const visibleDevice = (device) => ({
163
227
  id: device.id,
164
228
  accountId: device.accountId,
165
229
  name: device.name,
230
+ remark: device.remark ?? null,
166
231
  createdAt: device.createdAt,
167
232
  online: options.isOnline?.(device.id) ?? false,
168
233
  url: (options.pathAccess ? `${origin.origin}/device/${encodeURIComponent(device.id)}/` : undefined) ??
@@ -318,8 +383,19 @@ export async function createDeviceHub(options) {
318
383
  draft.devices = draft.devices.filter((device) => device.id !== id);
319
384
  const removedBots = new Set(draft.bots.filter((b) => b.deviceId === id).map((b) => b.id));
320
385
  draft.bots = draft.bots.filter((b) => b.deviceId !== id);
321
- for (const room of draft.rooms)
386
+ for (const room of draft.rooms) {
322
387
  room.botIds = room.botIds.filter((botId) => !removedBots.has(botId));
388
+ if (room.primaryBotId && removedBots.has(room.primaryBotId))
389
+ delete room.primaryBotId;
390
+ }
391
+ // A revoked device can no longer continue its conversations: close them now so the next turn
392
+ // reports a reason instead of a late 409 against a Bot that no longer exists.
393
+ for (const conversation of draft.conversations)
394
+ if (!conversation.closed && removedBots.has(conversation.botId)) {
395
+ conversation.closed = true;
396
+ conversation.closedReason = "device_revoked";
397
+ conversation.updatedAt = Date.now();
398
+ }
323
399
  for (const task of draft.tasks)
324
400
  if (task.deviceId === id && !isTerminal(task.status)) {
325
401
  task.status = "interrupted";
@@ -376,7 +452,19 @@ export async function createDeviceHub(options) {
376
452
  !Number.isSafeInteger(b.revision) ||
377
453
  b.revision < 1)
378
454
  fail(400, "Invalid Bot registration");
379
- return { id, name, description: b.description, enabled: b.enabled, revision: b.revision };
455
+ if (b.tools !== undefined &&
456
+ (!Array.isArray(b.tools) ||
457
+ b.tools.length > 256 ||
458
+ b.tools.some((name) => typeof name !== "string" || !name.trim() || name.length > 128)))
459
+ fail(400, "Invalid Bot tools");
460
+ return {
461
+ id,
462
+ name,
463
+ description: b.description,
464
+ enabled: b.enabled,
465
+ revision: b.revision,
466
+ ...(b.tools === undefined ? {} : { tools: [...new Set(b.tools)] }),
467
+ };
380
468
  });
381
469
  const bots = await store.transact((draft) => {
382
470
  if (!draft.devices.some((d) => d.id === device.id && d.accountId === owner.id))
@@ -395,7 +483,10 @@ export async function createDeviceHub(options) {
395
483
  if (previous &&
396
484
  (row.revision < previous.revision ||
397
485
  (row.revision === previous.revision &&
398
- ["name", "description", "enabled"].some((k) => previous[k] !== row[k]))))
486
+ (["name", "description", "enabled"].some((k) => previous[k] !== row[k]) ||
487
+ (row.tools !== undefined &&
488
+ previous.tools !== undefined &&
489
+ JSON.stringify(previous.tools) !== JSON.stringify(row.tools))))))
399
490
  fail(409, "Bot revision is stale");
400
491
  if (previous)
401
492
  Object.assign(previous, row, { updatedAt: Date.now() });
@@ -439,12 +530,122 @@ export async function createDeviceHub(options) {
439
530
  fail(400, "Invalid room Bot");
440
531
  if (draft.rooms.filter((r) => r.accountId === owner.id).length >= 100)
441
532
  fail(409, "Room capacity reached");
442
- const room = { id: randomUUID(), accountId: owner.id, name, botIds, createdAt: Date.now() };
533
+ const primaryBotId = req.body?.primaryBotId == null ? undefined : text(req.body.primaryBotId, 128);
534
+ if (primaryBotId && !botIds.includes(primaryBotId))
535
+ fail(400, "Primary Bot must be a room member");
536
+ const room = { id: randomUUID(), accountId: owner.id, name, botIds, primaryBotId, createdAt: Date.now() };
443
537
  draft.rooms.push(room);
444
538
  return room;
445
539
  });
446
540
  res.status(201).json({ room });
447
541
  });
542
+ const humanInteractions = new Map();
543
+ function liveInteractions(roomId, accountId) {
544
+ const state = store.snapshot();
545
+ for (const [key, items] of humanInteractions) {
546
+ const task = state.tasks.find((t) => t.id === key);
547
+ if (!task ||
548
+ task.cancelRequested ||
549
+ !(task.status === "running" || (task.status === "queued" && deliveredTasks.has(task.id))) ||
550
+ items.some((i) => i.attemptId !== task.attemptId))
551
+ humanInteractions.delete(key);
552
+ }
553
+ return [...humanInteractions.values()]
554
+ .flat()
555
+ .filter((i) => i.roomId === roomId &&
556
+ state.tasks.some((t) => t.id === i.taskId && t.accountId === accountId) &&
557
+ (i.deadline === undefined || i.deadline > Date.now()) &&
558
+ (options.isOnline?.(i.deviceId) ?? true));
559
+ }
560
+ function acceptInteractions(deviceId, event) {
561
+ const state = store.snapshot();
562
+ const task = state.tasks.find((t) => t.id === event.taskId && t.deviceId === deviceId && t.attemptId === event.attemptId && t.botId === event.botId);
563
+ const room = task &&
564
+ state.rooms.find((r) => r.id === task.roomId && r.accountId === task.accountId && r.botIds.includes(task.botId));
565
+ if (!task ||
566
+ !room ||
567
+ task.cancelRequested ||
568
+ !(task.status === "running" || (task.status === "queued" && deliveredTasks.has(task.id))) ||
569
+ state.devices.find((d) => d.id === deviceId)?.accountId !== task.accountId ||
570
+ !validInteractionProjection(event.items, {
571
+ taskId: task.id,
572
+ attemptId: task.attemptId,
573
+ roomId: task.roomId,
574
+ botId: task.botId,
575
+ deviceId,
576
+ }))
577
+ return;
578
+ if (event.items.length) {
579
+ if (!humanInteractions.has(task.id) && humanInteractions.size >= 128)
580
+ return;
581
+ humanInteractions.set(task.id, structuredClone(event.items));
582
+ }
583
+ else
584
+ humanInteractions.delete(task.id);
585
+ groupEvents.invalidate(task.roomId);
586
+ }
587
+ app.get("/api/rooms/:id/interactions", (req, res) => {
588
+ const owner = account(req);
589
+ if (agents.has(req))
590
+ fail(403, "Human interaction requires a user session");
591
+ if (!store.snapshot().rooms.some((r) => r.id === req.params.id && r.accountId === owner.id))
592
+ fail(404, "Room missing");
593
+ res.setHeader("Cache-Control", "no-store");
594
+ res.json({ interactions: liveInteractions(req.params.id, owner.id) });
595
+ });
596
+ app.post("/api/rooms/:id/interactions", async (req, res) => {
597
+ const owner = account(req);
598
+ if (agents.has(req))
599
+ fail(403, "Human interaction requires a user session");
600
+ if (!validInteractionAnswer(req.body))
601
+ fail(400, "Invalid interaction answer");
602
+ 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);
603
+ if (!item)
604
+ fail(409, "Interaction expired");
605
+ if (!(await options.relay?.answerInteraction?.(item.deviceId, req.body)))
606
+ fail(409, "Executor rejected or did not acknowledge the answer");
607
+ humanInteractions.set(item.taskId, (humanInteractions.get(item.taskId) ?? []).filter((i) => i.id !== item.id));
608
+ groupEvents.invalidate(item.roomId);
609
+ res.json({ forwarded: true });
610
+ });
611
+ app.post("/api/rooms/:id/canvas", async (req, res) => {
612
+ const owner = account(req);
613
+ if (agents.has(req))
614
+ fail(403, "Canvas binding requires a user session");
615
+ const raw = req.body?.binding;
616
+ if (!req.body ||
617
+ Object.keys(req.body).some((key) => key !== "binding") ||
618
+ (raw !== null &&
619
+ (!raw ||
620
+ typeof raw !== "object" ||
621
+ Array.isArray(raw) ||
622
+ Object.keys(raw).some((key) => !["deviceId", "graphId", "cwd", "title"].includes(key)) ||
623
+ typeof raw.deviceId !== "string" ||
624
+ typeof raw.graphId !== "string" ||
625
+ !/^[A-Za-z0-9._-]{1,64}$/.test(raw.graphId) ||
626
+ typeof raw.cwd !== "string" ||
627
+ !raw.cwd.trim() ||
628
+ raw.cwd.length > 4096 ||
629
+ typeof raw.title !== "string" ||
630
+ raw.title.length > 200)))
631
+ fail(400, "Invalid canvas binding");
632
+ const binding = raw === null
633
+ ? undefined
634
+ : { deviceId: raw.deviceId, graphId: raw.graphId, cwd: raw.cwd.trim(), title: raw.title };
635
+ let room;
636
+ await store.transact((state) => {
637
+ room = state.rooms.find((item) => item.id === req.params.id && item.accountId === owner.id);
638
+ if (!room)
639
+ fail(404, "Room missing");
640
+ if (binding &&
641
+ (!state.devices.some((device) => device.id === binding.deviceId && device.accountId === owner.id) ||
642
+ !state.bots.some((bot) => bot.deviceId === binding.deviceId && bot.accountId === owner.id && room.botIds.includes(bot.id))))
643
+ fail(403, "Canvas device must host a Bot in this group");
644
+ room.canvasBinding = binding;
645
+ });
646
+ groupEvents.invalidate(String(req.params.id));
647
+ res.json({ room });
648
+ });
448
649
  app.get("/api/rooms/:id", (req, res) => {
449
650
  const state = store.snapshot(), room = state.rooms.find((r) => r.id === req.params.id && r.accountId === account(req).id);
450
651
  if (!room ||
@@ -464,10 +665,798 @@ export async function createDeviceHub(options) {
464
665
  ?.name,
465
666
  })),
466
667
  messages: state.messages.filter((m) => m.roomId === room.id),
467
- tasks: state.tasks.filter((t) => t.roomId === room.id),
668
+ tasks: state.tasks.filter((t) => t.roomId === room.id).map(publicTask),
669
+ });
670
+ });
671
+ app.get("/api/rooms/:id/events", (req, res) => {
672
+ groupEvents.connect(account(req).id, String(req.params.id), res, users.get(req)?.device.id);
673
+ });
674
+ app.get("/api/rooms/:id/locks", (req, res) => {
675
+ const state = store.snapshot();
676
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === account(req).id);
677
+ if (!room ||
678
+ (agents.has(req) &&
679
+ !state.bots.some((b) => b.enabled &&
680
+ b.deviceId === agents.get(req).device.id &&
681
+ b.accountId === room.accountId &&
682
+ room.botIds.includes(b.id))))
683
+ fail(404, "Room missing");
684
+ res.json(lockManager.getRoomLockInfo(room.id));
685
+ });
686
+ app.get("/api/rooms/:id/blackboard", (req, res) => {
687
+ const owner = account(req);
688
+ const state = store.snapshot();
689
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
690
+ if (!room)
691
+ fail(404, "Room missing");
692
+ if (agents.has(req)) {
693
+ const agent = agents.get(req);
694
+ const sourceBotId = (req.query.sourceBotId ?? req.body?.sourceBotId);
695
+ if (!sourceBotId)
696
+ fail(403, "Source Bot required");
697
+ const source = state.bots.find((b) => b.id === sourceBotId && b.deviceId === agent.device.id && b.accountId === agent.account.id && b.enabled);
698
+ if (!source)
699
+ fail(403, "Source Bot access denied");
700
+ if (!room.botIds.includes(source.id))
701
+ fail(403, "Source Bot is not a room member");
702
+ }
703
+ res.json({ blackboard: room.blackboard ?? null });
704
+ });
705
+ const handleBlackboardUpdate = async (req, res) => {
706
+ const owner = account(req);
707
+ const { content, expectedVersion, title } = req.body ?? {};
708
+ const settings = currentSettings();
709
+ if (typeof content !== "string" || !content.trim())
710
+ fail(400, "Content must be a nonempty string");
711
+ if (Buffer.byteLength(content, "utf8") > settings.blackboardMaxBytes)
712
+ fail(400, `Content exceeds ${settings.blackboardMaxBytes} bytes limit`);
713
+ if (/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(content))
714
+ fail(400, "Content must not contain control characters");
715
+ if (typeof expectedVersion !== "number" || !Number.isSafeInteger(expectedVersion) || expectedVersion < 0) {
716
+ fail(400, "expectedVersion must be a non-negative safe integer");
717
+ }
718
+ if (title !== undefined) {
719
+ if (typeof title !== "string" || title.length > 200 || /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(title)) {
720
+ fail(400, "Invalid title");
721
+ }
722
+ }
723
+ let updatedBy;
724
+ const stateBefore = store.snapshot();
725
+ if (agents.has(req)) {
726
+ const agent = agents.get(req);
727
+ const sourceBotId = (req.body?.sourceBotId ?? req.query?.sourceBotId);
728
+ if (!sourceBotId)
729
+ fail(403, "Source Bot required");
730
+ const source = stateBefore.bots.find((b) => b.id === sourceBotId && b.deviceId === agent.device.id && b.accountId === agent.account.id && b.enabled);
731
+ if (!source)
732
+ fail(403, "Source Bot access denied");
733
+ const preRoom = stateBefore.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
734
+ if (!preRoom)
735
+ fail(404, "Room missing");
736
+ if (!preRoom.botIds.includes(source.id))
737
+ fail(403, "Source Bot is not a room member");
738
+ updatedBy = { type: "bot", id: source.id, name: source.name };
739
+ }
740
+ else {
741
+ const preRoom = stateBefore.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
742
+ if (!preRoom)
743
+ fail(404, "Room missing");
744
+ updatedBy = { type: "human", id: owner.id, name: owner.username };
745
+ }
746
+ const updatedBlackboard = await store.transact((draft) => {
747
+ const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
748
+ if (!room)
749
+ fail(404, "Room missing");
750
+ if (agents.has(req) && !room.botIds.includes(updatedBy.id))
751
+ fail(403, "Source Bot is not a room member");
752
+ const current = room.blackboard;
753
+ if (current) {
754
+ if (current.version !== expectedVersion)
755
+ fail(409, "Version conflict");
756
+ }
757
+ else {
758
+ if (expectedVersion !== 0)
759
+ fail(409, "Version conflict");
760
+ }
761
+ const nextVersion = current ? current.version + 1 : 1;
762
+ const nextBlackboard = {
763
+ version: nextVersion,
764
+ updatedAt: Date.now(),
765
+ updatedBy,
766
+ ...(title?.trim() ? { title: title.trim() } : {}),
767
+ content,
768
+ };
769
+ room.blackboard = nextBlackboard;
770
+ return nextBlackboard;
468
771
  });
772
+ groupEvents.invalidate(String(req.params.id));
773
+ res.json({ ok: true, blackboard: updatedBlackboard });
774
+ };
775
+ app.put("/api/rooms/:id/blackboard", handleBlackboardUpdate);
776
+ app.post("/api/rooms/:id/blackboard", handleBlackboardUpdate);
777
+ // === Group Webhooks ===
778
+ app.get("/api/rooms/:id/webhooks", (req, res) => {
779
+ const owner = account(req);
780
+ if (agents.has(req))
781
+ fail(403, "Webhook management requires a user session");
782
+ const state = store.snapshot();
783
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
784
+ if (!room)
785
+ fail(404, "Room missing");
786
+ res.setHeader("Cache-Control", "no-store");
787
+ res.json({ webhooks: room.webhooks ?? [] });
788
+ });
789
+ app.post("/api/rooms/:id/webhooks", async (req, res) => {
790
+ const owner = account(req);
791
+ if (agents.has(req))
792
+ fail(403, "Webhook management requires a user session");
793
+ const validated = validateWebhookInput(req.body, false);
794
+ let created;
795
+ await store.transact((state) => {
796
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
797
+ if (!room)
798
+ fail(404, "Room missing");
799
+ if (!room.webhooks)
800
+ room.webhooks = [];
801
+ if (room.webhooks.length >= 32)
802
+ fail(409, "Maximum webhooks limit reached");
803
+ const now = Date.now();
804
+ created = {
805
+ id: randomUUID(),
806
+ roomId: room.id,
807
+ name: validated.name,
808
+ type: validated.type,
809
+ enabled: validated.enabled ?? true,
810
+ createdAt: now,
811
+ updatedAt: now,
812
+ ...(validated.type === "incoming"
813
+ ? {
814
+ token: createWebhookToken(),
815
+ allowBotTrigger: validated.allowBotTrigger ?? true,
816
+ }
817
+ : {
818
+ url: validated.url,
819
+ secret: validated.secret,
820
+ events: validated.events ?? [...ALLOWED_WEBHOOK_EVENTS],
821
+ relayViaHub: validated.relayViaHub ?? true,
822
+ }),
823
+ };
824
+ room.webhooks.push(created);
825
+ });
826
+ groupEvents.invalidate(String(req.params.id));
827
+ res.json({ webhook: created });
828
+ });
829
+ const handleWebhookUpdate = async (req, res) => {
830
+ const owner = account(req);
831
+ if (agents.has(req))
832
+ fail(403, "Webhook management requires a user session");
833
+ const validated = validateWebhookInput(req.body, true);
834
+ let updated;
835
+ await store.transact((state) => {
836
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
837
+ if (!room)
838
+ fail(404, "Room missing");
839
+ const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
840
+ if (!hook)
841
+ fail(404, "Webhook missing");
842
+ if (validated.name !== undefined)
843
+ hook.name = validated.name;
844
+ if (validated.enabled !== undefined)
845
+ hook.enabled = validated.enabled;
846
+ if (hook.type === "incoming") {
847
+ if (validated.allowBotTrigger !== undefined)
848
+ hook.allowBotTrigger = validated.allowBotTrigger;
849
+ }
850
+ else {
851
+ if (validated.url !== undefined)
852
+ hook.url = validated.url;
853
+ if (validated.secret !== undefined)
854
+ hook.secret = validated.secret;
855
+ if (validated.events !== undefined)
856
+ hook.events = validated.events;
857
+ if (validated.relayViaHub !== undefined)
858
+ hook.relayViaHub = validated.relayViaHub;
859
+ }
860
+ hook.updatedAt = Date.now();
861
+ updated = hook;
862
+ });
863
+ groupEvents.invalidate(String(req.params.id));
864
+ res.json({ webhook: updated });
865
+ };
866
+ app.put("/api/rooms/:id/webhooks/:webhookId", handleWebhookUpdate);
867
+ app.post("/api/rooms/:id/webhooks/:webhookId", handleWebhookUpdate);
868
+ app.post("/api/rooms/:id/webhooks/:webhookId/regenerate-token", async (req, res) => {
869
+ const owner = account(req);
870
+ if (agents.has(req))
871
+ fail(403, "Webhook management requires a user session");
872
+ let updated;
873
+ await store.transact((state) => {
874
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
875
+ if (!room)
876
+ fail(404, "Room missing");
877
+ const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
878
+ if (!hook)
879
+ fail(404, "Webhook missing");
880
+ if (hook.type !== "incoming")
881
+ fail(400, "Only incoming webhooks have tokens");
882
+ hook.token = createWebhookToken();
883
+ hook.updatedAt = Date.now();
884
+ updated = hook;
885
+ });
886
+ groupEvents.invalidate(String(req.params.id));
887
+ res.json({ webhook: updated });
888
+ });
889
+ const handleWebhookDelete = async (req, res) => {
890
+ const owner = account(req);
891
+ if (agents.has(req))
892
+ fail(403, "Webhook management requires a user session");
893
+ await store.transact((state) => {
894
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
895
+ if (!room)
896
+ fail(404, "Room missing");
897
+ if (!room.webhooks?.some((w) => w.id === req.params.webhookId))
898
+ fail(404, "Webhook missing");
899
+ room.webhooks = room.webhooks.filter((w) => w.id !== req.params.webhookId);
900
+ });
901
+ groupEvents.invalidate(String(req.params.id));
902
+ res.json({ deleted: true });
903
+ };
904
+ app.delete("/api/rooms/:id/webhooks/:webhookId", handleWebhookDelete);
905
+ app.post("/api/rooms/:id/webhooks/:webhookId/delete", handleWebhookDelete);
906
+ app.post("/api/rooms/:id/hub-relay", async (req, res) => {
907
+ const owner = account(req);
908
+ if (agents.has(req))
909
+ fail(403, "Webhook management requires a user session");
910
+ const rawUrl = req.body?.hubRelayBaseUrl;
911
+ let baseUrl;
912
+ if (rawUrl !== undefined && rawUrl !== null && rawUrl !== "") {
913
+ if (typeof rawUrl !== "string")
914
+ fail(400, "Invalid hubRelayBaseUrl");
915
+ try {
916
+ const parsed = new URL(rawUrl.trim());
917
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
918
+ fail(400, "Invalid protocol");
919
+ baseUrl = parsed.origin;
920
+ }
921
+ catch {
922
+ fail(400, "hubRelayBaseUrl must be a valid HTTP(S) URL");
923
+ }
924
+ }
925
+ await store.transact((state) => {
926
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
927
+ if (!room)
928
+ fail(404, "Room missing");
929
+ room.hubRelayBaseUrl = baseUrl;
930
+ });
931
+ groupEvents.invalidate(String(req.params.id));
932
+ res.json({ hubRelayBaseUrl: baseUrl });
469
933
  });
470
- for (const operation of ["rename", "members", "delete"]) {
934
+ app.post("/api/rooms/:id/webhooks/:webhookId/test", async (req, res) => {
935
+ const owner = account(req);
936
+ if (agents.has(req))
937
+ fail(403, "Webhook management requires a user session");
938
+ const state = store.snapshot();
939
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
940
+ if (!room)
941
+ fail(404, "Room missing");
942
+ const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
943
+ if (!hook)
944
+ fail(404, "Webhook missing");
945
+ if (hook.type !== "outgoing") {
946
+ return res.json({ success: true, message: "Incoming webhook is active" });
947
+ }
948
+ if (!hook.url)
949
+ fail(400, "Webhook URL missing");
950
+ const result = await testOutgoingWebhook({ url: hook.url, secret: hook.secret });
951
+ res.json(result);
952
+ });
953
+ app.post("/api/rooms/:id/webhooks/incoming/:webhookId", async (req, res) => {
954
+ const roomId = String(req.params.id);
955
+ const webhookId = String(req.params.webhookId);
956
+ const snapshot = store.snapshot();
957
+ const room = snapshot.rooms.find((r) => r.id === roomId);
958
+ if (!room)
959
+ return res.status(404).json({ error: "Room missing" });
960
+ const webhook = room.webhooks?.find((w) => w.id === webhookId && w.type === "incoming");
961
+ if (!webhook || webhook.enabled === false)
962
+ return res.status(404).json({ error: "Webhook not found or disabled" });
963
+ const bearer = req.headers.authorization?.startsWith("Bearer ") ? req.headers.authorization.slice(7) : undefined;
964
+ const queryToken = typeof req.query?.token === "string" ? req.query.token : undefined;
965
+ const headerToken = typeof req.headers["x-webhook-token"] === "string" ? req.headers["x-webhook-token"] : undefined;
966
+ const bodyToken = typeof req.body?.token === "string" ? req.body.token : undefined;
967
+ const providedToken = queryToken ?? bearer ?? headerToken ?? bodyToken;
968
+ if (!providedToken || !webhook.token || !secureCompareTokens(providedToken, webhook.token)) {
969
+ return res.status(401).json({ error: "Invalid webhook token" });
970
+ }
971
+ const rawText = req.body?.text;
972
+ if (typeof rawText !== "string" || !rawText.trim()) {
973
+ return res.status(400).json({ error: "Missing or empty text" });
974
+ }
975
+ const content = text(rawText);
976
+ const senderName = typeof req.body?.senderName === "string" && req.body.senderName.trim()
977
+ ? text(req.body.senderName.trim(), 80)
978
+ : webhook.name;
979
+ const replyToMessageId = typeof req.body?.replyToMessageId === "string" ? text(req.body.replyToMessageId, 128) : undefined;
980
+ const inputTargets = Array.isArray(req.body?.targetBotIds)
981
+ ? req.body.targetBotIds.filter((id) => typeof id === "string")
982
+ : [];
983
+ const settings = currentSettings();
984
+ const key = randomUUID();
985
+ const fingerprint = hashSecret(JSON.stringify({
986
+ content,
987
+ senderName,
988
+ webhookId,
989
+ inputTargets,
990
+ replyToMessageId,
991
+ }));
992
+ const result = await store.transact((draft) => {
993
+ const activeRoom = draft.rooms.find((r) => r.id === roomId);
994
+ if (!activeRoom)
995
+ fail(404, "Room missing");
996
+ const activeWebhook = activeRoom.webhooks?.find((w) => w.id === webhookId && w.type === "incoming");
997
+ if (!activeWebhook || activeWebhook.enabled === false)
998
+ fail(404, "Webhook missing or disabled");
999
+ if (replyToMessageId && !draft.messages.some((m) => m.id === replyToMessageId && m.roomId === activeRoom.id)) {
1000
+ fail(400, "Reply target message is not in this room");
1001
+ }
1002
+ const targets = [];
1003
+ const allowTrigger = activeWebhook.allowBotTrigger !== false;
1004
+ if (allowTrigger) {
1005
+ if (inputTargets.length > 0) {
1006
+ targets.push(...inputTargets);
1007
+ }
1008
+ else {
1009
+ if (settings.allowBotMentions) {
1010
+ targets.push(...groupMentionTargets(content, activeRoom, draft.bots, settings.botMentionBudgetPerTurn));
1011
+ }
1012
+ if (!targets.length && activeRoom.primaryBotId) {
1013
+ if (activeRoom.botIds.includes(activeRoom.primaryBotId) &&
1014
+ validBot(draft, activeRoom.primaryBotId, activeRoom.accountId)) {
1015
+ targets.push(activeRoom.primaryBotId);
1016
+ }
1017
+ }
1018
+ }
1019
+ }
1020
+ if (targets.some((id) => !activeRoom.botIds.includes(id) || !validBot(draft, id, activeRoom.accountId))) {
1021
+ fail(400, "Invalid target Bot");
1022
+ }
1023
+ const now = Date.now();
1024
+ const rootId = randomUUID();
1025
+ const tasks = targets.map((botId, index) => {
1026
+ const targetBot = validBot(draft, botId, activeRoom.accountId);
1027
+ return {
1028
+ id: index === 0 ? rootId : randomUUID(),
1029
+ rootTaskId: rootId,
1030
+ dispatchDepth: 0,
1031
+ ...(index === 0 ? { dispatchCount: targets.length } : {}),
1032
+ attemptId: randomUUID(),
1033
+ roomId: activeRoom.id,
1034
+ accountId: activeRoom.accountId,
1035
+ botId,
1036
+ deviceId: targetBot.deviceId,
1037
+ botRevision: targetBot.revision,
1038
+ text: content,
1039
+ status: "queued",
1040
+ createdAt: now,
1041
+ updatedAt: now,
1042
+ };
1043
+ });
1044
+ for (const task of tasks) {
1045
+ task.kind = "message";
1046
+ const targetConv = draft.conversations
1047
+ .filter((entry) => entry.roomId === activeRoom.id &&
1048
+ entry.accountId === activeRoom.accountId &&
1049
+ entry.botId === task.botId &&
1050
+ !entry.closed &&
1051
+ entry.botRevision === task.botRevision &&
1052
+ entry.deviceId === task.deviceId)
1053
+ .sort((a, b) => b.updatedAt - a.updatedAt)[0];
1054
+ if (targetConv) {
1055
+ task.conversationId = targetConv.id;
1056
+ task.resume = true;
1057
+ advanceConversationTask(draft, targetConv, task);
1058
+ targetConv.rootTaskId = task.rootTaskId;
1059
+ targetConv.updatedAt = now;
1060
+ targetConv.dispatchDepth = 0;
1061
+ }
1062
+ else {
1063
+ establishConversation(draft, task);
1064
+ }
1065
+ recordConversationTurn(draft, task, key, fingerprint);
1066
+ }
1067
+ const message = {
1068
+ id: randomUUID(),
1069
+ roomId: activeRoom.id,
1070
+ accountId: activeRoom.accountId,
1071
+ text: content,
1072
+ sender: {
1073
+ type: "webhook",
1074
+ id: activeWebhook.id,
1075
+ name: senderName,
1076
+ },
1077
+ createdAt: now,
1078
+ taskIds: tasks.map((t) => t.id),
1079
+ ...(targets.length ? { targetBotIds: targets } : {}),
1080
+ ...(replyToMessageId ? { replyToMessageId } : {}),
1081
+ ...(tasks.length === 1 ? { conversationId: tasks[0].conversationId } : {}),
1082
+ ...(tasks.length ? { conversationIds: tasks.map((task) => task.conversationId) } : {}),
1083
+ };
1084
+ const context = tasks.length
1085
+ ? groupTaskContext(activeRoom, draft.bots, draft.messages, settings.groupContextBytes)
1086
+ : undefined;
1087
+ draft.tasks.push(...tasks);
1088
+ draft.messages.push(message);
1089
+ draft.receipts.push({
1090
+ accountId: activeRoom.accountId,
1091
+ roomId: activeRoom.id,
1092
+ key,
1093
+ fingerprint,
1094
+ messageId: message.id,
1095
+ createdAt: message.createdAt,
1096
+ });
1097
+ const oldMessages = draft.messages.filter((m) => m.roomId === activeRoom.id).slice(0, -getHistoryLimit());
1098
+ const removed = new Set(oldMessages.map((m) => m.id));
1099
+ draft.messages = draft.messages.filter((m) => !removed.has(m.id));
1100
+ trimRoomReceipts(draft, activeRoom.id);
1101
+ const oldTasks = new Set(draft.tasks
1102
+ .filter((t) => t.roomId === activeRoom.id &&
1103
+ isTerminal(t.status) &&
1104
+ !draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
1105
+ .slice(0, -getHistoryLimit())
1106
+ .map((t) => t.id));
1107
+ draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
1108
+ trimConversationHistory(draft, activeRoom.id);
1109
+ trimClosedConversations(draft, activeRoom.id);
1110
+ return { message, tasks, context, roomId: activeRoom.id };
1111
+ });
1112
+ for (const task of result.tasks) {
1113
+ if (task.status !== "waiting")
1114
+ await deliverTask(task, result.context);
1115
+ }
1116
+ groupEvents.invalidate(result.roomId);
1117
+ dispatchGroupWebhook(store, result.roomId, "message", result.message);
1118
+ res.json({
1119
+ success: true,
1120
+ message: result.message,
1121
+ tasks: result.tasks.map(publicTask),
1122
+ });
1123
+ });
1124
+ // === Task Details, Journal, and Reports ===
1125
+ app.get("/api/rooms/:id/tasks/:taskId", (req, res) => {
1126
+ const acc = account(req);
1127
+ const state = store.snapshot();
1128
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === acc.id);
1129
+ if (!room)
1130
+ fail(404, "Room missing");
1131
+ const task = state.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === acc.id);
1132
+ if (!task)
1133
+ fail(404, "Task missing");
1134
+ const bot = state.bots.find((b) => b.id === task.botId && b.accountId === acc.id);
1135
+ const device = state.devices.find((d) => d.id === task.deviceId && d.accountId === acc.id);
1136
+ const reportMeta = mergeTaskReportMetadata(task, taskReportStore.getReportMeta(task.id, task.attemptId, acc.id, room.id));
1137
+ const interactions = state.interactions
1138
+ ? state.interactions.filter((i) => i.taskId === task.id)
1139
+ : [];
1140
+ const deliveries = state.deliveries
1141
+ ? state.deliveries.filter((d) => d.taskId === task.id)
1142
+ : [];
1143
+ res.json({
1144
+ task: {
1145
+ id: task.id,
1146
+ roomId: task.roomId,
1147
+ accountId: task.accountId,
1148
+ deviceId: task.deviceId,
1149
+ botId: task.botId,
1150
+ botName: bot?.name,
1151
+ deviceName: device?.name,
1152
+ text: task.text,
1153
+ status: task.status,
1154
+ createdAt: task.createdAt,
1155
+ updatedAt: task.updatedAt,
1156
+ attemptId: task.attemptId,
1157
+ parentTaskId: task.parentTaskId,
1158
+ conversationId: task.conversationId,
1159
+ report: task.report,
1160
+ ...(task.attenuatedTools ? { attenuatedTools: task.attenuatedTools } : {}),
1161
+ },
1162
+ reportMeta,
1163
+ interactionCount: interactions.length,
1164
+ interactions: interactions.map((i) => ({
1165
+ id: i.id,
1166
+ kind: i.kind,
1167
+ question: i.question,
1168
+ resolved: !!i.decision || !!i.cancelled,
1169
+ decision: i.decision,
1170
+ })),
1171
+ journalUnavailable: groupEvents.isJournalUnavailable(task.id, task.attemptId),
1172
+ deliveries: deliveries.map((d) => ({
1173
+ id: d.id,
1174
+ commit: d.commit,
1175
+ branch: d.branch,
1176
+ summary: d.summary,
1177
+ passed: d.checks?.every((c) => c.status === "passed") ?? true,
1178
+ })),
1179
+ });
1180
+ });
1181
+ app.post("/api/rooms/:id/tasks/:taskId/approve-plan", async (req, res) => {
1182
+ const acc = account(req);
1183
+ if (agents.has(req)) {
1184
+ fail(403, "Plan approval is restricted to human users; Bots cannot self-approve");
1185
+ }
1186
+ const user = users.get(req)?.device;
1187
+ const approverName = user ? `${acc.username} · ${user.name}` : acc.username;
1188
+ const { plan, nextTask } = await store.transact((draft) => {
1189
+ const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === acc.id);
1190
+ if (!room)
1191
+ fail(404, "Room missing");
1192
+ const task = draft.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === acc.id);
1193
+ if (!task)
1194
+ fail(404, "Task missing");
1195
+ if (!task.planOnly || !task.plan)
1196
+ fail(400, "Task does not have a plan to approve");
1197
+ if (task.status !== "completed" || task.cancelRequested)
1198
+ fail(409, "Planning task must finish before approval");
1199
+ if (!validateTaskPlan(task.plan))
1200
+ fail(409, "Plan steps are invalid");
1201
+ if (validBot(draft, task.botId, acc.id)?.revision !== task.botRevision)
1202
+ fail(409, "Plan Bot configuration changed");
1203
+ if (!room.botIds.includes(task.botId))
1204
+ fail(409, "Plan Bot is no longer a room member");
1205
+ const result = atomicApproveGroupPlan(task.plan, approverName);
1206
+ if (!result.ok)
1207
+ fail(409, result.error);
1208
+ task.plan = result.plan;
1209
+ task.updatedAt = Date.now();
1210
+ const conversation = task.conversationId
1211
+ ? draft.conversations.find((c) => c.id === task.conversationId && c.roomId === room.id && c.accountId === acc.id)
1212
+ : undefined;
1213
+ if (!conversation || conversation.closed)
1214
+ fail(409, "Plan conversation unavailable");
1215
+ if ((task.dispatchDepth ?? 0) + 1 > 8)
1216
+ fail(409, "Dispatch depth exhausted");
1217
+ const root = draft.tasks.find((t) => t.id === (task.rootTaskId ?? task.id));
1218
+ if (!root)
1219
+ fail(409, "Dispatch root expired");
1220
+ if (root) {
1221
+ if ((root.dispatchCount ?? 0) >= 16)
1222
+ fail(409, "Dispatch budget exhausted");
1223
+ root.dispatchCount = (root.dispatchCount ?? 0) + 1;
1224
+ }
1225
+ const now = Date.now();
1226
+ const nextTaskId = randomUUID();
1227
+ const nextAttemptId = randomUUID();
1228
+ const nextTask = {
1229
+ id: nextTaskId,
1230
+ rootTaskId: task.rootTaskId ?? task.id,
1231
+ parentTaskId: task.id,
1232
+ dispatchDepth: (task.dispatchDepth ?? 0) + 1,
1233
+ attemptId: nextAttemptId,
1234
+ roomId: room.id,
1235
+ accountId: acc.id,
1236
+ botId: task.botId,
1237
+ deviceId: task.deviceId,
1238
+ botRevision: task.botRevision,
1239
+ 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.`,
1240
+ status: "queued",
1241
+ createdAt: now,
1242
+ updatedAt: now,
1243
+ planOnly: false,
1244
+ resume: Boolean(conversation),
1245
+ ...(conversation ? { conversationId: conversation.id } : {}),
1246
+ ...(task.sourceBotId ? { sourceBotId: task.sourceBotId } : {}),
1247
+ ...(task.attenuatedTools ? { attenuatedTools: [...task.attenuatedTools] } : {}),
1248
+ };
1249
+ draft.tasks.push(nextTask);
1250
+ if (conversation) {
1251
+ advanceConversationTask(draft, conversation, nextTask);
1252
+ conversation.updatedAt = now;
1253
+ }
1254
+ const idempotencyKey = randomUUID();
1255
+ const fingerprint = hashSecret(`approve-plan:${task.id}:${nextTaskId}:${now}`);
1256
+ recordConversationTurn(draft, nextTask, idempotencyKey, fingerprint);
1257
+ const message = {
1258
+ id: randomUUID(),
1259
+ roomId: room.id,
1260
+ accountId: acc.id,
1261
+ text: `Approved plan for task ${task.id}. Beginning execution.`,
1262
+ sender: {
1263
+ type: "human",
1264
+ id: acc.id,
1265
+ name: approverName,
1266
+ ...(user ? { sourceDeviceId: user.id } : {}),
1267
+ },
1268
+ createdAt: now,
1269
+ taskIds: [nextTaskId],
1270
+ targetBotIds: [task.botId],
1271
+ ...(conversation ? { conversationId: conversation.id, conversationIds: [conversation.id] } : {}),
1272
+ };
1273
+ draft.messages.push(message);
1274
+ return { plan: task.plan, nextTask };
1275
+ });
1276
+ res.json({ ok: true, plan, nextTaskId: nextTask.id });
1277
+ void drainConversation(nextTask.conversationId).catch(() => { });
1278
+ });
1279
+ app.post("/api/rooms/:id/tasks/:taskId/steer", async (req, res) => {
1280
+ const acc = account(req);
1281
+ const roomId = String(req.params.id);
1282
+ const taskId = String(req.params.taskId);
1283
+ const instruction = text(req.body?.text);
1284
+ if (!instruction)
1285
+ fail(400, "Steering instruction required");
1286
+ const snapshot = store.snapshot();
1287
+ const room = snapshot.rooms.find((r) => r.id === roomId && r.accountId === acc.id);
1288
+ if (!room)
1289
+ fail(404, "Room missing");
1290
+ const task = snapshot.tasks.find((t) => t.id === taskId && t.roomId === roomId && t.accountId === acc.id);
1291
+ if (!task)
1292
+ fail(404, "Task missing");
1293
+ if (task.status !== "running")
1294
+ fail(409, "Steering is only allowed on running tasks");
1295
+ await taskJournalManager
1296
+ .append(task.id, {
1297
+ botId: task.botId,
1298
+ attemptId: task.attemptId,
1299
+ type: "progress",
1300
+ phase: "running",
1301
+ summary: `In-flight steering: ${instruction.slice(0, 100)}`,
1302
+ output: instruction,
1303
+ }, { roomId: task.roomId, accountId: task.accountId })
1304
+ .catch(() => { });
1305
+ await store.transact((draft) => {
1306
+ draft.messages.push({
1307
+ id: randomUUID(),
1308
+ roomId,
1309
+ accountId: acc.id,
1310
+ text: `🕹️ **[飞行中即时转向 / In-flight Steering]** @${task.botId}:\n> ${instruction}`,
1311
+ sender: { type: "human", id: acc.id, name: acc.username },
1312
+ createdAt: Date.now(),
1313
+ taskIds: [task.id],
1314
+ });
1315
+ });
1316
+ const steerRelay = options.onSteer ?? options.relay?.onSteer;
1317
+ if (steerRelay) {
1318
+ await steerRelay(task.deviceId, { taskId: task.id, botId: task.botId, text: instruction }).catch(() => { });
1319
+ }
1320
+ res.json({ success: true, taskId: task.id, steered: true });
1321
+ });
1322
+ app.get("/api/rooms/:id/tasks/:taskId/journal", async (req, res) => {
1323
+ const acc = account(req);
1324
+ const state = store.snapshot();
1325
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === acc.id);
1326
+ if (!room)
1327
+ fail(404, "Room missing");
1328
+ const task = state.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === acc.id);
1329
+ if (!task)
1330
+ fail(404, "Task missing");
1331
+ const cursor = typeof req.query.cursor === "string" ? req.query.cursor : undefined;
1332
+ const limit = typeof req.query.limit === "string" ? parseInt(req.query.limit, 10) : undefined;
1333
+ const direction = req.query.direction === "backward" ? "backward" : "forward";
1334
+ const page = await taskJournalManager.getPage(task.id, acc.id, room.id, { cursor, limit, direction });
1335
+ // The task exists but never wrote a journal segment (queued, failed before the first progress
1336
+ // event, or created before the journal existed). An empty audit trail is a valid state, not a
1337
+ // missing resource: 404 here made every such task render as a broken panel in the UI.
1338
+ if (!page)
1339
+ return res.json({
1340
+ taskId: task.id,
1341
+ items: [],
1342
+ hasMore: false,
1343
+ totalEvents: 0,
1344
+ truncated: false,
1345
+ droppedCount: 0,
1346
+ journalUnavailable: groupEvents.isJournalUnavailable(task.id, task.attemptId),
1347
+ });
1348
+ res.json(page);
1349
+ });
1350
+ app.get("/api/rooms/:id/tasks/:taskId/report", (req, res) => {
1351
+ const acc = account(req);
1352
+ const state = store.snapshot();
1353
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === acc.id);
1354
+ if (!room)
1355
+ fail(404, "Room missing");
1356
+ const task = state.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === acc.id);
1357
+ if (!task)
1358
+ fail(404, "Task missing");
1359
+ const offset = typeof req.query.offset === "string" ? parseInt(req.query.offset, 10) : undefined;
1360
+ const limit = typeof req.query.limit === "string" ? parseInt(req.query.limit, 10) : undefined;
1361
+ const chunkIndex = typeof req.query.chunkIndex === "string" ? parseInt(req.query.chunkIndex, 10) : undefined;
1362
+ if (chunkIndex !== undefined && Number.isSafeInteger(chunkIndex)) {
1363
+ const chunkData = taskReportStore.getReportChunk(task.id, task.attemptId, acc.id, room.id, chunkIndex);
1364
+ if (!chunkData)
1365
+ fail(404, "Report chunk missing");
1366
+ return res.json({ ...chunkData, meta: mergeTaskReportMetadata(task, chunkData.meta) });
1367
+ }
1368
+ const reportData = taskReportStore.getReport(task.id, task.attemptId, acc.id, room.id, { offset, limit });
1369
+ if (!reportData)
1370
+ return res.json({ meta: mergeTaskReportMetadata(task, null) });
1371
+ res.json({ ...reportData, meta: mergeTaskReportMetadata(task, reportData.meta) });
1372
+ });
1373
+ app.post("/api/rooms/:id/tasks/:taskId/report", async (req, res) => {
1374
+ const agent = agents.get(req);
1375
+ if (!agent)
1376
+ fail(403, "Agent authentication required for report upload");
1377
+ const state = store.snapshot();
1378
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === agent.account.id);
1379
+ if (!room)
1380
+ fail(404, "Room missing");
1381
+ const task = state.tasks.find((t) => t.id === req.params.taskId && t.roomId === room.id && t.accountId === agent.account.id);
1382
+ if (!task)
1383
+ fail(404, "Task missing");
1384
+ if (task.deviceId !== agent.device.id)
1385
+ fail(403, "Only assigned execution device may upload reports");
1386
+ const body = req.body ?? {};
1387
+ if (body.taskId !== task.id || body.attemptId !== task.attemptId)
1388
+ fail(409, "Attempt mismatch");
1389
+ if (body.botId !== task.botId)
1390
+ fail(409, "Bot mismatch");
1391
+ if (!Number.isSafeInteger(body.totalBytes) || body.totalBytes < 0 || body.totalBytes > MAX_TASK_FULL_REPORT_BYTES)
1392
+ fail(413, "Full report exceeds 4 MiB quota");
1393
+ if (typeof body.fullSha256 !== "string" || !/^[a-f0-9]{64}$/.test(body.fullSha256))
1394
+ fail(400, "Missing full report hash");
1395
+ const bot = state.bots.find((b) => b.id === task.botId && b.accountId === agent.account.id && b.deviceId === agent.device.id);
1396
+ if (!bot || !bot.enabled || bot.revision !== task.botRevision)
1397
+ fail(409, "Bot revision changed");
1398
+ if (typeof body.text !== "string")
1399
+ fail(400, "Missing report text");
1400
+ const chunkIndex = typeof body.chunkIndex === "number" ? body.chunkIndex : 0;
1401
+ const totalChunks = typeof body.totalChunks === "number" ? body.totalChunks : 1;
1402
+ try {
1403
+ const meta = taskReportStore.appendReportChunk({
1404
+ taskId: task.id,
1405
+ attemptId: task.attemptId,
1406
+ chunkIndex,
1407
+ totalChunks,
1408
+ text: body.text,
1409
+ sha256: typeof body.sha256 === "string" ? body.sha256 : undefined,
1410
+ fullSha256: body.fullSha256,
1411
+ totalBytes: body.totalBytes,
1412
+ isFinal: !!body.isFinal,
1413
+ }, room.id, agent.account.id);
1414
+ if (meta.complete && (meta.sha256 !== body.fullSha256 || meta.totalBytes !== body.totalBytes))
1415
+ fail(409, "Assembled full report integrity mismatch");
1416
+ await store.transact((draft) => {
1417
+ const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
1418
+ if (!current)
1419
+ fail(409, "Report attempt no longer exists");
1420
+ current.reportMetadata = {
1421
+ sha256: meta.complete ? meta.sha256 : body.fullSha256,
1422
+ totalBytes: body.totalBytes,
1423
+ missing: false,
1424
+ rejected: false,
1425
+ uploadPending: !meta.complete,
1426
+ ...(!meta.complete ? { publicError: "report_upload_pending" } : {}),
1427
+ };
1428
+ });
1429
+ res.json({ meta: { ...meta, uploadPending: !meta.complete, missing: false } });
1430
+ }
1431
+ catch (cause) {
1432
+ if (cause?.name === "TaskReportQuotaError") {
1433
+ fail(413, cause.message);
1434
+ }
1435
+ else if (cause?.name === "TaskReportConflictError") {
1436
+ fail(409, cause.message);
1437
+ }
1438
+ else {
1439
+ fail(400, cause?.message ?? "Invalid report chunk");
1440
+ }
1441
+ }
1442
+ });
1443
+ app.get("/api/rooms/:id/history", (req, res) => {
1444
+ const agent = agents.get(req);
1445
+ if (!agent)
1446
+ fail(403, "Agent authentication required");
1447
+ const state = store.snapshot();
1448
+ const room = state.rooms.find((entry) => entry.id === req.params.id && entry.accountId === agent.account.id);
1449
+ const source = state.bots.find((bot) => bot.id === req.query.sourceBotId &&
1450
+ bot.deviceId === agent.device.id &&
1451
+ bot.accountId === agent.account.id &&
1452
+ bot.enabled);
1453
+ if (!room || !source || !room.botIds.includes(source.id))
1454
+ fail(404, "Room missing");
1455
+ if (req.query.before !== undefined && typeof req.query.before !== "string")
1456
+ fail(400, "Invalid history cursor");
1457
+ res.json(groupHistoryPage(room.id, state.messages, req.query.before));
1458
+ });
1459
+ for (const operation of ["rename", "members", "clear", "delete"]) {
471
1460
  app.post(`/api/rooms/:id/${operation}`, async (req, res) => {
472
1461
  const owner = account(req);
473
1462
  const result = await store.transact((draft) => {
@@ -480,42 +1469,521 @@ export async function createDeviceHub(options) {
480
1469
  const members = ids(req.body?.botIds);
481
1470
  if (!members.length || members.some((id) => !validBot(draft, id, owner.id)))
482
1471
  fail(400, "Invalid room Bot");
483
- if (draft.tasks.some((t) => t.roomId === room.id && !isTerminal(t.status) && !members.includes(t.botId)))
1472
+ if (draft.tasks.some((t) => t.roomId === room.id && taskPending(t) && !members.includes(t.botId)))
484
1473
  throw Object.assign(new Error("Stop removed Bots' active tasks first"), {
485
1474
  status: 409,
486
1475
  code: "ACTIVE_TASKS",
487
1476
  });
1477
+ const primaryBotId = req.body?.primaryBotId === undefined
1478
+ ? room.primaryBotId && members.includes(room.primaryBotId)
1479
+ ? room.primaryBotId
1480
+ : undefined
1481
+ : req.body.primaryBotId === null
1482
+ ? undefined
1483
+ : text(req.body.primaryBotId, 128);
1484
+ if (primaryBotId && !members.includes(primaryBotId))
1485
+ fail(400, "Primary Bot must be a room member");
488
1486
  room.botIds = members;
1487
+ room.primaryBotId = primaryBotId;
489
1488
  }
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"), {
1489
+ if (operation === "delete" || operation === "clear") {
1490
+ if (draft.tasks.some((t) => t.roomId === room.id && taskPending(t)))
1491
+ throw Object.assign(new Error("Stop active tasks before clearing or deleting room"), {
493
1492
  status: 409,
494
1493
  code: "ACTIVE_TASKS",
495
1494
  });
496
- draft.rooms = draft.rooms.filter((r) => r.id !== room.id);
1495
+ if (operation === "delete")
1496
+ draft.rooms = draft.rooms.filter((r) => r.id !== room.id);
497
1497
  draft.messages = draft.messages.filter((m) => m.roomId !== room.id);
498
1498
  draft.tasks = draft.tasks.filter((t) => t.roomId !== room.id);
499
1499
  draft.receipts = draft.receipts.filter((r) => r.roomId !== room.id);
500
- return { deleted: true };
1500
+ const removedConversations = new Set(draft.conversations.filter((c) => c.roomId === room.id).map((c) => c.id));
1501
+ draft.conversations = draft.conversations.filter((c) => c.roomId !== room.id);
1502
+ draft.deliveries = draft.deliveries.filter((d) => d.roomId !== room.id);
1503
+ draft.reviews = draft.reviews.filter((r) => r.roomId !== room.id);
1504
+ draft.deliveryReceipts = draft.deliveryReceipts.filter((r) => !removedConversations.has(r.conversationId));
1505
+ draft.conversationMessages = draft.conversationMessages.filter((m) => !removedConversations.has(m.conversationId));
1506
+ return operation === "delete" ? { deleted: true } : { cleared: true };
501
1507
  }
502
1508
  return { room };
503
1509
  });
1510
+ if (operation === "delete" || operation === "clear") {
1511
+ lockManager.clearRoom(String(req.params.id));
1512
+ }
504
1513
  res.json(result);
505
1514
  });
506
1515
  }
507
- app.post("/api/rooms/:id/messages", async (req, res) => {
1516
+ for (const kind of ["deliveries", "reviews"]) {
1517
+ app.post(`/api/rooms/:id/conversations/:conversationId/${kind}`, async (req, res) => {
1518
+ const owner = account(req);
1519
+ const record = await store.transact((draft) => {
1520
+ const actor = { accountId: owner.id, bot: ownBot(req, draft) };
1521
+ return (kind === "deliveries" ? addDelivery : addReview)(draft, req.params.id, req.params.conversationId, actor, req.body);
1522
+ });
1523
+ if (kind === "deliveries") {
1524
+ dispatchGroupWebhook(store, req.params.id, "delivery", record);
1525
+ }
1526
+ res.json(kind === "deliveries" ? { delivery: record } : { review: record });
1527
+ });
1528
+ }
1529
+ app.get("/api/rooms/:id/conversations/:conversationId/integrations", (req, res) => {
1530
+ const owner = account(req);
1531
+ const snapshot = store.snapshot();
1532
+ const conversation = snapshot.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
1533
+ if (!conversation)
1534
+ fail(404, "Conversation missing");
1535
+ res.json({ integrations: listIntegrations(snapshot, req.params.conversationId) });
1536
+ });
1537
+ app.post("/api/rooms/:id/conversations/:conversationId/integrations", async (req, res) => {
1538
+ const owner = account(req);
1539
+ const actor = { accountId: owner.id };
1540
+ if (!options.relay?.callDevice)
1541
+ fail(503, "Device relay unavailable");
1542
+ const driver = {
1543
+ callDeviceCommand: (id, a, p, opts) => options.relay.callDevice(id, a, p, opts),
1544
+ };
1545
+ const result = await hubPrepareIntegration(store, req.params.id, req.params.conversationId, actor, req.body ?? {}, driver);
1546
+ res.json({ integration: result });
1547
+ });
1548
+ app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/verify", async (req, res) => {
1549
+ const owner = account(req);
1550
+ const actor = { accountId: owner.id };
1551
+ if (!options.relay?.callDevice)
1552
+ fail(503, "Device relay unavailable");
1553
+ const driver = {
1554
+ callDeviceCommand: (id, a, p, opts) => options.relay.callDevice(id, a, p, opts),
1555
+ };
1556
+ const result = await hubVerifyIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, req.body ?? {}, driver);
1557
+ res.json({ integration: result });
1558
+ });
1559
+ app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/apply", async (req, res) => {
1560
+ const owner = account(req);
1561
+ const actor = { accountId: owner.id };
1562
+ if (!options.relay?.callDevice)
1563
+ fail(503, "Device relay unavailable");
1564
+ const driver = {
1565
+ callDeviceCommand: (id, a, p, opts) => options.relay.callDevice(id, a, p, opts),
1566
+ };
1567
+ const result = await hubConfirmIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, req.body ?? {}, driver);
1568
+ res.json({ integration: result });
1569
+ });
1570
+ app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/cancel", async (req, res) => {
1571
+ const owner = account(req);
1572
+ const actor = { accountId: owner.id };
1573
+ if (!options.relay?.callDevice)
1574
+ fail(503, "Device relay unavailable");
1575
+ const driver = {
1576
+ callDeviceCommand: (id, a, p, opts) => options.relay.callDevice(id, a, p, opts),
1577
+ };
1578
+ const result = await hubCancelIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, driver);
1579
+ res.json({ integration: result });
1580
+ });
1581
+ app.post("/api/rooms/:id/conversations/:conversationId/stop", async (req, res) => {
1582
+ const owner = account(req);
1583
+ const pending = await store.transact((draft) => {
1584
+ const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
1585
+ const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
1586
+ if (!conversation || !room)
1587
+ fail(404, "Conversation missing");
1588
+ const source = ownBot(req, draft);
1589
+ if (source && (!room.botIds.includes(source.id) || conversation.botId !== source.id))
1590
+ fail(403, "Bot may stop only its own conversation");
1591
+ conversation.closed = true;
1592
+ conversation.closedReason = "stopped";
1593
+ const tasks = draft.tasks.filter((t) => t.conversationId === conversation.id && taskPending(t));
1594
+ for (const task of tasks) {
1595
+ task.cancelRequested = true;
1596
+ if ((task.status === "queued" || task.status === "waiting") && !deliveredTasks.has(task.id)) {
1597
+ task.stopConfirmed = true;
1598
+ task.status = "interrupted";
1599
+ task.updatedAt = Date.now();
1600
+ task.report = "Conversation stopped before delivery.";
1601
+ }
1602
+ }
1603
+ return tasks;
1604
+ });
1605
+ for (const task of pending) {
1606
+ if (task.stopConfirmed) {
1607
+ await releaseLocksAndWake(String(req.params.id), task.id);
1608
+ continue;
1609
+ }
1610
+ const confirmed = await options.relay
1611
+ ?.cancelTask?.(task.deviceId, task.id, task.attemptId)
1612
+ .catch(() => ({ stopped: false }));
1613
+ if (!confirmed?.stopped)
1614
+ continue;
1615
+ await store.transact((draft) => {
1616
+ const current = draft.tasks.find((t) => t.id === task.id && t.attemptId === task.attemptId);
1617
+ if (!current)
1618
+ return;
1619
+ current.stopConfirmed = true;
1620
+ current.status = "interrupted";
1621
+ current.updatedAt = Date.now();
1622
+ current.report = "Conversation stopped.";
1623
+ });
1624
+ await releaseLocksAndWake(String(req.params.id), task.id);
1625
+ }
1626
+ const remaining = store
1627
+ .snapshot()
1628
+ .tasks.filter((t) => t.conversationId === req.params.conversationId && taskPending(t));
1629
+ res.json({ stopped: remaining.length === 0, pending: remaining.length });
1630
+ });
1631
+ app.post("/api/rooms/:id/conversations/:conversationId/delete", async (req, res) => {
1632
+ const owner = account(req);
1633
+ if (agents.has(req))
1634
+ fail(403, "Conversation deletion requires a user session");
1635
+ const result = await store.transact((draft) => {
1636
+ const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
1637
+ const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
1638
+ if (!room || !conversation)
1639
+ fail(404, "Conversation missing");
1640
+ if (draft.tasks.some((t) => t.conversationId === conversation.id && taskPending(t)))
1641
+ throw Object.assign(new Error("Stop the conversation before deleting it"), {
1642
+ status: 409,
1643
+ code: "ACTIVE_TASKS",
1644
+ });
1645
+ // Delivery/review records are the audit trail; deleting them is a separate, explicit decision.
1646
+ if (conversationHasAuditRecords(draft, conversation.id))
1647
+ fail(409, "Conversation has delivery history; audit records are retained");
1648
+ dropConversationRecords(draft, conversation.id);
1649
+ return { deleted: true };
1650
+ });
1651
+ groupEvents.invalidate(String(req.params.id));
1652
+ res.json(result);
1653
+ });
1654
+ app.post("/api/rooms/:id/conversations/:conversationId/attention", async (req, res) => {
1655
+ const owner = account(req);
1656
+ const question = text(req.body?.question, 2000);
1657
+ const kind = req.body?.kind;
1658
+ if (kind !== "answer" && kind !== "decision")
1659
+ fail(400, "Invalid attention kind");
1660
+ const parentTaskId = text(req.body?.parentTaskId, 128);
1661
+ const result = await store.transact((draft) => {
1662
+ const source = ownBot(req, draft);
1663
+ if (!source)
1664
+ fail(403, "Bot authentication required");
1665
+ const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
1666
+ const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === room?.id && c.accountId === owner.id);
1667
+ const task = draft.tasks.find((t) => t.id === parentTaskId &&
1668
+ t.conversationId === conversation?.id &&
1669
+ t.botId === source.id &&
1670
+ t.status === "running" &&
1671
+ !t.cancelRequested);
1672
+ if (!room ||
1673
+ !room.botIds.includes(source.id) ||
1674
+ !conversation ||
1675
+ conversation.closed ||
1676
+ conversation.botId !== source.id ||
1677
+ !task ||
1678
+ conversation.latestTaskId !== task.id)
1679
+ fail(409, "Attention requires the current running Bot task");
1680
+ if (conversation.attention) {
1681
+ if (conversation.attention.taskId === task.id &&
1682
+ conversation.attention.question === question &&
1683
+ conversation.attention.kind === kind)
1684
+ return conversation.attention;
1685
+ fail(409, "An unanswered question already exists");
1686
+ }
1687
+ conversation.attention = { id: randomUUID(), taskId: task.id, kind, question, createdAt: Date.now() };
1688
+ return conversation.attention;
1689
+ });
1690
+ res.json({ attention: result });
1691
+ });
1692
+ app.get("/api/rooms/:id/conversations/:conversationId/task-state", (req, res) => {
1693
+ const state = store.snapshot();
1694
+ const owner = account(req);
1695
+ const room = state.rooms.find((entry) => entry.id === req.params.id && entry.accountId === owner.id);
1696
+ const agent = agents.get(req);
1697
+ if (!room ||
1698
+ (agent &&
1699
+ !state.bots.some((bot) => bot.id === req.query.sourceBotId &&
1700
+ bot.deviceId === agent.device.id &&
1701
+ bot.accountId === owner.id &&
1702
+ bot.enabled &&
1703
+ room.botIds.includes(bot.id))))
1704
+ fail(404, "Room missing");
1705
+ const conversation = state.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room.id && entry.accountId === owner.id);
1706
+ if (!conversation)
1707
+ fail(404, "Conversation missing");
1708
+ const allowedQueries = ["sourceBotId", "beforeSequence", "summaryOnly"];
1709
+ for (const q of Object.keys(req.query)) {
1710
+ if (!allowedQueries.includes(q))
1711
+ fail(400, `Unknown query parameter: ${q}`);
1712
+ }
1713
+ let events = conversation.events ?? [];
1714
+ if (req.query.beforeSequence !== undefined) {
1715
+ const seq = Number(req.query.beforeSequence);
1716
+ if (!Number.isSafeInteger(seq) || seq < 0)
1717
+ fail(400, "Invalid beforeSequence");
1718
+ events = events.filter((e) => e.sequence < seq);
1719
+ }
1720
+ if (req.query.summaryOnly !== undefined && !["true", "false"].includes(String(req.query.summaryOnly))) {
1721
+ fail(400, "Invalid summaryOnly parameter");
1722
+ }
1723
+ const summary = conversation.taskState ? buildDeterministicTaskSummary(conversation.taskState) : undefined;
1724
+ if (req.query.summaryOnly === "true") {
1725
+ res.json({ summary, taskState: conversation.taskState });
1726
+ return;
1727
+ }
1728
+ res.json({ taskState: conversation.taskState, events, ...(summary ? { summary } : {}) });
1729
+ });
1730
+ app.get("/api/rooms/:id/conversations/:conversationId/evidence", (req, res) => {
1731
+ const state = store.snapshot();
1732
+ const owner = account(req);
1733
+ const room = state.rooms.find((entry) => entry.id === req.params.id && entry.accountId === owner.id);
1734
+ const agent = agents.get(req);
1735
+ if (!room ||
1736
+ (agent &&
1737
+ !state.bots.some((bot) => bot.id === req.query.sourceBotId &&
1738
+ bot.deviceId === agent.device.id &&
1739
+ bot.accountId === owner.id &&
1740
+ bot.enabled &&
1741
+ room.botIds.includes(bot.id))))
1742
+ fail(404, "Room missing");
1743
+ const conversation = state.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room.id && entry.accountId === owner.id);
1744
+ if (!conversation)
1745
+ fail(404, "Conversation missing");
1746
+ const allowedQueries = ["sourceBotId", "taskId", "deliveryId", "offset", "limit", "expectedDigest", "digest"];
1747
+ for (const q of Object.keys(req.query)) {
1748
+ if (!allowedQueries.includes(q))
1749
+ fail(400, `Unknown query parameter: ${q}`);
1750
+ }
1751
+ let offset = 0;
1752
+ if (req.query.offset !== undefined) {
1753
+ offset = Number(req.query.offset);
1754
+ if (!Number.isSafeInteger(offset) || offset < 0)
1755
+ fail(400, "Invalid offset");
1756
+ }
1757
+ let limit = 8192;
1758
+ if (req.query.limit !== undefined) {
1759
+ limit = Number(req.query.limit);
1760
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 65536)
1761
+ fail(400, "Invalid limit");
1762
+ }
1763
+ const expectedDigest = typeof req.query.expectedDigest === "string"
1764
+ ? req.query.expectedDigest
1765
+ : typeof req.query.digest === "string"
1766
+ ? req.query.digest
1767
+ : undefined;
1768
+ const taskId = typeof req.query.taskId === "string" ? req.query.taskId : conversation.latestTaskId;
1769
+ const targetTask = state.tasks.find((t) => t.id === taskId && t.conversationId === conversation.id);
1770
+ const deliveryId = typeof req.query.deliveryId === "string" ? req.query.deliveryId : undefined;
1771
+ const targetDelivery = deliveryId
1772
+ ? state.deliveries.find((d) => d.id === deliveryId && d.conversationId === conversation.id)
1773
+ : undefined;
1774
+ let evidence;
1775
+ if (targetTask?.attemptId) {
1776
+ const reportResult = taskReportStore.getReport(targetTask.id, targetTask.attemptId, owner.id, room.id, {
1777
+ offset,
1778
+ limit,
1779
+ expectedDigest,
1780
+ revision: conversation.taskState?.revision,
1781
+ });
1782
+ if (reportResult?.versionMismatch) {
1783
+ fail(409, "Report version digest mismatch; start reading from offset 0 with new digest");
1784
+ }
1785
+ if (reportResult && reportResult.text !== undefined) {
1786
+ evidence = {
1787
+ taskId: targetTask.id,
1788
+ attemptId: targetTask.attemptId,
1789
+ revision: conversation.taskState?.revision,
1790
+ totalBytes: reportResult.meta.totalBytes,
1791
+ offset: reportResult.offset ?? offset,
1792
+ limit: reportResult.limit ?? limit,
1793
+ chunk: reportResult.text,
1794
+ hasMore: reportResult.hasMore ?? false,
1795
+ nextOffset: reportResult.nextOffset ?? null,
1796
+ isExcerpt: (reportResult.hasMore ?? false) || (reportResult.offset ?? 0) > 0,
1797
+ complete: reportResult.meta.complete,
1798
+ source: "full_report",
1799
+ reportRef: reportResult.meta.storageLocation.reportRef,
1800
+ digest: reportResult.digest ?? "",
1801
+ sha256: reportResult.sha256 ?? reportResult.meta.sha256 ?? "",
1802
+ };
1803
+ }
1804
+ }
1805
+ if (!evidence && targetTask?.report) {
1806
+ const chunk = queryTaskReportChunk(targetTask.id, targetTask.report, offset, limit, {
1807
+ attemptId: targetTask.attemptId,
1808
+ revision: conversation.taskState?.revision,
1809
+ source: "report_excerpt",
1810
+ complete: false,
1811
+ });
1812
+ if (expectedDigest && chunk.digest !== expectedDigest) {
1813
+ fail(409, "Report version digest mismatch; start reading from offset 0 with new digest");
1814
+ }
1815
+ evidence = chunk;
1816
+ }
1817
+ res.json({
1818
+ conversationId: conversation.id,
1819
+ taskId,
1820
+ ...(evidence ? { evidence } : {}),
1821
+ ...(targetDelivery ? { delivery: targetDelivery } : {}),
1822
+ summary: conversation.taskState ? buildDeterministicTaskSummary(conversation.taskState) : undefined,
1823
+ });
1824
+ });
1825
+ app.post("/api/rooms/:id/conversations/:conversationId/task-state", async (req, res) => {
1826
+ const owner = account(req);
1827
+ const body = req.body;
1828
+ if (!body ||
1829
+ typeof body !== "object" ||
1830
+ Array.isArray(body) ||
1831
+ Object.keys(body).some((key) => ![
1832
+ "sourceBotId",
1833
+ "parentTaskId",
1834
+ "expectedRevision",
1835
+ "constraints",
1836
+ "progress",
1837
+ "blockers",
1838
+ "nextSteps",
1839
+ ].includes(key)) ||
1840
+ !Number.isSafeInteger(body.expectedRevision) ||
1841
+ body.expectedRevision < 0)
1842
+ fail(400, "Invalid task state update");
1843
+ const parentTaskId = text(body.parentTaskId, 128);
1844
+ const changes = {};
1845
+ for (const key of ["constraints", "blockers", "nextSteps"]) {
1846
+ const value = body[key];
1847
+ if (value === undefined)
1848
+ continue;
1849
+ if (!Array.isArray(value) ||
1850
+ value.length > 20 ||
1851
+ value.some((item) => typeof item !== "string" || !item.trim() || item.length > 500))
1852
+ fail(400, "Invalid task state list");
1853
+ changes[key] = [...value];
1854
+ }
1855
+ if (body.progress !== undefined) {
1856
+ if (typeof body.progress !== "string" || body.progress.length > 2000)
1857
+ fail(400, "Invalid progress");
1858
+ changes.progress = body.progress;
1859
+ }
1860
+ if (!Object.keys(changes).length)
1861
+ fail(400, "Task state update is empty");
1862
+ const conversation = await store.transact((draft) => {
1863
+ const source = ownBot(req, draft);
1864
+ if (!source)
1865
+ fail(403, "Bot authentication required");
1866
+ const room = draft.rooms.find((entry) => entry.id === req.params.id && entry.accountId === owner.id);
1867
+ const current = draft.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room?.id && entry.accountId === owner.id);
1868
+ const task = draft.tasks.find((entry) => entry.id === parentTaskId &&
1869
+ entry.conversationId === current?.id &&
1870
+ entry.botId === source.id &&
1871
+ entry.status === "running" &&
1872
+ !entry.cancelRequested);
1873
+ if (!room ||
1874
+ !room.botIds.includes(source.id) ||
1875
+ !current ||
1876
+ current.closed ||
1877
+ current.botId !== source.id ||
1878
+ !task ||
1879
+ current.latestTaskId !== task.id ||
1880
+ !current.taskState)
1881
+ fail(409, "Task state update requires the current running Bot task");
1882
+ if (current.taskState.revision !== body.expectedRevision)
1883
+ fail(409, "Task state revision changed; read task_state again");
1884
+ const previous = current.taskState.reported;
1885
+ const next = {
1886
+ constraints: [],
1887
+ progress: "",
1888
+ blockers: [],
1889
+ nextSteps: [],
1890
+ ...previous,
1891
+ ...changes,
1892
+ taskId: task.id,
1893
+ botId: source.id,
1894
+ provenance: "bot_reported",
1895
+ updatedAt: previous?.updatedAt ?? Date.now(),
1896
+ };
1897
+ if (JSON.stringify(next) !== JSON.stringify(previous))
1898
+ next.updatedAt = Date.now();
1899
+ current.taskState.reported = next;
1900
+ return current;
1901
+ });
1902
+ res.json({ taskState: conversation.taskState, events: conversation.events ?? [] });
1903
+ });
1904
+ app.get(["/api/rooms/:id/conversations", "/api/rooms/:id/conversations/:conversationId"], (req, res) => {
1905
+ const state = store.snapshot();
1906
+ const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === account(req).id);
1907
+ const agent = agents.get(req);
1908
+ if (!room ||
1909
+ (agent &&
1910
+ !state.bots.some((b) => b.id === req.query.sourceBotId &&
1911
+ b.deviceId === agent.device.id &&
1912
+ b.accountId === room.accountId &&
1913
+ b.enabled &&
1914
+ room.botIds.includes(b.id))))
1915
+ fail(404, "Room missing");
1916
+ const conversations = state.conversations
1917
+ .filter((c) => c.roomId === room.id && c.accountId === room.accountId)
1918
+ .sort((a, b) => b.updatedAt - a.updatedAt)
1919
+ .map((c) => ({
1920
+ ...c,
1921
+ status: conversationStatus(state, c),
1922
+ stale: conversationStale(state, c),
1923
+ ...deliverySummary(state, c.id, !req.params.conversationId),
1924
+ }));
1925
+ if (!req.params.conversationId)
1926
+ return res.json({ conversations });
1927
+ const conversation = conversations.find((c) => c.id === req.params.conversationId);
1928
+ if (!conversation)
1929
+ fail(404, "Conversation missing");
1930
+ if (req.query.before !== undefined && typeof req.query.before !== "string")
1931
+ fail(400, "Invalid conversation cursor");
1932
+ res.json({
1933
+ conversation,
1934
+ ...conversationPage(state, conversation.id, req.query.before),
1935
+ ...deliveryHistory(state, conversation.id),
1936
+ });
1937
+ });
1938
+ app.post([
1939
+ "/api/rooms/:id/messages",
1940
+ "/api/rooms/:id/conversations",
1941
+ "/api/rooms/:id/conversations/:conversationId/messages",
1942
+ ], async (req, res) => {
508
1943
  const owner = account(req);
509
1944
  const content = text(req.body?.text);
510
- const targets = ids(req.body?.targetBotIds ?? []);
1945
+ const conversationApi = req.path.includes("/conversations");
1946
+ const conversationId = req.params.conversationId;
1947
+ const kind = req.body?.kind ?? "message";
1948
+ const settings = currentSettings();
1949
+ if (!["message", "request", "reply"].includes(kind))
1950
+ fail(400, "Invalid message kind");
1951
+ const requestId = req.body?.requestId === undefined
1952
+ ? kind === "request"
1953
+ ? randomUUID()
1954
+ : undefined
1955
+ : text(req.body.requestId, 128);
1956
+ if (kind === "reply" && !requestId)
1957
+ fail(400, "Reply requires requestId");
1958
+ const targets = ids(conversationApi ? (conversationId ? [] : [text(req.body?.targetBotId, 128)]) : (req.body?.targetBotIds ?? []));
511
1959
  const transfer = handoff(req.body?.handoff);
512
1960
  const parentTaskId = req.body?.parentTaskId === undefined ? undefined : text(req.body.parentTaskId, 128);
1961
+ const attentionId = req.body?.attentionId === undefined ? undefined : text(req.body.attentionId, 128);
513
1962
  const key = req.body?.idempotencyKey === undefined ? randomUUID() : text(req.body.idempotencyKey, 128);
1963
+ const planOnly = req.body?.planOnly === true;
1964
+ const replyToMessageId = req.body?.replyToMessageId === undefined ? undefined : text(req.body.replyToMessageId, 128);
1965
+ const dependsOnTaskId = req.body?.dependsOnTaskId === undefined ? undefined : text(req.body.dependsOnTaskId, 128);
1966
+ let resourceLocks;
1967
+ try {
1968
+ if (req.body?.resourceLocks !== undefined) {
1969
+ resourceLocks = validateResourceLocks(req.body.resourceLocks);
1970
+ }
1971
+ }
1972
+ catch (err) {
1973
+ fail(400, err?.message ?? "Invalid resourceLocks");
1974
+ }
514
1975
  const fingerprint = hashSecret(JSON.stringify({
515
1976
  content,
1977
+ attentionId,
516
1978
  targets,
1979
+ conversationId,
1980
+ kind,
1981
+ requestId: req.body?.requestId,
517
1982
  transfer,
518
1983
  parentTaskId,
1984
+ planOnly,
1985
+ replyToMessageId,
1986
+ resourceLocks,
519
1987
  sourceDeviceId: (agents.get(req) ?? users.get(req))?.device.id,
520
1988
  sourceBotId: agents.has(req) ? req.body?.sourceBotId : undefined,
521
1989
  senderType: agents.has(req) ? "bot" : "human",
@@ -526,10 +1994,57 @@ export async function createDeviceHub(options) {
526
1994
  fail(404, "Room missing");
527
1995
  const source = ownBot(req, draft);
528
1996
  const userSource = users.get(req)?.device;
1997
+ let conversation = conversationId
1998
+ ? draft.conversations.find((c) => c.id === conversationId && c.roomId === room.id && c.accountId === owner.id)
1999
+ : undefined;
2000
+ if (conversationId && !conversation)
2001
+ fail(404, "Conversation missing");
2002
+ if (conversation?.closed)
2003
+ fail(409, "Conversation is closed");
2004
+ if (conversation) {
2005
+ const bot = validBot(draft, conversation.botId, owner.id);
2006
+ if (!bot || bot.revision !== conversation.botRevision || bot.deviceId !== conversation.deviceId)
2007
+ fail(409, "Conversation Bot configuration changed");
2008
+ targets.push(conversation.botId);
2009
+ }
529
2010
  if (source && !room.botIds.includes(source.id))
530
2011
  fail(403, "Source Bot is not a room member");
2012
+ if (replyToMessageId && !draft.messages.some((m) => m.id === replyToMessageId && m.roomId === room.id))
2013
+ fail(400, "Reply target message is not in this room");
2014
+ if (dependsOnTaskId && !draft.tasks.some((m) => m.id === dependsOnTaskId && m.roomId === room.id))
2015
+ fail(400, "Dependency target task is not in this room");
2016
+ const depTask = dependsOnTaskId ? draft.tasks.find((t) => t.id === dependsOnTaskId) : undefined;
2017
+ const dependencyActive = Boolean(depTask && !isTerminal(depTask.status));
2018
+ // The Hub owns dispatch semantics: a human message that only names Bots in its text must not
2019
+ // silently fall back to the primary Bot just because a client did not pre-resolve the mentions.
2020
+ const canParseMentions = (!source || settings.allowBotMentions) && !conversationApi && !conversation && !targets.length;
2021
+ if (canParseMentions)
2022
+ targets.push(...groupMentionTargets(content, room, draft.bots, settings.botMentionBudgetPerTurn));
531
2023
  if (targets.some((id) => !room.botIds.includes(id) || !validBot(draft, id, owner.id)))
532
2024
  fail(400, "Invalid target Bot");
2025
+ if (source &&
2026
+ targets.length &&
2027
+ !draft.tasks.some((t) => t.id === parentTaskId &&
2028
+ t.botId === source.id &&
2029
+ t.accountId === owner.id &&
2030
+ t.roomId === room.id &&
2031
+ (t.status === "running" || isTerminal(t.status))))
2032
+ fail(400, "Device dispatch requires its own bound parent task");
2033
+ {
2034
+ const prior = draft.conversationMessages.find((m) => conversationId !== undefined &&
2035
+ m.conversationId === conversationId &&
2036
+ m.idempotencyKey === key &&
2037
+ draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id && c.accountId === owner.id));
2038
+ if (prior) {
2039
+ if (prior.fingerprint !== fingerprint)
2040
+ fail(409, "Idempotency key reused");
2041
+ return {
2042
+ message: draft.messages.find((m) => m.taskIds.includes(prior.taskId)),
2043
+ tasks: draft.tasks.filter((t) => t.id === prior.taskId),
2044
+ duplicate: true,
2045
+ };
2046
+ }
2047
+ }
533
2048
  const receipt = draft.receipts.find((r) => r.roomId === room.id && r.accountId === owner.id && r.key === key);
534
2049
  if (receipt) {
535
2050
  if (receipt.fingerprint !== fingerprint)
@@ -540,48 +2055,156 @@ export async function createDeviceHub(options) {
540
2055
  duplicate: true,
541
2056
  };
542
2057
  }
2058
+ // Resolve implicit human targets after replay detection so retries remain stable across configuration changes.
2059
+ if (!source && !conversationApi && !targets.length && room.primaryBotId) {
2060
+ if (!room.botIds.includes(room.primaryBotId) || !validBot(draft, room.primaryBotId, owner.id))
2061
+ fail(400, "Primary Bot is unavailable");
2062
+ targets.push(room.primaryBotId);
2063
+ const bot = validBot(draft, room.primaryBotId, owner.id);
2064
+ conversation = draft.conversations
2065
+ .filter((entry) => entry.roomId === room.id &&
2066
+ entry.accountId === owner.id &&
2067
+ entry.botId === bot.id &&
2068
+ !entry.closed &&
2069
+ entry.botRevision === bot.revision &&
2070
+ entry.deviceId === bot.deviceId)
2071
+ .sort((a, b) => b.updatedAt - a.updatedAt)[0];
2072
+ }
2073
+ if (attentionId) {
2074
+ if (source || !conversationId || !conversation || conversation.attention?.id !== attentionId)
2075
+ fail(409, "Question changed or already answered");
2076
+ delete conversation.attention;
2077
+ }
2078
+ if (kind === "reply") {
2079
+ const request = draft.conversationMessages.find((m) => m.kind === "request" &&
2080
+ m.requestId === requestId &&
2081
+ draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id && c.accountId === owner.id));
2082
+ const requestedConversation = draft.conversations.find((c) => c.id === request?.conversationId);
2083
+ if (!request ||
2084
+ !requestedConversation ||
2085
+ source?.id !== requestedConversation.botId ||
2086
+ !conversation ||
2087
+ conversation.botId !== request.sourceBotId ||
2088
+ conversation.id !== draft.tasks.find((t) => t.id === request.taskId)?.sourceConversationId ||
2089
+ draft.tasks.find((t) => t.id === parentTaskId)?.conversationId !== request.conversationId)
2090
+ fail(403, "Reply must address the original requester from the requested Bot");
2091
+ if (draft.tasks.some((t) => t.resultOfTaskId === request.taskId))
2092
+ fail(409, "Request already completed");
2093
+ if (draft.conversationMessages.some((m) => m.kind === "reply" &&
2094
+ m.requestId === requestId &&
2095
+ m.idempotencyKey !== key &&
2096
+ draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id)))
2097
+ fail(409, "Request already answered");
2098
+ }
543
2099
  if (parentTaskId &&
544
2100
  !draft.tasks.some((t) => t.id === parentTaskId &&
545
2101
  t.roomId === room.id &&
546
2102
  t.accountId === owner.id &&
547
2103
  (isTerminal(t.status) || (source?.id === t.botId && t.status === "running"))))
548
2104
  fail(400, "Parent task must be terminal or the source device's running task in this room");
2105
+ if (kind === "request" &&
2106
+ draft.conversationMessages.some((m) => m.kind === "request" &&
2107
+ m.requestId === requestId &&
2108
+ draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id)))
2109
+ fail(409, "Request ID already exists");
549
2110
  const parent = parentTaskId ? draft.tasks.find((t) => t.id === parentTaskId) : undefined;
550
2111
  if (source && targets.length && (!parent || parent.botId !== source.id))
551
2112
  fail(400, "Device dispatch requires its own running or terminal parent task");
2113
+ // Explicit human input grants a new lineage; autonomous work always inherits its real parent.
552
2114
  const root = parent ? draft.tasks.find((t) => t.id === (parent.rootTaskId ?? parent.id)) : undefined;
553
2115
  if (parent && targets.length && !root)
554
2116
  fail(409, "Dispatch root expired");
555
2117
  const depth = parent ? (parent.dispatchDepth ?? 0) + 1 : 0;
556
- if (targets.length && depth > 8)
2118
+ if (planOnly && targets.some((id) => !validBot(draft, id, owner.id)?.tools?.includes("plan_update")))
2119
+ fail(409, "Planning requires plan_update authorization in each Bot tool allowlist");
2120
+ if (targets.length && depth > settings.maxDispatchDepth)
557
2121
  fail(409, "Dispatch depth exhausted");
558
- if (targets.length && (root?.dispatchCount ?? 0) + targets.length > 16)
2122
+ if (targets.length && (root?.dispatchCount ?? 0) + targets.length > settings.maxDispatchBudget)
559
2123
  fail(409, "Dispatch budget exhausted");
560
2124
  if (root && targets.length)
561
2125
  root.dispatchCount = (root.dispatchCount ?? 0) + targets.length;
562
- if (draft.tasks.filter((t) => t.roomId === room.id && !isTerminal(t.status)).length + targets.length > HISTORY)
2126
+ if (draft.tasks.filter((t) => t.roomId === room.id && taskPending(t)).length + targets.length >
2127
+ getHistoryLimit())
563
2128
  fail(409, "Too many active tasks");
2129
+ if (!conversation &&
2130
+ draft.conversations.filter((c) => c.roomId === room.id && !c.closed).length + targets.length >
2131
+ getHistoryLimit())
2132
+ fail(409, "Too many open conversations; stop or delete conversations to free capacity");
564
2133
  const now = Date.now();
565
2134
  const rootId = root?.id ?? randomUUID();
566
- const tasks = targets.map((botId, index) => ({
567
- id: !root && index === 0 ? rootId : randomUUID(),
568
- rootTaskId: rootId,
569
- dispatchDepth: depth,
570
- ...(!root && index === 0 ? { dispatchCount: targets.length } : {}),
571
- attemptId: randomUUID(),
572
- roomId: room.id,
573
- accountId: owner.id,
574
- botId,
575
- deviceId: validBot(draft, botId, owner.id).deviceId,
576
- botRevision: validBot(draft, botId, owner.id).revision,
577
- ...(source ? { sourceBotId: source.id } : {}),
578
- text: content,
579
- status: "queued",
580
- createdAt: now,
581
- updatedAt: now,
582
- ...(transfer ? { handoff: transfer } : {}),
583
- ...(parentTaskId ? { parentTaskId } : {}),
584
- }));
2135
+ const tasks = targets.map((botId, index) => {
2136
+ const targetBot = validBot(draft, botId, owner.id);
2137
+ let attenuatedTools;
2138
+ if (source) {
2139
+ const rawSourceTools = source.tools ?? [];
2140
+ const sourceTools = parent?.attenuatedTools
2141
+ ? rawSourceTools.filter((t) => !parent.attenuatedTools.includes(t))
2142
+ : rawSourceTools;
2143
+ const attenuated = computeAttenuatedTools(sourceTools, targetBot.tools ?? []);
2144
+ if (attenuated.length > 0) {
2145
+ attenuatedTools = attenuated;
2146
+ }
2147
+ }
2148
+ return {
2149
+ id: !root && index === 0 ? rootId : randomUUID(),
2150
+ rootTaskId: rootId,
2151
+ dispatchDepth: depth,
2152
+ ...(!root && index === 0 ? { dispatchCount: targets.length } : {}),
2153
+ attemptId: randomUUID(),
2154
+ roomId: room.id,
2155
+ accountId: owner.id,
2156
+ botId,
2157
+ deviceId: targetBot.deviceId,
2158
+ botRevision: targetBot.revision,
2159
+ ...(source ? { sourceBotId: source.id } : {}),
2160
+ text: content,
2161
+ status: dependencyActive ? "waiting" : "queued",
2162
+ ...(dependencyActive
2163
+ ? {
2164
+ blockReason: "dependency_waiting",
2165
+ blockReasonDetail: `Waiting for dependency task ${dependsOnTaskId}`,
2166
+ dependsOnTaskId,
2167
+ }
2168
+ : dependsOnTaskId
2169
+ ? { dependsOnTaskId }
2170
+ : {}),
2171
+ createdAt: now,
2172
+ updatedAt: now,
2173
+ ...(resourceLocks && resourceLocks.length ? { resourceLocks } : {}),
2174
+ ...(planOnly ? { planOnly: true, plan: { state: "draft", steps: [] } } : {}),
2175
+ ...(transfer ? { handoff: transfer } : {}),
2176
+ ...(parentTaskId ? { parentTaskId } : {}),
2177
+ ...(attenuatedTools ? { attenuatedTools } : {}),
2178
+ };
2179
+ });
2180
+ for (const task of tasks) {
2181
+ task.kind = kind;
2182
+ task.sourceConversationId = parent?.conversationId;
2183
+ task.requestId = requestId;
2184
+ const targetConv = conversation && conversation.botId === task.botId
2185
+ ? conversation
2186
+ : !source && !conversationApi && req.body?.newConversation !== true
2187
+ ? draft.conversations
2188
+ .filter((entry) => entry.roomId === room.id &&
2189
+ entry.accountId === owner.id &&
2190
+ entry.botId === task.botId &&
2191
+ !entry.closed &&
2192
+ entry.botRevision === task.botRevision &&
2193
+ entry.deviceId === task.deviceId)
2194
+ .sort((a, b) => b.updatedAt - a.updatedAt)[0]
2195
+ : undefined;
2196
+ if (targetConv) {
2197
+ task.conversationId = targetConv.id;
2198
+ task.resume = true;
2199
+ advanceConversationTask(draft, targetConv, task);
2200
+ targetConv.rootTaskId = task.rootTaskId;
2201
+ targetConv.updatedAt = now;
2202
+ targetConv.dispatchDepth = depth;
2203
+ }
2204
+ else
2205
+ establishConversation(draft, task);
2206
+ recordConversationTurn(draft, task, key, fingerprint);
2207
+ }
585
2208
  const message = {
586
2209
  id: randomUUID(),
587
2210
  roomId: room.id,
@@ -598,70 +2221,82 @@ export async function createDeviceHub(options) {
598
2221
  createdAt: now,
599
2222
  taskIds: tasks.map((t) => t.id),
600
2223
  targetBotIds: targets,
2224
+ ...(replyToMessageId ? { replyToMessageId } : {}),
2225
+ ...(tasks.length === 1 ? { conversationId: tasks[0].conversationId } : {}),
2226
+ ...(tasks.length ? { conversationIds: tasks.map((task) => task.conversationId) } : {}),
601
2227
  };
2228
+ // Freeze shared context before any recipient starts. Parallel answers cannot leak into siblings.
2229
+ const context = tasks.length
2230
+ ? groupTaskContext(room, draft.bots, draft.messages, settings.groupContextBytes)
2231
+ : undefined;
602
2232
  draft.tasks.push(...tasks);
603
2233
  draft.messages.push(message);
604
- draft.receipts.push({ accountId: owner.id, roomId: room.id, key, fingerprint, messageId: message.id });
605
- const oldMessages = draft.messages.filter((m) => m.roomId === room.id).slice(0, -HISTORY);
2234
+ draft.receipts.push({
2235
+ accountId: owner.id,
2236
+ roomId: room.id,
2237
+ key,
2238
+ fingerprint,
2239
+ messageId: message.id,
2240
+ createdAt: message.createdAt,
2241
+ });
2242
+ const oldMessages = draft.messages.filter((m) => m.roomId === room.id).slice(0, -getHistoryLimit());
606
2243
  const removed = new Set(oldMessages.map((m) => m.id));
2244
+ // Retention evicts messages, never the replay guard: a retry must not re-dispatch evicted work.
607
2245
  draft.messages = draft.messages.filter((m) => !removed.has(m.id));
608
- draft.receipts = draft.receipts.filter((r) => !removed.has(r.messageId));
2246
+ trimRoomReceipts(draft, room.id);
609
2247
  const oldTasks = new Set(draft.tasks
610
- .filter((t) => t.roomId === room.id && isTerminal(t.status))
611
- .slice(0, -HISTORY)
2248
+ .filter((t) => t.roomId === room.id &&
2249
+ isTerminal(t.status) &&
2250
+ !draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
2251
+ .slice(0, -getHistoryLimit())
612
2252
  .map((t) => t.id));
613
2253
  draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
614
- return { message, tasks, duplicate: false };
2254
+ trimConversationHistory(draft, room.id);
2255
+ trimClosedConversations(draft, room.id);
2256
+ return { message, tasks, duplicate: false, context };
615
2257
  });
616
2258
  if (!result.duplicate) {
617
2259
  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
- }
2260
+ if (task.status !== "waiting")
2261
+ await deliverTask(task, result.context);
2262
+ }
2263
+ if (result.message) {
2264
+ dispatchGroupWebhook(store, req.params.id, "message", result.message);
658
2265
  }
659
2266
  }
660
2267
  const state = store.snapshot();
661
2268
  res.json({
2269
+ ...(conversationApi
2270
+ ? {
2271
+ conversation: state.conversations.find((c) => c.id === result.tasks[0]?.conversationId),
2272
+ task: ((t) => (t ? publicTask(t) : undefined))(state.tasks.find((t) => t.id === result.tasks[0]?.id)),
2273
+ }
2274
+ : {}),
662
2275
  message: result.message,
663
- tasks: result.tasks.map((task) => state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId) ?? task),
2276
+ tasks: result.tasks.map((task) => publicTask(state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId) ?? task)),
2277
+ });
2278
+ });
2279
+ app.post("/api/devices/:id/remark", async (req, res) => {
2280
+ const owner = account(req);
2281
+ const id = String(req.params.id);
2282
+ const rawRemark = req.body?.remark;
2283
+ if (rawRemark !== null && rawRemark !== undefined && typeof rawRemark !== "string") {
2284
+ fail(400, "Invalid remark");
2285
+ }
2286
+ const remark = typeof rawRemark === "string" ? rawRemark.trim().slice(0, 80) : "";
2287
+ const updated = await store.transact((draft) => {
2288
+ const target = draft.devices.find((d) => d.id === id && d.accountId === owner.id);
2289
+ if (!target)
2290
+ fail(404, "Device missing");
2291
+ if (remark) {
2292
+ target.remark = remark;
2293
+ }
2294
+ else {
2295
+ delete target.remark;
2296
+ }
2297
+ return target;
664
2298
  });
2299
+ res.json({ device: visibleDevice(publicDevice(updated)) });
665
2300
  });
666
2301
  for (const action of ["alias", "portal"])
667
2302
  app.post(`/api/devices/:id/${action}`, async (req, res) => {
@@ -754,6 +2389,213 @@ export async function createDeviceHub(options) {
754
2389
  return;
755
2390
  app(req, res);
756
2391
  });
2392
+ // Accepted queued tasks remain in flight until a terminal event, including asynchronous relay delivery.
2393
+ const deliveredTasks = new Set();
2394
+ async function releaseLocksAndWake(roomId, taskId) {
2395
+ const promoted = lockManager.releaseLocks(roomId, taskId);
2396
+ if (promoted.length > 0) {
2397
+ await handlePromotedTasks(roomId, promoted);
2398
+ }
2399
+ }
2400
+ async function handlePromotedTasks(roomId, promotedTaskIds) {
2401
+ for (const taskId of promotedTaskIds) {
2402
+ const state = store.snapshot();
2403
+ const task = state.tasks.find((t) => t.id === taskId);
2404
+ if (!task) {
2405
+ lockManager.releaseLocks(roomId, taskId);
2406
+ continue;
2407
+ }
2408
+ if (task.cancelRequested || state.conversations.find((c) => c.id === task.conversationId)?.closed) {
2409
+ const nextPromoted = lockManager.releaseLocks(roomId, taskId);
2410
+ if (nextPromoted.length > 0) {
2411
+ await handlePromotedTasks(roomId, nextPromoted);
2412
+ }
2413
+ continue;
2414
+ }
2415
+ await store.transact((draft) => {
2416
+ const current = draft.tasks.find((t) => t.id === taskId);
2417
+ if (current && current.status === "waiting") {
2418
+ current.status = "queued";
2419
+ delete current.blockReason;
2420
+ delete current.blockReasonDetail;
2421
+ current.updatedAt = Date.now();
2422
+ }
2423
+ });
2424
+ const room = state.rooms.find((r) => r.id === roomId);
2425
+ const context = room
2426
+ ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes)
2427
+ : undefined;
2428
+ const updatedTask = store.snapshot().tasks.find((t) => t.id === taskId);
2429
+ if (updatedTask) {
2430
+ await deliverTask(updatedTask, context);
2431
+ }
2432
+ }
2433
+ }
2434
+ async function drainConversation(conversationId) {
2435
+ if (!conversationId)
2436
+ return;
2437
+ const state = store.snapshot();
2438
+ const next = nextConversationTask(state, conversationId);
2439
+ if (!next || deliveredTasks.has(next.id))
2440
+ return;
2441
+ const room = state.rooms.find((entry) => entry.id === next.roomId);
2442
+ await deliverTask(next, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
2443
+ }
2444
+ async function wakeDependentTasks(roomId, completedTaskId, report) {
2445
+ const dependentTaskIds = [];
2446
+ await store.transact((draft) => {
2447
+ for (const t of draft.tasks) {
2448
+ if (t.roomId === roomId && t.status === "waiting" && t.dependsOnTaskId === completedTaskId) {
2449
+ t.status = "queued";
2450
+ delete t.blockReason;
2451
+ delete t.blockReasonDetail;
2452
+ t.updatedAt = Date.now();
2453
+ if (report) {
2454
+ const excerpt = report.length > 2000 ? report.slice(0, 2000) + "..." : report;
2455
+ t.text = `[前序任务输出:\n${excerpt}\n]\n\n${t.text}`;
2456
+ }
2457
+ dependentTaskIds.push(t.id);
2458
+ }
2459
+ }
2460
+ });
2461
+ if (dependentTaskIds.length > 0) {
2462
+ const state = store.snapshot();
2463
+ const room = state.rooms.find((r) => r.id === roomId);
2464
+ const context = room
2465
+ ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes)
2466
+ : undefined;
2467
+ for (const id of dependentTaskIds) {
2468
+ const task = state.tasks.find((t) => t.id === id);
2469
+ if (task) {
2470
+ await deliverTask(task, context);
2471
+ }
2472
+ }
2473
+ }
2474
+ }
2475
+ async function deliverTask(task, context) {
2476
+ if (deliveredTasks.has(task.id))
2477
+ return;
2478
+ if (task.conversationId && nextConversationTask(store.snapshot(), task.conversationId)?.id !== task.id)
2479
+ return;
2480
+ if (task.resourceLocks && task.resourceLocks.length > 0) {
2481
+ const acquired = lockManager.acquireLocks({
2482
+ roomId: task.roomId,
2483
+ taskId: task.id,
2484
+ botId: task.botId,
2485
+ deviceId: task.deviceId,
2486
+ resourceLocks: task.resourceLocks,
2487
+ });
2488
+ if (!acquired.success) {
2489
+ await store.transact((draft) => {
2490
+ const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
2491
+ if (current && !isTerminal(current.status)) {
2492
+ current.status = "waiting";
2493
+ current.blockReason = "resource_locked";
2494
+ current.blockReasonDetail = `Waiting for locks: ${acquired.conflictingLocks.join(", ")}`;
2495
+ current.updatedAt = Date.now();
2496
+ }
2497
+ });
2498
+ return;
2499
+ }
2500
+ }
2501
+ deliveredTasks.add(task.id);
2502
+ const deliver = options.onTask ?? options.relay?.onTask;
2503
+ try {
2504
+ const latest = store.snapshot();
2505
+ if (latest.tasks.find((t) => t.id === task.id)?.cancelRequested ||
2506
+ latest.conversations.find((c) => c.id === task.conversationId)?.closed ||
2507
+ validBot(latest, task.botId, task.accountId)?.revision !== task.botRevision ||
2508
+ !latest.rooms.some((r) => r.id === task.roomId && r.botIds.includes(task.botId)))
2509
+ throw new Error("Bot no longer available");
2510
+ await store.transact((draft) => {
2511
+ const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
2512
+ if (current) {
2513
+ current.leaseToken = randomUUID();
2514
+ current.leaseGeneration = (current.leaseGeneration ?? 0) + 1;
2515
+ current.lastHeartbeatAt = Date.now();
2516
+ task.leaseToken = current.leaseToken;
2517
+ task.leaseGeneration = current.leaseGeneration;
2518
+ }
2519
+ const conversation = draft.conversations.find((entry) => entry.id === task.conversationId);
2520
+ if (conversation && !conversation.closed) {
2521
+ conversation.latestTaskId = task.id;
2522
+ conversation.updatedAt = Date.now();
2523
+ }
2524
+ });
2525
+ const committed = store.snapshot();
2526
+ if (committed.tasks.find((entry) => entry.id === task.id)?.cancelRequested ||
2527
+ committed.conversations.find((entry) => entry.id === task.conversationId)?.closed)
2528
+ throw new Error("Conversation stopped before delivery");
2529
+ const taskState = committed.conversations.find((entry) => entry.id === task.conversationId)?.taskState;
2530
+ if (!deliver ||
2531
+ (await deliver(task.deviceId, {
2532
+ ...task,
2533
+ leaseToken: task.leaseToken,
2534
+ leaseGeneration: task.leaseGeneration,
2535
+ context,
2536
+ taskState,
2537
+ })) === false)
2538
+ throw new Error("Delivery rejected");
2539
+ }
2540
+ catch {
2541
+ const failure = await store.transact((draft) => {
2542
+ const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
2543
+ if (!current || isTerminal(current.status) || current.cancelRequested)
2544
+ return;
2545
+ const report = "Task delivery failed; submit a new request to retry.";
2546
+ current.status = "failed";
2547
+ current.updatedAt = Date.now();
2548
+ current.report = report;
2549
+ if (current.conversationId)
2550
+ draft.conversationMessages.push({
2551
+ id: randomUUID(),
2552
+ conversationId: current.conversationId,
2553
+ taskId: current.id,
2554
+ kind: "result",
2555
+ text: report,
2556
+ sourceBotId: current.botId,
2557
+ requestId: current.requestId,
2558
+ createdAt: current.updatedAt,
2559
+ });
2560
+ const room = draft.rooms.find((r) => r.id === current.roomId);
2561
+ const context = room
2562
+ ? groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes)
2563
+ : undefined;
2564
+ const wake = queueParentResult(draft, current, currentSettings());
2565
+ draft.messages.push({
2566
+ id: randomUUID(),
2567
+ roomId: current.roomId,
2568
+ accountId: current.accountId,
2569
+ text: report,
2570
+ sender: {
2571
+ type: "bot",
2572
+ id: current.botId,
2573
+ name: draft.bots.find((bot) => bot.id === current.botId)?.name ?? current.botId,
2574
+ sourceDeviceId: current.deviceId,
2575
+ },
2576
+ createdAt: current.updatedAt,
2577
+ taskIds: [current.id],
2578
+ });
2579
+ const remove = new Set(draft.messages
2580
+ .filter((message) => message.roomId === current.roomId)
2581
+ .slice(0, -getHistoryLimit())
2582
+ .map((message) => message.id));
2583
+ draft.messages = draft.messages.filter((message) => !remove.has(message.id));
2584
+ trimRoomReceipts(draft, current.roomId);
2585
+ trimConversationHistory(draft, current.roomId);
2586
+ return { wake, context };
2587
+ });
2588
+ if (failure?.wake)
2589
+ await deliverTask(failure.wake, failure.context);
2590
+ }
2591
+ finally {
2592
+ if (isTerminal(store.snapshot().tasks.find((entry) => entry.id === task.id)?.status ?? "interrupted")) {
2593
+ deliveredTasks.delete(task.id);
2594
+ await releaseLocksAndWake(task.roomId, task.id);
2595
+ await drainConversation(task.conversationId);
2596
+ }
2597
+ }
2598
+ }
757
2599
  async function acceptTaskEvent(deviceId, event) {
758
2600
  if (!event ||
759
2601
  typeof event.taskId !== "string" ||
@@ -761,10 +2603,24 @@ export async function createDeviceHub(options) {
761
2603
  typeof event.botId !== "string" ||
762
2604
  !["running", "completed", "failed", "interrupted"].includes(event.status))
763
2605
  fail(400, "Invalid task event");
764
- const report = event.report === undefined ? undefined : text(event.report);
2606
+ const report = event.report === undefined
2607
+ ? event.status === "failed"
2608
+ ? "Task execution failed without a report."
2609
+ : event.status === "interrupted"
2610
+ ? "Task execution was interrupted without a report."
2611
+ : undefined
2612
+ : text(event.report);
765
2613
  if (event.status === "completed" && !report)
766
2614
  fail(400, "Completed task requires agent report");
767
- return store.transact((draft) => {
2615
+ let reportMetadata;
2616
+ try {
2617
+ if (event.reportMetadata !== undefined)
2618
+ reportMetadata = parseReportMetadata(event.reportMetadata);
2619
+ }
2620
+ catch {
2621
+ fail(400, "Invalid report metadata");
2622
+ }
2623
+ const result = await store.transact((draft) => {
768
2624
  const device = draft.devices.find((d) => d.id === deviceId);
769
2625
  const task = draft.tasks.find((t) => t.id === event.taskId &&
770
2626
  t.deviceId === deviceId &&
@@ -776,15 +2632,33 @@ export async function createDeviceHub(options) {
776
2632
  fail(404, "Task missing");
777
2633
  if (event.status !== "interrupted" && (!bot.enabled || bot.revision !== task.botRevision))
778
2634
  fail(409, "Bot configuration changed");
2635
+ if (isTerminal(event.status)) {
2636
+ const stored = taskReportStore.getReportMeta(task.id, task.attemptId, task.accountId, task.roomId);
2637
+ task.reportMetadata = stored?.complete
2638
+ ? {
2639
+ sha256: stored.sha256,
2640
+ totalBytes: stored.totalBytes,
2641
+ missing: false,
2642
+ rejected: false,
2643
+ uploadPending: false,
2644
+ }
2645
+ : (reportMetadata ?? task.reportMetadata ?? reportUploadMetadata());
2646
+ }
779
2647
  if (task.status === event.status) {
780
- if (task.report !== report)
2648
+ if (task.report && report && task.report !== report)
781
2649
  fail(409, "Conflicting duplicate event");
782
- return task;
2650
+ return { task };
783
2651
  }
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");
2652
+ // Allow safe outbox replay or recovery adoption if task was marked interrupted during restart/disconnect
2653
+ const inRecovery = typeof task.recoveryUntil === "number" && Date.now() <= task.recoveryUntil;
2654
+ const canAdoptInterrupted = (inRecovery || task.status === "interrupted") && (event.status === "completed" || event.status === "failed");
2655
+ if (!canAdoptInterrupted) {
2656
+ if (isTerminal(task.status) ||
2657
+ (task.status === "queued" && event.status !== "running" && event.status !== "interrupted") ||
2658
+ (task.status === "running" && !isTerminal(event.status)))
2659
+ fail(409, "Invalid task transition");
2660
+ }
2661
+ delete task.recoveryUntil;
788
2662
  task.status = event.status;
789
2663
  task.updatedAt = Date.now();
790
2664
  if (report)
@@ -798,29 +2672,427 @@ export async function createDeviceHub(options) {
798
2672
  sender: { type: "bot", id: bot.id, name: bot.name, sourceDeviceId: deviceId },
799
2673
  createdAt: Date.now(),
800
2674
  taskIds: [task.id],
2675
+ conversationId: task.conversationId,
801
2676
  });
2677
+ if (task.conversationId)
2678
+ draft.conversationMessages.push({
2679
+ id: randomUUID(),
2680
+ conversationId: task.conversationId,
2681
+ taskId: task.id,
2682
+ kind: "result",
2683
+ text: report,
2684
+ sourceBotId: bot.id,
2685
+ requestId: task.requestId,
2686
+ createdAt: Date.now(),
2687
+ });
802
2688
  const remove = new Set(draft.messages
803
2689
  .filter((m) => m.roomId === task.roomId)
804
- .slice(0, -HISTORY)
2690
+ .slice(0, -getHistoryLimit())
805
2691
  .map((m) => m.id));
806
2692
  draft.messages = draft.messages.filter((m) => !remove.has(m.id));
807
- draft.receipts = draft.receipts.filter((r) => !remove.has(r.messageId));
2693
+ trimRoomReceipts(draft, task.roomId);
2694
+ }
2695
+ const room = draft.rooms.find((r) => r.id === task.roomId);
2696
+ const context = groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes);
2697
+ const wake = queueParentResult(draft, task, currentSettings());
2698
+ trimConversationHistory(draft, task.roomId);
2699
+ return { task, wake, context };
2700
+ });
2701
+ if (result?.task) {
2702
+ taskJournalManager
2703
+ .append(result.task.id, {
2704
+ botId: result.task.botId,
2705
+ attemptId: result.task.attemptId,
2706
+ type: "status",
2707
+ phase: event.status,
2708
+ summary: `Task ${event.status}${report ? ": " + report.slice(0, 100) : ""}`,
2709
+ output: report,
2710
+ }, { roomId: result.task.roomId, accountId: result.task.accountId })
2711
+ .catch((cause) => {
2712
+ console.warn(`[TaskJournal] Journal append failed for task ${result.task.id}:`, cause);
2713
+ });
2714
+ }
2715
+ if (isTerminal(result.task.status)) {
2716
+ deliveredTasks.delete(result.task.id);
2717
+ await releaseLocksAndWake(result.task.roomId, result.task.id);
2718
+ if (result.task.status === "completed") {
2719
+ await wakeDependentTasks(result.task.roomId, result.task.id, report);
2720
+ dispatchGroupWebhook(store, result.task.roomId, "task_completed", {
2721
+ taskId: result.task.id,
2722
+ botId: result.task.botId,
2723
+ status: "completed",
2724
+ report: result.task.report,
2725
+ text: result.task.text,
2726
+ });
2727
+ }
2728
+ else if (result.task.status === "failed") {
2729
+ dispatchGroupWebhook(store, result.task.roomId, "task_failed", {
2730
+ taskId: result.task.id,
2731
+ botId: result.task.botId,
2732
+ status: "failed",
2733
+ report: result.task.report,
2734
+ text: result.task.text,
2735
+ });
2736
+ }
2737
+ if (report) {
2738
+ const state = store.snapshot();
2739
+ const msg = state.messages.find((m) => m.taskIds.includes(result.task.id) && m.sender.id === result.task.botId);
2740
+ if (msg) {
2741
+ dispatchGroupWebhook(store, result.task.roomId, "message", msg);
2742
+ }
2743
+ }
2744
+ }
2745
+ if (result.wake)
2746
+ await deliverTask(result.wake, result.context);
2747
+ await drainConversation(result.task.conversationId);
2748
+ return result.task;
2749
+ }
2750
+ // === Hub Restart Recovery Window ===
2751
+ const nowInit = Date.now();
2752
+ const recoveryGraceMs = 60_000;
2753
+ try {
2754
+ await store.transact((draft) => {
2755
+ for (const task of draft.tasks) {
2756
+ if (task.status === "running") {
2757
+ task.recoveryUntil = nowInit + recoveryGraceMs;
2758
+ }
2759
+ }
2760
+ });
2761
+ }
2762
+ catch (err) {
2763
+ console.error("DEBUG store.transact failed:", err);
2764
+ }
2765
+ let sweepInflight = false;
2766
+ const recoverySweepTimer = setInterval(() => {
2767
+ if (sweepInflight)
2768
+ return;
2769
+ const sweepNow = Date.now();
2770
+ const snapshot = store.snapshot();
2771
+ const hasDue = snapshot.tasks.some((t) => (t.recoveryUntil && sweepNow > t.recoveryUntil) ||
2772
+ (t.status === "running" && t.lastHeartbeatAt && sweepNow - t.lastHeartbeatAt > 30 * 60_000));
2773
+ if (!hasDue)
2774
+ return;
2775
+ sweepInflight = true;
2776
+ void (async () => {
2777
+ try {
2778
+ const settledWakes = [];
2779
+ await store.transact((draft) => {
2780
+ for (const task of draft.tasks) {
2781
+ const windowExpired = task.recoveryUntil && sweepNow > task.recoveryUntil;
2782
+ const leaseExpired = task.status === "running" && task.lastHeartbeatAt && sweepNow - task.lastHeartbeatAt > 30 * 60_000;
2783
+ if (windowExpired || leaseExpired) {
2784
+ delete task.recoveryUntil;
2785
+ if (task.status === "running") {
2786
+ task.status = "interrupted";
2787
+ task.updatedAt = sweepNow;
2788
+ const report = windowExpired
2789
+ ? "Hub restarted; recovery window expired without reconnect claim."
2790
+ : "Task lease expired due to prolonged inactivity.";
2791
+ task.report = report;
2792
+ const room = draft.rooms.find((r) => r.id === task.roomId);
2793
+ const context = room
2794
+ ? groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes)
2795
+ : undefined;
2796
+ const wake = queueParentResult(draft, task, currentSettings());
2797
+ trimConversationHistory(draft, task.roomId);
2798
+ settledWakes.push({
2799
+ wake,
2800
+ context,
2801
+ conversationId: task.conversationId,
2802
+ taskId: task.id,
2803
+ roomId: task.roomId,
2804
+ });
2805
+ }
2806
+ }
2807
+ }
2808
+ });
2809
+ for (const item of settledWakes) {
2810
+ deliveredTasks.delete(item.taskId);
2811
+ await releaseLocksAndWake(item.roomId, item.taskId);
2812
+ if (item.wake)
2813
+ await deliverTask(item.wake, item.context);
2814
+ await drainConversation(item.conversationId);
2815
+ }
2816
+ const expiredPromoted = lockManager.cleanupExpiredLocks();
2817
+ for (const pTaskId of expiredPromoted) {
2818
+ const pTask = store.snapshot().tasks.find((t) => t.id === pTaskId);
2819
+ if (pTask) {
2820
+ await handlePromotedTasks(pTask.roomId, [pTaskId]);
2821
+ }
2822
+ }
2823
+ }
2824
+ catch {
2825
+ console.warn("[HubRecovery] Sweep transaction failed");
2826
+ }
2827
+ finally {
2828
+ sweepInflight = false;
2829
+ }
2830
+ })();
2831
+ }, 10_000);
2832
+ recoverySweepTimer.unref();
2833
+ async function claimTask(deviceId, claim) {
2834
+ if (!claim ||
2835
+ typeof claim.taskId !== "string" ||
2836
+ typeof claim.attemptId !== "string" ||
2837
+ typeof claim.botId !== "string" ||
2838
+ typeof claim.leaseToken !== "string" ||
2839
+ !claim.leaseToken) {
2840
+ return {
2841
+ taskId: claim?.taskId ?? "",
2842
+ attemptId: claim?.attemptId ?? "",
2843
+ accepted: false,
2844
+ reason: "Invalid claim payload or missing leaseToken",
2845
+ };
2846
+ }
2847
+ return await store.transact((draft) => {
2848
+ const device = draft.devices.find((d) => d.id === deviceId);
2849
+ const task = draft.tasks.find((t) => t.id === claim.taskId &&
2850
+ t.deviceId === deviceId &&
2851
+ t.botId === claim.botId &&
2852
+ t.attemptId === claim.attemptId &&
2853
+ t.accountId === device?.accountId);
2854
+ if (!task || !device) {
2855
+ return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Task not found" };
2856
+ }
2857
+ const inRecovery = typeof task.recoveryUntil === "number" && Date.now() <= task.recoveryUntil;
2858
+ const isDisconnectInterrupted = task.status === "interrupted" &&
2859
+ !task.cancelRequested &&
2860
+ !task.stopConfirmed &&
2861
+ Date.now() - task.updatedAt <= 60_000;
2862
+ if (isTerminal(task.status) && !inRecovery && !isDisconnectInterrupted) {
2863
+ return {
2864
+ taskId: claim.taskId,
2865
+ attemptId: claim.attemptId,
2866
+ accepted: false,
2867
+ reason: "Task already terminated",
2868
+ };
2869
+ }
2870
+ if (task.cancelRequested || task.stopConfirmed) {
2871
+ return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Task stop requested" };
2872
+ }
2873
+ const bot = draft.bots.find((b) => b.id === task.botId && b.deviceId === deviceId && b.accountId === device.accountId);
2874
+ if (!bot || !bot.enabled || bot.revision !== task.botRevision) {
2875
+ return {
2876
+ taskId: claim.taskId,
2877
+ attemptId: claim.attemptId,
2878
+ accepted: false,
2879
+ reason: "Bot configuration changed or disabled",
2880
+ };
2881
+ }
2882
+ const room = draft.rooms.find((r) => r.id === task.roomId && r.botIds.includes(task.botId));
2883
+ if (!room) {
2884
+ return {
2885
+ taskId: claim.taskId,
2886
+ attemptId: claim.attemptId,
2887
+ accepted: false,
2888
+ reason: "Bot no longer member of room",
2889
+ };
2890
+ }
2891
+ if (task.leaseToken !== claim.leaseToken) {
2892
+ return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Lease token mismatch" };
2893
+ }
2894
+ if (task.leaseGeneration !== undefined && claim.leaseGeneration !== task.leaseGeneration) {
2895
+ return {
2896
+ taskId: claim.taskId,
2897
+ attemptId: claim.attemptId,
2898
+ accepted: false,
2899
+ reason: "Lease generation mismatch",
2900
+ };
2901
+ }
2902
+ if (task.status !== "running" && !inRecovery && !isDisconnectInterrupted) {
2903
+ return {
2904
+ taskId: claim.taskId,
2905
+ attemptId: claim.attemptId,
2906
+ accepted: false,
2907
+ reason: "Task not running or recovery window closed",
2908
+ };
2909
+ }
2910
+ delete task.recoveryUntil;
2911
+ task.status = "running";
2912
+ task.updatedAt = Date.now();
2913
+ task.lastHeartbeatAt = Date.now();
2914
+ return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: true };
2915
+ });
2916
+ }
2917
+ async function renewTaskLease(deviceId, renew) {
2918
+ if (!renew ||
2919
+ typeof renew.taskId !== "string" ||
2920
+ typeof renew.attemptId !== "string" ||
2921
+ typeof renew.botId !== "string" ||
2922
+ typeof renew.leaseToken !== "string" ||
2923
+ !renew.leaseToken) {
2924
+ return {
2925
+ taskId: renew?.taskId ?? "",
2926
+ attemptId: renew?.attemptId ?? "",
2927
+ accepted: false,
2928
+ reason: "Invalid renew payload or missing leaseToken",
2929
+ };
2930
+ }
2931
+ return await store.transact((draft) => {
2932
+ const device = draft.devices.find((d) => d.id === deviceId);
2933
+ const task = draft.tasks.find((t) => t.id === renew.taskId &&
2934
+ t.deviceId === deviceId &&
2935
+ t.botId === renew.botId &&
2936
+ t.attemptId === renew.attemptId &&
2937
+ t.accountId === device?.accountId);
2938
+ if (!task || !device || task.status !== "running") {
2939
+ return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task not running" };
2940
+ }
2941
+ if (task.cancelRequested || task.stopConfirmed) {
2942
+ return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task stop requested" };
2943
+ }
2944
+ if (task.leaseToken !== renew.leaseToken) {
2945
+ return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Lease token mismatch" };
2946
+ }
2947
+ if (task.leaseGeneration !== undefined && renew.leaseGeneration !== task.leaseGeneration) {
2948
+ return {
2949
+ taskId: renew.taskId,
2950
+ attemptId: renew.attemptId,
2951
+ accepted: false,
2952
+ reason: "Lease generation mismatch",
2953
+ };
2954
+ }
2955
+ const bot = draft.bots.find((b) => b.id === task.botId && b.deviceId === deviceId && b.accountId === device.accountId);
2956
+ if (!bot || !bot.enabled || bot.revision !== task.botRevision) {
2957
+ return {
2958
+ taskId: renew.taskId,
2959
+ attemptId: renew.attemptId,
2960
+ accepted: false,
2961
+ reason: "Bot configuration changed or disabled",
2962
+ };
2963
+ }
2964
+ const room = draft.rooms.find((r) => r.id === task.roomId && r.botIds.includes(task.botId));
2965
+ if (!room) {
2966
+ return {
2967
+ taskId: renew.taskId,
2968
+ attemptId: renew.attemptId,
2969
+ accepted: false,
2970
+ reason: "Bot no longer member of room",
2971
+ };
2972
+ }
2973
+ const hasActiveInteraction = liveInteractions(task.roomId, task.accountId).some((i) => i.taskId === task.id);
2974
+ const now = Date.now();
2975
+ if (renew.hasActivity || hasActiveInteraction) {
2976
+ task.lastHeartbeatAt = now;
2977
+ task.updatedAt = now;
2978
+ }
2979
+ return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: true };
2980
+ });
2981
+ }
2982
+ const toolLifecycleSeqs = new Map();
2983
+ async function acceptTaskToolLifecycle(deviceId, frame) {
2984
+ const state = store.snapshot();
2985
+ const device = state.devices.find((d) => d.id === deviceId);
2986
+ const task = state.tasks.find((t) => t.id === frame.taskId &&
2987
+ t.deviceId === deviceId &&
2988
+ t.botId === frame.botId &&
2989
+ t.attemptId === frame.attemptId &&
2990
+ t.accountId === device?.accountId);
2991
+ if (!task || !device)
2992
+ return;
2993
+ const room = state.rooms.find((r) => r.id === task.roomId && r.accountId === task.accountId);
2994
+ if (!room)
2995
+ return;
2996
+ // Deduplicate and enforce monotonic sequence if provided
2997
+ if (typeof frame.sequence === "number" && Number.isSafeInteger(frame.sequence)) {
2998
+ const seqKey = `${task.id}:${task.attemptId}`;
2999
+ const prevSeq = toolLifecycleSeqs.get(seqKey);
3000
+ if (prevSeq !== undefined && frame.sequence <= prevSeq)
3001
+ return;
3002
+ toolLifecycleSeqs.set(seqKey, frame.sequence);
3003
+ }
3004
+ const typeMapping = {
3005
+ start: "tool_start",
3006
+ progress: "tool_progress",
3007
+ end: "tool_end",
3008
+ failed: "tool_failed",
3009
+ };
3010
+ const entryType = typeMapping[frame.phase] || "tool_progress";
3011
+ await taskJournalManager
3012
+ .append(task.id, {
3013
+ botId: task.botId,
3014
+ attemptId: task.attemptId,
3015
+ type: entryType,
3016
+ phase: "running",
3017
+ toolName: frame.toolName,
3018
+ toolCallId: frame.callId,
3019
+ summary: frame.summary,
3020
+ parametersPreview: frame.parametersPreview,
3021
+ output: frame.outputSnippet,
3022
+ }, { roomId: task.roomId, accountId: task.accountId })
3023
+ .catch((err) => {
3024
+ console.warn(`[TaskJournal] Tool lifecycle append error for ${task.id}:`, err);
3025
+ });
3026
+ }
3027
+ async function acceptTaskPlanReady(deviceId, frame) {
3028
+ if (!frame ||
3029
+ typeof frame.taskId !== "string" ||
3030
+ typeof frame.botId !== "string" ||
3031
+ typeof frame.attemptId !== "string")
3032
+ return false;
3033
+ const plan = validateTaskPlan(frame.plan);
3034
+ if (!plan)
3035
+ return false;
3036
+ return store.transact((draft) => {
3037
+ const device = draft.devices.find((d) => d.id === deviceId);
3038
+ const task = draft.tasks.find((t) => t.id === frame.taskId &&
3039
+ t.deviceId === deviceId &&
3040
+ t.botId === frame.botId &&
3041
+ t.attemptId === frame.attemptId &&
3042
+ t.accountId === device?.accountId);
3043
+ if (!device || !task)
3044
+ return false;
3045
+ const bot = draft.bots.find((b) => b.id === frame.botId && b.deviceId === deviceId && b.accountId === device.accountId);
3046
+ if (!bot || !bot.enabled || bot.revision !== task.botRevision)
3047
+ return false;
3048
+ const room = draft.rooms.find((r) => r.id === task.roomId && r.accountId === task.accountId && r.botIds.includes(bot.id));
3049
+ if (!room ||
3050
+ !task.planOnly ||
3051
+ task.status !== "running" ||
3052
+ task.plan?.state === "approved" ||
3053
+ (bot.tools && !bot.tools.includes("plan_update")))
3054
+ return false;
3055
+ if (task.plan?.state === "ready")
3056
+ return JSON.stringify(task.plan) === JSON.stringify(plan);
3057
+ task.plan = plan;
3058
+ task.updatedAt = Date.now();
3059
+ return true;
3060
+ });
3061
+ }
3062
+ async function onTaskDisconnect(deviceId, taskId, attemptId) {
3063
+ const now = Date.now();
3064
+ const recoveryGraceMs = 60_000;
3065
+ await store.transact((draft) => {
3066
+ const task = draft.tasks.find((t) => t.id === taskId && t.deviceId === deviceId && t.attemptId === attemptId);
3067
+ if (task && task.status === "running") {
3068
+ task.recoveryUntil = now + recoveryGraceMs;
3069
+ task.updatedAt = now;
808
3070
  }
809
- return task;
810
3071
  });
811
3072
  }
812
3073
  return {
813
3074
  app,
814
3075
  server,
815
3076
  store,
3077
+ claimTask,
3078
+ renewTaskLease,
3079
+ onTaskDisconnect,
816
3080
  getAccount,
817
- getRelayAccount: (req) => users.get(req)?.account ?? getAccount(req),
3081
+ getRelayAccount: (req) => users.get(req)?.account ?? getAccount(req) ?? undefined,
818
3082
  authenticateAgent,
819
3083
  acceptTaskEvent,
3084
+ acceptInteractions,
3085
+ acceptTaskProgress: groupEvents.accept,
3086
+ acceptTaskToolLifecycle,
3087
+ acceptTaskPlanReady,
820
3088
  setRelay(relay) {
821
3089
  options.relay = relay;
822
3090
  },
823
3091
  async close() {
3092
+ clearInterval(recoverySweepTimer);
3093
+ lockManager.close();
3094
+ await groupEvents.close();
3095
+ await taskJournalManager.close();
824
3096
  pairs.clear();
825
3097
  if (server.listening)
826
3098
  await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));