@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,273 @@
1
+ // Tool inputs as file diffs: Claude Edit, MultiEdit and Write, and Codex apply_patch.
2
+ const EDIT_TOOL = /^(edit|multiedit)$/i;
3
+ const WRITE_TOOL = /^write$/i;
4
+ const PATCH_TOOL = /^apply_patch$/i;
5
+ const CONTEXT = 3;
6
+ const CLIP = /…\[truncated \d+ bytes\]$/;
7
+ const HUNK = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/;
8
+ const WRITTEN = /\bupdated\b|overwr/i;
9
+ export const DIFF_MAX_LINES = 400;
10
+ // Lines of a text: "" has none, one trailing newline adds none.
11
+ const linesOf = text => typeof text === "string" && text !== "" ? text.replace(/\n$/, "").split("\n") : [];
12
+ const lineOf = (t, s) => ({ t, s });
13
+ const countOf = (lines, t) => lines.filter(line => line.t === t).length;
14
+ // The hunk for one replacement: changed lines with up to CONTEXT unchanged lines around them.
15
+ function replaceHunk(oldText, newText) {
16
+ const a = linesOf(oldText);
17
+ const b = linesOf(newText);
18
+ let head = 0;
19
+ while (head < a.length && head < b.length && a[head] === b[head])
20
+ head += 1;
21
+ let tail = 0;
22
+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail])
23
+ tail += 1;
24
+ const before = a.slice(Math.max(0, head - CONTEXT), head).map(s => lineOf(" ", s));
25
+ const after = a.slice(a.length - Math.min(CONTEXT, tail)).map(s => lineOf(" ", s));
26
+ const removed = a.slice(head, a.length - tail).map(s => lineOf("-", s));
27
+ const added = b.slice(head, b.length - tail).map(s => lineOf("+", s));
28
+ return { lines: [...before, ...removed, ...added, ...after] };
29
+ }
30
+ const withHunks = (path, kind, hunks, notes = []) => {
31
+ const kept = hunks.filter(hunk => hunk.lines.some(line => line.t !== " "));
32
+ const lines = kept.flatMap(hunk => hunk.lines);
33
+ return { path, kind, hunks: kept, added: countOf(lines, "+"), removed: countOf(lines, "-"), notes };
34
+ };
35
+ // A complete JSON string value of a key in text, or undefined.
36
+ function stringField(text, key) {
37
+ const match = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(text);
38
+ return match ? JSON.parse(`"${match[1]}"`) : undefined;
39
+ }
40
+ // The start of a string value of a key that the clip cut short, decoded up to the cut.
41
+ function partialString(text, key) {
42
+ const start = new RegExp(`"${key}"\\s*:\\s*"`).exec(text);
43
+ if (!start)
44
+ return undefined;
45
+ let body = text.slice(start.index + start[0].length).replace(/\\u[0-9a-fA-F]{0,3}$/, "");
46
+ const trailing = /\\*$/.exec(body)[0].length;
47
+ if (trailing % 2)
48
+ body = body.slice(0, -1);
49
+ return JSON.parse(`"${body}"`);
50
+ }
51
+ // Claude's Edit, MultiEdit and Write inputs: old and new text, or the full content of a new file.
52
+ function claudeFiles(tool, value, output) {
53
+ const path = value.file_path ?? value.filePath;
54
+ if (typeof path !== "string" || !path)
55
+ return null;
56
+ if (WRITE_TOOL.test(tool)) {
57
+ if (typeof value.content !== "string")
58
+ return null;
59
+ return [{ ...withHunks(path, "add", [{ lines: linesOf(value.content).map(s => lineOf("+", s)) }]), written: WRITTEN.test(output || "") }];
60
+ }
61
+ const edits = /^multiedit$/i.test(tool) ? value.edits : [value];
62
+ if (!Array.isArray(edits) || !edits.length)
63
+ return null;
64
+ if (!edits.every(edit => typeof edit?.old_string === "string" && typeof edit?.new_string === "string"))
65
+ return null;
66
+ const notes = [];
67
+ if (edits.some(edit => edit.replace_all === true))
68
+ notes.push("replace all occurrences");
69
+ const hunks = edits.map(edit => replaceHunk(edit.old_string, edit.new_string));
70
+ if (!hunks.some(hunk => hunk.lines.some(line => line.t !== " ")) && edits.some(edit => edit.old_string !== edit.new_string))
71
+ notes.push("whitespace or trailing newline only");
72
+ return [withHunks(path, "update", hunks, notes)];
73
+ }
74
+ // Codex apply_patch envelope: "*** Begin Patch" with Add, Update and Delete File sections.
75
+ function envelopeFiles(lines) {
76
+ const files = [];
77
+ let file = null;
78
+ let hunk = null;
79
+ for (const line of lines) {
80
+ const section = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(line);
81
+ if (section) {
82
+ file = { path: section[2].trim(), kind: { add: "add", update: "update", delete: "delete" }[section[1].toLowerCase()], hunks: [] };
83
+ files.push(file);
84
+ hunk = null;
85
+ }
86
+ else if (/^\*\*\* Move to: /.test(line) && file) {
87
+ file.path = line.slice("*** Move to: ".length).trim();
88
+ }
89
+ else if (/^\*\*\* End Patch/.test(line)) {
90
+ file = null;
91
+ hunk = null;
92
+ }
93
+ else if (/^\*\*\* End of File/.test(line)) {
94
+ hunk = null;
95
+ }
96
+ else if (!file || line.startsWith("*** ")) {
97
+ continue;
98
+ }
99
+ else if (line.startsWith("@@")) {
100
+ hunk = { lines: [] };
101
+ file.hunks.push(hunk);
102
+ }
103
+ else if (/^[ +-]/.test(line) || line === "") {
104
+ // A blank line outside a hunk is the newline before the next section, not context.
105
+ if (line === "" && !hunk)
106
+ continue;
107
+ if (!hunk) {
108
+ hunk = { lines: [] };
109
+ file.hunks.push(hunk);
110
+ }
111
+ hunk.lines.push(lineOf(line === "" ? " " : line[0], line.slice(1)));
112
+ }
113
+ }
114
+ return files.map(item => withHunks(item.path, item.kind, item.hunks));
115
+ }
116
+ // Unified diff text (git or plain ---/+++ headers): one entry per file. A hunk's header counts say how many lines it holds, so a removed "-- x" line is a hunk line, not a header.
117
+ function unifiedFiles(lines) {
118
+ const files = [];
119
+ let file = null;
120
+ let hunk = null;
121
+ let left = { old: 0, next: 0 };
122
+ for (const line of lines) {
123
+ const open = hunk && (left.old > 0 || left.next > 0);
124
+ if (open && (line === "" || /^[ +-]/.test(line))) {
125
+ const t = line === "" ? " " : line[0];
126
+ hunk.lines.push(lineOf(t, line.slice(1)));
127
+ if (t !== "+")
128
+ left.old -= 1;
129
+ if (t !== "-")
130
+ left.next -= 1;
131
+ }
132
+ else if (line.startsWith("diff --git ")) {
133
+ file = { path: line.split(" b/").pop(), kind: "update", hunks: [] };
134
+ files.push(file);
135
+ hunk = null;
136
+ }
137
+ else if (line.startsWith("--- ")) {
138
+ // A git header already opened this file; a plain header opens the next one.
139
+ if (!file || file.hunks.length) {
140
+ file = { path: "", kind: "update", hunks: [] };
141
+ files.push(file);
142
+ hunk = null;
143
+ }
144
+ if (line.startsWith("--- /dev/null"))
145
+ file.kind = "add";
146
+ else
147
+ file.path ||= line.slice(4).trim().replace(/^a\//, "");
148
+ }
149
+ else if (line.startsWith("+++ ") && file) {
150
+ if (line.startsWith("+++ /dev/null"))
151
+ file.kind = "delete";
152
+ else
153
+ file.path = line.slice(4).trim().replace(/^b\//, "");
154
+ }
155
+ else if (HUNK.test(line) && file) {
156
+ const [, old, next] = HUNK.exec(line);
157
+ hunk = { lines: [] };
158
+ file.hunks.push(hunk);
159
+ left = { old: old === undefined ? 1 : Number(old), next: next === undefined ? 1 : Number(next) };
160
+ }
161
+ }
162
+ return files.filter(item => item.path).map(item => withHunks(item.path, item.kind, item.hunks));
163
+ }
164
+ // The patch text of an apply_patch input: a bare string, or the command, input or patch field of an object.
165
+ function patchTextOf(input) {
166
+ let value;
167
+ try {
168
+ value = JSON.parse(input);
169
+ }
170
+ catch {
171
+ return input;
172
+ }
173
+ if (typeof value === "string")
174
+ return value;
175
+ if (!value || typeof value !== "object")
176
+ return null;
177
+ const text = [value.input, value.command, value.patch].find(item => typeof item === "string" || Array.isArray(item));
178
+ return Array.isArray(text) ? text.findLast(item => typeof item === "string") ?? null : text ?? null;
179
+ }
180
+ // The patch text of a clipped apply_patch input: the decoded part of its string field, or the raw text.
181
+ function clippedPatchTextOf(body) {
182
+ if (!body.trimStart().startsWith("{"))
183
+ return body;
184
+ for (const key of ["input", "command", "patch"]) {
185
+ const text = partialString(body, key);
186
+ if (text !== undefined)
187
+ return text;
188
+ }
189
+ return null;
190
+ }
191
+ // Parses a Codex or unified patch into files; null when the text is neither.
192
+ function patchFiles(text) {
193
+ if (typeof text !== "string")
194
+ return null;
195
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
196
+ if (lines.includes("*** Begin Patch"))
197
+ return envelopeFiles(lines);
198
+ if (lines.some(line => line.startsWith("+++ ")) && lines.some(line => line.startsWith("@@")))
199
+ return unifiedFiles(lines);
200
+ return null;
201
+ }
202
+ // The fields a clipped Edit input still holds whole; a Write or MultiEdit clipped short is not shown.
203
+ function clippedClaudeValue(tool, body) {
204
+ if (!EDIT_TOOL.test(tool) || /^multiedit$/i.test(tool))
205
+ return null;
206
+ const path = stringField(body, "file_path") ?? stringField(body, "filePath");
207
+ const oldText = stringField(body, "old_string");
208
+ const newText = stringField(body, "new_string");
209
+ if (path === undefined || oldText === undefined || newText === undefined)
210
+ return null;
211
+ return { file_path: path, old_string: oldText, new_string: newText, replace_all: /"replace_all"\s*:\s*true/.test(body) };
212
+ }
213
+ /**
214
+ * Files a tool input changes as diffs, or null when the input is not a file edit:
215
+ * { files: [{ path, kind, hunks, added, removed, notes, written }], truncated }.
216
+ * output is the tool result text; a Write whose result says "updated" overwrote the file.
217
+ */
218
+ export function toolDiff(tool, input, output = "") {
219
+ if (!input || typeof tool !== "string")
220
+ return null;
221
+ const truncated = CLIP.test(input);
222
+ const body = truncated ? input.replace(CLIP, "") : input;
223
+ if (PATCH_TOOL.test(tool)) {
224
+ const files = patchFiles(truncated ? clippedPatchTextOf(body) : patchTextOf(input));
225
+ return files?.length ? { files, truncated } : null;
226
+ }
227
+ if (!EDIT_TOOL.test(tool) && !WRITE_TOOL.test(tool))
228
+ return null;
229
+ let value;
230
+ if (truncated)
231
+ value = clippedClaudeValue(tool, body);
232
+ else {
233
+ try {
234
+ value = JSON.parse(input);
235
+ }
236
+ catch {
237
+ return null;
238
+ }
239
+ }
240
+ const files = value && typeof value === "object" ? claudeFiles(tool, value, output) : null;
241
+ return files ? { files, truncated } : null;
242
+ }
243
+ /** A unified diff for one file: headers, then each hunk with counts recomputed from its lines (line numbers are not known). */
244
+ export function patchOf(file) {
245
+ const name = file.path.replace(/^\/+/, "");
246
+ const out = [`--- ${file.kind === "add" ? "/dev/null" : "a/" + name}`, `+++ ${file.kind === "delete" ? "/dev/null" : "b/" + name}`];
247
+ for (const hunk of file.hunks) {
248
+ const old = countOf(hunk.lines, " ") + countOf(hunk.lines, "-");
249
+ const next = countOf(hunk.lines, " ") + countOf(hunk.lines, "+");
250
+ out.push(`@@ -${old ? 1 : 0},${old} +${next ? 1 : 0},${next} @@`);
251
+ for (const line of hunk.lines)
252
+ out.push(line.t + line.s);
253
+ }
254
+ return out.join("\n");
255
+ }
256
+ /** The files with at most max diff lines across them, and the count of lines left out. */
257
+ export function limitFiles(files, max = DIFF_MAX_LINES) {
258
+ const total = files.reduce((sum, file) => sum + file.hunks.reduce((n, hunk) => n + hunk.lines.length, 0), 0);
259
+ let budget = max;
260
+ const shown = files.map(file => {
261
+ const hunks = [];
262
+ for (const hunk of file.hunks) {
263
+ if (budget <= 0)
264
+ break;
265
+ const lines = hunk.lines.slice(0, budget);
266
+ budget -= lines.length;
267
+ hunks.push({ lines });
268
+ }
269
+ return { ...file, hunks };
270
+ });
271
+ const kept = shown.reduce((sum, file) => sum + file.hunks.reduce((n, hunk) => n + hunk.lines.length, 0), 0);
272
+ return { files: shown, hidden: total - kept };
273
+ }
@@ -0,0 +1,58 @@
1
+ import { EventType } from "@ag-ui/core";
2
+ import { parseSSEStream, runHttpRequest } from "@ag-ui/client";
3
+ import { parseEvent, projectEvent } from "../../lib/agui.js";
4
+ import { A2UI_ACTIVITY } from "./a2ui.js";
5
+ export const ACTIVITY_BATCH = "ai-collab.activity-batch";
6
+ export const STREAM_ERROR = "ai-collab.stream-error";
7
+ /** Collect activity rows until the server completes a reset or append batch. */
8
+ export function projectUiEvents() {
9
+ let items = [];
10
+ return raw => {
11
+ const event = parseEvent(raw);
12
+ if (!event)
13
+ return null;
14
+ if (event.type === EventType.STATE_SNAPSHOT) {
15
+ return { type: event.type, event: "state", data: event.snapshot };
16
+ }
17
+ if (event.type === EventType.ACTIVITY_SNAPSHOT && event.activityType === A2UI_ACTIVITY && Array.isArray(event.content.a2ui_operations)) {
18
+ return { type: event.type, event: "surface", data: { id: event.messageId, operations: event.content.a2ui_operations } };
19
+ }
20
+ if (event.type === EventType.CUSTOM && event.name === STREAM_ERROR) {
21
+ return { type: event.type, event: "problem", data: event.value };
22
+ }
23
+ if (event.type === EventType.CUSTOM && event.name === ACTIVITY_BATCH) {
24
+ if (typeof event.value?.reset !== "boolean")
25
+ return null;
26
+ const data = { reset: event.value.reset, items };
27
+ items = [];
28
+ return { type: event.type, event: "activity", data };
29
+ }
30
+ const meta = event.metadata?.temmoUi;
31
+ if (!meta)
32
+ return null;
33
+ const row = projectEvent(event);
34
+ if (row?.kind !== "activity")
35
+ return null;
36
+ const { id, time, attachment } = meta;
37
+ const { from, session, harness, type, tool, callId, input, output, agent, compaction, clear, modelSwitch } = row;
38
+ items.push({
39
+ id, time, agent: from + "#" + session, harness, type,
40
+ ...(tool ? { tool } : {}), ...(callId ? { callId } : {}),
41
+ ...(input ? { input } : {}), ...(output ? { output } : {}),
42
+ ...(agent ? { subagent: agent } : {}), ...(attachment ? { attachment } : {}),
43
+ ...(compaction ? { compaction } : {}), ...(clear ? { clear } : {}), ...(modelSwitch ? { modelSwitch } : {}),
44
+ });
45
+ return null;
46
+ };
47
+ }
48
+ export function subscribeUiEvents(fetchResponse, observer) {
49
+ const project = projectUiEvents();
50
+ return parseSSEStream(runHttpRequest(fetchResponse)).subscribe({
51
+ ...observer,
52
+ next(raw) {
53
+ const update = project(raw);
54
+ if (update)
55
+ observer.next(update);
56
+ },
57
+ });
58
+ }
@@ -0,0 +1,5 @@
1
+ import { clsx } from "clsx";
2
+ import { twMerge } from "tailwind-merge";
3
+ export function cn(...inputs) {
4
+ return twMerge(clsx(inputs));
5
+ }
@@ -0,0 +1,25 @@
1
+ // In-memory view state that outlives a remount: composer drafts per conversation, Home's scroll and expanded groups.
2
+ export const MEMORY_MAX = 200;
3
+ /** One conversation's draft key: project chat and activity share project + "", a session's views share its address. */
4
+ export function conversationKey(project, session = "") {
5
+ return JSON.stringify([project || "", session || ""]);
6
+ }
7
+ /** A bounded Map: setting an empty value deletes it, and the oldest key drops past max. */
8
+ export function createMemory(max = MEMORY_MAX) {
9
+ const map = new Map();
10
+ return {
11
+ get: (key, fallback) => map.has(key) ? map.get(key) : fallback,
12
+ set(key, value) {
13
+ map.delete(key);
14
+ if (value === undefined || value === "")
15
+ return;
16
+ map.set(key, value);
17
+ if (map.size > max)
18
+ map.delete(map.keys().next().value);
19
+ },
20
+ delete: key => map.delete(key),
21
+ get size() { return map.size; },
22
+ };
23
+ }
24
+ export const drafts = createMemory();
25
+ export const views = createMemory();
@@ -0,0 +1,37 @@
1
+ import "../lib/names.js"; // first: folds AI_COLLAB_* env into TEMMO_* for the UI server process
2
+ import { existsSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { PHASE_PRODUCTION_SERVER } from "next/constants.js";
5
+ import { productionDistDir } from "../lib/ui-build-output.js";
6
+ const root = fileURLToPath(new URL("..", import.meta.url));
7
+ // The source tree runs server/ui.ts; the built package ships it compiled as server/ui.js.
8
+ const source = fileURLToPath(new URL("server/ui.ts", import.meta.url));
9
+ const server = existsSync(source) ? source : fileURLToPath(new URL("server/ui.js", import.meta.url));
10
+ // One id per build; the page compares its own with the server's to offer a reload after a deploy.
11
+ const build = Date.now().toString(36);
12
+ let serverDistDir;
13
+ export default (phase) => ({
14
+ turbopack: { root },
15
+ outputFileTracingRoot: root,
16
+ env: {
17
+ TEMMO_UI_SERVER: server,
18
+ TEMMO_BUILD: build,
19
+ NEXT_PUBLIC_TEMMO_TEST_BRIDGE: process.env.NEXT_PUBLIC_TEMMO_TEST_BRIDGE === "1" ? "1" : "0",
20
+ },
21
+ generateBuildId: () => build,
22
+ // Pin the actual directory for this server process, even when Next loads config more than once.
23
+ distDir: phase === PHASE_PRODUCTION_SERVER
24
+ ? (serverDistDir ??= productionDistDir())
25
+ : process.env.TEMMO_NEXT_DIST || ".next",
26
+ poweredByHeader: false,
27
+ async headers() {
28
+ return [
29
+ { source: "/:path*", headers: [{ key: "X-Content-Type-Options", value: "nosniff" }] },
30
+ // The service worker skips proxy.js; it gets its own CSP and is revalidated on every update check.
31
+ { source: "/sw.js", headers: [
32
+ { key: "Content-Type", value: "text/javascript; charset=utf-8" }, { key: "Cache-Control", value: "no-cache" },
33
+ { key: "Content-Security-Policy", value: "default-src 'none'; connect-src 'self'" },
34
+ ] },
35
+ ];
36
+ },
37
+ });
@@ -0,0 +1 @@
1
+ export default { plugins: { "@tailwindcss/postcss": {} } };
package/web/proxy.js ADDED
@@ -0,0 +1,25 @@
1
+ import { NextResponse } from "next/server";
2
+
3
+ export const config = {
4
+ matcher: [{
5
+ source: "/((?!api|_next/static|_next/image|favicon.ico|sw.js).*)",
6
+ missing: [{ type: "header", key: "next-router-prefetch" }, { type: "header", key: "purpose", value: "prefetch" }],
7
+ }],
8
+ };
9
+
10
+ // Per-request script nonce; Next.js applies it to its own inline scripts.
11
+ export function proxy(request) {
12
+ const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
13
+ const dev = process.env.NODE_ENV === "development" ? " 'unsafe-eval'" : "";
14
+ const csp = [
15
+ "default-src 'self'", `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${dev}`,
16
+ "style-src 'self' 'unsafe-inline'", "font-src 'self' data:", "img-src 'self' data: blob:", "connect-src 'self'",
17
+ "worker-src 'self'", "manifest-src 'self'", "object-src 'none'", "base-uri 'none'", "form-action 'self'", "frame-ancestors 'none'",
18
+ ].join("; ");
19
+ const headers = new Headers(request.headers);
20
+ headers.set("x-nonce", nonce);
21
+ headers.set("Content-Security-Policy", csp);
22
+ const response = NextResponse.next({ request: { headers } });
23
+ response.headers.set("Content-Security-Policy", csp);
24
+ return response;
25
+ }
@@ -0,0 +1,39 @@
1
+ // Temmo service worker: shows Web Push notifications and opens the UI at the item's thread on tap.
2
+ self.addEventListener("install", () => self.skipWaiting());
3
+ self.addEventListener("activate", event => event.waitUntil(self.clients.claim()));
4
+
5
+ self.addEventListener("push", event => {
6
+ let data = {};
7
+ try { data = event.data ? event.data.json() : {}; } catch { data = { body: event.data ? event.data.text() : "" }; }
8
+ const tag = typeof data.tag === "string" && data.tag ? data.tag : undefined;
9
+ const important = data.important === true;
10
+ event.waitUntil(self.registration.showNotification(String(data.title || "Temmo"), {
11
+ body: String(data.body || ""), tag, renotify: Boolean(tag && important), requireInteraction: important,
12
+ data: { url: typeof data.url === "string" ? data.url : "/" },
13
+ }));
14
+ });
15
+
16
+ self.addEventListener("notificationclick", event => {
17
+ event.notification.close();
18
+ let url = new URL(event.notification.data?.url || "/", self.location.origin);
19
+ if (url.origin !== self.location.origin) url = new URL("/", self.location.origin);
20
+ event.waitUntil((async () => {
21
+ const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
22
+ const open = windows.find(client => new URL(client.url).origin === self.location.origin);
23
+ if (!open) return self.clients.openWindow(url.href);
24
+ await open.focus();
25
+ open.postMessage({ type: "temmo-open", hash: url.hash });
26
+ })());
27
+ });
28
+
29
+ // The push service rotated the subscription: subscribe again with the same key and tell the server.
30
+ self.addEventListener("pushsubscriptionchange", event => {
31
+ event.waitUntil((async () => {
32
+ const key = event.oldSubscription?.options?.applicationServerKey;
33
+ const subscription = event.newSubscription || (key && await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key }));
34
+ if (!subscription) return;
35
+ const post = (method, body) => fetch("/api/push/subscribe", { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
36
+ if (event.oldSubscription) await post("DELETE", { endpoint: event.oldSubscription.endpoint }).catch(() => {});
37
+ await post("POST", { subscription: subscription.toJSON() });
38
+ })());
39
+ });
@@ -0,0 +1,178 @@
1
+ /**
2
+ * GitHub sign-in for the operator UI (OAuth app web flow). Off without ${configDir}/github.json.
3
+ * The session cookie is base64url(JSON {login, name, exp}) + "." + HMAC-SHA256 under ${stateDir}/auth/secret.
4
+ */
5
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
6
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { isAbsolute, join } from "node:path";
8
+ import { isGithubLogin } from "../../lib/config.js";
9
+ export const SESSION_COOKIE = "__Host-temmo-session";
10
+ export const STATE_COOKIE = "__Host-temmo-state";
11
+ export const SESSION_TTL_S = 30 * 24 * 3600;
12
+ const STATE_TTL_S = 600;
13
+ const SECRET_BYTES = 32;
14
+ const NAME_MAX = 100;
15
+ const GITHUB_TIMEOUT_MS = 10_000;
16
+ const AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
17
+ const TOKEN_URL = "https://github.com/login/oauth/access_token";
18
+ const USER_URL = "https://api.github.com/user";
19
+ const USER_AGENT = "temmo";
20
+ const STEPS = ["login", "callback", "logout", "me"];
21
+ const sign = (secret, data) => createHmac("sha256", secret).update(data).digest("base64url");
22
+ function safeEqual(a, b) {
23
+ const x = Buffer.from(String(a)), y = Buffer.from(String(b));
24
+ return x.length === y.length && timingSafeEqual(x, y);
25
+ }
26
+ /** A signed session cookie value for {login, name}, valid until exp (seconds). */
27
+ export function signSession(secret, { login, name = "", exp }) {
28
+ const data = Buffer.from(JSON.stringify({ login, name, exp })).toString("base64url");
29
+ return data + "." + sign(secret, data);
30
+ }
31
+ /** The session {login, name, exp} in a cookie value, or null when unsigned, tampered, malformed or expired. */
32
+ export function verifySession(secret, value, now = Date.now()) {
33
+ const [data, mac, ...extra] = String(value || "").split(".");
34
+ if (!data || !mac || extra.length || !safeEqual(mac, sign(secret, data)))
35
+ return null;
36
+ let session;
37
+ try {
38
+ session = JSON.parse(Buffer.from(data, "base64url").toString());
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ if (!isGithubLogin(session?.login) || !Number.isSafeInteger(session.exp) || session.exp * 1000 <= now)
44
+ return null;
45
+ return { login: session.login, name: typeof session.name === "string" ? session.name : "", exp: session.exp };
46
+ }
47
+ /** The value of one cookie in a Cookie header, or "". */
48
+ export function readCookie(request, name) {
49
+ for (const part of (request.headers.get("cookie") || "").split(";")) {
50
+ const at = part.indexOf("=");
51
+ if (at > 0 && part.slice(0, at).trim() === name)
52
+ return part.slice(at + 1).trim();
53
+ }
54
+ return "";
55
+ }
56
+ const cookie = (name, value, maxAge) => `${name}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
57
+ // The 32-byte HMAC key, created once with mode 0600; a concurrent creator's key wins.
58
+ function loadSecret(stateDir) {
59
+ const dir = join(stateDir, "auth");
60
+ const file = join(dir, "secret");
61
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
62
+ try {
63
+ writeFileSync(file, randomBytes(SECRET_BYTES), { mode: 0o600, flag: "wx" });
64
+ }
65
+ catch (err) {
66
+ if (err.code !== "EEXIST")
67
+ throw err;
68
+ }
69
+ const secret = readFileSync(file);
70
+ if (secret.length !== SECRET_BYTES)
71
+ throw new Error(`${file} must hold ${SECRET_BYTES} bytes`);
72
+ return secret;
73
+ }
74
+ /** The github.json settings, or null when the file is missing; throws when it is invalid. */
75
+ export function loadGithubConfig(dir) {
76
+ let raw;
77
+ try {
78
+ raw = readFileSync(join(dir, "github.json"), "utf8");
79
+ }
80
+ catch (err) {
81
+ if (err.code === "ENOENT")
82
+ return null;
83
+ throw err;
84
+ }
85
+ const value = JSON.parse(raw);
86
+ if (typeof value?.clientId !== "string" || !value.clientId || typeof value.clientSecretFile !== "string" || !isAbsolute(value.clientSecretFile) ||
87
+ (value.hosted !== undefined && typeof value.hosted !== "boolean") || !Array.isArray(value.users) || !value.users.length || !value.users.every(isGithubLogin)) {
88
+ throw new Error("github.json needs clientId, an absolute clientSecretFile and a users list of GitHub logins");
89
+ }
90
+ return { hosted: value.hosted === true, clientId: value.clientId, clientSecretFile: value.clientSecretFile, users: value.users.map((user) => user.toLowerCase()) };
91
+ }
92
+ function page(status, text, headers = {}) {
93
+ return new Response(text + "\n", { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", ...headers } });
94
+ }
95
+ function redirect(location, cookies = []) {
96
+ const headers = new Headers({ location, "cache-control": "no-store" });
97
+ for (const value of cookies)
98
+ headers.append("set-cookie", value);
99
+ return new Response(null, { status: 302, headers });
100
+ }
101
+ /**
102
+ * Sign-in for the UI, or null when ${dir}/github.json is missing. user(request) is the signed-in {login, name} or null;
103
+ * route(request, step) serves /api/auth/<step>. fetch is injectable so tests never call GitHub.
104
+ */
105
+ export function createAuth({ dir, stateDir, origin, fetch: get = fetch, now = Date.now }) {
106
+ const loaded = loadGithubConfig(dir);
107
+ if (!loaded)
108
+ return null;
109
+ const settings = loaded;
110
+ if (!origin)
111
+ throw new Error("GitHub sign-in needs TEMMO_UI_ORIGIN for its callback URL");
112
+ const secret = loadSecret(stateDir);
113
+ const callback = origin + "/api/auth/callback";
114
+ const allowed = (login) => settings.users.includes(String(login).toLowerCase());
115
+ function user(request) {
116
+ const session = verifySession(secret, readCookie(request, SESSION_COOKIE), now());
117
+ return session && allowed(session.login) ? { login: session.login, name: session.name } : null;
118
+ }
119
+ // The GitHub account behind an authorization code; the access token is used once and dropped.
120
+ async function account(code) {
121
+ const clientSecret = readFileSync(settings.clientSecretFile, "utf8").trim();
122
+ const tokenRes = await get(TOKEN_URL, {
123
+ method: "POST", signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS),
124
+ headers: { accept: "application/json", "user-agent": USER_AGENT },
125
+ body: new URLSearchParams({ client_id: settings.clientId, client_secret: clientSecret, code, redirect_uri: callback }),
126
+ });
127
+ const token = tokenRes.ok ? (await tokenRes.json().catch(() => ({}))).access_token : undefined;
128
+ if (typeof token !== "string" || !token)
129
+ return null;
130
+ const userRes = await get(USER_URL, {
131
+ signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS),
132
+ headers: { accept: "application/vnd.github+json", authorization: "Bearer " + token, "user-agent": USER_AGENT, "x-github-api-version": "2022-11-28" },
133
+ });
134
+ const profile = userRes.ok ? await userRes.json().catch(() => null) : null;
135
+ return isGithubLogin(profile?.login) ? { login: profile.login, name: typeof profile.name === "string" ? profile.name.slice(0, NAME_MAX) : "" } : null;
136
+ }
137
+ async function route(request, step) {
138
+ if (!STEPS.includes(step))
139
+ return page(404, "Unknown route");
140
+ if (step === "me")
141
+ return Response.json({ enabled: true, user: user(request) }, { headers: { "cache-control": "no-store" } });
142
+ if (step === "logout") {
143
+ if (request.method !== "POST")
144
+ return page(405, "Method not allowed");
145
+ if (request.headers.get("origin") !== origin)
146
+ return page(403, "Same-origin request required");
147
+ return new Response(null, { status: 204, headers: { "set-cookie": cookie(SESSION_COOKIE, "", 0), "cache-control": "no-store" } });
148
+ }
149
+ if (step === "login") {
150
+ const state = randomBytes(16).toString("hex");
151
+ const query = new URLSearchParams({ client_id: settings.clientId, redirect_uri: callback, state, scope: "", allow_signup: "false" });
152
+ return redirect(AUTHORIZE_URL + "?" + query, [cookie(STATE_COOKIE, state, STATE_TTL_S)]);
153
+ }
154
+ const url = new URL(request.url);
155
+ const state = url.searchParams.get("state") || "";
156
+ const code = url.searchParams.get("code") || "";
157
+ const clear = cookie(STATE_COOKIE, "", 0);
158
+ const expected = readCookie(request, STATE_COOKIE);
159
+ if (!expected || !state || !safeEqual(state, expected))
160
+ return page(400, "Sign-in expired or was not started here; open /api/auth/login again.", { "set-cookie": clear });
161
+ if (!code)
162
+ return page(400, "GitHub sent no authorization code.", { "set-cookie": clear });
163
+ let found;
164
+ try {
165
+ found = await account(code);
166
+ }
167
+ catch {
168
+ found = null;
169
+ }
170
+ if (!found)
171
+ return page(502, "GitHub sign-in failed; try again.", { "set-cookie": clear });
172
+ if (!allowed(found.login))
173
+ return page(403, `GitHub user ${found.login} may not use this Temmo.`, { "set-cookie": clear });
174
+ const value = signSession(secret, { ...found, exp: Math.floor(now() / 1000) + SESSION_TTL_S });
175
+ return redirect("/", [clear, cookie(SESSION_COOKIE, value, SESSION_TTL_S)]);
176
+ }
177
+ return { user, route, hosted: settings.hosted };
178
+ }