@temmo/cli 0.0.0-stage → 0.19.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 (445) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.claude-plugin/plugin.json +16 -0
  3. package/.codex-plugin/plugin.json +30 -0
  4. package/.cursor-plugin/plugin.json +22 -0
  5. package/.mcp.json +18 -0
  6. package/LICENSE +202 -0
  7. package/README.md +82 -2
  8. package/THIRD_PARTY_NOTICES +32 -0
  9. package/commands/afk.md +17 -0
  10. package/deploy/build-ui.mjs +65 -0
  11. package/deploy/claude/README.md +16 -0
  12. package/deploy/claude/auto-mode.json +31 -0
  13. package/deploy/postgres/compose.yaml +26 -0
  14. package/deploy/temmo-runner.service +24 -0
  15. package/deploy/verify-ui.mjs +15 -0
  16. package/harness-core/README.md +27 -0
  17. package/harness-core/bin/harness.mjs +17 -0
  18. package/harness-core/package.json +10 -0
  19. package/harness-core/stage.mjs +108 -0
  20. package/harness-core/stages/commit.md +7 -0
  21. package/harness-core/stages/pr.md +7 -0
  22. package/harness-core/stages/push.md +7 -0
  23. package/hooks/codex-hooks.json +14 -0
  24. package/hooks/cursor-hooks.json +17 -0
  25. package/hooks/hooks.json +27 -0
  26. package/lib/acp/permission.js +72 -0
  27. package/lib/acp/sessionConfig.js +109 -0
  28. package/lib/activity.js +244 -0
  29. package/lib/agent-guard.js +72 -0
  30. package/lib/agents-route.js +55 -0
  31. package/lib/agents.js +213 -0
  32. package/lib/agui.js +255 -0
  33. package/lib/alerts.js +36 -0
  34. package/lib/analyze-otlp.js +46 -0
  35. package/lib/analyze-run-code.js +397 -0
  36. package/lib/analyze-sources.js +372 -0
  37. package/lib/approval-card.js +54 -0
  38. package/lib/approval-cli.js +53 -0
  39. package/lib/approval-request.js +81 -0
  40. package/lib/approval-signer.js +48 -0
  41. package/lib/approvals.js +295 -0
  42. package/lib/attachment-cache.js +236 -0
  43. package/lib/attachment.js +63 -0
  44. package/lib/blocked.js +20 -0
  45. package/lib/build-review.js +90 -0
  46. package/lib/builder/cli.js +90 -0
  47. package/lib/builder/policy.js +176 -0
  48. package/lib/builder/recover.js +189 -0
  49. package/lib/builder/run.js +240 -0
  50. package/lib/builder/settle.js +198 -0
  51. package/lib/builder/stage.js +240 -0
  52. package/lib/builder/state.js +73 -0
  53. package/lib/builder/supervisor.js +289 -0
  54. package/lib/builder-clean.js +223 -0
  55. package/lib/builder-code.cjs +67 -0
  56. package/lib/builder.js +9 -0
  57. package/lib/bus-postgres.js +281 -0
  58. package/lib/bus.js +349 -0
  59. package/lib/catalog/author.js +278 -0
  60. package/lib/catalog/dot.js +426 -0
  61. package/lib/catalog/pattern-model.js +193 -0
  62. package/lib/catalog/patterns.js +324 -0
  63. package/lib/catalog/projects.js +83 -0
  64. package/lib/catalog/records.js +2 -0
  65. package/lib/catalog/roster.js +70 -0
  66. package/lib/catalog/team-files.js +49 -0
  67. package/lib/catalog/teams.js +109 -0
  68. package/lib/claude-socket.js +333 -0
  69. package/lib/cli.js +741 -0
  70. package/lib/code-mode.js +45 -0
  71. package/lib/code-read-policy.yaml +9 -0
  72. package/lib/code-run.js +461 -0
  73. package/lib/codex-compact.js +141 -0
  74. package/lib/compaction.js +21 -0
  75. package/lib/config.js +424 -0
  76. package/lib/cursor-trace.js +248 -0
  77. package/lib/deep-link.js +20 -0
  78. package/lib/deliver-push.js +120 -0
  79. package/lib/delivery.js +28 -0
  80. package/lib/deploy-tree.js +227 -0
  81. package/lib/durable.js +404 -0
  82. package/lib/factory-tick.js +32 -0
  83. package/lib/family.js +63 -0
  84. package/lib/fetch-origin.js +53 -0
  85. package/lib/format.js +133 -0
  86. package/lib/harness-surface-cli.js +153 -0
  87. package/lib/harness-surface.js +486 -0
  88. package/lib/harness.js +271 -0
  89. package/lib/hook.mjs +291 -0
  90. package/lib/idle.js +40 -0
  91. package/lib/install-cursor.js +115 -0
  92. package/lib/install-opencode.js +105 -0
  93. package/lib/job.js +82 -0
  94. package/lib/land-cli.js +319 -0
  95. package/lib/land-member.js +64 -0
  96. package/lib/land.js +320 -0
  97. package/lib/lessons.js +223 -0
  98. package/lib/limit-alert.js +423 -0
  99. package/lib/limits.js +284 -0
  100. package/lib/machine-prompt.js +19 -0
  101. package/lib/merge-sweep.js +149 -0
  102. package/lib/messaging.js +1002 -0
  103. package/lib/mission-cli.js +103 -0
  104. package/lib/mission.js +241 -0
  105. package/lib/mode.js +215 -0
  106. package/lib/models.js +114 -0
  107. package/lib/names.js +86 -0
  108. package/lib/opencode-api.js +57 -0
  109. package/lib/opencode-plugin.mjs +313 -0
  110. package/lib/operator-token.js +78 -0
  111. package/lib/operator.js +187 -0
  112. package/lib/pad-activity.js +143 -0
  113. package/lib/pad-fresh.js +44 -0
  114. package/lib/pad.js +198 -0
  115. package/lib/pattern-cli.js +120 -0
  116. package/lib/pattern-compiler.js +68 -0
  117. package/lib/pattern-runs.js +795 -0
  118. package/lib/pattern-stall.js +58 -0
  119. package/lib/pattern-tick.js +45 -0
  120. package/lib/pattern-workflow.js +69 -0
  121. package/lib/pi-extension.mjs +98 -0
  122. package/lib/pi.js +57 -0
  123. package/lib/plugin-copy.js +76 -0
  124. package/lib/pm-review.js +32 -0
  125. package/lib/pm-workspace.js +87 -0
  126. package/lib/postgres.js +115 -0
  127. package/lib/pr-card.js +34 -0
  128. package/lib/probe.js +295 -0
  129. package/lib/process.js +67 -0
  130. package/lib/project-pause.js +23 -0
  131. package/lib/prune.js +793 -0
  132. package/lib/questions.js +250 -0
  133. package/lib/receipts.js +63 -0
  134. package/lib/reflect.js +962 -0
  135. package/lib/rename-migration.js +118 -0
  136. package/lib/run-terminal.js +437 -0
  137. package/lib/runner-request.js +33 -0
  138. package/lib/sandbox-app.js +120 -0
  139. package/lib/sandbox-claims.js +258 -0
  140. package/lib/sandbox-cli.js +188 -0
  141. package/lib/sandbox-hosts-cli.js +68 -0
  142. package/lib/sandbox-hosts.js +94 -0
  143. package/lib/sandbox-pr.js +102 -0
  144. package/lib/sandbox-proposal.js +367 -0
  145. package/lib/sandbox-tools.js +143 -0
  146. package/lib/sandbox.js +501 -0
  147. package/lib/schedule-session.js +68 -0
  148. package/lib/session-activity.js +67 -0
  149. package/lib/session-events.js +94 -0
  150. package/lib/sessions/control.js +244 -0
  151. package/lib/sessions/git-refs.js +265 -0
  152. package/lib/sessions/launch.js +359 -0
  153. package/lib/sessions/registry.js +450 -0
  154. package/lib/sessions/scope.js +111 -0
  155. package/lib/setup.js +377 -0
  156. package/lib/signed-approval.js +225 -0
  157. package/lib/slash.js +167 -0
  158. package/lib/spawn-cli.js +45 -0
  159. package/lib/spawn.js +107 -0
  160. package/lib/start-limit.js +58 -0
  161. package/lib/state.js +24 -0
  162. package/lib/stop.js +308 -0
  163. package/lib/store-read.js +62 -0
  164. package/lib/store.js +252 -0
  165. package/lib/subagent-guard.js +240 -0
  166. package/lib/surfaces/channel-post.js +43 -0
  167. package/lib/surfaces/instructions.js +15 -0
  168. package/lib/surfaces/mcp-reload.js +144 -0
  169. package/lib/surfaces/ops.js +629 -0
  170. package/lib/surfaces/render-mcp.js +33 -0
  171. package/lib/surfaces/run-terminal-ops.js +40 -0
  172. package/lib/surfaces/sandbox-ops.js +36 -0
  173. package/lib/surfaces/schema.js +7 -0
  174. package/lib/surfaces/task-view.js +90 -0
  175. package/lib/surfaces/types.js +4 -0
  176. package/lib/task-cli.js +274 -0
  177. package/lib/task-order.js +34 -0
  178. package/lib/task-order.mjs +2 -0
  179. package/lib/task-route.js +125 -0
  180. package/lib/tasks.js +631 -0
  181. package/lib/team-permission.js +34 -0
  182. package/lib/team-templates/blitz/team.dot +9 -0
  183. package/lib/team-templates/factory/team.dot +26 -0
  184. package/lib/team-templates/feature/team.dot +14 -0
  185. package/lib/team-templates/fix-and-review/team.dot +12 -0
  186. package/lib/team-templates/product/team.dot +16 -0
  187. package/lib/team-templates/release/team.dot +7 -0
  188. package/lib/team-templates/review/team.dot +6 -0
  189. package/lib/terminal-draft.js +42 -0
  190. package/lib/thread-branch.js +82 -0
  191. package/lib/thread-channel-store.js +181 -0
  192. package/lib/thread-channels.js +116 -0
  193. package/lib/thread-listening.js +20 -0
  194. package/lib/thread-routes.js +91 -0
  195. package/lib/threads.js +441 -0
  196. package/lib/tool-api.js +33 -0
  197. package/lib/transcript.js +98 -0
  198. package/lib/ui-build-output.js +19 -0
  199. package/lib/ui-capabilities.js +90 -0
  200. package/lib/usage.js +182 -0
  201. package/lib/vendor/mcp-sdk.d.mts +4 -0
  202. package/lib/vendor/mcp-sdk.mjs +17046 -0
  203. package/lib/waiter.js +127 -0
  204. package/lib/workflows.js +546 -0
  205. package/lib/worktree-setup.js +86 -0
  206. package/package.json +110 -4
  207. package/runner/adapters/claude.js +465 -0
  208. package/runner/adapters/cli-sandbox.js +277 -0
  209. package/runner/adapters/codex.js +675 -0
  210. package/runner/adapters/cursor.mjs +937 -0
  211. package/runner/adapters/fake.js +119 -0
  212. package/runner/adapters/opencode-sandbox.js +370 -0
  213. package/runner/adapters/opencode.js +486 -0
  214. package/runner/adapters/pi-sandbox.js +134 -0
  215. package/runner/adapters/pi.js +364 -0
  216. package/runner/client.js +40 -0
  217. package/runner/contract.js +129 -0
  218. package/runner/control.js +178 -0
  219. package/runner/delivery.js +184 -0
  220. package/runner/factory-tick.mjs +10 -0
  221. package/runner/lock.js +41 -0
  222. package/runner/main.mjs +118 -0
  223. package/runner/pattern-tick.mjs +16 -0
  224. package/runner/publish.js +113 -0
  225. package/runner/runner.js +2612 -0
  226. package/runner/sandbox-run.mjs +239 -0
  227. package/runner/schedules.js +294 -0
  228. package/runner/task-wake.js +59 -0
  229. package/scripts/ai-collab +3 -0
  230. package/scripts/ai-collab-bus.mjs +4 -0
  231. package/scripts/ai-collab-code-mcp.mjs +3 -0
  232. package/scripts/ai-collab-hook +3 -0
  233. package/scripts/ai-collab-hook.mjs +3 -0
  234. package/scripts/ai-collab-mcp-tools.mjs +2 -0
  235. package/scripts/ai-collab-mcp.mjs +3 -0
  236. package/scripts/ai-collab.mjs +3 -0
  237. package/scripts/install-cursor.mjs +11 -0
  238. package/scripts/install-opencode.mjs +10 -0
  239. package/scripts/temmo +3 -0
  240. package/scripts/temmo-bus.mjs +151 -0
  241. package/scripts/temmo-code-mcp.mjs +63 -0
  242. package/scripts/temmo-hook +3 -0
  243. package/scripts/temmo-hook.mjs +201 -0
  244. package/scripts/temmo-mcp-tools.mjs +22 -0
  245. package/scripts/temmo-mcp.mjs +27 -0
  246. package/scripts/temmo.mjs +4 -0
  247. package/skills/antislop/SKILL.md +701 -0
  248. package/skills/antislop/VERSION +1 -0
  249. package/skills/antislop-code/SKILL.md +128 -0
  250. package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
  251. package/skills/antislop-human/SKILL.md +204 -0
  252. package/skills/antislop-human/contrast-check.py +168 -0
  253. package/skills/antislop-human/contrast-mcp.py +125 -0
  254. package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
  255. package/skills/antislop-human/references/WCAG.md +127 -0
  256. package/skills/antislop-layoutmobile/SKILL.md +170 -0
  257. package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
  258. package/skills/antislop-ui/SKILL.md +351 -0
  259. package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
  260. package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
  261. package/skills/harness-surface/SKILL.md +42 -0
  262. package/skills/land/SKILL.md +32 -0
  263. package/skills/memory-file/SKILL.md +39 -0
  264. package/skills/temmo/SKILL.md +101 -0
  265. package/skills/temmo/references/role-programs.md +47 -0
  266. package/skills/ui-sdk/SKILL.md +56 -0
  267. package/skills/ui-sdk/references/agent-ready.md +136 -0
  268. package/skills/ui-sdk/references/build-interface.md +187 -0
  269. package/skills/ui-sdk/references/create-component.md +88 -0
  270. package/skills/ui-sdk/references/patterns.md +246 -0
  271. package/skills/ui-sdk/references/styles.md +66 -0
  272. package/skills/ui-sdk/references/testing.md +172 -0
  273. package/skills/ui-sdk/references/web-components.md +78 -0
  274. package/tools/screen-state.mjs +119 -0
  275. package/tools/smoke-ui.mjs +540 -0
  276. package/web/app/activity.jsx +251 -0
  277. package/web/app/agent-mark.tsx +43 -0
  278. package/web/app/alert-level.jsx +16 -0
  279. package/web/app/api/[action]/route.js +8 -0
  280. package/web/app/api/auth/[step]/route.js +12 -0
  281. package/web/app/api/events/route.js +8 -0
  282. package/web/app/api/file/[name]/route.js +8 -0
  283. package/web/app/api/land/route.js +12 -0
  284. package/web/app/api/lessons/route.js +8 -0
  285. package/web/app/api/push/key/route.js +8 -0
  286. package/web/app/api/push/subscribe/route.js +12 -0
  287. package/web/app/api/push/test/route.js +8 -0
  288. package/web/app/api/refs/route.js +8 -0
  289. package/web/app/api/review-diff/route.js +8 -0
  290. package/web/app/api/schedules/route.js +8 -0
  291. package/web/app/api/thread-diff/route.js +8 -0
  292. package/web/app/api/version/route.js +6 -0
  293. package/web/app/cards.jsx +189 -0
  294. package/web/app/chat-api.js +82 -0
  295. package/web/app/chat-composer.jsx +313 -0
  296. package/web/app/chat-console.jsx +691 -0
  297. package/web/app/chat-image.tsx +61 -0
  298. package/web/app/chat-message.jsx +122 -0
  299. package/web/app/chat-shared.jsx +59 -0
  300. package/web/app/chat-sidebar.jsx +25 -0
  301. package/web/app/chat-stream.js +127 -0
  302. package/web/app/chat.jsx +31 -0
  303. package/web/app/compactions.jsx +57 -0
  304. package/web/app/composer-actions.tsx +87 -0
  305. package/web/app/decisions.jsx +53 -0
  306. package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
  307. package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
  308. package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
  309. package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
  310. package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
  311. package/web/app/globals.css +199 -0
  312. package/web/app/home.jsx +246 -0
  313. package/web/app/icon.svg +1 -0
  314. package/web/app/land-panel.jsx +63 -0
  315. package/web/app/land-reviews.jsx +20 -0
  316. package/web/app/layout.jsx +17 -0
  317. package/web/app/lessons.tsx +76 -0
  318. package/web/app/logo.tsx +13 -0
  319. package/web/app/logos.jsx +16 -0
  320. package/web/app/manifest.js +8 -0
  321. package/web/app/mode-menu.tsx +46 -0
  322. package/web/app/new-session.jsx +275 -0
  323. package/web/app/notify.jsx +180 -0
  324. package/web/app/outcomes.tsx +94 -0
  325. package/web/app/page.jsx +9 -0
  326. package/web/app/pattern-graph.jsx +75 -0
  327. package/web/app/patterns-page.jsx +293 -0
  328. package/web/app/phone-nav.tsx +36 -0
  329. package/web/app/progress-feed.tsx +33 -0
  330. package/web/app/providers.tsx +27 -0
  331. package/web/app/quote.jsx +15 -0
  332. package/web/app/run-card.tsx +200 -0
  333. package/web/app/run-requests.tsx +148 -0
  334. package/web/app/scheduled.jsx +105 -0
  335. package/web/app/session-panel.tsx +174 -0
  336. package/web/app/session-toolbar.tsx +180 -0
  337. package/web/app/shadcn.css +638 -0
  338. package/web/app/shipped.jsx +49 -0
  339. package/web/app/subagent-runs.jsx +31 -0
  340. package/web/app/task-graph.jsx +67 -0
  341. package/web/app/tasks-strip.tsx +36 -0
  342. package/web/app/tasks.jsx +375 -0
  343. package/web/app/team-author.jsx +145 -0
  344. package/web/app/team-editor.jsx +88 -0
  345. package/web/app/thread-agents.tsx +32 -0
  346. package/web/app/thread-place.tsx +9 -0
  347. package/web/app/thread-sessions.tsx +149 -0
  348. package/web/app/thread-sidebar.tsx +418 -0
  349. package/web/app/thread-switcher.tsx +27 -0
  350. package/web/app/tool-diff.jsx +94 -0
  351. package/web/components/a2ui/controls.jsx +36 -0
  352. package/web/components/a2ui/option-picker.jsx +23 -0
  353. package/web/components/a2ui/script.tsx +121 -0
  354. package/web/components/a2ui/surface.jsx +81 -0
  355. package/web/components/chat/thread.jsx +50 -0
  356. package/web/components/script-text.tsx +42 -0
  357. package/web/components/ui/avatar.jsx +115 -0
  358. package/web/components/ui/badge.jsx +47 -0
  359. package/web/components/ui/button.jsx +63 -0
  360. package/web/components/ui/chat-container.jsx +52 -0
  361. package/web/components/ui/choice-list.tsx +72 -0
  362. package/web/components/ui/code-block.jsx +60 -0
  363. package/web/components/ui/copy-button.tsx +41 -0
  364. package/web/components/ui/dropdown-menu.jsx +257 -0
  365. package/web/components/ui/markdown.jsx +84 -0
  366. package/web/components/ui/message.jsx +28 -0
  367. package/web/components/ui/popover.jsx +33 -0
  368. package/web/components/ui/scroll-button.jsx +34 -0
  369. package/web/components/ui/select.jsx +189 -0
  370. package/web/components/ui/sheet.jsx +152 -0
  371. package/web/components/ui/sonner.jsx +10 -0
  372. package/web/components/ui/tabs.jsx +88 -0
  373. package/web/components/ui/textarea.jsx +20 -0
  374. package/web/components/ui/tooltip.jsx +56 -0
  375. package/web/components.json +24 -0
  376. package/web/instrumentation.js +8 -0
  377. package/web/lib/a2ui-catalog.js +34 -0
  378. package/web/lib/a2ui-pr.js +76 -0
  379. package/web/lib/a2ui-run-catalog.js +18 -0
  380. package/web/lib/a2ui-run.js +93 -0
  381. package/web/lib/a2ui.js +262 -0
  382. package/web/lib/activity-rows.js +275 -0
  383. package/web/lib/agent-detail.js +5 -0
  384. package/web/lib/alert-level.js +44 -0
  385. package/web/lib/approval-mode.js +22 -0
  386. package/web/lib/chat-turns.js +174 -0
  387. package/web/lib/child-subagents.js +16 -0
  388. package/web/lib/compaction-view.js +48 -0
  389. package/web/lib/composer-actions.js +40 -0
  390. package/web/lib/context-view.js +57 -0
  391. package/web/lib/fuzzy.js +26 -0
  392. package/web/lib/highlight.js +44 -0
  393. package/web/lib/lessons-view.js +23 -0
  394. package/web/lib/mentions.js +16 -0
  395. package/web/lib/message-routing.js +105 -0
  396. package/web/lib/new-session.js +85 -0
  397. package/web/lib/operator-messages.js +28 -0
  398. package/web/lib/pattern-graph.js +165 -0
  399. package/web/lib/pattern-view.js +33 -0
  400. package/web/lib/pending-summary.js +18 -0
  401. package/web/lib/permission-modes.js +30 -0
  402. package/web/lib/project-feed.js +107 -0
  403. package/web/lib/quote.js +7 -0
  404. package/web/lib/reply-quote.js +31 -0
  405. package/web/lib/scheduled.js +79 -0
  406. package/web/lib/selection.js +110 -0
  407. package/web/lib/send-confirmation.js +22 -0
  408. package/web/lib/session-dead.js +10 -0
  409. package/web/lib/session-state.js +132 -0
  410. package/web/lib/sidebar.js +15 -0
  411. package/web/lib/slash-commands.js +164 -0
  412. package/web/lib/start-default.js +35 -0
  413. package/web/lib/start-mode.js +35 -0
  414. package/web/lib/stream-views.js +49 -0
  415. package/web/lib/subagent-state.js +20 -0
  416. package/web/lib/task-board.js +54 -0
  417. package/web/lib/task-graph.js +183 -0
  418. package/web/lib/task-tags.js +41 -0
  419. package/web/lib/team-editor.js +10 -0
  420. package/web/lib/thread-groups.js +86 -0
  421. package/web/lib/threads.js +28 -0
  422. package/web/lib/tool-diff.js +273 -0
  423. package/web/lib/ui-events.js +58 -0
  424. package/web/lib/utils.js +5 -0
  425. package/web/lib/view-memory.js +25 -0
  426. package/web/next.config.mjs +37 -0
  427. package/web/postcss.config.mjs +1 -0
  428. package/web/proxy.js +25 -0
  429. package/web/public/sw.js +39 -0
  430. package/web/server/auth.js +178 -0
  431. package/web/server/dispatch.js +293 -0
  432. package/web/server/history.js +56 -0
  433. package/web/server/hosted.js +58 -0
  434. package/web/server/hub.js +126 -0
  435. package/web/server/instance.js +5 -0
  436. package/web/server/land-reviews.js +64 -0
  437. package/web/server/push.js +148 -0
  438. package/web/server/run-terminal.js +79 -0
  439. package/web/server/schedules.js +38 -0
  440. package/web/server/shipped.js +51 -0
  441. package/web/server/task-board.js +71 -0
  442. package/web/server/threads.js +209 -0
  443. package/web/server/ui.js +2937 -0
  444. package/web/tsconfig.base.json +16 -0
  445. package/web/tsconfig.json +9 -0
