@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,372 @@
1
+ /**
2
+ * Data sources for `temmo analyze run-code`. A source is {name, load({since, until}) -> {turns?, scheduleRuns?,
3
+ * tasks?, notes?}}; a Phoenix source can implement the same interface later. A turn is one model response:
4
+ * {harness, native, cwd, sub, model, ts (ms), tok: {input, cw5, cw1, cacheRead, output} | null, calls: [call]}
5
+ * and a call is {name, path, refused, failed}. `input` is uncached input; cache writes are separate.
6
+ */
7
+ import { execFileSync } from "node:child_process";
8
+ import { globSync, readFileSync, statSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { DatabaseSync } from "node:sqlite";
12
+ import { READ_TOOLS } from "./code-run.js";
13
+ import { commandSegments, isStoreBypass } from "./store-read.js";
14
+ export const READ_PATHS = ["mcp_read", "cli_read", "run_code", "run_read_code"];
15
+ // CLI read commands that `temmo` answers through run_code once readsThroughRunCode is on (see readProgram in cli.mjs).
16
+ const CLI_READ = /^(?:\S*\/)?temmo\s+(?:task\s+(?:list|show)|agents|sessions|history|peers|team\s+status|pattern\s+list|status)\b/;
17
+ const CLI_READ_LOOSE = /(?:^|[\s"'`;&|(])(?:\S*\/)?temmo\s+(?:task\s+(?:list|show)|agents|sessions|history|peers|team\s+status|pattern\s+list|status)\b/;
18
+ const REFUSAL = /through run_code|reads go through run_code/;
19
+ // Transcripts from before the rename name the servers ai-collab and ai-collab-code.
20
+ const MCP_NAME = /^(?:mcp__)?(?:plugin_(?:temmo|ai-collab)_)?(temmo-code|temmo|ai-collab-code|ai-collab)(?:__|_)(.+)$/;
21
+ const text = (value) => typeof value === "string" ? value : value == null ? "" : JSON.stringify(value);
22
+ const str = (value) => Array.isArray(value) ? value.join(" ") : text(value);
23
+ /** The temmo read path a tool call used, or null: {path, tool}. */
24
+ export function classifyCall({ name = "", input, loose = false }) {
25
+ const mcp = MCP_NAME.exec(name);
26
+ if (mcp) {
27
+ const [, server, tool] = mcp;
28
+ if (server.endsWith("-code"))
29
+ return { path: tool === "run_read_code" ? "run_read_code" : tool === "run_code" ? "run_code" : null, tool };
30
+ return { path: READ_TOOLS.includes(tool) ? "mcp_read" : null, tool };
31
+ }
32
+ const command = typeof input === "string" ? input : str(input?.command ?? input?.cmd);
33
+ const bypassCall = { name, input };
34
+ if (command) {
35
+ if (loose ? CLI_READ_LOOSE.test(command) : commandSegments(command).some((s) => CLI_READ.test(s)))
36
+ return { path: "cli_read", tool: "cli" };
37
+ if (isStoreBypass(bypassCall))
38
+ return { path: "bypass_read", tool: "shell" };
39
+ return { path: null, tool: name };
40
+ }
41
+ if (isStoreBypass(bypassCall))
42
+ return { path: "bypass_read", tool: name.toLowerCase() };
43
+ return { path: null, tool: name };
44
+ }
45
+ export const isRefusal = (content) => REFUSAL.test(text(content));
46
+ /** A run_code result that failed: ok:false, a staging error, or an error that is not a read refusal. */
47
+ export function isRunCodeFailure(content, isError) {
48
+ const s = text(content);
49
+ if (isRefusal(s))
50
+ return false;
51
+ return /"ok"\s*:\s*false/.test(s) || /could not stage/.test(s) || Boolean(isError);
52
+ }
53
+ function makeCall(name, input, loose) {
54
+ const { path } = classifyCall({ name, input, loose });
55
+ return { name, path, refused: false, failed: false };
56
+ }
57
+ function settle(call, content, isError) {
58
+ if (!call.path)
59
+ return;
60
+ if (call.path !== "bypass_read" && isRefusal(content))
61
+ call.refused = true;
62
+ else if ((call.path === "run_code" || call.path === "run_read_code") && isRunCodeFailure(content, isError))
63
+ call.failed = true;
64
+ }
65
+ const inWindow = (ts, { since, until }) => Number.isFinite(ts) && !(since != null && ts < since) && !(until != null && ts >= until);
66
+ const lines = (file) => readFileSync(file, "utf8").split("\n");
67
+ const parse = (line) => { try {
68
+ return JSON.parse(line);
69
+ }
70
+ catch {
71
+ return null;
72
+ } };
73
+ const files = (home, pattern) => globSync(join(home, pattern));
74
+ /** Claude Code transcripts: dedupe on message.id + requestId, keep the max output count, union the tool_use blocks. */
75
+ export function claudeSource({ home = homedir() } = {}) {
76
+ return {
77
+ name: "claude-transcripts",
78
+ async load(win = {}) {
79
+ const turns = [];
80
+ for (const file of files(home, ".claude/projects/**/*.jsonl")) {
81
+ const byKey = new Map();
82
+ const pending = new Map();
83
+ for (const line of lines(file)) {
84
+ const wantsResult = pending.size && line.includes("tool_result");
85
+ if (!wantsResult && !line.includes('"usage"'))
86
+ continue;
87
+ const d = parse(line);
88
+ const m = d?.message;
89
+ if (!m || typeof m !== "object")
90
+ continue;
91
+ if ((m).role === "user" && wantsResult && Array.isArray((m).content)) {
92
+ for (const p of (m).content) {
93
+ const tuId = (p).tool_use_id;
94
+ if ((p).type === "tool_result" && pending.has(tuId))
95
+ settle(pending.get(tuId), (p).content, (p).is_error === true);
96
+ }
97
+ continue;
98
+ }
99
+ if ((m).role !== "assistant" || !(m).usage || !(m).id || !d.timestamp || !(m).model || (m).model.startsWith("<"))
100
+ continue;
101
+ const key = `${(m).id}|${d.requestId ?? ""}`;
102
+ let turn = byKey.get(key);
103
+ if (!turn) {
104
+ turn = { harness: "claude", native: d.sessionId || (file.split("/").pop() || "").replace(/\.jsonl$/, ""), cwd: d.cwd || "", sub: d.isSidechain === true || file.includes("/subagents/"), model: (m).model, ts: Date.parse(d.timestamp || ""), tok: null, calls: [], ids: new Set() };
105
+ byKey.set(key, turn);
106
+ }
107
+ const u = (m).usage;
108
+ if (!turn.tok || (u?.output_tokens || 0) >= turn.tok.output) {
109
+ const cc = (u?.cache_creation || {});
110
+ const c1 = cc.ephemeral_1h_input_tokens || 0;
111
+ let c5 = cc.ephemeral_5m_input_tokens || 0;
112
+ const total = u?.cache_creation_input_tokens || 0;
113
+ if (c1 + c5 < total)
114
+ c5 = total - c1;
115
+ turn.tok = { input: u?.input_tokens || 0, cw5: c5, cw1: c1, cacheRead: u?.cache_read_input_tokens || 0, output: u?.output_tokens || 0 };
116
+ }
117
+ for (const p of Array.isArray((m).content) ? (m).content : []) {
118
+ if ((p).type !== "tool_use" || turn.ids.has((p).id))
119
+ continue;
120
+ turn.ids.add((p).id);
121
+ const call = makeCall((p).name, (p).input, false);
122
+ turn.calls.push(call);
123
+ if (call.path)
124
+ pending.set((p).id, call);
125
+ }
126
+ }
127
+ for (const turn of byKey.values()) {
128
+ delete turn.ids;
129
+ if (inWindow(turn.ts, win))
130
+ turns.push(turn);
131
+ }
132
+ }
133
+ return { turns };
134
+ },
135
+ };
136
+ }
137
+ /** Codex rollouts: one turn per response_id from token_usage_record; calls attach to the next usage record. */
138
+ export function codexSource({ home = homedir() } = {}) {
139
+ return {
140
+ name: "codex-sessions",
141
+ async load(win = {}) {
142
+ const turns = [];
143
+ for (const file of files(home, ".codex/sessions/**/*.jsonl")) {
144
+ let native = file;
145
+ let cwd = "";
146
+ let sub = false;
147
+ let model = "";
148
+ const models = new Map();
149
+ const seen = new Set();
150
+ const byCall = new Map();
151
+ let queued = [];
152
+ let last = null;
153
+ const emit = (ts, tid, tok) => {
154
+ const t = { harness: "codex", native, cwd, sub, model: models.get(tid) || model, ts: Date.parse(ts), tok, calls: queued };
155
+ queued = [];
156
+ last = t;
157
+ if (inWindow(t.ts, win))
158
+ turns.push(t);
159
+ };
160
+ for (const line of lines(file)) {
161
+ const d = parse(line);
162
+ const p = (d?.payload || {});
163
+ if (d?.type === "session_meta") {
164
+ native = (p).id || native;
165
+ cwd = (p).cwd || cwd;
166
+ sub = Boolean((p).source?.subagent) || sub;
167
+ }
168
+ else if (d?.type === "turn_context") {
169
+ model = (p).model || model;
170
+ models.set((p).turn_id, (p).model);
171
+ cwd = (p).cwd || cwd;
172
+ }
173
+ else if (d?.type === "response_item" && ((p).type === "function_call" || (p).type === "custom_tool_call")) {
174
+ const call = makeCall((p).namespace ? `${(p).namespace}${(p).name}` : (p).name, (p).type === "function_call" ? parseArgs((p).arguments) : (p).input, (p).type === "custom_tool_call");
175
+ byCall.set((p).call_id, call);
176
+ queued.push(call);
177
+ }
178
+ else if (d?.type === "response_item" && ((p).type === "function_call_output" || (p).type === "custom_tool_call_output")) {
179
+ const call = byCall.get((p).call_id);
180
+ if (call)
181
+ settle(call, outputText((p).output), false);
182
+ }
183
+ else if (d?.type === "token_usage_record" && (p).usage) {
184
+ if (seen.has((p).response_id))
185
+ continue;
186
+ seen.add((p).response_id);
187
+ const u = (p).usage;
188
+ emit(d?.timestamp, (p).turn_id, { input: (u?.input_tokens || 0) - (u?.cached_input_tokens || 0), cw5: 0, cw1: 0, cacheRead: u?.cached_input_tokens || 0, output: u?.output_tokens || 0 });
189
+ }
190
+ }
191
+ if (queued.length && last) {
192
+ last.calls.push(...queued);
193
+ }
194
+ }
195
+ return { turns };
196
+ },
197
+ };
198
+ }
199
+ const parseArgs = (value) => { if (typeof value !== "string")
200
+ return value; try {
201
+ return JSON.parse(value);
202
+ }
203
+ catch {
204
+ return value;
205
+ } };
206
+ const outputText = (out) => Array.isArray(out) ? out.map((o) => o?.text ?? "").join("\n") : text(out);
207
+ const dbReadOnly = (file) => new DatabaseSync(file, { readOnly: true });
208
+ /** OpenCode: assistant messages carry tokens; tool parts hang off a message. */
209
+ export function opencodeSource({ home = homedir() } = {}) {
210
+ return {
211
+ name: "opencode-db",
212
+ async load(win = {}) {
213
+ const file = join(home, ".local/share/opencode/opencode.db");
214
+ let db;
215
+ try {
216
+ db = dbReadOnly(file);
217
+ }
218
+ catch {
219
+ return { turns: [], notes: ["OpenCode database not readable"] };
220
+ }
221
+ try {
222
+ const parts = new Map();
223
+ for (const r of db.prepare("select message_id, data from part where json_extract(data, '$.type') = 'tool'").all()) {
224
+ const p = parse(r.data);
225
+ if (!p)
226
+ continue;
227
+ const state = (p).state;
228
+ const call = makeCall((p).tool, state?.input, false);
229
+ settle(call, state?.output ?? state?.error, state?.status === "error");
230
+ const arr = parts.get(r.message_id);
231
+ if (arr)
232
+ arr.push(call);
233
+ else
234
+ parts.set(r.message_id, [call]);
235
+ }
236
+ const turns = [];
237
+ const q = "select m.id, m.session_id, m.time_created, m.data, s.directory, s.parent_id from message m left join session s on s.id = m.session_id";
238
+ for (const r of db.prepare(q).all()) {
239
+ const d = parse(r.data);
240
+ if (d?.role !== "assistant")
241
+ continue;
242
+ const t = d.tokens || {};
243
+ const ts = Number(r.time_created);
244
+ if (!inWindow(ts, win))
245
+ continue;
246
+ const c = t.cache || {};
247
+ const tok = t.input || t.output ? { input: t.input || 0, cw5: c.write || 0, cw1: 0, cacheRead: c.read || 0, output: (t.output || 0) + (t.reasoning || 0) } : null;
248
+ turns.push({ harness: "opencode", native: r.session_id, cwd: r.directory || "", sub: Boolean(r.parent_id), model: d.modelID || "unknown", provider: d.providerID, ts, tok, calls: parts.get(r.id) || [] });
249
+ }
250
+ return { turns };
251
+ }
252
+ finally {
253
+ db.close();
254
+ }
255
+ },
256
+ };
257
+ }
258
+ /** Cursor chat stores: tool calls and model name only. No usage and no per-message time, so a turn dates from its session. */
259
+ export function cursorSource({ home = homedir() } = {}) {
260
+ return {
261
+ name: "cursor-chats",
262
+ async load(win = {}) {
263
+ const turns = [];
264
+ for (const file of files(home, ".cursor/chats/*/*/store.db")) {
265
+ let db;
266
+ try {
267
+ db = dbReadOnly(file);
268
+ }
269
+ catch {
270
+ continue;
271
+ }
272
+ try {
273
+ const meta = parse(Buffer.from(String((db.prepare("select value from meta limit 1").get()?.value ?? "")), "hex").toString());
274
+ if (!meta?.agentId)
275
+ continue;
276
+ const createdAt = Number(meta.createdAt) || statSync(file).mtimeMs;
277
+ if (!inWindow(createdAt, win))
278
+ continue;
279
+ const byCall = new Map();
280
+ let model = "";
281
+ const own = [];
282
+ for (const r of db.prepare("select data from blobs").all()) {
283
+ const b = Buffer.from(r.data);
284
+ if (b[0] !== 123)
285
+ continue;
286
+ const d = parse(b.toString());
287
+ if (!d || !Array.isArray((d).content))
288
+ continue;
289
+ if ((d).role === "assistant") {
290
+ const calls = [];
291
+ for (const p of (d).content) {
292
+ model = (p).providerOptions?.cursor?.modelName || model;
293
+ if ((p).type !== "tool-call")
294
+ continue;
295
+ const mcp = (p).toolName === "CallMcpTool" && (p).args ? `mcp__${(p).args.server}__${(p).args.toolName}` : (p).toolName;
296
+ const call = makeCall(mcp, (p).args, false);
297
+ byCall.set((p).toolCallId, call);
298
+ calls.push(call);
299
+ }
300
+ own.push({ calls, model });
301
+ }
302
+ else if ((d).role === "tool") {
303
+ for (const p of (d).content) {
304
+ if ((p).type === "tool-result" && byCall.has((p).toolCallId)) {
305
+ const call = byCall.get((p).toolCallId);
306
+ if (call)
307
+ settle(call, (p).result, false);
308
+ }
309
+ }
310
+ }
311
+ }
312
+ for (const t of own)
313
+ turns.push({ harness: "cursor", native: meta.agentId || "", cwd: "", sub: false, model: t.model || model || "unknown", ts: createdAt, tok: null, calls: t.calls, sessionSpan: [createdAt, statSync(file).mtimeMs] });
314
+ }
315
+ finally {
316
+ db.close();
317
+ }
318
+ }
319
+ return { turns, notes: ["Cursor stores no token usage and no per-message time: turns date from session creation."] };
320
+ },
321
+ };
322
+ }
323
+ /** Runner schedule log lines `<name>: ok|failed[ (<reason>)] in <ms> ms` from the user journal. `run` returns journalctl JSON lines. */
324
+ export function journalSource({ run } = {}) {
325
+ const exec = run || ((win) => {
326
+ const args = ["--user", "-u", "temmo-runner", "-u", "ai-collab-runner", "-o", "json", "--no-pager", "-g", "(ok|failed)( \\(.*\\))? in [0-9]+ ms"];
327
+ if (win.since != null)
328
+ args.push("--since", new Date(win.since).toISOString().replace("T", " ").slice(0, 19) + " UTC");
329
+ if (win.until != null)
330
+ args.push("--until", new Date(win.until).toISOString().replace("T", " ").slice(0, 19) + " UTC");
331
+ return execFileSync("journalctl", args, { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
332
+ });
333
+ return {
334
+ name: "runner-journal",
335
+ async load(win = {}) {
336
+ let raw;
337
+ try {
338
+ raw = exec(win);
339
+ }
340
+ catch (e) {
341
+ return { scheduleRuns: [], notes: [`journalctl unavailable: ${String(e.message).split("\n")[0]}`] };
342
+ }
343
+ const scheduleRuns = [];
344
+ for (const line of raw.split("\n")) {
345
+ const d = line ? parse(line) : null;
346
+ const m = d ? (/(?:^|\s)([\w.-]+): (ok|failed)(?: \(.*\))? in (\d+) ms\s*$/.exec(text(d.MESSAGE))) : null;
347
+ if (!m)
348
+ continue;
349
+ const ts = Number(d?.__REALTIME_TIMESTAMP) / 1000;
350
+ if (inWindow(ts, win))
351
+ scheduleRuns.push({ name: m[1], ok: m[2] === "ok", ms: Number(m[3]), ts });
352
+ }
353
+ return { scheduleRuns };
354
+ },
355
+ };
356
+ }
357
+ /** Task store: how many tasks were last updated as done per period (a throughput check, not a per-agent metric). */
358
+ export function taskStoreSource({ home = homedir() } = {}) {
359
+ return {
360
+ name: "task-store",
361
+ async load() {
362
+ const tasks = [];
363
+ for (const file of files(home, ".local/share/temmo/tasks/*.json")) {
364
+ const d = parse(readFileSync(file, "utf8"));
365
+ const taskList = Array.isArray(d?.tasks) ? d.tasks : [];
366
+ for (const t of taskList)
367
+ tasks.push({ id: (t).id, status: (t).status, updated: (t).updated, created: (t).created, progress: ((t).progress || []).length });
368
+ }
369
+ return { tasks };
370
+ },
371
+ };
372
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Approval cards on the wire: question cleaning and the size fit every card goes through. A leaf module, so the
3
+ * approval, question and limit-alert modules can share it without importing one another.
4
+ */
5
+ import { encodeEnvelope } from "./agui.js";
6
+ import { MESSAGE_MAX_BYTES } from "./config.js";
7
+ import { stripControl } from "./format.js";
8
+ const QUESTION_MAX = 500;
9
+ const HEADER_MAX = 40;
10
+ const LABEL_MAX = 100;
11
+ const QUESTIONS_MAX = 4;
12
+ const OPTIONS_MAX = 6;
13
+ // Last resort: a summary longer than this is cut before the card is refused (a limit card lists every joined session).
14
+ const SUMMARY_FIT_MAX = 200;
15
+ export const text = (value, max) => typeof value === "string" ? stripControl(value).slice(0, max) : "";
16
+ /** AskUserQuestion questions with every field type-checked and capped, or null when the shape is wrong. */
17
+ export function cleanQuestions(raw, { descriptionMax = 300, previewMax = 2000 } = {}) {
18
+ if (!Array.isArray(raw) || !raw.length || raw.length > QUESTIONS_MAX)
19
+ return null;
20
+ const out = [];
21
+ for (const q of raw) {
22
+ if (!q || typeof q.question !== "string" || !q.question.trim() || !Array.isArray(q.options) || !q.options.length)
23
+ return null;
24
+ const options = q.options.slice(0, OPTIONS_MAX).map((o) => ({
25
+ label: text(o?.label, LABEL_MAX),
26
+ ...(descriptionMax && text(o?.description, descriptionMax) ? { description: text(o.description, descriptionMax) } : {}),
27
+ ...(previewMax && text(o?.preview, previewMax) ? { preview: text(o.preview, previewMax) } : {}),
28
+ }));
29
+ if (options.some((o) => !o.label))
30
+ return null;
31
+ out.push({ question: text(q.question, QUESTION_MAX), header: text(q.header, HEADER_MAX), multiSelect: q.multiSelect === true, options });
32
+ }
33
+ return out;
34
+ }
35
+ function fitWith(kind, base, rawQuestions, wire) {
36
+ const tries = rawQuestions ? [[300, 2000], [200, 400], [100, 0], [0, 0]] : [[0, 0]];
37
+ for (const [descriptionMax, previewMax] of tries) {
38
+ const questions = rawQuestions ? cleanQuestions(rawQuestions, { descriptionMax, previewMax }) : undefined;
39
+ const message = encodeEnvelope(kind, questions ? { ...base, questions } : base, wire);
40
+ if (Buffer.byteLength(message) <= MESSAGE_MAX_BYTES)
41
+ return message;
42
+ }
43
+ return null;
44
+ }
45
+ /**
46
+ * An envelope of `kind` within MESSAGE_MAX_BYTES: long choice previews and descriptions shrink first, then the
47
+ * summary; null if it still cannot fit.
48
+ */
49
+ export function fitApprovalEnvelope(kind, base, rawQuestions, wire) {
50
+ const fitted = fitWith(kind, base, rawQuestions, wire);
51
+ if (fitted || typeof base.summary !== "string" || base.summary.length <= SUMMARY_FIT_MAX)
52
+ return fitted;
53
+ return fitWith(kind, { ...base, summary: `${base.summary.slice(0, SUMMARY_FIT_MAX - 1)}…` }, rawQuestions, wire);
54
+ }
@@ -0,0 +1,53 @@
1
+ // `temmo approval verify|take`: the signed-approval check from a shell, for harnesses without a Claude-shaped hook.
2
+ import { readFileSync } from "node:fs";
3
+ import { sessionLabel } from "./config.js";
4
+ import { approvalsDir, takeApproval, trustedApprovalKeys, verifyApproval } from "./signed-approval.js";
5
+ export const APPROVAL_USAGE = `usage: temmo approval verify --token <signed:...> --session <id> --tool <name> (--input <json> | --input-file <path>) [--request <id>]
6
+ temmo approval take --session <id> --tool <name> (--input <json> | --input-file <path>)
7
+ verify checks one token against one call and burns nothing; take finds this session's stored approval for the call and burns it (the gate).
8
+ --session takes the 16-hex session label or the harness's raw session id. Exit 0: allowed; 1: refused; 2: usage.`;
9
+ function flagValue(args, name) {
10
+ const at = args.indexOf(name);
11
+ return at >= 0 && at + 1 < args.length ? args[at + 1] : undefined;
12
+ }
13
+ /** Runs approval verify|take; prints {ok, reason} or {ok, claims} as one JSON line. */
14
+ export function approvalCli(args, { env, out, err, now = Date.now() }) {
15
+ const [sub, ...rest] = args;
16
+ const rawSession = flagValue(rest, "--session");
17
+ const tool = flagValue(rest, "--tool");
18
+ const inputFile = flagValue(rest, "--input-file");
19
+ let inputText = flagValue(rest, "--input");
20
+ if (inputText === undefined && inputFile) {
21
+ try {
22
+ inputText = readFileSync(inputFile, "utf8");
23
+ }
24
+ catch (error) {
25
+ err.write(`temmo: ${error.message}\n`);
26
+ return 2;
27
+ }
28
+ }
29
+ if ((sub !== "verify" && sub !== "take") || !rawSession || !tool || inputText === undefined) {
30
+ err.write(`${APPROVAL_USAGE}\n`);
31
+ return 2;
32
+ }
33
+ let input;
34
+ try {
35
+ input = JSON.parse(inputText);
36
+ }
37
+ catch {
38
+ err.write("temmo: --input must be JSON\n");
39
+ return 2;
40
+ }
41
+ const session = /^[a-f0-9]{16}$/.test(rawSession) ? rawSession : sessionLabel(rawSession);
42
+ const keys = trustedApprovalKeys(env);
43
+ let verdict;
44
+ if (sub === "verify") {
45
+ const request = flagValue(rest, "--request");
46
+ verdict = verifyApproval(flagValue(rest, "--token"), { session, tool, input, ...(request ? { requestId: request } : {}) }, { keys, now });
47
+ }
48
+ else {
49
+ verdict = takeApproval(approvalsDir(env), { session, tool, input }, { keys, now });
50
+ }
51
+ out.write(`${JSON.stringify(verdict)}\n`);
52
+ return verdict.ok ? 0 : 1;
53
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * request_approval: the agent asks the operator's phone to allow one exact tool call (docs/security.md#signed-approvals).
3
+ * The card carries the call's exact input, so the UI server hashes and summarises what it signs itself. Only a reply
4
+ * the bus stamped operator-verified counts, and an Allow counts only with a token that verifies for this card, session,
5
+ * tool and input; it is stored for the PreToolUse gate (lib/signed-approval.ts takeApproval). Anything else keeps waiting.
6
+ */
7
+ import { randomBytes } from "node:crypto";
8
+ import { broadcastTopic } from "./config.js";
9
+ import { fitApprovalEnvelope, text } from "./approval-card.js";
10
+ import { publish, streamEvents } from "./messaging.js";
11
+ import { deepLink } from "./deep-link.js";
12
+ import { alertPriority, readAlertLevel } from "./alerts.js";
13
+ import { approvalEnd, waitForOperatorReply } from "./operator.js";
14
+ import { sendReceipts } from "./receipts.js";
15
+ import { approvalsDir, savePendingApproval, trustedApprovalKeys, verifyApproval } from "./signed-approval.js";
16
+ export const SIGNED_TOOL_MAX = 128;
17
+ export const SIGNED_WAIT_DEFAULT_S = 300;
18
+ export const SIGNED_WAIT_MAX_S = 600;
19
+ const REASON_MAX = 200;
20
+ const SUMMARY_MAX = 300;
21
+ const END_TIMEOUT_MS = 1500;
22
+ const ALLOW_SIGNED = /^allow\s+(signed:\S+)$/i;
23
+ const DENY = /^deny$/i;
24
+ /** The one-line card summary the UI shows for a signed-approval request: reason and the input, both from the card. */
25
+ export function signedSummary(reason, input) {
26
+ const why = text(reason, REASON_MAX);
27
+ return text([why, JSON.stringify(input)].filter(Boolean).join(": "), SUMMARY_MAX);
28
+ }
29
+ /** Posts the card, waits for a verified, correctly signed Allow or a verified Deny, and closes the card. */
30
+ export async function requestSignedApproval(cfg, { tool, input, reason = "", seconds = SIGNED_WAIT_DEFAULT_S, signal, now = Date.now, stream = streamEvents, send = publish, env = process.env }) {
31
+ if (!cfg.session)
32
+ throw new Error("request_approval needs this session's label");
33
+ if (typeof tool !== "string" || !tool || tool.length > SIGNED_TOOL_MAX)
34
+ throw new Error("tool must be the blocked tool's name");
35
+ if (!input || typeof input !== "object" || Array.isArray(input))
36
+ throw new Error("input must be the blocked call's exact input object");
37
+ const id = randomBytes(6).toString("hex");
38
+ const t0 = now();
39
+ const deadline = t0 + Math.max(1, Math.min(Number(seconds) || SIGNED_WAIT_DEFAULT_S, SIGNED_WAIT_MAX_S)) * 1000;
40
+ const summary = signedSummary(reason, input);
41
+ const message = fitApprovalEnvelope("approval", {
42
+ from: cfg.peer, session: cfg.session, harness: "claude", id, tool, summary, reason: text(reason, REASON_MAX),
43
+ signed: { input }, expiresAt: deadline, ts: new Date(t0).toISOString(),
44
+ }, undefined, cfg.wire);
45
+ if (!message)
46
+ throw new Error("The call's input is too large for an approval card");
47
+ const sender = `${cfg.peer}#${cfg.session}`;
48
+ await send(cfg, broadcastTopic(cfg.project), message, { title: `Approve ${tool} for ${sender}: ${summary}`.slice(0, 200), priority: alertPriority(readAlertLevel(), "question", 4), click: deepLink({ project: cfg.project }) });
49
+ const dir = approvalsDir(env);
50
+ let expiresAt = 0;
51
+ const outcome = await waitForOperatorReply({
52
+ cfg, topic: broadcastTopic(cfg.project), id, deadline, signal, mode: "stream", since: String(Math.floor(t0 / 1000)), stream,
53
+ read: (reply) => {
54
+ // An unverified reply (shared bus token) never decides a signed approval.
55
+ if (!reply.verified)
56
+ return null;
57
+ const answer = reply.answer.trim();
58
+ if (DENY.test(answer))
59
+ return "deny";
60
+ const token = ALLOW_SIGNED.exec(answer)?.[1];
61
+ if (!token)
62
+ return null;
63
+ const keys = trustedApprovalKeys(env);
64
+ const v = verifyApproval(token, { session: cfg.session, tool, input, requestId: id }, { keys, now: now() });
65
+ if (!v.ok || !savePendingApproval(dir, token, keys, now()).ok)
66
+ return null;
67
+ expiresAt = v.claims.exp;
68
+ return "allow";
69
+ },
70
+ });
71
+ const decision = outcome.status === "reply" ? outcome.value : null;
72
+ if (decision)
73
+ sendReceipts(cfg, [outcome.messageId]);
74
+ const end = decision === "allow" ? "allowed" : decision === "deny" ? "denied" : outcome.status;
75
+ if (end !== "skipped") {
76
+ await send(cfg, broadcastTopic(cfg.project), approvalEnd(cfg, id, end, { session: cfg.session }), { title: `temmo approval ${end}`, priority: 1, signal: AbortSignal.timeout(END_TIMEOUT_MS) }).catch(() => { });
77
+ }
78
+ if (decision === "allow")
79
+ return { status: "approved", id, expiresAt, note: "Retry the identical call now: the PreToolUse gate allows it once within 10 minutes." };
80
+ return { status: decision === "deny" ? "denied" : outcome.status, id };
81
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The signing half of signed approvals (docs/security.md#signed-approvals): only the UI server imports this module.
3
+ * The Ed25519 private key lives in a 0600 file beside operator-token in the config dir; no environment variable,
4
+ * spawn env, sandbox upload or OpenShell policy carries it. Its public half sits beside it (0644) for verifiers.
5
+ */
6
+ import { createPrivateKey, generateKeyPairSync, randomBytes, sign } from "node:crypto";
7
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import path from "node:path";
9
+ import { configDir } from "./config.js";
10
+ import { APPROVAL_PUBLIC_KEY_FILE, APPROVAL_TTL_MS, SIGNED_PREFIX, validClaims } from "./signed-approval.js";
11
+ const KEY_FILE = "approval-ed25519.key";
12
+ /** The private key's file in the config dir. */
13
+ export function approvalKeyFile(env = process.env) {
14
+ return path.join(configDir(env), KEY_FILE);
15
+ }
16
+ /** Reads the signing key, creating the pair on first use (exclusive 0600 create; a concurrent creator's key wins). */
17
+ export function ensureApprovalKey(env = process.env) {
18
+ const file = approvalKeyFile(env);
19
+ try {
20
+ return createPrivateKey(readFileSync(file, "utf8"));
21
+ }
22
+ catch (error) {
23
+ if (error.code !== "ENOENT")
24
+ throw error;
25
+ }
26
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
27
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
28
+ try {
29
+ writeFileSync(file, privateKey.export({ type: "pkcs8", format: "pem" }), { flag: "wx", mode: 0o600 });
30
+ writeFileSync(path.join(configDir(env), APPROVAL_PUBLIC_KEY_FILE), publicKey.export({ type: "spki", format: "pem" }), { mode: 0o644 });
31
+ }
32
+ catch (error) {
33
+ if (error.code !== "EEXIST")
34
+ throw error;
35
+ }
36
+ return createPrivateKey(readFileSync(file, "utf8"));
37
+ }
38
+ /** Signs one approval for one call; the nonce and expiry are set here, never by the caller. Returns "signed:<token>". */
39
+ export function signApproval(key, fields, now = Date.now()) {
40
+ const claims = {
41
+ v: 1, session: fields.session, tool: fields.tool, inputHash: fields.inputHash, requestId: fields.requestId,
42
+ iat: now, exp: now + APPROVAL_TTL_MS, nonce: randomBytes(16).toString("hex"), ...(fields.by ? { by: fields.by } : {}),
43
+ };
44
+ if (!validClaims(claims))
45
+ throw new Error("Invalid approval fields");
46
+ const data = Buffer.from(JSON.stringify(claims)).toString("base64url");
47
+ return `${SIGNED_PREFIX}${data}.${sign(null, Buffer.from(data), key).toString("base64url")}`;
48
+ }