@temmo/cli 0.0.0-stage → 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 +110 -4
  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,143 @@
1
+ // The common tools every OpenShell agent sandbox gets: the image has no git or node, so the host's are uploaded to TOOLS.
2
+ // Extra tools the operator approved sit beside the file's own list in ~/.config/temmo/sandbox-tools.json (docs/sandbox-proposals.md).
3
+ import { createHash } from "node:crypto";
4
+ import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { sharedLibs, toolSources } from "./builder/stage.js";
8
+ import { configDir } from "./config.js";
9
+ import { readJson, writeFileAtomic } from "./store.js";
10
+ import { findExecutable } from "./sessions/scope.js";
11
+ import { execArgv, runTool, TOOLS, uploadFile, uploadTree } from "./sandbox.js";
12
+ /** What every agent sandbox has under TOOLS/bin, builders included (test/sandbox-contract.test.mjs). */
13
+ export const COMMON_TOOLS = ["git", "npm", "npx", "oncebitten"];
14
+ export const SANDBOX_TOOLS_FILE = "sandbox-tools.json";
15
+ // One safe PATH binary name: no slash, no leading dot or dash, so a config entry cannot name a path or a flag.
16
+ export const TOOL_NAME = /^[a-z0-9][a-z0-9._+-]{0,63}$/;
17
+ /** The env a process in the sandbox needs to find the uploaded tools. */
18
+ export const TOOL_ENV = {
19
+ PATH: `${TOOLS}/bin:${TOOLS}/node/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`, GIT_EXEC_PATH: `${TOOLS}/git-core`, LD_LIBRARY_PATH: `${TOOLS}/lib`,
20
+ };
21
+ const TOOLCHAIN_MARK = `${TOOLS}/.toolchain`;
22
+ /** Path of the approved extra-tools file under the config directory. */
23
+ export function sandboxToolsPath(env = process.env) {
24
+ return join(configDir(env), SANDBOX_TOOLS_FILE);
25
+ }
26
+ /** Tool names from sandbox-tools.json; missing or invalid file → []. Never creates the file. */
27
+ export function readSandboxTools(env = process.env) {
28
+ const value = readJson(sandboxToolsPath(env));
29
+ const list = Array.isArray(value) ? value
30
+ : value && typeof value === "object" && Array.isArray(value.tools)
31
+ ? value.tools
32
+ : [];
33
+ const seen = new Set();
34
+ for (const entry of list)
35
+ if (typeof entry === "string" && TOOL_NAME.test(entry))
36
+ seen.add(entry);
37
+ return [...seen].sort();
38
+ }
39
+ /** Writes `{ "tools": [...] }` atomically; creates the config directory when needed. */
40
+ export function writeSandboxTools(names, env = process.env) {
41
+ const tools = [...new Set(names.filter((n) => TOOL_NAME.test(n)))].sort();
42
+ writeFileAtomic(sandboxToolsPath(env), `${JSON.stringify({ tools }, null, 2)}\n`);
43
+ }
44
+ /** The host binary a tool name resolves to on PATH, or "" when nothing executable answers it. */
45
+ export function resolveToolOnPath(name, env = process.env) {
46
+ return TOOL_NAME.test(name) ? findExecutable(name, env.PATH || "") : "";
47
+ }
48
+ /** Adds tool names; every name must resolve on the host PATH or nothing is written. */
49
+ export function addSandboxTools(names, env = process.env) {
50
+ const parsed = [];
51
+ for (const name of names) {
52
+ if (!TOOL_NAME.test(name))
53
+ return { error: `"${name}" is not a tool name (lowercase letters, digits, . _ + -)` };
54
+ if (COMMON_TOOLS.includes(name))
55
+ return { error: `${name} is in every sandbox already; it does not belong in ${SANDBOX_TOOLS_FILE}` };
56
+ if (!resolveToolOnPath(name, env))
57
+ return { error: `${name} is not an executable on the host PATH` };
58
+ parsed.push(name);
59
+ }
60
+ const before = new Set(readSandboxTools(env));
61
+ const tools = [...new Set([...before, ...parsed])].sort();
62
+ writeSandboxTools(tools, env);
63
+ return { tools, added: tools.filter((n) => !before.has(n)) };
64
+ }
65
+ /** Removes tool names; unknown names are simply not removed. */
66
+ export function removeSandboxTools(names, env = process.env) {
67
+ for (const name of names)
68
+ if (!TOOL_NAME.test(name))
69
+ return { error: `"${name}" is not a tool name (lowercase letters, digits, . _ + -)` };
70
+ const drop = new Set(names);
71
+ const current = readSandboxTools(env);
72
+ const tools = current.filter((n) => !drop.has(n));
73
+ writeSandboxTools(tools, env);
74
+ return { tools, removed: current.filter((n) => drop.has(n)) };
75
+ }
76
+ /** The approved extra tools with their host binaries; a name that no longer resolves maps to "". */
77
+ export function extraToolSources(env = process.env) {
78
+ return readSandboxTools(env).map((name) => [name, resolveToolOnPath(name, env)]);
79
+ }
80
+ /** Stages the host's git, git-core, oncebitten, node and npm, plus the approved extras, under dir with their non-glibc libraries; `key` changes when any of them does. */
81
+ export async function stageToolchain(dir, env, log) {
82
+ const src = toolSources({ root: "", harness: "" }, env);
83
+ const extras = extraToolSources(env);
84
+ const tools = join(dir, "tools");
85
+ mkdirSync(join(tools, "bin"), { recursive: true });
86
+ const copies = [["git", src.git], ["oncebitten", src.oncebitten], ...extras];
87
+ for (const [bin, from] of copies) {
88
+ if (from) {
89
+ copyFileSync(from, join(tools, "bin", bin));
90
+ chmodSync(join(tools, "bin", bin), 0o755);
91
+ }
92
+ else if (log)
93
+ log(`no ${bin} found on the host; the sandbox has none`);
94
+ }
95
+ const binaries = [src.git, src.node, ...extras.map(([, from]) => from)].filter(Boolean);
96
+ const libs = [...new Set((await Promise.all(binaries.map((bin) => sharedLibs(bin, env)))).flat())];
97
+ // The image lacks some of their libraries (libatomic.so.1, measured 2026-11-22); glibc itself stays the image's.
98
+ if (libs.length)
99
+ mkdirSync(join(tools, "lib"), { recursive: true });
100
+ // Named by the soname ldd printed, not the real file's name, or the loader misses it.
101
+ for (const lib of libs)
102
+ copyFileSync(realpathSync(lib), join(tools, "lib", basename(lib)));
103
+ if (src.npm) {
104
+ symlinkSync(`${TOOLS}/node/lib/node_modules/npm/bin/npm-cli.js`, join(tools, "bin", "npm"));
105
+ symlinkSync(`${TOOLS}/node/lib/node_modules/npm/bin/npx-cli.js`, join(tools, "bin", "npx"));
106
+ }
107
+ const extrasKey = extras.map(([name, from]) => `${name}=${from}`).sort().join("\n");
108
+ const key = createHash("sha256").update([src.git, src.gitCore, src.oncebitten, src.node, src.npm, extrasKey].join("\n")).digest("hex").slice(0, 16);
109
+ writeFileSync(join(tools, basename(TOOLCHAIN_MARK)), `${key}\n`);
110
+ return { tools, gitCore: src.gitCore, node: src.node, npm: src.npm, libs, key };
111
+ }
112
+ /** Uploads the common tools to TOOLS unless the sandbox already has this host's set (TOOLCHAIN_MARK holds its key). */
113
+ export async function uploadToolchain({ openshell, env, sandbox, label, log }) {
114
+ const exec = (command) => runTool(openshell, execArgv({ openshell, sandbox, command }).slice(1), { env });
115
+ const dir = mkdtempSync(join(tmpdir(), "temmo-sandbox-tools-"));
116
+ try {
117
+ // Held back until the mark check: a sandbox that already has this host's set logs nothing.
118
+ const missing = [];
119
+ const staged = await stageToolchain(dir, env, (line) => missing.push(`${label}: ${line}`));
120
+ if ((await exec(["cat", TOOLCHAIN_MARK])).stdout.trim() === staged.key)
121
+ return;
122
+ if (!staged.node)
123
+ log(`${label}: no node found on the host; the sandbox has none`);
124
+ for (const line of missing)
125
+ log(line);
126
+ const mark = join(staged.tools, basename(TOOLCHAIN_MARK));
127
+ const key = readFileSync(mark, "utf8");
128
+ rmSync(mark);
129
+ await uploadTree({ openshell, env, sandbox, local: staged.tools, remote: dirname(TOOLS), gitIgnore: false });
130
+ if (staged.gitCore)
131
+ await uploadTree({ openshell, env, sandbox, local: staged.gitCore, remote: TOOLS, gitIgnore: false });
132
+ if (staged.node)
133
+ await uploadFile({ openshell, env, sandbox, local: staged.node, remoteDir: `${TOOLS}/node/bin` });
134
+ if (staged.npm)
135
+ await uploadTree({ openshell, env, sandbox, local: staged.npm, remote: `${TOOLS}/node/lib/node_modules`, gitIgnore: false });
136
+ // The mark goes last, so an upload cut short is redone on the next start.
137
+ writeFileSync(mark, key);
138
+ await uploadFile({ openshell, env, sandbox, local: mark, remoteDir: TOOLS });
139
+ }
140
+ finally {
141
+ rmSync(dir, { recursive: true, force: true });
142
+ }
143
+ }
package/lib/sandbox.js ADDED
@@ -0,0 +1,501 @@
1
+ // OpenShell sandboxes: CLI calls, the sandbox cap, and the staged upload that builders and scheduled runs share.
2
+ // Verified against openshell 0.1.9 on 2026-11-22 (docs/owned-sessions-contract.md, OpenShell section).
3
+ import { spawn } from "node:child_process";
4
+ import { createHash } from "node:crypto";
5
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { homedir, tmpdir } from "node:os";
7
+ import { basename, dirname, join } from "node:path";
8
+ import { setTimeout as delay } from "node:timers/promises";
9
+ import { autoDefaults } from "./config.js";
10
+ export const SANDBOX = "/sandbox";
11
+ export const WORK = `${SANDBOX}/work`;
12
+ export const TOOLS = `${SANDBOX}/tools`;
13
+ export const HOME_IN = `${SANDBOX}/home`;
14
+ export const OUT = `${SANDBOX}/out`;
15
+ export const DEPS = `${SANDBOX}/deps`;
16
+ export const NTFY_TOKEN_IN = `${HOME_IN}/.config/temmo/ntfy-token`;
17
+ // The cap on OpenShell sandboxes when defaults.json names no maxSandboxes (operator decision 2026-11-23).
18
+ export const DEFAULT_MAX_SANDBOXES = 6;
19
+ // openshell 0.1.9 refuses a sandbox name over 19 characters (measured 2026-11-22).
20
+ const SANDBOX_NAME_MAX = 19;
21
+ const SETUP_TIMEOUT_MS = 60_000;
22
+ export const SYNC_TIMEOUT_MS = 600_000;
23
+ export const UPLOAD_TIMEOUT_MS = 900_000;
24
+ // openshell refuses uploads with "sandbox is not ready" while a sandbox comes up after a gateway restart (2026-12-04).
25
+ const NOT_READY = /sandbox is not ready/i;
26
+ const NOT_READY_WAIT_MS = 180_000;
27
+ const NOT_READY_POLL_MS = 2_000;
28
+ // run_code's shared sandbox and its per-call read sandboxes (lib/code-run.ts) sit outside the cap.
29
+ const CAP_EXEMPT = /^(ai-collab-code$|aic-ro-)/;
30
+ const MANAGED_LABEL = "ai-collab.managed";
31
+ const PROJECT_LABEL = "ai-collab.project";
32
+ const KIND_LABEL = "ai-collab.kind";
33
+ const OWNER_LABEL = "ai-collab.owner";
34
+ const VERSION_LABEL = "ai-collab.version";
35
+ // The names temmo generated before labels: sandboxName, teamSandboxName, builderSandbox (b-<8>-<6hex>), runSandboxName (s-<8>-<6hex>).
36
+ const LEGACY_NAME = /^(ai-collab-[a-z0-9-]{1,10}|team-[0-9a-f]{14}|b-[A-Za-z0-9-]{0,8}-[0-9a-f]{6}|s-[A-Za-z0-9-]{0,8}-[0-9a-f]{6})$/;
37
+ const PACKAGE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
38
+ /** Lowercase DNS-label-safe sandbox name for a project. */
39
+ export function sandboxName(project) {
40
+ // The pre-rename prefix stays: the runner reuses a project's sandbox by this name across restarts.
41
+ return prefixedName("ai-collab-", project);
42
+ }
43
+ /** The sandbox the runner's OpenCode sessions of a project share: aic-oc-<project>, apart from Cursor's ai-collab-<project>. */
44
+ export function opencodeSandboxName(project) {
45
+ return prefixedName("aic-oc-", project);
46
+ }
47
+ /** The sandbox the runner's sessions of one harness share in a project: Cursor's ai-collab-<p>, OpenCode's aic-oc-<p>, Claude's aic-cl-<p>, Codex's aic-cx-<p>, pi's aic-pi-<p>. */
48
+ export function harnessSandboxName(harness, project) {
49
+ if (harness === "opencode")
50
+ return opencodeSandboxName(project);
51
+ if (harness === "claude")
52
+ return prefixedName("aic-cl-", project);
53
+ if (harness === "codex")
54
+ return prefixedName("aic-cx-", project);
55
+ if (harness === "pi")
56
+ return prefixedName("aic-pi-", project);
57
+ return sandboxName(project);
58
+ }
59
+ // prefix plus the project's slug, or plus 8 hex of its hash when the slug is empty or too long.
60
+ function prefixedName(prefix, project) {
61
+ const slug = String(project).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
62
+ const name = `${prefix}${slug}`;
63
+ if (slug && name.length <= SANDBOX_NAME_MAX)
64
+ return name;
65
+ const suffix = createHash("sha256").update(String(project)).digest("hex").slice(0, 8);
66
+ return `${prefix}${suffix}`;
67
+ }
68
+ /** The sandbox a team run's OpenShell members share: team-<14 hex of project/run>. */
69
+ export function teamSandboxName(project, run) {
70
+ return "team-" + createHash("sha256").update(project + "/" + run).digest("hex").slice(0, 14);
71
+ }
72
+ /** The phase a sandbox JSON record reports; 0.1.9 writes "Ready" on `sandbox get` and `sandbox list`. */
73
+ export function sandboxPhase(sandbox) {
74
+ const status = sandbox?.status;
75
+ const statusPhase = typeof status === "object" && status !== null ? status.phase : undefined;
76
+ return String(sandbox?.phase ?? sandbox?.state ?? statusPhase ?? status ?? "");
77
+ }
78
+ /** The start/resume step for a sandbox in a non-ready phase, or null when it needs none. */
79
+ export function stateCommand(name, phase) {
80
+ if (/suspend/i.test(phase))
81
+ return ["resume", name];
82
+ if (/stop|exited|terminated/i.test(phase))
83
+ return ["start", name];
84
+ return null;
85
+ }
86
+ /** Argv that runs a command in a sandbox; env pairs come first, then `--workdir`, then the command. */
87
+ export function execArgv({ openshell, sandbox, workdir, env = {}, command }) {
88
+ return [
89
+ openshell, "sandbox", "exec", "--no-tty", "-n", sandbox,
90
+ ...Object.entries(env).flatMap(([key, value]) => ["--env", `${key}=${value}`]),
91
+ ...(workdir ? ["--workdir", workdir] : []),
92
+ "--", ...command,
93
+ ];
94
+ }
95
+ /** Argv that copies a host directory into a sandbox; both paths end in "/" so the basename is kept. */
96
+ export function uploadArgv({ openshell, sandbox, local, remote }) {
97
+ return [openshell, "sandbox", "upload", sandbox, `${local.replace(/\/+$/, "")}/`, `${remote.replace(/\/+$/, "")}/`];
98
+ }
99
+ /** Argv that copies a sandbox path back to the host. */
100
+ export function downloadArgv({ openshell, sandbox, remote, local }) {
101
+ return [openshell, "sandbox", "download", sandbox, remote, local];
102
+ }
103
+ /** Runs a short-lived tool to completion; never rejects, so a missing binary reports through `stderr`. */
104
+ export function runTool(bin, args, { env, cwd, timeoutMs = SETUP_TIMEOUT_MS, stdin } = {}) {
105
+ return new Promise((resolve) => {
106
+ const child = spawn(bin, args, { env, cwd, shell: false, stdio: [stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"] });
107
+ let stdout = "";
108
+ let stderr = "";
109
+ child.stdout?.setEncoding("utf8");
110
+ child.stderr?.setEncoding("utf8");
111
+ child.stdout?.on("data", (d) => { stdout += d; });
112
+ child.stderr?.on("data", (d) => { stderr += d; });
113
+ if (stdin !== undefined) {
114
+ child.stdin?.on("error", () => { });
115
+ child.stdin?.end(stdin);
116
+ }
117
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
118
+ child.on("error", (error) => { clearTimeout(timer); resolve({ code: null, stdout, stderr: error.message }); });
119
+ child.on("close", (code) => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
120
+ });
121
+ }
122
+ /** Replaces a live sandbox's policy. `policy update` cannot change an endpoint that is already listed with different metadata. */
123
+ export async function setSandboxPolicy({ openshell, env, name, policy }) {
124
+ await must(openshell, ["policy", "set", "--policy", policy, "--wait", name], { env, timeoutMs: SYNC_TIMEOUT_MS, what: "policy set" });
125
+ }
126
+ /**
127
+ * Replaces the policy on each named sandbox that exists on the gateway now, and returns those names. A sandbox that
128
+ * does not exist yet gets its policy at create. Lists once, so a runner start costs one `sandbox list` per harness.
129
+ */
130
+ export async function refreshSandboxPolicies({ openshell, env, names, policy }) {
131
+ if (!names.length)
132
+ return [];
133
+ const list = await listAllSandboxes({ openshell, env });
134
+ if (list.code !== 0)
135
+ throw new Error(`openshell sandbox list failed: ${list.stderr.trim() || `exit ${list.code}`}`);
136
+ const present = new Set(list.records.map((s) => s?.name).filter((n) => typeof n === "string"));
137
+ const refreshed = [...new Set(names)].filter((name) => present.has(name));
138
+ for (const name of refreshed)
139
+ await setSandboxPolicy({ openshell, env, name, policy });
140
+ return refreshed;
141
+ }
142
+ /** Runs a command to completion, throwing `<prefix><what> failed: <detail>` on a non-zero exit. */
143
+ export async function must(bin, args, { env, timeoutMs, what, errorPrefix = "openshell ", stdoutFallback = false }) {
144
+ const out = await runTool(bin, args, { env, timeoutMs });
145
+ if (out.code === 0)
146
+ return out;
147
+ const detail = (stdoutFallback ? out.stderr || out.stdout || "" : out.stderr || "").trim() || `exit ${out.code}`;
148
+ throw new Error(`${errorPrefix}${what} failed: ${detail}`);
149
+ }
150
+ /** A git runner for a host command: runs `git -C cwd args`, returns stdout, throws with `git <verb> failed:`. */
151
+ export function gitIn(env, timeoutMs = UPLOAD_TIMEOUT_MS) {
152
+ return async (cwd, args) => (await must("git", ["-C", cwd, ...args], { env, timeoutMs, what: `git ${args[0]}`, errorPrefix: "", stdoutFallback: true })).stdout;
153
+ }
154
+ /** Parses `openshell sandbox list -o json`; throws when the reply is not JSON. */
155
+ export function parseSandboxList(stdout) {
156
+ let parsed;
157
+ try {
158
+ parsed = JSON.parse(stdout);
159
+ }
160
+ catch {
161
+ throw new Error("openshell sandbox list printed no JSON");
162
+ }
163
+ return Array.isArray(parsed?.sandboxes) ? parsed.sandboxes : [];
164
+ }
165
+ /** Every sandbox on the gateway: pages through `sandbox list` until a page names no next token. Stops at the first failed page. */
166
+ export async function listAllSandboxes({ openshell, env }) {
167
+ const records = [];
168
+ let token = "";
169
+ const seen = new Set();
170
+ for (;;) {
171
+ const out = await runTool(openshell, ["sandbox", "list", "-o", "json", ...(token ? ["--page-token", token] : [])], { env });
172
+ if (out.code !== 0)
173
+ return { code: out.code, stderr: out.stderr, records };
174
+ records.push(...parseSandboxList(out.stdout));
175
+ const next = String(JSON.parse(out.stdout).next_page_token ?? "");
176
+ if (!next || seen.has(next))
177
+ return { code: 0, stderr: "", records };
178
+ seen.add(next);
179
+ token = next;
180
+ }
181
+ }
182
+ /** The labels every temmo sandbox is created with: the managed mark, its project, kind, owner and package version. */
183
+ export function sandboxLabels({ project, kind, owner }) {
184
+ return { [MANAGED_LABEL]: "true", [PROJECT_LABEL]: project, [KIND_LABEL]: kind, [OWNER_LABEL]: owner, [VERSION_LABEL]: PACKAGE_VERSION };
185
+ }
186
+ /** The `--label key=value` pairs for `sandbox create`. */
187
+ export function labelArgs(labels) {
188
+ return Object.entries(labels).flatMap(([key, value]) => ["--label", `${key}=${value}`]);
189
+ }
190
+ /** The labels a sandbox record reports; a sandbox created without labels reports none. */
191
+ export function labelsOf(sandbox) {
192
+ return sandbox?.labels && typeof sandbox.labels === "object" ? sandbox.labels : {};
193
+ }
194
+ /**
195
+ * Lists sandboxes once, then creates the named one when it is missing, starts or resumes it when its
196
+ * phase says so. Throws an Error whose message the operator can act on; never prints a secret.
197
+ */
198
+ export async function ensureSandbox({ openshell, env, name, policy, labels = {}, recreateBroken = false }) {
199
+ const list = await listAllSandboxes({ openshell, env });
200
+ if (list.code !== 0)
201
+ throw new Error(`openshell sandbox list failed: ${list.stderr.trim() || `exit ${list.code}`}`);
202
+ let found = list.records.find((s) => s?.name === name);
203
+ const foundProject = labelsOf(found)[PROJECT_LABEL];
204
+ if (found && foundProject && labels[PROJECT_LABEL] && foundProject !== labels[PROJECT_LABEL])
205
+ throw new Error(`sandbox ${name} belongs to project ${foundProject}; it is not reused`);
206
+ // A sandbox in Error never becomes ready; a caller whose sandbox holds no work (run_code) replaces it.
207
+ if (found && recreateBroken && /error|fail/i.test(sandboxPhase(found))) {
208
+ await must(openshell, ["sandbox", "delete", name], { env, timeoutMs: SYNC_TIMEOUT_MS, what: "sandbox delete" });
209
+ found = undefined;
210
+ }
211
+ if (found) {
212
+ const step = stateCommand(name, sandboxPhase(found));
213
+ if (step)
214
+ await must(openshell, ["sandbox", ...step], { env, what: `sandbox ${step[0]}` });
215
+ // Create applies --policy once. A sandbox kept from an older run gets the policy this process wrote.
216
+ if (policy)
217
+ await setSandboxPolicy({ openshell, env, name, policy });
218
+ return name;
219
+ }
220
+ await must(openshell, [
221
+ "sandbox", "create", "--name", name, "--no-tty", "--detach",
222
+ ...(policy ? ["--policy", policy] : []),
223
+ ...labelArgs(labels),
224
+ ], { env, timeoutMs: SYNC_TIMEOUT_MS, what: "sandbox create" });
225
+ return name;
226
+ }
227
+ /** Uploads a host directory into a sandbox; a tree git filtering empties is retried unfiltered. */
228
+ export async function uploadTree({ openshell, env, sandbox, local, remote, gitIgnore = true }) {
229
+ const args = uploadArgv({ openshell, sandbox, local, remote }).slice(1);
230
+ if (!gitIgnore)
231
+ args.push("--no-git-ignore");
232
+ const out = await runTool(openshell, args, { env, timeoutMs: SYNC_TIMEOUT_MS });
233
+ // Inside a work tree openshell drops .gitignore matches, and a tree with no tracked files uploads nothing.
234
+ if (gitIgnore && out.code !== 0 && /Git filtering selected no files/i.test(out.stderr)) {
235
+ return must(openshell, [...args.slice(0, 2), "--no-git-ignore", ...args.slice(2)], { env, timeoutMs: SYNC_TIMEOUT_MS, what: "sandbox upload" });
236
+ }
237
+ if (out.code !== 0)
238
+ throw new Error(`openshell sandbox upload failed: ${out.stderr.trim() || `exit ${out.code}`}`);
239
+ return out;
240
+ }
241
+ /** Uploads a host directory unfiltered: .gitignore filtering would drop the clone's .git and every dependency. */
242
+ export function uploadAll({ openshell, env, sandbox, local, remote, timeoutMs = UPLOAD_TIMEOUT_MS, errorPrefix, stdoutFallback }) {
243
+ return must(openshell, ["sandbox", "upload", sandbox, `${local.replace(/\/+$/, "")}/`, `${remote.replace(/\/+$/, "")}/`, "--no-git-ignore"], { env, timeoutMs, what: "sandbox upload", errorPrefix, stdoutFallback });
244
+ }
245
+ /** Uploads one host file into a sandbox directory; a trailing slash on the directory keeps the file's own name. */
246
+ export async function uploadFile({ openshell, env, sandbox, local, remoteDir }) {
247
+ const dest = `${remoteDir.replace(/\/+$/, "")}/`;
248
+ return must(openshell, ["sandbox", "upload", sandbox, local, dest, "--no-git-ignore"], { env, timeoutMs: SYNC_TIMEOUT_MS, what: "sandbox upload" });
249
+ }
250
+ /** Runs `attempt` again every `pollMs` while it throws "sandbox is not ready", until `waitMs` has passed; other errors throw at once. */
251
+ export async function whenSandboxReady(attempt, { waitMs = NOT_READY_WAIT_MS, pollMs = NOT_READY_POLL_MS } = {}) {
252
+ const deadline = Date.now() + waitMs;
253
+ for (;;) {
254
+ try {
255
+ return await attempt();
256
+ }
257
+ catch (error) {
258
+ if (!NOT_READY.test(error.message) || Date.now() >= deadline)
259
+ throw error;
260
+ }
261
+ await delay(pollMs);
262
+ }
263
+ }
264
+ /** Downloads a sandbox path to a host path. */
265
+ export async function downloadTree({ openshell, env, sandbox, remote, local, timeoutMs = SYNC_TIMEOUT_MS, errorPrefix, stdoutFallback }) {
266
+ return must(openshell, downloadArgv({ openshell, sandbox, remote, local }).slice(1), { env, timeoutMs, what: "sandbox download", errorPrefix, stdoutFallback });
267
+ }
268
+ /** Deletes a sandbox; never throws, so a failed cleanup cannot mask the session's own error. */
269
+ export async function destroySandbox({ openshell, env, name }) {
270
+ const out = await runTool(openshell, ["sandbox", "delete", name], { env, timeoutMs: SYNC_TIMEOUT_MS });
271
+ return { ok: out.code === 0, detail: (out.stderr || out.stdout).trim() };
272
+ }
273
+ /** Names of sandboxes this runner owns for a project. */
274
+ export function ownedSandboxNames(project) {
275
+ return [sandboxName(project)];
276
+ }
277
+ /** The sandbox cap: defaults.json maxSandboxes when a positive integer, else DEFAULT_MAX_SANDBOXES. */
278
+ export function maxSandboxes(env = process.env) {
279
+ const defaults = autoDefaults(env);
280
+ const value = defaults?.maxSandboxes;
281
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : DEFAULT_MAX_SANDBOXES;
282
+ }
283
+ /** The sandbox names the cap counts: every one but run_code's. */
284
+ export function countedSandboxes(names) {
285
+ return names.filter((name) => typeof name === "string" && !CAP_EXEMPT.test(name));
286
+ }
287
+ /**
288
+ * The sandboxes the cap counts, across every project on the gateway: each managed one but run_code's, plus an unlabelled
289
+ * sandbox whose name matches a temmo name (logged as legacy). Unmanaged sandboxes are never counted.
290
+ */
291
+ export function capCounted(records, log = () => { }) {
292
+ return records.flatMap((s) => {
293
+ const name = s?.name ?? "";
294
+ const labels = labelsOf(s);
295
+ if (labels[MANAGED_LABEL] === "true")
296
+ return labels[KIND_LABEL] !== "code" ? [name] : [];
297
+ if (Object.keys(labels).length === 0 && LEGACY_NAME.test(name) && !CAP_EXEMPT.test(name)) {
298
+ log(`sandbox ${name} has no labels; the cap counts it by its legacy name`);
299
+ return [name];
300
+ }
301
+ return [];
302
+ });
303
+ }
304
+ /**
305
+ * Why a new sandbox named `name` may not start, or "" when it may: the cap is machine-wide and counts every project's
306
+ * builders, runner sessions and schedule ticks. A name already listed is a reuse, not a new sandbox. A failed list is left to the create step.
307
+ */
308
+ export async function sandboxCapRefusal({ openshell, env, name = "", log }) {
309
+ const list = await listAllSandboxes({ openshell, env }).catch(() => null);
310
+ if (!list || list.code !== 0)
311
+ return "";
312
+ const records = list.records;
313
+ if (name && records.some((s) => s?.name === name))
314
+ return "";
315
+ const counted = capCounted(records, log);
316
+ const cap = maxSandboxes(env);
317
+ return counted.length >= cap ? `${counted.length} OpenShell sandboxes are running (${counted.join(", ")}); the cap is ${cap} (defaults.json maxSandboxes)` : "";
318
+ }
319
+ /**
320
+ * The sandboxes temmo created for a project, kind and owner, read from their labels. An unlabelled sandbox is
321
+ * selected only when its name is in legacyNames (the name it had before labels), and is logged as legacy.
322
+ */
323
+ export async function listManagedSandboxes({ openshell, env, project, kind, owner, legacyNames = [], log = () => { } }) {
324
+ const list = await listAllSandboxes({ openshell, env });
325
+ if (list.code !== 0)
326
+ throw new Error(`openshell sandbox list failed: ${list.stderr.trim() || `exit ${list.code}`}`);
327
+ return list.records.flatMap((s) => {
328
+ const name = s?.name ?? "";
329
+ const labels = labelsOf(s);
330
+ if (labels[MANAGED_LABEL] === "true") {
331
+ return labels[PROJECT_LABEL] === project && labels[KIND_LABEL] === kind && labels[OWNER_LABEL] === owner ? [{ name, labels, legacy: false }] : [];
332
+ }
333
+ if (Object.keys(labels).length === 0 && legacyNames.includes(name)) {
334
+ log(`sandbox ${name} has no labels; selected by its legacy name`);
335
+ return [{ name, labels, legacy: true }];
336
+ }
337
+ return [];
338
+ });
339
+ }
340
+ /** Deletes the sandboxes listManagedSandboxes selects; never throws, so a failed cleanup cannot mask the session's own error. */
341
+ export async function destroyOwnedSandboxes({ openshell, env, project, kind, owner, legacyNames, log }) {
342
+ let selected;
343
+ try {
344
+ selected = await listManagedSandboxes({ openshell, env, project, kind, owner, legacyNames, log });
345
+ }
346
+ catch (error) {
347
+ return { ok: false, detail: error.message, names: [] };
348
+ }
349
+ const failed = [];
350
+ for (const sandbox of selected) {
351
+ const out = await destroySandbox({ openshell, env, name: sandbox.name });
352
+ if (!out.ok)
353
+ failed.push(`${sandbox.name}: ${out.detail}`);
354
+ }
355
+ return { ok: failed.length === 0, detail: failed.join("; "), names: selected.map((s) => s.name) };
356
+ }
357
+ /**
358
+ * The Claude and Codex login files a sandbox gets, found as lib/builder.ts finds them: Claude's
359
+ * `$CLAUDE_CONFIG_DIR/.credentials.json` (default ~/.claude), Codex's `$CODEX_HOME/auth.json`, else ~/.codex/auth.json.
360
+ */
361
+ export function harnessLogins(env = process.env, home = env.HOME || homedir(), remoteHome = HOME_IN) {
362
+ const claude = join(env.CLAUDE_CONFIG_DIR || join(home, ".claude"), ".credentials.json");
363
+ const codex = [join(env.CODEX_HOME || join(home, ".codex"), "auth.json"), join(home, ".codex", "auth.json")].find((file) => existsSync(file));
364
+ const pi = join(env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent"), "auth.json");
365
+ return [
366
+ ...(existsSync(claude) ? [{ harness: "claude", file: claude, remoteDir: `${remoteHome}/.claude` }] : []),
367
+ ...(codex ? [{ harness: "codex", file: codex, remoteDir: `${remoteHome}/.codex` }] : []),
368
+ ...(existsSync(pi) ? [{ harness: "pi", file: pi, remoteDir: `${remoteHome}/.pi/agent` }] : []),
369
+ ];
370
+ }
371
+ /** Copies one secret in through a 0600 temp file, so it never appears in argv, env or a log. */
372
+ export async function uploadSecret({ openshell, env, sandbox, file, remoteDir, name = basename(file), tmpPrefix = "temmo-sandbox-secret-" }) {
373
+ const dir = mkdtempSync(join(tmpdir(), tmpPrefix));
374
+ try {
375
+ writeFileSync(join(dir, name), readFileSync(file), { mode: 0o600 });
376
+ return await uploadFile({ openshell, env, sandbox, local: join(dir, name), remoteDir });
377
+ }
378
+ finally {
379
+ rmSync(dir, { recursive: true, force: true });
380
+ }
381
+ }
382
+ /** Copies the host's Claude and Codex logins into a sandbox home; a failed copy is logged, never fatal. Returns the harnesses copied. */
383
+ export async function uploadLogins({ openshell, env, sandbox, home, remoteHome, log = () => { } }) {
384
+ const copied = [];
385
+ for (const login of harnessLogins(env, home, remoteHome)) {
386
+ try {
387
+ await uploadSecret({ openshell, env, sandbox, file: login.file, remoteDir: login.remoteDir });
388
+ copied.push(login.harness);
389
+ }
390
+ catch (error) {
391
+ log(`could not copy the ${login.harness} login into ${sandbox}: ${error.message.split("\n")[0]}`);
392
+ }
393
+ }
394
+ return copied;
395
+ }
396
+ /** The host's bus token file from defaults.json, or "". */
397
+ export function hostTokenFile(env = process.env) {
398
+ const defaults = autoDefaults(env);
399
+ const file = defaults?.tokenFile;
400
+ return typeof file === "string" && existsSync(file) ? file : "";
401
+ }
402
+ /** Regular executable files directly in a directory: the binaries a network policy names. */
403
+ export function executables(dir) {
404
+ try {
405
+ return readdirSync(dir).filter((f) => { const st = statSync(join(dir, f)); return st.isFile() && (st.mode & 0o111) !== 0; });
406
+ }
407
+ catch {
408
+ return [];
409
+ }
410
+ }
411
+ /** The SHA-256 of a file, or "" when it cannot be read. */
412
+ export function fileHash(file) {
413
+ try {
414
+ return createHash("sha256").update(readFileSync(file)).digest("hex");
415
+ }
416
+ catch {
417
+ return "";
418
+ }
419
+ }
420
+ /**
421
+ * Uploads the staged tree in the order builders and scheduled runs share; each caller's optional steps are the fields
422
+ * it sets (npm and logins). Returns the SHA-256 of the uploaded credentials file, or "".
423
+ */
424
+ export async function stageAndUpload(a) {
425
+ const { openshell, env, sandbox, log, staged, layout, style } = a;
426
+ const common = { openshell, env, sandbox };
427
+ await uploadAll({ ...common, local: staged.clone, remote: WORK, ...style });
428
+ await uploadAll({ ...common, local: staged.tools, remote: SANDBOX, ...style });
429
+ await uploadAll({ ...common, local: staged.home, remote: SANDBOX, ...style });
430
+ if (staged.gitCore)
431
+ await uploadAll({ ...common, local: staged.gitCore, remote: TOOLS, ...style });
432
+ if (staged.node)
433
+ await uploadFile({ ...common, local: staged.node, remoteDir: `${TOOLS}/node/bin` });
434
+ if (staged.npm)
435
+ await uploadAll({ ...common, local: staged.npm, remote: `${TOOLS}/node/lib/node_modules`, ...style });
436
+ if (layout.file)
437
+ await uploadFile({ ...common, local: layout.tree, remoteDir: layout.dir });
438
+ else
439
+ await uploadAll({ ...common, local: layout.tree, remote: layout.dir, ...style });
440
+ let authHash = "";
441
+ if (layout.auth) {
442
+ await uploadSecret({ ...common, file: layout.auth, remoteDir: layout.authDir, tmpPrefix: a.secretTmp });
443
+ authHash = fileHash(layout.auth);
444
+ }
445
+ else
446
+ log(a.authMissing);
447
+ if (a.logins)
448
+ await uploadLogins({ ...common, home: a.logins.home, remoteHome: a.logins.remoteHome, log });
449
+ if (staged.ntfyToken)
450
+ await uploadSecret({ ...common, file: staged.ntfyToken, remoteDir: dirname(NTFY_TOKEN_IN), name: basename(NTFY_TOKEN_IN), tmpPrefix: a.secretTmp });
451
+ if (staged.nodeModules) {
452
+ await uploadAll({ ...common, local: staged.nodeModules, remote: DEPS, ...style });
453
+ await must(openshell, execArgv({ openshell, sandbox, command: ["ln", "-sfn", `${DEPS}/${basename(staged.nodeModules)}`, `${staged.workdir}/node_modules`] }).slice(1), { env, timeoutMs: UPLOAD_TIMEOUT_MS, what: "sandbox exec ln", ...style });
454
+ }
455
+ return { authHash };
456
+ }
457
+ /** Commits loose work in a downloaded clone when it has any; returns whether it committed. */
458
+ export async function commitUncommitted({ git, repo, message, trailer }) {
459
+ if (!(await git(repo, ["status", "--porcelain"])).trim())
460
+ return false;
461
+ await git(repo, ["add", "-A"]);
462
+ await git(repo, [...(await commitIdentity({ git, repo })), "commit", "--quiet", "--no-verify", "-m", message, ...(trailer ? ["-m", trailer] : [])]);
463
+ return true;
464
+ }
465
+ /** Identity flags for a commit the host makes for an agent: none when git can name the committer, else a fixed temmo one (a CI runner has none). */
466
+ export async function commitIdentity({ git, repo }) {
467
+ try {
468
+ await git(repo, ["var", "GIT_COMMITTER_IDENT"]);
469
+ return [];
470
+ }
471
+ catch {
472
+ return ["-c", "user.name=temmo", "-c", "user.email=temmo@localhost"];
473
+ }
474
+ }
475
+ /** The commits a clone has on top of its base. */
476
+ export async function commitsAhead({ git, repo, base }) {
477
+ return Number((await git(repo, ["rev-list", "--count", `${base}..HEAD`])).trim()) || 0;
478
+ }
479
+ /**
480
+ * Downloads the clone, commits loose work, and fetches new commits into cwd's repo as sandbox/<name>-<stamp>; returns that branch or "".
481
+ */
482
+ export async function landBranch({ openshell, env, sandbox, cwd, name, workdir, base, dir, log, now = Date.now() }) {
483
+ const git = gitIn(env);
484
+ await runTool(openshell, execArgv({ openshell, sandbox, command: ["rm", "-f", `${workdir}/node_modules`] }).slice(1), { env });
485
+ const back = join(dir, "back", basename(cwd));
486
+ mkdirSync(dirname(back), { recursive: true });
487
+ await downloadTree({ openshell, env, sandbox, remote: workdir, local: back, timeoutMs: UPLOAD_TIMEOUT_MS, errorPrefix: "", stdoutFallback: true });
488
+ if (!existsSync(join(back, ".git")))
489
+ throw new Error("the downloaded workspace has no git repository");
490
+ await commitUncommitted({ git, repo: back, message: `chore(sandbox): uncommitted work from schedule ${name}` });
491
+ const ahead = await commitsAhead({ git, repo: back, base });
492
+ if (!ahead) {
493
+ log("no new commits");
494
+ return "";
495
+ }
496
+ const stamp = new Date(now).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
497
+ const target = `sandbox/${name}-${stamp}`;
498
+ await git(cwd, ["fetch", "--quiet", back, `HEAD:refs/heads/${target}`]);
499
+ log(`${ahead} commit(s) on branch ${target} in ${cwd}`);
500
+ return target;
501
+ }