@temmo/cli 0.0.0 → 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 +112 -1
  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,2937 @@
1
+ import { SEND_CONFIRMATION } from "../lib/send-confirmation.js";
2
+ import { landReviews, mergeReview } from "./land-reviews.js";
3
+ import { HOST_CHECKOUT, LandRefused, deployedField, hostLand } from "../../lib/land.js";
4
+ import { isProjectPaused, PROJECT_PAUSED, setProjectPaused } from "../../lib/project-pause.js";
5
+ import { terminalHasDraft } from "../../lib/terminal-draft.js";
6
+ import { EventType } from "@ag-ui/core";
7
+ import { operatorPrompt, publishMode as publishModeAll } from "../../lib/mode.js";
8
+ import { buildEvent, encodeEnvelope, envelopeToEvent, projectEvent, readWireRecord } from "../../lib/agui.js";
9
+ import { ACTIVITY_BATCH, STREAM_ERROR } from "../lib/ui-events.js";
10
+ import { execFile } from "node:child_process";
11
+ import { mkdirSync, watch } from "node:fs";
12
+ import { basename, isAbsolute, join } from "node:path";
13
+ import { promisify } from "node:util";
14
+ import { buzzes, readAlertLevel, writeAlertLevel } from "../../lib/alerts.js";
15
+ import { MAX_BODY_CHARS, autoDefaults, loadConfig, loadProjects, activityTopic, startDefaultSetting, startPlaceSetting, broadcastTopic, configDir, stateDir, inboxTopic, receiptsTopic, statusTopic, threadTopic, SESSION_LABEL, isGithubLogin, isValidName } from "../../lib/config.js";
16
+ import { ACTIVITY_TYPES } from "../../lib/activity.js";
17
+ import { stripControl } from "../../lib/format.js";
18
+ import { withOperatorToken } from "../../lib/operator-token.js";
19
+ import { ensureApprovalKey, signApproval } from "../../lib/approval-signer.js";
20
+ import { approvalInputHash } from "../../lib/signed-approval.js";
21
+ import { signedSummary } from "../../lib/approval-request.js";
22
+ import { MESSAGE_MAX_BYTES, latestStatuses, changeQueuedMessage, queuedMessage, markUrgent, parseEnvelope, sendMessage } from "../../lib/messaging.js";
23
+ import { ATTACHMENT_MAX_BYTES, imageAttachment } from "../../lib/attachment.js";
24
+ import { IMAGE_FILE, TEXT_FILE, attachmentOf, ensureAttachment, cachedAttachment, readAttachmentFile } from "../../lib/attachment-cache.js";
25
+ import { publish } from "../../lib/messaging.js";
26
+ import { openQuestions, parseQuestionText } from "../../lib/questions.js";
27
+ import { approvalEnd, readReply } from "../../lib/operator.js";
28
+ import { PR_TOOL } from "../../lib/pr-card.js";
29
+ import { disposeSession, listSessions, sessionPlace, worktreeGone } from "../../lib/sessions/registry.js";
30
+ import { readState, statePath } from "../../lib/state.js";
31
+ import { readReceipts } from "../../lib/receipts.js";
32
+ import { controlSession } from "../../lib/sessions/control.js";
33
+ import { interruptSession } from "../../lib/sessions/control.js";
34
+ import { slashCommand } from "../../lib/slash.js";
35
+ import { readContext } from "../../lib/usage.js";
36
+ import { parseCommand } from "../lib/slash-commands.js";
37
+ import { startModes } from "../lib/start-mode.js";
38
+ import { APPROVAL_ID, CLAUDE_SWITCH_MODES, END_REASONS, cleanQuestions, parseChoice, replyDecision } from "../../lib/approvals.js";
39
+ import { START_HARNESSES, availableHarnesses, availablePlaces, claudePermissionFor, defaultStartPlace, openshellHarnesses, openshellRunner, projectRoot, checkPrompt, startSession } from "../../lib/sessions/launch.js";
40
+ import { findExecutable } from "../../lib/sessions/scope.js";
41
+ import { codeModeDefault } from "../../lib/code-mode.js";
42
+ import { cleanName } from "../../lib/sessions/registry.js";
43
+ import { REF_NAME_MAX, gitRunner, listBranches, listWorktrees, parseWorktreeList, pickedWorktree, prHead, refInputError, untrackedDiff } from "../../lib/sessions/git-refs.js";
44
+ import { listModels } from "../../lib/models.js";
45
+ import { LIMIT_TOOL, chooseLimit, limitEndMessage, skipLimit } from "../../lib/limit-alert.js";
46
+ import { SANDBOX_CHANGE_TOOL, announceChangeDecision, applySandboxChange, denySandboxChange, sandboxCardSummary } from "../../lib/sandbox-proposal.js";
47
+ import { limitEndNotice } from "../../lib/start-limit.js";
48
+ import { closedProjectNames, readProjectsFile, removeProject, setProjectClosed } from "../../lib/catalog/projects.js";
49
+ import { createTeam } from "../../lib/catalog/roster.js";
50
+ import { deleteTeam, listTeams, teamTask } from "../../lib/catalog/teams.js";
51
+ import { clearFields, modelFields, sessionHistory } from "../../lib/session-events.js";
52
+ import { compactionFields } from "../../lib/compaction.js";
53
+ import { checkTeamText, copyPattern, listPatterns, removableNames, removePattern, savePattern, saveTeamText, teamTemplates, teamTextOf } from "../../lib/catalog/patterns.js";
54
+ import { authorModel, authorTeam, saveAuthoredTeam } from "../../lib/catalog/author.js";
55
+ import { listOwned, readOwned, setNextPermission } from "../../lib/sessions/registry.js";
56
+ import { requestTeamPermission } from "../../lib/team-permission.js";
57
+ import { builderAssignment, recoverBuilder, stoppedBuilder } from "../../lib/builder.js";
58
+ import { REVIEW_ACTIONS, STATUSES, TaskNotFoundError, openTasks } from "../../lib/tasks.js";
59
+ import { priorityOf } from "../../lib/task-order.js";
60
+ import { mentions, mentionedNames, mentionedTeams, startOnlyMentions, messageDestinations } from "../lib/message-routing.js";
61
+ import { taskTags } from "../lib/task-tags.js";
62
+ import { shippedTasks } from "./shipped.js";
63
+ import { taskBoard } from "./task-board.js";
64
+ import { advanceRun, listRuns, rolesByAddress, startRun } from "../../lib/pattern-runs.js";
65
+ import { formatTeamOrchestrator } from "../../lib/format.js";
66
+ import { activityRows, groupSubagents, summarize, turnStarts } from "../lib/activity-rows.js";
67
+ import { childRuns } from "../lib/child-subagents.js";
68
+ import { fallbackName, sessionCounts, shownOnline, visibleWake, waitingOn } from "../lib/session-state.js";
69
+ import { createHostedUi } from "./hosted.js";
70
+ import { createAuth } from "./auth.js";
71
+ import { createHub } from "./hub.js";
72
+ import { sendToThread } from "../../lib/thread-channels.js";
73
+ import { readerCopy } from "../../lib/thread-listening.js";
74
+ import { createPush, notice } from "./push.js";
75
+ import { createDispatcher } from "./dispatch.js";
76
+ import { runnerClient, runnerUp } from "../../runner/client.js";
77
+ import { runnerSocket } from "../../runner/control.js";
78
+ import { CLAUDE_CLI_MODES, runnerModeOfClaude } from "../../runner/contract.js";
79
+ import { readScheduleRuns, readSchedules } from "./schedules.js";
80
+ import { rankLessons, readProjectLessons } from "../../lib/lessons.js";
81
+ import { quotedReply, splitQuotedReply, usableReplyId } from "../lib/reply-quote.js";
82
+ import { answerMessage, answerText, terminalMessages } from "../lib/operator-messages.js";
83
+ import { A2UI_ACTIVITY, choiceAnswers, surfaceAnswer, surfaceOf } from "../lib/a2ui.js";
84
+ import { prAnswer, prSurfaceOf } from "../lib/a2ui-pr.js";
85
+ import { runTerminalUi } from "./run-terminal.js";
86
+ import { projectThreads } from "./threads.js";
87
+ import { THREAD_ID } from "../../lib/threads.js";
88
+ export { mentionedNames, mentionedTeams, startOnlyMentions };
89
+ const INSTANCE = Symbol.for("temmo.ui");
90
+ const shared = globalThis;
91
+ const ACTIONS = ["history", "messages", "send", "reply", "nudge", "queue", "compact", "model", "wake", "afk", "alerts", "close", "reopen", "delete", "approve", "a2ui", "start", "models", "dispose", "team", "interrupt", "end", "command", "pattern", "decide", "move-task", "continue-builder", "recover-builder", "project-pause", "land-reviews", "land", "create-pr", "review", "skip", "request-outcome", "approve-outcome", "accept-outcome", "thread"];
92
+ const HOSTED_ACTIONS = new Set(["history", "messages", "send", "reply", "afk", "approve", "a2ui", "skip"]);
93
+ const START_GAP_MS = 10_000;
94
+ const REFRESH_MS = 10_000;
95
+ const PARENT = /^[a-z0-9-]{1,24}#[a-f0-9]{16}$/;
96
+ // Bases tried in order when a thread names none, or its own no longer resolves.
97
+ const THREAD_BASES = ["origin/HEAD", "main"];
98
+ const STARTABLE_CACHE_MS = 60_000;
99
+ const ANSWER_MAX_CHARS = 2000;
100
+ const MODES = ["on", "off", "quiet"];
101
+ const MAX_REQUEST_BYTES = 32768;
102
+ const ONLINE_MS = 30 * 60_000;
103
+ const KEEPALIVE_MS = 25_000;
104
+ // Finished subagent runs the sidebar lists per session.
105
+ const FINISHED_RUNS = 10;
106
+ const PUSH_DELAY_MS = 25;
107
+ // The next flush waits this many times the last flush's cost, so snapshot building takes at most a fifth of the event loop.
108
+ const PUSH_COST_FACTOR = 4;
109
+ const MAX_MESSAGES = 100;
110
+ // Milestone posts the Recent progress view lists, newest first, across projects.
111
+ const MAX_PROGRESS = 50;
112
+ const SCHEDULE_NAME = /^[a-z0-9-]{1,40}$/;
113
+ // Characters of the replied message sent with a reply; the browser shows the first 80.
114
+ const QUOTE_MAX = 200;
115
+ const IMPORTANT = /^IMPORTANT, the agent waits for this answer: /;
116
+ const SKIPPED_PROGRESS = "Skipped by operator";
117
+ // The hub keeps the newest 500 events per topic; 3 MB of cached history covers 500 full 4 KB activity envelopes.
118
+ const ACTIVITY_TAIL_BYTES = 3 * 1024 * 1024;
119
+ const ACTIVITY_TEXT_MAX = 8192;
120
+ const ACTIVITY_NAME_MAX = 128;
121
+ const RECIPIENTS_MAX = 5000;
122
+ // Notify only for items this recent that still wait on the operator; older history was seen or has closed.
123
+ const NOTIFY_RECENT_MS = 15 * 60_000;
124
+ const NOTIFY_RETRY_MS = 30_000;
125
+ const IMPORTANT_PREFIX = "IMPORTANT, the agent waits for this answer: ";
126
+ const PUSH_ACTIONS = ["key", "subscribe", "test"];
127
+ // A review diff is plain text in one response; past this it is a download, not a phone view.
128
+ const DIFF_MAX_BYTES = 4 * 1024 * 1024;
129
+ // Largest untracked file the thread diff shows as an addition.
130
+ const UNTRACKED_FILE_BYTES = 512 * 1024;
131
+ const REF_KINDS = ["branches", "worktrees"];
132
+ const PR_QUERY = /^#([1-9][0-9]{0,6})$/;
133
+ // A question or approval reply the UI sent for a signed-in user names them in its reply title.
134
+ const REPLY_TITLE = /^Reply from operator \(([^)]+)\)$/;
135
+ const encoder = new TextEncoder();
136
+ const runFile = promisify(execFile);
137
+ // A channel copy's post id (lib/messaging.ts MESSAGE_ID).
138
+ const CHANNEL_POST_ID = /^[a-zA-Z0-9-]{1,64}$/;
139
+ const peerOf = (address) => String(address || "").split("#")[0];
140
+ const replyTitle = (cfg, by) => "Reply from " + cfg.peer + (by ? ` (${by})` : "");
141
+ const replyBy = (event) => { const by = REPLY_TITLE.exec(event.title || "")?.[1]; return isGithubLogin(by) ? by : undefined; };
142
+ // Operator AFK mode for every project's agents, by the signed-in user if any; throws when any project's publish fails.
143
+ export async function publishMode(cfgs, mode, by) {
144
+ const failed = (await publishModeAll(cfgs, mode, by ? { by } : {})).filter(r => !r.ok);
145
+ if (failed.length)
146
+ throw new Error(`Mode publish failed for ${failed.map(r => r.project).join(", ")}`);
147
+ }
148
+ // Latest operator mode envelope in the given events; none means off.
149
+ function latestMode(events) {
150
+ let latest = { mode: "off", at: 0 };
151
+ for (const event of events) {
152
+ const envelope = parseEnvelope(event.message);
153
+ if (envelope?.kind !== "mode" || envelope.from !== "operator" || !MODES.includes(envelope.mode))
154
+ continue;
155
+ const at = Number(envelope.ts) || event.time * 1000;
156
+ if (at >= latest.at)
157
+ latest = { mode: envelope.mode, at };
158
+ }
159
+ return latest;
160
+ }
161
+ const FILE_NAME = IMAGE_FILE;
162
+ const activityCache = new WeakMap();
163
+ const cleanText = (value, max) => typeof value === "string" && value ? stripControl(value).slice(0, max) : undefined;
164
+ // One activity row per valid activity envelope; anything else on the topic is dropped. Cached per event object.
165
+ function activityItem(event) {
166
+ if (activityCache.has(event))
167
+ return activityCache.get(event).item;
168
+ const record = readWireRecord(event.message);
169
+ const original = record && record.v !== 1 ? record : null;
170
+ const e = original ? projectEvent(original) : record;
171
+ let item = null;
172
+ if (e?.kind === "activity" && isValidName(e.from) && typeof e.session === "string" && SESSION_LABEL.test(e.session) && ACTIVITY_TYPES.includes(e.type)) {
173
+ item = { id: event.id, time: event.time, agent: e.from + "#" + e.session, harness: cleanText(e.harness, 10) || "other", type: e.type };
174
+ for (const [key, max] of [["tool", ACTIVITY_NAME_MAX], ["callId", ACTIVITY_NAME_MAX], ["input", ACTIVITY_TEXT_MAX], ["output", ACTIVITY_TEXT_MAX]]) {
175
+ const value = cleanText(e[key], max);
176
+ if (value)
177
+ item[key] = value;
178
+ }
179
+ if (e.type === "prompt" && e.system === true)
180
+ item.system = true;
181
+ const compaction = e.compaction ? compactionFields(e.compaction) : null;
182
+ if (compaction)
183
+ item.compaction = compaction;
184
+ if (e.clear)
185
+ item.clear = clearFields(e.clear);
186
+ const modelSwitch = e.modelSwitch ? modelFields(e.modelSwitch) : null;
187
+ if (modelSwitch)
188
+ item.modelSwitch = modelSwitch;
189
+ const attachment = attachmentOf(event, { text: true });
190
+ if (attachment)
191
+ item.attachment = attachment;
192
+ // A subagent's rows carry its run; the envelope's agent becomes subagent because agent already names the session.
193
+ const run = cleanText(e.agent?.id, ACTIVITY_NAME_MAX);
194
+ if (run)
195
+ item.subagent = { id: run, type: cleanText(e.agent.type, ACTIVITY_NAME_MAX) || "" };
196
+ }
197
+ activityCache.set(event, { item, original });
198
+ return item;
199
+ }
200
+ function activityFrame(source) {
201
+ const cached = activityCache.get(source);
202
+ if (cached.frame)
203
+ return cached.frame;
204
+ const { item: row, original } = cached;
205
+ const { id, time, agent, subagent, attachment, ...fields } = row;
206
+ const [from, session] = agent.split("#");
207
+ const runId = original?.runId ?? original?.metadata?.aiCollab?.runId;
208
+ const run = typeof runId === "string" && {
209
+ type: original.type, runId, parentRunId: original.parentRunId, outcome: original.outcome, input: original.input,
210
+ };
211
+ const event = envelopeToEvent({
212
+ v: 1, kind: "activity", from, session, ts: time * 1000, ...fields,
213
+ ...(subagent ? { agent: subagent } : {}),
214
+ }, { id: original?.type === EventType.TOOL_CALL_RESULT ? original.messageId : id, run });
215
+ cached.frame = { ...event, metadata: { ...event.metadata, temmoUi: { id, time, attachment } } };
216
+ return cached.frame;
217
+ }
218
+ // One chat entry per bus event; status and alert envelopes are skipped.
219
+ // Decoded once per bus event: the thread feed decodes the project topic once per thread session, and every view re-reads it.
220
+ const entryCache = new WeakMap();
221
+ function entry(event) {
222
+ if (!event || typeof event !== "object")
223
+ return decodeEntry(event);
224
+ if (!entryCache.has(event))
225
+ entryCache.set(event, Object.freeze(decodeEntry(event)));
226
+ return entryCache.get(event);
227
+ }
228
+ function decodeEntry(event) {
229
+ const item = baseEntry(event);
230
+ const attachment = item && attachmentOf(event);
231
+ return attachment ? { ...item, attachment } : item;
232
+ }
233
+ function baseEntry(event) {
234
+ const { message, id, time } = event;
235
+ const envelope = parseEnvelope(message);
236
+ if (!envelope || envelope.kind === "question") {
237
+ const question = parseQuestionText(envelope || message);
238
+ if (question)
239
+ return { id, time, kind: "Question", sender: question.sender, from: question.sender, body: question.body, question: question.id };
240
+ }
241
+ if (envelope) {
242
+ if (envelope.kind === "approval" || envelope.kind === "approval-view")
243
+ return approvalEntry(event, envelope);
244
+ if (envelope.kind !== "msg" || typeof envelope.body !== "string")
245
+ return null;
246
+ // System messages can use the operator address for reply routing.
247
+ const system = envelope.system === true;
248
+ const sender = system ? "system" : envelope.session ? `${envelope.from}#${envelope.session}` : envelope.from;
249
+ const to = envelope.toSession ? `${envelope.to}#${envelope.toSession}` : envelope.to;
250
+ const by = !system && envelope.from === "operator" && isGithubLogin(envelope.by) ? { by: envelope.by } : {};
251
+ // A reply to a message names it as replyOf; replyTo stays the answer link to a question.
252
+ return { id, time, kind: "Message", sender, from: sender, to, body: envelope.body, thread: envelope.operatorThread === true, ...(typeof envelope.channel === "string" && CHANNEL_POST_ID.test(envelope.channel) ? { channelOf: envelope.channel } : {}), ...(system ? { system: true } : {}), ...(envelope.urgent === true ? { urgent: true } : {}), ...(envelope.startOnly === true ? { startOnly: true } : {}), ...(typeof envelope.replyTo === "string" && envelope.replyTo ? { replyOf: envelope.replyTo } : {}), ...(typeof envelope.mentionedIn === "string" ? { mentionedIn: envelope.mentionedIn } : {}), ...by };
253
+ }
254
+ const reply = readReply(event);
255
+ const by = replyBy(event);
256
+ if (reply && !reply.skipped)
257
+ return { id, time, kind: "Reply", sender: "ntfy", from: "ntfy", body: reply.answer, question: reply.id, ...(by ? { by } : {}) };
258
+ return { id, time, kind: "Message", sender: "ntfy", from: "ntfy", body: message };
259
+ }
260
+ // A permission request or AskUserQuestion choice a hook is waiting on; its state comes from replies and its end envelope.
261
+ function approvalEntry({ id, time }, e) {
262
+ if (!isValidName(e.from) || !APPROVAL_ID.test(e.id) || (e.session !== undefined && !SESSION_LABEL.test(e.session)))
263
+ return null;
264
+ const sender = e.session ? `${e.from}#${e.session}` : e.from;
265
+ // A create-PR request is approval-shaped on the wire but is not a permission ask: the tap runs host-side (openPrRequest).
266
+ if (e.tool === PR_TOOL && e.questions === undefined) {
267
+ const note = cleanText(e.summary, 300) || "";
268
+ return { id, time, kind: "CreatePr", sender, from: sender, body: note, createPr: { id: e.id, harness: cleanText(e.harness, 10) || "other", note } };
269
+ }
270
+ // A sandbox change card shows the summary derived from the change the tap applies, never the agent's own summary text.
271
+ if (e.tool === SANDBOX_CHANGE_TOOL) {
272
+ const summary = e.kind === "approval" && e.questions === undefined ? sandboxCardSummary(e.change, e.reason) : null;
273
+ if (!summary)
274
+ return null;
275
+ e = { ...e, summary };
276
+ }
277
+ const questions = e.questions === undefined ? undefined : cleanQuestions(e.questions);
278
+ if (questions === null)
279
+ return null;
280
+ // A signed-approval card (lib/approval-request.ts): the UI hashes and summarises the exact input itself, never trusting the agent's summary.
281
+ if (e.signed !== undefined) {
282
+ const input = e.signed?.input;
283
+ if (questions || e.kind !== "approval" || !e.session || typeof e.tool !== "string" || cleanText(e.tool, ACTIVITY_NAME_MAX) !== e.tool
284
+ || !input || typeof input !== "object" || Array.isArray(input))
285
+ return null;
286
+ e = { ...e, summary: signedSummary(e.reason, input), signedFor: { session: e.session, inputHash: approvalInputHash(e.tool, input) } };
287
+ }
288
+ const approval = {
289
+ id: e.id, harness: cleanText(e.harness, 10) || "other", tool: cleanText(e.tool, ACTIVITY_NAME_MAX) || "tool",
290
+ summary: cleanText(e.summary, 300) || "", expiresAt: Number.isSafeInteger(e.expiresAt) ? e.expiresAt : 0,
291
+ ...(questions ? { questions } : {}), ...(e.kind === "approval-view" ? { terminal: true } : {}), ...(e.owned === true ? { owned: true } : {}),
292
+ ...(typeof e.switchTo === "string" && CLAUDE_SWITCH_MODES.has(e.switchTo) ? { switchTo: e.switchTo } : {}),
293
+ ...(e.signedFor ? { signed: e.signedFor } : {}),
294
+ };
295
+ return { id, time, kind: "Approval", sender, from: sender, body: approval.summary, approval };
296
+ }
297
+ // Outcome of each approval and the answers to each question (with who sent them), from the broadcast topic's replies and end envelopes.
298
+ function outcomes(events) {
299
+ const ends = new Map();
300
+ const endMeta = new Map();
301
+ const replies = new Map();
302
+ const senders = new Map();
303
+ for (const event of events) {
304
+ const match = readReply(event);
305
+ if (match && !match.skipped) {
306
+ if (!replies.has(match.id)) {
307
+ replies.set(match.id, []);
308
+ senders.set(match.id, []);
309
+ }
310
+ replies.get(match.id).push(match.answer);
311
+ senders.get(match.id).push(replyBy(event));
312
+ continue;
313
+ }
314
+ const e = parseEnvelope(event.message);
315
+ if (e?.kind === "approval-end" && APPROVAL_ID.test(e.id) && END_REASONS.includes(e.reason) && !ends.has(e.id)) {
316
+ ends.set(e.id, e.reason);
317
+ endMeta.set(e.id, e);
318
+ }
319
+ }
320
+ return { ends, endMeta, replies, senders };
321
+ }
322
+ // The base, branch and worktreePath a start names; empty values count as unnamed.
323
+ function pickOf(given) {
324
+ return Object.fromEntries(Object.entries(given).filter(([, value]) => value !== undefined && value !== null && value !== ""));
325
+ }
326
+ function reject(status, message) {
327
+ throw Object.assign(new Error(message), { status });
328
+ }
329
+ function json(status, value) {
330
+ return Response.json(value, { status, headers: { "Cache-Control": "no-store" } });
331
+ }
332
+ function sentStream(confirmed, complete) {
333
+ const encoder = new TextEncoder();
334
+ const line = (value) => encoder.encode(JSON.stringify(value) + "\n");
335
+ let canceled = false;
336
+ const body = new ReadableStream({
337
+ start(controller) {
338
+ controller.enqueue(line(confirmed));
339
+ void complete().then((result) => {
340
+ if (canceled)
341
+ return;
342
+ controller.enqueue(line(result));
343
+ controller.close();
344
+ });
345
+ },
346
+ cancel() { canceled = true; },
347
+ });
348
+ return new Response(body, {
349
+ status: 201,
350
+ headers: { "Content-Type": SEND_CONFIRMATION, "Cache-Control": "no-store, no-transform", "X-Accel-Buffering": "no" },
351
+ });
352
+ }
353
+ function failure(err) {
354
+ const status = err.status || ([401, 403].includes(err.ntfyStatus) ? 403 : err.ntfyStatus === 429 ? 429 : 502);
355
+ const message = err.status ? err.message : status === 403 ? "The bus token cannot access that channel"
356
+ : status === 429 ? "The messaging service is rate limiting requests; try again shortly" : "Messaging service unavailable";
357
+ return { status, message };
358
+ }
359
+ async function readBody(request, limit) {
360
+ if (!request.body)
361
+ reject(400, "Expected a request body");
362
+ const chunks = [];
363
+ let size = 0;
364
+ for await (const part of request.body) {
365
+ size += part.length;
366
+ if (size > limit)
367
+ reject(413, "Message too large");
368
+ chunks.push(part);
369
+ }
370
+ return Buffer.concat(chunks);
371
+ }
372
+ function jsonPayload(text) {
373
+ try {
374
+ const value = JSON.parse(text);
375
+ if (value && typeof value === "object" && !Array.isArray(value))
376
+ return value;
377
+ }
378
+ catch { }
379
+ reject(400, "Expected a JSON object");
380
+ }
381
+ async function payload(request) {
382
+ if (!request.body)
383
+ reject(400, "Expected a JSON object");
384
+ return jsonPayload((await readBody(request, MAX_REQUEST_BYTES)).toString());
385
+ }
386
+ async function imagePayload(request) {
387
+ const bytes = await readBody(request, ATTACHMENT_MAX_BYTES + MAX_REQUEST_BYTES);
388
+ let form;
389
+ try {
390
+ form = await new Response(bytes, { headers: { "content-type": String(request.headers.get("content-type")) } }).formData();
391
+ }
392
+ catch {
393
+ reject(400, "Invalid image upload");
394
+ }
395
+ const metadata = form.get("message");
396
+ const file = form.get("image");
397
+ if (form.getAll("message").length !== 1 || typeof metadata !== "string" || Buffer.byteLength(metadata) > MAX_REQUEST_BYTES
398
+ || form.getAll("image").length !== 1 || !(file instanceof File))
399
+ reject(400, "Expected one image and its message");
400
+ if (file.size > ATTACHMENT_MAX_BYTES)
401
+ reject(413, "Image is over 15 MB");
402
+ const input = jsonPayload(metadata);
403
+ try {
404
+ return { input, attachment: imageAttachment(file.name, Buffer.from(await file.arrayBuffer())) };
405
+ }
406
+ catch (error) {
407
+ reject(400, error.message);
408
+ }
409
+ }
410
+ // A Home card's context meter: the harness's last token count and window, only when a token count is recorded.
411
+ function cardContext(cfg, agent) {
412
+ const { tokens, window } = readContext({ stateDir: cfg.stateDir, project: cfg.project, peer: agent.peer, session: agent.session });
413
+ return tokens === null ? {} : { context: { tokens, window } };
414
+ }
415
+ function recipient(cfg, target, exact = false) {
416
+ if (typeof target !== "string")
417
+ reject(400, "Select a recipient");
418
+ const [role, session, ...extra] = target.split("#");
419
+ if (target === "all" && !exact)
420
+ return role;
421
+ if (!isValidName(role) || role === "all" || extra.length ||
422
+ ((session !== undefined || exact) && (typeof session !== "string" || !SESSION_LABEL.test(session))) ||
423
+ (cfg.peers.length && !cfg.peers.includes(role)))
424
+ reject(400, "Invalid recipient");
425
+ return role;
426
+ }
427
+ // CSRF guard for state-changing requests: the browser must send the UI's own origin.
428
+ export function assertSameOrigin(request, allowedOrigin) {
429
+ const origin = request.headers.get("origin");
430
+ const site = request.headers.get("sec-fetch-site");
431
+ const host = request.headers.get("host") || new URL(request.url).host;
432
+ const local = /^127\.0\.0\.1(:\d+)?$/.test(host);
433
+ const fromUi = (allowedOrigin && origin === allowedOrigin) || (local && origin === "http://" + host);
434
+ if ((site && site !== "same-origin") || !fromUi)
435
+ reject(403, "Same-origin request required");
436
+ }
437
+ // The project's task backend, or null when its projects.json "tasks" setting names none.
438
+ function tasksOf(name, env) {
439
+ try {
440
+ return openTasks(name, env);
441
+ }
442
+ catch {
443
+ return null;
444
+ }
445
+ }
446
+ /**
447
+ * Compacts through the runner when it owns the session: its adapters run the harness's own trigger (Claude /compact,
448
+ * Codex thread/compact/start, OpenCode session.compact). Resolves null when the runner does not own the address, so the
449
+ * caller falls back to lib/sessions/control.ts (a terminal session, or a session outside the runner). `runner` is the
450
+ * runnerClient factory, injected in tests.
451
+ */
452
+ async function runnerCompact(address, runner, env) {
453
+ const r = await runner({ socket: runnerSocket(env) }).compact(address).catch(() => null);
454
+ if (!r || ![200, 409].includes(r.status) || !r.body)
455
+ return null;
456
+ return r.status === 200 ? r.body : { status: "failed", detail: r.body.error || "The runner refused the compaction" };
457
+ }
458
+ // The status events that keep a session online: a turn started or an AFK hold, reported within ONLINE_MS.
459
+ function statusOnline(state) {
460
+ return Boolean(state) && (state.event === "start" || state.event === "hold") && Date.now() - (Date.parse(state.ts) || 0) < ONLINE_MS;
461
+ }
462
+ // The runner's owned record for a session address, or null when the runner does not own that session.
463
+ function ownedRecord(cfg, address) {
464
+ const owned = readOwned(cfg, String(address).split("#")[1] ?? "");
465
+ return owned?.address === address ? owned : null;
466
+ }
467
+ // An open runner-owned permission request with its session's mode, place and address, so the card can offer /mode.
468
+ function withModeControl(cfg, address, approval) {
469
+ if (!approval.owned || approval.questions || approval.state !== "pending")
470
+ return approval;
471
+ const owned = ownedRecord(cfg, address);
472
+ if (!owned || owned.status === "ended" || typeof owned.permissionMode !== "string")
473
+ return approval;
474
+ return { ...approval, modeControl: { address, current: owned.permissionMode, place: typeof owned.place === "string" ? owned.place : "folder" } };
475
+ }
476
+ // True when the runner holds this session (starting, running or idle-waiting); the runner delivers its messages itself.
477
+ function runnerHeld(cfg, target) {
478
+ const owned = ownedRecord(cfg, target);
479
+ return Boolean(owned) && owned.status !== "ended";
480
+ }
481
+ // A reply whose id the server cannot accept goes out as plain text quoting the original's first and last words.
482
+ function replyQuote(replyTo, body, quote) {
483
+ if (usableReplyId(replyTo))
484
+ return { replyTo };
485
+ return { quoted: true, body: quotedReply(body, originalOf(quote)) };
486
+ }
487
+ // The reply composer's copy of the original, {sender, body}; the server sends it as text, never as a link.
488
+ function originalOf(quote) {
489
+ const source = quote && typeof quote === "object" && !Array.isArray(quote) ? quote : null;
490
+ if (!source)
491
+ return {};
492
+ return { sender: typeof source.sender === "string" ? source.sender : "", body: typeof source.body === "string" ? source.body : "" };
493
+ }
494
+ export function createUi({ cfg, projects: configs = cfg ? [cfg] : [], allowedOrigin = "", control = controlSession, interrupt = interruptSession, setMode = publishMode, env = process.env, start: launch = startSession, runnerStarts = false, models = listModels, push: notifier = null, auth = null, runner = runnerClient, hasDraft = terminalHasDraft, hosted = false, landingCheckout = HOST_CHECKOUT, runMergeReview = mergeReview, land = hostLand, threadClient: threadClientOf }) {
495
+ if (!configs.length)
496
+ throw new Error("No temmo project is configured");
497
+ for (const item of configs)
498
+ if (!item.enabled)
499
+ throw new Error(item.reason);
500
+ if (allowedOrigin && (!allowedOrigin.startsWith("https://") || new URL(allowedOrigin).origin !== allowedOrigin)) {
501
+ throw new Error("TEMMO_UI_ORIGIN must be a single HTTPS origin without a trailing slash");
502
+ }
503
+ const clients = new Set();
504
+ const hubs = new Map();
505
+ const known = new Set();
506
+ // Projects deleted in this process; they stay hidden until the next start.
507
+ const removed = new Set();
508
+ // Closed or deleted projects: hidden from the UI and silent in notifications.
509
+ const hiddenProjects = () => new Set([...closedProjectNames(env), ...removed]);
510
+ const projects = new Map();
511
+ let pushTimer = null;
512
+ // Milliseconds the last flush took; a busy bus then cannot keep the event loop building snapshots.
513
+ let pushCost = 0;
514
+ let lastStartAt = 0;
515
+ let closed = false;
516
+ let landing = { running: false, receipts: [] };
517
+ const start = launch === startSession ? startSession : async (cfg, options) => isProjectPaused(cfg) ? { status: "failed", detail: PROJECT_PAUSED } : launch(cfg, options);
518
+ function broadcast() {
519
+ if (pushTimer)
520
+ return;
521
+ pushTimer = setTimeout(() => {
522
+ pushTimer = null;
523
+ const started = Date.now();
524
+ // Clients on the same view share one snapshot per flush: building it is the server's costliest step.
525
+ const views = new Map();
526
+ for (const client of clients)
527
+ if (client.ready)
528
+ push(client, views);
529
+ pushCost = Date.now() - started;
530
+ }, Math.max(PUSH_DELAY_MS, pushCost * PUSH_COST_FACTOR));
531
+ pushTimer.unref?.();
532
+ }
533
+ const runTerminal = runTerminalUi({ env, hosted, broadcast, notify: (project, request) => notifier && buzzes(readAlertLevel(env), "question")
534
+ && notifier.notify(project + ":" + request.id, notice({ project, kind: "approval", id: request.id, sender: request.session, tool: "run in terminal", text: request.reason, important: true })).catch(() => { }) });
535
+ // Adds a project once; a hub new to this instance gets its listener, and push keeps its topics open.
536
+ function addProject(item) {
537
+ if (projects.has(item.project) || closed)
538
+ return false;
539
+ // Projects on the same bus URL and token share one hub, hence one streaming subscription.
540
+ const key = JSON.stringify([item.url, item.token]);
541
+ if (!hubs.has(key)) {
542
+ const hub = createHub(item, { keep: name => known.has(name) });
543
+ hubs.set(key, hub);
544
+ hub.listen((name, events) => {
545
+ for (const project of projects.values()) {
546
+ if (project.hub !== hub)
547
+ continue;
548
+ if (name === project.status)
549
+ latestStatuses(events, project.statuses);
550
+ if (name === project.receipts)
551
+ readReceipts(events, project.reads);
552
+ // A first prompt names its thread before any set_identity (docs/threads.md "Naming").
553
+ if (name === project.activity && events.some((event) => activityItem(event)?.type === "prompt"))
554
+ project.threads?.sync();
555
+ if (notifier)
556
+ notifyActions(project, name, events);
557
+ }
558
+ broadcast();
559
+ });
560
+ }
561
+ const registry = join(item.stateDir, item.project, "registry");
562
+ mkdirSync(registry, { recursive: true, mode: 0o700 });
563
+ // A registry change may be a new session: it gets a thread at the next sync (docs/threads.md).
564
+ let named = null;
565
+ // First prompts name a thread until its lead sets an activity line (docs/threads.md "Naming").
566
+ const threads = hosted ? null : projectThreads(item, { env, broadcast, prompts: () => named ? firstPrompts(named) : new Map(), ...(threadClientOf ? { client: threadClientOf(item) } : {}) });
567
+ const watcher = watch(registry, () => { threads?.sync(); broadcast(); });
568
+ watcher.unref();
569
+ threads?.sync();
570
+ // Task edits from the CLI or an agent reach open streams through the backend's watch.
571
+ const tasks = hosted ? null : tasksOf(item.project, env);
572
+ const unwatchTasks = tasks ? tasks.watch(broadcast) : () => { };
573
+ runTerminal.watch(item);
574
+ const project = {
575
+ cfg: item, hub: hubs.get(key), watcher, tasks, unwatchTasks, threads,
576
+ operator: { ...item, peer: "operator", session: "" },
577
+ topic: broadcastTopic(item.project), status: statusTopic(item.project), activity: activityTopic(item.project),
578
+ receipts: receiptsTopic(item.project),
579
+ inboxes: new Map(item.peers.map((peer) => [peer, inboxTopic(item.project, peer)])),
580
+ wakes: new Map(), statuses: new Map(), reads: new Map(), recipients: new Map(),
581
+ };
582
+ for (const name of [project.topic, project.status, project.activity, project.receipts, ...project.inboxes.values()])
583
+ known.add(name);
584
+ projects.set(item.project, project);
585
+ named = project;
586
+ // Archive incoming events even while every browser tab is closed.
587
+ const open = (name) => project.hub.open(name, name === project.activity ? { tailBytes: ACTIVITY_TAIL_BYTES } : undefined).catch(() => {
588
+ if (!closed)
589
+ setTimeout(() => open(name), NOTIFY_RETRY_MS).unref?.();
590
+ });
591
+ for (const name of [project.topic, project.status, project.activity, project.receipts, ...project.inboxes.values()])
592
+ open(name);
593
+ broadcast();
594
+ return true;
595
+ }
596
+ for (const item of configs)
597
+ addProject(item);
598
+ const fallback = projects.values().next().value;
599
+ // New approvals, choice cards, questions, and direct messages to the operator become one push each.
600
+ function notifyActions(project, topic, added) {
601
+ const name = project.cfg.project;
602
+ if (hiddenProjects().has(name))
603
+ return;
604
+ const fresh = added.filter((event) => Date.now() - event.time * 1000 < NOTIFY_RECENT_MS);
605
+ // The phone alert level decides which pushes go out; the message itself stays in the chat.
606
+ const send = (id, fields) => {
607
+ if (!buzzes(readAlertLevel(env), fields.kind === "message" ? "direct" : "question"))
608
+ return;
609
+ notifier.notify(name + ":" + id, notice({ project: name, id, ...fields })).catch(() => { });
610
+ };
611
+ if (topic === project.topic) {
612
+ const { ends, replies } = outcomes(project.hub.events(topic));
613
+ for (const event of fresh) {
614
+ const item = baseEntry(event);
615
+ if (item?.kind === "Approval") {
616
+ const { id, harness, tool, summary, questions, expiresAt, terminal } = item.approval;
617
+ // A view-only card (AFK off) is answered at the terminal, so it sends no push.
618
+ if (terminal || ends.has(id) || replies.has(id) || (expiresAt && expiresAt < Date.now()))
619
+ continue;
620
+ send(id, questions ? { kind: "choice", sender: item.sender, harness, text: questions[0].question, important: true }
621
+ : { kind: "approval", sender: item.sender, harness, tool, text: summary, important: true });
622
+ }
623
+ else if (item?.kind === "CreatePr" && !ends.has(item.createPr.id)) {
624
+ send(item.createPr.id, { kind: "approval", sender: item.sender, harness: item.createPr.harness, tool: "create_pr", text: item.createPr.note || "Open a pull request", important: true });
625
+ }
626
+ else if (item?.kind === "Question" && !replies.has(item.question) && !ends.has(item.question)) {
627
+ const important = item.body.startsWith(IMPORTANT_PREFIX);
628
+ send(item.question, { kind: "question", sender: item.sender, text: important ? item.body.slice(IMPORTANT_PREFIX.length) : item.body, important });
629
+ }
630
+ }
631
+ }
632
+ else if ([...project.inboxes.values()].includes(topic)) {
633
+ for (const event of fresh) {
634
+ const item = baseEntry(event);
635
+ // A system message is temmo's own machinery, not the operator's words, so it sends no phone push.
636
+ if (item?.kind === "Message" && item.to === "operator" && item.thread && item.from !== "operator" && !item.system)
637
+ send(event.id, { kind: "message", sender: item.from, text: item.body });
638
+ }
639
+ }
640
+ }
641
+ function projectFor(name) {
642
+ if (name === undefined || name === null || name === "")
643
+ return fallback;
644
+ if (!projects.has(name))
645
+ reject(hosted ? 404 : 400, "Unknown project");
646
+ return projects.get(name);
647
+ }
648
+ // @pattern in any chat starts a run of the saved pattern with the text after the tag as its task.
649
+ async function routePatternMentions(project, body) {
650
+ const { cfg } = project;
651
+ const patterns = listPatterns(cfg, env);
652
+ const notes = [];
653
+ for (const name of mentionedTeams(body, Object.keys(patterns).filter((item) => !patterns[item].legacy))) {
654
+ const task = teamTask(body, name);
655
+ const started = await startRun(cfg, name, task, env, { start, models: await models(cfg.stateDir, env, { peers: cfg.peers }) }).catch((error) => ({ status: "failed", detail: error.message }));
656
+ notes.push(`@${name} run ${started.id ?? ""} ${started.status}${started.detail ? ": " + started.detail : ""}`);
657
+ }
658
+ return notes;
659
+ }
660
+ async function routeTeamMentions(project, body, target, by, thread) {
661
+ const { cfg, operator } = project;
662
+ const teams = listTeams(cfg, env);
663
+ const notes = [];
664
+ for (const name of mentionedTeams(body, Object.keys(teams))) {
665
+ const members = teams[name];
666
+ if (!members?.length) {
667
+ notes.push(`@${name} unknown team`);
668
+ continue;
669
+ }
670
+ const task = teamTask(body, name);
671
+ const orch = formatTeamOrchestrator(name, members, task);
672
+ const mentionedIn = target === "all" ? "all" : target;
673
+ if (target === "all") {
674
+ if (!startable(project).includes("claude")) {
675
+ notes.push(`@${name} claude not available here`);
676
+ await refuseStart(project, target, "@" + name, "claude is not available here");
677
+ }
678
+ else
679
+ notes.push(`@${name}${await startFor(cfg, orch, { harness: "claude", system: true }, { project, target, tag: "@" + name }, thread)}`);
680
+ continue;
681
+ }
682
+ if (target.includes("#")) {
683
+ await sendMessage(operator, target, orch, { operatorThread: true, mentionedIn, forTeam: name, ...(by ? { by } : {}) });
684
+ notes.push(`@${name} orchestrator notified`);
685
+ }
686
+ else
687
+ notes.push(`@${name} needs a session or project chat`);
688
+ }
689
+ return notes;
690
+ }
691
+ // An @session gets the post in its direct chat; an @harness reaches its running sessions, or starts one with the post as prompt.
692
+ // A thread id means the post came from a thread's composer: a started session joins that thread instead of opening a new one.
693
+ async function routeMentions(project, body, target, by, sentTo, attachment, broadcastId, thread) {
694
+ const { cfg, operator } = project;
695
+ const teamNames = [...Object.keys(listTeams(cfg, env)), ...Object.keys(listPatterns(cfg, env))];
696
+ const sessions = listSessions(cfg);
697
+ // mentionOf names the broadcast, so a session that reads both takes the post once.
698
+ const direct = (to, forSubagent) => sendMessage(operator, to, body, { operatorThread: true, mentionedIn: target, attachment, ...(broadcastId ? { mentionOf: broadcastId } : {}), ...(by ? { by } : {}), ...(forSubagent ? { forSubagent } : {}) });
699
+ const notes = attachment
700
+ ? mentionedTeams(body, teamNames).map(name => "@" + name + " needs a text-only message to start")
701
+ : [...(await routeTeamMentions(project, body, target, by, thread)), ...(await routePatternMentions(project, body))];
702
+ for (const name of mentionedNames(body, cfg.peers, teamNames)) {
703
+ if (name === target)
704
+ continue;
705
+ if (name.includes(":")) {
706
+ if (attachment) {
707
+ notes.push("@" + name + " needs a text-only message to start");
708
+ continue;
709
+ }
710
+ const [harness, model] = [name.slice(0, name.indexOf(":")), name.slice(name.indexOf(":") + 1)];
711
+ if (!startable(project).includes(harness)) {
712
+ notes.push("@" + name + " not available here");
713
+ await refuseStart(project, target, "@" + name, `${harness} is not available here`);
714
+ }
715
+ else if (!(await models(cfg.stateDir, env, { peers: cfg.peers }))[harness]?.includes(model)) {
716
+ notes.push("@" + name + " unknown model");
717
+ await refuseStart(project, target, "@" + name, `${harness} lists no model named ${model}`);
718
+ }
719
+ else
720
+ notes.push("@" + name + await startFor(cfg, body, { harness, model }, { project, target, tag: "@" + name }, thread));
721
+ continue;
722
+ }
723
+ if (name.includes("#")) {
724
+ // @session/run goes to the session that owns the subagent run.
725
+ const [address, run] = name.split("/");
726
+ if (!run && sentTo.has(address))
727
+ continue;
728
+ const session = sessions.find(item => item.id === address);
729
+ if (!session) {
730
+ notes.push("@" + name + " unknown");
731
+ continue;
732
+ }
733
+ await direct(address, run);
734
+ // An idle session wakes on its tag, as it would on a direct message.
735
+ const woke = session.online ? null : wakeAgent(project, address, session);
736
+ notes.push("@" + name + (woke?.status === "waking" ? " sent, waking" : " sent"));
737
+ continue;
738
+ }
739
+ const running = sessions.filter(item => item.peer === name && item.online && !sentTo.has(item.id));
740
+ if (running.length) {
741
+ for (const item of running)
742
+ await direct(item.id);
743
+ notes.push("@" + name + " sent to " + running.length + (running.length === 1 ? " session" : " sessions"));
744
+ continue;
745
+ }
746
+ if (sessions.some(item => item.peer === name && sentTo.has(item.id)))
747
+ continue;
748
+ if (!startable(project).includes(name)) {
749
+ notes.push("@" + name + " not available here");
750
+ await refuseStart(project, target, "@" + name, `${name} is not available here`);
751
+ continue;
752
+ }
753
+ notes.push("@" + name + (attachment ? " needs a text-only message to start" : await startFor(cfg, body, { harness: name }, { project, target, tag: "@" + name }, thread)));
754
+ }
755
+ return notes;
756
+ }
757
+ // Posts temmo's own system message in the chat the operator wrote in, so a refused tag start is visible there and not only
758
+ // in the small per-message note. It rides the operator address as a system message (the same as a pattern-run failure notice).
759
+ // In the project chat it is startOnly, so no running agent is woken by it. Best effort: a failed post leaves the note.
760
+ async function refuseStart(project, target, tag, reason) {
761
+ const text = `${tag} did not start: ${reason}${/[.!]$/.test(reason) ? "" : "."}`;
762
+ await postSystem(project, target, text, true);
763
+ }
764
+ async function postSystem(project, target, text, startOnly = false) {
765
+ const direct = typeof target === "string" && target.includes("#");
766
+ const to = direct ? target : "all";
767
+ await sendMessage(project.operator, to, text, { system: true, onPublished: project.hub.record, ...(direct ? { operatorThread: true } : startOnly ? { startOnly: true } : {}) }).catch(() => { });
768
+ }
769
+ // Starts a mention's session at the project's default start place (docs/configuration.md startPlace: OpenShell when
770
+ // this project and harness offer it), one start per START_GAP_MS; returns the note after the tag. A tag posted inside
771
+ // a thread runs in the thread's worktree and joins that thread, so it does not open a new one (docs/threads.md).
772
+ // A refusal also posts a system message in the operator's chat (see refuseStart); so does a start that later ends on a usage limit.
773
+ async function startFor(cfg, body, options, report, thread) {
774
+ const refuse = async (note, reason = note.replace(/^: /, "")) => {
775
+ if (report)
776
+ await refuseStart(report.project, report.target, report.tag, reason);
777
+ return note;
778
+ };
779
+ if (isProjectPaused(cfg))
780
+ return refuse(": " + PROJECT_PAUSED, PROJECT_PAUSED + ". Resume new work to start it.");
781
+ const checked = checkPrompt(body);
782
+ if (checked.error)
783
+ return refuse(": " + checked.error);
784
+ // A tag posted in a thread runs in that thread's worktree and joins it; an unknown thread refuses the start.
785
+ let inThread = null;
786
+ if (thread && report?.project?.threads) {
787
+ inThread = await report.project.threads.startIn(thread).catch(() => null);
788
+ if (!inThread)
789
+ return refuse(": unknown thread", "the thread is unknown or belongs to another project");
790
+ }
791
+ const threadTree = inThread?.worktree && inThread.worktree !== taskRoot(report.project) ? inThread.worktree : "";
792
+ // The place a tag start takes: the configured default place (OpenShell unless defaults.json names another), never a
793
+ // hardcoded folder. In a thread it runs on the thread's worktree: in OpenShell there, else on the host.
794
+ const preferred = defaultStartPlace(startPlaces(report.project), options.harness, env);
795
+ const where = threadTree && preferred !== "openshell" ? "worktree" : preferred;
796
+ if (Date.now() - lastStartAt < START_GAP_MS)
797
+ return refuse(": wait 10 seconds between starts", "wait 10 seconds between starts");
798
+ lastStartAt = Date.now();
799
+ // pi has no CLI start argv: it runs as a runner-owned rpc session (runner/adapters/pi.ts), so its tag start goes to
800
+ // the runner. An OpenShell start with no configured shared sandbox is runner-owned too, as in the composer start, and
801
+ // so is an OpenShell start on a thread's worktree, which the shared sandbox cannot mount.
802
+ if (options.harness === "pi" || (where === "openshell" && (!openshellRunner(env) || threadTree))) {
803
+ const placed = threadTree ? { place: where === "openshell" ? "openshell" : "worktree", worktreePath: threadTree } : { place: where };
804
+ const result = await runner({ socket: runnerSocket(env), timeoutMs: 120_000 })
805
+ .start({ project: cfg.project, harness: options.harness, prompt: checked.text, ...placed, system: options.system === true, ...(options.model ? { model: options.model } : {}) })
806
+ .catch(() => null);
807
+ if (!result || result.status !== 201)
808
+ return refuse(": " + (result?.body?.error || "the session runner is unavailable"));
809
+ if (inThread)
810
+ await report.project.threads?.claim(result.body.session, { thread: inThread, prompt: checked.text });
811
+ return " starting a new session";
812
+ }
813
+ // A tag start runs unattended, like a spawned member: Claude on the host takes auto unless defaults.json names a
814
+ // claudePermissionMode; in OpenShell startSession runs it with bypassPermissions.
815
+ const unattended = options.harness === "claude" && where !== "openshell" && autoDefaults(env)?.claudePermissionMode === undefined ? { claudePermission: "auto" } : {};
816
+ const taggedStart = { ...options, ...unattended, prompt: checked.text, env, ...(threadTree ? { place: "folder", origin: threadTree } : { place: where }) };
817
+ // Only the real launcher reports how its process ended; a replacement launcher keeps the options it always got.
818
+ const watching = launch === startSession && Boolean(report);
819
+ let finish;
820
+ const exited = new Promise(resolve => { finish = resolve; });
821
+ if (watching)
822
+ taggedStart.onEnd = ({ log }) => finish(log);
823
+ const result = launch === startSession
824
+ ? await startSession(cfg, { ...taggedStart, requireRunCode: true })
825
+ : await start(cfg, taggedStart);
826
+ if (result.status === "failed")
827
+ return refuse(" start failed: " + result.detail, "start failed: " + result.detail);
828
+ if (inThread)
829
+ await report.project.threads?.claim(result.session, { thread: inThread, prompt: checked.text });
830
+ if (watching) {
831
+ void exited.then(log => {
832
+ const notice = limitEndNotice({ tag: report.tag, harness: options.harness, model: options.model, log });
833
+ return notice ? postSystem(report.project, report.target, notice, true) : undefined;
834
+ });
835
+ }
836
+ return " starting a new session";
837
+ }
838
+ function inboxOf(project, peer) {
839
+ return project.inboxes.get(peer) || inboxTopic(project.cfg.project, peer);
840
+ }
841
+ function wakeAgent(project, target, session) {
842
+ if (hosted)
843
+ return { status: "unsupported", detail: "The agent will receive this on its next poll." };
844
+ const { wakes, cfg, statuses } = project;
845
+ if (!session)
846
+ return { status: "unsupported", detail: "This agent must register its local session before it can be woken." };
847
+ // A running session needs no wake; receipts show when it reads the message.
848
+ if (session.online || runnerHeld(cfg, target) || statusOnline(statuses.get(target)))
849
+ return { status: "online" };
850
+ if (wakes.get(target)?.status !== "waking") {
851
+ // at lets the UI drop the banner once the session reports after the wake began (visibleWake).
852
+ const at = Date.now();
853
+ wakes.set(target, { status: "waking", detail: "Waking the selected session.", at });
854
+ void Promise.resolve().then(() => control("wake", session, { cfg })).then(result => wakes.set(target, { ...result, at }), () => wakes.set(target, { status: "failed", detail: "The session could not be woken.", at })).finally(broadcast);
855
+ }
856
+ return wakes.get(target);
857
+ }
858
+ // Latest msg time (ms) per sender address and per harness, from hub history already in memory.
859
+ function lastMessages(project) {
860
+ const last = new Map();
861
+ const note = (key, at) => { if (at > (last.get(key) || 0))
862
+ last.set(key, at); };
863
+ for (const name of [project.topic, ...project.inboxes.values()]) {
864
+ for (const event of project.hub.events(name)) {
865
+ const envelope = parseEnvelope(event.message);
866
+ if (envelope?.kind !== "msg" || !isValidName(envelope.from) || envelope.from === "operator")
867
+ continue;
868
+ const at = event.time * 1000;
869
+ note(envelope.from, at);
870
+ if (typeof envelope.session === "string" && SESSION_LABEL.test(envelope.session))
871
+ note(`${envelope.from}#${envelope.session}`, at);
872
+ }
873
+ }
874
+ return last;
875
+ }
876
+ function agents(project, last) {
877
+ const { cfg, statuses, wakes } = project;
878
+ const allowed = (peer) => peer !== "operator" && (!cfg.peers.length || cfg.peers.includes(peer));
879
+ const found = new Map();
880
+ for (const [id, at] of last) {
881
+ const [peer, session] = id.split("#");
882
+ if (session && allowed(peer))
883
+ found.set(id, { id, peer, session, seenAt: at, online: false });
884
+ }
885
+ for (const [id, state] of statuses) {
886
+ const [peer, session] = id.split("#");
887
+ if (!session || !allowed(peer))
888
+ continue;
889
+ const seenAt = Date.parse(state.ts) || 0;
890
+ found.set(id, { id, peer, session, seenAt, online: statusOnline(state), ...(state.parent ? { parent: state.parent } : {}) });
891
+ }
892
+ // Hooks refresh seenAt on every event; minute resolution keeps snapshot pushes to one per agent per minute.
893
+ let root = "";
894
+ try {
895
+ root = projectRoot(cfg.project, env);
896
+ }
897
+ catch { /* no registered root */ }
898
+ for (const { id, peer, session, online, seenAt, parent, cwd, name, identityName, activity, sandbox, model, runningJobs } of listSessions(cfg)) {
899
+ const where = sessionPlace({ cwd, sandbox }, root);
900
+ const started = typeof parent === "string" && PARENT.test(parent) ? parent : found.get(id)?.parent;
901
+ found.set(id, {
902
+ id, peer, session, online, seenAt, ...(runningJobs ? { runningJobs } : {}), activeAt: Math.floor((seenAt || 0) / 60_000) * 60_000, registered: true, ...(started ? { parent: started } : {}),
903
+ ...(typeof cwd === "string" && isAbsolute(cwd) ? { folder: cleanText(basename(cwd), ACTIVITY_NAME_MAX) } : {}),
904
+ // An offline session whose worktree was deleted has nothing to resume, so its card is dropped.
905
+ ...(worktreeGone({ cwd, online: online || Boolean(runningJobs), sandbox }, root) ? { gone: true } : {}),
906
+ ...(cleanName(name) ? { name: cleanName(name) } : {}),
907
+ // The name set_identity chose, which the sidebar lists as an agent (PM first), with its activity line.
908
+ ...(cleanName(identityName) ? { identityName: cleanName(identityName) } : {}),
909
+ ...(cleanName(identityName) && typeof activity === "string" && activity.trim() ? { activity: cleanText(activity, ACTIVITY_NAME_MAX) } : {}),
910
+ ...(where ? { where: cleanText(where, ACTIVITY_NAME_MAX) } : {}),
911
+ ...(typeof model === "string" && model ? { model: cleanText(model, ACTIVITY_NAME_MAX) } : {}),
912
+ });
913
+ }
914
+ const prompts = firstPrompts(project);
915
+ for (const [id, data] of found) {
916
+ if (cfg.owner)
917
+ data.owner = cfg.owner;
918
+ data.lastMessageAt = last.get(id) || 0;
919
+ // Without a harness name: the folder and the first prompt's words, from activity in memory.
920
+ if (!data.name) {
921
+ const name = fallbackName(data.folder || "", prompts.get(id));
922
+ if (name) {
923
+ data.name = name;
924
+ data.generatedName = true;
925
+ }
926
+ }
927
+ const wake = visibleWake(wakes.get(id), { ...data, statusAt: Date.parse(statuses.get(id)?.ts) || 0 });
928
+ if (wake)
929
+ data.wake = wake;
930
+ }
931
+ return [...found.values()].sort((a, b) => b.lastMessageAt - a.lastMessageAt || b.seenAt - a.seenAt || a.id.localeCompare(b.id));
932
+ }
933
+ // First prompt per session in activity history held in memory.
934
+ function firstPrompts(project) {
935
+ const first = new Map();
936
+ for (const event of project.hub.events(project.activity)) {
937
+ const item = activityItem(event);
938
+ if (item?.type === "prompt" && item.input && !first.has(item.agent))
939
+ first.set(item.agent, item.input);
940
+ }
941
+ return first;
942
+ }
943
+ // The latest time each sender posted a message: its replies to the operator and its broadcasts. An agent's replies sit in
944
+ // its own peer inbox, so the project topic and every peer inbox cover them. A prompt answered in the terminal leaves no
945
+ // reply on the bus, but the agent that asked posts again once it moves on.
946
+ function latestPosts(project) {
947
+ const latest = new Map();
948
+ const topics = new Set([project.topic, ...project.inboxes.values()]);
949
+ for (const topic of topics) {
950
+ for (const item of entries(project.hub.events, topic, (e) => e.kind === "Message")) {
951
+ if (item.time > (latest.get(item.from) ?? 0))
952
+ latest.set(item.from, item.time);
953
+ }
954
+ }
955
+ return latest;
956
+ }
957
+ // Open approvals and unanswered questions per sender address, as chat entries the cards render.
958
+ function pendingBySender(project, list, persistent = false) {
959
+ const { ends, replies } = outcomes(project.hub.events(project.topic));
960
+ const online = new Set(list.filter((agent) => agent.online).map((agent) => agent.id));
961
+ const liveMode = projectModeReader(project);
962
+ let posts;
963
+ // An ask_question the asker still lists as open (lib/questions.ts) waits on the phone alone, whatever the asker posts meanwhile.
964
+ const stillAsked = (item, id) => {
965
+ const [peer, session] = String(item.from).split("#");
966
+ if (!session || ownedRecord(project.cfg, item.from)?.status === "ended")
967
+ return false;
968
+ return openQuestions({ stateDir: project.cfg.stateDir, project: project.cfg.project, peer, session }).some(q => q.id === id);
969
+ };
970
+ // The sender posted after this prompt: it moved on, so the prompt was answered elsewhere (its terminal).
971
+ const movedOn = (item) => ((posts ??= latestPosts(project)).get(item.from) ?? 0) > item.time
972
+ && !stillAsked(item, item.question ?? item.approval?.id);
973
+ const out = new Map();
974
+ const add = (sender, item) => { if (!out.has(sender))
975
+ out.set(sender, []); out.get(sender).push(item); };
976
+ for (const item of entries(project.hub.events, project.topic, (e) => e.kind === "Approval" || e.kind === "Question")) {
977
+ if (item.kind === "Approval") {
978
+ const approval = withModeControl(project.cfg, item.from, approvalState(liveMode, item.approval, ends, replies));
979
+ if (approval.state !== "pending" || (approval.expiresAt && approval.expiresAt < Date.now()) || movedOn(item))
980
+ continue;
981
+ // A view-only terminal approval is answered in the terminal, so it does not wait on the operator.
982
+ add(item.from, { ...item, project: project.cfg.project, approval, blocking: approval.terminal !== true, expiresAt: approval.expiresAt });
983
+ }
984
+ else if (item.question && !replies.has(item.question) && !ends.has(item.question) && !movedOn(item) && (persistent || online.has(item.from) || Date.now() - item.time * 1000 < ONLINE_MS)) {
985
+ add(item.from, { ...item, project: project.cfg.project, blocking: IMPORTANT.test(item.body) });
986
+ }
987
+ }
988
+ return out;
989
+ }
990
+ function projectDecisions(project, runs, list) {
991
+ const { tasks } = taskBoard(project.tasks, list, runs, project.tasks ? listOwned(project.cfg) : []);
992
+ const agentsById = new Map(list.map((agent) => [agent.id, agent]));
993
+ const decisions = new Map();
994
+ function add(key, item, run) {
995
+ const tags = taskTags(item.body || "").map(match => match[2]);
996
+ const owned = tasks.filter(task => task.owner === item.from && task.status !== "done");
997
+ const task = tasks.find(task => tags.includes(task.id) || (run && (task.run === run.id || task.id === run.task)))
998
+ ?? (owned.length === 1 ? owned[0] : null);
999
+ decisions.set(key, { ...item, key, project: project.cfg.project, agentName: agentsById.get(item.from)?.name,
1000
+ ...(run ? { run: run.id } : {}),
1001
+ ...(task ? { task: { id: task.id, title: task.title, priority: priorityOf(task) } } : {}) });
1002
+ }
1003
+ for (const items of pendingBySender(project, [], true).values()) {
1004
+ for (const item of items) {
1005
+ if (item.approval?.terminal || (hosted && item.approval?.tool === LIMIT_TOOL))
1006
+ continue;
1007
+ const run = runs.find((run) => Object.values(run.instances ?? {}).flat().includes(item.from)
1008
+ || Object.values(run.sessions ?? {}).includes(item.from));
1009
+ add(item.question ?? item.approval.id, item, run);
1010
+ }
1011
+ }
1012
+ if (!hosted)
1013
+ for (const run of runs) {
1014
+ if (run.status !== "suspended" || !run.suspension)
1015
+ continue;
1016
+ const { suspension } = run;
1017
+ add(suspension.id, { kind: "Suspension", suspension, from: suspension.caller || run.sessions?.[suspension.from] || suspension.from,
1018
+ time: (suspension.at ?? run.startedAt) / 1000 }, run);
1019
+ }
1020
+ return [...decisions.values()];
1021
+ }
1022
+ // Agents' milestone posts on the project chat (send_to_all progress=true; older posts are to=all fyi notes), each with its
1023
+ // thread, newest first: posts share whole-second stamps, so arrival order breaks ties.
1024
+ function progressPosts(project) {
1025
+ const threads = project.threads?.list() || [];
1026
+ return project.hub.events(project.topic).flatMap((event) => {
1027
+ const envelope = parseEnvelope(event.message);
1028
+ if (envelope?.kind !== "msg" || envelope.to !== "all" || envelope.system === true || envelope.from === "operator")
1029
+ return [];
1030
+ if (envelope.progress !== true && (envelope.priority !== "fyi" || envelope.replyTo))
1031
+ return [];
1032
+ const item = entry(event);
1033
+ if (item?.kind !== "Message")
1034
+ return [];
1035
+ const thread = threads.find((row) => (row.sessions || []).includes(item.from));
1036
+ return [{ id: item.id, time: item.time, from: item.from, body: item.body, project: project.cfg.project,
1037
+ ...(thread ? { thread: { id: thread.id, title: thread.title } } : {}) }];
1038
+ }).reverse();
1039
+ }
1040
+ // Addresses of the project's sessions in list that wait on the operator (sessionState "waiting").
1041
+ function waitingIds(project, list) {
1042
+ const pending = pendingBySender(project, list);
1043
+ return new Set(list.filter((agent) => waitingOn(pending.get(agent.id), Date.now())).map((agent) => agent.id));
1044
+ }
1045
+ // Sessions that still have a place to run: an offline one whose worktree was deleted is left out of cards and counts.
1046
+ function placed(list) {
1047
+ return list.filter((agent) => !agent.gone);
1048
+ }
1049
+ // Home and Sessions cards: each session's facts for sessionState(), its last action and running subagents.
1050
+ function sessionCards(project, list, mode) {
1051
+ const { cfg, statuses } = project;
1052
+ const shown = placed(list);
1053
+ const rows = groupSubagents(activityRows(activityList(project)));
1054
+ const latest = new Map();
1055
+ const lastAction = new Map();
1056
+ const runs = new Map();
1057
+ for (const row of rows) {
1058
+ latest.set(row.agent, row);
1059
+ if (row.type === "subagent") {
1060
+ if (!row.done) {
1061
+ if (!runs.has(row.agent))
1062
+ runs.set(row.agent, []);
1063
+ runs.get(row.agent).push(row);
1064
+ }
1065
+ if (row.last)
1066
+ lastAction.set(row.agent, { tool: row.last.tool, summary: row.last.summary, time: row.last.time, subagent: row.kind || "agent" });
1067
+ }
1068
+ else if (row.tool && (row.type === "tool_call" || row.type === "tool_result" || row.type === "error")) {
1069
+ lastAction.set(row.agent, { tool: row.tool, summary: summarize(row.input).slice(0, 160), time: row.time });
1070
+ }
1071
+ }
1072
+ const pending = pendingBySender(project, list);
1073
+ const membership = rolesByAddress(listRuns(cfg));
1074
+ const turns = turnStarts(rows);
1075
+ return shown.map((agent) => {
1076
+ const row = latest.get(agent.id);
1077
+ const lastAt = row ? Math.max(row.time, ...(row.rows || []).map((r) => r.time)) * 1000 : 0;
1078
+ const open = row && row.type === "tool_call" && !row.result;
1079
+ // Unfinished runs; the browser counts only those with a row in the last 2 min (runState).
1080
+ const subagents = (runs.get(agent.id) || []).map((run) => ({ id: run.id, agent: run.agent, run: run.run, kind: run.kind, model: run.model, description: run.description, steps: run.steps, time: run.time, lastTime: run.lastTime, last: run.last, open: run.open }));
1081
+ return {
1082
+ ...agent, project: cfg.project, harness: peerOf(agent.id), online: shownOnline(agent), lastActivityAt: lastAt, ...(open ? { openCallAt: lastAt } : {}), ...(turns.has(agent.id) ? { turnStartAt: turns.get(agent.id) } : {}),
1083
+ // Only the Stop hook's own "hold" status marks a hold; an ordinary turn end publishes "stop".
1084
+ afkHold: mode !== "off" && statuses.get(agent.id)?.event === "hold" && row?.type === "stop",
1085
+ ...(lastAction.has(agent.id) ? { lastAction: lastAction.get(agent.id) } : {}), subagents, pending: pending.get(agent.id) || [],
1086
+ ...(membership.get(agent.id) ? { team: membership.get(agent.id)?.team, role: membership.get(agent.id)?.role } : {}),
1087
+ ...cardContext(cfg, agent),
1088
+ };
1089
+ });
1090
+ }
1091
+ /** Each session's finished subagent runs, newest first and capped, for the sidebar; gone sessions keep theirs. */
1092
+ function finishedRuns(project) {
1093
+ const done = new Map();
1094
+ for (const run of groupSubagents(activityRows(activityList(project)))) {
1095
+ if (run.type !== "subagent" || !run.done)
1096
+ continue;
1097
+ if (!done.has(run.agent))
1098
+ done.set(run.agent, []);
1099
+ done.get(run.agent)?.push({ id: run.id, agent: run.agent, run: run.run, kind: run.kind, description: run.description, steps: run.steps, time: run.time, lastTime: run.lastTime, done: true });
1100
+ }
1101
+ for (const [agent, runs] of done)
1102
+ done.set(agent, runs.reverse().slice(0, FINISHED_RUNS));
1103
+ return done;
1104
+ }
1105
+ function harnesses(project, list, last) {
1106
+ const names = project.cfg.peers.length ? project.cfg.peers : [...new Set(list.map((agent) => agent.peer))].sort();
1107
+ return names.map((id) => {
1108
+ const sessions = list.filter((agent) => agent.peer === id);
1109
+ return { id, lastMessageAt: last.get(id) || 0, activeAt: Math.max(0, ...sessions.map((agent) => agent.activeAt || 0)), sessions: sessions.length, online: sessions.filter((agent) => agent.online).length };
1110
+ });
1111
+ }
1112
+ // Ticks for an operator message: read when every recipient read it, delivered when one was online then or since.
1113
+ function receiptOf(project, item, list, reads) {
1114
+ // A start-only post has no recipient to wait on: its tag starts a session with no inbox position for it.
1115
+ if (item.startOnly)
1116
+ return "";
1117
+ const at = item.time * 1000;
1118
+ const [peer, session] = item.to.split("#");
1119
+ const targets = list.filter((agent) => agent.session && (peer === "all" || agent.peer === peer) && (!session || agent.session === session));
1120
+ // Sessions online when the UI first saw the message; history older than ONLINE_MS has no such snapshot.
1121
+ if (!project.recipients.has(item.id)) {
1122
+ project.recipients.set(item.id, new Set(Date.now() - at < ONLINE_MS ? targets.filter((agent) => agent.online).map((agent) => agent.id) : []));
1123
+ for (const id of project.recipients.keys()) {
1124
+ if (project.recipients.size <= RECIPIENTS_MAX)
1125
+ break;
1126
+ project.recipients.delete(id);
1127
+ }
1128
+ }
1129
+ const online = project.recipients.get(item.id);
1130
+ const read = reads.get(item.id) || new Set();
1131
+ // Only a hook's read receipt moves a tick: being online says nothing about whether the agent has the message.
1132
+ if (session)
1133
+ return read.has(item.to) ? "read" : "sent";
1134
+ // A broadcast waits only for sessions online at send time; without any, for the sessions that read it.
1135
+ const waiting = online.size ? [...online] : [...read];
1136
+ if (waiting.length && waiting.every(id => read.has(id)))
1137
+ return "read";
1138
+ return read.size ? "delivered" : "sent";
1139
+ }
1140
+ function entries(events, name, keep) {
1141
+ return events(name).map(entry).filter((item) => item && keep(item));
1142
+ }
1143
+ // Operator answers to questions and approvals on the project topic, each linked to the ask it answers (replyTo).
1144
+ function answersOf(events, topic) {
1145
+ const asks = new Map();
1146
+ for (const item of topic) {
1147
+ if (item.kind === "Question")
1148
+ asks.set(item.question, { asker: item.from });
1149
+ if (item.kind === "Approval")
1150
+ asks.set(item.approval.id, { asker: item.from, approval: item.approval });
1151
+ }
1152
+ return events.flatMap((event) => {
1153
+ const reply = readReply(event);
1154
+ const ask = reply && !reply.skipped && asks.get(reply.id);
1155
+ if (!ask)
1156
+ return [];
1157
+ const decision = ask.approval ? replyDecision(ask.approval, reply.answer) : null;
1158
+ return [{ id: event.id, time: event.time, asker: ask.asker, question: reply.id, body: answerText(decision, reply.answer), by: replyBy(event) }];
1159
+ });
1160
+ }
1161
+ function queueEntry(item) {
1162
+ if (item.kind !== "Message" || item.from !== "operator" || !item.thread || typeof item.to !== "string")
1163
+ return false;
1164
+ const [peer, session, ...extra] = item.to.split("#");
1165
+ return isValidName(peer) && typeof session === "string" && SESSION_LABEL.test(session) && !extra.length;
1166
+ }
1167
+ // Zoom by sender: the whole project, one harness, or one session's direct thread.
1168
+ function messages(project, { harness, session }, agentList, { events = project.hub.events, archived = false } = {}) {
1169
+ const reads = archived ? readReceipts(events(project.receipts), new Map(), Infinity) : project.reads;
1170
+ const activity = (session) => activityList(project, session, events);
1171
+ const sharedEvents = events(project.topic);
1172
+ const topic = sharedEvents.map(entry).filter(Boolean);
1173
+ const answers = answersOf(sharedEvents, topic);
1174
+ const answered = new Set(answers.map((answer) => answer.question));
1175
+ // An answer shows as an operator message, so the bus Reply entry it came from goes.
1176
+ const shared = topic.filter((item) => !(item.kind === "Reply" && answered.has(item.question)));
1177
+ const states = new Map();
1178
+ const local = new Set(agentList.filter((agent) => agent.registered).map((agent) => agent.id));
1179
+ const withQueue = (items) => items.map((item) => {
1180
+ if (!queueEntry(item))
1181
+ return item;
1182
+ if (!states.has(item.to)) {
1183
+ const [peer, session] = item.to.split("#");
1184
+ states.set(item.to, readState(statePath({ ...project.cfg, peer, session })));
1185
+ }
1186
+ const state = states.get(item.to);
1187
+ const current = queuedMessage(item, state);
1188
+ if (!current)
1189
+ return { ...item, ...state.queue[item.id], queueStatus: "Canceled" };
1190
+ const claimed = state.seen.includes(item.id);
1191
+ const read = reads.get(item.id)?.has(item.to);
1192
+ if (!archived && local.has(item.to) && !claimed && !read)
1193
+ return { ...current, queued: true };
1194
+ return claimed && !read ? { ...current, queueStatus: "Claimed for delivery" } : current;
1195
+ });
1196
+ let list;
1197
+ if (session) {
1198
+ // A system message rides the operator's address, so it belongs in the operator's thread with that session.
1199
+ const fromOperator = (item) => item.from === "operator" || item.system === true;
1200
+ // A session's chat is its direct messages with the operator. A thread post, and the copy a listening session got of one, belong to the thread view.
1201
+ const thread = (item) => item.thread && !item.channelOf && ((fromOperator(item) && item.to === session) || (item.from === session && item.to === "operator"));
1202
+ const inbox = entries(events, inboxOf(project, peerOf(session)), () => true);
1203
+ const sent = withQueue(inbox);
1204
+ list = [...sent.filter(thread), ...terminalPrompts(activity(session), [...topic, ...sent]),
1205
+ ...shared.filter((item) => item.from === session).map((item) => ({ ...item, scope: "all" })),
1206
+ ...answers.filter((answer) => answer.asker === session).map(answerMessage)];
1207
+ }
1208
+ else if (harness) {
1209
+ const related = (item) => peerOf(item.from) === harness || peerOf(item.to) === harness || mentions(item.body, harness);
1210
+ list = [...shared.filter(related).map((item) => ({ ...item, scope: "all" })),
1211
+ ...withQueue(entries(events, inboxOf(project, harness), (item) => item.kind === "Message"))];
1212
+ }
1213
+ else {
1214
+ const peers = new Set([...project.inboxes.keys(), ...activity().map((item) => peerOf(item.agent))]);
1215
+ const inbox = [...peers].flatMap(peer => entries(events, inboxOf(project, peer), () => true));
1216
+ const sent = [...topic, ...withQueue(inbox)];
1217
+ // Inbox direct sends stay in session threads; they only suppress terminal echoes here.
1218
+ // An agent's answer to a project-chat @mention (mentionedIn "all") also shows here, quoting the post it answers.
1219
+ const mentions = new Map(inbox.filter(item => item.from === "operator" && item.mentionedIn === "all").map(item => [item.id, item]));
1220
+ // Only the mention's addressee answers it here; a reply from another session stays out.
1221
+ const mentionReplies = inbox.filter(item => item.thread && item.to === "operator" && mentions.has(item.replyOf) && item.from === mentions.get(item.replyOf).to)
1222
+ .map(item => ({ ...item, quote: { id: item.replyOf, sender: "operator", body: String(mentions.get(item.replyOf).body || "").slice(0, QUOTE_MAX) } }));
1223
+ list = [...shared, ...mentionReplies, ...answers.map(answerMessage), ...terminalPrompts(activity(), sent)];
1224
+ }
1225
+ const { ends, endMeta, replies, senders } = outcomes(sharedEvents);
1226
+ // A reply carries its replied message's sender and opening text, even when that message is off the page.
1227
+ const byId = new Map(list.map(item => [item.id, item]));
1228
+ // A reply to a session's final text names that text's activity row; the rows are read only when a reply needs one.
1229
+ let texts;
1230
+ const said = (id) => (texts ??= new Map(activity(session).filter((row) => row.type === "text").map((row) => [row.id, row]))).get(id);
1231
+ const quoted = (item) => {
1232
+ const message = item.replyOf && byId.get(item.replyOf);
1233
+ const row = !message && item.replyOf && said(item.replyOf);
1234
+ const original = message || (row && { id: row.id, sender: row.agent, body: row.output });
1235
+ if (original)
1236
+ return { ...item, quote: { id: original.id, sender: original.sender || original.from, body: String(original.body || "").slice(0, QUOTE_MAX) } };
1237
+ // An operator reply sent as quoted text (an unlinkable id) shows the same card, with nothing to link to.
1238
+ const split = item.kind === "Message" && item.from === "operator" && !item.quote ? splitQuotedReply(item.body) : null;
1239
+ return split ? { ...item, body: split.body, quote: { id: "", sender: split.quote.sender, body: split.quote.body.slice(0, QUOTE_MAX) } } : item;
1240
+ };
1241
+ const sorted = list.sort((a, b) => a.time - b.time || a.id.localeCompare(b.id));
1242
+ const recent = new Set(sorted.slice(-MAX_MESSAGES));
1243
+ const liveMode = projectModeReader(project);
1244
+ return sorted.filter(item => archived || recent.has(item) || (session && item.queued))
1245
+ .map(item => {
1246
+ if (item.kind === "Approval")
1247
+ return { ...item, approval: withModeControl(project.cfg, item.from, approvalState(liveMode, item.approval, ends, replies, senders)) };
1248
+ // A PR request's card shows its outcome once closed: created (with the url), dismissed, or the failure.
1249
+ if (item.kind === "CreatePr") {
1250
+ const end = endMeta.get(item.createPr.id);
1251
+ if (!end)
1252
+ return item;
1253
+ return { ...item, createPr: { ...item.createPr, state: ends.get(item.createPr.id), ...(end.url ? { url: end.url } : {}), ...(end.why ? { why: end.why } : {}) } };
1254
+ }
1255
+ if (item.kind === "Question" && replies.has(item.question)) {
1256
+ const by = senders.get(item.question)[0];
1257
+ return { ...item, answer: replies.get(item.question)[0], ...(by ? { answeredBy: by } : {}) };
1258
+ }
1259
+ if (item.kind === "Question" && ends.get(item.question) === "skipped")
1260
+ return { ...item, skipped: true };
1261
+ const stated = item.from === "operator" && item.kind === "Message" && item.to && !item.terminal && !item.replyTo ? { ...item, receipt: receiptOf(project, item, agentList, reads) } : item;
1262
+ return quoted(stated);
1263
+ });
1264
+ }
1265
+ // The thread view's feed (docs/threads.md "Thread view"): the thread's channel posts, oldest first, in the chat
1266
+ // message shape; the thread itself is the addressee, so rows read like the session chat's.
1267
+ function threadPosts(project, id, agentList) {
1268
+ const posts = project.hub.events(threadTopic(project.cfg.project, id))
1269
+ .map(entry).filter((item) => item?.kind === "Message")
1270
+ .map((item) => ({ ...item, to: "all" }));
1271
+ // Agents answer the operator directly, so each thread session's chat joins the feed; a channel post's per-recipient copies stay out.
1272
+ const sessions = project.threads?.list()?.find((thread) => thread.id === id)?.sessions || [];
1273
+ const direct = sessions.flatMap(session => messages(project, { harness: peerOf(session), session }, agentList))
1274
+ .filter((item) => !item.channelOf && !item.queued);
1275
+ const seen = new Set();
1276
+ return [...posts, ...direct].filter((item) => !seen.has(item.id) && seen.add(item.id))
1277
+ .sort((a, b) => a.time - b.time || String(a.id).localeCompare(String(b.id)));
1278
+ }
1279
+ // Show system prompts and typed prompts in chat, with typed echoes removed.
1280
+ function terminalPrompts(activity, sent) {
1281
+ const prompts = activity.filter((item) => item.type === "prompt" && item.input && (item.system || operatorPrompt(item.input)));
1282
+ return terminalMessages(prompts, sent);
1283
+ }
1284
+ // pending, sent (answered, the hook has not read it yet), or the end reason; with the decision or answers that applied.
1285
+ // A terminal card also carries the live mode, so its hint never says AFK is off once the operator is back away.
1286
+ function approvalState(projectMode, approval, ends, replies, senders = new Map()) {
1287
+ const decisions = (replies.get(approval.id) || []).map((answer) => replyDecision(approval, answer));
1288
+ const at = decisions.findIndex(Boolean);
1289
+ const decision = decisions[at];
1290
+ const by = senders.get(approval.id)?.[at];
1291
+ const state = ends.get(approval.id) || (decision ? "sent" : "pending");
1292
+ return {
1293
+ ...approval, state,
1294
+ ...(approval.terminal ? { mode: projectMode() } : {}),
1295
+ ...(decision ? { decision: decision.behavior, ...(decision.answers ? { answers: decision.answers } : {}), ...(by ? { by } : {}) } : {}),
1296
+ };
1297
+ }
1298
+ // The project's latest operator mode, read once per snapshot and shared by every card that needs it.
1299
+ function projectModeReader(project) {
1300
+ let mode;
1301
+ return () => (mode ??= latestMode(project.hub.events(project.topic)).mode);
1302
+ }
1303
+ function findApproval(project, id) {
1304
+ if (typeof id !== "string" || !APPROVAL_ID.test(id))
1305
+ reject(400, "Invalid approval");
1306
+ const item = project.hub.events(project.topic).map(entry).find((e) => e?.kind === "Approval" && e.approval.id === id);
1307
+ if (!item)
1308
+ reject(404, "Unknown approval");
1309
+ if (item.approval.terminal)
1310
+ reject(409, "Answer this in the terminal");
1311
+ const { ends } = outcomes(project.hub.events(project.topic));
1312
+ if (ends.has(id) || (item.approval.expiresAt && item.approval.expiresAt < Date.now()))
1313
+ reject(409, "This request has closed");
1314
+ return item.approval;
1315
+ }
1316
+ // Publishes an allow/deny decision, or the answers to a choice, as the reply the hook waits on.
1317
+ async function answerApproval(project, id, { decision, answers }, by) {
1318
+ const approval = findApproval(project, id);
1319
+ let answer;
1320
+ if (approval.questions) {
1321
+ if (!answers || typeof answers !== "object" || Array.isArray(answers))
1322
+ reject(400, "Answer every question");
1323
+ answer = JSON.stringify(answers);
1324
+ if (answer.length > ANSWER_MAX_CHARS || !parseChoice(approval.questions, answer))
1325
+ reject(400, "Answer every question");
1326
+ }
1327
+ else {
1328
+ // "always" allows the tool kind for the rest of a runner-owned Cursor session (lib/approvals.ts replyDecision).
1329
+ if (!["allow", "always", "deny"].includes(decision))
1330
+ reject(400, "Decision must be allow, always or deny");
1331
+ if (decision === "always" && !(approval.owned && approval.harness === "cursor"))
1332
+ reject(400, "Always is offered only for runner-owned Cursor sessions");
1333
+ answer = decision;
1334
+ }
1335
+ if (approval.tool === LIMIT_TOOL)
1336
+ return answerLimit(project, approval, answer);
1337
+ if (approval.tool === SANDBOX_CHANGE_TOOL)
1338
+ return answerSandboxChange(project, id, decision, by);
1339
+ if (approval.signed)
1340
+ return answerSigned(project, approval, answer, by);
1341
+ await publishDecision(project, id, `reply ${id} ${answer}`, by, value => replyDecision(approval, value));
1342
+ return { sent: true, status: approval.questions ? "Answer sent" : decision === "allow" ? "Allow sent" : decision === "always" ? "Allow for this session sent" : "Deny sent" };
1343
+ }
1344
+ // The Create PR card's tap (lib/pr-card.ts): the thread is resolved from the requester's session address, never from
1345
+ // anything the agent claimed, then the host opens the PR exactly like the thread's Diff tab does. The outcome closes
1346
+ // the card and posts to the channel, where the requesting agent can read it.
1347
+ async function openPrRequest(project, { id, decision }, by) {
1348
+ if (hosted)
1349
+ reject(403, "Pull requests are opened on the host machine");
1350
+ const events = project.hub.events(project.topic);
1351
+ const item = events.map(entry).find((e) => e?.kind === "CreatePr" && e.createPr.id === id);
1352
+ if (!item)
1353
+ reject(404, "Unknown PR request");
1354
+ if (outcomes(events).ends.has(id))
1355
+ reject(409, "This request has closed");
1356
+ const close = (reason, extra = {}) => publish(project.cfg, project.topic, approvalEnd(project.operator, id, reason, extra), { title: "PR request", priority: 1, onPublished: project.hub.record });
1357
+ if (decision === "dismiss") {
1358
+ await close("skipped");
1359
+ return { status: "Dismissed" };
1360
+ }
1361
+ // The thread may have gained its branch after the card was published, so read a fresh record before opening.
1362
+ await project.threads?.refresh?.();
1363
+ const thread = project.threads?.list?.().find((t) => t.sessions?.includes(item.sender));
1364
+ if (!thread) {
1365
+ await close("cancelled", { why: "this session belongs to no thread" });
1366
+ return { status: "Refused", why: "this session belongs to no thread" };
1367
+ }
1368
+ if (!thread.branch || !thread.worktree) {
1369
+ await close("cancelled", { why: "the thread has no branch to open a PR from" });
1370
+ return { status: "Refused", why: "the thread has no branch to open a PR from" };
1371
+ }
1372
+ try {
1373
+ const opened = await land.open(thread.branch, thread.worktree, item.createPr.note || undefined);
1374
+ const number = Number(opened.url.split("/").pop());
1375
+ if (!thread.prs?.some((pr) => pr.number === number)) {
1376
+ await project.threads.handle({ op: "attach-pr", thread: thread.id, pr: { number, url: opened.url, head: thread.branch, base: "main", state: "open" } });
1377
+ }
1378
+ await close("allowed", { url: opened.url });
1379
+ await sendMessage(project.operator, "all", `PR #${number} opened: ${opened.url}${by ? " · by " + by : ""}`, { system: true, onPublished: project.hub.record }).catch(() => { });
1380
+ return { status: opened.created ? "PR opened" : "PR exists", url: opened.url };
1381
+ }
1382
+ catch (err) {
1383
+ const why = err instanceof LandRefused ? err.message : String(err?.message || err);
1384
+ await close("cancelled", { why });
1385
+ return { status: "Refused", why };
1386
+ }
1387
+ }
1388
+ // A sandbox change card (lib/sandbox-proposal.ts): the tap applies on this host, like the limit card's pick and the
1389
+ // run-in-terminal click. Nothing here reads a bus reply: a forged `reply <id> allow` leaves the proposal pending.
1390
+ // The O_EXCL claim in applySandboxChange / denySandboxChange makes a proposal apply exactly once per machine.
1391
+ async function answerSandboxChange(project, id, decision, by) {
1392
+ if (hosted)
1393
+ reject(403, "Sandbox changes apply on the host machine");
1394
+ if (!["allow", "deny"].includes(decision))
1395
+ reject(400, "Decision must be allow or deny");
1396
+ const cards = project.hub.events(project.topic)
1397
+ .map((event) => parseEnvelope(event.message))
1398
+ .filter((e) => (e?.kind === "approval" || e?.kind === "approval-view") && e.id === id);
1399
+ // A second card under this id could have swapped the change after the operator read the first one.
1400
+ if (cards.length !== 1)
1401
+ reject(409, "Two cards share this proposal id; ask the agent to propose again");
1402
+ const raw = cards[0];
1403
+ if (raw.kind !== "approval" || raw.tool !== SANDBOX_CHANGE_TOOL)
1404
+ reject(404, "Unknown sandbox change");
1405
+ const where = { stateDir: project.cfg.stateDir, project: project.cfg.project, id, by: by || "operator" };
1406
+ const session = typeof raw.session === "string" ? raw.session : undefined;
1407
+ if (decision === "deny") {
1408
+ const denied = denySandboxChange({ ...where, why: "denied from the phone UI" });
1409
+ if (denied.status !== "denied")
1410
+ reject(409, "This request has closed");
1411
+ await announceChangeDecision(project.operator, { id, session, reason: "denied", detail: `denied by ${by || "operator"}`, system: true, onPublished: project.hub.record });
1412
+ return { sent: true, status: "Deny sent" };
1413
+ }
1414
+ const applied = await applySandboxChange({ ...where, change: raw.change, env });
1415
+ if (applied.status === "already")
1416
+ reject(409, "This request has closed");
1417
+ if (applied.status === "failed") {
1418
+ await announceChangeDecision(project.operator, { id, session, reason: "cancelled", detail: applied.why, system: true, onPublished: project.hub.record });
1419
+ return { status: "Refused", why: applied.why };
1420
+ }
1421
+ await announceChangeDecision(project.operator, { id, session, reason: "allowed", detail: applied.detail, system: true, onPublished: project.hub.record });
1422
+ return { status: "Applied", detail: applied.detail };
1423
+ }
1424
+ // A limit card's pick: "Wait for reset" acknowledges; a replacement starts a session (lib/limit-alert.ts chooseLimit). No bus reply: no hook waits.
1425
+ // A signed-approval card: Allow publishes an Ed25519 approval bound to this card, session, tool and input hash (lib/approval-signer.ts).
1426
+ async function answerSigned(project, approval, answer, by) {
1427
+ if (answer !== "allow" && answer !== "deny")
1428
+ reject(400, "Decision must be allow or deny");
1429
+ if (answer === "allow" && hosted)
1430
+ reject(403, "Sign approvals on the agent machine");
1431
+ const reply = answer === "allow"
1432
+ ? `allow ${signApproval(ensureApprovalKey(env), { session: approval.signed.session, tool: approval.tool, inputHash: approval.signed.inputHash, requestId: approval.id, ...(isGithubLogin(by) ? { by } : {}) })}`
1433
+ : "deny";
1434
+ await publishDecision(project, approval.id, `reply ${approval.id} ${reply}`, by, (value) => replyDecision(approval, value));
1435
+ return { sent: true, status: answer === "allow" ? "Signed allow sent" : "Deny sent" };
1436
+ }
1437
+ async function answerLimit(project, approval, answer) {
1438
+ if (hosted)
1439
+ reject(403, "Handle usage limits on the agent machine");
1440
+ const label = Object.values(parseChoice(approval.questions, answer) ?? {})[0];
1441
+ // Text typed in Other, not a listed option, names a harness or model (lib/limit-alert.ts typedReplacement).
1442
+ const listedOption = (approval.questions?.[0]?.options ?? []).some((o) => o.label === label);
1443
+ const result = await chooseLimit(project.cfg, { id: approval.id, ...(listedOption ? { label } : { typed: label }), start, env });
1444
+ if (result.status === "duplicate")
1445
+ reject(409, result.detail);
1446
+ if (result.status === "failed")
1447
+ reject(400, result.detail);
1448
+ // The pick closes the card on every phone: no second pick, and the waiting dot clears.
1449
+ await publish(project.cfg, project.topic, limitEndMessage(project.cfg, approval.id, "answered")).catch(() => { });
1450
+ if (result.status === "waiting")
1451
+ return { sent: true, status: "Waiting for reset" };
1452
+ return { sent: true, status: `Started ${result.session}`, session: result.session, detail: result.detail };
1453
+ }
1454
+ /**
1455
+ * Skip: closes an open decision without answering it. An approval, choice, question or limit card gets an approval-end with reason
1456
+ * "skipped" and no reply, so a waiting hook returns no decision and the harness's own prompt stays in charge. A task question is
1457
+ * cleared with a progress line. A runner-owned approval has no terminal prompt to fall back on, so it cannot be skipped.
1458
+ */
1459
+ async function skipDecision(project, { id, taskId }, by) {
1460
+ const who = by ? `operator:${by}` : "operator";
1461
+ if (taskId !== undefined) {
1462
+ if (hosted)
1463
+ reject(403, "Skip task questions on the agent machine");
1464
+ if (!project.tasks || typeof taskId !== "string")
1465
+ reject(400, "Give the task id");
1466
+ const result = { status: "Skipped", detail: taskId };
1467
+ let task;
1468
+ try {
1469
+ task = project.tasks.get(taskId);
1470
+ }
1471
+ catch (err) {
1472
+ if (err instanceof TaskNotFoundError)
1473
+ return result;
1474
+ reject(404, err.message);
1475
+ }
1476
+ if (!task.question || task.question.answer)
1477
+ reject(409, "This task has no open question");
1478
+ try {
1479
+ await project.tasks.update(taskId, { ask: null, progress: { by: who, text: SKIPPED_PROGRESS } });
1480
+ }
1481
+ catch (err) {
1482
+ if (err instanceof TaskNotFoundError)
1483
+ return result;
1484
+ reject(400, err.message);
1485
+ }
1486
+ broadcast();
1487
+ return result;
1488
+ }
1489
+ if (typeof id !== "string" || !APPROVAL_ID.test(id))
1490
+ reject(400, "Invalid decision");
1491
+ const items = project.hub.events(project.topic).map(entry);
1492
+ const hasApproval = items.some((e) => e?.kind === "Approval" && e.approval.id === id);
1493
+ if (!hasApproval && !items.some((e) => e?.kind === "Question" && e.question === id))
1494
+ return { status: "Skipped" };
1495
+ await resolveDecision(project, id, async (_events, replies) => {
1496
+ if (hasApproval) {
1497
+ const approval = findApproval(project, id);
1498
+ if (approval.owned)
1499
+ reject(409, "A runner session has no terminal prompt; answer this request");
1500
+ if (replies.some((value) => replyDecision(approval, value)))
1501
+ reject(409, "This request has closed");
1502
+ if (approval.tool === LIMIT_TOOL) {
1503
+ if (hosted)
1504
+ reject(403, "Handle usage limits on the agent machine");
1505
+ const result = await skipLimit(project.cfg, id);
1506
+ if (result.status !== "skipped")
1507
+ reject(409, result.detail);
1508
+ }
1509
+ }
1510
+ else if (replies.length)
1511
+ reject(409, "This question has closed");
1512
+ const end = encodeEnvelope("approval-end", { from: "operator", id, reason: "skipped", ...(by ? { by } : {}), ts: new Date().toISOString() }, project.cfg.wire);
1513
+ await publish(project.cfg, project.topic, end, { title: "temmo approval skipped", priority: 1, onPublished: project.hub.record });
1514
+ });
1515
+ return { status: "Skipped" };
1516
+ }
1517
+ async function resolveDecision(project, id, resolve) {
1518
+ const pending = project.publishingDecisions ??= new Set();
1519
+ const events = project.hub.events(project.topic);
1520
+ const { ends, replies } = outcomes(events);
1521
+ if (pending.has(id) || ends.has(id))
1522
+ reject(409, "This request has closed");
1523
+ pending.add(id);
1524
+ try {
1525
+ await resolve(events, replies.get(id) ?? []);
1526
+ }
1527
+ finally {
1528
+ pending.delete(id);
1529
+ }
1530
+ }
1531
+ async function publishDecision(project, id, reply, by, valid = Boolean) {
1532
+ await resolveDecision(project, id, async (_events, replies) => {
1533
+ if (replies.some(valid))
1534
+ reject(409, "This request has closed");
1535
+ await publish(project.cfg, project.topic, reply, { title: replyTitle(project.cfg, by), onPublished: project.hub.record });
1536
+ });
1537
+ }
1538
+ // An A2UI surface action: a choice's picks become the answers object, a question's text the reply body.
1539
+ async function answerSurface(project, answer, by) {
1540
+ if (answer.kind === "approval") {
1541
+ const approval = findApproval(project, answer.id);
1542
+ const answers = approval.questions && answer.picks ? choiceAnswers(approval.questions, answer.picks, answer.other) : undefined;
1543
+ return answerApproval(project, answer.id, { decision: answer.decision, answers }, by);
1544
+ }
1545
+ const text = answer.body.trim();
1546
+ if (!/^[a-f0-9]{12}$/.test(answer.question) || !text || text.length > 2000)
1547
+ reject(400, "Enter 1–2000 characters");
1548
+ const reply = `reply ${answer.question} ${text}`;
1549
+ if (Buffer.byteLength(reply) > MESSAGE_MAX_BYTES)
1550
+ reject(400, "Reply exceeds the size limit");
1551
+ await publishDecision(project, answer.question, reply, by);
1552
+ return { sent: true };
1553
+ }
1554
+ // Harnesses each project can start, cached because it scans PATH.
1555
+ function startable(project) {
1556
+ if (hosted)
1557
+ return [];
1558
+ if (!project.startable || Date.now() - project.startable.at > STARTABLE_CACHE_MS)
1559
+ project.startable = { at: Date.now(), list: availableHarnesses(project.cfg, env) };
1560
+ return project.startable.list;
1561
+ }
1562
+ // Start places (folder, worktree, openshell) for the project, cached like startable().
1563
+ function startPlaces(project) {
1564
+ if (hosted)
1565
+ return [];
1566
+ if (!project.places || Date.now() - project.places.at > STARTABLE_CACHE_MS)
1567
+ project.places = { at: Date.now(), list: availablePlaces(project.cfg, env) };
1568
+ return project.places.list;
1569
+ }
1570
+ // A project's checkout, for the git reads behind review packets; "" when it is unregistered or missing.
1571
+ function taskRoot(project) {
1572
+ try {
1573
+ return projectRoot(project.cfg.project, env);
1574
+ }
1575
+ catch {
1576
+ return "";
1577
+ }
1578
+ }
1579
+ const canLand = (project) => !hosted && project.tasks && taskRoot(project) === landingCheckout;
1580
+ // The plain-text diff of one build, capped so a huge change cannot exhaust memory or the connection.
1581
+ async function diffRange(root, base, commit) {
1582
+ const { stdout } = await runFile("git", ["diff", "--no-ext-diff", "--no-textconv", base, commit, "--"], { cwd: root, timeout: 10_000, maxBuffer: DIFF_MAX_BYTES }).catch(() => reject(422, "The build diff is unavailable or larger than 4 MiB"));
1583
+ return stdout;
1584
+ }
1585
+ function snapshot({ project, harness, session, scope, thread, history: wantHistory, progress: wantProgress }) {
1586
+ const last = lastMessages(project);
1587
+ const list = agents(project, last);
1588
+ // A session whose worktree was deleted has no card to answer on, so it does not count as waiting either.
1589
+ const waiting = waitingIds(project, placed(list));
1590
+ const mode = latestMode([...projects.values()].flatMap(item => item.hub.events(item.topic))).mode;
1591
+ // Home covers every project's hub; Sessions only this project. Both ride the same pushed state event.
1592
+ const own = sessionCards(project, list, mode);
1593
+ const cardsById = new Map(own.map((card) => [card.id, card]));
1594
+ // Child sessions join their parent's subagents on the agent list only; the cards nest them already (sessionTree).
1595
+ const kids = childRuns(own);
1596
+ const hidden = hiddenProjects();
1597
+ const shown = [...projects.values()].filter(item => !hidden.has(item.cfg.project));
1598
+ // Another project's agents and cards, built once per snapshot: each reads that project's whole session registry.
1599
+ const otherAgents = new Map();
1600
+ const agentsOf = (item) => otherAgents.get(item) ?? otherAgents.set(item, agents(item, lastMessages(item))).get(item);
1601
+ const otherCards = new Map();
1602
+ const cardsOf = (item) => otherCards.get(item) ?? otherCards.set(item, sessionCards(item, agentsOf(item), mode)).get(item);
1603
+ const cards = scope === "home" ? shown.flatMap(item => item === project ? sessionCards(item, list, mode)
1604
+ : item.failed ? [] : cardsOf(item))
1605
+ : scope === "sessions" ? sessionCards(project, list, mode) : undefined;
1606
+ const runs = listRuns(project.cfg);
1607
+ const finished = finishedRuns(project);
1608
+ // Each agent's compactions, clears and model switches from the activity in memory; only the compactions view asks (history=1).
1609
+ const history = wantHistory ? sessionHistory(activityList(project)) : new Map();
1610
+ return {
1611
+ project: project.cfg.project, operator: project.operator.peer, mode, alerts: readAlertLevel(env),
1612
+ // Sessions per project as running and inactive, read by the sidebar rows; kept apart from projects. A session
1613
+ // whose worktree was deleted has no card, so it is not counted either.
1614
+ projectCounts: Object.fromEntries(shown.map(item => [item.cfg.project, sessionCounts(item === project ? own : item.failed ? [] : cardsOf(item))])),
1615
+ // Waiting counts per project, present only when above 0; a failed project has no sessions to count.
1616
+ projects: shown.map(item => {
1617
+ const count = item === project ? waiting.size : item.failed ? 0 : waitingIds(item, placed(agentsOf(item))).size;
1618
+ return { id: item.cfg.project, peers: item.cfg.peers, ...(isProjectPaused(item.cfg) ? { paused: true } : {}), ...(count ? { waiting: count } : {}) };
1619
+ }),
1620
+ // Registered projects marked closed, listed so the sidebar can reopen them.
1621
+ closedProjects: closedProjectNames(env).filter(name => !removed.has(name) && (!hosted || projects.has(name))),
1622
+ // Projects auto-joined from a session's repo have no projects.json entry, so Close and Delete do not apply.
1623
+ autoProjects: shown.map(item => item.cfg.project).filter(name => !readProjectsFile(env).some(entry => entry?.project === name)),
1624
+ view: { harness, session, ...(scope ? { scope } : {}) },
1625
+ ...runTerminal.snapshot(project.cfg, session),
1626
+ harnesses: harnesses(project, placed(list), last),
1627
+ // Unfinished subagent runs ride on each agent for the composer's @session/run picker.
1628
+ agents: list.map(agent => {
1629
+ const card = cardsById.get(agent.id);
1630
+ const subagents = [...(card?.subagents || []), ...(kids.get(agent.id) || [])];
1631
+ const owned = agent.peer === "claude" && agent.id === session ? readOwned(project.cfg, agent.session) : null;
1632
+ const modelControl = owned?.address === agent.id && ["idle", "running"].includes(owned.status)
1633
+ ? { current: owned.model || "", busy: owned.status === "running" } : null;
1634
+ const { lastActivityAt, openCallAt, turnStartAt, afkHold, pending, team, role } = card || {};
1635
+ // The runner's status for a session it holds; the UI offers Stop and End on it.
1636
+ const held = owned ?? readOwned(project.cfg, agent.session);
1637
+ const runnerStatus = held?.address === agent.id && held.status !== "ended" ? String(held.status) : "";
1638
+ // The held session's mode and place, so the Actions menu's /mode lists what the approval card's menu lists.
1639
+ const runnerMode = runnerStatus && typeof held.permissionMode === "string" ? { current: held.permissionMode, place: typeof held.place === "string" ? held.place : "folder" } : null;
1640
+ const base = { ...agent, ...(runnerStatus ? { runnerStatus } : {}), ...(runnerMode ? { runnerMode } : {}), lastActivityAt, openCallAt, turnStartAt, afkHold, pending, ...(team ? { team, role } : {}), ...(subagents.length ? { subagents } : {}),
1641
+ ...(finished.has(agent.id) ? { finishedSubagents: finished.get(agent.id) } : {}), ...(modelControl ? { modelControl } : {}) };
1642
+ // Context telemetry and instruction files from the session's state file (lib/usage.ts).
1643
+ const context = readContext({ stateDir: project.cfg.stateDir, project: project.cfg.project, peer: agent.peer, session: agent.session });
1644
+ const withContext = context.tokens !== null || context.files.length ? { ...base, context } : base;
1645
+ const withHistory = history.has(agent.id) ? { ...withContext, history: history.get(agent.id) } : withContext;
1646
+ return waiting.has(agent.id) ? { ...withHistory, waiting: true } : withHistory;
1647
+ }),
1648
+ messages: thread ? threadPosts(project, thread, list) : scope === "home" ? [] : messages(project, { harness, session }, list),
1649
+ ...(cards ? { sessions: cards } : {}),
1650
+ ...(scope === "home" ? {
1651
+ ...(!hosted ? { shipped: shown.flatMap(item => item.failed ? [] :
1652
+ shippedTasks(item.tasks, item.cfg.project, taskRoot(item))).sort((a, b) => b.at - a.at) } : {}),
1653
+ unavailable: shown.filter(item => item.failed).map(item => item.cfg.project),
1654
+ // Only the Recent progress view asks (progress=1), so Home's other views skip the scan.
1655
+ ...(wantProgress ? { progress: shown.flatMap(item => item.failed ? [] : progressPosts(item))
1656
+ .sort((a, b) => b.time - a.time).slice(0, MAX_PROGRESS) } : {})
1657
+ } : {}),
1658
+ // Every scope carries every shown project's decisions, so the bell counts them anywhere.
1659
+ decisions: shown.flatMap(item => item.failed ? [] : projectDecisions(item, item === project ? runs : listRuns(item.cfg), item === project ? list : cards ? cards.filter((card) => card.project === item.cfg.project) : agentsOf(item))),
1660
+ ...((scope === "home" ? shown.some(canLand) : canLand(project)) ? { landing } : {}),
1661
+ ...(hosted ? { hosted: true } : {}),
1662
+ // A tree other than main serves this UI (`temmo deploy --from`); the header shows a banner.
1663
+ ...(hosted ? {} : deployedField(env)),
1664
+ startable: startable(project),
1665
+ threads: project.threads?.list() || [],
1666
+ // The new-session default (defaults.json startDefault, else cursor on deepseek); the form prefills it when available.
1667
+ startDefault: startDefaultSetting(env),
1668
+ // The describe-a-team writer (TEMMO_TEAM_AUTHOR_MODEL, else cursor deepseek); the composer prefills it and can override it.
1669
+ authorDefault: authorModel(env),
1670
+ // Native code mode for new starts (defaults.json codeMode, default on); the composer prefills its toggle.
1671
+ codeModeDefault: codeModeDefault(env),
1672
+ startPlaces: startPlaces(project),
1673
+ // The configured start place (defaults.json startPlace) and the harnesses OpenShell can take; the composer preselects from both.
1674
+ startPlace: startPlaces(project).includes(startPlaceSetting(env)) ? startPlaceSetting(env) : "folder",
1675
+ openshellHarnesses: startPlaces(project).includes("openshell") ? openshellHarnesses(env) : [],
1676
+ teams: Object.entries(hosted ? {} : listTeams(project.cfg, env)).map(([id, members]) => ({ id, members })),
1677
+ patterns: hosted ? [] : patternRows(project.cfg, env),
1678
+ templates: teamTemplates(),
1679
+ runs: runs.slice(0, 20),
1680
+ tasks: taskBoard(project.tasks, list, runs, project.tasks ? listOwned(project.cfg) : [], hosted ? undefined : task => stoppedBuilder(project.cfg.project, task, env), project.tasks ? (task, sessions) => builderAssignment(project.cfg.project, task, sessions, env) : undefined, hosted ? undefined : { project: project.cfg.project, root: taskRoot(project) }),
1681
+ };
1682
+ }
1683
+ // Listed patterns for the Patterns page; removable marks the project's own patterns and teams (global teams stay in teams.json).
1684
+ function patternRows(cfg, env) {
1685
+ const removable = removableNames(cfg, env);
1686
+ return Object.values(listPatterns(cfg, env)).map((entry) => {
1687
+ const { name, source, legacy, invalid, description, roles, handoffs } = entry;
1688
+ return {
1689
+ name, source, legacy: legacy === true, removable: removable.has(name), ...(invalid ? { invalid } : {}), ...(description ? { description } : {}), roles, handoffs,
1690
+ ...(source !== "team" ? { dot: teamTextOf(entry) } : {}), ...(source === "project" ? { editable: true } : {}),
1691
+ // A team.dot team: the only kind /team-permission can rewrite.
1692
+ ...(entry.file ? { teamFile: true } : {}),
1693
+ };
1694
+ });
1695
+ }
1696
+ // One session's activity, or every allowed agent's for the project overview, oldest first.
1697
+ function activityList(project, session, events) {
1698
+ return scopedActivity(project, session, events).map(activityItem);
1699
+ }
1700
+ function scopedActivity(project, session, events = project.hub.events) {
1701
+ const { cfg } = project;
1702
+ return events(project.activity).filter((event) => {
1703
+ const item = activityItem(event);
1704
+ return item && (!cfg.peers.length || cfg.peers.includes(peerOf(item.agent))) && (!session || item.agent === session);
1705
+ });
1706
+ }
1707
+ // Activity travels as deltas: a reset with the full list, then only rows newer than the last one sent.
1708
+ function pushActivity(client) {
1709
+ if (!client.activity)
1710
+ return;
1711
+ const list = scopedActivity(client.project, client.session);
1712
+ const at = client.activitySent === undefined ? -1 : list.findIndex((item) => item.id === client.activitySent);
1713
+ const reset = at < 0 && !(client.activitySent === "" && list.length === 0);
1714
+ const items = reset ? list : list.slice(at + 1);
1715
+ if (!reset && !items.length)
1716
+ return;
1717
+ client.activitySent = list.at(-1)?.id ?? "";
1718
+ for (const item of items)
1719
+ client.send(activityFrame(item));
1720
+ client.send(buildEvent(EventType.CUSTOM, { name: ACTIVITY_BATCH, value: { reset } }));
1721
+ }
1722
+ // A2UI surfaces for the cards on screen: one ACTIVITY_SNAPSHOT per surface whose operations changed since the last push.
1723
+ function pushSurfaces(client, current) {
1724
+ const entries = [...(current.messages || []), ...(current.sessions || []).flatMap((card) => card.pending || [])];
1725
+ const sent = new Map();
1726
+ const now = Date.now();
1727
+ for (const surface of [...entries.map(entry => surfaceOf(entry, now) || prSurfaceOf(entry, now)), ...runTerminal.surfaces(current, now)]) {
1728
+ if (!surface || sent.has(surface.id))
1729
+ continue;
1730
+ const json = JSON.stringify(surface.operations);
1731
+ sent.set(surface.id, json);
1732
+ if (client.surfaces.get(surface.id) === json)
1733
+ continue;
1734
+ client.send(buildEvent(EventType.ACTIVITY_SNAPSHOT, {
1735
+ messageId: surface.id, activityType: A2UI_ACTIVITY, content: { a2ui_operations: surface.operations }, replace: true,
1736
+ }));
1737
+ }
1738
+ // Surfaces that left the screen are dropped, so a long connection does not grow the map.
1739
+ client.surfaces = sent;
1740
+ }
1741
+ // Surfaces go before the state frame: a client that stops reading at the state frame must not get frames after it.
1742
+ function push(client, views) {
1743
+ if (client.authorized && !client.authorized())
1744
+ return client.disconnect();
1745
+ const key = JSON.stringify([client.project.cfg.project, client.harness, client.session, client.scope, client.thread, client.history]);
1746
+ const current = views?.get(key) ?? snapshot(client);
1747
+ views?.set(key, current);
1748
+ client.hasQueuedMessages = Boolean(client.session && current.messages.some(item => item.queued));
1749
+ client.hasOpenTasks = current.tasks.tasks.some(task => task.status !== "done");
1750
+ client.hasReview = current.tasks.tasks.some(task => task.review && !task.review.decision);
1751
+ client.hasRunningJobs = current.agents.some(agent => agent.runningJobs) || current.sessions?.some((agent) => agent.runningJobs);
1752
+ pushSurfaces(client, current);
1753
+ const state = JSON.stringify(buildEvent(EventType.STATE_SNAPSHOT, { snapshot: current }));
1754
+ if (state !== client.last) {
1755
+ if (!client.last)
1756
+ client.write(`event: state\ndata: ${JSON.stringify(current)}\n\n`);
1757
+ client.last = state;
1758
+ client.write(`data: ${state}\n\n`);
1759
+ }
1760
+ pushActivity(client);
1761
+ }
1762
+ async function load(client) {
1763
+ const { project, harness, session } = client;
1764
+ const { hub } = project;
1765
+ try {
1766
+ const required = [project.status, project.topic];
1767
+ if (harness)
1768
+ required.push(inboxOf(project, harness));
1769
+ // The thread view reads its channel posts from the thread's own topic (docs/threads.md "Thread channels"); a session's direct chat does not.
1770
+ for (const id of new Set([client.thread].filter(Boolean))) {
1771
+ const topic = threadTopic(project.cfg.project, id);
1772
+ // The hub keeps a topic's subscription only while it is known, so a new post reaches the open view.
1773
+ known.add(topic);
1774
+ required.push(topic);
1775
+ }
1776
+ // Project and session chats need activity for typed prompts in their first snapshot.
1777
+ const activity = hub.open(project.activity, { tailBytes: ACTIVITY_TAIL_BYTES });
1778
+ const needsActivity = client.activity || client.scope || session || !harness;
1779
+ if (!needsActivity)
1780
+ activity.catch(() => { });
1781
+ // Other inboxes feed last-message times and receipts feed ticks; a failure is tolerated. Opening all at once lets the hub subscribe once.
1782
+ const optional = Promise.allSettled([project.receipts, ...project.inboxes.values()].filter(name => !required.includes(name)).map(name => hub.open(name)));
1783
+ const opened = await Promise.allSettled([...required.map(name => hub.open(name)), ...(needsActivity ? [activity] : [])]);
1784
+ const failed = opened.find(result => result.status === "rejected");
1785
+ if (failed && ![project.topic, project.activity, ...project.inboxes.values()].some(name => hub.history.events(name, 1).length))
1786
+ throw failed.reason;
1787
+ await optional;
1788
+ // Home needs status, broadcast and activity of every other project; one that fails is listed as unavailable.
1789
+ if (client.scope === "home") {
1790
+ await Promise.all([...projects.values()].filter(item => item !== project).map(async (item) => {
1791
+ const opened = await Promise.allSettled([item.status, item.topic, item.activity].map(name => item.hub.open(name, name === item.activity ? { tailBytes: ACTIVITY_TAIL_BYTES } : undefined)));
1792
+ item.failed = opened.some(result => result.status === "rejected");
1793
+ }));
1794
+ }
1795
+ client.ready = true;
1796
+ push(client);
1797
+ }
1798
+ catch (err) {
1799
+ client.send(buildEvent(EventType.CUSTOM, { name: STREAM_ERROR, value: { error: failure(err).message } }));
1800
+ }
1801
+ }
1802
+ function view(url) {
1803
+ const project = projectFor(url.searchParams.get("project"));
1804
+ const { cfg } = project;
1805
+ const session = url.searchParams.get("session") || "";
1806
+ let harness = url.searchParams.get("harness") || "";
1807
+ if (session)
1808
+ harness = recipient(cfg, session, true);
1809
+ else if (harness && (!isValidName(harness) || harness === "all" || harness === "operator" ||
1810
+ (cfg.peers.length && !cfg.peers.includes(harness))))
1811
+ reject(400, "Unknown harness");
1812
+ // view=activity adds the activity stream: one session's, or the project overview without a session.
1813
+ const mode = url.searchParams.get("view");
1814
+ // view=home adds every project's session cards; view=sessions this project's.
1815
+ const scope = mode === "home" || mode === "sessions" ? mode : "";
1816
+ // thread=<id> makes the feed that thread's channel posts (docs/threads.md "Thread view").
1817
+ const thread = url.searchParams.get("thread") || "";
1818
+ if (thread && !THREAD_ID.test(thread))
1819
+ reject(400, "Unknown thread");
1820
+ return { project, harness: scope === "home" ? "" : harness, session: scope === "home" ? "" : session, activity: mode === "activity", scope, thread, history: url.searchParams.get("history") === "1", progress: scope === "home" && url.searchParams.get("progress") === "1" };
1821
+ }
1822
+ // GET /api/land: the open PRs into main with their checks, and the last deploy result.
1823
+ async function landApi(request) {
1824
+ try {
1825
+ caller(request);
1826
+ if (hosted)
1827
+ reject(403, "Landing is unavailable in hosted mode");
1828
+ return json(200, { prs: await land.list(), deploy: await land.lastDeploy(env) });
1829
+ }
1830
+ catch (err) {
1831
+ return json(err.status || 502, { error: err.message });
1832
+ }
1833
+ }
1834
+ // The signed-in GitHub user, or a 401 while sign-in is on; null while it is off.
1835
+ function caller(request) {
1836
+ if (!auth)
1837
+ return null;
1838
+ return auth.user(request) || reject(401, "Sign in with GitHub");
1839
+ }
1840
+ // /api/auth/<step>; without github.json only "me" answers, saying sign-in is off.
1841
+ async function authApi(request, step) {
1842
+ if (auth)
1843
+ return auth.route(request, step);
1844
+ return step === "me" ? json(200, { enabled: false, user: null }) : json(404, { error: "GitHub sign-in is not configured" });
1845
+ }
1846
+ function events(request) {
1847
+ let selected;
1848
+ try {
1849
+ caller(request);
1850
+ selected = view(new URL(request.url));
1851
+ }
1852
+ catch (err) {
1853
+ return json(err.status || 400, { error: err.message });
1854
+ }
1855
+ let client;
1856
+ let keepalive;
1857
+ const close = () => {
1858
+ clearInterval(keepalive);
1859
+ clients.delete(client);
1860
+ };
1861
+ const body = new ReadableStream({
1862
+ start(controller) {
1863
+ client = {
1864
+ ...selected, ready: false, last: "", surfaces: new Map(),
1865
+ ...(hosted ? {
1866
+ authorized: () => Boolean(auth.user(request)),
1867
+ disconnect() { if (clients.has(client))
1868
+ client.end(); },
1869
+ } : {}),
1870
+ end() {
1871
+ close();
1872
+ try {
1873
+ controller.close();
1874
+ }
1875
+ catch { /* already closed or cancelled */ }
1876
+ },
1877
+ send(event) { this.write(`data: ${JSON.stringify(event)}\n\n`); },
1878
+ write(text) {
1879
+ try {
1880
+ controller.enqueue(encoder.encode(text));
1881
+ }
1882
+ catch {
1883
+ close();
1884
+ }
1885
+ },
1886
+ };
1887
+ clients.add(client);
1888
+ keepalive = setInterval(() => {
1889
+ if (client.authorized && !client.authorized())
1890
+ return client.disconnect();
1891
+ client.write(": keepalive\n\n");
1892
+ // A process can exit without a task or job registry write, and a build review shows a branch that can move.
1893
+ // Home also picks up merges that move origin/main without changing a task.
1894
+ // A local delivery claim can complete without a receipt or registry update.
1895
+ if (client.ready && (client.hasQueuedMessages || client.hasRunningJobs || client.hasOpenTasks || client.hasReview || (!hosted && client.scope === "home")) && clients.has(client))
1896
+ push(client);
1897
+ }, KEEPALIVE_MS);
1898
+ keepalive.unref?.();
1899
+ // An aborted request also ends the body, so a reader of the stream sees it finish instead of waiting forever.
1900
+ request.signal?.addEventListener("abort", () => {
1901
+ close();
1902
+ try {
1903
+ controller.close();
1904
+ }
1905
+ catch { /* already closed or cancelled */ }
1906
+ }, { once: true });
1907
+ void load(client);
1908
+ },
1909
+ cancel: close,
1910
+ });
1911
+ return new Response(body, {
1912
+ headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store, no-transform", "X-Accel-Buffering": "no" },
1913
+ });
1914
+ }
1915
+ // The archive endpoint remains usable while transport is down.
1916
+ function history(request, by, body) {
1917
+ const { project, harness, session } = view(new URL(request.url));
1918
+ if (typeof body.query !== "string" || body.query.length > 200)
1919
+ reject(400, "Invalid search query");
1920
+ if (hiddenProjects().has(project.cfg.project))
1921
+ reject(404, "Project is closed");
1922
+ const store = project.hub.history;
1923
+ const conversation = JSON.stringify([project.cfg.project, harness, session]);
1924
+ const reader = by?.toLowerCase() || "";
1925
+ const topics = new Map();
1926
+ const sequences = new Map();
1927
+ function events(topic) {
1928
+ if (!topics.has(topic)) {
1929
+ const rows = store.events(topic);
1930
+ for (const row of rows)
1931
+ sequences.set(row.id, row.sequence);
1932
+ topics.set(topic, rows);
1933
+ }
1934
+ return topics.get(topic);
1935
+ }
1936
+ const list = messages(project, { harness, session }, agents(project, lastMessages(project)), { events, archived: true });
1937
+ const incoming = new Map(list.filter(item => item.from !== "operator" && !item.system && item.kind !== "Reply")
1938
+ .map(item => [item.id, sequences.get(item.id)]));
1939
+ const query = body.query.trim().toLowerCase();
1940
+ const matches = list.filter(item => !query || [item.body, item.sender, item.attachment?.name]
1941
+ .some(value => typeof value === "string" && value.toLowerCase().includes(query)));
1942
+ const before = body.before === undefined ? matches.length : matches.findIndex(item => item.id === body.before);
1943
+ if (before < 0)
1944
+ reject(400, "Unknown history cursor");
1945
+ if (body.read !== undefined) {
1946
+ const sequence = incoming.get(body.read);
1947
+ if (!sequence)
1948
+ reject(400, "Unknown message");
1949
+ store.mark(conversation, reader, sequence);
1950
+ }
1951
+ const position = store.position(conversation, reader);
1952
+ let unread = 0;
1953
+ let newest = 0;
1954
+ let latest;
1955
+ for (const [id, sequence] of incoming) {
1956
+ if (sequence > position)
1957
+ unread++;
1958
+ if (sequence > newest) {
1959
+ newest = sequence;
1960
+ latest = id;
1961
+ }
1962
+ }
1963
+ const page = matches.slice(Math.max(0, before - 50), before).reverse();
1964
+ return json(200, { messages: page, next: before > 50 ? page.at(-1).id : null, unread, latest });
1965
+ }
1966
+ /**
1967
+ * The submitted build's changes as plain text, read from the project checkout for the packet named in the query.
1968
+ * The commit and base come from the stored packet, never the request, so a URL cannot ask for an arbitrary diff.
1969
+ */
1970
+ async function reviewDiff(request) {
1971
+ try {
1972
+ caller(request);
1973
+ if (hosted)
1974
+ reject(403, "Build reviews are unavailable in hosted mode");
1975
+ const query = new URL(request.url).searchParams;
1976
+ const project = projectFor(query.get("project"));
1977
+ const id = query.get("id");
1978
+ const task = project.tasks && typeof id === "string" ? project.tasks.list().find((item) => item.id === id) : undefined;
1979
+ const review = task?.review;
1980
+ if (!review || review.submission !== query.get("submission"))
1981
+ reject(404, "Review packet unavailable");
1982
+ const root = taskRoot(project);
1983
+ if (!root)
1984
+ reject(409, "The project checkout is unavailable");
1985
+ const diff = await diffRange(root, review.base, review.commit);
1986
+ return new Response(diff, { headers: {
1987
+ "Content-Type": "text/plain; charset=utf-8",
1988
+ "X-Content-Type-Options": "nosniff",
1989
+ "Cache-Control": "no-store",
1990
+ } });
1991
+ }
1992
+ catch (err) {
1993
+ return json(err.status || 400, { error: err.message });
1994
+ }
1995
+ }
1996
+ /**
1997
+ * A thread's changes as plain text: its worktree against the merge-base with its base ref, uncommitted edits and
1998
+ * untracked files included.
1999
+ * The worktree must be one git lists for the project checkout, so a stored path cannot point the diff elsewhere.
2000
+ */
2001
+ async function threadDiff(request) {
2002
+ try {
2003
+ caller(request);
2004
+ if (hosted)
2005
+ reject(403, "Thread diffs are unavailable in hosted mode");
2006
+ const query = new URL(request.url).searchParams;
2007
+ const project = projectFor(query.get("project"));
2008
+ const id = query.get("thread") ?? "";
2009
+ if (!THREAD_ID.test(id))
2010
+ reject(400, "Invalid thread id");
2011
+ const thread = project.threads?.list().find((item) => item.id === id);
2012
+ if (!thread)
2013
+ reject(404, "Thread unavailable");
2014
+ const root = taskRoot(project);
2015
+ if (!root)
2016
+ reject(409, "The project checkout is unavailable");
2017
+ const gitFile = findExecutable("git", env.PATH);
2018
+ if (!gitFile)
2019
+ reject(409, "git is not installed");
2020
+ const run = gitRunner(gitFile, env);
2021
+ const listed = parseWorktreeList((await run(["worktree", "list", "--porcelain"], root)).stdout).map(row => row.path);
2022
+ const tree = thread.worktree || root;
2023
+ if (!listed.includes(tree))
2024
+ reject(409, "The thread's worktree is not part of the project checkout");
2025
+ let base = "";
2026
+ for (const ref of [thread.baseRef, ...THREAD_BASES]) {
2027
+ if (!ref || refInputError(ref, "base"))
2028
+ continue;
2029
+ const found = await run(["merge-base", "--end-of-options", ref, "HEAD"], tree);
2030
+ if (found.code === 0 && found.stdout.trim()) {
2031
+ base = found.stdout.trim();
2032
+ break;
2033
+ }
2034
+ }
2035
+ if (!base)
2036
+ reject(409, "No base ref resolves for this thread");
2037
+ const { stdout } = await runFile(gitFile, ["diff", "--no-ext-diff", "--no-textconv", base, "--"], { cwd: tree, env, timeout: 10_000, maxBuffer: DIFF_MAX_BYTES }).catch(() => reject(422, "The thread diff is unavailable or larger than 4 MiB"));
2038
+ const added = await untrackedDiff(gitFile, tree, env, { fileBytes: UNTRACKED_FILE_BYTES, totalBytes: DIFF_MAX_BYTES - Buffer.byteLength(stdout) });
2039
+ return new Response(stdout + added, { headers: {
2040
+ "Content-Type": "text/plain; charset=utf-8",
2041
+ "X-Content-Type-Options": "nosniff",
2042
+ "Cache-Control": "no-store",
2043
+ } });
2044
+ }
2045
+ catch (err) {
2046
+ return json(err.status || 400, { error: err.message });
2047
+ }
2048
+ }
2049
+ // Branches or worktrees of the project checkout for the start toolbar, filtered and capped here; "#123" adds that PR's head.
2050
+ async function refs(request) {
2051
+ try {
2052
+ caller(request);
2053
+ if (hosted)
2054
+ reject(403, "Branches are unavailable in hosted mode");
2055
+ const query = new URL(request.url).searchParams;
2056
+ const project = projectFor(query.get("project"));
2057
+ const kind = query.get("kind") ?? "branches";
2058
+ if (!REF_KINDS.includes(kind))
2059
+ reject(400, "kind must be branches or worktrees");
2060
+ const q = (query.get("q") ?? "").trim();
2061
+ if (q.length > REF_NAME_MAX)
2062
+ reject(400, "The search is too long");
2063
+ const root = taskRoot(project);
2064
+ if (!root)
2065
+ reject(409, "The project checkout is unavailable");
2066
+ const gitFile = findExecutable("git", env.PATH);
2067
+ if (!gitFile)
2068
+ reject(409, "git is not installed");
2069
+ const run = gitRunner(gitFile, env);
2070
+ if (kind === "worktrees")
2071
+ return json(200, await listWorktrees(run, root, { query: q }));
2072
+ const ghFile = findExecutable("gh", env.PATH);
2073
+ const pr = PR_QUERY.exec(q);
2074
+ const listed = await listBranches(run, root, { query: pr ? "" : q });
2075
+ return json(200, { ...listed, gh: Boolean(ghFile), pr: ghFile && pr ? await prHead(ghFile, run, root, Number(pr[1]), env) : null });
2076
+ }
2077
+ catch (err) {
2078
+ return json(err.status || 400, { error: err.message });
2079
+ }
2080
+ }
2081
+ async function handle(request, action) {
2082
+ try {
2083
+ if (request.method !== "POST" || !ACTIONS.includes(action))
2084
+ reject(404, "Unknown route");
2085
+ const by = caller(request)?.login;
2086
+ if (hosted && !HOSTED_ACTIONS.has(action))
2087
+ reject(403, "This action is unavailable in hosted mode");
2088
+ assertSameOrigin(request, allowedOrigin);
2089
+ const contentType = request.headers.get("content-type")?.split(";")[0].trim();
2090
+ const upload = action === "send" && contentType === "multipart/form-data";
2091
+ if (!upload && contentType !== "application/json")
2092
+ reject(415, "JSON required");
2093
+ if (action === "history")
2094
+ return history(request, by, await payload(request));
2095
+ const { input, attachment } = upload ? await imagePayload(request) : { input: await payload(request) };
2096
+ const { project: name, paused, target, body, queueAction, question, mode, level: alertLevel, id, status: taskStatus, decision, answers, harness, prompt, place, worktree, openshell, base, branch, worktreePath, urgent, sendAnyway, model, startMode, codeMode, permission, team: teamName, members, editTeam, delete: deleteTeamName, replyTo, quote, command, pattern: patternSpec, deletePattern: deletePatternName, copyPattern: copyPatternName, replace: replacePatternName, checkDot, teamDot, teamNew, startPattern, task: patternTask, advanceRun: advanceRunId, advanceEvent, advanceNote, advanceConfirmation, authorRequest, authorDot, authorScope, authorCurrent, authorTurns, authorHarness, authorModel: authorModelName, authorReplace, forwardedProps, answer: decisionText, commit, submission, note: reviewNote, taskId } = input;
2097
+ // Merges one PR whose checks are green at the head the operator reviewed, then starts deploy detached.
2098
+ if (action === "land") {
2099
+ const number = input.number;
2100
+ const headSha = typeof input.headSha === "string" ? input.headSha : "";
2101
+ if (!Number.isInteger(number) || number < 1 || !/^[0-9a-f]{40}$/.test(headSha))
2102
+ reject(400, "Give the PR number and its head commit");
2103
+ try {
2104
+ await land.merge(number, headSha);
2105
+ }
2106
+ catch (err) {
2107
+ reject(err instanceof LandRefused ? 409 : 502, err.message);
2108
+ }
2109
+ const deploy = await land.startDeploy().then(() => "deploy started", err => "deploy not started: " + err.message);
2110
+ return json(201, { status: "Merged", detail: `#${number} merged; ${deploy}` });
2111
+ }
2112
+ // Pushes a thread's branch and opens its ready-for-review PR into main (or reuses the open one), then attaches the PR to the thread.
2113
+ // The optional proof is the commands run and their output; it goes in the PR body.
2114
+ if (action === "create-pr") {
2115
+ if (hosted)
2116
+ reject(403, "Pull requests are unavailable in hosted mode");
2117
+ const project = projectFor(name);
2118
+ const id = typeof input.thread === "string" ? input.thread : "";
2119
+ if (!THREAD_ID.test(id))
2120
+ reject(400, "Invalid thread id");
2121
+ const thread = project.threads?.list().find((item) => item.id === id);
2122
+ if (!thread)
2123
+ reject(404, "Thread unavailable");
2124
+ if (!thread.branch || !thread.worktree)
2125
+ reject(409, "This thread has no branch to open a PR from");
2126
+ if (input.proof !== undefined && typeof input.proof !== "string")
2127
+ reject(400, "proof must be text");
2128
+ let opened;
2129
+ try {
2130
+ opened = await land.open(thread.branch, thread.worktree, input.proof ?? undefined);
2131
+ }
2132
+ catch (err) {
2133
+ reject(err instanceof LandRefused ? 409 : 502, err.message);
2134
+ }
2135
+ const number = Number(opened.url.split("/").pop());
2136
+ if (!thread.prs?.some((pr) => pr.number === number)) {
2137
+ await project.threads.handle({ op: "attach-pr", thread: id, pr: { number, url: opened.url, head: thread.branch, base: "main", state: "open" } });
2138
+ }
2139
+ return json(201, { status: opened.created ? "PR opened" : "PR exists", detail: opened.url, url: opened.url });
2140
+ }
2141
+ if (action === "afk") {
2142
+ if (!MODES.includes(mode))
2143
+ reject(400, "Mode must be on, off, or quiet");
2144
+ await setMode([...projects.values()].map(item => item.cfg), mode, by);
2145
+ return json(201, { status: "AFK " + mode, detail: "Sent to " + projects.size + (projects.size === 1 ? " project" : " projects") });
2146
+ }
2147
+ // Close hides a project from the sidebar and Home; Delete drops its registry entry only (repo, worktrees, message history stay).
2148
+ if (action === "close" || action === "reopen") {
2149
+ setProjectClosed(env, name, action === "close");
2150
+ return json(200, { status: action === "close" ? "Closed" : "Reopened", detail: name });
2151
+ }
2152
+ if (action === "alerts") {
2153
+ writeAlertLevel(env, alertLevel);
2154
+ // The level rides the state snapshot, so push one: an open tab must show the new level without waiting for
2155
+ // some later message to refresh it. Without this, the choice looks lost until the next unrelated event.
2156
+ broadcast();
2157
+ return json(200, { status: "Alerts " + alertLevel, detail: alertLevel });
2158
+ }
2159
+ if (action === "delete") {
2160
+ removeProject(env, name);
2161
+ removed.add(name);
2162
+ return json(200, { status: "Deleted", detail: name });
2163
+ }
2164
+ if (action === "land-reviews") {
2165
+ if (landing.running)
2166
+ reject(409, "A review batch is already running");
2167
+ const hidden = hiddenProjects();
2168
+ const targets = [...projects].filter(([id, item]) => (name === undefined || id === name) && !hidden.has(id) && canLand(item))
2169
+ .map(([name, item]) => ({ name, tasks: item.tasks }));
2170
+ if (!targets.length)
2171
+ reject(403, "Select a project registered to the PM checkout");
2172
+ landing = { running: true, receipts: [] };
2173
+ broadcast();
2174
+ landReviews(targets, {
2175
+ by: by ? `operator:${by}` : "operator",
2176
+ merge: review => runMergeReview(review, env),
2177
+ onReceipt(result) {
2178
+ landing.receipts.push(result);
2179
+ broadcast();
2180
+ },
2181
+ }).catch(error => { landing.error = error.message; }).finally(() => {
2182
+ landing.running = false;
2183
+ landing.finished = true;
2184
+ broadcast();
2185
+ });
2186
+ return json(202, { status: "Landing reviews" });
2187
+ }
2188
+ const project = projectFor(name);
2189
+ const { cfg, operator, topic } = project;
2190
+ if (action === "thread") {
2191
+ if (!project.threads)
2192
+ reject(403, "Threads are unavailable here");
2193
+ return json(200, await project.threads.handle(input));
2194
+ }
2195
+ if (action === "project-pause") {
2196
+ if (!projects.has(name))
2197
+ reject(400, "Select a project");
2198
+ if (typeof paused !== "boolean")
2199
+ reject(400, "paused must be true or false");
2200
+ setProjectPaused(cfg, paused);
2201
+ broadcast();
2202
+ return json(200, { status: paused ? "New work paused" : "New work resumed" });
2203
+ }
2204
+ if (["start", "continue-builder", "recover-builder"].includes(action) && isProjectPaused(cfg))
2205
+ reject(409, PROJECT_PAUSED);
2206
+ if (action === "approve")
2207
+ return json(201, await answerApproval(project, id, { decision, answers }, by));
2208
+ if (action === "skip")
2209
+ return json(201, await skipDecision(project, { id, taskId }, by));
2210
+ if (action === "continue-builder") {
2211
+ if (!startable(project).includes(harness))
2212
+ reject(400, "Select an available harness");
2213
+ const result = await runner({ socket: runnerSocket(env), timeoutMs: 120_000 })
2214
+ .continueBuilder({ project: name, taskId: id, harness })
2215
+ .catch(() => reject(503, "The session runner is unavailable"));
2216
+ if (result.status !== 201)
2217
+ reject(result.status, result.body.error || "The runner refused the continuation");
2218
+ broadcast();
2219
+ return json(201, result.body);
2220
+ }
2221
+ if (action === "recover-builder") {
2222
+ if (!project.tasks || typeof id !== "string")
2223
+ reject(400, "Give the task id");
2224
+ try {
2225
+ await recoverBuilder(cfg.project, id, harness, () => listOwned(cfg), env);
2226
+ }
2227
+ catch (err) {
2228
+ reject(409, err.message);
2229
+ }
2230
+ broadcast();
2231
+ return json(201, { status: "Builder started", detail: id });
2232
+ }
2233
+ if (["request-outcome", "approve-outcome", "accept-outcome"].includes(action)) {
2234
+ if (!project.tasks)
2235
+ reject(400, "Select a project with a task store");
2236
+ const step = action.split("-")[0];
2237
+ if (step === "approve" && isProjectPaused(cfg))
2238
+ reject(409, PROJECT_PAUSED);
2239
+ let outcome;
2240
+ try {
2241
+ outcome = await project.tasks.outcome(step, input);
2242
+ }
2243
+ catch (err) {
2244
+ reject(step === "request" ? 400 : 409, err.message);
2245
+ }
2246
+ broadcast();
2247
+ return json(step === "request" ? 201 : 200, { outcome });
2248
+ }
2249
+ if (action === "move-task") {
2250
+ if (!project.tasks || typeof id !== "string" || !STATUSES.includes(taskStatus))
2251
+ reject(400, "Give a task id and valid status");
2252
+ try {
2253
+ await project.tasks.update(id, { status: taskStatus });
2254
+ }
2255
+ catch (err) {
2256
+ reject(400, err.message);
2257
+ }
2258
+ broadcast();
2259
+ return json(200, { status: "Task moved", detail: id });
2260
+ }
2261
+ // The operator's verdict on a build: accept finishes the task at that commit, return queues it with a note.
2262
+ if (action === "review") {
2263
+ if (!project.tasks || typeof id !== "string" || !REVIEW_ACTIONS.includes(decision))
2264
+ reject(400, "Invalid build review request");
2265
+ if (typeof commit !== "string" || typeof submission !== "string")
2266
+ reject(400, "The review packet is missing its commit");
2267
+ // The branch tip is read fresh inside decideReview: a stale read could accept a build the branch has left.
2268
+ try {
2269
+ await project.tasks.decideReview(id, {
2270
+ commit, submission, action: decision, note: typeof reviewNote === "string" ? reviewNote.trim() : "",
2271
+ by: by ? `operator:${by}` : "operator", root: taskRoot(project),
2272
+ });
2273
+ }
2274
+ catch (err) {
2275
+ reject(409, err.message);
2276
+ }
2277
+ broadcast();
2278
+ return json(201, { status: decision === "accept" ? "Build accepted" : "Build returned", detail: id });
2279
+ }
2280
+ // The next agent run reads the operator's answer from the task store.
2281
+ if (action === "decide") {
2282
+ if (!project.tasks)
2283
+ reject(400, "This project has no task store");
2284
+ const text = typeof decisionText === "string" ? decisionText.trim() : "";
2285
+ if (typeof id !== "string" || !text)
2286
+ reject(400, "Give the task id and an answer");
2287
+ try {
2288
+ await project.tasks.update(id, { answer: { text, by: by ? `operator:${by}` : "operator" } });
2289
+ }
2290
+ catch (err) {
2291
+ reject(400, err.message);
2292
+ }
2293
+ return json(201, { status: "Decided", detail: id });
2294
+ }
2295
+ // AG-UI run input from an A2UI surface: its userAction is the answer, mapped onto the approval or question reply path.
2296
+ if (action === "a2ui") {
2297
+ const run = runTerminal.answer(cfg, forwardedProps?.a2uiAction?.userAction, by);
2298
+ if (run)
2299
+ return json(201, run);
2300
+ const pr = prAnswer(forwardedProps?.a2uiAction?.userAction);
2301
+ if (pr)
2302
+ return json(201, await openPrRequest(project, pr, by));
2303
+ const answer = surfaceAnswer(forwardedProps?.a2uiAction?.userAction);
2304
+ if (!answer)
2305
+ reject(400, "Unknown answer");
2306
+ return json(201, await answerSurface(project, answer, by));
2307
+ }
2308
+ if (action === "models")
2309
+ return json(200, await models(cfg.stateDir, env, { peers: cfg.peers }));
2310
+ if (action === "team") {
2311
+ if (deleteTeamName) {
2312
+ return json(201, deleteTeam(cfg, String(deleteTeamName), env));
2313
+ }
2314
+ if (!teamName || !Array.isArray(members) || !members.length)
2315
+ reject(400, "Enter a team name and at least one member");
2316
+ const modelList = await models(cfg.stateDir, env, { peers: cfg.peers });
2317
+ return json(201, await createTeam(cfg, String(teamName), members.map(String), env, modelList));
2318
+ }
2319
+ if (action === "pattern") {
2320
+ // The team editor: checkDot parses team.dot for its live preview (no write); teamDot saves it as the project's team file.
2321
+ if (checkDot !== undefined)
2322
+ return json(200, checkTeamText(cfg, String(teamName ?? ""), String(checkDot)));
2323
+ if (teamDot !== undefined) {
2324
+ const modelList = await models(cfg.stateDir, env, { peers: cfg.peers });
2325
+ return json(201, await saveTeamText(cfg, String(teamName ?? ""), String(teamDot), env, modelList, { create: teamNew === true }).catch((error) => reject(400, error.message)));
2326
+ }
2327
+ if (editTeam === true) {
2328
+ if (!teamName || !Array.isArray(members) || !members.length || members.some(member => typeof member !== "string")) {
2329
+ reject(400, "Enter a team name and at least one member");
2330
+ }
2331
+ const modelList = await models(cfg.stateDir, env, { peers: cfg.peers });
2332
+ const saved = await createTeam(cfg, String(teamName), members, env, modelList, { edit: true })
2333
+ .catch((error) => reject(400, error.message));
2334
+ broadcast();
2335
+ return json(201, saved);
2336
+ }
2337
+ if (deletePatternName)
2338
+ return json(201, removePattern(cfg, String(deletePatternName), env));
2339
+ // Team author: one writing-agent turn from the operator's chat text, then a save of the DOT it drafted.
2340
+ if (authorRequest !== undefined) {
2341
+ // The composer picks the writer. An unknown harness or model is refused here, before the process starts.
2342
+ const writerHarness = authorHarness ? String(authorHarness) : "";
2343
+ const writerModel = authorModelName ? String(authorModelName) : "";
2344
+ if (writerHarness && (!START_HARNESSES.includes(writerHarness) || !startable(project).includes(writerHarness))) {
2345
+ reject(400, "That harness is not available for this project");
2346
+ }
2347
+ if (writerModel) {
2348
+ const forHarness = writerHarness || authorModel(env).harness;
2349
+ const listed = await models(cfg.stateDir, env, { peers: cfg.peers });
2350
+ if (!listed[forHarness]?.includes(writerModel))
2351
+ reject(400, "That model is not available for this harness");
2352
+ }
2353
+ const drafted = await authorTeam(cfg, {
2354
+ request: String(authorRequest ?? ""), name: String(teamName ?? ""), scope: String(authorScope ?? "project"),
2355
+ current: String(authorCurrent ?? ""), turns: Array.isArray(authorTurns) ? authorTurns : [], peers: cfg.peers, startable: startable(project), env,
2356
+ ...(writerHarness ? { harness: writerHarness } : {}), ...(writerModel ? { model: writerModel } : {}),
2357
+ }).catch((error) => reject(400, error.message));
2358
+ return json(201, drafted);
2359
+ }
2360
+ if (authorDot !== undefined) {
2361
+ // The operator confirmed the name: save the draft, replacing an entry only when authorReplace names it.
2362
+ const saved = await saveAuthoredTeam(cfg, {
2363
+ name: String(teamName ?? ""), dot: String(authorDot), scope: String(authorScope ?? "project"),
2364
+ replace: authorReplace === undefined || authorReplace === null ? "" : String(authorReplace),
2365
+ env, models: await models(cfg.stateDir, env, { peers: cfg.peers }),
2366
+ }).catch((error) => reject(400, error.message));
2367
+ return json(201, saved);
2368
+ }
2369
+ if (copyPatternName)
2370
+ return json(201, await copyPattern(cfg, String(copyPatternName), env, await models(cfg.stateDir, env, { peers: cfg.peers })).catch((error) => reject(400, error.message)));
2371
+ if (startPattern) {
2372
+ if (isProjectPaused(cfg))
2373
+ reject(409, PROJECT_PAUSED);
2374
+ const started = await startRun(cfg, String(startPattern), String(patternTask ?? ""), env, { start, models: await models(cfg.stateDir, env, { peers: cfg.peers }) })
2375
+ .catch((error) => reject(400, error.message));
2376
+ return json(201, started);
2377
+ }
2378
+ // Operator override: the run's active role need not be the caller; the handoff records the operator's login.
2379
+ if (advanceRunId) {
2380
+ const advanced = await advanceRun(cfg, String(advanceRunId), String(advanceEvent ?? ""), { note: String(advanceNote ?? ""), override: true, confirmation: String(advanceConfirmation ?? ""), by: by ?? "operator", env, start })
2381
+ .catch((error) => reject(400, error.message));
2382
+ broadcast();
2383
+ return json(201, advanced);
2384
+ }
2385
+ // replace names the pattern the editor opened; a different name in patternSpec renames it.
2386
+ const replace = replacePatternName === undefined || replacePatternName === null ? "" : String(replacePatternName);
2387
+ return json(201, await savePattern(cfg, patternSpec, { replace }, env, await models(cfg.stateDir, env, { peers: cfg.peers })));
2388
+ }
2389
+ if (action === "start") {
2390
+ if (!startable(project).includes(harness))
2391
+ reject(400, "That harness is not available for this project");
2392
+ // The UI sends worktree / openshell booleans; place is the same choice by name.
2393
+ if (worktree === true && openshell === true)
2394
+ reject(400, "Pick a worktree or openshell, not both");
2395
+ const named = place ?? (worktree === true ? "worktree" : openshell === true ? "openshell" : undefined);
2396
+ if (named !== undefined && !startPlaces(project).includes(named))
2397
+ reject(400, "That start place is not available for this project");
2398
+ // A start in a thread runs in the thread's worktree as a folder start (docs/threads.md).
2399
+ const inThread = project.threads ? await project.threads.startIn(input.thread) : null;
2400
+ if (inThread && named !== undefined && named !== "folder")
2401
+ reject(400, "A start in a thread runs in the thread's worktree; drop the place");
2402
+ if (inThread && codeMode === true)
2403
+ reject(400, "A start in a thread cannot use code mode yet");
2404
+ // A start in a thread takes the default place like a tag posted there: OpenShell on the thread's worktree when
2405
+ // the project and harness offer it, else a folder start on the host.
2406
+ const preferred = defaultStartPlace(startPlaces(project), harness, env);
2407
+ const where = inThread ? (preferred === "openshell" ? "openshell" : "folder") : named ?? preferred;
2408
+ if (where === "openshell" && !openshellHarnesses(env).includes(harness))
2409
+ reject(400, `${harness} cannot start in OpenShell yet; pick Folder or Worktree`);
2410
+ const pick = pickOf({ base, branch, worktreePath });
2411
+ if (Object.keys(pick).length && where !== "worktree")
2412
+ reject(400, "base, branch and worktreePath need place worktree");
2413
+ if (Object.keys(pick).length) {
2414
+ const root = taskRoot(project);
2415
+ if (!root)
2416
+ reject(409, "The project checkout is unavailable");
2417
+ const picked = await pickedWorktree(root, pick, env);
2418
+ if (picked.error)
2419
+ reject(400, picked.error);
2420
+ }
2421
+ const checked = checkPrompt(prompt);
2422
+ if (checked.error)
2423
+ reject(400, checked.error);
2424
+ const chosen = model === undefined || model === null || model === "" ? undefined : model;
2425
+ if (chosen !== undefined && (typeof chosen !== "string" || !(await models(cfg.stateDir, env, { peers: cfg.peers }))[harness]?.includes(chosen))) {
2426
+ reject(400, "That model is not available for this harness");
2427
+ }
2428
+ // The dialogue's Agent / Ask / Plan pill; an unnamed mode is the harness's normal, editing one.
2429
+ const chosenMode = startMode === undefined || startMode === null || startMode === "" ? "agent" : startMode;
2430
+ if (typeof chosenMode !== "string" || !startModes(harness).includes(chosenMode))
2431
+ reject(400, "That mode is not available for this harness");
2432
+ if (codeMode !== undefined && codeMode !== null && typeof codeMode !== "boolean")
2433
+ reject(400, "codeMode must be true or false");
2434
+ if (harness === "claude" && codeMode === true && (chosenMode !== "agent" || where === "openshell")) {
2435
+ reject(400, "Claude code mode requires Agent mode in a folder or worktree");
2436
+ }
2437
+ // --permission on a start: a Claude permission mode for this launch only (the same check as the runner's).
2438
+ const permissionChosen = permission === undefined || permission === null || permission === "" ? undefined : permission;
2439
+ if (permissionChosen !== undefined) {
2440
+ if (harness !== "claude")
2441
+ reject(400, "permission applies to Claude starts only");
2442
+ const named = claudePermissionFor(harness, cfg, env, { sandboxed: where === "openshell", setting: permissionChosen });
2443
+ if (named.error)
2444
+ reject(400, named.error);
2445
+ if (codeMode === true)
2446
+ reject(400, "A code-mode start runs supervised; drop permission or code mode");
2447
+ if (where === "openshell")
2448
+ reject(400, "An OpenShell start runs full-access; drop permission or pick folder or worktree");
2449
+ }
2450
+ if (Date.now() - lastStartAt < START_GAP_MS)
2451
+ reject(429, "Wait 10 seconds between starts");
2452
+ lastStartAt = Date.now();
2453
+ const threadTree = inThread?.worktree && inThread.worktree !== taskRoot(project) ? inThread.worktree : "";
2454
+ // Without a configured shared sandbox, OpenShell starts are runner-owned: one sandbox per project, commits landed on close.
2455
+ // The shared sandbox cannot mount a thread's worktree, so a start in a thread is runner-owned too.
2456
+ if (launch === startSession && where === "openshell" && (!openshellRunner(env) || threadTree)) {
2457
+ const result = await runner({ socket: runnerSocket(env), timeoutMs: 300_000 })
2458
+ .start({ project: name, harness, prompt: checked.text, place: "openshell", ...(threadTree ? { worktreePath: threadTree } : {}), system: false, ...(chosen !== undefined ? { model: chosen } : {}) })
2459
+ .catch(() => reject(503, "The session runner is unavailable"));
2460
+ if (result.status !== 201)
2461
+ reject(result.status, result.body.error || "The runner refused the start");
2462
+ await project.threads?.claim(result.body.session, { thread: inThread, prompt: checked.text });
2463
+ return json(201, result.body);
2464
+ }
2465
+ // Codex, Cursor and OpenCode agent starts are runner sessions: the chat and thread show their replies and failures, and Stop works.
2466
+ // pi is always a runner session: it has no CLI start argv at all, whatever codeMode says (its adapter ignores it).
2467
+ if (runnerStarts && launch === startSession && harness !== "claude" && chosenMode === "agent" && (codeMode !== true || harness === "pi")) {
2468
+ const placed = threadTree ? { place: "worktree", worktreePath: threadTree } : { place: where, ...pick };
2469
+ const result = await runner({ socket: runnerSocket(env), timeoutMs: 120_000 })
2470
+ .start({ project: name, harness, prompt: checked.text, ...placed, system: false, ...(chosen !== undefined ? { model: chosen } : {}) })
2471
+ .catch(() => reject(503, "The session runner is unavailable"));
2472
+ if (result.status !== 201)
2473
+ reject(result.status, result.body.error || "The runner refused the start");
2474
+ await project.threads?.claim(result.body.session, { thread: inThread, prompt: checked.text });
2475
+ return json(201, result.body);
2476
+ }
2477
+ if (launch === startSession && harness === "claude" && codeMode === true) {
2478
+ const result = await runner({ socket: runnerSocket(env), timeoutMs: 120_000 })
2479
+ .start({ project: name, harness, prompt: checked.text, place: where, permissionMode: "supervised", codeMode: true, system: false, ...pick, ...(chosen !== undefined ? { model: chosen } : {}) })
2480
+ .catch(() => reject(503, "The session runner is unavailable"));
2481
+ if (result.status !== 201)
2482
+ reject(result.status, result.body.error || "The runner refused the start");
2483
+ await project.threads?.claim(result.body.session, { prompt: checked.text });
2484
+ return json(201, result.body);
2485
+ }
2486
+ const started = await start(cfg, { harness, prompt: checked.text, env, place: where, mode: chosenMode, ...(inThread ? { origin: inThread.worktree } : {}), ...(Object.keys(pick).length ? { pick } : {}), ...(permissionChosen !== undefined ? { claudePermission: permissionChosen } : {}), ...(chosen !== undefined ? { model: chosen } : {}), ...(typeof codeMode === "boolean" ? { codeMode } : {}) });
2487
+ await project.threads?.claim(started.session, { thread: inThread, prompt: checked.text });
2488
+ return json(201, started);
2489
+ }
2490
+ // A queued message is already on the bus: the urgent marker makes the recipient's next hook poll at once.
2491
+ if (action === "nudge") {
2492
+ recipient(cfg, target, true);
2493
+ markUrgent(operator, target);
2494
+ return json(200, { status: "Sending at the agent's next tool call" });
2495
+ }
2496
+ if (action === "queue") {
2497
+ const peer = recipient(cfg, target, true);
2498
+ if (typeof id !== "string" || !/^[a-zA-Z0-9-]{1,64}$/.test(id))
2499
+ reject(400, "Invalid message ID");
2500
+ const registered = listSessions(cfg).find(session => session.id === target);
2501
+ if (!registered)
2502
+ reject(409, "Queue actions require a locally registered session");
2503
+ const inbox = inboxOf(project, peer);
2504
+ await project.hub.open(inbox);
2505
+ await project.hub.open(project.receipts);
2506
+ const item = entries(project.hub.events, inbox, (item) => item.id === id && item.to === target && queueEntry(item))[0];
2507
+ if (!item)
2508
+ reject(404, "Queued message unavailable");
2509
+ if (item.by && item.by !== by)
2510
+ reject(403, "Only the sender can change this message");
2511
+ if (project.reads.get(id)?.has(target))
2512
+ reject(409, "The agent already read this message");
2513
+ let change;
2514
+ if (queueAction === "edit") {
2515
+ if (typeof body !== "string" || !body.trim() || body.length > MAX_BODY_CHARS)
2516
+ reject(400, `Enter 1–${MAX_BODY_CHARS} characters`);
2517
+ change = { body: body.trim() };
2518
+ }
2519
+ else if (queueAction === "cancel")
2520
+ change = { cancelled: true };
2521
+ else if (queueAction === "steer")
2522
+ change = { urgent: true };
2523
+ else
2524
+ reject(400, "Unknown queue action");
2525
+ const session = target.split("#")[1];
2526
+ if (!await changeQueuedMessage({ ...cfg, peer, session }, id, change))
2527
+ reject(409, "This message is no longer available to change");
2528
+ let outcome = {};
2529
+ if (change.urgent) {
2530
+ markUrgent(operator, target);
2531
+ const wake = wakeAgent(project, target, registered);
2532
+ outcome = wake.status === "online" || wake.status === "queued"
2533
+ ? { status: "Queued for the agent’s next poll" }
2534
+ : wake;
2535
+ }
2536
+ broadcast();
2537
+ return json(200, outcome);
2538
+ }
2539
+ if (action === "dispose") {
2540
+ disposeSession(cfg, target);
2541
+ return json(200, { status: "Disposed", detail: target });
2542
+ }
2543
+ // Codex (app-server turn/interrupt) and OpenCode (its API); Claude and Cursor answer unsupported.
2544
+ if (action === "interrupt") {
2545
+ recipient(cfg, target, true);
2546
+ // The runner stops a turn of any harness it holds; outside it, only Codex and OpenCode take an interrupt.
2547
+ if (runnerHeld(cfg, target)) {
2548
+ const r = await runner({ socket: runnerSocket(env) }).interrupt(target).catch(() => reject(503, "The session runner is unavailable"));
2549
+ if (![200, 202].includes(r.status ?? 0))
2550
+ reject(r.status ?? 502, r.body?.error || "The runner refused the interrupt");
2551
+ broadcast();
2552
+ return json(200, { status: "Interrupted", detail: target });
2553
+ }
2554
+ return json(200, await interrupt(listSessions(cfg).find(item => item.id === target)));
2555
+ }
2556
+ // End closes a runner-held session for good: its run stops and it takes no more messages.
2557
+ if (action === "end") {
2558
+ recipient(cfg, target, true);
2559
+ if (!runnerHeld(cfg, target))
2560
+ reject(404, "Only a session the runner holds can be ended here");
2561
+ const r = await runner({ socket: runnerSocket(env) }).close(target).catch(() => reject(503, "The session runner is unavailable"));
2562
+ if (r.status !== 200)
2563
+ reject(r.status ?? 502, r.body?.error || "The runner refused to end the session");
2564
+ broadcast();
2565
+ return json(200, { status: "Ended", detail: target });
2566
+ }
2567
+ // A message starting with / is a command for the session, not chat; support is listed in web/lib/slash-commands.js.
2568
+ if (action === "command") {
2569
+ if (typeof command !== "string" || command.length > MAX_BODY_CHARS)
2570
+ reject(400, `Enter 1–${MAX_BODY_CHARS} characters`);
2571
+ const parsed = parseCommand(command);
2572
+ if (!parsed)
2573
+ reject(400, "Commands start with /name");
2574
+ // /afk is the sidebar switch typed in any chat: it sets every project's mode, not the session's.
2575
+ if (parsed.name === "afk") {
2576
+ const next = String(parsed.args ?? "").trim();
2577
+ if (!MODES.includes(next))
2578
+ return json(200, { status: "failed", detail: "Use /afk on, /afk off or /afk quiet." });
2579
+ await setMode([...projects.values()].map(item => item.cfg), next, by);
2580
+ broadcast();
2581
+ return json(200, { status: "succeeded", detail: `AFK ${next} for ${projects.size} ${projects.size === 1 ? "project" : "projects"}.` });
2582
+ }
2583
+ recipient(cfg, target, true);
2584
+ const listed = listSessions(cfg).find(item => item.id === target);
2585
+ // An owned session's place decides whether /permission full-access is an OpenShell session's.
2586
+ const place = listed ? ownedRecord(cfg, listed.id)?.place : undefined;
2587
+ const session = listed && place ? { ...listed, place } : listed;
2588
+ // /compact compacts an owned session in place; every other command keeps its control path.
2589
+ const compact = parsed.name === "compact"
2590
+ ? async (peer) => (await runnerCompact(peer.id, runner, env)) ?? control("compact", peer, { cfg })
2591
+ : (peer) => control("compact", peer, { cfg });
2592
+ // /permission stores the next-start mode on the session; /team-permission asks the operator before writing team.dot.
2593
+ // The runner rewrites its owned record from memory, so a stored value never reaches a runner-owned session's wake.
2594
+ const askTeamPermission = (team, mode) => { const { done, ...reply } = requestTeamPermission(cfg, team, mode, { env }); void done; return reply; };
2595
+ // /mode changes a runner-owned session's live mode; the runner applies the start checks again.
2596
+ const setSessionMode = async (peer, mode) => {
2597
+ if (!ownedRecord(cfg, peer.id))
2598
+ throw new Error("/mode needs a runner-owned session; /permission sets a terminal Claude session's next start");
2599
+ const result = await runner({ socket: runnerSocket(env) }).setMode(peer.id, mode).catch(() => { throw new Error("The session runner is unavailable"); });
2600
+ if (result.status !== 200)
2601
+ throw new Error(result.body?.error || "The runner refused the mode change");
2602
+ broadcast();
2603
+ return result.body;
2604
+ };
2605
+ // /permission takes a runner mode or auto-afk (lib/slash.ts); a terminal Claude session stores Claude's name for it.
2606
+ const setPermission = async (peer, mode) => {
2607
+ if (!ownedRecord(cfg, peer.id)) {
2608
+ if (peer.harness !== "claude")
2609
+ throw new Error(`/permission changes a runner-owned ${peer.harness} session; a terminal one has no stored mode`);
2610
+ const claudeName = mode === "auto-afk" ? mode : Object.entries(CLAUDE_CLI_MODES).find(([, runnerMode]) => runnerMode === mode)?.[0];
2611
+ return setNextPermission(cfg, { id: peer.id, label: String(peer.id).split("#")[1] ?? "", value: claudeName ?? mode });
2612
+ }
2613
+ // A runner-owned session changes now; auto-afk resolves as a start would (supervised while AFK is on).
2614
+ const resolved = mode === "auto-afk" ? claudePermissionFor("claude", cfg, env, { setting: mode }) : null;
2615
+ const live = resolved ? (resolved.flag ? runnerModeOfClaude(resolved.flag) : "supervised") : mode;
2616
+ return { live: (await setSessionMode(peer, live)).permissionMode ?? live };
2617
+ };
2618
+ // /model switches a runner-owned session's model through the runner; a terminal session has no route to its model.
2619
+ const setSessionModel = async (peer, model) => {
2620
+ if (!ownedRecord(cfg, peer.id))
2621
+ throw new Error(`This ${peer.harness} session runs outside temmo; start it from temmo to switch models`);
2622
+ const result = await runner({ socket: runnerSocket(env) }).setModel(peer.id, model).catch(() => { throw new Error("The session runner is unavailable"); });
2623
+ if (result.status !== 200)
2624
+ throw new Error(result.body?.error || "The runner refused the model switch");
2625
+ broadcast();
2626
+ return result.body;
2627
+ };
2628
+ return json(200, await slashCommand(session, parsed, { compact, setPermission, setMode: setSessionMode, setModel: setSessionModel, askTeamPermission }));
2629
+ }
2630
+ if (action === "model") {
2631
+ const harness = recipient(cfg, target, true);
2632
+ if (harness !== "claude" || !ownedRecord(cfg, target))
2633
+ reject(404, "Select a runner-owned Claude session");
2634
+ const result = await runner({ socket: runnerSocket(env) }).setModel(target, model)
2635
+ .catch(() => reject(503, "The session runner is unavailable"));
2636
+ if (result.status !== 200)
2637
+ reject(result.status, result.body.error || "The runner refused the model switch");
2638
+ broadcast();
2639
+ return json(200, result.body);
2640
+ }
2641
+ if (action === "compact" || action === "wake") {
2642
+ recipient(cfg, target, true);
2643
+ const session = listSessions(cfg).find(item => item.id === target);
2644
+ if (action === "wake")
2645
+ return json(200, wakeAgent(project, target, session));
2646
+ // The runner owns the harness trigger for a session it started; a terminal session falls back to controls.
2647
+ return json(200, (await runnerCompact(target, runner, env)) ?? await control("compact", session, { cfg }));
2648
+ }
2649
+ if (typeof body !== "string" || (!body.trim() && !attachment) || body.length > MAX_BODY_CHARS)
2650
+ reject(400, `Enter 1–${MAX_BODY_CHARS} characters`);
2651
+ if (action === "reply" || question !== undefined) {
2652
+ if (attachment)
2653
+ reject(400, "Question replies require text");
2654
+ if (typeof question !== "string" || !/^[a-f0-9]{12}$/.test(question) || (target && target !== "all"))
2655
+ reject(400, "Invalid question");
2656
+ const reply = `reply ${question} ${body.trim()}`;
2657
+ if (body.trim().length > 2000 || Buffer.byteLength(reply) > MESSAGE_MAX_BYTES)
2658
+ reject(400, "Reply exceeds the size limit");
2659
+ await publishDecision(project, question, reply, by);
2660
+ return json(201, { sent: true });
2661
+ }
2662
+ recipient(cfg, target);
2663
+ const reply = replyTo === undefined || replyTo === null || replyTo === "" ? null : replyQuote(replyTo, body, quote);
2664
+ const text = reply?.quoted ? reply.body : body.trim();
2665
+ const { tagged, destinations } = messageDestinations(text, target, action === "send" && project.tasks ? () => project.tasks.list() : null);
2666
+ const [primary] = destinations;
2667
+ // A post tagged only @harness:model starts sessions; it names nobody running, so no running session takes it.
2668
+ const startOnly = !attachment && !hosted && action === "send" && !reply?.quoted && destinations.size === 1 && primary === "all"
2669
+ && startOnlyMentions(text, cfg.peers, [...Object.keys(listTeams(cfg, env)), ...Object.keys(listPatterns(cfg, env))]);
2670
+ const notes = [];
2671
+ let wake;
2672
+ let channelSent = null;
2673
+ let broadcastId;
2674
+ try {
2675
+ if (urgent !== undefined && typeof urgent !== "boolean")
2676
+ reject(400, "urgent must be true or false");
2677
+ if (!reply?.quoted && replyTo !== undefined && replyTo !== null && replyTo !== ""
2678
+ && (typeof replyTo !== "string" || !/^[a-zA-Z0-9-]{1,64}$/.test(replyTo)))
2679
+ reject(400, "Invalid reply ID");
2680
+ for (const to of destinations)
2681
+ recipient(cfg, to);
2682
+ if (action === "send") {
2683
+ if (sendAnyway !== undefined && typeof sendAnyway !== "boolean")
2684
+ reject(400, "sendAnyway must be true or false");
2685
+ if (!hosted && !sendAnyway && [...destinations].some(to => to.includes("#"))) {
2686
+ const held = await Promise.all(listSessions(cfg).filter(session => destinations.has(session.id))
2687
+ .map(session => hasDraft(session, { env })));
2688
+ if (held.some(Boolean))
2689
+ return json(200, { sent: false, draftHeld: true });
2690
+ }
2691
+ }
2692
+ const sender = action === "send" ? operator : cfg;
2693
+ // An operator message sent in a thread carries its id (docs/threads.md).
2694
+ const thread = action === "send" && input.thread ? input.thread : undefined;
2695
+ if (thread !== undefined && (typeof thread !== "string" || !THREAD_ID.test(thread)))
2696
+ reject(400, "Invalid thread");
2697
+ if (input.channel !== undefined && typeof input.channel !== "boolean")
2698
+ reject(400, "channel must be true or false");
2699
+ // A composer post in an open thread goes to everyone listening there (docs/threads.md "Thread channels"); #task tags keep their owners.
2700
+ if (thread && input.channel === true && !tagged.length) {
2701
+ const envelopeReply = reply?.replyTo ? { replyTo: reply.replyTo } : (!reply?.quoted && typeof replyTo === "string" && replyTo ? { replyTo } : {});
2702
+ const posted = await sendToThread(operator, `thread:${thread}`, text, { ...(project.threads?.channels ? { client: project.threads.channels } : {}), onPublished: project.hub.record, onPost: project.hub.record, attachment, urgent: urgent === true, ...envelopeReply, ...(by ? { by } : {}) });
2703
+ channelSent = new Set(posted.delivered);
2704
+ notes.push(`Thread: ${posted.delivered.length} listening`);
2705
+ // The session the operator is reading always gets the post, once, even when it muted the thread (docs/threads.md).
2706
+ if (readerCopy(target, channelSent)) {
2707
+ await sendMessage(operator, target, text, { threadId: thread, channelOf: posted.id, operatorThread: true, onPublished: project.hub.record, attachment, urgent: urgent === true, ...envelopeReply, ...(by ? { by } : {}) });
2708
+ channelSent.add(target);
2709
+ notes.push("To " + target);
2710
+ }
2711
+ // Every recipient wakes as a direct message would wake it: offline sessions resume, running ones read it at their next turn.
2712
+ const registered = listSessions(cfg);
2713
+ for (const to of channelSent) {
2714
+ const result = wakeAgent(project, to, registered.find(item => item.id === to));
2715
+ if (to === target)
2716
+ wake = result;
2717
+ }
2718
+ }
2719
+ else
2720
+ for (const to of destinations) {
2721
+ const direct = action === "send" && to.includes("#");
2722
+ const envelopeReply = reply?.replyTo && (to === target || destinations.size === 1) ? { replyTo: reply.replyTo }
2723
+ : (!reply?.quoted && replyTo !== undefined && replyTo !== null && replyTo !== "" && to === target ? { replyTo } : {});
2724
+ const published = await sendMessage(sender, to, text, { onPublished: project.hub.record, operatorThread: direct, attachment, urgent: urgent === true, ...(startOnly && to === primary ? { startOnly: true } : {}), ...(thread ? { threadId: thread } : {}), ...envelopeReply, ...(by && sender.peer === "operator" ? { by } : {}) });
2725
+ if (to === "all" && typeof published?.id === "string")
2726
+ broadcastId = published.id;
2727
+ if (direct) {
2728
+ const result = wakeAgent(project, to, listSessions(cfg).find(item => item.id === to));
2729
+ if (destinations.size === 1)
2730
+ wake = result;
2731
+ }
2732
+ if (tagged.length)
2733
+ notes.push(to === "all" ? "Project chat" : "To " + to);
2734
+ }
2735
+ }
2736
+ catch (err) {
2737
+ if (err.message.includes("-byte wire limit"))
2738
+ reject(400, err.message);
2739
+ throw err;
2740
+ }
2741
+ const confirmed = { sent: true, ...(reply?.quoted ? { quoted: true } : {}), ...(wake ? { wake } : {}) };
2742
+ const result = () => notes.length ? { ...confirmed, status: "Sent", detail: notes.join(" · ") } : confirmed;
2743
+ if (hosted || action !== "send")
2744
+ return json(201, result());
2745
+ const complete = async () => {
2746
+ notes.push(...await routeMentions(project, text, primary, by, channelSent ?? destinations, attachment, broadcastId, input.thread));
2747
+ return result();
2748
+ };
2749
+ if (request.headers.get("accept") === SEND_CONFIRMATION) {
2750
+ return sentStream(result(), () => complete().catch(error => {
2751
+ notes.push("Mention delivery failed: " + failure(error).message);
2752
+ return result();
2753
+ }));
2754
+ }
2755
+ return json(201, await complete());
2756
+ }
2757
+ catch (err) {
2758
+ const { status, message } = failure(err);
2759
+ return json(status, { error: message });
2760
+ }
2761
+ }
2762
+ // GET key, POST/DELETE subscribe, POST test: the browser's push subscription and a test notification.
2763
+ async function pushApi(request, action) {
2764
+ try {
2765
+ caller(request);
2766
+ if (!PUSH_ACTIONS.includes(action))
2767
+ reject(404, "Unknown route");
2768
+ if (!notifier)
2769
+ reject(404, "Notifications are not configured");
2770
+ if (action === "key") {
2771
+ if (request.method !== "GET")
2772
+ reject(405, "Method not allowed");
2773
+ return json(200, { publicKey: notifier.publicKey() });
2774
+ }
2775
+ if (!(action === "subscribe" ? ["POST", "DELETE"] : ["POST"]).includes(request.method))
2776
+ reject(405, "Method not allowed");
2777
+ assertSameOrigin(request, allowedOrigin);
2778
+ if (request.headers.get("content-type")?.split(";")[0].trim() !== "application/json")
2779
+ reject(415, "JSON required");
2780
+ const { subscription, endpoint } = await payload(request);
2781
+ if (action === "subscribe" && request.method === "POST") {
2782
+ notifier.subscribe(subscription);
2783
+ return json(201, { subscribed: true });
2784
+ }
2785
+ if (typeof endpoint !== "string" || !endpoint)
2786
+ reject(400, "Endpoint required");
2787
+ if (action === "subscribe")
2788
+ return json(200, { removed: notifier.unsubscribe(endpoint) });
2789
+ if (!notifier.subscriptions().some((item) => item.endpoint === endpoint))
2790
+ reject(404, "This browser is not subscribed");
2791
+ const result = await notifier.send({ title: "Temmo test", body: "Notifications reach this device.", tag: "test", url: "/", important: false }, { endpoint });
2792
+ return json(result.sent ? 201 : 502, result.sent ? { sent: true } : { error: "The push service did not accept the test" });
2793
+ }
2794
+ catch (err) {
2795
+ const { status, message } = failure(err);
2796
+ return json(status, { error: message });
2797
+ }
2798
+ }
2799
+ /**
2800
+ * Serves an attachment that appears in a loaded project's history; anything else is 404.
2801
+ * Images come from chat topics; text/plain comes only from the activity topic (a large tool result).
2802
+ * The first request downloads the file into the shared local cache; later ones read it from disk, so
2803
+ * each attachment is downloaded once, however many tabs, reloads or devices ask.
2804
+ */
2805
+ async function file(name, request) {
2806
+ if (auth && !(request && auth.user(request)))
2807
+ return json(401, { error: "Sign in with GitHub" });
2808
+ const text = TEXT_FILE.test(name);
2809
+ if (!text && !FILE_NAME.test(name))
2810
+ return new Response("Not found", { status: 404 });
2811
+ for (const project of projects.values()) {
2812
+ const topics = text ? [project.activity] : [project.topic, ...project.inboxes.values()];
2813
+ const found = topics.some(topic => project.hub.history.events(topic).some((event) => attachmentOf(event, { text })?.file === name));
2814
+ if (!found)
2815
+ continue;
2816
+ let cached = cachedAttachment(project.cfg, name);
2817
+ if (!cached) {
2818
+ cached = await ensureAttachment(project.cfg, name, { signal: request?.signal })
2819
+ .catch(() => null);
2820
+ }
2821
+ if (!cached)
2822
+ return new Response("Attachment unavailable", { status: 502 });
2823
+ const headers = {
2824
+ "content-type": cached.type, "cache-control": hosted ? "no-store" : "private, max-age=3600",
2825
+ "x-content-type-options": "nosniff", "content-disposition": "inline",
2826
+ "content-length": String(cached.size),
2827
+ ...(text ? { "content-security-policy": "sandbox; default-src 'none'" } : {}),
2828
+ };
2829
+ // A HEAD or a conditional request needs no body; send the same headers with no read.
2830
+ if (request?.method === "HEAD")
2831
+ return new Response(null, { headers });
2832
+ const ifNoneMatch = request?.headers?.get?.("if-none-match");
2833
+ const etag = `"${name}-${cached.size}"`;
2834
+ if (ifNoneMatch === etag)
2835
+ return new Response(null, { status: 304, headers: { ...headers, etag } });
2836
+ return new Response(readAttachmentFile(cached), { headers: { ...headers, etag } });
2837
+ }
2838
+ return new Response("Not found", { status: 404 });
2839
+ }
2840
+ // Read-only Harness² lesson library of one project, most-reinforced first per harness. Sign-in applies as to the event stream.
2841
+ function lessons(request) {
2842
+ try {
2843
+ caller(request);
2844
+ const { cfg } = projectFor(new URL(request.url).searchParams.get("project"));
2845
+ const library = readProjectLessons(cfg.stateDir, cfg.project);
2846
+ const harnesses = Object.keys(library).sort().map((harness) => ({ harness, lessons: rankLessons(library[harness]) }));
2847
+ return json(200, { project: cfg.project, harnesses });
2848
+ }
2849
+ catch (err) {
2850
+ return json(err.status || 400, { error: err.message });
2851
+ }
2852
+ }
2853
+ // Read-only runner schedules; ?runs=<name> returns that schedule's latest runs. Sign-in applies as to the event stream.
2854
+ async function schedules(request) {
2855
+ try {
2856
+ caller(request);
2857
+ const name = new URL(request.url).searchParams.get("runs");
2858
+ if (name === null)
2859
+ return json(200, await readSchedules({ socket: runnerSocket(env) }));
2860
+ if (!SCHEDULE_NAME.test(name))
2861
+ reject(400, "Invalid schedule name");
2862
+ return json(200, await readScheduleRuns(name, { env, socket: runnerSocket(env) }));
2863
+ }
2864
+ catch (err) {
2865
+ return json(err.status || 400, { error: err.message });
2866
+ }
2867
+ }
2868
+ return {
2869
+ auth: authApi,
2870
+ events,
2871
+ schedules,
2872
+ lessons,
2873
+ reviewDiff,
2874
+ threadDiff,
2875
+ refs,
2876
+ file,
2877
+ handle,
2878
+ land: landApi,
2879
+ push: pushApi,
2880
+ /** Adds every enabled config not yet watched (auto-joined repos); returns how many were added. */
2881
+ refresh(list) {
2882
+ return list.filter((item) => item.enabled && addProject(item)).length;
2883
+ },
2884
+ close() {
2885
+ closed = true;
2886
+ // Ending each stream lets the HTTP server's close finish: next start waits on open connections at SIGTERM.
2887
+ for (const client of [...clients]) {
2888
+ client.write = () => { };
2889
+ client.end?.();
2890
+ }
2891
+ clients.clear();
2892
+ clearTimeout(pushTimer ?? undefined);
2893
+ for (const project of projects.values()) {
2894
+ project.watcher.close();
2895
+ project.unwatchTasks();
2896
+ project.threads?.close();
2897
+ }
2898
+ for (const hub of hubs.values())
2899
+ hub.close();
2900
+ runTerminal.close();
2901
+ },
2902
+ };
2903
+ }
2904
+ // Process-wide instance shared by every route bundle; tests may install their own first.
2905
+ export function ui() {
2906
+ if (!shared[INSTANCE]) {
2907
+ const auth = createAuth({ dir: configDir(process.env), stateDir: stateDir(process.env), origin: process.env.TEMMO_UI_ORIGIN });
2908
+ if (auth?.hosted) {
2909
+ shared[INSTANCE] = createHostedUi({
2910
+ auth, projects: loadProjects(process.env, { host: "operator" }),
2911
+ stateDir: stateDir(process.env), origin: process.env.TEMMO_UI_ORIGIN, createUi,
2912
+ });
2913
+ return shared[INSTANCE];
2914
+ }
2915
+ // The UI posts with the operator token, so the bus stamps the operator's messages verified (lib/operator-token.ts).
2916
+ const listed = withOperatorToken(loadProjects(process.env, { host: "operator" }));
2917
+ const projects = listed.length ? listed
2918
+ : withOperatorToken([loadConfig(process.env, { cwd: process.env.TEMMO_UI_WORKSPACE || process.cwd(), host: "operator" })]);
2919
+ // VAPID subject: the UI's HTTPS origin, or a mailto: placeholder without one.
2920
+ const push = createPush({ dir: join(projects[0].stateDir, "push"), subject: process.env.TEMMO_UI_ORIGIN || "mailto:temmo@localhost.invalid" });
2921
+ const instance = createUi({ projects, allowedOrigin: process.env.TEMMO_UI_ORIGIN, push, auth, runnerStarts: true });
2922
+ // Repos that auto-join after start-up appear within one refresh interval.
2923
+ setInterval(() => instance.refresh(withOperatorToken(loadProjects(process.env, { host: "operator" }))), REFRESH_MS).unref();
2924
+ shared[INSTANCE] = instance;
2925
+ // Pushes direct messages into Codex, OpenCode and Claude sessions; it stands down while the runner delivers.
2926
+ // TEMMO_DISPATCH=off turns it off.
2927
+ if (process.env.TEMMO_DISPATCH !== "off") {
2928
+ const dispatcher = createDispatcher({ projects: () => loadProjects(process.env, { host: "operator" }).filter(item => item.enabled), skip: runnerUp });
2929
+ dispatcher.start();
2930
+ }
2931
+ }
2932
+ return shared[INSTANCE];
2933
+ }
2934
+ export function installUi(instance) {
2935
+ shared[INSTANCE] = instance;
2936
+ return instance;
2937
+ }