@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
package/lib/threads.js ADDED
@@ -0,0 +1,441 @@
1
+ /**
2
+ * Threads on the Postgres bus store (docs/threads.md): the schema, the store the /threads routes call, and the
3
+ * sync that gives every unassigned session a thread.
4
+ */
5
+ import { randomBytes } from "node:crypto";
6
+ import path from "node:path";
7
+ import { worktreeRoot } from "./sessions/registry.js";
8
+ export const THREAD_STATUSES = ["active", "snoozed", "settled", "archived"];
9
+ export const PR_STATES = ["draft", "open", "merged", "closed"];
10
+ export const THREAD_ID = /^th_[a-f0-9]{16}$/;
11
+ // auto: the sync names the thread from its lead session; operator: a rename froze it; NULL: a row from before the column.
12
+ export const TITLE_SOURCES = ["auto", "operator"];
13
+ const SYNC_LOCK = 7306459; // pg_advisory_xact_lock key: one sync assigns at a time
14
+ const SESSION = /^[a-z0-9-]+#[a-f0-9]{16}$/;
15
+ const BRANCH = /^\S{1,200}$/;
16
+ const TEXT_MAX = 200;
17
+ const URL_MAX = 500;
18
+ const SYNC_MAX = 2000;
19
+ const PROMPT_TITLE_MAX = 60;
20
+ export const UNTITLED = "Untitled";
21
+ // A worktree or subagent label repeats the address and names nothing.
22
+ const MACHINE_NAME = /^agent-[0-9a-f]{8,}$/i;
23
+ function bad(message, status = 400) {
24
+ return Object.assign(new Error(message), { status });
25
+ }
26
+ const clean = (value, max = TEXT_MAX) => String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
27
+ function text(value, name, max = TEXT_MAX) {
28
+ if (value === undefined || value === null)
29
+ return "";
30
+ if (typeof value !== "string")
31
+ throw bad(`${name} must be a string`);
32
+ return clean(value, max);
33
+ }
34
+ function folder(value, name) {
35
+ const v = text(value, name, 1000);
36
+ if (v && !path.isAbsolute(v))
37
+ throw bad(`${name} must be an absolute path`);
38
+ return v;
39
+ }
40
+ function optional(value, pattern, name) {
41
+ if (value === undefined || value === null || value === "")
42
+ return null;
43
+ if (typeof value !== "string" || !pattern.test(value))
44
+ throw bad(`Invalid ${name}`);
45
+ return value;
46
+ }
47
+ const rowThread = (row) => ({
48
+ id: row.id,
49
+ project: row.project,
50
+ title: row.title,
51
+ worktree: row.worktree,
52
+ branch: row.branch,
53
+ baseRef: row.base_ref,
54
+ parentThreadId: row.parent_thread_id,
55
+ leadSession: row.lead_session,
56
+ patternRun: row.pattern_run,
57
+ status: row.status,
58
+ pinned: row.pinned,
59
+ titleSource: row.title_source ?? null,
60
+ createdAt: Number(row.created_at),
61
+ updatedAt: Number(row.updated_at),
62
+ });
63
+ const rowPr = (row) => ({
64
+ id: Number(row.id),
65
+ position: row.position,
66
+ number: row.number === null ? null : Number(row.number),
67
+ url: row.url,
68
+ head: row.head,
69
+ base: row.base,
70
+ state: row.state,
71
+ });
72
+ /** Creates the thread tables and the events.thread_id column inside the caller's open migration transaction. */
73
+ export async function migrateThreads(client, schema) {
74
+ const statuses = THREAD_STATUSES.map((s) => `'${s}'`).join(",");
75
+ const states = PR_STATES.map((s) => `'${s}'`).join(",");
76
+ await client.query(`CREATE TABLE IF NOT EXISTS ${schema}.threads (
77
+ id TEXT PRIMARY KEY,
78
+ project TEXT NOT NULL,
79
+ title TEXT NOT NULL DEFAULT '',
80
+ worktree TEXT NOT NULL DEFAULT '',
81
+ branch TEXT NOT NULL DEFAULT '',
82
+ base_ref TEXT NOT NULL DEFAULT '',
83
+ parent_thread_id TEXT REFERENCES ${schema}.threads(id) ON DELETE SET NULL,
84
+ lead_session TEXT,
85
+ pattern_run TEXT,
86
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN (${statuses})),
87
+ pinned BOOLEAN NOT NULL DEFAULT false,
88
+ created_at BIGINT NOT NULL,
89
+ updated_at BIGINT NOT NULL
90
+ )`);
91
+ await client.query(`CREATE TABLE IF NOT EXISTS ${schema}.thread_sessions (
92
+ project TEXT NOT NULL,
93
+ session TEXT NOT NULL,
94
+ thread_id TEXT NOT NULL REFERENCES ${schema}.threads(id) ON DELETE CASCADE,
95
+ joined_at BIGINT NOT NULL,
96
+ PRIMARY KEY (project, session)
97
+ )`);
98
+ await client.query(`CREATE TABLE IF NOT EXISTS ${schema}.thread_prs (
99
+ id BIGSERIAL PRIMARY KEY,
100
+ thread_id TEXT NOT NULL REFERENCES ${schema}.threads(id) ON DELETE CASCADE,
101
+ position INTEGER NOT NULL,
102
+ number BIGINT,
103
+ url TEXT,
104
+ head TEXT NOT NULL,
105
+ base TEXT NOT NULL,
106
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN (${states})),
107
+ created_at BIGINT NOT NULL,
108
+ updated_at BIGINT NOT NULL,
109
+ CHECK (number IS NOT NULL OR url IS NOT NULL)
110
+ )`);
111
+ await client.query(`CREATE INDEX IF NOT EXISTS threads_project_updated ON ${schema}.threads(project, updated_at)`);
112
+ await client.query(`CREATE INDEX IF NOT EXISTS threads_project_worktree ON ${schema}.threads(project, worktree)`);
113
+ await client.query(`CREATE INDEX IF NOT EXISTS threads_project_run ON ${schema}.threads(project, pattern_run)`);
114
+ await client.query(`CREATE INDEX IF NOT EXISTS thread_sessions_thread ON ${schema}.thread_sessions(thread_id)`);
115
+ await client.query(`CREATE INDEX IF NOT EXISTS thread_prs_thread ON ${schema}.thread_prs(thread_id, position)`);
116
+ await client.query(`ALTER TABLE ${schema}.events ADD COLUMN IF NOT EXISTS thread_id TEXT`);
117
+ const sources = TITLE_SOURCES.map((s) => `'${s}'`).join(",");
118
+ await client.query(`ALTER TABLE ${schema}.threads ADD COLUMN IF NOT EXISTS title_source TEXT CHECK (title_source IN (${sources}))`);
119
+ }
120
+ /** The title a lead session gives its thread: its set_identity activity line, else its first prompt's first line, clipped to 60. */
121
+ export function sessionTitle({ activity, prompt }) {
122
+ const line = (value) => String(value ?? "").split(/\r?\n/).map((l) => l.replace(/\s+/g, " ").trim()).find(Boolean) || "";
123
+ return clean(line(activity)) || clean(line(prompt), PROMPT_TITLE_MAX);
124
+ }
125
+ /** A title when the session has given none: its name, else the worktree folder; never the session address. */
126
+ function fallbackTitle(s, worktree, base) {
127
+ const name = typeof s.name === "string" ? clean(s.name) : "";
128
+ if (name && !name.includes("#") && !MACHINE_NAME.test(name))
129
+ return name;
130
+ return worktree && worktree !== base ? path.basename(worktree) : UNTITLED;
131
+ }
132
+ // The names the sync gave before sessions named their threads: an address, or the worktree folder.
133
+ const placeholder = (title, worktree) => title.includes("#") || Boolean(worktree && title === path.basename(worktree));
134
+ // A pattern run's thread before its session names it.
135
+ const RUN_TITLE = /^run \S+$/;
136
+ const flat = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
137
+ /**
138
+ * The thread's next title from its lead session, or null to keep it: an operator rename keeps it; a row from before
139
+ * title_source changes only while its title is a placeholder; an auto title follows the activity line, and takes a prompt
140
+ * title only over a fallback or a title cut from that same prompt, so a later prompt never replaces the first.
141
+ */
142
+ export function nextTitle(thread, lead, base = "") {
143
+ if (thread.titleSource === "operator")
144
+ return null;
145
+ const worktree = thread.worktree || "";
146
+ const own = sessionTitle(lead);
147
+ const stale = placeholder(thread.title, worktree);
148
+ if (thread.titleSource !== "auto" && !stale)
149
+ return null;
150
+ const fallback = fallbackTitle(lead, worktree, base);
151
+ const filler = stale || thread.title === fallback || thread.title === UNTITLED || RUN_TITLE.test(thread.title);
152
+ const activity = sessionTitle({ activity: lead.activity });
153
+ const fromPrompt = Boolean(thread.title) && flat(lead.prompt).startsWith(flat(thread.title));
154
+ const next = activity || (own && (filler || fromPrompt) ? own : stale ? fallback : thread.title);
155
+ return next !== thread.title ? next : null;
156
+ }
157
+ /** The session a thread is named after: its lead, else its first member. */
158
+ export const leadOf = (thread) => thread.leadSession || thread.sessions?.[0] || "";
159
+ /** Where a thread runs: "main" for the project root, else its worktree folder; "" without a worktree. */
160
+ export function threadPlace(worktree, root = "") {
161
+ if (typeof worktree !== "string" || !worktree)
162
+ return "";
163
+ return root && worktree === root ? "main" : path.basename(worktree);
164
+ }
165
+ /** The thread store over one pool; `schema` is already validated by the caller. */
166
+ export function createThreadStore({ pool, schema, now = Date.now }) {
167
+ let last = 0;
168
+ // Strictly increasing stamps keep join order when several sessions join within one millisecond.
169
+ const stamp = () => (last = Math.max(now(), last + 1));
170
+ async function inTransaction(fn) {
171
+ const client = await pool.connect();
172
+ try {
173
+ await client.query("BEGIN");
174
+ const result = await fn(client);
175
+ await client.query("COMMIT");
176
+ return result;
177
+ }
178
+ catch (error) {
179
+ await client.query("ROLLBACK").catch(() => { });
180
+ throw error;
181
+ }
182
+ finally {
183
+ client.release();
184
+ }
185
+ }
186
+ /** Threads with their sessions and PRs, two queries for any number of threads. */
187
+ async function withParts(rows, db = pool) {
188
+ const threads = rows.map(rowThread);
189
+ if (!threads.length)
190
+ return threads;
191
+ const ids = threads.map((t) => t.id);
192
+ const sessions = await db.query(`SELECT thread_id, session FROM ${schema}.thread_sessions WHERE thread_id = ANY($1) ORDER BY joined_at, session`, [ids]);
193
+ const prs = await db.query(`SELECT * FROM ${schema}.thread_prs WHERE thread_id = ANY($1) ORDER BY position, id`, [ids]);
194
+ const byId = new Map(threads.map((t) => [t.id, Object.assign(t, { sessions: [], prs: [] })]));
195
+ for (const row of sessions.rows)
196
+ byId.get(row.thread_id).sessions.push(row.session);
197
+ for (const row of prs.rows)
198
+ byId.get(row.thread_id).prs.push(rowPr(row));
199
+ return threads;
200
+ }
201
+ async function get(id, db = pool) {
202
+ if (typeof id !== "string" || !THREAD_ID.test(id))
203
+ throw bad("Invalid thread");
204
+ const { rows } = await db.query(`SELECT * FROM ${schema}.threads WHERE id = $1`, [id]);
205
+ if (!rows.length)
206
+ throw bad("Unknown thread", 404);
207
+ return (await withParts(rows, db))[0];
208
+ }
209
+ const touch = (db, id) => db.query(`UPDATE ${schema}.threads SET updated_at = $2 WHERE id = $1`, [id, stamp()]);
210
+ async function list({ project, archived = false } = {}) {
211
+ if (typeof project !== "string" || !project)
212
+ throw bad("project required");
213
+ const { rows } = await pool.query(`SELECT * FROM ${schema}.threads WHERE project = $1 AND ($2 OR status <> 'archived') ORDER BY pinned DESC, updated_at DESC, id`, [project, archived === true]);
214
+ return withParts(rows);
215
+ }
216
+ async function create(fields = {}, client = pool) {
217
+ const project = text(fields.project, "project");
218
+ if (!project)
219
+ throw bad("project required");
220
+ const branch = text(fields.branch, "branch");
221
+ const baseRef = text(fields.baseRef, "baseRef");
222
+ if (branch && !BRANCH.test(branch))
223
+ throw bad("Invalid branch");
224
+ if (baseRef && !BRANCH.test(baseRef))
225
+ throw bad("Invalid baseRef");
226
+ const titleSource = fields.titleSource === undefined ? "auto" : fields.titleSource;
227
+ if (!TITLE_SOURCES.includes(titleSource))
228
+ throw bad("Invalid titleSource");
229
+ const at = stamp();
230
+ const row = [
231
+ `th_${randomBytes(8).toString("hex")}`, project, text(fields.title, "title"), folder(fields.worktree, "worktree"), branch, baseRef,
232
+ optional(fields.parentThreadId, THREAD_ID, "parentThreadId"), optional(fields.leadSession, SESSION, "leadSession"),
233
+ text(fields.patternRun, "patternRun") || null, at, titleSource,
234
+ ];
235
+ await client.query(`INSERT INTO ${schema}.threads (id, project, title, worktree, branch, base_ref, parent_thread_id, lead_session, pattern_run, created_at, updated_at, title_source)
236
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10, $11)`, row);
237
+ return get(row[0], client);
238
+ }
239
+ async function update(id, { title, status, pinned, leadSession } = {}) {
240
+ await get(id);
241
+ const sets = [];
242
+ const values = [id];
243
+ const set = (column, value) => sets.push(`${column} = $${values.push(value)}`);
244
+ if (title !== undefined) {
245
+ set("title", text(title, "title"));
246
+ set("title_source", "operator");
247
+ }
248
+ if (status !== undefined) {
249
+ if (!THREAD_STATUSES.includes(status))
250
+ throw bad("Invalid status");
251
+ set("status", status);
252
+ }
253
+ if (pinned !== undefined) {
254
+ if (typeof pinned !== "boolean")
255
+ throw bad("pinned must be true or false");
256
+ set("pinned", pinned);
257
+ }
258
+ if (leadSession !== undefined)
259
+ set("lead_session", optional(leadSession, SESSION, "leadSession"));
260
+ set("updated_at", stamp());
261
+ await pool.query(`UPDATE ${schema}.threads SET ${sets.join(", ")} WHERE id = $1`, values);
262
+ return get(id);
263
+ }
264
+ async function attachPr(id, { number, url, head, base, state = "open", position } = {}) {
265
+ if (number !== undefined && number !== null && !(Number.isSafeInteger(number) && number > 0))
266
+ throw bad("Invalid PR number");
267
+ if (url !== undefined && url !== null && !(typeof url === "string" && url.startsWith("https://") && url.length <= URL_MAX && !/\s/.test(url)))
268
+ throw bad("Invalid PR url");
269
+ if ((number === undefined || number === null) && (url === undefined || url === null))
270
+ throw bad("A PR needs a number or a url");
271
+ if (typeof head !== "string" || !BRANCH.test(head) || typeof base !== "string" || !BRANCH.test(base))
272
+ throw bad("Invalid head or base");
273
+ if (!PR_STATES.includes(state))
274
+ throw bad("Invalid PR state");
275
+ if (position !== undefined && position !== null && !(Number.isSafeInteger(position) && position >= 0))
276
+ throw bad("Invalid position");
277
+ await get(id);
278
+ await inTransaction(async (client) => {
279
+ await client.query(`SELECT id FROM ${schema}.threads WHERE id = $1 FOR UPDATE`, [id]);
280
+ const { rows } = await client.query(`SELECT COALESCE(MAX(position) + 1, 0) AS next FROM ${schema}.thread_prs WHERE thread_id = $1`, [id]);
281
+ const next = Number(rows[0].next);
282
+ const at = position === undefined || position === null ? next : Math.min(position, next);
283
+ await client.query(`UPDATE ${schema}.thread_prs SET position = position + 1 WHERE thread_id = $1 AND position >= $2`, [id, at]);
284
+ const time = stamp();
285
+ await client.query(`INSERT INTO ${schema}.thread_prs (thread_id, position, number, url, head, base, state, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8)`, [id, at, number ?? null, url ?? null, head, base, state, time]);
286
+ await touch(client, id);
287
+ });
288
+ return get(id);
289
+ }
290
+ async function detachPr(id, prId) {
291
+ if (!Number.isSafeInteger(prId) || prId <= 0)
292
+ throw bad("Invalid PR");
293
+ await get(id);
294
+ await inTransaction(async (client) => {
295
+ await client.query(`SELECT id FROM ${schema}.threads WHERE id = $1 FOR UPDATE`, [id]);
296
+ const { rows } = await client.query(`DELETE FROM ${schema}.thread_prs WHERE id = $1 AND thread_id = $2 RETURNING position`, [prId, id]);
297
+ if (!rows.length)
298
+ throw bad("Unknown PR", 404);
299
+ await client.query(`UPDATE ${schema}.thread_prs SET position = position - 1 WHERE thread_id = $1 AND position > $2`, [id, rows[0].position]);
300
+ await touch(client, id);
301
+ });
302
+ return get(id);
303
+ }
304
+ const join = (db, project, session, threadId) => db.query(`INSERT INTO ${schema}.thread_sessions (project, session, thread_id, joined_at) VALUES ($1, $2, $3, $4)
305
+ ON CONFLICT (project, session) DO UPDATE SET thread_id = EXCLUDED.thread_id, joined_at = EXCLUDED.joined_at`, [project, session, threadId, stamp()]);
306
+ async function moveSession(id, { session } = {}) {
307
+ if (typeof session !== "string" || !SESSION.test(session))
308
+ throw bad("Invalid session");
309
+ const thread = await get(id);
310
+ await inTransaction(async (client) => {
311
+ // Under sync's lock, so a sync that read the members before this move cannot write its stale assignment over it.
312
+ await client.query("SELECT pg_advisory_xact_lock($1)", [SYNC_LOCK]);
313
+ // A lead that leaves its thread stops leading it.
314
+ await client.query(`UPDATE ${schema}.threads SET lead_session = NULL WHERE project = $1 AND lead_session = $2 AND id <> $3`, [thread.project, session, id]);
315
+ await join(client, thread.project, session, id);
316
+ await touch(client, id);
317
+ });
318
+ return get(id);
319
+ }
320
+ /** Gives each unassigned session a thread by the docs/threads.md "Assignment" rules; fills an empty worktree on the way. */
321
+ async function sync({ project, root = "", sessions } = {}) {
322
+ if (typeof project !== "string" || !project)
323
+ throw bad("project required");
324
+ if (!Array.isArray(sessions) || sessions.length > SYNC_MAX)
325
+ throw bad("sessions must be an array");
326
+ const base = folder(root, "root");
327
+ const input = sessions.filter((s) => s && typeof s.address === "string" && SESSION.test(s.address) && typeof s.cwd === "string" && path.isAbsolute(s.cwd));
328
+ return inTransaction(async (client) => {
329
+ await client.query("SELECT pg_advisory_xact_lock($1)", [SYNC_LOCK]);
330
+ const threads = new Map((await client.query(`SELECT * FROM ${schema}.threads WHERE project = $1 ORDER BY created_at, id`, [project])).rows.map((row) => [row.id, rowThread(row)]));
331
+ const member = new Map();
332
+ for (const row of (await client.query(`SELECT session, thread_id FROM ${schema}.thread_sessions WHERE project = $1`, [project])).rows) {
333
+ member.set(row.session, threads.get(row.thread_id));
334
+ }
335
+ const assigned = [];
336
+ let created = 0;
337
+ const tree = (s) => (typeof s.worktree === "string" && path.isAbsolute(s.worktree) && s.worktree) || (base && (s.cwd === base || s.cwd.startsWith(base + path.sep)) ? base : s.cwd);
338
+ const branchOf = (s) => (typeof s.branch === "string" && BRANCH.test(s.branch) ? s.branch : "");
339
+ const titleOf = (s, where) => sessionTitle(s) || fallbackTitle(s, where, base);
340
+ const open = async (fields) => {
341
+ const thread = await create({ project, ...fields }, client);
342
+ threads.set(thread.id, thread);
343
+ created += 1;
344
+ return thread;
345
+ };
346
+ const place = async (s) => {
347
+ const where = tree(s);
348
+ const parent = typeof s.parent === "string" ? member.get(s.parent) : undefined;
349
+ if (parent && (parent.worktree === where || !parent.worktree))
350
+ return parent;
351
+ const titled = { worktree: where, branch: branchOf(s) };
352
+ if (parent)
353
+ return open({ ...titled, title: titleOf(s, where), parentThreadId: parent.id });
354
+ if (typeof s.patternRun === "string" && s.patternRun) {
355
+ const run = [...threads.values()].find((t) => t.patternRun === s.patternRun && t.status !== "archived");
356
+ return run || open({ ...titled, title: sessionTitle(s) || `run ${s.patternRun}`, patternRun: s.patternRun });
357
+ }
358
+ if (where !== base) {
359
+ // An archived thread stays archived: a new session in its worktree starts a new thread.
360
+ const shared = [...threads.values()].find((t) => t.worktree === where && t.status !== "archived");
361
+ return shared || open({ ...titled, title: titleOf(s, where) });
362
+ }
363
+ return open({ ...titled, title: titleOf(s, where) });
364
+ };
365
+ // Threads a UI start created before the session had a folder take the folder of their first session.
366
+ for (const s of input) {
367
+ const thread = member.get(s.address);
368
+ if (!thread || thread.worktree)
369
+ continue;
370
+ thread.worktree = tree(s);
371
+ thread.branch ||= branchOf(s);
372
+ await client.query(`UPDATE ${schema}.threads SET worktree = $2, branch = $3, updated_at = $4 WHERE id = $1`, [thread.id, thread.worktree, thread.branch, stamp()]);
373
+ }
374
+ let pending = input.filter((s) => !member.has(s.address));
375
+ let force = false;
376
+ while (pending.length) {
377
+ const waiting = new Set(pending.map((s) => s.address));
378
+ const ready = force ? pending : pending.filter((s) => !(typeof s.parent === "string" && waiting.has(s.parent) && s.parent !== s.address));
379
+ // A parent cycle makes no progress; then the remaining parents count as absent.
380
+ if (!ready.length) {
381
+ force = true;
382
+ continue;
383
+ }
384
+ for (const s of ready) {
385
+ const thread = await place(s);
386
+ await join(client, project, s.address, thread.id);
387
+ member.set(s.address, thread);
388
+ assigned.push({ session: s.address, thread: thread.id });
389
+ }
390
+ const done = new Set(ready.map((s) => s.address));
391
+ pending = pending.filter((s) => !done.has(s.address));
392
+ }
393
+ // Each thread takes its lead's title (docs/threads.md "Naming"); a rename stops it. updated_at stays: naming is not work.
394
+ const byAddress = new Map(input.map((s) => [s.address, s]));
395
+ const members = new Map();
396
+ for (const row of (await client.query(`SELECT thread_id, session FROM ${schema}.thread_sessions WHERE project = $1 ORDER BY joined_at, session`, [project])).rows) {
397
+ members.set(row.thread_id, [...(members.get(row.thread_id) || []), row.session]);
398
+ }
399
+ let retitled = 0;
400
+ for (const thread of threads.values()) {
401
+ const lead = byAddress.get(leadOf({ leadSession: thread.leadSession, sessions: members.get(thread.id) }));
402
+ const title = lead ? nextTitle(thread, lead, base) : null;
403
+ if (title === null)
404
+ continue;
405
+ await client.query(`UPDATE ${schema}.threads SET title = $2, title_source = 'auto' WHERE id = $1`, [thread.id, title]);
406
+ thread.title = title;
407
+ retitled += 1;
408
+ }
409
+ return { assigned, created, ...(retitled ? { retitled } : {}) };
410
+ });
411
+ }
412
+ return { list, get: (id) => get(id), create: (fields) => create(fields), update, attachPr, detachPr, moveSession, sync };
413
+ }
414
+ /** The sync input for one project: registry sessions and owned records merged by address, owned fields first. */
415
+ export function threadSessionsOf({ sessions = [], owned = [], root = "", prompts }) {
416
+ const byAddress = new Map();
417
+ for (const s of sessions) {
418
+ if (!s || typeof s.id !== "string")
419
+ continue;
420
+ byAddress.set(s.id, { address: s.id, cwd: s.cwd, parent: s.parent, name: s.identityName || s.name, branch: s.branch, activity: s.activity });
421
+ }
422
+ for (const o of owned) {
423
+ if (!o || typeof o.address !== "string")
424
+ continue;
425
+ const seen = byAddress.get(o.address) || { address: o.address };
426
+ byAddress.set(o.address, { ...seen, cwd: o.cwd ?? seen.cwd, parent: o.parent ?? seen.parent, patternRun: o.patternRun ?? seen.patternRun });
427
+ }
428
+ return [...byAddress.values()]
429
+ .filter((s) => typeof s.cwd === "string" && path.isAbsolute(s.cwd))
430
+ .map((s) => ({
431
+ address: s.address,
432
+ cwd: s.cwd,
433
+ worktree: worktreeRoot(s.cwd, root),
434
+ parent: typeof s.parent === "string" ? s.parent : null,
435
+ patternRun: typeof s.patternRun === "string" ? s.patternRun : null,
436
+ name: typeof s.name === "string" ? s.name : "",
437
+ branch: typeof s.branch === "string" ? s.branch : "",
438
+ activity: typeof s.activity === "string" ? s.activity : "",
439
+ prompt: prompts?.get(s.address) || "",
440
+ }));
441
+ }
@@ -0,0 +1,33 @@
1
+ import { loadConfig, ownEnv } from "./config.js";
2
+ import { schemaProblem } from "./code-run.js";
3
+ import { OPS } from "./surfaces/ops.js";
4
+ const BUILDER_START = "builder_start";
5
+ const builderStartOnHost = (env) => !env.OPENSHELL_SANDBOX && !env.TEMMO_BUILDER && !env.TEMMO_SANDBOX_OUT;
6
+ const listed = (env) => OPS.filter((op) => op.surfaces.includes("mcp") && (op.name !== BUILDER_START || builderStartOnHost(env)) && (!op.available || op.available(env)));
7
+ const definition = ({ name, description, inputSchema }) => ({ name, description, inputSchema });
8
+ /** In-process client for programs running under an operator-configured OpenShell policy. */
9
+ export function toolClient({ env = process.env, cwd = process.cwd(), host = "" } = {}) {
10
+ return {
11
+ listTools: () => structuredClone(listed(env).map(definition)),
12
+ callTool: (name, args = {}, { signal } = {}) => callTool(name, args, { environment: env, cwd, host, signal }),
13
+ };
14
+ }
15
+ async function callTool(name, args, { environment, cwd, host, signal }) {
16
+ signal?.throwIfAborted();
17
+ const op = listed(environment).find((candidate) => candidate.name === name);
18
+ if (!op)
19
+ throw new Error("Unknown tool");
20
+ if (op.name === BUILDER_START) {
21
+ const problem = schemaProblem(op.inputSchema, args);
22
+ if (problem)
23
+ throw new Error(problem);
24
+ }
25
+ // A child agent's MCP server inherits its parent's environment; ownEnv drops the parent's identity.
26
+ const env = ownEnv(environment, host);
27
+ const cfg = loadConfig(op.listing ? { ...env, TEMMO_PEER: env.TEMMO_PEER || host || "operator" } : env, { cwd, host, session: args.session });
28
+ if (!cfg.enabled)
29
+ throw new Error(cfg.reason);
30
+ if (op.needsSession && !cfg.session)
31
+ throw new Error("Pass the session label supplied by the temmo hook");
32
+ return op.handler(args, { cfg, env, host, signal });
33
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Detects a prompt the operator queued in a session while its Stop hook waits in AFK mode.
3
+ * - Claude Code appends {"type":"queue-operation","operation":"enqueue","content":"…"} to the transcript
4
+ * (Stop input transcript_path) when a typed or Remote Control prompt waits for the hook.
5
+ * - Codex appends {"session_id","ts","text"} to $CODEX_HOME/history.jsonl when the user presses Enter.
6
+ * Both formats are undocumented, so every failure means "nothing queued" (the wait goes on as before).
7
+ * Only bytes appended after the watch starts are read; nothing from these files is published.
8
+ */
9
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { isAbsolute, join } from "node:path";
12
+ import { operatorPrompt } from "./mode.js";
13
+ const READ_MAX_BYTES = 4 * 1024 * 1024;
14
+ /** True when queued content came from the operator. */
15
+ export function queuedByOperator(content, env = process.env) {
16
+ return typeof content === "string" && operatorPrompt(content, env);
17
+ }
18
+ // Bytes [from, to) of the file as text.
19
+ function readRange(path, from, to) {
20
+ const fd = openSync(path, "r");
21
+ try {
22
+ const data = Buffer.alloc(to - from);
23
+ const n = readSync(fd, data, 0, data.length, from);
24
+ return data.subarray(0, n).toString("utf8");
25
+ }
26
+ finally {
27
+ closeSync(fd);
28
+ }
29
+ }
30
+ /**
31
+ * check() that reads the complete JSON lines appended to path since the watch began and reports
32
+ * whether any satisfies match(entry). Null when the file is unreadable now.
33
+ */
34
+ function watchAppended(path, match) {
35
+ let offset;
36
+ try {
37
+ offset = statSync(path).size;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ let partial = "";
43
+ return () => {
44
+ try {
45
+ const size = statSync(path).size;
46
+ if (size < offset) {
47
+ offset = size;
48
+ partial = "";
49
+ }
50
+ if (size === offset)
51
+ return false;
52
+ let from = offset;
53
+ if (size - from > READ_MAX_BYTES) {
54
+ from = size - READ_MAX_BYTES;
55
+ partial = "";
56
+ }
57
+ const lines = (partial + readRange(path, from, size)).split("\n");
58
+ offset = size;
59
+ partial = lines.pop();
60
+ for (const line of lines) {
61
+ let entry;
62
+ try {
63
+ entry = JSON.parse(line);
64
+ }
65
+ catch {
66
+ continue;
67
+ }
68
+ if (entry && typeof entry === "object" && match(entry))
69
+ return true;
70
+ }
71
+ return false;
72
+ }
73
+ catch {
74
+ return false;
75
+ }
76
+ };
77
+ }
78
+ /**
79
+ * For a Stop hook: a check() reporting whether the operator queued a prompt in this session since the watch began.
80
+ * Claude reads transcript_path, Codex reads history.jsonl; other harnesses and unreadable files return null.
81
+ */
82
+ export function watchQueue(host, input = {}, { env = process.env, now = Date.now } = {}) {
83
+ if (host === "claude") {
84
+ const path = input.transcript_path;
85
+ if (typeof path !== "string" || !isAbsolute(path))
86
+ return null;
87
+ return watchAppended(path, (e) => e.type === "queue-operation" && e.operation === "enqueue" && queuedByOperator(e.content, env));
88
+ }
89
+ if (host === "codex") {
90
+ const session = input.session_id;
91
+ if (typeof session !== "string" || !session)
92
+ return null;
93
+ const startS = Math.floor(now() / 1000);
94
+ const home = env.CODEX_HOME || join(env.HOME || homedir(), ".codex");
95
+ return watchAppended(join(home, "history.jsonl"), (e) => e.session_id === session && Number(e.ts) >= startS && queuedByOperator(e.text, env));
96
+ }
97
+ return null;
98
+ }
@@ -0,0 +1,19 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import path from "node:path";
4
+ export function productionDistDir(web = fileURLToPath(new URL("../web/", import.meta.url))) {
5
+ if (process.env.TEMMO_NEXT_DIST)
6
+ return process.env.TEMMO_NEXT_DIST;
7
+ let build;
8
+ try {
9
+ build = readFileSync(path.join(web, ".next-builds", "current"), "utf8").trim();
10
+ }
11
+ catch (err) {
12
+ if (err.code === "ENOENT")
13
+ return ".next";
14
+ throw err;
15
+ }
16
+ if (!/^build-[a-zA-Z0-9]+$/.test(build))
17
+ throw new Error("Invalid Next.js build pointer");
18
+ return ".next-builds/" + build;
19
+ }