@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,94 @@
1
+ /**
2
+ * Personal sandbox web hosts: `~/.config/temmo/sandbox-hosts.json`. Policy generation
3
+ * merges these into every sandbox policy as a `personal` network rule; regenerating policy never
4
+ * writes this file, so operator edits stay until they change the file (or the CLI).
5
+ */
6
+ import path from "node:path";
7
+ import { configDir } from "./config.js";
8
+ import { readJson, writeFileAtomic } from "./store.js";
9
+ export const SANDBOX_HOSTS_FILE = "sandbox-hosts.json";
10
+ // Hostname: labels of letters/digits/hyphen, optional trailing dot; port optional 1..65535.
11
+ const HOST_SPEC = /^(?<host>(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}|(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))\.?(?::(?<port>[1-9][0-9]{0,4}))?$/i;
12
+ /** Path of the personal hosts file under the config directory. */
13
+ export function sandboxHostsPath(env = process.env) {
14
+ return path.join(configDir(env), SANDBOX_HOSTS_FILE);
15
+ }
16
+ /** `host` or `host:port` as one SandboxHost, or an error string. */
17
+ export function parseHostSpec(spec) {
18
+ const raw = spec.trim();
19
+ if (!raw)
20
+ return { error: "empty host" };
21
+ if (/[\s/?#]/.test(raw) || /^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
22
+ return { error: `"${raw}" is not a host[:port]; use a hostname (and optional :port), not a URL` };
23
+ }
24
+ const match = HOST_SPEC.exec(raw);
25
+ if (!match?.groups?.host)
26
+ return { error: `"${raw}" is not a valid host[:port]` };
27
+ const host = match.groups.host.toLowerCase().replace(/\.$/, "");
28
+ const port = match.groups.port ? Number(match.groups.port) : 443;
29
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
30
+ return { error: `"${raw}" has an invalid port` };
31
+ return { host, port };
32
+ }
33
+ /** Stable string form of a host (port only when not 443). */
34
+ export function formatHostSpec({ host, port }) {
35
+ return port === 443 ? host : `${host}:${port}`;
36
+ }
37
+ function keyOf(h) {
38
+ return `${h.host}:${h.port}`;
39
+ }
40
+ /** Deduped, sorted hosts from mixed string/`SandboxHost` inputs; skips invalid strings. */
41
+ export function normalizeHosts(entries) {
42
+ const byKey = new Map();
43
+ for (const entry of entries) {
44
+ const parsed = typeof entry === "string" ? parseHostSpec(entry) : entry;
45
+ if ("error" in parsed)
46
+ continue;
47
+ byKey.set(keyOf(parsed), parsed);
48
+ }
49
+ return [...byKey.values()].sort((a, b) => keyOf(a).localeCompare(keyOf(b)));
50
+ }
51
+ /** Hosts from sandbox-hosts.json; missing or invalid file → []. Never creates the file. */
52
+ export function readSandboxHosts(env = process.env) {
53
+ const value = readJson(sandboxHostsPath(env));
54
+ const list = Array.isArray(value) ? value
55
+ : value && typeof value === "object" && Array.isArray(value.hosts)
56
+ ? value.hosts
57
+ : [];
58
+ return normalizeHosts(list.filter((h) => typeof h === "string" || (h != null && typeof h === "object")));
59
+ }
60
+ /** Writes `{ "hosts": [...] }` atomically; creates the config directory when needed. */
61
+ export function writeSandboxHosts(hosts, env = process.env) {
62
+ const normalized = normalizeHosts(hosts);
63
+ writeFileAtomic(sandboxHostsPath(env), `${JSON.stringify({ hosts: normalized.map(formatHostSpec) }, null, 2)}\n`);
64
+ }
65
+ /** Adds host specs; returns the new list and what was added, or an error. */
66
+ export function addSandboxHosts(specs, env = process.env) {
67
+ const parsed = [];
68
+ for (const spec of specs) {
69
+ const one = parseHostSpec(spec);
70
+ if ("error" in one)
71
+ return { error: one.error };
72
+ parsed.push(one);
73
+ }
74
+ const before = new Set(readSandboxHosts(env).map(keyOf));
75
+ const hosts = normalizeHosts([...readSandboxHosts(env), ...parsed]);
76
+ const added = hosts.filter((h) => !before.has(keyOf(h)));
77
+ writeSandboxHosts(hosts, env);
78
+ return { hosts, added };
79
+ }
80
+ /** Removes host specs; returns the new list and what was removed, or an error. */
81
+ export function removeSandboxHosts(specs, env = process.env) {
82
+ const drop = new Set();
83
+ for (const spec of specs) {
84
+ const one = parseHostSpec(spec);
85
+ if ("error" in one)
86
+ return { error: one.error };
87
+ drop.add(keyOf(one));
88
+ }
89
+ const current = readSandboxHosts(env);
90
+ const removed = current.filter((h) => drop.has(keyOf(h)));
91
+ const hosts = current.filter((h) => !drop.has(keyOf(h)));
92
+ writeSandboxHosts(hosts, env);
93
+ return { hosts, removed };
94
+ }
@@ -0,0 +1,102 @@
1
+ // request_pr for a runner-owned session: the runner, which holds the host worktree and GitHub credentials, copies the
2
+ // sandbox's commits to the session's branch, pushes that branch and opens or updates its PR with gh. The sandbox never
3
+ // gets a remote or a token. The request and its answer ride the bus like fetch_origin (lib/fetch-origin.ts); a session
4
+ // no runner owns, or a runner that never answers, gets the operator's Create PR card instead (lib/pr-card.ts).
5
+ import { randomBytes } from "node:crypto";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { encodeEnvelope, parseWireEnvelope } from "./agui.js";
8
+ import { broadcastTopic } from "./config.js";
9
+ import { BRANCH, LandRefused, execRun, requestLand } from "./land.js";
10
+ import { pollCached, publish } from "./messaging.js";
11
+ import { requestPr } from "./pr-card.js";
12
+ /** Branches request_pr never pushes: the operator lands them. */
13
+ export const PROTECTED_BRANCHES = new Set(["main", "master", "HEAD"]);
14
+ export const PR_NOTE_MAX = 500;
15
+ /** How long the agent waits for the runner to take the request before it falls back to the operator card. */
16
+ export const PR_ACK_SECONDS = 10;
17
+ export const PR_WAIT_SECONDS = 180;
18
+ /** The line every OpenShell session's first prompt (and the prompt after a pad restart) carries. */
19
+ export const SANDBOX_GIT_NOTE = "\n\n[temmo] This sandbox has no git remote: commit your work; use fetch_origin to rebase on origin/main; call request_pr with your test proof to push your branch and open its PR.";
20
+ /** Publish the request and return its id; the runner owning the session answers with pr-request-end. */
21
+ export async function publishPrRequest(cfg, note) {
22
+ if (!cfg.session)
23
+ throw new Error("request_pr needs the session label");
24
+ const id = randomBytes(6).toString("hex");
25
+ await publish(cfg, broadcastTopic(cfg.project), encodeEnvelope("pr-request", {
26
+ from: cfg.peer, session: cfg.session, id, note: String(note).slice(0, PR_NOTE_MAX), ts: new Date().toISOString(),
27
+ }, cfg.wire), { title: "PR request" });
28
+ return id;
29
+ }
30
+ /** The runner's answer: accepted at once, then done with the URL or failed with the reason; not-owned sends the agent to the card. */
31
+ export function prRequestEnd(cfg, id, answer) {
32
+ return encodeEnvelope("pr-request-end", { from: cfg.peer, id, ...answer, ts: new Date().toISOString() }, cfg.wire);
33
+ }
34
+ // Polls the topic for answers to id until one passes accept or the deadline; null on the deadline.
35
+ async function nextAnswer(cfg, id, cursor, until, accept, signal) {
36
+ const topic = broadcastTopic(cfg.project);
37
+ for (;;) {
38
+ for (const event of await pollCached(cfg, topic, cursor.at, signal).catch(() => [])) {
39
+ cursor.at = event.id;
40
+ const e = parseWireEnvelope(event.message);
41
+ if (e?.kind !== "pr-request-end" || e.id !== id)
42
+ continue;
43
+ const answer = {
44
+ reason: (["accepted", "done", "failed", "not-owned"].includes(e.reason) ? e.reason : "failed"),
45
+ ...(typeof e.url === "string" ? { url: e.url } : {}),
46
+ ...(typeof e.created === "boolean" ? { created: e.created } : {}),
47
+ ...(typeof e.branch === "string" ? { branch: e.branch } : {}),
48
+ ...(typeof e.why === "string" ? { why: e.why } : {}),
49
+ };
50
+ if (accept(answer))
51
+ return answer;
52
+ }
53
+ if (Date.now() >= until || signal?.aborted)
54
+ return null;
55
+ await delay(400, undefined, { signal }).catch(() => undefined);
56
+ }
57
+ }
58
+ /**
59
+ * request_pr from an agent. A runner-owned session (owned) asks its runner to push and open the PR and waits for the URL;
60
+ * anything else, a runner that says it does not own the session, or one that never answers, posts the operator card.
61
+ */
62
+ export async function requestSessionPr(cfg, note, { harness = "", owned = false, ackSeconds = PR_ACK_SECONDS, seconds = PR_WAIT_SECONDS, signal } = {}) {
63
+ const card = async (why) => ({ id: await requestPr(cfg, note, harness), status: "card", why });
64
+ if (!owned)
65
+ return card("not a runner-owned session: the operator opens the PR from the Create PR card");
66
+ const cursor = { at: String(Math.floor(Date.now() / 1000) - 1) };
67
+ const id = await publishPrRequest(cfg, note);
68
+ const first = await nextAnswer(cfg, id, cursor, Date.now() + ackSeconds * 1000, () => true, signal);
69
+ if (!first)
70
+ return card("no runner answered: the operator opens the PR from the Create PR card");
71
+ if (first.reason === "not-owned")
72
+ return card(first.why || "the runner does not own this session");
73
+ const end = first.reason === "accepted" ? await nextAnswer(cfg, id, cursor, Date.now() + seconds * 1000, (a) => a.reason !== "accepted", signal) : first;
74
+ if (!end)
75
+ return { id, status: "pending", why: "the runner is still pushing; its PR link will be posted to the channel" };
76
+ const { reason, ...rest } = end;
77
+ return { id, status: reason === "done" ? "done" : "failed", ...rest };
78
+ }
79
+ /** A branch request_pr may push: a valid name that is not main, master or a detached HEAD. */
80
+ export function pushableBranch(branch) {
81
+ return BRANCH.test(branch) && !PROTECTED_BRANCHES.has(branch) && !branch.includes("..");
82
+ }
83
+ /**
84
+ * Host side: copies the sandbox commits to the worktree (syncBack), then pushes the worktree's branch and opens its PR
85
+ * into main, or updates the open one's body. The note is the PR body; an empty note lets gh fill it from the commits.
86
+ */
87
+ export async function pushSessionPr({ cwd, note = "", syncBack, run = execRun }) {
88
+ const head = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd, encoding: "utf8" });
89
+ const branch = head.status === 0 ? head.stdout.trim() : "";
90
+ if (!pushableBranch(branch))
91
+ throw new LandRefused(`refusing to push ${branch || "a worktree with no branch"}: ${PROTECTED_BRANCHES.has(branch) ? "the operator lands it" : "not a branch name request_pr pushes"}`);
92
+ if (syncBack)
93
+ await syncBack();
94
+ const body = String(note).trim().slice(0, PR_NOTE_MAX);
95
+ const opened = await requestLand(branch, { run, cwd, ...(body ? { description: body } : {}) });
96
+ if (!opened.created && body) {
97
+ const edited = await run("gh", ["pr", "edit", opened.url, "--body", body], { cwd, encoding: "utf8" });
98
+ if (edited.status !== 0)
99
+ throw new Error(`gh pr edit failed: ${(edited.stderr || "").trim().split("\n").pop() || `exit ${edited.status}`}`);
100
+ }
101
+ return { ...opened, branch };
102
+ }
@@ -0,0 +1,367 @@
1
+ /**
2
+ * Sandbox change proposals: an agent proposes egress hosts and copied tools, the operator approves on a phone card
3
+ * or from a terminal, and only an approval writes ~/.config/temmo/sandbox-hosts.json and sandbox-tools.json
4
+ * and re-applies the change to live sandboxes (docs/sandbox-proposals.md).
5
+ * The card is approval-shaped on the wire (tool "sandbox_change", the lib/approvals.ts envelope) but no hook reads it
6
+ * and nothing here reads a bus reply: a `reply <id> allow` on the broadcast topic is forgeable by any bus client,
7
+ * exactly like an unverified ask_question answer (lib/operator-token.ts stamps only UI posts). The only paths to applySandboxChange
8
+ * are the UI server's authenticated approve route (web/server/ui.ts, GitHub sign-in + same-origin, like
9
+ * lib/run-terminal.ts's decideRun) and the operator's own terminal (lib/sandbox-cli.ts).
10
+ */
11
+ import { randomBytes } from "node:crypto";
12
+ import { mkdirSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { setTimeout as delay } from "node:timers/promises";
15
+ import { fitApprovalEnvelope } from "./approval-card.js";
16
+ import { parseWireEnvelope } from "./agui.js";
17
+ import { COMMON_TOOLS, readSandboxTools, resolveToolOnPath, uploadToolchain, writeSandboxTools } from "./sandbox-tools.js";
18
+ import { formatHostSpec, parseHostSpec, readSandboxHosts, writeSandboxHosts } from "./sandbox-hosts.js";
19
+ import { labelsOf, listAllSandboxes } from "./sandbox.js";
20
+ import { stripControl } from "./format.js";
21
+ import { approvalEnd } from "./operator.js";
22
+ import { broadcastTopic } from "./config.js";
23
+ import { pollCached, publish, sendMessage } from "./messaging.js";
24
+ import { runnerRequest, runnerSocket } from "./runner-request.js";
25
+ /** The approval card's tool name; the UI server intercepts this tool in its authenticated approve route. */
26
+ export const SANDBOX_CHANGE_TOOL = "sandbox_change";
27
+ export const PROPOSAL_ID = /^[a-f0-9]{12}$/;
28
+ const REASON_MAX = 500;
29
+ const LIST_MAX = 20;
30
+ const DIFF_MAX = 4000;
31
+ // The card shows its summary cut at 300 characters; the delta leads and stays under this so the operator always sees all of it.
32
+ const DELTA_MAX = 200;
33
+ const HISTORY_TAIL_BYTES = 1024 * 1024;
34
+ // approval-end reasons mapped to what the proposing agent sees.
35
+ const END_STATUS = { allowed: "applied", denied: "denied", skipped: "skipped", cancelled: "failed" };
36
+ function endStatus(reason) {
37
+ return reason in END_STATUS ? END_STATUS[reason] : "failed";
38
+ }
39
+ function stringList(value, label) {
40
+ if (value === undefined)
41
+ return [];
42
+ if (!Array.isArray(value) || value.length > LIST_MAX || !value.every((v) => typeof v === "string")) {
43
+ return { error: `${label} must be an array of at most ${LIST_MAX} strings` };
44
+ }
45
+ return value.map((v) => v.trim()).filter(Boolean);
46
+ }
47
+ function hostList(value, label) {
48
+ const raw = stringList(value, label);
49
+ if ("error" in raw)
50
+ return raw;
51
+ const byKey = new Map();
52
+ for (const spec of raw) {
53
+ const one = parseHostSpec(spec);
54
+ if ("error" in one)
55
+ return { error: one.error };
56
+ byKey.set(`${one.host}:${one.port}`, one);
57
+ }
58
+ return [...byKey.values()];
59
+ }
60
+ function toolList(value, label) {
61
+ const raw = stringList(value, label);
62
+ if ("error" in raw)
63
+ return raw;
64
+ const names = [...new Set(raw)];
65
+ for (const name of names) {
66
+ if (!/^[a-z0-9][a-z0-9._+-]{0,63}$/.test(name))
67
+ return { error: `"${name}" is not a tool name (lowercase letters, digits, . _ + -)` };
68
+ }
69
+ return names.sort();
70
+ }
71
+ /**
72
+ * Validate one proposal's fields: at least one change, hosts as host[:port], tools as PATH binary names that are
73
+ * not already in every sandbox, and nothing both added and removed. Returns the normalized change and reason.
74
+ */
75
+ export function validateChange(args) {
76
+ const reason = typeof args.reason === "string" ? stripControl(args.reason).trim() : "";
77
+ if (!reason || reason.length > REASON_MAX)
78
+ return { error: `reason must be 1 to ${REASON_MAX} printable characters` };
79
+ const addHosts = hostList(args.add_hosts, "add_hosts");
80
+ if ("error" in addHosts)
81
+ return addHosts;
82
+ const removeHosts = hostList(args.remove_hosts, "remove_hosts");
83
+ if ("error" in removeHosts)
84
+ return removeHosts;
85
+ const addTools = toolList(args.add_tools, "add_tools");
86
+ if ("error" in addTools)
87
+ return addTools;
88
+ const removeTools = toolList(args.remove_tools, "remove_tools");
89
+ if ("error" in removeTools)
90
+ return removeTools;
91
+ const hostKey = (h) => `${h.host}:${h.port}`;
92
+ const both = (a, b) => [...a].filter((k) => b.has(k));
93
+ if (both(new Set(addHosts.map(hostKey)), new Set(removeHosts.map(hostKey))).length)
94
+ return { error: "a host cannot be added and removed in one proposal" };
95
+ if (both(new Set(addTools), new Set(removeTools)).length)
96
+ return { error: "a tool cannot be added and removed in one proposal" };
97
+ const shadowed = addTools.filter((n) => COMMON_TOOLS.includes(n));
98
+ if (shadowed.length)
99
+ return { error: `${shadowed.join(", ")} is in every sandbox already; it does not need a proposal` };
100
+ if (!addHosts.length && !removeHosts.length && !addTools.length && !removeTools.length) {
101
+ return { error: "give at least one of add_hosts, remove_hosts, add_tools, remove_tools" };
102
+ }
103
+ const change = { addHosts, removeHosts, addTools, removeTools };
104
+ if (changeDelta(change).length > DELTA_MAX)
105
+ return { error: `the change must fit ${DELTA_MAX} characters on the card; split it into smaller proposals` };
106
+ return { change, reason };
107
+ }
108
+ function wireOf(change) {
109
+ return {
110
+ add_hosts: change.addHosts.map(formatHostSpec),
111
+ remove_hosts: change.removeHosts.map(formatHostSpec),
112
+ add_tools: change.addTools,
113
+ remove_tools: change.removeTools,
114
+ };
115
+ }
116
+ export function currentConfig(env = process.env) {
117
+ return { hosts: readSandboxHosts(env).map(formatHostSpec), tools: readSandboxTools(env) };
118
+ }
119
+ /** The before/after text the card and the CLI show: kept lines plain, removals "-", additions "+". */
120
+ export function renderDiff(change, before) {
121
+ const apply = (list, remove, add) => [...new Set([...list.filter((x) => !remove.includes(x)), ...add])].sort();
122
+ const section = (title, pre, post) => {
123
+ const kept = pre.filter((x) => post.includes(x));
124
+ const removed = pre.filter((x) => !post.includes(x));
125
+ const added = post.filter((x) => !pre.includes(x));
126
+ if (!removed.length && !added.length)
127
+ return `${title}:\n (unchanged: ${pre.join(", ") || "none"})`;
128
+ return [`${title}:`, ...kept.map((x) => ` ${x}`), ...removed.map((x) => `- ${x}`), ...added.map((x) => `+ ${x}`)].join("\n");
129
+ };
130
+ const hosts = apply(before.hosts, change.removeHosts.map(formatHostSpec), change.addHosts.map(formatHostSpec));
131
+ const tools = apply(before.tools, change.removeTools, change.addTools);
132
+ return [section("hosts", before.hosts, hosts), section("tools", before.tools, tools)].join("\n").slice(0, DIFF_MAX);
133
+ }
134
+ function changeDelta(change) {
135
+ const parts = [];
136
+ if (change.addHosts.length)
137
+ parts.push(`hosts +${change.addHosts.map(formatHostSpec).join(",")}`);
138
+ if (change.removeHosts.length)
139
+ parts.push(`hosts -${change.removeHosts.map(formatHostSpec).join(",")}`);
140
+ if (change.addTools.length)
141
+ parts.push(`tools +${change.addTools.join(",")}`);
142
+ if (change.removeTools.length)
143
+ parts.push(`tools -${change.removeTools.join(",")}`);
144
+ return parts.join("; ");
145
+ }
146
+ /** One line for the card summary: the whole delta first, then the reason. */
147
+ export function changeSummary(change, reason) {
148
+ return `${changeDelta(change)} | ${reason}`.slice(0, 300);
149
+ }
150
+ /**
151
+ * The summary a card shows, derived from the envelope's change and reason rather than its own summary field, so
152
+ * the operator approves exactly what applySandboxChange writes. null when the change does not validate.
153
+ */
154
+ export function sandboxCardSummary(change, reason) {
155
+ const raw = (change && typeof change === "object" ? change : {});
156
+ const valid = validateChange({ add_hosts: raw.add_hosts, remove_hosts: raw.remove_hosts, add_tools: raw.add_tools, remove_tools: raw.remove_tools, reason });
157
+ return "error" in valid ? null : changeSummary(valid.change, valid.reason);
158
+ }
159
+ /**
160
+ * Post the proposal as an approval card and return its pending id. The diff is computed from the config this
161
+ * process can read: on the host that is the real one; from a sandbox the before lists are empty, and the CLI's
162
+ * `sandbox pending` recomputes them from the host config before the operator decides.
163
+ */
164
+ export async function proposeSandboxChange(cfg, args, { env = process.env, harness = "other" } = {}) {
165
+ const valid = validateChange(args);
166
+ if ("error" in valid)
167
+ throw new Error(valid.error);
168
+ const { change, reason } = valid;
169
+ const diff = renderDiff(change, currentConfig(env));
170
+ const id = randomBytes(6).toString("hex");
171
+ const message = fitApprovalEnvelope("approval", {
172
+ from: cfg.peer, ...(cfg.session ? { session: cfg.session } : {}), harness,
173
+ id, tool: SANDBOX_CHANGE_TOOL, summary: changeSummary(change, reason), expiresAt: 0,
174
+ reason, change: wireOf(change), diff, ts: new Date().toISOString(),
175
+ }, undefined, cfg.wire);
176
+ if (!message)
177
+ throw new Error("the proposal is over the wire limit");
178
+ const sender = cfg.session ? `${cfg.peer}#${cfg.session}` : cfg.peer;
179
+ await publish(cfg, broadcastTopic(cfg.project), message, {
180
+ title: `Sandbox change from ${sender}: ${reason}`.slice(0, 200), priority: 4,
181
+ });
182
+ return { id, status: "pending", change: wireOf(change), reason, diff };
183
+ }
184
+ /** The proposals on the project's broadcast topic, newest first, with each card's close state. */
185
+ export async function listProposals(cfg, { poll = pollCached } = {}) {
186
+ const events = await poll(cfg, broadcastTopic(cfg.project), "all", undefined, { tailBytes: HISTORY_TAIL_BYTES });
187
+ const out = new Map();
188
+ const ended = new Set();
189
+ const cards = new Map();
190
+ for (const ev of events) {
191
+ const e = parseWireEnvelope(ev.message);
192
+ if ((e?.kind === "approval" || e?.kind === "approval-view") && typeof e.id === "string")
193
+ cards.set(e.id, (cards.get(e.id) ?? 0) + 1);
194
+ if (e?.kind === "approval" && e.tool === SANDBOX_CHANGE_TOOL && PROPOSAL_ID.test(String(e.id))) {
195
+ const change = e.change && typeof e.change === "object" ? e.change : {};
196
+ out.set(e.id, {
197
+ id: e.id,
198
+ sender: typeof e.session === "string" && e.session ? `${e.from}#${e.session}` : String(e.from),
199
+ session: typeof e.session === "string" ? e.session : "",
200
+ reason: stripControl(String(e.reason ?? "")).slice(0, REASON_MAX),
201
+ change,
202
+ diff: String(e.diff ?? "").slice(0, DIFF_MAX),
203
+ askedAt: Date.parse(String(e.ts ?? "")) || ev.time * 1000,
204
+ status: "pending",
205
+ });
206
+ }
207
+ else if (e?.kind === "approval-end" && PROPOSAL_ID.test(String(e.id)) && !ended.has(e.id)) {
208
+ ended.add(e.id);
209
+ const p = out.get(e.id);
210
+ if (p) {
211
+ p.status = endStatus(String(e.reason));
212
+ if (typeof e.why === "string")
213
+ p.why = stripControl(e.why).slice(0, 500);
214
+ }
215
+ }
216
+ }
217
+ // A second card under the same id could swap the change after the operator read it; such a proposal never applies.
218
+ for (const p of out.values()) {
219
+ if ((cards.get(p.id) ?? 0) > 1)
220
+ Object.assign(p, { status: "failed", why: "two cards share this proposal id; propose again", duplicate: true });
221
+ }
222
+ return [...out.values()].sort((a, b) => b.askedAt - a.askedAt);
223
+ }
224
+ export async function findProposal(cfg, id, opts = {}) {
225
+ if (!PROPOSAL_ID.test(String(id)))
226
+ return null;
227
+ return (await listProposals(cfg, opts)).find((p) => p.id === id) ?? null;
228
+ }
229
+ /** Poll for the operator's decision on a proposal until the deadline; pending when it passes first. */
230
+ export async function waitForChangeResult(cfg, id, { seconds = 25, signal, poll } = {}) {
231
+ if (!PROPOSAL_ID.test(String(id)))
232
+ throw new Error("Invalid proposal ID");
233
+ const deadline = Date.now() + Math.max(0, Math.min(45, seconds)) * 1000;
234
+ for (;;) {
235
+ const found = await findProposal(cfg, String(id), { poll }).catch(() => null);
236
+ if (found && found.status !== "pending")
237
+ return { id: String(id), status: found.status, ...(found.why ? { why: found.why } : {}) };
238
+ if (Date.now() >= deadline || signal?.aborted)
239
+ return { id: String(id), status: "pending" };
240
+ await delay(1000, undefined, { signal }).catch(() => undefined);
241
+ if (signal?.aborted)
242
+ return { id: String(id), status: "pending" };
243
+ }
244
+ }
245
+ // The one-shot claim: like lib/run-terminal.ts's decision.json, O_EXCL makes a proposal apply exactly once,
246
+ // across the UI server and any terminal on this machine.
247
+ const claimDir = (stateDir, project, id) => join(stateDir, project, "sandbox-changes", id);
248
+ export function claimChange(stateDir, project, id, record) {
249
+ try {
250
+ mkdirSync(claimDir(stateDir, project, id), { recursive: true, mode: 0o700 });
251
+ writeFileSync(join(claimDir(stateDir, project, id), "decision.json"), `${JSON.stringify(record)}\n`, { flag: "wx", mode: 0o600 });
252
+ return true;
253
+ }
254
+ catch (error) {
255
+ if (error.code === "EEXIST")
256
+ return false;
257
+ throw error;
258
+ }
259
+ }
260
+ /**
261
+ * Apply an approved change: claim it once, re-validate the (untrusted) change, resolve every added tool on the
262
+ * host PATH, write both config files, then re-apply to live sandboxes. Host-only: callers are the UI server's
263
+ * authenticated route and the operator's CLI; nothing here reads the bus.
264
+ */
265
+ export async function applySandboxChange({ stateDir, project, id, change, by = "operator", env = process.env, reapply = reapplyLive }) {
266
+ if (!PROPOSAL_ID.test(String(id)))
267
+ return { status: "failed", why: "invalid proposal id" };
268
+ if (!claimChange(stateDir, project, id, { decision: "apply", by, at: Date.now() })) {
269
+ return { status: "already", why: "this proposal was already decided" };
270
+ }
271
+ const raw = (change ?? {});
272
+ const valid = validateChange({
273
+ add_hosts: raw.add_hosts, remove_hosts: raw.remove_hosts, add_tools: raw.add_tools, remove_tools: raw.remove_tools,
274
+ reason: "applied",
275
+ });
276
+ if ("error" in valid)
277
+ return { status: "failed", why: valid.error };
278
+ const { change: c } = valid;
279
+ const missing = c.addTools.filter((name) => !resolveToolOnPath(name, env));
280
+ if (missing.length)
281
+ return { status: "failed", why: `not on the host PATH: ${missing.join(", ")}` };
282
+ const dropHost = new Set(c.removeHosts.map((h) => `${h.host}:${h.port}`));
283
+ const hosts = [...readSandboxHosts(env).filter((h) => !dropHost.has(`${h.host}:${h.port}`)), ...c.addHosts];
284
+ writeSandboxHosts(hosts, env);
285
+ const dropTool = new Set(c.removeTools);
286
+ const tools = [...readSandboxTools(env).filter((n) => !dropTool.has(n)), ...c.addTools];
287
+ writeSandboxTools(tools, env);
288
+ const parts = [];
289
+ if (c.addHosts.length || c.removeHosts.length) {
290
+ parts.push(`hosts +${c.addHosts.map(formatHostSpec).join(",") || "-"} -${c.removeHosts.map(formatHostSpec).join(",") || "-"}`);
291
+ }
292
+ const toolsChanged = c.addTools.length + c.removeTools.length > 0;
293
+ if (toolsChanged)
294
+ parts.push(`tools +${c.addTools.join(",") || "-"} -${c.removeTools.join(",") || "-"}`);
295
+ const live = await reapply({ env, toolsChanged }).catch((error) => ({ detail: `live re-apply failed: ${error.message}` }));
296
+ parts.push(live.detail);
297
+ return { status: "applied", detail: parts.join("; ") };
298
+ }
299
+ /** Close a proposal as denied; one-shot like apply. */
300
+ export function denySandboxChange({ stateDir, project, id, by = "operator", why = "" }) {
301
+ if (!PROPOSAL_ID.test(String(id)))
302
+ return { status: "already", why: "invalid proposal id" };
303
+ if (!claimChange(stateDir, project, id, { decision: "deny", by, why, at: Date.now() })) {
304
+ return { status: "already", why: "this proposal was already decided" };
305
+ }
306
+ return { status: "denied" };
307
+ }
308
+ /**
309
+ * Re-apply the just-written config to the live sandboxes: the toolchain re-uploads where the mark changed, and the
310
+ * runner rebuilds each harness's policy (its adapters own policy shape). A missing runner or openshell is reported,
311
+ * never fatal: new and reused sandboxes get the config anyway, and a runner start refreshes idle ones.
312
+ */
313
+ export async function reapplyLive({ env = process.env, toolsChanged = false } = {}) {
314
+ const notes = [];
315
+ if (toolsChanged) {
316
+ const { refreshed, failed } = await uploadToolchainForAll({ env });
317
+ notes.push(refreshed.length || failed.length
318
+ ? `tools re-uploaded to ${refreshed.length} sandbox(es)${failed.length ? `; failed: ${failed.join(", ")}` : ""}`
319
+ : "tools: no live sandbox needed the new set");
320
+ }
321
+ try {
322
+ const { status, body } = await runnerRequest("POST", "/v1/sandbox/reapply-policies", {}, { socket: runnerSocket(env) });
323
+ if (status === 200)
324
+ notes.push("policy refreshed on live sandboxes");
325
+ else
326
+ notes.push(`policy refresh refused: ${body?.error || `status ${status}`}`);
327
+ }
328
+ catch {
329
+ notes.push("policy refresh deferred: the runner is not reachable; live sandboxes get it at the next runner or session start");
330
+ }
331
+ return { detail: notes.join("; ") || "no live sandboxes" };
332
+ }
333
+ /** The toolchain re-upload half of reapplyLive, over every managed sandbox but run_code's. uploadToolchain is mark-gated: an unchanged set uploads nothing. */
334
+ async function uploadToolchainForAll({ env, openshell = env.TEMMO_OPENSHELL_BIN || "openshell" }) {
335
+ const refreshed = [];
336
+ const failed = [];
337
+ for (const name of await managedSandboxNames({ env, openshell })) {
338
+ try {
339
+ await uploadToolchain({ openshell, env, sandbox: name, label: name, log: () => { } });
340
+ refreshed.push(name);
341
+ }
342
+ catch {
343
+ failed.push(name);
344
+ }
345
+ }
346
+ return { refreshed, failed };
347
+ }
348
+ /** Managed sandbox names on the gateway, run_code's read sandboxes excluded (their policy names no personal hosts). */
349
+ export async function managedSandboxNames({ env = process.env, openshell = env.TEMMO_OPENSHELL_BIN || "openshell" } = {}) {
350
+ const list = await listAllSandboxes({ openshell, env });
351
+ if (list.code !== 0)
352
+ return [];
353
+ return list.records.flatMap((s) => {
354
+ const labels = labelsOf(s);
355
+ return labels["ai-collab.managed"] === "true" && labels["ai-collab.kind"] !== "code" && typeof s?.name === "string" ? [s.name] : [];
356
+ });
357
+ }
358
+ /**
359
+ * Close the card and tell the channel what happened, so the proposing agent can read the outcome with
360
+ * channel_history (the request_pr pattern). cfg must be an operator-peer config for system=true.
361
+ */
362
+ export async function announceChangeDecision(cfg, { id, session, reason, detail, system = false, onPublished }) {
363
+ const topic = broadcastTopic(cfg.project);
364
+ await publish(cfg, topic, approvalEnd(cfg, id, reason, { ...(session ? { session } : {}), ...(detail ? { why: detail.slice(0, 500) } : {}) }), { title: "temmo sandbox change", priority: 1, ...(onPublished ? { onPublished } : {}) }).catch(() => { });
365
+ const verb = reason === "allowed" ? "applied" : reason === "denied" ? "denied" : reason;
366
+ await sendMessage(cfg, "all", `sandbox change ${id} ${verb}${detail ? `: ${detail.slice(0, 400)}` : ""}`, { ...(system ? { system: true } : {}), ...(onPublished ? { onPublished } : {}) }).catch(() => { });
367
+ }