@@ -0,0 +1,1002 @@
1
+ /**
2
+ * Messaging: the bus HTTP client (publish, cached poll, stream), send and claim of msg envelopes, the channel and status
3
+ * reads, delivery reservations, and the wait loop (waitUntil, streamWaiter) with the inbox read (readInbox).
4
+ * Every network call goes through the bus client below. Delivery is best-effort: publish failures throw to the caller
5
+ * (CLI) or are swallowed by hooks; there is no outbox or retry (read receipts: lib/receipts.ts).
6
+ */
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
9
+ import path from "node:path";
10
+ import { MAX_BODY_CHARS, MESSAGE_MAX_BYTES, SEND_MAX_BYTES, SESSION_LABEL, isGithubLogin, isValidName, statusTopic, inboxTopic, broadcastTopic, threadTopic } from "./config.js";
11
+ import { deepLink } from "./deep-link.js";
12
+ import { alertPriority, readAlertLevel } from "./alerts.js";
13
+ import { parsePhoneReply, parseQuestionText } from "./questions.js";
14
+ import { readState, writeState, statePath, withLock } from "./state.js";
15
+ import { parseMode, recordMode } from "./mode.js";
16
+ import { imageAttachment, readAttachment } from "./attachment.js";
17
+ import { attachmentOf, cacheAttachmentsWithin, cacheUploadedAttachment, localizedAttachment } from "./attachment-cache.js";
18
+ import { encodeEnvelope, parseWireEnvelope } from "./agui.js";
19
+ import { sendReceipts, settleReceipts } from "./receipts.js";
20
+ import { reconnectBackoff } from "./operator.js";
21
+ export { MESSAGE_MAX_BYTES, SEND_MAX_BYTES } from "./config.js";
22
+ export const INITIAL_LOOKBACK_S = 3600; // first contact: deliver messages from the last hour
23
+ export const MAX_PER_CLAIM = 20;
24
+ export const HISTORY_DEFAULT = 30;
25
+ export const HISTORY_MAX = 100;
26
+ const HISTORY_TAIL_BYTES = 1024 * 1024; // the newest channel events a history read keeps
27
+ const SEEN_MAX = 500;
28
+ export const RESERVE_MS = 60_000; // a delivery reservation expires after this, so a crashed pusher cannot hold a message
29
+ // A hook may spend this long caching delivered attachments; past it the message arrives with metadata only.
30
+ export const ATTACHMENT_BUDGET_MS = 4000;
31
+ const HARNESSES = new Set(["claude", "codex", "cursor", "opencode", "pi"]);
32
+ const MESSAGE_ID = /^[a-zA-Z0-9-]{1,64}$/;
33
+ // States of a respond envelope (a msg with replyTo); old clients ignore the field.
34
+ export const RESPOND_STATES = ["working", "reply", "done", "declined"];
35
+ // normal wakes an idle session, urgent also polls at the next hook, fyi is queued without a wake.
36
+ export const PRIORITIES = ["normal", "urgent", "fyi"];
37
+ // The bus limit on one poll body; a larger body is cut at its last complete line.
38
+ const POLL_MAX_BYTES = 256 * 1024;
39
+ const STREAM_LINE_MAX = 64 * 1024;
40
+ const STREAM_IDLE_MS = 120_000;
41
+ const TAIL_READ_MAX_BYTES = 32 * 1024 * 1024;
42
+ const STREAM_BACKOFF_MAX_MS = 60_000;
43
+ const loggedNtfyErrors = new Set();
44
+ // The chat an @mention came from: "all" (the project chat) or a session address.
45
+ const MENTIONED_IN = /^(all|[a-z0-9-]{1,24}#[a-f0-9]{16})$/;
46
+ // The run ID of a subagent that an @mention names; the parent session relays it.
47
+ const SUBAGENT_RUN = /^[A-Za-z0-9_-]{1,64}$/;
48
+ // A team name when the operator routed work to a team orchestrator.
49
+ const TEAM_NAME = /^(?=.{1,24}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;
50
+ const THREAD_ID = /^th_[a-f0-9]{16}$/;
51
+ // A project-chat @tag: a harness, harness#session, harness#session/run, or harness:model.
52
+ // The lookahead refuses #, so a malformed @harness#label tag matches nothing rather than the whole harness.
53
+ const AGENT_MENTION = /(^|[^\w#-])@([a-z0-9-]{1,24}(?:#[a-f0-9]{16}(?:\/[A-Za-z0-9_-]{1,64})?|:[A-Za-z0-9][A-Za-z0-9._/-]{0,119})?)(?![\w#-])/g;
54
+ /** Waits until until() returns a value, the deadline passes, alive() turns false, or the signal aborts. Each step waits on stream or poll. */
55
+ export async function waitUntil(o) {
56
+ const now = o.now ?? Date.now;
57
+ for (let first = true;; first = false) {
58
+ if (!(first && o.checkFirst === false)) {
59
+ const value = await o.until(first);
60
+ if (value !== undefined)
61
+ return { status: "hit", value };
62
+ if (o.signal?.aborted)
63
+ return { status: "aborted" };
64
+ if (o.alive && !o.alive())
65
+ return { status: "timeout" };
66
+ }
67
+ if (o.signal?.aborted)
68
+ return { status: "aborted" };
69
+ const remaining = o.deadline - now();
70
+ if (remaining <= 0)
71
+ return { status: "timeout" };
72
+ const outcome = await nextStep(o, remaining);
73
+ if (outcome === "aborted" || o.signal?.aborted)
74
+ return { status: "aborted" };
75
+ if (outcome === "queued")
76
+ return { status: "queued" };
77
+ if (outcome === "error" && o.errorPauseMs)
78
+ await delay(Math.min(o.errorPauseMs, Math.max(0, o.deadline - now())));
79
+ }
80
+ }
81
+ // One wait of at most ms: the stream step, or a poll sleep capped at the poll interval.
82
+ function nextStep(o, ms) {
83
+ if (o.stream)
84
+ return o.stream(ms, o.signal);
85
+ const poll = o.poll ?? { intervalMs: ms };
86
+ const sleep = poll.sleep ?? ((d, sig) => delay(d, undefined, { signal: sig }));
87
+ return sleep(Math.min(poll.intervalMs, ms), o.signal).then(() => "timeout", () => "timeout");
88
+ }
89
+ /** Waiter on this peer's inbox and broadcast topics. wait(ms) resolves "event" on the first new event, "timeout" after ms, or "error" after an exponential backoff (stopPollMs doubling to 60 s) when the stream fails. */
90
+ export function streamWaiter(cfg, startMs) {
91
+ let since = String(Math.floor(startMs / 1000));
92
+ const backoff = reconnectBackoff(cfg.stopPollMs, STREAM_BACKOFF_MAX_MS);
93
+ return async (ms, signal) => {
94
+ const ctrl = new AbortController();
95
+ signal?.addEventListener("abort", () => ctrl.abort(), { once: true });
96
+ let timedOut = false;
97
+ const timer = setTimeout(() => { timedOut = true; ctrl.abort(); }, ms);
98
+ try {
99
+ const topics = [inboxTopic(cfg.project, cfg.peer), broadcastTopic(cfg.project)];
100
+ for await (const ev of streamEvents(cfg, topics, { since, signal: ctrl.signal, onOpen: () => backoff.reset() })) {
101
+ since = ev.id;
102
+ return "event";
103
+ }
104
+ }
105
+ catch { /* timeout, outage, or HTTP error such as 429 */ }
106
+ finally {
107
+ clearTimeout(timer);
108
+ ctrl.abort();
109
+ }
110
+ if (timedOut)
111
+ return "timeout";
112
+ if (signal?.aborted)
113
+ return "aborted";
114
+ await backoff.wait(signal, ms);
115
+ return "error";
116
+ };
117
+ }
118
+ /** Claims new messages for this session (peek leaves them unread), then publishes read receipts; receipts default to claims only. */
119
+ export async function readInbox(cfg, { peek = false, strict = true, limit, accept, receipts = !peek, settle = true, claim = claimInbox } = {}) {
120
+ const messages = await claim(cfg, { commit: !peek, strict, limit, accept });
121
+ if (receipts) {
122
+ sendReceipts(cfg, messages.map((m) => m.id));
123
+ if (settle)
124
+ await settleReceipts();
125
+ }
126
+ return messages;
127
+ }
128
+ /**
129
+ * ntfy turns the two characters \n of a query-string message into a newline, which breaks JSON string escapes.
130
+ * For a JSON message, respell \n and \\ as \u000a and \: the same JSON value, safe through the query string.
131
+ */
132
+ export function querySafe(message) {
133
+ try {
134
+ JSON.parse(message);
135
+ }
136
+ catch {
137
+ return message;
138
+ }
139
+ return message.replace(/\\(\\|n)/g, (_, c) => (c === "n" ? "\\u000a" : "\\u005c"));
140
+ }
141
+ // The request timeout, or the caller's deadline when that ends sooner.
142
+ function withSignal(signal, ms) {
143
+ return signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
144
+ }
145
+ // operatorToken is set only in the UI server's configs (lib/operator-token.ts withOperatorToken).
146
+ function headers(cfg, extra = {}) {
147
+ const h = { ...extra };
148
+ const token = cfg.operatorToken || cfg.token;
149
+ if (token)
150
+ h.authorization = `Bearer ${token}`;
151
+ return h;
152
+ }
153
+ /** Publishes one message; resolves with the new event's id (true when the server's answer carries none). */
154
+ export async function publish(cfg, topic, message, { title, attach, signal, priority, click, threadId, onPublished } = {}) {
155
+ // An attachment is the request body; the bus then takes message and title from the query string.
156
+ const query = attach && new URLSearchParams({
157
+ message: querySafe(message), filename: attach.filename,
158
+ ...(title ? { title } : {}), ...(click ? { click } : {}), ...(priority ? { priority: String(priority) } : {}), ...(threadId ? { thread_id: threadId } : {}),
159
+ });
160
+ const res = attach
161
+ ? await fetch(`${cfg.url}/${topic}?${query}`, {
162
+ method: "PUT", headers: headers(cfg), body: attach.data, signal: withSignal(signal, cfg.timeoutMs * 4),
163
+ })
164
+ : await fetch(`${cfg.url}/`, {
165
+ method: "POST",
166
+ headers: headers(cfg, { "content-type": "application/json" }),
167
+ body: JSON.stringify({ topic, message, ...(title ? { title } : {}), ...(priority ? { priority } : {}), ...(click ? { click } : {}), ...(threadId ? { thread_id: threadId } : {}) }),
168
+ signal: withSignal(signal, cfg.timeoutMs),
169
+ });
170
+ const text = await res.text().catch(() => "");
171
+ if (!res.ok)
172
+ throw Object.assign(new Error(`publish failed: HTTP ${res.status}`), { ntfyStatus: res.status });
173
+ const id = publishedId(text);
174
+ const published = attach || onPublished ? messageEvent(text) : undefined;
175
+ if (attach && published) {
176
+ try {
177
+ cacheUploadedAttachment(cfg, published, attach);
178
+ }
179
+ catch { /* upload already succeeded */ }
180
+ }
181
+ if (id && onPublished) {
182
+ const event = published || { id, message, title, time: Math.floor(Date.now() / 1000) };
183
+ onPublished({ ...event, topic });
184
+ }
185
+ return id || true;
186
+ }
187
+ // The id of the event the bus answers a publish with, or "".
188
+ function publishedId(text) {
189
+ try {
190
+ const id = JSON.parse(text)?.id;
191
+ return typeof id === "string" && /^[a-zA-Z0-9-]{1,64}$/.test(id) ? id : "";
192
+ }
193
+ catch {
194
+ return "";
195
+ }
196
+ }
197
+ async function readBounded(res, maxBytes) {
198
+ if (!res.body)
199
+ return "";
200
+ const reader = res.body.getReader();
201
+ const chunks = [];
202
+ let total = 0;
203
+ let truncated = false;
204
+ for (;;) {
205
+ const { done, value } = await reader.read();
206
+ if (done)
207
+ break;
208
+ total += value.length;
209
+ if (total > maxBytes) {
210
+ chunks.push(value.subarray(0, value.length - (total - maxBytes)));
211
+ truncated = true;
212
+ await reader.cancel().catch(() => { });
213
+ break;
214
+ }
215
+ chunks.push(value);
216
+ }
217
+ let text = Buffer.concat(chunks.map((c) => Buffer.from(c))).toString("utf8");
218
+ // Drop a partial trailing line so only complete JSON lines are parsed.
219
+ if (truncated)
220
+ text = text.slice(0, text.lastIndexOf("\n") + 1);
221
+ return text;
222
+ }
223
+ // Keeps the newest complete lines within keepBytes; stops reading after TAIL_READ_MAX_BYTES.
224
+ async function readTail(res, keepBytes) {
225
+ if (!res.body)
226
+ return "";
227
+ const reader = res.body.getReader();
228
+ const decoder = new TextDecoder();
229
+ const lines = [];
230
+ let kept = 0;
231
+ let partial = "";
232
+ let total = 0;
233
+ for (;;) {
234
+ const { done, value } = await reader.read();
235
+ if (done)
236
+ break;
237
+ total += value.length;
238
+ const parts = (partial + decoder.decode(value, { stream: true })).split("\n");
239
+ partial = parts.pop() ?? "";
240
+ for (const line of parts) {
241
+ lines.push(line);
242
+ kept += line.length + 1;
243
+ }
244
+ while (kept > keepBytes && lines.length)
245
+ kept -= (lines.shift() ?? "").length + 1;
246
+ if (total > TAIL_READ_MAX_BYTES) {
247
+ await reader.cancel().catch(() => { });
248
+ break;
249
+ }
250
+ }
251
+ return lines.join("\n") + "\n";
252
+ }
253
+ /**
254
+ * Cached read: GET /<topic>/json?poll=1&since=<id|unix-seconds|duration>.
255
+ * Returns only "message" events, oldest first. tailBytes keeps the newest events instead of the oldest.
256
+ */
257
+ export async function pollCached(cfg, topic, since, signal, { tailBytes = 0 } = {}) {
258
+ const url = `${cfg.url}/${encodeURIComponent(topic)}/json?poll=1&since=${encodeURIComponent(since)}`;
259
+ const timeout = AbortSignal.timeout(cfg.timeoutMs);
260
+ const res = await fetch(url, { headers: headers(cfg), signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
261
+ if (!res.ok) {
262
+ logNtfyErrorOnce(res.status, await res.text().catch(() => ""));
263
+ throw Object.assign(new Error(`poll failed: HTTP ${res.status}`), { ntfyStatus: res.status });
264
+ }
265
+ const text = tailBytes ? await readTail(res, tailBytes) : await readBounded(res, POLL_MAX_BYTES);
266
+ return text.split("\n").map(messageEvent).filter((ev) => ev !== null);
267
+ }
268
+ // The JSON error body of a bus response, or {} when the body is not JSON.
269
+ function ntfyErrorOf(body) {
270
+ try {
271
+ return JSON.parse(body) ?? {};
272
+ }
273
+ catch {
274
+ return {};
275
+ }
276
+ }
277
+ // Writes one stderr line per distinct bus status and error code: "bus HTTP 429 code 42905: <error>".
278
+ function logNtfyErrorOnce(status, body) {
279
+ const parsed = ntfyErrorOf(body);
280
+ const key = `${status}:${parsed.code ?? ""}`;
281
+ if (loggedNtfyErrors.has(key))
282
+ return;
283
+ loggedNtfyErrors.add(key);
284
+ const code = parsed.code ? ` code ${parsed.code}` : "";
285
+ const error = typeof parsed.error === "string" ? `: ${parsed.error}` : "";
286
+ process.stderr.write(`temmo: bus HTTP ${status}${code}${error}\n`);
287
+ }
288
+ function messageEvent(line) {
289
+ if (!line.trim())
290
+ return null;
291
+ let ev;
292
+ try {
293
+ ev = JSON.parse(line);
294
+ }
295
+ catch {
296
+ return null;
297
+ }
298
+ if (!ev || ev.event !== "message" || typeof ev.id !== "string" || typeof ev.message !== "string")
299
+ return null;
300
+ const a = ev.attachment;
301
+ const attachment = a && typeof a.url === "string"
302
+ ? { name: String(a.name || ""), type: String(a.type || ""), size: Number(a.size) || 0, url: a.url }
303
+ : undefined;
304
+ // The title carries who sent a UI reply (web/server/ui.ts replyTitle).
305
+ const title = typeof ev.title === "string" && ev.title ? { title: ev.title.slice(0, 200) } : {};
306
+ const reset = ev.reset === true ? { reset: true } : {};
307
+ // Only the bus sets verified, and only for a publish that carried the operator token (lib/operator-token.ts).
308
+ const verified = ev.verified === true ? { verified: true } : {};
309
+ return { id: ev.id, time: Number(ev.time) || 0, topic: ev.topic, message: ev.message, ...title, ...(attachment ? { attachment } : {}), ...reset, ...verified };
310
+ }
311
+ // The stream's first line is its open line; reset: true there means the bus replayed from the oldest event.
312
+ function openedWithReset(line) {
313
+ try {
314
+ return JSON.parse(line)?.reset === true;
315
+ }
316
+ catch {
317
+ return false;
318
+ }
319
+ }
320
+ /**
321
+ * Streaming read of GET /<topic1>,<topic2>/json?since=…; yields message events until close, idle, or abort.
322
+ * onReset() runs once when the bus flags the replay (an unknown since): the events then carry the replayed backlog.
323
+ */
324
+ export async function* streamEvents(cfg, topics, { since = "", signal, onOpen, onReset } = {}) {
325
+ const ctrl = new AbortController();
326
+ const abort = () => ctrl.abort(signal?.reason);
327
+ signal?.addEventListener("abort", abort, { once: true });
328
+ let timer = setTimeout(() => ctrl.abort(new Error("subscribe timed out")), cfg.timeoutMs);
329
+ const arm = () => {
330
+ clearTimeout(timer);
331
+ timer = setTimeout(() => ctrl.abort(new Error("subscription idle")), STREAM_IDLE_MS);
332
+ };
333
+ try {
334
+ const query = since ? `?since=${encodeURIComponent(since)}` : "";
335
+ const res = await fetch(`${cfg.url}/${topics.map(encodeURIComponent).join(",")}/json${query}`, {
336
+ headers: headers(cfg), signal: ctrl.signal,
337
+ });
338
+ if (!res.ok) {
339
+ await res.arrayBuffer().catch(() => { });
340
+ throw Object.assign(new Error(`subscribe failed: HTTP ${res.status}`), { ntfyStatus: res.status });
341
+ }
342
+ arm();
343
+ onOpen?.();
344
+ let buffer = "";
345
+ let first = true;
346
+ const body = res.body;
347
+ if (!body)
348
+ throw new Error("subscribe response has no body");
349
+ for await (const chunk of body.pipeThrough(new TextDecoderStream())) {
350
+ arm();
351
+ const lines = (buffer + chunk).split("\n");
352
+ buffer = lines.pop() ?? "";
353
+ if (buffer.length > STREAM_LINE_MAX)
354
+ throw new Error("subscription line too long");
355
+ for (const line of lines) {
356
+ if (first && line.trim()) {
357
+ first = false;
358
+ if (openedWithReset(line))
359
+ onReset?.();
360
+ }
361
+ const ev = messageEvent(line);
362
+ if (ev)
363
+ yield ev;
364
+ }
365
+ }
366
+ }
367
+ finally {
368
+ clearTimeout(timer);
369
+ signal?.removeEventListener("abort", abort);
370
+ ctrl.abort();
371
+ }
372
+ }
373
+ // The sender's session label when the envelope carries a valid one, else "".
374
+ function sessionOf(m) {
375
+ return typeof m.session === "string" && SESSION_LABEL.test(m.session) ? m.session : "";
376
+ }
377
+ // A sender or recipient address: the harness, or harness#session when a session is named.
378
+ function addressOf(peer, session) {
379
+ return session ? `${peer}#${session}` : peer;
380
+ }
381
+ // The envelope timestamp when it is short and plain, else "".
382
+ function timestampOf(m) {
383
+ return typeof m.ts === "string" && /^[\w:.+-]{1,40}$/.test(m.ts) ? m.ts : "";
384
+ }
385
+ function envelope(cfg, kind, fields) {
386
+ return encodeEnvelope(kind, { from: cfg.peer, ...(cfg.session ? { session: cfg.session } : {}), ...fields }, cfg.wire);
387
+ }
388
+ export function parseEnvelope(raw) {
389
+ return parseWireEnvelope(raw);
390
+ }
391
+ /** Status carries metadata only: peer, event, harness, time. No paths, prompts, or output. */
392
+ export async function publishStatus(cfg, { event, harness }) {
393
+ const h = HARNESSES.has(harness) ? harness : "other";
394
+ const msg = envelope(cfg, "status", { event, harness: h, ...(cfg.parent ? { parent: cfg.parent } : {}), ts: new Date().toISOString() });
395
+ await publish(cfg, statusTopic(cfg.project), msg, { title: "temmo status", priority: alertPriority(readAlertLevel(), "other") });
396
+ }
397
+ /**
398
+ * Sends one msg envelope; resolves {topic, id}. urgent marks it for delivery at the recipient's next hook (markUrgent);
399
+ * state (with replyTo) answers a message as working, reply, done or declined; by names the operator's GitHub login;
400
+ * forSubagent names the subagent run (of the target session) that the message is for.
401
+ * priority is normal, urgent (same as urgent: true) or fyi (queued, never wakes an idle session);
402
+ * expectReply marks a direct message the dispatcher redelivers until the target answers (web/server/dispatch.ts);
403
+ * system marks text temmo's own machinery sends (a compaction request, a pattern-run notice) under the operator's
404
+ * address: it reaches the operator's own reply routes, but readers show the sender as "system", not as the operator.
405
+ * startOnly marks a project-chat post that only starts sessions, so no running session takes it.
406
+ * progress marks a project-chat post as a milestone note (send_to_all progress=true), which the phone's Recent progress lists.
407
+ * A thread:<id> target posts to the thread channel (lib/thread-channels.ts); channelOf marks one of its copies.
408
+ */
409
+ export async function sendMessage(cfg, target, body, options = {}) {
410
+ if (!cfg.enabled)
411
+ throw new Error(`disabled: ${cfg.reason}`);
412
+ if (String(target).startsWith("thread:")) {
413
+ const { sendToThread } = await import("./thread-channels.js");
414
+ return sendToThread(cfg, target, body, options);
415
+ }
416
+ let { urgent } = options;
417
+ const { operatorThread, system, replyTo, attachment, state, by, mentionedIn, forSubagent, forTeam, priority, expectReply, startOnly, progress, threadId, channelOf, mentionOf, onPublished } = options;
418
+ const [peer, session, ...extra] = String(target).split("#");
419
+ if (!isValidName(peer) || extra.length || (session !== undefined && (peer === "all" || !SESSION_LABEL.test(session)))) {
420
+ throw new Error(`invalid peer name "${target}"`);
421
+ }
422
+ if (peer !== "all" && cfg.peers.length && !cfg.peers.includes(peer)) {
423
+ throw new Error(`peer "${target}" is not in TEMMO_PEERS`);
424
+ }
425
+ if (typeof body !== "string" || (!body.trim() && attachment === undefined))
426
+ throw new Error("empty message");
427
+ if (body.length > MAX_BODY_CHARS)
428
+ throw new Error(`message is over ${MAX_BODY_CHARS} characters`);
429
+ const topic = peer === "all" ? broadcastTopic(cfg.project) : inboxTopic(cfg.project, peer);
430
+ if (operatorThread && (cfg.peer !== "operator" || !session))
431
+ throw new Error("Direct chats require a session");
432
+ if (replyTo !== undefined && !MESSAGE_ID.test(replyTo))
433
+ throw new Error("invalid reply_to message ID");
434
+ if (state !== undefined && (!RESPOND_STATES.includes(state) || !replyTo))
435
+ throw new Error("state must be working, reply, done or declined, with reply_to");
436
+ if (by !== undefined && (cfg.peer !== "operator" || !isGithubLogin(by)))
437
+ throw new Error("by must be a GitHub login on an operator message");
438
+ if (system !== undefined && (system !== true || cfg.peer !== "operator")) {
439
+ throw new Error("system messages are temmo's own, sent from the operator address");
440
+ }
441
+ if (mentionedIn !== undefined && !MENTIONED_IN.test(mentionedIn))
442
+ throw new Error("invalid mentionedIn chat");
443
+ if (mentionOf !== undefined && (cfg.peer !== "operator" || !MESSAGE_ID.test(mentionOf)))
444
+ throw new Error("mentionOf must be an operator copy of a message id");
445
+ if (forSubagent !== undefined && !SUBAGENT_RUN.test(forSubagent))
446
+ throw new Error("invalid forSubagent run ID");
447
+ if (forTeam !== undefined && !TEAM_NAME.test(forTeam))
448
+ throw new Error("invalid forTeam name");
449
+ if (priority !== undefined && !PRIORITIES.includes(priority))
450
+ throw new Error("priority must be normal, urgent or fyi");
451
+ if (priority === "fyi" && urgent === true)
452
+ throw new Error("a message cannot be both fyi and urgent");
453
+ if (expectReply !== undefined && typeof expectReply !== "boolean")
454
+ throw new Error("expect_reply must be true or false");
455
+ if (expectReply === true && (peer === "all" || priority === "fyi"))
456
+ throw new Error("expect_reply needs a direct, non-fyi message");
457
+ if (startOnly !== undefined && typeof startOnly !== "boolean")
458
+ throw new Error("start_only must be true or false");
459
+ if (startOnly === true && peer !== "all")
460
+ throw new Error("start_only needs the project chat");
461
+ if (progress !== undefined && (progress !== true || peer !== "all"))
462
+ throw new Error("progress needs the project chat");
463
+ if (channelOf !== undefined && (!MESSAGE_ID.test(channelOf) || !session || threadId === undefined))
464
+ throw new Error("channelOf needs a thread copy to a session");
465
+ if (threadId !== undefined && ((cfg.peer !== "operator" && channelOf === undefined) || !THREAD_ID.test(threadId)))
466
+ throw new Error("threadId must be a thread id on an operator message");
467
+ if (priority === "urgent")
468
+ urgent = true;
469
+ const project = session ? sessionProject(cfg, peer, session) : cfg.project;
470
+ const sent = await sendEnvelope(cfg, project === cfg.project ? topic : inboxTopic(project, peer), {
471
+ to: peer, ...(session ? { toSession: session } : {}), ts: new Date().toISOString(), body,
472
+ ...(operatorThread ? { operatorThread: true } : {}),
473
+ ...(system === true ? { system: true } : {}),
474
+ ...(replyTo ? { replyTo } : {}),
475
+ ...(state ? { state } : {}),
476
+ ...(urgent === true ? { urgent: true } : {}),
477
+ ...(priority === "fyi" ? { priority } : {}),
478
+ ...(expectReply === true ? { expectReply: true } : {}),
479
+ ...(startOnly === true ? { startOnly: true } : {}),
480
+ ...(progress === true ? { progress: true } : {}),
481
+ ...(by ? { by } : {}),
482
+ ...(mentionedIn ? { mentionedIn } : {}),
483
+ ...(mentionOf ? { mentionOf } : {}),
484
+ ...(forSubagent ? { forSubagent } : {}),
485
+ ...(forTeam ? { forTeam } : {}),
486
+ ...(threadId ? { threadId } : {}),
487
+ ...(channelOf ? { channel: channelOf } : {}),
488
+ }, { attachment, onPublished, ...(threadId && !channelOf ? { threadId } : {}) });
489
+ if (urgent === true)
490
+ markUrgent({ ...cfg, project }, String(target));
491
+ return sent;
492
+ }
493
+ /**
494
+ * The project whose inbox reaches peer#session. A session label names one session machine-wide, so a target
495
+ * registered only under another project (a spawned child working in another repo, its parent here) lives there;
496
+ * otherwise, and when the registries are unreadable or ambiguous, the sender's own project.
497
+ */
498
+ export function sessionProject(cfg, peer, session) {
499
+ const file = `${peer}#${session}.json`;
500
+ const registered = (project) => existsSync(path.join(cfg.stateDir, project, "registry", file));
501
+ if (!cfg.stateDir || registered(cfg.project))
502
+ return cfg.project;
503
+ let names = [];
504
+ try {
505
+ names = readdirSync(cfg.stateDir);
506
+ }
507
+ catch {
508
+ return cfg.project;
509
+ }
510
+ const found = names.filter((name) => name !== cfg.project && isValidName(name) && registered(name));
511
+ return found.length === 1 ? found[0] : cfg.project;
512
+ }
513
+ /** Publishes a thread-channel post once on its thread topic with events.thread_id set; nothing reads that topic for delivery. */
514
+ export async function publishThreadPost(cfg, threadId, body, { attachment, by, onPublished } = {}) {
515
+ if (!THREAD_ID.test(threadId))
516
+ throw new Error("invalid thread id");
517
+ if (body.length > MAX_BODY_CHARS)
518
+ throw new Error(`message is over ${MAX_BODY_CHARS} characters`);
519
+ return sendEnvelope(cfg, threadTopic(cfg.project, threadId), {
520
+ to: `thread:${threadId}`, ts: new Date().toISOString(), body, threadId,
521
+ ...(cfg.peer === "operator" && isGithubLogin(by) ? { by } : {}),
522
+ }, { attachment, threadId, onPublished });
523
+ }
524
+ function urgentFile(cfg, target) {
525
+ return path.join(cfg.stateDir, cfg.project, "urgent", target);
526
+ }
527
+ /**
528
+ * Records that an urgent message for target (all, peer, or peer#session) was published. Hooks on this machine read
529
+ * the marker before their poll throttle, so the next hook event polls the bus at once. Best effort: errors are ignored.
530
+ */
531
+ export function markUrgent(cfg, target, now = Date.now()) {
532
+ try {
533
+ const file = urgentFile(cfg, target);
534
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
535
+ writeFileSync(file, String(now), { mode: 0o600 });
536
+ }
537
+ catch { /* the message still arrives at the next unthrottled poll */ }
538
+ }
539
+ /** True when an urgent message for this peer or session was marked after `at` (ms). Costs up to three small file reads. */
540
+ export function urgentSince(cfg, at) {
541
+ const targets = ["all", cfg.peer, ...(cfg.session ? [`${cfg.peer}#${cfg.session}`] : [])];
542
+ return targets.some((target) => {
543
+ try {
544
+ return Number(readFileSync(urgentFile(cfg, target), "utf8")) > at;
545
+ }
546
+ catch {
547
+ return false;
548
+ }
549
+ });
550
+ }
551
+ async function sendEnvelope(cfg, topic, fields, { attachment, onPublished, threadId } = {}) {
552
+ const msg = envelope(cfg, "msg", fields);
553
+ // With an attachment the message travels in the query string, respelled by querySafe.
554
+ const limit = attachment === undefined ? SEND_MAX_BYTES : MESSAGE_MAX_BYTES;
555
+ if (Buffer.byteLength(attachment === undefined ? msg : querySafe(msg)) > limit) {
556
+ throw new Error(`encoded message exceeds the ${limit}-byte wire limit`);
557
+ }
558
+ const attach = attachment === undefined ? undefined
559
+ : typeof attachment === "object" && Buffer.isBuffer(attachment.data) && typeof attachment.filename === "string"
560
+ ? imageAttachment(attachment.filename, attachment.data) : readAttachment(attachment);
561
+ const from = addressOf(cfg.peer, cfg.session);
562
+ // deep-link.mjs infers its parameter type without project; the call passes it.
563
+ const link = { project: cfg.project, session: cfg.session ? from : "" };
564
+ const click = deepLink(link);
565
+ const id = await publish(cfg, topic, msg, { title: `temmo from ${from}`, attach, onPublished, click, priority: alertPriority(readAlertLevel(), "direct"), ...(threadId ? { threadId } : {}) });
566
+ return { topic, ...(typeof id === "string" ? { id } : {}) };
567
+ }
568
+ export async function replyToOperator(cfg, id, body, { attachment, state } = {}) {
569
+ if (!cfg.session || typeof id !== "string" || !MESSAGE_ID.test(id)) {
570
+ throw new Error("Use the session and message ID supplied by the temmo hook");
571
+ }
572
+ if (typeof body !== "string" || !body.trim() || body.length > MAX_BODY_CHARS) {
573
+ throw new Error(`Enter 1–${MAX_BODY_CHARS} characters`);
574
+ }
575
+ const topic = inboxTopic(cfg.project, cfg.peer);
576
+ // The newest end: a long inbox exceeds one bounded poll, and the reply target is recent.
577
+ const history = await pollCached(cfg, topic, "all", undefined, { tailBytes: POLL_MAX_BYTES });
578
+ const original = parseEnvelope(history.find((event) => event.id === id)?.message);
579
+ if (original?.kind !== "msg" || original.from !== "operator" || original.operatorThread !== true ||
580
+ original.to !== cfg.peer || original.toSession !== cfg.session) {
581
+ throw new Error("This operator message is unavailable for your session");
582
+ }
583
+ if (state !== undefined && !RESPOND_STATES.includes(state))
584
+ throw new Error("state must be working, reply, done or declined");
585
+ await sendEnvelope(cfg, topic, {
586
+ to: "operator", operatorThread: true, replyTo: id, ts: new Date().toISOString(), body, ...(state ? { state } : {}),
587
+ }, { attachment });
588
+ return { sent: true };
589
+ }
590
+ /**
591
+ * True when a project-chat body addresses this agent. `@peer` names the harness and wakes every session of it.
592
+ * `@peer#session` (and `@peer#session/run`) names that session. A `@peer:model` tag starts a new session and does not.
593
+ */
594
+ export function mentionsAgent(body, { peer, session } = {}) {
595
+ if (!peer)
596
+ return false;
597
+ const address = session ? `${peer}#${session}` : "";
598
+ for (const match of String(body).matchAll(AGENT_MENTION)) {
599
+ const name = match[2].replace(/\.+$/, "");
600
+ if (name === peer)
601
+ return true;
602
+ if (address && (name === address || name.startsWith(`${address}/`)))
603
+ return true;
604
+ }
605
+ return false;
606
+ }
607
+ /**
608
+ * Read new messages for this peer (direct inbox plus broadcast).
609
+ * - throttle: skip the network if the last poll was < pollIntervalMs ago (hot hooks), unless an urgent marker is newer.
610
+ * - commit: false = peek, no cursor or dedup writes.
611
+ * - strict: rethrow errors and lock contention instead of returning [] (CLI).
612
+ * Cursors advance only past events that were processed, so a cap or failure
613
+ * leaves the remainder for the next claim.
614
+ * An agent session (cfg.session set) takes a project-chat post only when mentionsAgent matches.
615
+ * A direct message, including one to the peer inbox, is always taken. A claim with no session is the
616
+ * peer inbox and still sees the channel. Phone alert priority is unchanged.
617
+ */
618
+ export async function claimInbox(cfg, opts = {}) {
619
+ const { now = Date.now(), throttle = false, commit = true, strict = false, limit = MAX_PER_CLAIM, accept = () => true, poll = null, peek = null, limited = null } = opts;
620
+ if (!cfg.enabled)
621
+ return [];
622
+ const file = statePath(cfg);
623
+ const inbox = inboxTopic(cfg.project, cfg.peer);
624
+ const all = broadcastTopic(cfg.project);
625
+ const snapshot = readState(file);
626
+ if (throttle && cfg.pollIntervalMs > 0 && now - snapshot.lastPollAt < cfg.pollIntervalMs && !urgentSince(cfg, snapshot.lastPollAt))
627
+ return [];
628
+ // Network reads run before the lock; the lock covers only the state read, the apply and the write.
629
+ const fetched = await fetchTopics(cfg, snapshot, [inbox, all], now, { poll, peek, file, limited });
630
+ const apply = (state) => applyEvents(cfg, state, fetched, { inbox, all, now, limit, accept, strict });
631
+ if (!commit) {
632
+ try {
633
+ const state = readState(file);
634
+ const out = apply(state);
635
+ if (peek && out.length === 0)
636
+ recordPeek(peek, file, snapshot, fetched, state, [inbox, all]);
637
+ return out;
638
+ }
639
+ catch (err) {
640
+ if (strict)
641
+ throw err;
642
+ return [];
643
+ }
644
+ }
645
+ try {
646
+ const r = await underLock(file, () => {
647
+ const state = readState(file);
648
+ state.lastPollAt = now;
649
+ const out = apply(state);
650
+ state.reserved = Object.fromEntries(Object.entries(state.reserved).filter(([, v]) => untilOf(v) > now));
651
+ writeState(file, state);
652
+ return out;
653
+ });
654
+ if (!r.locked) {
655
+ if (strict)
656
+ throw new Error("another temmo process holds the inbox lock; retry");
657
+ return [];
658
+ }
659
+ // A delivered attachment is cached once for the whole machine, outside the lock and under a short budget,
660
+ // so the agent reads the file the UI already has instead of downloading it from the bus again.
661
+ return r.value.some((m) => m.attachment && !m.attachment.local_path)
662
+ ? await cacheAttachmentsWithin(cfg, r.value, { budgetMs: ATTACHMENT_BUDGET_MS })
663
+ : r.value;
664
+ }
665
+ catch (err) {
666
+ if (strict)
667
+ throw err;
668
+ return [];
669
+ }
670
+ }
671
+ // Queue changes share the inbox lock with hook claims and push reservations.
672
+ export async function changeQueuedMessage(cfg, id, change) {
673
+ const file = statePath(cfg);
674
+ const result = await withInboxLock(file, () => {
675
+ const state = readState(file);
676
+ if (state.seen.includes(id) || untilOf(state.reserved[id]) > Date.now() || state.queue?.[id]?.cancelled)
677
+ return false;
678
+ state.queue = { ...state.queue, [id]: { ...state.queue?.[id], ...change } };
679
+ writeState(file, state);
680
+ return true;
681
+ });
682
+ return result.locked && result.value;
683
+ }
684
+ export function queuedMessage(message, state) {
685
+ const change = state.queue?.[message.id];
686
+ return change?.cancelled ? null : change ? { ...message, ...change } : message;
687
+ }
688
+ // A push can peek before an edit, so resolve its payload again after reserving.
689
+ export function reservedMessage(cfg, message) {
690
+ return queuedMessage(message, readState(statePath(cfg)));
691
+ }
692
+ // Bus event ids are digits. An ntfy-era state file holds alphanumeric ids no bus event carries: reading from one
693
+ // replays the whole topic past a seen list that matches nothing, so it counts as no cursor (first contact).
694
+ function committedId(state, topic) {
695
+ const cur = state.topics[topic];
696
+ const id = cur && typeof cur === "object" ? cur.id : undefined;
697
+ return typeof id === "string" && /^\d+$/.test(id) ? id : "";
698
+ }
699
+ // A peek is a read position per lane (live or wake path), state file and topic: each path refuses different messages.
700
+ function peekKey(lane, file, topic) {
701
+ return `${lane}\n${file}\n${topic}`;
702
+ }
703
+ // Polls each topic from the peek position while it still follows the committed cursor, else from the committed cursor.
704
+ // A failed topic is kept as its error (fail open per topic). poll memoizes reads by topic and since across sessions in one tick.
705
+ // limited holds the topics that answered 429 earlier in the tick: they are not polled again.
706
+ async function fetchTopics(cfg, state, topics, now, { poll = null, peek = null, file = "", limited = null } = {}) {
707
+ const fetched = new Map();
708
+ for (const topic of topics) {
709
+ if (limited?.has(topic)) {
710
+ fetched.set(topic, { error: Object.assign(new Error("topic rate limited earlier this tick"), { ntfyStatus: 429 }) });
711
+ continue;
712
+ }
713
+ const committed = committedId(state, topic);
714
+ const peeked = peek?.cursors.get(peekKey(peek.lane, file, topic));
715
+ const since = peeked && peeked.base === committed ? peeked.id : committed || String(Math.floor(now / 1000) - INITIAL_LOOKBACK_S);
716
+ try {
717
+ const key = `${topic}\n${since}`;
718
+ let read = poll?.get(key);
719
+ if (!read) {
720
+ read = pollCached(cfg, topic, since).then((events) => {
721
+ if (events.some((e) => e.reset))
722
+ process.stderr.write(`temmo: bus replayed ${topic} from the oldest event (unknown cursor)\n`);
723
+ return events;
724
+ });
725
+ poll?.set(key, read);
726
+ }
727
+ fetched.set(topic, { events: await read });
728
+ }
729
+ catch (err) {
730
+ fetched.set(topic, { error: err });
731
+ if (err.ntfyStatus === 429)
732
+ limited?.add(topic);
733
+ }
734
+ }
735
+ return fetched;
736
+ }
737
+ // After a peek that returned nothing, moves the in-memory read position past the events it examined, so an idle
738
+ // session stops re-reading the same broadcast backlog. Only memory: the committed cursor is never written here.
739
+ function recordPeek(peek, file, snapshot, fetched, state, topics) {
740
+ for (const topic of topics) {
741
+ if (fetched.get(topic)?.error)
742
+ continue;
743
+ const id = committedId(state, topic);
744
+ const base = committedId(snapshot, topic);
745
+ if (id && id !== base)
746
+ peek.cursors.set(peekKey(peek.lane, file, topic), { base, id });
747
+ }
748
+ }
749
+ /**
750
+ * Whether an event is the operator's own words, verified: the bus stamped it (operator token) and it is phone text
751
+ * (no envelope) or an operator envelope that is not a temmo system message.
752
+ */
753
+ export function operatorVerified(ev, m) {
754
+ return ev.verified === true && (m === null || (m.from === "operator" && m.system !== true));
755
+ }
756
+ // Applies fetched events to state: cursor, seen ids, mode, and the messages this session takes.
757
+ // A reserved id belongs to a push in flight: the cursor stops before it, so a failed push can still deliver it.
758
+ // accept(message) decides whether a message counts toward limit; a refused one is neither returned nor counted.
759
+ function applyEvents(cfg, state, fetched, { inbox, all, now, limit, accept, strict }) {
760
+ const seen = new Set(state.seen);
761
+ const reserved = new Set(liveReserved(state, now));
762
+ const out = [];
763
+ let lastError;
764
+ const add = (message) => {
765
+ if (accept(message))
766
+ out.push(message);
767
+ };
768
+ for (const topic of [inbox, all]) {
769
+ if (out.length >= limit)
770
+ break;
771
+ const f = fetched.get(topic);
772
+ if (!f)
773
+ continue;
774
+ if (f.error) {
775
+ lastError = f.error;
776
+ continue;
777
+ }
778
+ const cur = (state.topics[topic] && typeof state.topics[topic] === "object" ? state.topics[topic] : {});
779
+ state.topics[topic] = cur;
780
+ for (const ev of f.events ?? []) {
781
+ if (out.length >= limit)
782
+ break;
783
+ if (reserved.has(ev.id))
784
+ break;
785
+ cur.id = ev.id;
786
+ if (seen.has(ev.id))
787
+ continue;
788
+ seen.add(ev.id);
789
+ const m = parseEnvelope(ev.message);
790
+ if ((!m || m.kind === "question") && topic === all && ev.message.trim() && !parsePhoneReply(ev.message)) {
791
+ const question = parseQuestionText(m || ev.message);
792
+ if (m && !question)
793
+ continue;
794
+ if (question && cfg.session && question.sender === `${cfg.peer}#${cfg.session}`)
795
+ continue; // own question
796
+ const text = (question?.text ?? ev.message).slice(0, MAX_BODY_CHARS);
797
+ // Channel text wakes an agent session only when it @mentions that session or its harness.
798
+ if (cfg.session && !mentionsAgent(text, cfg))
799
+ continue;
800
+ add({
801
+ id: ev.id, from: "ntfy", to: "all", ts: "", body: text,
802
+ ...(question ? {} : { operatorBroadcast: true }),
803
+ ...(!question && operatorVerified(ev, null) ? { verified: true } : {}),
804
+ });
805
+ continue;
806
+ }
807
+ if (topic === all && m?.kind === "mode") {
808
+ recordMode(state, parseMode(m));
809
+ continue;
810
+ }
811
+ if (!m || m.kind !== "msg" || typeof m.body !== "string")
812
+ continue;
813
+ if (!isValidName(m.from))
814
+ continue;
815
+ const senderSession = sessionOf(m);
816
+ if (m.from === cfg.peer && (!senderSession || !cfg.session || senderSession === cfg.session))
817
+ continue;
818
+ const wantTo = topic === inbox ? cfg.peer : "all";
819
+ if (m.to !== wantTo || (m.toSession !== undefined && m.toSession !== cfg.session))
820
+ continue;
821
+ // A direct copy of a project-chat post and the broadcast itself are one message: a session takes whichever it reads first.
822
+ if (topic === inbox && m.from === "operator" && typeof m.mentionOf === "string" && MESSAGE_ID.test(m.mentionOf)) {
823
+ if (seen.has(m.mentionOf))
824
+ continue;
825
+ seen.add(m.mentionOf);
826
+ }
827
+ // A start-only post (only @harness:model tags) addresses the sessions its tags start; no running session takes it.
828
+ if (topic === all && m.from === "operator" && m.startOnly === true && m.toSession === undefined)
829
+ continue;
830
+ // An agent session does not take project-chat noise. The cursor has already moved past it, so it never starts a turn.
831
+ // A direct message was accepted above. An operator post that @mentions this session or its harness is kept.
832
+ if (topic === all && cfg.session && !mentionsAgent(m.body, cfg))
833
+ continue;
834
+ const operatorThread = m.from === "operator" && m.operatorThread === true && Boolean(m.toSession);
835
+ const operatorBroadcast = m.from === "operator" && topic === all;
836
+ // A screenshot travels as an attachment; local_path appears once this machine has the file cached.
837
+ const attachment = attachmentOf(ev);
838
+ const message = queuedMessage({
839
+ id: ev.id,
840
+ from: addressOf(m.from, senderSession),
841
+ to: m.toSession ? `${m.to}#${m.toSession}` : m.to,
842
+ ts: timestampOf(m),
843
+ body: m.body.slice(0, MAX_BODY_CHARS),
844
+ ...(operatorThread ? { operatorThread: true } : {}),
845
+ ...(operatorBroadcast ? { operatorBroadcast: true } : {}),
846
+ ...(m.from === "operator" && m.system === true ? { system: true } : {}),
847
+ ...(operatorVerified(ev, m) ? { verified: true } : {}),
848
+ ...(typeof m.replyTo === "string" && MESSAGE_ID.test(m.replyTo) ? { replyTo: m.replyTo } : {}),
849
+ ...(RESPOND_STATES.includes(m.state) ? { state: m.state } : {}),
850
+ ...(m.urgent === true ? { urgent: true } : {}),
851
+ ...(m.priority === "fyi" ? { priority: "fyi" } : {}),
852
+ ...(m.expectReply === true ? { expectReply: true } : {}),
853
+ ...(m.from === "operator" && isGithubLogin(m.by) ? { by: m.by } : {}),
854
+ ...(m.from === "operator" && typeof m.mentionedIn === "string" && MENTIONED_IN.test(m.mentionedIn) ? { mentionedIn: m.mentionedIn } : {}),
855
+ ...(m.from === "operator" && typeof m.forSubagent === "string" && SUBAGENT_RUN.test(m.forSubagent) ? { forSubagent: m.forSubagent } : {}),
856
+ ...(m.from === "operator" && typeof m.forTeam === "string" && TEAM_NAME.test(m.forTeam) ? { forTeam: m.forTeam } : {}),
857
+ ...(typeof m.channel === "string" && MESSAGE_ID.test(m.channel) && typeof m.threadId === "string" && THREAD_ID.test(m.threadId) ? { thread: m.threadId } : {}),
858
+ // A screenshot travels as an attachment; local_path appears once this machine has the file cached.
859
+ ...(attachment ? { attachment: localizedAttachment(cfg, attachment) } : {}),
860
+ }, state);
861
+ if (message)
862
+ add(message);
863
+ }
864
+ }
865
+ if (strict && lastError && out.length === 0)
866
+ throw lastError;
867
+ state.seen = [...seen].slice(-SEEN_MAX);
868
+ return out;
869
+ }
870
+ /**
871
+ * Newest `limit` msg envelopes on the project's all topic, oldest first. Read-only: no cursor, no receipts.
872
+ */
873
+ export async function channelHistory(cfg, { limit = HISTORY_DEFAULT } = {}) {
874
+ if (!cfg.enabled)
875
+ throw new Error(`disabled: ${cfg.reason}`);
876
+ const events = await pollCached(cfg, broadcastTopic(cfg.project), "all", undefined, { tailBytes: HISTORY_TAIL_BYTES });
877
+ const out = [];
878
+ for (const ev of events) {
879
+ const m = parseEnvelope(ev.message);
880
+ if (m?.kind !== "msg" || typeof m.body !== "string" || m.to !== "all" || m.toSession !== undefined || !isValidName(m.from))
881
+ continue;
882
+ // An image in history names its cached copy when this machine has one, so a reader never re-downloads it.
883
+ const attachment = attachmentOf(ev);
884
+ out.push({
885
+ id: ev.id,
886
+ from: addressOf(m.from, sessionOf(m)),
887
+ to: "all",
888
+ ts: timestampOf(m),
889
+ body: m.body.slice(0, MAX_BODY_CHARS),
890
+ ...(m.from === "operator" && isGithubLogin(m.by) ? { by: m.by } : {}),
891
+ ...(operatorVerified(ev, m) ? { verified: true } : {}),
892
+ ...(attachment ? { attachment: localizedAttachment(cfg, attachment) } : {}),
893
+ });
894
+ }
895
+ return out.slice(-Math.min(Math.max(Math.trunc(Number(limit)) || HISTORY_DEFAULT, 1), HISTORY_MAX));
896
+ }
897
+ // Ids reserved by a pusher that have not expired yet.
898
+ function liveReserved(state, now) {
899
+ return Object.keys(state.reserved).filter((id) => untilOf(state.reserved[id]) > now);
900
+ }
901
+ // A reservation is a number (an expiry, the dispatcher's) or {until, owner} (a workflow's).
902
+ function untilOf(v) {
903
+ return typeof v === "number" ? v : (v?.until ?? 0);
904
+ }
905
+ function ownerOf(v) {
906
+ return typeof v === "object" && v ? (v.owner ?? null) : null;
907
+ }
908
+ // Runs fn under the file lock; fn runs synchronously inside it, as before the typed move.
909
+ function underLock(file, fn, options) {
910
+ return withLock(file, async () => fn(), options);
911
+ }
912
+ // Runs fn under the inbox lock, retrying once with a longer wait; { locked: false } when both attempts fail.
913
+ async function withInboxLock(file, fn) {
914
+ const first = await underLock(file, fn);
915
+ return first.locked ? first : underLock(file, fn, { waitMs: 5000 });
916
+ }
917
+ /**
918
+ * Reserves messages for one delivery path under the inbox lock, so the waiter's claim and the dispatcher's push cannot
919
+ * both take one. Returns the ids this caller owns; [] when the lock is busy. allowSeen reserves ids already delivered
920
+ * (a redelivery), so the seen list can be trimmed without exposing them.
921
+ */
922
+ export async function reserveDelivery(cfg, ids, { now = Date.now(), ttlMs = RESERVE_MS, allowSeen = false } = {}) {
923
+ const file = statePath(cfg);
924
+ const r = await withInboxLock(file, () => {
925
+ const state = readState(file);
926
+ const taken = new Set([...(allowSeen ? [] : state.seen), ...liveReserved(state, now)]);
927
+ const own = ids.filter((id) => !taken.has(id) && !state.queue?.[id]?.cancelled);
928
+ for (const id of own)
929
+ state.reserved[id] = now + ttlMs;
930
+ writeState(file, state);
931
+ return own;
932
+ });
933
+ return r.locked ? r.value : [];
934
+ }
935
+ /** Drops reservations after a failed push or an expired confirmation, so the waiter and the hooks can take the messages. */
936
+ export async function releaseDelivery(cfg, ids) {
937
+ const file = statePath(cfg);
938
+ await withInboxLock(file, () => {
939
+ const state = readState(file);
940
+ for (const id of ids)
941
+ delete state.reserved[id];
942
+ writeState(file, state);
943
+ });
944
+ }
945
+ /** Marks messages as delivered by another path (the dispatcher), so this session's hooks skip them. */
946
+ export async function markDelivered(cfg, ids) {
947
+ const file = statePath(cfg);
948
+ await withInboxLock(file, () => {
949
+ const state = readState(file);
950
+ state.seen = [...new Set([...state.seen, ...ids])].slice(-SEEN_MAX);
951
+ for (const id of ids)
952
+ delete state.reserved[id];
953
+ writeState(file, state);
954
+ });
955
+ }
956
+ /** Latest status per peer seen in the last `since` window (a bus duration like "12h"). */
957
+ export async function readStatuses(cfg, { since = "24h" } = {}) {
958
+ return latestStatuses(await pollCached(cfg, statusTopic(cfg.project), since));
959
+ }
960
+ /** Latest status per peer or peer#session in a list of status-topic events, oldest first. */
961
+ export function latestStatuses(events, latest = new Map()) {
962
+ for (const ev of events) {
963
+ const m = parseEnvelope(ev.message);
964
+ if (!m || m.kind !== "status" || !isValidName(m.from))
965
+ continue;
966
+ latest.set(addressOf(m.from, sessionOf(m)), {
967
+ event: String(m.event || "").slice(0, 10),
968
+ harness: String(m.harness || "").slice(0, 10),
969
+ ts: String(m.ts || "").slice(0, 40),
970
+ ...(typeof m.parent === "string" && /^[a-z0-9-]{1,24}#[a-f0-9]{16}$/.test(m.parent) ? { parent: m.parent } : {}),
971
+ });
972
+ }
973
+ return latest;
974
+ }
975
+ /**
976
+ * Reserves messages for one workflow owner (its workflow id). The owner re-acquires its own reservations, so a restart
977
+ * resumes them. Resolves {owned, busy}: owned are the ids this owner holds; busy is true when the inbox lock stayed taken.
978
+ */
979
+ export async function reserveOwned(cfg, ids, { owner, now = Date.now(), ttlMs = RESERVE_MS, allowSeen = false }) {
980
+ const file = statePath(cfg);
981
+ const r = await withInboxLock(file, () => {
982
+ const state = readState(file);
983
+ const seen = new Set(allowSeen ? [] : state.seen);
984
+ const own = ids.filter((id) => !seen.has(id) && !state.queue?.[id]?.cancelled && (untilOf(state.reserved[id]) <= now || ownerOf(state.reserved[id]) === owner));
985
+ for (const id of own)
986
+ state.reserved[id] = { until: now + ttlMs, owner };
987
+ writeState(file, state);
988
+ return own;
989
+ });
990
+ return r.locked ? { owned: r.value, busy: false } : { owned: [], busy: true };
991
+ }
992
+ /** Drops this owner's reservations after a failed push or an expired confirmation; another owner's stay. */
993
+ export async function releaseOwned(cfg, ids, owner) {
994
+ const file = statePath(cfg);
995
+ await withInboxLock(file, () => {
996
+ const state = readState(file);
997
+ for (const id of ids)
998
+ if (ownerOf(state.reserved[id]) === owner)
999
+ delete state.reserved[id];
1000
+ writeState(file, state);
1001
+ });
1002
+ }