@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,937 @@
1
+ // Cursor adapter: one `<cursor cli> acp` child per owned session over stdio JSON-RPC, optionally inside an OpenShell sandbox.
2
+ import { spawn } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import { homedir, tmpdir } from "node:os";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { EventType } from "@ag-ui/core";
9
+ import { answerOptionId, grantKey, permissionQuestion, selectPermissionOptionId } from "../../lib/acp/permission.js";
10
+ import { flattenSelectChoices, modelConfigOption, sessionModels } from "../../lib/acp/sessionConfig.js";
11
+ import { autoDefaults, sessionLabel } from "../../lib/config.js";
12
+ import { exportSpans, otlpEndpoint, runRecorder } from "../../lib/cursor-trace.js";
13
+ import { cursorBinary } from "../../lib/harness.js";
14
+ import { findExecutable } from "../../lib/sessions/scope.js";
15
+ import { argv, LAUNCH_BINARY } from "../../lib/harness.js";
16
+ import { APPROVAL_REQUESTED, APPROVAL_RESOLVED, permissionSettings } from "../contract.js";
17
+ import { builderPolicy } from "../../lib/builder.js";
18
+ import { MANAGED_ENV, subagentDenial } from "../../lib/subagent-guard.js";
19
+ import { destroyOwnedSandboxes, ensureSandbox as ensureSandboxIn, execArgv as sandboxExecArgv, runTool, refreshSandboxPolicies, sandboxLabels, sandboxName as sandboxNameFor, teamSandboxName, uploadFile, uploadLogins, uploadSecret, uploadTree, } from "../../lib/sandbox.js";
20
+ import { TOOL_ENV, uploadToolchain } from "../../lib/sandbox-tools.js";
21
+ import { sandboxBus, sandboxDefaults } from "../../lib/builder/policy.js";
22
+ import { sandboxBusMcpServer, uploadAppTree } from "../../lib/sandbox-app.js";
23
+ // The landing lives in lib/sandbox-claims.ts; re-exported so imports of cursor.mjs keep working.
24
+ import { makeExec, syncBackWork, syncSandboxBack, uploadClone } from "../../lib/sandbox-claims.js";
25
+ export { syncSandboxBack, uploadClone };
26
+ // ACP protocolVersion 1 and the method names come from the ACP spec; `agent acp` answered `initialize`
27
+ // with protocolVersion 1 on 2026-11-22 (docs/owned-sessions-contract.md, Cursor adapter).
28
+ const PROTOCOL_VERSION = 1;
29
+ const SETUP_TIMEOUT_MS = 30_000;
30
+ const TOOL_TIMEOUT_MS = 60_000;
31
+ const CLIENT = { name: "temmo-runner", version: "0" };
32
+ const OWNED = { TEMMO_OWNED: "cursor" };
33
+ // Where a sandbox session's worktree lives inside the sandbox and the home its CLI runs with.
34
+ const SANDBOX_ROOT = "/sandbox";
35
+ const SANDBOX_HOME = "/sandbox/home";
36
+ const SANDBOX_BIN = "/sandbox/bin";
37
+ // The host bus, as the runner's sandbox stage publishes it (BUS_URL, lib/builder/policy.ts). The file is the only copy of the bearer token.
38
+ const TOKEN_IN = `${SANDBOX_HOME}/.config/temmo/ntfy-token`;
39
+ // The name the CLI is launched by inside a sandbox, whatever it is called on the host.
40
+ const SANDBOX_LAUNCHER = LAUNCH_BINARY.cursor;
41
+ // The CLI marks itself non-dumpable unless this is set; OpenShell then cannot read its /proc/<pid>/exe and denies its sockets (lib/builder.ts).
42
+ const SANDBOX_CURSOR_ENV = { CURSOR_AGENT_ALLOW_PROCESS_INSPECTION: "1" };
43
+ // How long shutdown waits for killed CLIs to exit before it waits on their sandbox releases.
44
+ const SHUTDOWN_EXIT_WAIT_MS = 5_000;
45
+ // The sandbox has no temmo hook script, so a managed child's subagentStart hook is a shell line gated on its env.
46
+ // Cursor has no switch that turns native subagents off (docs/spawn-agent-spec.md, A3); the sandbox is shared per project.
47
+ const quoteSh = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
48
+ const SANDBOX_HOOKS = `${JSON.stringify({ version: 1, hooks: { subagentStart: [{
49
+ command: `cat >/dev/null; if [ "$${MANAGED_ENV}" = 1 ]; then printf '%s\\n' ${quoteSh(JSON.stringify(subagentDenial("cursor")))}; else printf '{}\\n'; fi`, timeout: 10,
50
+ }] } }, null, 2)}\n`;
51
+ // The temmo bus MCP server a host session gets in session/new and load; a sandbox has no node or app tree to run it.
52
+ const BUS_MCP_SCRIPT = fileURLToPath(new URL("../../scripts/temmo-mcp.mjs", import.meta.url));
53
+ // Env the bus MCP server needs to find its config and project; secrets stay out of the ACP request.
54
+ const BUS_MCP_ENV = /^(HOME|PATH|XDG_[A-Z_]+|TEMMO_[A-Z0-9_]+)$/;
55
+ const SECRET_ENV = /TOKEN|SECRET|PASSWORD|KEY/;
56
+ /** The OpenShell sandbox name for a project: ai-collab-<project>, lowercase, at most 40 characters of project. */
57
+ export const sandboxName = (project) => sandboxNameFor(project);
58
+ /** Argv of the ACP server: `--force` when the mode asks for it, `--model` when one is named, then the `acp` subcommand. */
59
+ export function acpArgs({ force = false, model } = {}) {
60
+ return argv("cursor", "acp", { force, model })[1];
61
+ }
62
+ /** Configured MCP servers in the ACP McpServer shape: an ACP array as given, or a Cursor mcp.json `mcpServers` record converted. */
63
+ export function acpMcpServers(configured) {
64
+ if (Array.isArray(configured))
65
+ return configured.filter((s) => s && typeof s.name === "string" && s.name);
66
+ if (!configured || typeof configured !== "object")
67
+ return [];
68
+ const pairs = (record) => Object.entries(record ?? {}).map(([name, value]) => ({ name, value: String(value) }));
69
+ return Object.entries(configured).map(([name, s]) => {
70
+ if (typeof s?.url === "string")
71
+ return { type: s.type === "sse" ? "sse" : "http", name, url: s.url, headers: pairs(s.headers) };
72
+ if (typeof s?.command === "string")
73
+ return { name, command: s.command, args: Array.isArray(s.args) ? s.args.map(String) : [], env: pairs(s.env) };
74
+ return null;
75
+ }).filter(Boolean);
76
+ }
77
+ // The bus MCP server's env: HOME, PATH, XDG and TEMMO variables without secrets, then its peer and project.
78
+ function busMcpEnv(env, project) {
79
+ const vars = Object.entries(env).filter(([name]) => BUS_MCP_ENV.test(name) && !SECRET_ENV.test(name) && name !== "TEMMO_OWNED");
80
+ const fixed = { TEMMO_PEER: "cursor", ...(project ? { TEMMO_PROJECT: project } : {}) };
81
+ return [...vars.filter(([name]) => !Object.hasOwn(fixed, name)), ...Object.entries(fixed)].map(([name, value]) => ({ name, value: String(value) }));
82
+ }
83
+ /**
84
+ * The mcpServers of session/new, load and resume: the bus server on the host (a configured server of the same name
85
+ * replaces it), then the configured ones; http and sse servers only when initialize advertised that transport.
86
+ */
87
+ export function sessionMcpServers({ place, project, env = {}, configured, mcpCapabilities = {} } = {}) {
88
+ const extra = acpMcpServers(configured);
89
+ // A sandbox session runs the copy prepareSandbox staged under /sandbox/tools; a host session runs this checkout's.
90
+ const bus = extra.some((s) => s.name === "temmo") ? []
91
+ : place === "openshell" ? [sandboxBusServer(project)]
92
+ : [{ name: "temmo", command: process.execPath, args: [BUS_MCP_SCRIPT, "cursor"], env: busMcpEnv(env, project) }];
93
+ return [...bus, ...extra].filter((s) => (s.type === "http" ? mcpCapabilities.http === true : s.type === "sse" ? mcpCapabilities.sse === true : true));
94
+ }
95
+ // The bus MCP server inside a sandbox, in the ACP shape (env as name/value pairs).
96
+ function sandboxBusServer(project) {
97
+ const server = sandboxBusMcpServer({ project, peer: "cursor" });
98
+ return { name: "temmo", command: server.command, args: server.args, env: Object.entries(server.env).map(([name, value]) => ({ name, value: String(value) })) };
99
+ }
100
+ /**
101
+ * Argv that runs the Cursor CLI inside a sandbox: `openshell sandbox exec` with the session's workdir, the owned
102
+ * marker, and the CLI's home (so it reads the auth file written there) . The CLI name defaults to `cursor-agent`,
103
+ * the name inside the sandbox image, not the host's.
104
+ */
105
+ export function execArgv({ openshell, sandbox, args, binary = LAUNCH_BINARY.cursor, workdir, env = {} }) {
106
+ return sandboxExecArgv({
107
+ openshell, sandbox, workdir, command: [binary, ...args],
108
+ env: { TEMMO_OWNED: "cursor", ...env },
109
+ });
110
+ }
111
+ export { runTool };
112
+ function forceOf(permission, place) {
113
+ const force = permission?.force === true;
114
+ if (force && place !== "openshell")
115
+ throw new Error("cursor full-access runs only in openshell");
116
+ return force;
117
+ }
118
+ // Bytes of the child's stderr kept for the error that ends the connection; enough for a provider's limit message.
119
+ const STDERR_TAIL_MAX = 4000;
120
+ /** An ACP JSON-RPC error as an Error that keeps the envelope's code and data (a limit or auth error carries its detail there). */
121
+ function acpError(error) {
122
+ const out = new Error(error.message ?? "ACP error");
123
+ // UNVERIFIED: which codes cursor-agent uses for a usage limit; the envelope is kept whole so a classifier can read it.
124
+ if (error.code !== undefined)
125
+ out.code = error.code;
126
+ if (error.data !== undefined)
127
+ out.data = error.data;
128
+ return out;
129
+ }
130
+ /** The error for a child that exited: the exit status plus the tail of its stderr, where a startup refusal lands. */
131
+ function exitError(code, signal, stderrTail) {
132
+ const out = new Error(`cursor-agent acp exited (${signal ?? `code ${code}`})`);
133
+ if (code !== null && code !== undefined)
134
+ out.code = code;
135
+ if (signal)
136
+ out.signal = signal;
137
+ const tail = String(stderrTail ?? "").trim();
138
+ if (tail)
139
+ out.stderr = tail;
140
+ return out;
141
+ }
142
+ /** Everything an error carries, as one text for the limit classifier: its message, code, data and stderr tail. */
143
+ export function errorText(error) {
144
+ const parts = [error?.message ?? String(error ?? "")];
145
+ if (error?.code !== undefined)
146
+ parts.push(typeof error.code === "object" ? JSON.stringify(error.code) : String(error.code));
147
+ if (error?.data !== undefined)
148
+ parts.push(typeof error.data === "string" ? error.data : JSON.stringify(error.data));
149
+ if (error?.stderr)
150
+ parts.push(String(error.stderr));
151
+ return parts.filter(Boolean).join("\n");
152
+ }
153
+ // One ACP connection: newline-delimited JSON-RPC 2.0 over the child's stdio.
154
+ function connect(argv, { env, cwd, log, onRequest, onNotify }) {
155
+ const child = spawn(argv[0], argv.slice(1), { env, cwd, shell: false, stdio: ["pipe", "pipe", "pipe"] });
156
+ const pending = new Map();
157
+ let nextId = 1;
158
+ let buffer = "";
159
+ let dead = null;
160
+ // The last lines the child wrote to stderr, kept for the error that ends the connection (limit text lives here).
161
+ let stderrTail = "";
162
+ const keepStderr = (chunk) => { stderrTail = (stderrTail + chunk).slice(-STDERR_TAIL_MAX); };
163
+ let settleExit;
164
+ const exited = new Promise((resolve) => { settleExit = resolve; });
165
+ // A sandbox's `exec` client is not the process holding the pipes once it is killed: the remote command inherits
166
+ // them, so they are destroyed here or the runner never exits after a close.
167
+ const destroyStreams = () => {
168
+ for (const stream of [child.stdin, child.stdout, child.stderr])
169
+ if (!stream.destroyed)
170
+ stream.destroy();
171
+ };
172
+ child.stdin.on("error", () => { });
173
+ child.stdout.setEncoding("utf8");
174
+ child.stderr.setEncoding("utf8");
175
+ child.stdout.on("data", (chunk) => {
176
+ buffer += chunk;
177
+ for (let i = buffer.indexOf("\n"); i >= 0; i = buffer.indexOf("\n")) {
178
+ const line = buffer.slice(0, i);
179
+ buffer = buffer.slice(i + 1);
180
+ if (line.trim())
181
+ dispatch(line);
182
+ }
183
+ });
184
+ child.stderr.on("data", (chunk) => { keepStderr(chunk); for (const line of chunk.split("\n"))
185
+ if (line.trim())
186
+ log(line.trimEnd()); });
187
+ child.on("error", (error) => fail(error));
188
+ child.on("exit", (code, signal) => { fail(exitError(code, signal, stderrTail)); settleExit(); });
189
+ function send(message) {
190
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
191
+ }
192
+ function dispatch(line) {
193
+ let message;
194
+ try {
195
+ message = JSON.parse(line);
196
+ }
197
+ catch {
198
+ log(`ignored non-JSON line from cursor-agent: ${line.slice(0, 200)}`);
199
+ return;
200
+ }
201
+ if (message.method !== undefined && message.id !== undefined)
202
+ return onRequest(message);
203
+ if (message.method !== undefined)
204
+ return onNotify(message.method, message.params ?? {});
205
+ const waiter = pending.get(message.id);
206
+ if (!waiter)
207
+ return;
208
+ pending.delete(message.id);
209
+ clearTimeout(waiter.timer);
210
+ if (message.error)
211
+ waiter.reject(acpError(message.error));
212
+ else
213
+ waiter.resolve(message.result);
214
+ }
215
+ function fail(error) {
216
+ if (dead)
217
+ return;
218
+ dead = error;
219
+ for (const waiter of pending.values()) {
220
+ clearTimeout(waiter.timer);
221
+ waiter.reject(error);
222
+ }
223
+ pending.clear();
224
+ }
225
+ return {
226
+ pid: child.pid,
227
+ get dead() { return dead; },
228
+ request(method, params, timeoutMs) {
229
+ if (dead)
230
+ return Promise.reject(dead);
231
+ const id = nextId++;
232
+ return new Promise((resolve, reject) => {
233
+ const timer = timeoutMs ? setTimeout(() => { pending.delete(id); reject(new Error(`${method} timed out`)); }, timeoutMs) : null;
234
+ pending.set(id, { resolve, reject, timer });
235
+ send({ id, method, params });
236
+ });
237
+ },
238
+ notify: (method, params) => send({ method, params }),
239
+ reply: (id, result) => send({ id, result }),
240
+ replyError: (id, code, message) => send({ id, error: { code, message } }),
241
+ kill: () => { child.kill("SIGTERM"); destroyStreams(); },
242
+ closed: exited,
243
+ child,
244
+ };
245
+ }
246
+ /**
247
+ * Uploads what a sandbox session needs and returns the exec env and workdir.
248
+ *
249
+ * Verified flow (docs/owned-sessions-contract.md, OpenShell): a sandbox gets no host bind mount, so the worktree
250
+ * is uploaded before the run and downloaded after it; the CLI tree is uploaded once under SANDBOX_ROOT; auth is the
251
+ * host's `$XDG_CONFIG_HOME/cursor/auth.json` (or `~/.config/cursor/auth.json`), written to a 0600 temp file and
252
+ * uploaded, never passed in argv or --env, so it never reaches a log. Missing auth is not fatal: the CLI asks to log in.
253
+ * The bus token is uploaded the same way when the host has one, and defaults.json points tokenFile at that path,
254
+ * so send_to_all, reply_to_operator and ask_question can publish. A team worktree reuses the clone and still
255
+ * gets the token: the marker skips only the worktree upload.
256
+ */
257
+ export async function prepareSandbox({ openshell, env, sandbox, cwd, home = homedir(), project = "", cursorTree, launcher = SANDBOX_LAUNCHER, staged = new Set(), reuseWorktree = false, managed = false, log = () => { } }) {
258
+ const remoteWork = `${SANDBOX_ROOT}/work`;
259
+ const workdir = `${remoteWork}/${basename(cwd)}`;
260
+ const marker = `${SANDBOX_ROOT}/.team-worktree-ready`;
261
+ const exec = (command) => runTool(openshell, sandboxExecArgv({ openshell, sandbox, command }).slice(1), { env });
262
+ const ready = reuseWorktree && (await exec(["test", "-f", marker])).code === 0;
263
+ if (!ready) {
264
+ if (existsSync(join(cwd, ".git")))
265
+ await uploadClone({ openshell, env, sandbox, cwd, remote: remoteWork });
266
+ else
267
+ await uploadTree({ openshell, env, sandbox, local: cwd, remote: remoteWork });
268
+ if (reuseWorktree && (await exec(["touch", marker])).code !== 0)
269
+ throw new Error("Could not mark team worktree ready");
270
+ }
271
+ await uploadToolchain({ openshell, env, sandbox, label: "cursor", log });
272
+ // The app scripts the sandbox's bus MCP server runs; stageNtfy below stages the bus config and token.
273
+ await uploadAppTree({ openshell, env, sandbox });
274
+ const execEnv = { ...TOOL_ENV, HOME: SANDBOX_HOME, XDG_CONFIG_HOME: `${SANDBOX_HOME}/.config` };
275
+ if (cursorTree) {
276
+ // The host install tree is about 500 MB, so it is uploaded once per sandbox and reused after that; the
277
+ // bin/ symlink is one small upload and always replaces the old target.
278
+ if (!staged.has(sandbox)) {
279
+ await uploadTree({ openshell, env, sandbox, local: cursorTree, remote: `${SANDBOX_ROOT}/agent` });
280
+ staged.add(sandbox);
281
+ }
282
+ const dir = mkdtempSync(join(tmpdir(), "temmo-sandbox-bin-"));
283
+ try {
284
+ mkdirSync(join(dir, "bin"));
285
+ symlinkSync(join(SANDBOX_ROOT, "agent", basename(cursorTree), launcher), join(dir, "bin", SANDBOX_LAUNCHER));
286
+ // Its own directory (/sandbox/bin), so a second session's upload never lands on the first's.
287
+ await uploadTree({ openshell, env, sandbox, local: join(dir, "bin"), remote: SANDBOX_ROOT, gitIgnore: false });
288
+ }
289
+ finally {
290
+ rmSync(dir, { recursive: true, force: true });
291
+ }
292
+ execEnv.PATH = `${SANDBOX_BIN}:${TOOL_ENV.PATH}`;
293
+ }
294
+ else {
295
+ // Nothing to upload: the binary must already be on the sandbox's own PATH (an image that ships it).
296
+ log(`cursor: no CLI install tree found for ${launcher}; the sandbox's own PATH must have it`);
297
+ }
298
+ const authPath = [join(home, ".config", "cursor", "auth.json"), join(home, ".cursor", "auth.json")].find((p) => existsSync(p));
299
+ if (authPath) {
300
+ await uploadAuth({ openshell, env, sandbox, authPath, log });
301
+ }
302
+ else {
303
+ log("cursor: no host auth.json found; the sandbox CLI will ask to log in");
304
+ }
305
+ // Claude and Codex logins too, as builders get them (operator decision 2026-11-23).
306
+ await uploadLogins({ openshell, env, sandbox, home, remoteHome: SANDBOX_HOME, log });
307
+ await stageNtfy({ openshell, env, sandbox, project, workdir, log });
308
+ if (managed) {
309
+ await stageHooks({ openshell, env, sandbox });
310
+ execEnv[MANAGED_ENV] = "1";
311
+ }
312
+ return { workdir, env: execEnv };
313
+ }
314
+ // Writes the user-level hooks.json the sandbox CLI reads from $HOME/.cursor; a failure fails the start, so no child runs unblocked.
315
+ async function stageHooks({ openshell, env, sandbox }) {
316
+ const dir = mkdtempSync(join(tmpdir(), "temmo-sandbox-hooks-"));
317
+ try {
318
+ writeFileSync(join(dir, "hooks.json"), SANDBOX_HOOKS);
319
+ await uploadFile({ openshell, env, sandbox, local: join(dir, "hooks.json"), remoteDir: `${SANDBOX_HOME}/.cursor` });
320
+ }
321
+ finally {
322
+ rmSync(dir, { recursive: true, force: true });
323
+ }
324
+ }
325
+ // The host's bus token file from defaults.json, or "" when none is configured.
326
+ function hostTokenFile(env) {
327
+ const file = autoDefaults(env)?.tokenFile;
328
+ return typeof file === "string" && existsSync(file) ? file : "";
329
+ }
330
+ // Uploads the bearer token and points the sandbox MCP at that file. The token stays out of argv, env and logs.
331
+ async function stageNtfy({ openshell, env, sandbox, project, workdir, log }) {
332
+ const token = hostTokenFile(env);
333
+ if (!token)
334
+ return;
335
+ const dir = mkdtempSync(join(tmpdir(), "temmo-sandbox-ntfy-"));
336
+ try {
337
+ const ntfy = sandboxBus(TOKEN_IN);
338
+ const config = join(dir, "temmo");
339
+ mkdirSync(config, { recursive: true });
340
+ writeFileSync(join(config, "defaults.json"), sandboxDefaults({ tokenFile: TOKEN_IN }), { mode: 0o600 });
341
+ if (project && workdir)
342
+ writeFileSync(join(config, "projects.json"), `${JSON.stringify([{ root: workdir, project, ...ntfy }], null, 2)}\n`, { mode: 0o600 });
343
+ // The directory upload replaces temmo/, so the token file goes in after it and is not wiped.
344
+ await uploadTree({ openshell, env, sandbox, local: config, remote: dirname(dirname(TOKEN_IN)), gitIgnore: false });
345
+ await uploadSecret({ openshell, env, sandbox, file: token, remoteDir: dirname(TOKEN_IN), name: basename(TOKEN_IN) });
346
+ }
347
+ catch (error) {
348
+ log(`cursor: could not stage the bus token; sends from the sandbox will be refused (${error.message.split("\n")[0]})`);
349
+ }
350
+ finally {
351
+ rmSync(dir, { recursive: true, force: true });
352
+ }
353
+ }
354
+ // Copies the auth file in through a 0600 temp file (a single-file upload keeps the mode), then deletes the temp file.
355
+ async function uploadAuth({ openshell, env, sandbox, authPath, log }) {
356
+ const dir = mkdtempSync(join(tmpdir(), "temmo-sandbox-auth-"));
357
+ const copy = join(dir, "auth.json");
358
+ try {
359
+ let auth = "";
360
+ try {
361
+ auth = readFileSync(authPath, "utf8");
362
+ }
363
+ catch {
364
+ auth = "";
365
+ }
366
+ if (!auth) {
367
+ log("cursor: the host auth.json is unreadable; the sandbox CLI will ask to log in");
368
+ return;
369
+ }
370
+ writeFileSync(copy, auth, { mode: 0o600 });
371
+ await uploadFile({ openshell, env, sandbox, local: copy, remoteDir: `${SANDBOX_HOME}/.config/cursor` });
372
+ }
373
+ catch (error) {
374
+ log(`cursor: could not stage the sandbox auth file; the CLI will ask to log in (${error.message})`);
375
+ }
376
+ finally {
377
+ rmSync(dir, { recursive: true, force: true });
378
+ }
379
+ }
380
+ /** The network policy a Cursor sandbox gets when TEMMO_OPENSHELL_POLICY names none: Cursor's API and the host's bus, for the uploaded CLI's binaries. */
381
+ export function cursorPolicy(cursorTree) {
382
+ const inTree = `${SANDBOX_ROOT}/agent/${basename(cursorTree)}`;
383
+ let files = [];
384
+ try {
385
+ files = readdirSync(cursorTree).filter((f) => { const st = statSync(join(cursorTree, f)); return st.isFile() && (st.mode & 0o111) !== 0; });
386
+ }
387
+ catch { /* no tree: the policy names no binary */ }
388
+ return builderPolicy({ harness: "cursor", binaries: files.map((f) => `${inTree}/${f}`), packages: true });
389
+ }
390
+ // Writes cursorPolicy to a private file once per adapter and returns its path; "" without a CLI tree.
391
+ function writePolicy(cursorTree) {
392
+ if (!cursorTree)
393
+ return "";
394
+ const dir = mkdtempSync(join(tmpdir(), "temmo-cursor-policy-"));
395
+ const file = join(dir, "policy.yaml");
396
+ writeFileSync(file, `${JSON.stringify(cursorPolicy(cursorTree), null, 2)}\n`, { mode: 0o600 });
397
+ return file;
398
+ }
399
+ /** Maps AG-UI output for one harness session: a run, its text and tool calls, and its approval cards. */
400
+ export default function cursorAdapter(config = {}) {
401
+ const envOf = config.env ?? {};
402
+ const openshellBin = envOf.TEMMO_OPENSHELL_BIN || "openshell";
403
+ // Both resolve against the caller's PATH: the service may start with a bare one.
404
+ const lookupPath = config.path ?? envOf.PATH ?? process.env.PATH ?? "";
405
+ const cursorBin = envOf.TEMMO_CURSOR_BIN || cursorBinary(lookupPath);
406
+ // The CLI tree uploaded into a sandbox: the version directory that holds the host binary's real path.
407
+ const cursorTree = envOf.TEMMO_CURSOR_TREE || treeOf(cursorBin, lookupPath);
408
+ let policyPath = envOf.TEMMO_OPENSHELL_POLICY || "";
409
+ // writePolicy's temp dir ("" when the env names the policy), removed when its last session releases or at shutdown.
410
+ let policyDir = "";
411
+ let policyUsers = 0;
412
+ const connections = new Set();
413
+ // Set by suspend() when the runner stops: no session releases its sandbox from then on.
414
+ let suspended = false;
415
+ // Sandbox releases in flight, including those a dying CLI starts; shutdown waits for them.
416
+ const releasing = new Set();
417
+ // One sandbox per project, reused: created by the first session and deleted when the last one closes.
418
+ const sandboxes = new Map();
419
+ // Sessions restored after a runner restart, by address. Each holds a claim on its sandbox until it resumes or closes.
420
+ const restored = new Map();
421
+ // Sandboxes whose (large) CLI tree is already uploaded; it is only re-uploaded into a new sandbox.
422
+ const stagedTrees = new Set();
423
+ // Starts the ACP child (inside the sandbox for openshell) and negotiates initialize; returns the session state.
424
+ async function attach(spec, ctx) {
425
+ const force = forceOf(spec.permission, spec.place);
426
+ const cursorArgs = acpArgs({ force, model: spec.model });
427
+ const env = { ...spec.env, ...OWNED };
428
+ let argv;
429
+ // A claimed sandbox (and the session that holds it) is released again on any failure below.
430
+ let sandbox = null;
431
+ // A restored session already holds its claim on the sandbox: resuming takes it over instead of counting a second one.
432
+ const held = spec.address ? restored.get(spec.address) : undefined;
433
+ if (held)
434
+ restored.delete(spec.address);
435
+ const session = {
436
+ sessionId: null, run: null, approvals: new Map(), tools: new Map(), closed: false, ctx, sandbox: null, env, cwd: spec.cwd, model: spec.model, project: spec.project, owned: ownerOf(spec),
437
+ // Grant keys (lib/acp/permission.ts grantKey) the operator allowed for the rest of this session; the runner answers those itself.
438
+ grants: new Set(), loading: false, configOptions: null, modelState: null, init: null, place: spec.place, mcpConfigured: spec.mcpServers,
439
+ };
440
+ try {
441
+ if (spec.place === "openshell") {
442
+ // One sandbox per project, reused: created by the first session and deleted when the last one closes.
443
+ const name = sandboxOf(spec);
444
+ if (!policyPath) {
445
+ policyPath = writePolicy(cursorTree);
446
+ policyDir = policyPath && dirname(policyPath);
447
+ }
448
+ if (policyDir) {
449
+ policyUsers++;
450
+ session.policyDir = policyDir;
451
+ }
452
+ sandbox = await ensureSandboxIn({ openshell: openshellBin, env, name, policy: policyPath, labels: sandboxLabels({ project: spec.project, ...ownerOf(spec) }) });
453
+ if (!held)
454
+ claim(sandbox, spec.cwd);
455
+ session.sandbox = sandbox;
456
+ const prepared = await prepareSandbox({
457
+ openshell: openshellBin, env, sandbox, cwd: spec.cwd, home: spec.home ?? spec.env?.HOME, project: spec.project, cursorTree,
458
+ staged: stagedTrees, reuseWorktree: Boolean(spec.patternRun), managed: spec.managed === true, log: (l) => ctx.log(l),
459
+ });
460
+ argv = execArgv({ openshell: openshellBin, sandbox, args: cursorArgs, workdir: prepared.workdir, env: { ...prepared.env, ...SANDBOX_CURSOR_ENV } });
461
+ // The CLI runs in the sandbox, so it must be told the sandbox path, not the host's.
462
+ session.remoteCwd = prepared.workdir;
463
+ }
464
+ else {
465
+ argv = [cursorBin, ...cursorArgs];
466
+ }
467
+ }
468
+ catch (error) {
469
+ await closeSandbox(session);
470
+ throw error;
471
+ }
472
+ const conn = connect(argv, {
473
+ env,
474
+ cwd: spec.place === "openshell" ? undefined : spec.cwd,
475
+ log: (line) => ctx.log(line),
476
+ onRequest: (message) => handleRequest(session, conn, message),
477
+ onNotify: (method, params) => handleNotify(session, method, params),
478
+ });
479
+ connections.add(conn);
480
+ ctx.signal.addEventListener("abort", () => conn.kill(), { once: true });
481
+ // A CLI that dies on its own (crash, sandbox delete) gives up its claim too, so no sandbox is left behind.
482
+ conn.closed.then(() => { if (session.sandbox)
483
+ void closeSandbox(session); });
484
+ try {
485
+ const init = await conn.request("initialize", {
486
+ protocolVersion: PROTOCOL_VERSION,
487
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
488
+ clientInfo: CLIENT,
489
+ }, SETUP_TIMEOUT_MS);
490
+ session.init = init ?? {};
491
+ if (spec.requireLoad && !resumeMethod(session))
492
+ throw new Error("the Cursor CLI advertises neither session/resume nor loadSession; the session cannot resume");
493
+ return { conn, session };
494
+ }
495
+ catch (error) {
496
+ // The CLI may have died before initialize answered; closing the connection is what ends a sandbox run.
497
+ conn.kill();
498
+ connections.delete(conn);
499
+ await closeSandbox(session);
500
+ throw error;
501
+ }
502
+ }
503
+ // session/resume when the agent advertises it (no replay), else session/load; null when it offers neither.
504
+ function resumeMethod(session) {
505
+ const caps = session.init?.agentCapabilities ?? {};
506
+ if (caps.sessionCapabilities?.resume != null)
507
+ return "session/resume";
508
+ return caps.loadSession === true ? "session/load" : null;
509
+ }
510
+ // The mcpServers this session sends on every session/new, load and resume.
511
+ const mcpServersOf = (session) => sessionMcpServers({
512
+ place: session.place, project: session.project, env: session.env, configured: session.mcpConfigured, mcpCapabilities: session.init?.agentCapabilities?.mcpCapabilities,
513
+ });
514
+ // Keeps what a session/new, load, resume or set_config_option response says about config options and models.
515
+ function adoptConfig(session, response) {
516
+ if (Array.isArray(response?.configOptions))
517
+ session.configOptions = response.configOptions;
518
+ if (response?.models && typeof response.models === "object")
519
+ session.modelState = response.models;
520
+ session.model ||= sessionModels({ configOptions: session.configOptions, models: session.modelState }).current;
521
+ }
522
+ function handleRequest(session, conn, message) {
523
+ if (message.method === "session/request_permission")
524
+ return askPermission(session, conn, message);
525
+ conn.replyError(message.id, -32601, `temmo does not serve ${message.method}`);
526
+ }
527
+ function handleNotify(session, method, params) {
528
+ if (method !== "session/update")
529
+ return;
530
+ // session/load replays the whole conversation as session/update before it answers. The runner already holds that
531
+ // history (durable log and bus), so the replay is dropped on purpose; the session is idle once load answers.
532
+ if (session.loading)
533
+ return;
534
+ const update = params.update ?? {};
535
+ if (update.sessionUpdate === "config_option_update")
536
+ return adoptConfig(session, update);
537
+ if (!session.run)
538
+ return;
539
+ const run = session.run;
540
+ switch (update.sessionUpdate) {
541
+ case "agent_message_chunk":
542
+ if (update.content?.type === "text" && typeof update.content.text === "string")
543
+ run.text += update.content.text;
544
+ return;
545
+ case "tool_call": {
546
+ if (typeof update.toolCallId !== "string")
547
+ return;
548
+ flushText(session, run);
549
+ const toolCallName = update.title || update.kind || "tool";
550
+ session.tools.set(update.toolCallId, toolCallName);
551
+ run.trace?.toolStart(update.toolCallId, toolCallName, update.rawInput);
552
+ session.ctx.emit({
553
+ type: EventType.TOOL_CALL_CHUNK, toolCallId: update.toolCallId, toolCallName,
554
+ delta: JSON.stringify(update.rawInput ?? {}, null, 2),
555
+ });
556
+ return;
557
+ }
558
+ case "tool_call_update": {
559
+ if (typeof update.toolCallId !== "string" || !["completed", "failed"].includes(update.status))
560
+ return;
561
+ const failed = update.status === "failed";
562
+ run.trace?.toolEnd(update.toolCallId, { name: session.tools.get(update.toolCallId), failed });
563
+ session.ctx.emit({
564
+ type: EventType.TOOL_CALL_RESULT, toolCallId: update.toolCallId, messageId: `${update.toolCallId}:result`, role: "tool",
565
+ content: resultText(update, failed),
566
+ metadata: { aiCollab: { toolCallName: session.tools.get(update.toolCallId) ?? "tool", failed } },
567
+ });
568
+ session.tools.delete(update.toolCallId);
569
+ return;
570
+ }
571
+ default:
572
+ return;
573
+ }
574
+ }
575
+ // A question-shaped request (Cursor's ask_question fallback) becomes a question card; a tool the operator allowed
576
+ // for the session is answered here; anything else becomes an approval card.
577
+ function askPermission(session, conn, message) {
578
+ const request = message.params ?? {};
579
+ const toolCall = request.toolCall ?? {};
580
+ const toolCallName = toolCall.title || toolCall.kind || "tool";
581
+ const question = permissionQuestion(request);
582
+ const key = grantKey(toolCall);
583
+ if (!question && session.grants.has(key)) {
584
+ const optionId = selectPermissionOptionId(request, "acceptForSession");
585
+ if (optionId) {
586
+ conn.reply(message.id, { outcome: { outcome: "selected", optionId } });
587
+ session.ctx.log(`cursor: allowed ${toolCallName} for this session (${key})`);
588
+ return;
589
+ }
590
+ }
591
+ const interruptId = randomUUID();
592
+ session.approvals.set(interruptId, { rpcId: message.id, conn, request, question, key });
593
+ if (question) {
594
+ session.ctx.emit({
595
+ type: EventType.CUSTOM, name: APPROVAL_REQUESTED,
596
+ value: { interruptId, reason: "question", toolCallId: toolCall.toolCallId, toolCallName: "AskQuestion", summary: question.question.question, questions: [question.question] },
597
+ });
598
+ return;
599
+ }
600
+ const input = toolCall.rawInput === undefined ? "" : `: ${JSON.stringify(toolCall.rawInput).slice(0, 1000)}`;
601
+ session.ctx.emit({
602
+ type: EventType.CUSTOM, name: APPROVAL_REQUESTED,
603
+ value: { interruptId, reason: "tool_approval", toolCallId: toolCall.toolCallId, toolCallName, summary: `${toolCallName}${input}` },
604
+ });
605
+ }
606
+ // The option a decision picks and its resolve reason: a question's chosen label (else its skip), or allow once,
607
+ // allow for the session (scope "session", remembered in session.grants), or reject once.
608
+ function chosenOption(session, approval, decision) {
609
+ const allow = decision.behavior === "allow";
610
+ if (approval.question) {
611
+ const picked = allow ? answerOptionId(approval.question, decision.answers) : undefined;
612
+ if (picked)
613
+ return { optionId: picked, reason: "answered" };
614
+ return { optionId: approval.question.skipOptionId ?? selectPermissionOptionId(approval.request, "decline"), reason: "denied" };
615
+ }
616
+ const always = allow && decision.scope === "session";
617
+ if (always)
618
+ session.grants.add(approval.key);
619
+ return { optionId: selectPermissionOptionId(approval.request, always ? "acceptForSession" : allow ? "accept" : "decline"), reason: allow ? "allowed" : "denied" };
620
+ }
621
+ function respond(session, interruptId, decision) {
622
+ const approval = session.approvals.get(interruptId);
623
+ if (!approval)
624
+ return;
625
+ session.approvals.delete(interruptId);
626
+ const { optionId, reason } = chosenOption(session, approval, decision);
627
+ if (optionId) {
628
+ approval.conn.reply(approval.rpcId, { outcome: { outcome: "selected", optionId } });
629
+ session.ctx.emit({ type: EventType.CUSTOM, name: APPROVAL_RESOLVED, value: { interruptId, status: "resolved", reason } });
630
+ }
631
+ else {
632
+ approval.conn.reply(approval.rpcId, { outcome: { outcome: "cancelled" } });
633
+ session.ctx.emit({ type: EventType.CUSTOM, name: APPROVAL_RESOLVED, value: { interruptId, status: "cancelled", reason: "cancelled" } });
634
+ }
635
+ }
636
+ function cancelApprovals(session) {
637
+ for (const interruptId of [...session.approvals.keys()])
638
+ respond(session, interruptId, { behavior: "deny" });
639
+ }
640
+ function flushText(session, run) {
641
+ if (!run.text)
642
+ return;
643
+ session.ctx.emit({ type: EventType.TEXT_MESSAGE_CHUNK, messageId: `${run.runId}:m${++run.messageSeq}`, role: "assistant", delta: run.text });
644
+ run.text = "";
645
+ }
646
+ // Each run's OTLP trace (lib/cursor-trace.ts): model and tool calls; ACP reports no token counts. Never awaited.
647
+ function exportRun(run, status) {
648
+ if (run.trace)
649
+ void exportSpans(run.trace.spans({ status }), { endpoint: otlpEndpoint({ ...process.env, ...envOf }) });
650
+ }
651
+ function endRun(session, run, outcome) {
652
+ exportRun(run, outcome === "success" ? "ok" : outcome);
653
+ flushText(session, run);
654
+ cancelApprovals(session);
655
+ session.run = null;
656
+ session.ctx.emit({ type: EventType.RUN_FINISHED, threadId: threadOf(session), runId: run.runId, outcome: { type: outcome } });
657
+ }
658
+ function failRun(session, run, error) {
659
+ exportRun(run, "error");
660
+ cancelApprovals(session);
661
+ session.run = null;
662
+ // The message carries the ACP code, data and stderr tail too, so a limit classifier sees everything the error had.
663
+ const text = errorText(error);
664
+ session.ctx.emit({ type: EventType.RUN_ERROR, message: text, metadata: { aiCollab: { runId: run.runId, ...(error?.code !== undefined ? { code: error.code } : {}) } } });
665
+ }
666
+ const threadOf = (session) => `cursor#${sessionLabel(session.sessionId)}`;
667
+ // The sandbox a session lives in: its team run's, else its project's. Deterministic, so a restart can name it again.
668
+ const sandboxOf = ({ project, patternRun }) => (patternRun ? teamSandboxName(project, patternRun) : sandboxName(project));
669
+ // The label kind and owner of a session's sandbox: its team run's, else its project's shared one.
670
+ const ownerOf = ({ patternRun, project }) => (patternRun ? { kind: "team", owner: patternRun } : { kind: "session", owner: project });
671
+ // Counts a session's claim on its project's sandbox; the sandbox is deleted when the last claim goes.
672
+ function claim(name, cwd) {
673
+ const known = sandboxes.get(name) ?? { cwd, refs: 0 };
674
+ known.refs += 1;
675
+ sandboxes.set(name, known);
676
+ }
677
+ // Copies a sandbox session's edits back to the host worktree, then drops the session's claim on the sandbox;
678
+ // the sandbox is deleted when no session holds it any more. Logs rather than throws, and runs at most once.
679
+ function closeSandbox(session) {
680
+ // A runner stop keeps the sandbox: the session resumes into it after the restart (restore re-claims it).
681
+ if (suspended)
682
+ return Promise.resolve(true);
683
+ if (!session.release) {
684
+ session.release = releaseSandbox(session);
685
+ releasing.add(session.release);
686
+ session.release.finally(() => releasing.delete(session.release)).catch(() => { });
687
+ }
688
+ return session.release;
689
+ }
690
+ // Removes the written policy dir; the next sandbox session writes a fresh one.
691
+ function dropPolicy() {
692
+ if (!policyDir)
693
+ return;
694
+ rmSync(policyDir, { recursive: true, force: true });
695
+ policyDir = "";
696
+ policyPath = "";
697
+ policyUsers = 0;
698
+ }
699
+ async function releaseSandbox(session) {
700
+ if (session.policyDir) {
701
+ if (session.policyDir === policyDir && --policyUsers === 0)
702
+ dropPolicy();
703
+ session.policyDir = "";
704
+ }
705
+ const name = session.sandbox;
706
+ session.sandbox = null;
707
+ const log = session.ctx.log;
708
+ if (!name)
709
+ return true;
710
+ if (session.cwd)
711
+ await syncSandboxBack({ openshell: openshellBin, env: session.env, sandbox: name, cwd: session.cwd, log });
712
+ const known = sandboxes.get(name);
713
+ if (known) {
714
+ known.refs = Math.max(0, (known.refs ?? 1) - 1);
715
+ if (known.refs > 0)
716
+ return true;
717
+ sandboxes.delete(name);
718
+ }
719
+ const out = await destroyOwnedSandboxes({ openshell: openshellBin, env: session.env, project: session.project, ...session.owned, legacyNames: [name], log });
720
+ stagedTrees.delete(name);
721
+ if (!out.ok)
722
+ log(`cursor: could not delete sandbox ${name}: ${out.detail}`);
723
+ return out.ok;
724
+ }
725
+ function makeHandle({ conn, session }) {
726
+ return {
727
+ get nativeId() { return session.sessionId; },
728
+ async send(input) {
729
+ if (session.run)
730
+ throw new Error("a cursor run is already running");
731
+ if (conn.dead)
732
+ throw conn.dead;
733
+ const runId = randomUUID();
734
+ const run = { runId, text: "", messageSeq: 0, trace: runRecorder({ address: threadOf(session), role: "runner", model: session.model }) };
735
+ session.run = run;
736
+ session.ctx.emit({
737
+ type: EventType.RUN_STARTED, threadId: threadOf(session), runId,
738
+ input: { threadId: threadOf(session), runId, tools: [], context: [], messages: [{ id: `${runId}:input`, role: "user", content: input.text }] },
739
+ });
740
+ conn.request("session/prompt", { sessionId: session.sessionId, prompt: [{ type: "text", text: input.text }] }, null)
741
+ .then((result) => endRun(session, run, result?.stopReason === "cancelled" ? "cancelled" : "success"), (error) => failRun(session, run, error));
742
+ return { runId };
743
+ },
744
+ async interrupt() {
745
+ if (!session.run)
746
+ return;
747
+ conn.notify("session/cancel", { sessionId: session.sessionId });
748
+ cancelApprovals(session);
749
+ },
750
+ async respond(interruptId, decision) { respond(session, interruptId, decision); },
751
+ // session/set_config_option on the model option the session advertised, else the unstable session/set_model (an agent
752
+ // without it answers -32601). cursor-agent 2026.11.22 implements both (its set_model calls set_config_option with configId "model"); not called live.
753
+ async setModel(modelId) {
754
+ if (conn.dead)
755
+ throw conn.dead;
756
+ if (session.run)
757
+ throw new Error("the Cursor session must be idle to switch models");
758
+ const option = modelConfigOption(session.configOptions);
759
+ if (option) {
760
+ const values = flattenSelectChoices(option.options).map((c) => c.value);
761
+ // Cursor takes bracket overrides on a listed model, as `<model>[effort=high]` (`agent --help`, --model).
762
+ if (values.length && !values.includes(modelId) && !values.includes(modelId.replace(/\[[^\]]*\]$/, "")))
763
+ throw new Error(`the Cursor session offers no model ${modelId}`);
764
+ adoptConfig(session, await conn.request("session/set_config_option", { sessionId: session.sessionId, configId: option.id, value: modelId }, TOOL_TIMEOUT_MS));
765
+ }
766
+ else {
767
+ await conn.request("session/set_model", { sessionId: session.sessionId, modelId }, TOOL_TIMEOUT_MS);
768
+ }
769
+ session.model = modelId;
770
+ },
771
+ // The session's models as the agent listed them in its last session response.
772
+ models() { return sessionModels({ configOptions: session.configOptions, models: session.modelState }); },
773
+ // Configured MCP servers outlive a runner restart, so resume sends the same list.
774
+ resumeData() { return session.mcpConfigured === undefined ? {} : { mcpServers: session.mcpConfigured }; },
775
+ // Copies the sandbox's commits to the host worktree for land finish; uncommitted work is refused so the two never diverge.
776
+ async syncBack(opts) {
777
+ if (!session.sandbox || !session.cwd)
778
+ throw new Error("this session has no sandbox to copy back");
779
+ return syncBackWork({
780
+ openshell: openshellBin, env: session.env, exec: makeExec(openshellBin, session.env), sandbox: session.sandbox, cwd: session.cwd,
781
+ log: session.ctx.log, landing: { label: "cursor", trailer: "Assisted-by: Cursor:cursor-agent" }, ...opts,
782
+ });
783
+ },
784
+ // Closing a sandbox session ends its CLI, copies its edits back, then deletes the sandbox.
785
+ async close() {
786
+ if (session.closed)
787
+ return;
788
+ session.closed = true;
789
+ if (session.run)
790
+ conn.notify("session/cancel", { sessionId: session.sessionId });
791
+ cancelApprovals(session);
792
+ conn.kill();
793
+ connections.delete(conn);
794
+ await closeSandbox(session);
795
+ },
796
+ };
797
+ }
798
+ return {
799
+ harness: "cursor",
800
+ capabilities: { steer: false, images: false, resume: "transcript", permissionModes: ["supervised", "full-access"], places: ["folder", "worktree", "openshell"] },
801
+ async available(env = {}) {
802
+ const out = await runTool(cursorBin, ["--version"], { env });
803
+ return out.code === 0 ? { ok: true, detail: out.stdout.trim() } : { ok: false, detail: out.stderr.trim() || `${cursorBin} exited ${out.code}` };
804
+ },
805
+ async open(options, ctx) {
806
+ const attached = await attach({ ...options, requireLoad: false }, ctx);
807
+ try {
808
+ const { session } = attached;
809
+ const created = await attached.conn.request("session/new", { cwd: session.remoteCwd ?? options.cwd, mcpServers: mcpServersOf(session) }, SETUP_TIMEOUT_MS);
810
+ session.sessionId = created.sessionId;
811
+ adoptConfig(session, created);
812
+ return makeHandle(attached);
813
+ }
814
+ catch (error) {
815
+ attached.conn.kill();
816
+ connections.delete(attached.conn);
817
+ await closeSandbox(attached.session);
818
+ throw error;
819
+ }
820
+ },
821
+ async resume(record, ctx, env) {
822
+ const settings = permissionSettings("cursor", record.permissionMode, record.place);
823
+ if (settings.error)
824
+ throw new Error(settings.error);
825
+ const attached = await attach({
826
+ project: record.project, cwd: record.cwd, place: record.place, permission: settings.settings,
827
+ model: record.model, patternRun: record.patternRun, address: record.address, env, requireLoad: true, managed: record.managed === true,
828
+ ...(record.resume?.mcpServers !== undefined ? { mcpServers: record.resume.mcpServers } : {}),
829
+ }, ctx);
830
+ try {
831
+ const { session } = attached;
832
+ session.sessionId = record.nativeId;
833
+ const method = resumeMethod(session);
834
+ session.loading = method === "session/load";
835
+ try {
836
+ adoptConfig(session, await attached.conn.request(method, { sessionId: record.nativeId, cwd: session.remoteCwd ?? record.cwd, mcpServers: mcpServersOf(session) }, TOOL_TIMEOUT_MS));
837
+ }
838
+ finally {
839
+ session.loading = false;
840
+ }
841
+ return makeHandle(attached);
842
+ }
843
+ catch (error) {
844
+ attached.conn.kill();
845
+ connections.delete(attached.conn);
846
+ await closeSandbox(attached.session);
847
+ throw error;
848
+ }
849
+ },
850
+ // UNVERIFIED: the `--list-models` output format; lines are read as "<id>" or "<id> - <label>".
851
+ async listModels(env = {}) {
852
+ const out = await runTool(cursorBin, ["--list-models"], { env, timeoutMs: TOOL_TIMEOUT_MS });
853
+ if (out.code !== 0)
854
+ throw new Error(`${cursorBin} --list-models failed: ${out.stderr.trim() || `exit ${out.code}`}`);
855
+ return out.stdout.split("\n").map((l) => l.trim()).filter((l) => l && !/^(available|tip|loading)/i.test(l))
856
+ .map((l) => { const [id, ...label] = l.split(/\s+-\s+/); return label.length ? { id, label: label.join(" - ") } : { id }; });
857
+ },
858
+ async listCommands() { return []; },
859
+ /**
860
+ * A session the runner restored after a restart has no handle and lost its in-memory sandbox claim. This names its
861
+ * sandbox again and rebuilds the claim, so that closing it (release) syncs its edits back and frees the sandbox.
862
+ */
863
+ restore(record, ctx, env = {}) {
864
+ if (record?.place !== "openshell" || record.status === "ended" || !record.address || restored.has(record.address))
865
+ return;
866
+ const name = sandboxOf(record);
867
+ claim(name, record.cwd);
868
+ restored.set(record.address, { sessionId: record.nativeId, sandbox: name, cwd: record.cwd, env: { ...env, ...OWNED }, ctx, approvals: new Map(), closed: false, project: record.project, owned: ownerOf(record) });
869
+ },
870
+ /** Ends a restored session that never resumed: copies its edits back and deletes the sandbox when no other session holds it. */
871
+ async release(record) {
872
+ const session = restored.get(record?.address);
873
+ if (!session)
874
+ return true;
875
+ restored.delete(record.address);
876
+ session.closed = true;
877
+ return closeSandbox(session);
878
+ },
879
+ /** A runner start replaces the policy on the project sandboxes that already exist, so a deploy reaches idle ones too. */
880
+ async reapplyPolicy(projects) {
881
+ const names = projects.map((project) => sandboxNameFor(project));
882
+ if (!names.length)
883
+ return;
884
+ if (!policyPath) {
885
+ policyPath = writePolicy(cursorTree);
886
+ policyDir = policyPath && dirname(policyPath);
887
+ }
888
+ if (!policyPath)
889
+ return;
890
+ await refreshSandboxPolicies({ openshell: openshellBin, env: envOf, names, policy: policyPath });
891
+ },
892
+ /** The runner is stopping: killed CLIs keep their sandboxes, so restored sessions resume without a rebuild. */
893
+ suspend() { suspended = true; },
894
+ async shutdown() {
895
+ const exits = [...connections].map((conn) => conn.closed);
896
+ for (const conn of connections)
897
+ conn.kill();
898
+ connections.clear();
899
+ // A killed CLI's exit starts its session's release; wait for the exits, then for every release.
900
+ let timer;
901
+ const cap = new Promise((resolve) => { timer = setTimeout(resolve, SHUTDOWN_EXIT_WAIT_MS); });
902
+ await Promise.race([Promise.allSettled(exits), cap]);
903
+ clearTimeout(timer);
904
+ await Promise.allSettled([...releasing]);
905
+ dropPolicy();
906
+ },
907
+ };
908
+ }
909
+ // The directory a Cursor CLI install lives in: `~/.local/bin/agent` is a symlink into
910
+ // `~/.local/share/cursor-agent/versions/<v>/`, which holds the CLI and its bundled node.
911
+ export function treeOf(bin, path = "") {
912
+ if (!bin)
913
+ return "";
914
+ const found = bin.includes("/") ? bin : findExecutable(bin, path);
915
+ if (!found)
916
+ return "";
917
+ let real = found;
918
+ try {
919
+ real = realpathSync(found);
920
+ }
921
+ catch {
922
+ return "";
923
+ }
924
+ const dir = dirname(real);
925
+ // Only the real layout counts: a lone binary (a test fake, a wrapper on PATH) has no tree to upload.
926
+ return existsSync(join(dir, "node")) ? dir : "";
927
+ }
928
+ // Text of a finished tool call: the text content blocks, else the raw output, else a status word.
929
+ function resultText(update, failed) {
930
+ const blocks = Array.isArray(update.content) ? update.content : [];
931
+ const text = blocks.map((b) => (b?.type === "content" && b.content?.type === "text" ? b.content.text : "")).join("");
932
+ if (text)
933
+ return text;
934
+ if (typeof update.rawOutput === "string" && update.rawOutput)
935
+ return update.rawOutput;
936
+ return failed ? "failed" : "completed";
937
+ }