@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,248 @@
1
+ /**
2
+ * OTLP traces for Cursor runs. Cursor's own OpenTelemetry exporter posts only to Cursor's backend (URL and bearer
3
+ * token fixed in the CLI), so temmo builds the spans from what it sees: the stream-json output of a run it
4
+ * launches (model, tool calls, token usage) or the Cursor hooks of any other run (model, tool calls; Cursor hands
5
+ * hooks no token counts). One trace per run: an AGENT root, one LLM child, one TOOL child per tool call, with
6
+ * OpenInference attributes. Export is best effort: one POST with a short timeout that never throws.
7
+ */
8
+ import { randomBytes } from "node:crypto";
9
+ import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, existsSync } from "node:fs";
10
+ import path from "node:path";
11
+ import { encodeTraceRequest } from "./analyze-otlp.js";
12
+ import { autoDefaults, sessionLabel, stateDir } from "./config.js";
13
+ export const DEFAULT_OTLP_ENDPOINT = "http://localhost:6006/v1/traces";
14
+ export const EXPORT_TIMEOUT_MS = 1500;
15
+ // Set on a Cursor process whose launcher traces it from stream-json or ACP; its hooks then record nothing.
16
+ export const TRACE_ENV = "TEMMO_CURSOR_TRACE";
17
+ // The temmo.role a hook-traced run reports (a schedule sets schedule:<name>).
18
+ export const ROLE_ENV = "TEMMO_TRACE_ROLE";
19
+ const OFF = new Set(["", "off", "false", "0", "none"]);
20
+ const INPUT_MAX = 1000;
21
+ const HOOK_DIR = "cursor-traces";
22
+ /**
23
+ * The OTLP/HTTP traces URL, or "" when export is off. TEMMO_OTLP_ENDPOINT wins, then defaults.json "otlpEndpoint";
24
+ * a machine with a defaults.json but no such key gets DEFAULT_OTLP_ENDPOINT. No defaults.json (an isolated test
25
+ * HOME, a fresh install) means no export.
26
+ */
27
+ export function otlpEndpoint(env = process.env) {
28
+ const defaults = autoDefaults(env);
29
+ const value = env.TEMMO_OTLP_ENDPOINT ?? (defaults ? defaults.otlpEndpoint ?? DEFAULT_OTLP_ENDPOINT : "");
30
+ return typeof value === "string" && !OFF.has(value.trim().toLowerCase()) ? value.trim() : "";
31
+ }
32
+ const newId = (bytes) => randomBytes(bytes).toString("hex");
33
+ const clip = (value) => {
34
+ const text = typeof value === "string" ? value : JSON.stringify(value ?? {});
35
+ return text.length > INPUT_MAX ? text.slice(0, INPUT_MAX) : text;
36
+ };
37
+ /**
38
+ * The spans of one run. usage is {input, output, cacheRead, cacheWrite}; the prompt count includes cached tokens.
39
+ * tools are [{name, startMs, endMs, input, failed}].
40
+ */
41
+ export function runSpans({ address, role, model, startMs, endMs, usage, tools = [], status = "ok" }) {
42
+ const traceId = newId(16);
43
+ const rootId = newId(8);
44
+ const shared = { "session.id": address, ...(role ? { "temmo.role": role } : {}) };
45
+ const modelAttr = model ? { "llm.model_name": model } : {};
46
+ const tokens = usage ? (() => {
47
+ const prompt = (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
48
+ return {
49
+ "llm.token_count.prompt": prompt, "llm.token_count.completion": usage.output || 0, "llm.token_count.total": prompt + (usage.output || 0),
50
+ "llm.token_count.prompt_details.cache_read": usage.cacheRead || 0, "llm.token_count.prompt_details.cache_write": usage.cacheWrite || 0,
51
+ };
52
+ })() : {};
53
+ return [
54
+ {
55
+ traceId, spanId: rootId, name: "cursor-agent run", startMs, endMs,
56
+ attrs: { "openinference.span.kind": "AGENT", ...shared, ...modelAttr, "temmo.harness": "cursor", "temmo.status": status, "temmo.tool_calls": tools.length },
57
+ },
58
+ {
59
+ traceId, spanId: newId(8), parentSpanId: rootId, name: "cursor llm", startMs, endMs,
60
+ attrs: { "openinference.span.kind": "LLM", ...shared, ...modelAttr, "llm.provider": "cursor", ...tokens },
61
+ },
62
+ ...tools.map((tool) => ({
63
+ traceId, spanId: newId(8), parentSpanId: rootId, name: `tool ${tool.name}`, startMs: tool.startMs, endMs: Math.max(tool.startMs, tool.endMs),
64
+ attrs: { "openinference.span.kind": "TOOL", ...shared, "tool.name": tool.name, "input.value": clip(tool.input), ...(tool.failed ? { "temmo.failed": true } : {}) },
65
+ })),
66
+ ];
67
+ }
68
+ /** POSTs the spans as OTLP protobuf; resolves true on a 2xx, false on anything else. Never rejects. */
69
+ export async function exportSpans(spans, { endpoint, timeoutMs = EXPORT_TIMEOUT_MS, project = "temmo" } = {}) {
70
+ if (!endpoint || !spans.length)
71
+ return false;
72
+ try {
73
+ const res = await fetch(endpoint, {
74
+ method: "POST", headers: { "content-type": "application/x-protobuf" },
75
+ body: encodeTraceRequest(spans, { project, service: "temmo-cursor", scope: "temmo.cursor-trace" }),
76
+ signal: AbortSignal.timeout(timeoutMs),
77
+ });
78
+ await res.arrayBuffer().catch(() => { });
79
+ return res.ok;
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ function streamTool(toolCall) {
86
+ const key = Object.keys(toolCall ?? {})[0] ?? "tool";
87
+ const body = toolCall?.[key] ?? {};
88
+ const args = body?.args;
89
+ const name = args?.toolName || args?.name;
90
+ return { name: key === "mcpToolCall" && name ? `mcp ${name}` : key.replace(/ToolCall$/, "") || "tool", body };
91
+ }
92
+ /**
93
+ * One run's recorder: tool calls by id, usage, status. spans() closes calls still open as failed. The runner's ACP
94
+ * adapter drives it directly; streamTrace feeds it from stream-json.
95
+ */
96
+ export function runRecorder({ address, role, model, now = Date.now } = {}) {
97
+ const startMs = now();
98
+ const open = new Map();
99
+ const tools = [];
100
+ const rec = {
101
+ address, model, usage: null, status: "ok",
102
+ toolStart(id, name, input) { open.set(id, { name, startMs: now(), input }); },
103
+ toolEnd(id, { name, input, failed = false } = {}) {
104
+ const started = open.get(id) ?? { name: name || "tool", startMs: now(), input };
105
+ open.delete(id);
106
+ tools.push({ ...started, endMs: now(), failed });
107
+ },
108
+ spans({ status } = {}) {
109
+ const endMs = now();
110
+ const unfinished = [...open.values()].map((tool) => ({ ...tool, endMs, failed: true }));
111
+ return runSpans({ address: rec.address, role, model: rec.model, startMs, endMs, usage: rec.usage, tools: [...tools, ...unfinished], status: status ?? rec.status });
112
+ },
113
+ };
114
+ return rec;
115
+ }
116
+ /**
117
+ * A tracer fed the lines of `cursor-agent -p --output-format stream-json`. model is the --model the launcher passed
118
+ * (the init event names only a display label); address defaults to cursor#<label of the run's session id>.
119
+ */
120
+ export function streamTrace({ address, role, model, now = Date.now } = {}) {
121
+ const rec = runRecorder({ address, role, model, now });
122
+ let sessionId = "";
123
+ let shownModel = "";
124
+ return {
125
+ line(text) {
126
+ let event;
127
+ try {
128
+ event = JSON.parse(text);
129
+ }
130
+ catch {
131
+ return;
132
+ }
133
+ if (!event || typeof event !== "object")
134
+ return;
135
+ if (typeof event.session_id === "string")
136
+ sessionId ||= event.session_id;
137
+ if (event.type === "system" && typeof event.model === "string")
138
+ shownModel = event.model;
139
+ if (event.type === "tool_call" && typeof event.call_id === "string") {
140
+ const { name, body } = streamTool(event.tool_call);
141
+ const bodyArgs = body;
142
+ if (event.subtype === "started")
143
+ rec.toolStart(event.call_id, name, bodyArgs.args);
144
+ if (event.subtype === "completed")
145
+ rec.toolEnd(event.call_id, { name, input: bodyArgs.args, failed: Boolean(bodyArgs.result) && !bodyArgs.result?.success });
146
+ }
147
+ if (event.type === "result") {
148
+ rec.status = event.is_error ? "error" : "ok";
149
+ const u = event.usage;
150
+ if (u && typeof u === "object")
151
+ rec.usage = { input: u.inputTokens, output: u.outputTokens, cacheRead: u.cacheReadTokens, cacheWrite: u.cacheWriteTokens };
152
+ }
153
+ },
154
+ spans({ exitStatus } = {}) {
155
+ rec.address ||= `cursor#${sessionLabel(sessionId) || "unknown"}`;
156
+ rec.model ||= shownModel;
157
+ return rec.spans({ status: exitStatus });
158
+ },
159
+ };
160
+ }
161
+ /** Feeds a child's stdout through a streamTrace while passing it on to `out`; finish() exports the trace. */
162
+ export function traceStream(stream, { env = process.env, out, ...options }) {
163
+ const trace = streamTrace(options);
164
+ let rest = "";
165
+ stream.setEncoding("utf8");
166
+ stream.on("data", (chunk) => {
167
+ out?.write(chunk);
168
+ rest += chunk;
169
+ const lines = rest.split("\n");
170
+ rest = lines.pop() ?? "";
171
+ for (const line of lines)
172
+ trace.line(line);
173
+ });
174
+ return {
175
+ finish({ exitStatus } = {}) {
176
+ if (rest)
177
+ trace.line(rest);
178
+ rest = "";
179
+ return exportSpans(trace.spans({ exitStatus }), { endpoint: otlpEndpoint(env) });
180
+ },
181
+ };
182
+ }
183
+ const START_EVENTS = new Set(["sessionstart", "beforesubmitprompt"]);
184
+ const TOOL_EVENTS = new Set(["posttooluse", "posttoolusefailure"]);
185
+ const END_EVENTS = new Set(["stop", "sessionend"]);
186
+ /**
187
+ * Records one Cursor hook event in the state dir and, at stop or sessionEnd, exports the run's trace. A turn starts at
188
+ * sessionStart or beforeSubmitPrompt and ends at the next stop or sessionEnd (`-p` runs fire no stop). Returns the
189
+ * exported spans, or null.
190
+ */
191
+ export async function hookTrace(msg, { env = process.env, now = Date.now } = {}) {
192
+ // A launcher that traces the run itself (builder, runner-owned session) marks its Cursor process.
193
+ if (env[TRACE_ENV] || env.TEMMO_OWNED)
194
+ return null;
195
+ const endpoint = otlpEndpoint(env);
196
+ const label = sessionLabel(msg.conversation_id || msg.session_id);
197
+ if (!endpoint || !label)
198
+ return null;
199
+ const key = String(msg.hook_event_name || "").toLowerCase();
200
+ const dir = path.join(stateDir(env), HOOK_DIR);
201
+ const file = path.join(dir, `${label}.jsonl`);
202
+ const at = now();
203
+ const add = (record) => { mkdirSync(dir, { recursive: true, mode: 0o700 }); appendFileSync(file, JSON.stringify(record) + "\n", { mode: 0o600 }); };
204
+ if (START_EVENTS.has(key) && !existsSync(file))
205
+ add({ start: at, model: msg.model });
206
+ if (TOOL_EVENTS.has(key)) {
207
+ const duration = Number(msg.duration) || 0;
208
+ add({ tool: String(msg.tool_name || "tool"), id: msg.tool_use_id, at, duration, input: msg.tool_input, failed: key === "posttoolusefailure", model: msg.model });
209
+ }
210
+ if (!END_EVENTS.has(key) || !existsSync(file))
211
+ return null;
212
+ // Claimed by rename, so a second registration of the same hook finds nothing to export.
213
+ const claimed = `${file}.${process.pid}.${newId(4)}`;
214
+ try {
215
+ renameSync(file, claimed);
216
+ }
217
+ catch {
218
+ return null;
219
+ }
220
+ let records = [];
221
+ try {
222
+ records = readFileSync(claimed, "utf8").split("\n").filter(Boolean).map((line) => { try {
223
+ return JSON.parse(line);
224
+ }
225
+ catch {
226
+ return null;
227
+ } }).filter(Boolean);
228
+ }
229
+ finally {
230
+ rmSync(claimed, { force: true });
231
+ }
232
+ const seen = new Set();
233
+ const tools = [];
234
+ for (const r of records) {
235
+ if (!r.tool || (r.id && seen.has(r.id)))
236
+ continue;
237
+ if (r.id)
238
+ seen.add(r.id);
239
+ tools.push({ name: r.tool, startMs: r.at - Math.round(r.duration), endMs: r.at, input: r.input, failed: r.failed });
240
+ }
241
+ const durationMs = Number(msg.duration_ms) || 0;
242
+ const startMs = Math.min(records.find((r) => r.start)?.start ?? at, durationMs ? at - durationMs : at, ...tools.map((t) => t.startMs));
243
+ const model = records.find((r) => r.start && r.model)?.model || records.find((r) => r.model)?.model || msg.model;
244
+ const status = typeof msg.final_status === "string" ? msg.final_status : typeof msg.status === "string" ? msg.status : "ok";
245
+ const spans = runSpans({ address: `cursor#${label}`, role: env[ROLE_ENV] || "session", model, startMs, endMs: at, tools, status });
246
+ await exportSpans(spans, { endpoint });
247
+ return spans;
248
+ }
@@ -0,0 +1,20 @@
1
+ // UI deep links: the hash parameters web/lib/selection.js reads, on the base URL in TEMMO_UI_URL.
2
+ export function uiBase(env = process.env) {
3
+ const value = String(env.TEMMO_UI_URL || "").trim().replace(/\/+$/, "");
4
+ return /^https?:\/\/[^\s/]+(\/\S*)?$/.test(value) ? value : "";
5
+ }
6
+ /** A UI link to a project's chat, a session's thread, or one of its subagent runs; "" without a base URL. */
7
+ export function deepLink({ base = uiBase(), project, session = "", run = "" } = {}) {
8
+ if (!base || !project)
9
+ return "";
10
+ const params = new URLSearchParams({ project, level: session ? "session" : "project" });
11
+ if (session) {
12
+ params.set("harness", session.split("#")[0]);
13
+ params.set("session", session);
14
+ }
15
+ if (run) {
16
+ params.set("tab", "subagents");
17
+ params.set("run", run);
18
+ }
19
+ return `${base}/#${params}`;
20
+ }
@@ -0,0 +1,120 @@
1
+ // Pushes one message into a live, non-owned session: Claude socket, Codex queue, OpenCode HTTP.
2
+ // Shared by the UI dispatcher (web/server/dispatch.ts) and the runner's delivery workflows (runner/delivery.mjs).
3
+ import { execFile } from "node:child_process";
4
+ import { readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { receiptsTopic } from "./config.js";
7
+ import { claudeTarget, deliverToClaude } from "./claude-socket.js";
8
+ import { nativeSessionId, harnessEnv } from "./sessions/control.js";
9
+ import { parseEnvelope } from "./messaging.js";
10
+ import { sessionIdleState } from "./idle.js";
11
+ import { pollCached } from "./messaging.js";
12
+ import { opencodeRequest } from "./opencode-api.js";
13
+ import { readReceipts } from "./receipts.js";
14
+ import { argv } from "./harness.js";
15
+ import { writeState } from "./state.js";
16
+ import { stopHookRunning } from "./stop.js";
17
+ export const PUSHED = new Set(["claude", "codex", "opencode"]);
18
+ const CODEX_TIMEOUT_MS = 30_000;
19
+ // A direct, non-broadcast message that is not fyi: the only kind pushed.
20
+ export const direct = (m) => m.priority !== "fyi" && m.from !== "ntfy" && m.to !== "all";
21
+ // Runs a command and resolves its exit code (null on a spawn error or timeout).
22
+ export function runCommand(file, args, { env }) {
23
+ return new Promise((resolve) => {
24
+ // stdio is not in execFile's option types; a non-literal object passes it through unchanged.
25
+ const options = { env, timeout: CODEX_TIMEOUT_MS, stdio: "ignore" };
26
+ execFile(file, args, options, (error) => resolve(error ? (typeof error.code === "number" ? error.code : null) : 0));
27
+ });
28
+ }
29
+ /**
30
+ * Delivers text through the session's harness API. Resolves {status}: "delivered", "unsent", or for Claude "unconfirmed"
31
+ * with watch() and confirmedSince(id) (see lib/claude-socket.ts deliverToClaude).
32
+ */
33
+ export async function pushSession(session, text, { urgent, ids }, { env = process.env, run = runCommand, opencode = opencodeRequest, claude = deliverToClaude } = {}) {
34
+ if (!nativeSessionId(session.harness, session.sessionId))
35
+ return { status: "unsent" };
36
+ if (session.harness === "claude")
37
+ return await claude(session, { text, ids }, { env });
38
+ if (session.harness === "codex") {
39
+ const [file, args] = argv("codex", "queue", { id: session.sessionId, text });
40
+ const ok = await run(file, args, { env: harnessEnv() }) === 0;
41
+ return { status: ok ? "delivered" : "unsent" };
42
+ }
43
+ const r = await opencode("POST", `/api/session/${encodeURIComponent(session.sessionId)}/prompt`, {
44
+ body: { text, delivery: urgent ? "steer" : "queue", resume: true }, env,
45
+ });
46
+ return { status: r.ok ? "delivered" : "unsent" };
47
+ }
48
+ /**
49
+ * Whether a session takes a push now. Claude takes a socket message in any state, when its gate is open, except while its
50
+ * Stop hook runs: a socket push then marks the message delivered and the hold never sees it (cfg: the project config).
51
+ * Codex waits for an idle session; OpenCode takes a queued or steering prompt in any state (active is its active-session set, or null).
52
+ */
53
+ // Whether a Claude session's Stop hook runs now: its hold delivers the messages, so a push waits (scfg: the session's config).
54
+ export const holdRunning = (session, scfg) => session.harness === "claude" && stopHookRunning(scfg);
55
+ export async function readySession(session, active, { env = process.env, idle = sessionIdleState, cfg = null } = {}) {
56
+ if (session.harness === "claude") {
57
+ if (cfg && holdRunning(session, { ...cfg, peer: session.peer, session: session.session }))
58
+ return false;
59
+ return claudeTarget(session, { env }) !== null;
60
+ }
61
+ if (session.harness === "opencode")
62
+ return active !== null;
63
+ return await idle(session, { env }) === "idle";
64
+ }
65
+ // Whether a session still works on an earlier push: an OpenCode session with a running turn queues a new copy behind it.
66
+ export const busyWithPush = (session, active) => session.harness === "opencode" && Boolean(active?.has(session.sessionId));
67
+ /**
68
+ * Read receipts and replies for delivered messages. refresh(cfg, topics) folds new events in; acked(id, address) is true
69
+ * once the address read the message or answered it.
70
+ */
71
+ export function ackTracker({ poll = pollCached } = {}) {
72
+ const reads = new Map();
73
+ const answers = new Map();
74
+ const cursors = new Map();
75
+ return {
76
+ async refresh(cfg, topics) {
77
+ for (const topic of topics) {
78
+ const key = `${cfg.project}\n${topic}`;
79
+ let events;
80
+ try {
81
+ events = await poll(cfg, topic, cursors.get(key) || "all");
82
+ }
83
+ catch {
84
+ continue;
85
+ }
86
+ if (events.length)
87
+ cursors.set(key, events.at(-1).id);
88
+ if (topic === receiptsTopic(cfg.project)) {
89
+ readReceipts(events, reads);
90
+ continue;
91
+ }
92
+ for (const ev of events) {
93
+ const m = parseEnvelope(ev.message);
94
+ if (m?.kind !== "msg" || typeof m.replyTo !== "string" || typeof m.session !== "string")
95
+ continue;
96
+ if (!answers.has(m.replyTo))
97
+ answers.set(m.replyTo, new Set());
98
+ answers.get(m.replyTo).add(`${m.from}#${m.session}`);
99
+ }
100
+ }
101
+ },
102
+ acked: (id, address) => Boolean(reads.get(id)?.has(address) || answers.get(id)?.has(address)),
103
+ };
104
+ }
105
+ // The UI dispatcher's ledger of expect-reply messages it delivered: {entries: {<msg id>: {address, firstAt, lastAt, attempts, message}}}.
106
+ export function dispatchLedgerFile(cfg) {
107
+ return join(cfg.stateDir, cfg.project, "dispatch.json");
108
+ }
109
+ export function readDispatchLedger(cfg) {
110
+ try {
111
+ const entries = JSON.parse(readFileSync(dispatchLedgerFile(cfg), "utf8")).entries;
112
+ return entries && typeof entries === "object" ? entries : {};
113
+ }
114
+ catch {
115
+ return {};
116
+ }
117
+ }
118
+ export function writeDispatchLedger(cfg, entries) {
119
+ writeState(dispatchLedgerFile(cfg), { entries });
120
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Push delivery policy: the rules the runner's durable workflow (runner/delivery.ts) and the UI dispatcher
3
+ * (web/server/dispatch.ts) both follow. Pure: each engine keeps its own I/O, persistence and timers.
4
+ */
5
+ export const REDELIVER_MS = 10 * 60_000;
6
+ export const MAX_ATTEMPTS = 5;
7
+ export const TTL_MS = 24 * 3_600_000;
8
+ export const BACKOFF_BASE_MS = 5_000;
9
+ export const BACKOFF_MAX_MS = 10 * 60_000;
10
+ /** Wait after the nth failed push: BACKOFF_BASE_MS doubling, capped at BACKOFF_MAX_MS. */
11
+ export function backoffMs(failures) {
12
+ return Math.min(BACKOFF_BASE_MS * 2 ** (failures - 1), BACKOFF_MAX_MS);
13
+ }
14
+ /** The next step for one message, checked in this order: answer, TTL, redelivery timing, attempt cap, busy, ready. */
15
+ export function nextAction(state, now, facts) {
16
+ const redelivery = state.pushes > 0;
17
+ if (redelivery && facts.acked)
18
+ return "answered";
19
+ if (state.firstAt !== null && now - state.firstAt >= TTL_MS)
20
+ return "expired";
21
+ if (redelivery && state.dueAt !== null && now < state.dueAt)
22
+ return "wait";
23
+ if (redelivery && state.pushes >= MAX_ATTEMPTS)
24
+ return "dropped";
25
+ if (redelivery && facts.busy)
26
+ return "wait";
27
+ return facts.ready ? "push" : "wait";
28
+ }
@@ -0,0 +1,227 @@
1
+ // The deployed tree: one link the systemd units run through, the drop-ins that route them, and the --from source checks.
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, resolve, sep } from "node:path";
5
+ import { stateDir, stallLimitMs } from "./config.js";
6
+ import { PACKAGE_NAME } from "./names.js";
7
+ import { runnerRequest, runnerSocket } from "./runner-request.js";
8
+ export const DROP_IN = "deploy-tree.conf";
9
+ export const DBOS_VERSION = /export const DBOS_APP_VERSION = "([^"]+)"/;
10
+ export const BRANCH_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
11
+ /** Escape a literal string for use inside a RegExp. */
12
+ function escapeRegExp(text) {
13
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+ }
15
+ /** Last non-empty line of a stream, for error messages. */
16
+ function lastLine(text) {
17
+ return (text || "").trim().split("\n").at(-1) || "";
18
+ }
19
+ /** Symlink the systemd units run through. */
20
+ export function deployLink(env) {
21
+ return join(stateDir(env), "current");
22
+ }
23
+ /** Current deploy target, or null when the link is absent. */
24
+ export function readLink(env) {
25
+ try {
26
+ return readlinkSync(deployLink(env));
27
+ }
28
+ catch (err) {
29
+ if (err.code === "ENOENT")
30
+ return null;
31
+ throw err;
32
+ }
33
+ }
34
+ /** Atomically point the deploy link at absolute tree. */
35
+ export function pointLink(env, tree) {
36
+ mkdirSync(stateDir(env), { recursive: true });
37
+ const link = deployLink(env);
38
+ const tmp = `${link}.tmp-${process.pid}`;
39
+ rmSync(tmp, { force: true });
40
+ symlinkSync(tree, tmp);
41
+ renameSync(tmp, link);
42
+ }
43
+ /** Cache holding one worktree per deployed branch. */
44
+ export function deployCache(env) {
45
+ return join(env.XDG_CACHE_HOME || join(env.HOME || homedir(), ".cache"), "temmo-deploy");
46
+ }
47
+ /** Directory of user systemd units. */
48
+ export function unitsDir(env) {
49
+ return join(env.XDG_CONFIG_HOME || join(env.HOME || homedir(), ".config"), "systemd", "user");
50
+ }
51
+ /** Effective [Service] WorkingDirectory and ExecStart across unit and drop-ins. */
52
+ function parseService(unitText, dropIns) {
53
+ let workingDirectory = null;
54
+ let execStart = [];
55
+ for (const text of [unitText, ...dropIns]) {
56
+ let section = "";
57
+ for (const raw of text.split(/\r?\n/)) {
58
+ const line = raw.trim();
59
+ if (line.startsWith("[")) {
60
+ section = line;
61
+ }
62
+ else if (section === "[Service]" && line.startsWith("WorkingDirectory=")) {
63
+ workingDirectory = line.slice("WorkingDirectory=".length).trim();
64
+ }
65
+ else if (section === "[Service]" && line.startsWith("ExecStart=")) {
66
+ const value = line.slice("ExecStart=".length).trim();
67
+ execStart = value === "" ? [] : [...execStart, value];
68
+ }
69
+ }
70
+ }
71
+ return { workingDirectory, execStart };
72
+ }
73
+ /** Matches the checkout path (absolute or %h form) only at a token boundary. */
74
+ function checkoutPattern(hostCheckout, home) {
75
+ const forms = [hostCheckout];
76
+ if (hostCheckout.startsWith(`${home}/`))
77
+ forms.push(`%h${hostCheckout.slice(home.length)}`);
78
+ return `(?:${forms.map(escapeRegExp).join("|")})(?=/|\\s|$)`;
79
+ }
80
+ /** Drop-in text that repoints a unit at the deployed tree. */
81
+ export function unitDropIn({ unitText, dropIns, hostCheckout, home, link }) {
82
+ const { execStart } = parseService(unitText, dropIns);
83
+ if (execStart.length !== 1)
84
+ throw new Error(`unit needs exactly one ExecStart, found ${execStart.length}`);
85
+ const command = execStart[0];
86
+ const pattern = checkoutPattern(hostCheckout, home);
87
+ if (!new RegExp(pattern).test(command))
88
+ throw new Error(`ExecStart does not run the host checkout ${hostCheckout}: ${command}`);
89
+ const rewritten = command.replace(new RegExp(pattern, "g"), link);
90
+ return [
91
+ `# Written by \`temmo deploy --install-units\`: the service runs the deployed tree through ${link}.`,
92
+ "[Service]",
93
+ `WorkingDirectory=${link}`,
94
+ "ExecStart=",
95
+ `ExecStart=${rewritten}`,
96
+ "",
97
+ ].join("\n");
98
+ }
99
+ /** Write the deploy drop-in for each service and reload systemd. */
100
+ export async function installUnits({ env, hostCheckout, run, services }) {
101
+ const dir = unitsDir(env);
102
+ const link = deployLink(env);
103
+ const home = env.HOME || homedir();
104
+ const written = [];
105
+ for (const service of services) {
106
+ const unitPath = join(dir, `${service}.service`);
107
+ if (!existsSync(unitPath))
108
+ throw new Error(`${unitPath} is missing`);
109
+ const unitText = readFileSync(unitPath, "utf8");
110
+ const dropInDir = join(dir, `${service}.service.d`);
111
+ const dropIns = [];
112
+ if (existsSync(dropInDir)) {
113
+ const names = readdirSync(dropInDir).filter((name) => name.endsWith(".conf") && name !== DROP_IN).sort();
114
+ for (const name of names)
115
+ dropIns.push(readFileSync(join(dropInDir, name), "utf8"));
116
+ }
117
+ const text = unitDropIn({ unitText, dropIns, hostCheckout, home, link });
118
+ mkdirSync(dropInDir, { recursive: true });
119
+ const dropInPath = join(dropInDir, DROP_IN);
120
+ writeFileSync(dropInPath, text);
121
+ written.push(dropInPath);
122
+ }
123
+ if (readLink(env) === null)
124
+ pointLink(env, hostCheckout);
125
+ const res = await run("systemctl", ["--user", "daemon-reload"], { encoding: "utf8" });
126
+ if (res.status !== 0)
127
+ throw new Error(lastLine(res.stderr) || "systemctl --user daemon-reload failed");
128
+ return written;
129
+ }
130
+ /** True when every service already has the deploy drop-in. */
131
+ export function unitsInstalled(env, services) {
132
+ const dir = unitsDir(env);
133
+ return services.every((service) => existsSync(join(dir, `${service}.service.d`, DROP_IN)));
134
+ }
135
+ /** DBOS app version declared in the tree, or null. */
136
+ export function dbosVersion(tree) {
137
+ const file = join(tree, "lib", "workflows.ts");
138
+ if (!existsSync(file))
139
+ return null;
140
+ return readFileSync(file, "utf8").match(DBOS_VERSION)?.[1] ?? null;
141
+ }
142
+ /** Addresses of sessions the runner reports as running; a turn idle past the stall limit no longer holds deploy. */
143
+ export async function inFlight(env, { request = runnerRequest } = {}) {
144
+ try {
145
+ const res = await request("GET", "/v1/sessions", undefined, { socket: runnerSocket(env), timeoutMs: 3000 });
146
+ if (res.status !== 200)
147
+ return [];
148
+ // A session whose view carries no lastActivityAt (an older runner) still counts as in flight.
149
+ const stalledBefore = Date.now() - stallLimitMs(env);
150
+ const live = (s) => s.status === "running" && !(typeof s.lastActivityAt === "number" && s.lastActivityAt < stalledBefore);
151
+ return (res.body?.sessions ?? []).filter(live).map((s) => s.session);
152
+ }
153
+ catch {
154
+ return [];
155
+ }
156
+ }
157
+ /** Resolve a deploy source (path or branch name) to { kind, tree, ref }. */
158
+ export async function resolveSource(from, { run, hostCheckout, env, cwd }) {
159
+ if (from.startsWith("/") || from.startsWith("./") || from.startsWith("../")) {
160
+ const tree = realpathSync(resolve(cwd, from));
161
+ const top = await run("git", ["rev-parse", "--show-toplevel"], { cwd: tree, encoding: "utf8" });
162
+ if (top.status !== 0 || top.stdout.trim() !== tree)
163
+ throw new Error(`${tree} is not a git checkout`);
164
+ const pkgPath = join(tree, "package.json");
165
+ let pkg;
166
+ try {
167
+ pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
168
+ }
169
+ catch {
170
+ throw new Error(`${pkgPath} is missing or unreadable`);
171
+ }
172
+ // A tree from before the rename still carries the old package name.
173
+ if (pkg.name !== PACKAGE_NAME && pkg.name !== "ai-collab")
174
+ throw new Error(`${tree} is not a temmo checkout`);
175
+ const head = await run("git", ["symbolic-ref", "--short", "-q", "HEAD"], { cwd: tree, encoding: "utf8" });
176
+ if (head.status === 0 && head.stdout.trim())
177
+ return { kind: "path", tree, ref: head.stdout.trim() };
178
+ const sha = await run("git", ["rev-parse", "HEAD"], { cwd: tree, encoding: "utf8" });
179
+ if (sha.status !== 0)
180
+ throw new Error(`${tree} has no HEAD commit`);
181
+ return { kind: "path", tree, ref: `detached ${sha.stdout.trim().slice(0, 12)}` };
182
+ }
183
+ if (from === "main")
184
+ throw new Error("refusing branch main: use --main");
185
+ if (!BRANCH_NAME.test(from))
186
+ throw new Error(`${from} is not a valid branch name`);
187
+ const valid = await run("git", ["check-ref-format", "--branch", from], { cwd: hostCheckout, encoding: "utf8" });
188
+ if (valid.status !== 0)
189
+ throw new Error(`${from} is not a valid branch name`);
190
+ const cache = deployCache(env);
191
+ const tree = join(cache, from);
192
+ if (tree !== cache && !tree.startsWith(cache + sep))
193
+ throw new Error(`${from} escapes the deploy cache`);
194
+ return { kind: "branch", tree, ref: from };
195
+ }
196
+ /** Run git in cwd; throw with the last stderr line on failure. */
197
+ async function gitOrThrow(run, cwd, args) {
198
+ const res = await run("git", args, { cwd, encoding: "utf8" });
199
+ if (res.status !== 0)
200
+ throw new Error(lastLine(res.stderr) || `git ${args[0]} failed`);
201
+ return res.stdout.trim();
202
+ }
203
+ /** Materialize branch as a detached tree; returns the commit sha. */
204
+ export async function checkoutBranch({ run, hostCheckout, tree, branch }) {
205
+ const local = await run("git", ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`], { cwd: hostCheckout, encoding: "utf8" });
206
+ let sha = local.stdout.trim();
207
+ if (local.status !== 0 || !sha) {
208
+ const fetched = await run("git", ["fetch", "--quiet", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], { cwd: hostCheckout, encoding: "utf8" });
209
+ if (fetched.status !== 0)
210
+ throw new Error(lastLine(fetched.stderr) || `git fetch ${branch} failed`);
211
+ sha = await gitOrThrow(run, hostCheckout, ["rev-parse", `refs/remotes/origin/${branch}^{commit}`]);
212
+ }
213
+ if (!sha)
214
+ throw new Error(`${branch} does not resolve to a commit`);
215
+ if (!existsSync(tree)) {
216
+ mkdirSync(dirname(tree), { recursive: true });
217
+ await gitOrThrow(run, hostCheckout, ["worktree", "add", "--detach", tree, sha]);
218
+ }
219
+ else {
220
+ await gitOrThrow(run, tree, ["checkout", "--detach", "--quiet", sha]);
221
+ }
222
+ return sha;
223
+ }
224
+ /** True when the tree has uncommitted tracked changes. */
225
+ export async function dirty(run, tree) {
226
+ return (await gitOrThrow(run, tree, ["status", "--porcelain", "--untracked-files=no"])).length > 0;
227
+ }