@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/bus.js ADDED
@@ -0,0 +1,349 @@
1
+ /**
2
+ * The local message bus: the ntfy-subset HTTP API the plugin already speaks, served from this machine's
3
+ * Postgres (lib/bus-postgres.ts) instead of a container. Same topics, same JSON-line protocol, same
4
+ * Bearer token, so every client (hooks, runner, UI server, tests) is unchanged; what changes is where events live.
5
+ *
6
+ * Endpoints (the subset lib/messaging.ts uses):
7
+ * POST / JSON publish {topic, message, title?}
8
+ * PUT /<topic>?message=&filename= attachment publish, file as the body
9
+ * GET /file/<id> attachment bytes
10
+ * GET /<topic>/json?poll=1&since= cached bounded read (NDJSON)
11
+ * GET /<t1,t2>/json?since= streaming subscription (NDJSON until close)
12
+ * POST /tasks/<op> the host task store for sandboxed sessions (lib/task-route.ts)
13
+ *
14
+ * Durability: events and attachments survive a restart, and retention is days instead of ntfy's 12 h
15
+ * cache, so an AFK gap or a runner restart cannot drop an approval or a reply. No rate limits: the
16
+ * bus is loopback-only (sandboxes arrive through host.openshell.internal) behind a shared token.
17
+ */
18
+ import http, {} from "node:http";
19
+ import { threadRoute } from "./thread-routes.js";
20
+ import { agentsRoute } from "./agents-route.js";
21
+ import { threadChannelRoute } from "./thread-channel-store.js";
22
+ import { isOperatorCredential } from "./operator-token.js";
23
+ import { taskRoute } from "./task-route.js";
24
+ export const DEFAULT_RETENTION_MS = 7 * 24 * 3_600_000;
25
+ const MESSAGE_MAX_BYTES = 64 * 1024;
26
+ const FILE_MAX_BYTES = 16 * 1024 * 1024;
27
+ const FILE_EXT = /\.(png|jpe?g|gif|webp|txt)$/i;
28
+ // oxlint-disable-next-line quality/no-known-value-widening -- looked up by a runtime file extension
29
+ const FILE_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".txt": "text/plain; charset=utf-8" };
30
+ function fileType(name) {
31
+ const ext = String(name).slice(String(name).lastIndexOf(".")).toLowerCase();
32
+ return FILE_TYPES[ext] || "application/octet-stream";
33
+ }
34
+ // ntfy turns the two characters \n of a query-string message into a newline; clients respell them, and the
35
+ // bus turns them back. Kept so the wire stays identical for anything that already escapes this way.
36
+ const unescapeQuery = (text) => String(text ?? "").replaceAll("\\n", "\n");
37
+ /** The store kind: TEMMO_BUS_STORE, else defaults.json busStore, else postgres; the SQLite store is retired. */
38
+ export function resolveBusStoreKind(env = process.env, defaults = {}) {
39
+ const kind = env.TEMMO_BUS_STORE || defaults.busStore || "postgres";
40
+ if (kind === "sqlite")
41
+ throw new Error("bus: the SQLite store (bus.db) is retired; set busStore to postgres or remove it (docs/configuration.md#bus-store)");
42
+ if (kind !== "postgres")
43
+ throw new Error(`bus: unknown store ${kind}; use postgres`);
44
+ return kind;
45
+ }
46
+ /**
47
+ * "since" as clients send it: "all", a duration (90m, 12h, 3d), unix seconds (9+ digits), or an event id.
48
+ * Returns {kind, value} where kind is all|time|id|none.
49
+ */
50
+ export function parseSince(since, nowSec = Math.floor(Date.now() / 1000)) {
51
+ const s = String(since ?? "");
52
+ if (s === "" || s === "all")
53
+ return { kind: "all" };
54
+ const dur = /^(\d+)(s|m|h|d)$/.exec(s);
55
+ if (dur) {
56
+ // oxlint-disable-next-line quality/no-known-value-widening -- looked up by the runtime duration unit
57
+ const unit = { s: 1, m: 60, h: 3600, d: 86400 }[dur[2]];
58
+ return { kind: "time", value: nowSec - Number(dur[1]) * unit };
59
+ }
60
+ if (/^\d{9,}$/.test(s))
61
+ return { kind: "time", value: Number(s) };
62
+ if (/^\d+$/.test(s))
63
+ return { kind: "id", value: Number(s) };
64
+ return { kind: "none" };
65
+ }
66
+ /**
67
+ * The store interface the server calls. Every operation may return a value or a promise (the server awaits):
68
+ * kind "memory" | "postgres"
69
+ * publish({topic, message, title, attachment}) -> event
70
+ * resolve(topics, since) -> {since, reset} the since to read from; an unknown id reads all, reset true
71
+ * poll(topic, since) -> events the cached read
72
+ * stream(topics, since, send) -> unsubscribe backfill from since, then each new event for topics
73
+ * putFile({name, data}) -> {file, type, size}
74
+ * getFile(id) -> {data, type, name, size} | null
75
+ * prune(nowSec?) -> {events, files}
76
+ * threads? the thread store (lib/threads.ts); Postgres only, docs/threads.md
77
+ * close()
78
+ */
79
+ /** Events and attachments in memory: what the test fake runs on, and enough for a throwaway bus. */
80
+ export function openMemoryStore() {
81
+ const events = [];
82
+ const subscribers = new Set();
83
+ const state = { seq: 0, files: new Map() };
84
+ const store = {
85
+ kind: "memory",
86
+ files: state.files,
87
+ publish({ topic, message, title = "", attachment = null, verified = false }) {
88
+ state.seq += 1;
89
+ const ev = {
90
+ id: String(state.seq),
91
+ time: Math.floor(Date.now() / 1000),
92
+ event: "message",
93
+ topic,
94
+ message,
95
+ title,
96
+ ...(attachment ? { attachment } : {}),
97
+ ...(verified ? { verified: true } : {}),
98
+ };
99
+ events.push(ev);
100
+ for (const send of subscribers)
101
+ send(ev);
102
+ return ev;
103
+ },
104
+ resolve(topics, since) {
105
+ const s = parseSince(since);
106
+ if (s.kind === "all" || s.kind === "time")
107
+ return { since, reset: false };
108
+ const known = s.kind === "id" && events.some((e) => topics.includes(e.topic) && Number(e.id) === s.value);
109
+ return known ? { since, reset: false } : { since: "all", reset: true };
110
+ },
111
+ poll(topic, since) {
112
+ const all = events.filter((e) => e.topic === topic);
113
+ const s = parseSince(since || "all");
114
+ if (s.kind === "all")
115
+ return all;
116
+ if (s.kind === "time")
117
+ return all.filter((e) => e.time >= s.value);
118
+ if (s.kind === "id") {
119
+ const idx = all.findIndex((e) => Number(e.id) === s.value);
120
+ return idx >= 0 ? all.slice(idx + 1) : all; // unknown id: everything, dedup must cope
121
+ }
122
+ return all;
123
+ },
124
+ backfill(topics, since) {
125
+ const s = parseSince(since);
126
+ const all = events.filter((e) => topics.includes(e.topic));
127
+ if (s.kind === "all")
128
+ return all;
129
+ if (s.kind === "time")
130
+ return all.filter((e) => e.time >= s.value);
131
+ if (s.kind === "id")
132
+ return all.filter((e) => Number(e.id) > s.value);
133
+ return [];
134
+ },
135
+ subscribe(send) {
136
+ subscribers.add(send);
137
+ return () => subscribers.delete(send);
138
+ },
139
+ stream(topics, since, send) {
140
+ for (const ev of store.backfill(topics, since))
141
+ send(ev);
142
+ return store.subscribe((ev) => { if (topics.includes(ev.topic))
143
+ send(ev); });
144
+ },
145
+ putFile({ name, data }) {
146
+ const ext = (FILE_EXT.exec(name)?.[0] || ".bin").toLowerCase();
147
+ const file = `f${state.files.size + 1}${ext}`;
148
+ state.files.set(file, { data, type: fileType(name) });
149
+ return { file, type: fileType(name), size: data.length };
150
+ },
151
+ getFile(id) {
152
+ const hit = state.files.get(String(id));
153
+ return hit ? { ...hit, name: String(id), size: hit.data.length } : null;
154
+ },
155
+ prune() { return { events: 0, files: 0 }; },
156
+ close() { subscribers.clear(); },
157
+ };
158
+ return store;
159
+ }
160
+ async function readBody(req, maxBytes) {
161
+ const chunks = [];
162
+ let total = 0;
163
+ for await (const chunk of req) {
164
+ total += chunk.length;
165
+ if (total > maxBytes) {
166
+ req.destroy();
167
+ throw Object.assign(new Error("body too large"), { status: 413 });
168
+ }
169
+ chunks.push(chunk);
170
+ }
171
+ return Buffer.concat(chunks);
172
+ }
173
+ /**
174
+ * The bus server. `store` holds events and attachments; `token` (when set) is required as a Bearer token
175
+ * on every request, the same trust boundary the ntfy token was. `operatorToken` is accepted wherever `token` is,
176
+ * and an event published with it is stamped `verified` (lib/operator-token.ts). `hooks` is optional and test-only: onRequest
177
+ * (awaited first), fault(req) and onPoll(rec) may return {status, body, headers} to refuse a request, and
178
+ * onPublish, onPoll, onSubscribe, onFileRead observe traffic. Production passes none and keeps no log.
179
+ */
180
+ export function createBusServer({ store, token = "", operatorToken = "", baseUrl = "", hooks = {}, directory = null, tasks = null }) {
181
+ const server = http.createServer(async (req, res) => {
182
+ await hooks.onRequest?.(req);
183
+ const operator = isOperatorCredential(req.headers.authorization, operatorToken);
184
+ if (token && !operator && req.headers.authorization !== `Bearer ${token}`) {
185
+ res.writeHead(401);
186
+ return res.end("unauthorized");
187
+ }
188
+ const fault = hooks.fault?.(req);
189
+ if (fault) {
190
+ res.writeHead(fault.status, fault.headers || {});
191
+ return res.end(fault.body);
192
+ }
193
+ const url = new URL(req.url, "http://bus.invalid");
194
+ const base = () => baseUrl || `http://127.0.0.1:${server.address().port}`;
195
+ if (req.method === "POST" && url.pathname === "/") {
196
+ // oxlint-disable-next-line typescript/no-explicit-any -- the publish body is client JSON, checked below
197
+ let body;
198
+ try {
199
+ body = JSON.parse((await readBody(req, MESSAGE_MAX_BYTES)).toString("utf8"));
200
+ }
201
+ catch {
202
+ res.writeHead(400);
203
+ return res.end("bad json");
204
+ }
205
+ if (typeof body.topic !== "string" || typeof body.message !== "string") {
206
+ res.writeHead(400);
207
+ return res.end("missing topic or message");
208
+ }
209
+ const ev = await store.publish({ topic: body.topic, message: body.message, title: body.title || "", ...(typeof body.thread_id === "string" ? { threadId: body.thread_id } : {}), verified: operator });
210
+ hooks.onPublish?.({ id: ev.id, topic: body.topic, message: body.message, title: body.title || "", auth: req.headers.authorization || "" });
211
+ res.writeHead(200, { "content-type": "application/json" });
212
+ return res.end(JSON.stringify(ev));
213
+ }
214
+ const put = /^\/([^/]+)$/.exec(url.pathname);
215
+ if (req.method === "PUT" && put) {
216
+ let data;
217
+ try {
218
+ data = await readBody(req, FILE_MAX_BYTES);
219
+ }
220
+ catch (error) {
221
+ res.writeHead(error.status || 400);
222
+ return res.end(error.message);
223
+ }
224
+ const name = url.searchParams.get("filename") || "file";
225
+ const saved = await store.putFile({ name, data });
226
+ const topic = decodeURIComponent(put[1]);
227
+ const message = unescapeQuery(url.searchParams.get("message"));
228
+ const title = url.searchParams.get("title") || "";
229
+ const threadId = url.searchParams.get("thread_id");
230
+ const ev = await store.publish({
231
+ topic, message, title, ...(threadId ? { threadId } : {}), verified: operator,
232
+ attachment: { name, type: saved.type, size: saved.size, url: `${base()}/file/${saved.file}` },
233
+ });
234
+ hooks.onPublish?.({ id: ev.id, topic, message, title, auth: req.headers.authorization || "", attachment: { name, size: data.length } });
235
+ res.writeHead(200, { "content-type": "application/json" });
236
+ return res.end(JSON.stringify(ev));
237
+ }
238
+ const fileMatch = /^\/file\/([^/]+)$/.exec(url.pathname);
239
+ if (req.method === "GET" && fileMatch) {
240
+ const hit = await store.getFile(fileMatch[1]);
241
+ if (!hit) {
242
+ res.writeHead(404);
243
+ return res.end();
244
+ }
245
+ hooks.onFileRead?.(decodeURIComponent(fileMatch[1]));
246
+ res.writeHead(200, { "content-type": hit.type });
247
+ return res.end(hit.data);
248
+ }
249
+ const json = /^\/(.+)\/json$/.exec(url.pathname);
250
+ if (req.method === "GET" && json && url.searchParams.get("poll") === "1") {
251
+ const topic = decodeURIComponent(json[1]);
252
+ const since = url.searchParams.get("since") || "all";
253
+ const refused = hooks.onPoll?.({ topic, since, poll: "1" });
254
+ if (refused) {
255
+ res.writeHead(refused.status, refused.headers || {});
256
+ return res.end(refused.body);
257
+ }
258
+ const cursor = await store.resolve([topic], since);
259
+ const out = await store.poll(topic, cursor.since);
260
+ res.writeHead(200, { "content-type": "application/x-ndjson" });
261
+ const line = (ev) => JSON.stringify(cursor.reset ? { ...ev, reset: true } : ev);
262
+ const keep = out.map(line);
263
+ keep.push(line({ id: "keepalive", time: 0, event: "keepalive", topic }));
264
+ return res.end(`${keep.join("\n")}\n`);
265
+ }
266
+ if (req.method === "GET" && json) {
267
+ const names = json[1].split(",").map(decodeURIComponent);
268
+ const since = url.searchParams.get("since") || "";
269
+ hooks.onSubscribe?.({ topics: names, since });
270
+ let cursor;
271
+ try {
272
+ cursor = await store.resolve(names, since);
273
+ }
274
+ catch {
275
+ res.writeHead(500);
276
+ return res.end();
277
+ }
278
+ res.writeHead(200, { "content-type": "application/x-ndjson", "cache-control": "no-cache", "x-accel-buffering": "no" });
279
+ res.write(`${JSON.stringify({ id: "open", time: 0, event: "open", topic: names.join(","), ...(cursor.reset ? { reset: true } : {}) })}\n`);
280
+ let closed = false;
281
+ // lastSeen only guards against a duplicate the store could hand us twice.
282
+ let lastSeen = 0n;
283
+ const send = (ev) => {
284
+ if (closed || !names.includes(ev.topic))
285
+ return;
286
+ const id = BigInt(ev.id);
287
+ if (id <= lastSeen)
288
+ return;
289
+ lastSeen = id;
290
+ res.write(`${JSON.stringify(ev)}\n`);
291
+ };
292
+ const keepalive = setInterval(() => {
293
+ if (!closed)
294
+ res.write(`${JSON.stringify({ id: "keepalive", time: 0, event: "keepalive", topic: names.join(",") })}\n`);
295
+ }, 30_000);
296
+ keepalive.unref?.();
297
+ let unsubscribe = () => { };
298
+ req.on("close", () => {
299
+ closed = true;
300
+ clearInterval(keepalive);
301
+ unsubscribe();
302
+ });
303
+ // A store may await its backlog read, so a client that left meanwhile is unsubscribed on arrival.
304
+ let stop;
305
+ try {
306
+ stop = await store.stream(names, cursor.since, send);
307
+ }
308
+ catch {
309
+ clearInterval(keepalive);
310
+ return res.end();
311
+ }
312
+ if (closed)
313
+ stop();
314
+ else
315
+ unsubscribe = stop;
316
+ return;
317
+ }
318
+ if (agentsRoute(directory, req, res, url))
319
+ return;
320
+ if (await taskRoute(tasks, req, res, url))
321
+ return;
322
+ if (await threadChannelRoute(store, req, res, url))
323
+ return;
324
+ if (await threadRoute(store, req, res, url))
325
+ return;
326
+ res.writeHead(404);
327
+ res.end();
328
+ });
329
+ return {
330
+ server,
331
+ listen: (port = 0, host = "127.0.0.1") => new Promise((resolve) => server.listen(port, host, () => resolve(`http://${host}:${server.address().port}`))),
332
+ close: () => new Promise((resolve) => {
333
+ server.closeAllConnections();
334
+ server.close(() => resolve());
335
+ }),
336
+ };
337
+ }
338
+ /** The production bundle: an opened store (Postgres in production) plus the server in front of it. */
339
+ export function openBus({ store, token = "", operatorToken = "", baseUrl = "", directory = null, tasks = null }) {
340
+ if (!store)
341
+ throw new Error("openBus: pass an opened store");
342
+ const bus = createBusServer({ store, token, operatorToken, baseUrl, directory, tasks });
343
+ return {
344
+ ...bus,
345
+ store,
346
+ prune: () => store.prune(),
347
+ close: async () => { await bus.close(); await store.close(); },
348
+ };
349
+ }
@@ -0,0 +1,278 @@
1
+ /** Team author: chat becomes a writing agent's brief; its answer's DOT is checked by the save path before anything is written. */
2
+ import { execFile } from "node:child_process";
3
+ import { isValidName } from "../config.js";
4
+ import { childEnv, PROMPT_MAX_CHARS } from "../sessions/launch.js";
5
+ import { cursorBinary } from "../harness.js";
6
+ import { findExecutable } from "../sessions/scope.js";
7
+ import { argv, FALLBACK_MODEL, formatHarnessModel, HARNESSES, isHarness, parseHarnessModel } from "../harness.js";
8
+ import { parseDot } from "./dot.js";
9
+ import { checkTeamText, listPatterns, saveTeamText, validatePatternModels } from "./patterns.js";
10
+ import { listTeams } from "./teams.js";
11
+ import { globalTeamsDir, isRegularFile, saveTeamFile, teamFilePath } from "./team-files.js";
12
+ /** One message or role prompt the brief carries; longer text is cut so the brief stays one start prompt. */
13
+ const AUTHOR_TEXT_MAX = 1200;
14
+ /** The brief is one start prompt (lib/sessions/launch.ts checkPrompt), so it has the same cap. Test-only export. */
15
+ export const AUTHOR_PROMPT_MAX = PROMPT_MAX_CHARS;
16
+ /** Chat turns carried into the brief, oldest first. */
17
+ const AUTHOR_TURNS_MAX = 12;
18
+ /** The order a fallback writer is taken in; the house default comes first. */
19
+ const AUTHOR_PREFERENCE = ["cursor", "claude", "codex", "opencode"];
20
+ const AUTHOR_SCOPES = ["project", "global"];
21
+ const FENCE = /```[ \t]*(?:dot|graphviz)?[ \t]*\r?\n([\s\S]*?)```/g;
22
+ const WRITER_TIMEOUT_MS = 180_000;
23
+ const FAILURE_DETAIL_MAX = 300;
24
+ const TEAM_NAME_HINT = "team-name";
25
+ /** The models a vague request falls back to; the first is the house default. */
26
+ const HOUSE_MODELS = `cursor:${FALLBACK_MODEL}, claude:claude-haiku-5-5, opencode:lemonade/Qwen-Qwen4-35B-A3B-Loom, then plain codex or opencode`;
27
+ // The team.dot rules a writing agent needs, in the order it fills the file in.
28
+ const CONTRACT = `- Name the digraph for the team: digraph "NAME" { ... }. It must match the team name exactly.
29
+ - One node per role: <id> [agent="HARNESS[:MODEL]", prompt="..."];
30
+ - Role id: 1-24 chars of a-z, 0-9 and "-", starting with a letter; "done" is not an id. 1-8 roles.
31
+ - prompt: the role's responsibility in one or two sentences, 1-1000 chars. Required on every role.
32
+ - agent harness: claude, codex, cursor or opencode; add ":model" only when the operator names one.
33
+ - Extra node attributes, when useful: count=1..8 (instances), skill="name", fallback="harness[:model]".
34
+ - One edge per handoff: from -> to [on="event", kind="pair", required=true];
35
+ - kind is pair (default), broadcast or fan-in; required=true means the run cannot finish without it.
36
+ - cap=1..10 limits a role-to-role handoff's repeats. A pair edge needs the same count on both roles.
37
+ - "done" only receives an edge; never declare it. At least one edge must reach done.
38
+ - Every role must be reachable from the first role, which is the entry role.
39
+ - graph [description="one sentence", max_visits=1..50] is optional.
40
+ - No node/edge defaults, no subgraphs, no variables. Quote ids that contain "-".
41
+ - Prefer few roles: one per distinct responsibility, and one handoff event per real transition.`;
42
+ const oneLine = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
43
+ const scopeLine = (scope) => (scope === "global"
44
+ ? "Scope: global — the file is saved in the config directory and every project can use it."
45
+ : "Scope: project — the file is saved in this project's .ai-collab/teams folder.");
46
+ function turnLines(turns) {
47
+ const lines = [];
48
+ for (const turn of turns) {
49
+ const text = oneLine(turn?.text).slice(0, AUTHOR_TEXT_MAX);
50
+ if (text)
51
+ lines.push(`${turn?.from === "agent" ? "Your last answer" : "Operator"}: ${text}`);
52
+ }
53
+ return lines;
54
+ }
55
+ /** Test-only: the brief for the writing agent: its one job, the team.dot contract, the name and scope, the team being edited (if any), the chat so far, and the operator's request. Always fits one start prompt. */
56
+ export function buildAuthorPrompt({ request, name = "", scope = "project", current = "", turns = [], peers = [] } = {}) {
57
+ const named = isValidName(name);
58
+ const teamName = named ? name : TEAM_NAME_HINT;
59
+ const useScope = AUTHOR_SCOPES.includes(scope) ? scope : "project";
60
+ const harnesses = (Array.isArray(peers) ? peers : []).filter((peer) => HARNESSES.includes(peer));
61
+ let useRequest = oneLine(request).slice(0, AUTHOR_TEXT_MAX);
62
+ let useCurrent = String(current ?? "").trim();
63
+ let useTurns = (Array.isArray(turns) ? turns : []).filter((turn) => oneLine(turn?.text)).slice(-AUTHOR_TURNS_MAX);
64
+ const compose = () => {
65
+ const lines = [
66
+ "You author teams for temmo. Turn the operator's request into one team.dot file.",
67
+ "",
68
+ "Answer with exactly one fenced block and nothing else:",
69
+ "```dot",
70
+ `digraph "${teamName}" {`,
71
+ " ...",
72
+ "}",
73
+ "```",
74
+ "",
75
+ "The file must pass these checks:",
76
+ CONTRACT,
77
+ "",
78
+ `Team name: ${named ? teamName : "the name the operator confirms"}`,
79
+ scopeLine(useScope),
80
+ harnesses.length ? `This project may run: ${harnesses.join(", ")}.` : "",
81
+ `When the operator names no model, prefer ${HOUSE_MODELS}.`,
82
+ ];
83
+ if (useCurrent)
84
+ lines.push("", "The team as it is now; change only what the request asks for:", "```dot", useCurrent, "```");
85
+ const history = turnLines(useTurns);
86
+ if (history.length)
87
+ lines.push("", "Conversation so far, oldest first:", ...history);
88
+ lines.push("", useTurns.length ? "New request from the operator:" : "Operator request:", useRequest || "(the operator has not said yet)");
89
+ return lines.join("\n");
90
+ };
91
+ // An oversized brief keeps its rules and its name, and drops history, then the current team, then request text.
92
+ for (;;) {
93
+ const text = compose();
94
+ if (text.length <= AUTHOR_PROMPT_MAX)
95
+ return text;
96
+ if (useTurns.length) {
97
+ useTurns = useTurns.slice(1);
98
+ continue;
99
+ }
100
+ if (useCurrent.length > 400) {
101
+ useCurrent = `${useCurrent.slice(0, 400)}\n...`;
102
+ continue;
103
+ }
104
+ if (useRequest.length > 200) {
105
+ useRequest = `${useRequest.slice(0, 200)}...`;
106
+ continue;
107
+ }
108
+ return text.slice(0, AUTHOR_PROMPT_MAX);
109
+ }
110
+ }
111
+ /** Every block that could hold DOT, in the order the writing agent wrote them: fenced blocks, then a bare digraph. */
112
+ function dotBlocks(text) {
113
+ const source = String(text ?? "");
114
+ const blocks = [];
115
+ for (const match of source.matchAll(FENCE)) {
116
+ const body = match[1].trim();
117
+ if (body)
118
+ blocks.push(body);
119
+ }
120
+ const start = /^\s*digraph\b/m.exec(source);
121
+ const end = source.lastIndexOf("}");
122
+ if (start && end > start.index)
123
+ blocks.push(source.slice(start.index, end + 1).trim());
124
+ return blocks;
125
+ }
126
+ /** Test-only: the first block that parses as team.dot, else the first block as written ("" when the answer has none). */
127
+ export function extractDot(reply) {
128
+ const blocks = dotBlocks(String(reply ?? ""));
129
+ for (const block of blocks) {
130
+ try {
131
+ parseDot(block);
132
+ return block;
133
+ }
134
+ catch { /* next block */ }
135
+ }
136
+ return blocks[0] ?? "";
137
+ }
138
+ /**
139
+ * Test-only export. The DOT from a writing agent's answer, checked by the same parse and validate a save uses.
140
+ * `exists` is the source of the entry already using the name ("" when the name is free).
141
+ * `suggested` is the digraph name the agent wrote, so the UI can propose it when the operator left the name blank.
142
+ */
143
+ export function draftTeam(cfg, { name = "", reply = "", env = process.env } = {}) {
144
+ const dot = extractDot(reply);
145
+ if (!dot)
146
+ return { ok: false, error: "The answer has no DOT block; ask the agent for one ```dot block.", line: null, dot: "", suggested: "", name: "" };
147
+ const suggested = (() => { try {
148
+ return parseDot(dot).name;
149
+ }
150
+ catch {
151
+ return "";
152
+ } })();
153
+ // With no name yet, the digraph name the agent wrote is the proposal the operator confirms.
154
+ const useName = isValidName(name) ? name : suggested;
155
+ const check = checkTeamText(cfg, useName, dot);
156
+ const all = listPatterns(cfg, env);
157
+ const existing = Object.hasOwn(all, useName) ? all[useName] : undefined;
158
+ if (!check.ok)
159
+ return { ...check, dot, suggested, name: useName };
160
+ return { ...check, dot, suggested, name: useName, exists: existing?.source ?? "" };
161
+ }
162
+ /**
163
+ * Saves authored DOT as a team file in the project or global teams directory.
164
+ *
165
+ * The text is parsed, validated and model-checked first. An existing entry of the same name is replaced only
166
+ * when `replace` names it (the operator's confirm), a built-in is never shadowed, and a legacy roster name is
167
+ * refused. Project saves go through saveTeamText, so they take the same locks and drop a shadowed JSON pattern.
168
+ */
169
+ export async function saveAuthoredTeam(cfg, { name, dot, scope = "project", replace = "", env = process.env, models } = {}) {
170
+ const teamName = String(name ?? "");
171
+ if (!isValidName(teamName))
172
+ throw new Error("Team name must be 1-24 chars of a-z, 0-9 and single hyphens");
173
+ if (!AUTHOR_SCOPES.includes(scope))
174
+ throw new Error('Scope must be "project" or "global"');
175
+ const confirmed = replace === teamName && Boolean(teamName);
176
+ const check = checkTeamText(cfg, teamName, String(dot ?? ""));
177
+ if (!check.ok)
178
+ throw Object.assign(new Error(check.error), { line: check.line });
179
+ const text = `${String(dot).trimEnd()}\n`;
180
+ const all = listPatterns(cfg, env);
181
+ const existing = Object.hasOwn(all, teamName) ? all[teamName] : undefined;
182
+ if (existing?.source === "built-in")
183
+ throw new Error(`"${teamName}" is a built-in pattern; pick another name`);
184
+ if (listTeams(cfg, env)[teamName])
185
+ throw new Error(`"${teamName}" is a team name; pick another`);
186
+ // Saving into the other scope would make a second file that silently shadows the first.
187
+ if (existing && scope === "project" && existing.source === "global") {
188
+ throw new Error(`"${teamName}" is a global team; save it with global scope, or pick another name`);
189
+ }
190
+ if (existing && scope === "global" && existing.source === "project") {
191
+ throw new Error(`"${teamName}" is a project team; edit that copy, or pick another name`);
192
+ }
193
+ if (existing && !confirmed)
194
+ throw new Error(`"${teamName}" already exists; confirm the replacement to save over it`);
195
+ if (scope === "project") {
196
+ // saveTeamText takes the projects.json lock, writes the file and drops a shadowed JSON pattern.
197
+ return await saveTeamText(cfg, teamName, text, env, models, { create: !confirmed });
198
+ }
199
+ const file = teamFilePath(globalTeamsDir(env), teamName);
200
+ if (isRegularFile(file) && !confirmed)
201
+ throw new Error(`"${teamName}" already exists; confirm the replacement to save over it`);
202
+ await validatePatternModels(check.pattern, cfg, env, models);
203
+ saveTeamFile(file, text);
204
+ return { ...check.pattern, source: "global", file };
205
+ }
206
+ /** Harness and model for the writing agent: TEMMO_TEAM_AUTHOR_MODEL, else the house default. */
207
+ export function authorModel(env = process.env) {
208
+ const raw = String(env.TEMMO_TEAM_AUTHOR_MODEL || formatHarnessModel({ harness: "cursor", model: FALLBACK_MODEL })).trim();
209
+ const [harness] = raw.split(":");
210
+ if (!isHarness(harness))
211
+ return { harness: "cursor", model: FALLBACK_MODEL };
212
+ return parseHarnessModel(raw) ?? { harness, model: "" };
213
+ }
214
+ /**
215
+ * Test-only export. The writer to use: authorModel, unless the project cannot run that harness and another is installed, in which case
216
+ * that harness writes with no model (a model name belongs to the harness it was chosen for).
217
+ */
218
+ export function authorHarness(env = process.env, startable = []) {
219
+ const chosen = authorModel(env);
220
+ if (!startable.length || startable.includes(chosen.harness))
221
+ return chosen;
222
+ const fallback = AUTHOR_PREFERENCE.find((harness) => startable.includes(harness));
223
+ return fallback ? { harness: fallback, model: "" } : chosen;
224
+ }
225
+ /** Test-only: the argv for one non-interactive writing-agent turn; the brief is one element, so no shell quoting applies. */
226
+ export function authorCommand(harness, prompt, model = "") {
227
+ if (!isHarness(harness))
228
+ return null;
229
+ return argv(harness, "author", { prompt, model });
230
+ }
231
+ const defaultExec = (file, args, options) => new Promise((resolve) => {
232
+ execFile(file, args, { ...options, timeout: WRITER_TIMEOUT_MS, maxBuffer: 1 << 20, shell: false }, (error, stdout, stderr) => resolve({
233
+ code: error ? (typeof error.code === "number" ? error.code : 1) : 0,
234
+ stdout: String(stdout || ""),
235
+ stderr: String(stderr || ""),
236
+ }));
237
+ });
238
+ /**
239
+ * One writing-agent turn: the brief goes to the harness as a single argument and its stdout comes back.
240
+ * Resolves { status:"answered", reply } or { status:"failed", detail }; an injected `run` stands in for the whole
241
+ * exec step (it is called with the harness name, so a test needs no binary on PATH), and with no `run` the binary
242
+ * must be on PATH or the turn fails as "not installed". A non-zero exit keeps the harness's own stderr (a usage
243
+ * limit is printed there and stdout is empty), so the operator sees why it stopped.
244
+ */
245
+ async function askAuthor(prompt, { harness, model, env = process.env, run }) {
246
+ const command = authorCommand(harness, String(prompt ?? ""), model ?? "");
247
+ if (!command)
248
+ return { status: "failed", detail: `unknown harness "${harness}"` };
249
+ const vars = childEnv(env);
250
+ const [binary, args] = command;
251
+ const name = harness === "cursor" && !run ? cursorBinary(vars.PATH) : binary;
252
+ const exec = run ?? defaultExec;
253
+ const file = run ? name : findExecutable(name, vars.PATH);
254
+ if (!file)
255
+ return { status: "failed", detail: `${name} is not installed` };
256
+ const result = await exec(file, args, { env: vars, cwd: env.HOME || process.cwd() });
257
+ const reply = String(result?.stdout ?? "").trim();
258
+ const errorText = String(result?.stderr ?? "").trim();
259
+ if (result?.code !== 0) {
260
+ const why = (reply || errorText).replace(/\s+/g, " ").slice(0, FAILURE_DETAIL_MAX);
261
+ return { status: "failed", detail: `${name} exited ${result?.code}${why ? `: ${why}` : ""}`, reply };
262
+ }
263
+ if (!reply)
264
+ return { status: "failed", detail: `${name} answered nothing` };
265
+ return { status: "answered", reply, harness: harness, file };
266
+ }
267
+ /**
268
+ * One authoring turn end to end: build the brief, ask a writing agent, and check the DOT it returned.
269
+ * The operator sees the draft; nothing is saved until saveAuthoredTeam with the confirmed name.
270
+ */
271
+ export async function authorTeam(cfg, { request, name = "", scope = "project", current = "", turns = [], peers = [], startable = [], env = process.env, harness, model, run } = {}) {
272
+ const prompt = buildAuthorPrompt({ request, name, scope, current, turns, peers });
273
+ const chosen = authorHarness(env, startable);
274
+ const answer = await askAuthor(prompt, { harness: harness ?? chosen.harness, model: model ?? chosen.model, env, ...(run ? { run } : {}) });
275
+ if (answer.status !== "answered")
276
+ return { ...answer, prompt };
277
+ return { ...answer, prompt, ...draftTeam(cfg, { name, reply: answer.reply, env }) };
278
+ }