@capybara-hq/kernel 0.1.0-rc.5 → 0.1.0-rc.50

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 (1397) hide show
  1. package/bootstrap.json +61 -19
  2. package/dist/admin/admin-agents.controller.d.ts +28 -0
  3. package/dist/admin/admin-agents.controller.js +79 -0
  4. package/dist/admin/admin-connectors.controller.d.ts +29 -0
  5. package/dist/admin/admin-connectors.controller.js +79 -0
  6. package/dist/admin/admin-items.schemas.d.ts +42 -0
  7. package/dist/admin/admin-items.schemas.js +48 -0
  8. package/dist/admin/admin.controller.d.ts +35 -94
  9. package/dist/admin/admin.controller.js +93 -83
  10. package/dist/admin/admin.module.d.ts +6 -1
  11. package/dist/admin/admin.module.js +62 -4
  12. package/dist/admin/admin.schemas.d.ts +97 -0
  13. package/dist/admin/admin.schemas.js +53 -0
  14. package/dist/admin/audit-log.service.d.ts +51 -0
  15. package/dist/admin/audit-log.service.js +78 -0
  16. package/dist/admin/audit.controller.d.ts +26 -0
  17. package/dist/admin/audit.controller.js +72 -0
  18. package/dist/admin/audit.schemas.d.ts +16 -0
  19. package/dist/admin/audit.schemas.js +37 -0
  20. package/dist/admin/extensions.controller.d.ts +10 -0
  21. package/dist/admin/extensions.controller.js +18 -0
  22. package/dist/admin/extensions.schemas.d.ts +7 -0
  23. package/dist/admin/extensions.schemas.js +10 -0
  24. package/dist/admin/health.service.d.ts +104 -0
  25. package/dist/admin/health.service.js +254 -0
  26. package/dist/admin/limit-defaults.d.ts +20 -0
  27. package/dist/admin/limit-defaults.js +10 -0
  28. package/dist/admin/org-network.controller.d.ts +30 -0
  29. package/dist/admin/org-network.controller.js +77 -0
  30. package/dist/admin/org-network.schemas.d.ts +16 -0
  31. package/dist/admin/org-network.schemas.js +27 -0
  32. package/dist/admin/org-network.service.d.ts +43 -0
  33. package/dist/admin/org-network.service.js +109 -0
  34. package/dist/admin/outbox-dead.controller.d.ts +21 -0
  35. package/dist/admin/outbox-dead.controller.js +65 -0
  36. package/dist/admin/outbox-dead.schemas.d.ts +24 -0
  37. package/dist/admin/outbox-dead.schemas.js +42 -0
  38. package/dist/admin/outbox-dead.service.d.ts +81 -0
  39. package/dist/admin/outbox-dead.service.js +248 -0
  40. package/dist/admin/overview.controller.d.ts +31 -0
  41. package/dist/admin/overview.controller.js +78 -0
  42. package/dist/admin/overview.schemas.d.ts +8 -0
  43. package/dist/admin/overview.schemas.js +13 -0
  44. package/dist/admin/overview.service.d.ts +147 -0
  45. package/dist/admin/overview.service.js +256 -0
  46. package/dist/admin/usage.service.d.ts +149 -0
  47. package/dist/admin/usage.service.js +321 -0
  48. package/dist/agents/admin-agents.d.ts +105 -0
  49. package/dist/agents/admin-agents.js +228 -0
  50. package/dist/agents/agent-lookup.d.ts +10 -2
  51. package/dist/agents/agent-lookup.js +20 -10
  52. package/dist/agents/agent-profile.service.d.ts +7 -5
  53. package/dist/agents/agent-profile.service.js +14 -9
  54. package/dist/agents/agents.controller.d.ts +7 -287
  55. package/dist/agents/agents.controller.js +7 -67
  56. package/dist/agents/agents.module.d.ts +4 -3
  57. package/dist/agents/agents.module.js +13 -3
  58. package/dist/agents/agents.schemas.d.ts +440 -0
  59. package/dist/agents/agents.schemas.js +126 -0
  60. package/dist/agents/agents.service.d.ts +67 -13
  61. package/dist/agents/agents.service.js +243 -80
  62. package/dist/agents/definition.d.ts +94 -49
  63. package/dist/agents/definition.js +183 -233
  64. package/dist/agents/from-template.d.ts +8 -5
  65. package/dist/agents/from-template.js +132 -88
  66. package/dist/agents/from-template.service.d.ts +12 -0
  67. package/dist/agents/from-template.service.js +23 -6
  68. package/dist/agents/instruction-files.js +0 -3
  69. package/dist/agents/models.controller.d.ts +38 -6
  70. package/dist/agents/models.controller.js +70 -9
  71. package/dist/agents/org-templates.d.ts +13 -3
  72. package/dist/agents/org-templates.js +168 -67
  73. package/dist/agents/pending-connector-requests.d.ts +2 -0
  74. package/dist/agents/pending-connector-requests.js +1 -1
  75. package/dist/agents/pending-connectors.controller.d.ts +1 -1
  76. package/dist/agents/pending-connectors.controller.js +2 -2
  77. package/dist/agents/pending-connectors.service.d.ts +2 -2
  78. package/dist/agents/pending-connectors.service.js +20 -20
  79. package/dist/agents/profile.d.ts +18 -0
  80. package/dist/agents/profile.js +5 -1
  81. package/dist/agents/readiness.controller.d.ts +8 -19
  82. package/dist/agents/readiness.controller.js +11 -25
  83. package/dist/agents/readiness.service.d.ts +42 -0
  84. package/dist/agents/readiness.service.js +78 -0
  85. package/dist/agents/templates.controller.d.ts +8 -17
  86. package/dist/agents/templates.controller.js +13 -31
  87. package/dist/agents/templates.js +8 -20
  88. package/dist/agents/templates.schemas.d.ts +20 -0
  89. package/dist/agents/templates.schemas.js +45 -0
  90. package/dist/app.d.ts +4 -0
  91. package/dist/app.js +4 -0
  92. package/dist/attribution/platform-attribution.d.ts +104 -0
  93. package/dist/attribution/platform-attribution.js +149 -0
  94. package/dist/background/background.controller.js +3 -2
  95. package/dist/background/background.module.js +2 -2
  96. package/dist/background/background.schemas.d.ts +10 -0
  97. package/dist/background/background.schemas.js +16 -0
  98. package/dist/background/finish.d.ts +13 -2
  99. package/dist/background/finish.js +71 -6
  100. package/dist/background/launch-lock.d.ts +1 -1
  101. package/dist/background/launch-lock.js +1 -1
  102. package/dist/background/launch.d.ts +37 -19
  103. package/dist/background/launch.js +64 -41
  104. package/dist/background/managed-output.d.ts +110 -0
  105. package/dist/background/managed-output.js +219 -0
  106. package/dist/background/managed.d.ts +52 -0
  107. package/dist/background/managed.js +128 -0
  108. package/dist/background/poll.job.d.ts +41 -11
  109. package/dist/background/poll.job.js +195 -61
  110. package/dist/background/render.d.ts +9 -0
  111. package/dist/background/render.js +20 -0
  112. package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
  113. package/dist/background/retire-legacy-tasks.job.js +149 -0
  114. package/dist/background/session.d.ts +3 -44
  115. package/dist/background/session.js +3 -75
  116. package/dist/background/stop.d.ts +46 -25
  117. package/dist/background/stop.js +126 -90
  118. package/dist/background/store.d.ts +144 -56
  119. package/dist/background/store.js +234 -87
  120. package/dist/background/tasks.service.d.ts +39 -10
  121. package/dist/background/tasks.service.js +128 -75
  122. package/dist/background/wake-rules.d.ts +5 -0
  123. package/dist/background/wake-rules.js +18 -6
  124. package/dist/catalog/admin-catalog.controller.d.ts +70 -69
  125. package/dist/catalog/admin-catalog.controller.js +133 -60
  126. package/dist/catalog/admin-catalog.schemas.d.ts +87 -0
  127. package/dist/catalog/admin-catalog.schemas.js +107 -0
  128. package/dist/catalog/appearance.schemas.d.ts +10 -0
  129. package/dist/catalog/appearance.schemas.js +20 -0
  130. package/dist/catalog/appearance.service.d.ts +105 -0
  131. package/dist/catalog/appearance.service.js +304 -0
  132. package/dist/catalog/catalog-content.d.ts +89 -6
  133. package/dist/catalog/catalog-content.js +89 -9
  134. package/dist/catalog/catalog-files.d.ts +42 -0
  135. package/dist/catalog/catalog-files.js +89 -0
  136. package/dist/catalog/catalog-import.module.js +3 -4
  137. package/dist/catalog/catalog-items.d.ts +11 -0
  138. package/dist/catalog/catalog-items.js +25 -3
  139. package/dist/catalog/catalog-scope.service.d.ts +92 -40
  140. package/dist/catalog/catalog-scope.service.js +278 -133
  141. package/dist/catalog/catalog.module.d.ts +2 -1
  142. package/dist/catalog/catalog.module.js +20 -6
  143. package/dist/catalog/catalog.service.d.ts +32 -6
  144. package/dist/catalog/catalog.service.js +99 -9
  145. package/dist/catalog/claude/report.d.ts +9 -2
  146. package/dist/catalog/claude/report.js +1 -0
  147. package/dist/catalog/claude/translate.js +4 -1
  148. package/dist/catalog/cli.d.ts +0 -10
  149. package/dist/catalog/cli.js +3 -25
  150. package/dist/catalog/component-promotion.js +1 -2
  151. package/dist/catalog/component-scope.controller.d.ts +21 -71
  152. package/dist/catalog/component-scope.controller.js +39 -69
  153. package/dist/catalog/component-scope.schemas.d.ts +118 -0
  154. package/dist/catalog/component-scope.schemas.js +97 -0
  155. package/dist/catalog/component-scope.service.d.ts +105 -14
  156. package/dist/catalog/component-scope.service.js +228 -33
  157. package/dist/catalog/component-state.d.ts +54 -9
  158. package/dist/catalog/component-state.js +93 -37
  159. package/dist/catalog/git-source.d.ts +9 -1
  160. package/dist/catalog/git-source.js +29 -2
  161. package/dist/catalog/install-status.d.ts +6 -0
  162. package/dist/catalog/install-status.js +6 -0
  163. package/dist/catalog/job-ids.d.ts +8 -24
  164. package/dist/catalog/job-ids.js +11 -20
  165. package/dist/catalog/marketplace-fetch.d.ts +5 -2
  166. package/dist/catalog/marketplace-fetch.js +4 -1
  167. package/dist/catalog/marketplace-icons.d.ts +64 -0
  168. package/dist/catalog/marketplace-icons.js +131 -0
  169. package/dist/catalog/marketplaces.controller.d.ts +31 -39
  170. package/dist/catalog/marketplaces.controller.js +85 -50
  171. package/dist/catalog/marketplaces.schemas.d.ts +48 -0
  172. package/dist/catalog/marketplaces.schemas.js +53 -0
  173. package/dist/catalog/marketplaces.service.d.ts +57 -4
  174. package/dist/catalog/marketplaces.service.js +268 -8
  175. package/dist/catalog/org-catalog.controller.d.ts +37 -66
  176. package/dist/catalog/org-catalog.controller.js +71 -72
  177. package/dist/catalog/org-catalog.schemas.d.ts +117 -0
  178. package/dist/catalog/org-catalog.schemas.js +141 -0
  179. package/dist/catalog/org-catalog.service.d.ts +11 -2
  180. package/dist/catalog/org-catalog.service.js +69 -12
  181. package/dist/catalog/org-extension-switch.d.ts +7 -2
  182. package/dist/catalog/org-extension-switch.js +56 -9
  183. package/dist/catalog/org-extension.controller.d.ts +33 -19
  184. package/dist/catalog/org-extension.controller.js +63 -16
  185. package/dist/catalog/org-extension.schemas.d.ts +15 -0
  186. package/dist/catalog/org-extension.schemas.js +22 -0
  187. package/dist/catalog/org-plugin-uploads.controller.d.ts +4 -25
  188. package/dist/catalog/org-plugin-uploads.controller.js +15 -29
  189. package/dist/catalog/org-plugin-uploads.d.ts +18 -13
  190. package/dist/catalog/org-plugin-uploads.js +17 -17
  191. package/dist/catalog/org-plugin-uploads.schemas.d.ts +19 -0
  192. package/dist/catalog/org-plugin-uploads.schemas.js +30 -0
  193. package/dist/catalog/owned-items.d.ts +12 -15
  194. package/dist/catalog/owned-items.js +35 -36
  195. package/dist/catalog/owned-plugin-cleanup.d.ts +8 -17
  196. package/dist/catalog/owned-plugin-cleanup.js +12 -66
  197. package/dist/catalog/platform-components.d.ts +75 -32
  198. package/dist/catalog/platform-components.js +177 -81
  199. package/dist/catalog/platform-import-update.d.ts +50 -0
  200. package/dist/catalog/platform-import-update.js +116 -0
  201. package/dist/catalog/plugin-import.d.ts +146 -51
  202. package/dist/catalog/plugin-import.js +313 -159
  203. package/dist/catalog/plugin-install.d.ts +62 -62
  204. package/dist/catalog/plugin-install.js +185 -183
  205. package/dist/catalog/plugin-package.d.ts +54 -13
  206. package/dist/catalog/plugin-package.js +225 -33
  207. package/dist/catalog/plugin-upgrade.d.ts +81 -16
  208. package/dist/catalog/plugin-upgrade.js +241 -67
  209. package/dist/catalog/requests.service.d.ts +72 -11
  210. package/dist/catalog/requests.service.js +235 -17
  211. package/dist/catalog/scope-jobs.d.ts +59 -0
  212. package/dist/catalog/scope-jobs.js +78 -0
  213. package/dist/catalog/scope-orgs.d.ts +1 -1
  214. package/dist/catalog/scope-orgs.js +1 -2
  215. package/dist/catalog/scope-sync-workers.d.ts +23 -0
  216. package/dist/catalog/scope-sync-workers.js +70 -2
  217. package/dist/catalog/scope-sync.d.ts +68 -95
  218. package/dist/catalog/scope-sync.js +128 -205
  219. package/dist/catalog/unshare.d.ts +3 -4
  220. package/dist/catalog/unshare.js +6 -8
  221. package/dist/channels/actions.d.ts +5 -0
  222. package/dist/channels/actions.js +32 -7
  223. package/dist/channels/cards.d.ts +62 -9
  224. package/dist/channels/cards.js +190 -28
  225. package/dist/channels/channels.module.d.ts +13 -9
  226. package/dist/channels/channels.module.js +36 -13
  227. package/dist/channels/channels.schemas.d.ts +41 -0
  228. package/dist/channels/channels.schemas.js +40 -0
  229. package/dist/channels/connections.controller.d.ts +46 -37
  230. package/dist/channels/connections.controller.js +76 -34
  231. package/dist/channels/connections.service.d.ts +107 -17
  232. package/dist/channels/connections.service.js +260 -31
  233. package/dist/channels/deliver-job.d.ts +32 -0
  234. package/dist/channels/deliver-job.js +29 -0
  235. package/dist/channels/features.d.ts +2 -0
  236. package/dist/channels/features.js +9 -5
  237. package/dist/channels/file-delivery.d.ts +74 -0
  238. package/dist/channels/file-delivery.js +176 -0
  239. package/dist/channels/inbound.d.ts +9 -32
  240. package/dist/channels/inbound.js +84 -52
  241. package/dist/channels/job-ids.d.ts +2 -6
  242. package/dist/channels/job-ids.js +2 -6
  243. package/dist/channels/jobs.d.ts +37 -20
  244. package/dist/channels/jobs.js +79 -27
  245. package/dist/channels/outbound.d.ts +45 -5
  246. package/dist/channels/outbound.js +341 -24
  247. package/dist/channels/phrases.d.ts +176 -34
  248. package/dist/channels/phrases.js +151 -30
  249. package/dist/channels/supervisor.d.ts +4 -3
  250. package/dist/channels/supervisor.js +6 -3
  251. package/dist/channels/threads.d.ts +16 -3
  252. package/dist/channels/threads.js +38 -3
  253. package/dist/channels/webhook.d.ts +21 -1
  254. package/dist/channels/webhook.js +39 -4
  255. package/dist/client/client-access.service.d.ts +102 -0
  256. package/dist/client/client-access.service.js +303 -0
  257. package/dist/client/client-builds.service.d.ts +109 -0
  258. package/dist/client/client-builds.service.js +229 -0
  259. package/dist/client/client-delivery.controller.d.ts +25 -0
  260. package/dist/client/client-delivery.controller.js +66 -0
  261. package/dist/client/client-files.d.ts +48 -0
  262. package/dist/client/client-files.js +136 -0
  263. package/dist/client/client-reports.cron.d.ts +13 -0
  264. package/dist/client/client-reports.cron.js +42 -0
  265. package/dist/client/client-reports.service.d.ts +30 -0
  266. package/dist/client/client-reports.service.js +102 -0
  267. package/dist/client/client-sign-in.service.d.ts +21 -0
  268. package/dist/client/client-sign-in.service.js +49 -0
  269. package/dist/client/client.controller.d.ts +49 -0
  270. package/dist/client/client.controller.js +129 -0
  271. package/dist/client/client.module.d.ts +8 -0
  272. package/dist/client/client.module.js +28 -0
  273. package/dist/client/client.schemas.d.ts +61 -0
  274. package/dist/client/client.schemas.js +27 -0
  275. package/dist/config/docs.js +2 -0
  276. package/dist/config/env.js +19 -1
  277. package/dist/config/load.d.ts +11 -0
  278. package/dist/config/load.js +52 -2
  279. package/dist/config/permission-migration.d.ts +26 -0
  280. package/dist/config/permission-migration.js +64 -0
  281. package/dist/config/schema.d.ts +111 -50
  282. package/dist/config/schema.js +575 -92
  283. package/dist/conversations/access.d.ts +14 -5
  284. package/dist/conversations/access.js +29 -20
  285. package/dist/conversations/agent-tree.d.ts +16 -0
  286. package/dist/conversations/agent-tree.js +36 -0
  287. package/dist/conversations/attachments.service.d.ts +49 -3
  288. package/dist/conversations/attachments.service.js +108 -38
  289. package/dist/conversations/conversations.controller.d.ts +41 -86
  290. package/dist/conversations/conversations.controller.js +75 -114
  291. package/dist/conversations/conversations.module.d.ts +1 -1
  292. package/dist/conversations/conversations.module.js +19 -7
  293. package/dist/conversations/conversations.schemas.d.ts +60 -0
  294. package/dist/conversations/conversations.schemas.js +93 -0
  295. package/dist/conversations/conversations.service.d.ts +268 -41
  296. package/dist/conversations/conversations.service.js +525 -145
  297. package/dist/conversations/delivery-scope.d.ts +34 -0
  298. package/dist/conversations/delivery-scope.js +23 -0
  299. package/dist/conversations/{environment-status.d.ts → device-status.d.ts} +9 -9
  300. package/dist/conversations/{environment-status.js → device-status.js} +18 -18
  301. package/dist/conversations/event-log.d.ts +58 -12
  302. package/dist/conversations/event-log.js +132 -22
  303. package/dist/conversations/events.d.ts +811 -43
  304. package/dist/conversations/events.js +850 -87
  305. package/dist/conversations/files.d.ts +82 -12
  306. package/dist/conversations/files.js +210 -54
  307. package/dist/conversations/media-types.d.ts +25 -0
  308. package/dist/conversations/media-types.js +38 -0
  309. package/dist/conversations/message-context.d.ts +82 -0
  310. package/dist/conversations/message-context.js +149 -0
  311. package/dist/conversations/permission-profile-store.d.ts +50 -0
  312. package/dist/conversations/permission-profile-store.js +67 -0
  313. package/dist/conversations/permission-profile-store.module.d.ts +2 -0
  314. package/dist/conversations/permission-profile-store.module.js +19 -0
  315. package/dist/conversations/permission-profiles.controller.d.ts +84 -0
  316. package/dist/conversations/permission-profiles.controller.js +105 -0
  317. package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
  318. package/dist/conversations/permission-profiles.schemas.js +23 -0
  319. package/dist/conversations/permission-profiles.service.d.ts +56 -0
  320. package/dist/conversations/permission-profiles.service.js +179 -0
  321. package/dist/conversations/prompt-suggestion-request.d.ts +95 -0
  322. package/dist/conversations/prompt-suggestion-request.js +213 -0
  323. package/dist/conversations/prompt-suggestion-store.d.ts +51 -0
  324. package/dist/conversations/prompt-suggestion-store.js +136 -0
  325. package/dist/conversations/prompt-suggestions.d.ts +153 -0
  326. package/dist/conversations/prompt-suggestions.js +563 -0
  327. package/dist/conversations/queue.d.ts +20 -4
  328. package/dist/conversations/queue.js +31 -3
  329. package/dist/conversations/queue.service.d.ts +20 -9
  330. package/dist/conversations/queue.service.js +92 -27
  331. package/dist/conversations/source.d.ts +10 -0
  332. package/dist/conversations/source.js +17 -0
  333. package/dist/conversations/titles.d.ts +21 -8
  334. package/dist/conversations/titles.js +57 -22
  335. package/dist/conversations/tree.d.ts +10 -0
  336. package/dist/conversations/tree.js +35 -0
  337. package/dist/ctx/create-ctx.d.ts +91 -10
  338. package/dist/ctx/create-ctx.js +231 -48
  339. package/dist/ctx/net.d.ts +50 -0
  340. package/dist/ctx/net.js +67 -0
  341. package/dist/ctx/secrets.d.ts +24 -7
  342. package/dist/ctx/secrets.js +97 -30
  343. package/dist/db/kernel-schema.d.ts +766 -51
  344. package/dist/devices/access.d.ts +66 -0
  345. package/dist/devices/access.js +113 -0
  346. package/dist/devices/access.module.d.ts +2 -0
  347. package/dist/devices/access.module.js +19 -0
  348. package/dist/devices/conversation-devices.d.ts +140 -0
  349. package/dist/devices/conversation-devices.js +331 -0
  350. package/dist/devices/device-projects.service.d.ts +160 -0
  351. package/dist/devices/device-projects.service.js +499 -0
  352. package/dist/devices/devices.controller.d.ts +65 -0
  353. package/dist/devices/devices.controller.js +221 -0
  354. package/dist/devices/devices.module.d.ts +8 -0
  355. package/dist/devices/devices.module.js +49 -0
  356. package/dist/devices/devices.schemas.d.ts +11 -0
  357. package/dist/devices/devices.schemas.js +30 -0
  358. package/dist/devices/devices.service.d.ts +529 -0
  359. package/dist/devices/devices.service.js +1317 -0
  360. package/dist/devices/dto.d.ts +102 -0
  361. package/dist/devices/dto.js +124 -0
  362. package/dist/devices/errors.d.ts +13 -0
  363. package/dist/devices/errors.js +15 -0
  364. package/dist/devices/label.d.ts +11 -0
  365. package/dist/devices/label.js +25 -0
  366. package/dist/{environments → devices}/legacy-cleanup.job.d.ts +4 -4
  367. package/dist/{environments → devices}/legacy-cleanup.job.js +7 -7
  368. package/dist/devices/project-rules.d.ts +44 -0
  369. package/dist/devices/project-rules.js +27 -0
  370. package/dist/devices/public-suffix.d.ts +6 -0
  371. package/dist/devices/public-suffix.js +79 -0
  372. package/dist/devices/working-root.d.ts +47 -0
  373. package/dist/devices/working-root.js +61 -0
  374. package/dist/errors.d.ts +309 -21
  375. package/dist/errors.js +309 -21
  376. package/dist/evals/evals.module.js +16 -3
  377. package/dist/evals/evals.schemas.d.ts +110 -0
  378. package/dist/evals/evals.schemas.js +107 -0
  379. package/dist/evals/jobs.d.ts +14 -6
  380. package/dist/evals/jobs.js +21 -19
  381. package/dist/evals/plan.d.ts +20 -15
  382. package/dist/evals/plan.js +29 -6
  383. package/dist/evals/reconstruct.d.ts +70 -21
  384. package/dist/evals/reconstruct.js +180 -78
  385. package/dist/evals/recorded-permission-context.d.ts +77 -0
  386. package/dist/evals/recorded-permission-context.js +151 -0
  387. package/dist/evals/recorded-tools.d.ts +18 -26
  388. package/dist/evals/recorded-tools.js +54 -84
  389. package/dist/evals/run-replay.d.ts +36 -9
  390. package/dist/evals/run-replay.js +101 -30
  391. package/dist/evals/runs.controller.d.ts +2 -57
  392. package/dist/evals/runs.controller.js +1 -42
  393. package/dist/evals/runs.service.d.ts +13 -13
  394. package/dist/evals/runs.service.js +55 -62
  395. package/dist/evals/sets.controller.d.ts +2 -28
  396. package/dist/evals/sets.controller.js +1 -31
  397. package/dist/evals/sets.service.d.ts +24 -11
  398. package/dist/evals/sets.service.js +64 -23
  399. package/dist/evals/snapshot.d.ts +9 -3
  400. package/dist/evals/snapshot.js +5 -4
  401. package/dist/evals/step-replay.d.ts +8 -1
  402. package/dist/evals/step-replay.js +8 -2
  403. package/dist/evals/trajectory.d.ts +19 -3
  404. package/dist/evals/trajectory.js +14 -1
  405. package/dist/evals/worker.d.ts +10 -1
  406. package/dist/evals/worker.js +24 -14
  407. package/dist/extensions/admin-ops.d.ts +53 -7
  408. package/dist/extensions/admin-ops.js +142 -20
  409. package/dist/extensions/admin-view.d.ts +25 -4
  410. package/dist/extensions/admin-view.js +166 -29
  411. package/dist/extensions/approvals.d.ts +12 -2
  412. package/dist/extensions/blobs.d.ts +14 -1
  413. package/dist/extensions/blobs.js +48 -5
  414. package/dist/extensions/bootstrap.d.ts +73 -11
  415. package/dist/extensions/bootstrap.js +161 -38
  416. package/dist/extensions/cli.js +0 -1
  417. package/dist/extensions/config-hash.d.ts +10 -0
  418. package/dist/extensions/config-hash.js +38 -0
  419. package/dist/extensions/deployment-config.d.ts +16 -1
  420. package/dist/extensions/deployment-config.js +83 -0
  421. package/dist/extensions/effective-config.d.ts +6 -0
  422. package/dist/extensions/effective-config.js +18 -7
  423. package/dist/extensions/enabled.d.ts +24 -4
  424. package/dist/extensions/enabled.js +47 -10
  425. package/dist/extensions/extensions.module.js +29 -13
  426. package/dist/extensions/guide-places.d.ts +68 -0
  427. package/dist/extensions/guide-places.js +152 -0
  428. package/dist/extensions/hooks.d.ts +22 -3
  429. package/dist/extensions/hooks.js +15 -1
  430. package/dist/extensions/host.d.ts +79 -17
  431. package/dist/extensions/host.js +288 -83
  432. package/dist/extensions/installs.d.ts +11 -4
  433. package/dist/extensions/installs.js +24 -2
  434. package/dist/extensions/instance.d.ts +15 -2
  435. package/dist/extensions/instance.js +18 -0
  436. package/dist/extensions/ledger.d.ts +1 -1
  437. package/dist/extensions/lifecycle-hooks.d.ts +99 -0
  438. package/dist/extensions/lifecycle-hooks.js +273 -0
  439. package/dist/extensions/lifecycle.d.ts +6 -1
  440. package/dist/extensions/lifecycle.js +9 -2
  441. package/dist/extensions/locks.d.ts +12 -0
  442. package/dist/extensions/locks.js +26 -0
  443. package/dist/extensions/org-config.d.ts +39 -9
  444. package/dist/extensions/org-config.js +86 -49
  445. package/dist/extensions/package.d.ts +6 -5
  446. package/dist/extensions/package.js +5 -5
  447. package/dist/extensions/permission-set.d.ts +40 -9
  448. package/dist/extensions/permission-set.js +43 -9
  449. package/dist/extensions/permission-view.d.ts +98 -18
  450. package/dist/extensions/permission-view.js +48 -20
  451. package/dist/extensions/plugin-guides.d.ts +282 -0
  452. package/dist/extensions/plugin-guides.js +554 -0
  453. package/dist/extensions/plugin-icons.d.ts +54 -0
  454. package/dist/extensions/plugin-icons.js +125 -0
  455. package/dist/extensions/plugin-items.d.ts +21 -1
  456. package/dist/extensions/plugin-items.js +28 -0
  457. package/dist/extensions/point-defaults.controller.d.ts +2 -8
  458. package/dist/extensions/point-defaults.controller.js +1 -3
  459. package/dist/extensions/point-defaults.d.ts +31 -2
  460. package/dist/extensions/point-defaults.js +48 -15
  461. package/dist/extensions/point-defaults.schemas.d.ts +9 -0
  462. package/dist/extensions/point-defaults.schemas.js +14 -0
  463. package/dist/extensions/resolve.d.ts +46 -0
  464. package/dist/extensions/resolve.js +70 -1
  465. package/dist/extensions/single-provider.d.ts +92 -0
  466. package/dist/extensions/single-provider.js +180 -0
  467. package/dist/extensions/sources.d.ts +13 -2
  468. package/dist/extensions/sources.js +2 -0
  469. package/dist/extensions/state.module.d.ts +9 -0
  470. package/dist/extensions/state.module.js +46 -0
  471. package/dist/extensions/sync.js +5 -10
  472. package/dist/extensions/unavailable.d.ts +50 -0
  473. package/dist/extensions/unavailable.js +114 -0
  474. package/dist/extensions/usage-subscribers.d.ts +43 -0
  475. package/dist/extensions/usage-subscribers.js +108 -0
  476. package/dist/files/previewers.controller.js +2 -3
  477. package/dist/files/previewers.d.ts +46 -2
  478. package/dist/files/previewers.js +90 -30
  479. package/dist/files/previewers.schemas.d.ts +10 -0
  480. package/dist/files/previewers.schemas.js +9 -0
  481. package/dist/git/gateway.d.ts +93 -0
  482. package/dist/git/gateway.js +750 -0
  483. package/dist/git/gateway.route.d.ts +16 -0
  484. package/dist/git/gateway.route.js +41 -0
  485. package/dist/git/git.module.d.ts +10 -0
  486. package/dist/git/git.module.js +31 -0
  487. package/dist/git/identity.d.ts +80 -0
  488. package/dist/git/identity.js +209 -0
  489. package/dist/git/pkt-line.d.ts +53 -0
  490. package/dist/git/pkt-line.js +146 -0
  491. package/dist/git/run-end.d.ts +29 -0
  492. package/dist/git/run-end.js +121 -0
  493. package/dist/git/sources.d.ts +42 -0
  494. package/dist/git/sources.js +134 -0
  495. package/dist/git/tickets.d.ts +69 -0
  496. package/dist/git/tickets.js +194 -0
  497. package/dist/html/csp.d.ts +13 -0
  498. package/dist/html/csp.js +33 -0
  499. package/dist/html/html-document.controller.d.ts +31 -0
  500. package/dist/html/html-document.controller.js +75 -0
  501. package/dist/html/html-document.service.d.ts +49 -0
  502. package/dist/html/html-document.service.js +143 -0
  503. package/dist/html/html-token.d.ts +58 -0
  504. package/dist/html/html-token.js +154 -0
  505. package/dist/html/html-type.d.ts +13 -0
  506. package/dist/html/html-type.js +40 -0
  507. package/dist/html/html.module.d.ts +6 -0
  508. package/dist/html/html.module.js +26 -0
  509. package/dist/http/api.module.js +78 -5
  510. package/dist/http/app.d.ts +14 -2
  511. package/dist/http/app.js +15 -2
  512. package/dist/http/error.filter.d.ts +2 -0
  513. package/dist/http/error.filter.js +9 -2
  514. package/dist/http/gateway-routes.d.ts +7 -3
  515. package/dist/http/gateway-routes.js +6 -3
  516. package/dist/http/plugin-dispatch.d.ts +58 -18
  517. package/dist/http/plugin-dispatch.js +137 -30
  518. package/dist/http/plugin-route-access.d.ts +57 -0
  519. package/dist/http/plugin-route-access.js +207 -0
  520. package/dist/identity/accounts.d.ts +64 -5
  521. package/dist/identity/accounts.js +148 -11
  522. package/dist/identity/audit.d.ts +0 -12
  523. package/dist/identity/audit.js +0 -27
  524. package/dist/identity/auth.controller.js +5 -9
  525. package/dist/identity/auth.guard.d.ts +26 -12
  526. package/dist/identity/auth.guard.js +72 -34
  527. package/dist/identity/cookies.d.ts +8 -7
  528. package/dist/identity/cookies.js +19 -29
  529. package/dist/identity/identity.module.js +5 -0
  530. package/dist/identity/initial-passwords.controller.d.ts +22 -0
  531. package/dist/identity/initial-passwords.controller.js +49 -0
  532. package/dist/identity/initial-passwords.d.ts +61 -0
  533. package/dist/identity/initial-passwords.job.d.ts +16 -0
  534. package/dist/identity/initial-passwords.job.js +46 -0
  535. package/dist/identity/initial-passwords.js +158 -0
  536. package/dist/identity/me.controller.d.ts +12 -0
  537. package/dist/identity/me.controller.js +33 -1
  538. package/dist/identity/me.schemas.d.ts +24 -0
  539. package/dist/identity/me.schemas.js +25 -0
  540. package/dist/identity/principal.d.ts +8 -0
  541. package/dist/identity/principal.js +8 -0
  542. package/dist/identity/sessions.d.ts +0 -6
  543. package/dist/identity/sessions.js +0 -18
  544. package/dist/identity/settings.d.ts +237 -3
  545. package/dist/identity/settings.js +524 -14
  546. package/dist/identity/write-actor.d.ts +11 -0
  547. package/dist/identity/write-actor.js +7 -0
  548. package/dist/inbox/inbox.module.js +2 -1
  549. package/dist/inbox/inbox.schemas.d.ts +8 -0
  550. package/dist/inbox/inbox.schemas.js +11 -0
  551. package/dist/inbox/inbox.service.d.ts +27 -25
  552. package/dist/inbox/inbox.service.js +14 -6
  553. package/dist/inbox/org-notices.d.ts +1 -1
  554. package/dist/inbox/platform-inbox.controller.d.ts +1 -1
  555. package/dist/inbox/platform-inbox.controller.js +2 -2
  556. package/dist/inbox/platform-inbox.service.d.ts +35 -26
  557. package/dist/inbox/platform-inbox.service.js +76 -57
  558. package/dist/index.d.ts +15 -2
  559. package/dist/index.js +16 -2
  560. package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
  561. package/dist/infra/cli/kernel-cli.module.js +10 -2
  562. package/dist/infra/cli/master-key-rewrap.d.ts +15 -0
  563. package/dist/infra/cli/master-key-rewrap.js +24 -0
  564. package/dist/infra/cli/permission-cutover.d.ts +59 -0
  565. package/dist/infra/cli/permission-cutover.js +107 -0
  566. package/dist/infra/config/kernel-config.service.d.ts +8 -1
  567. package/dist/infra/config/kernel-config.service.js +71 -25
  568. package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
  569. package/dist/infra/database/startup-activation-transaction.js +242 -0
  570. package/dist/infra/database/transaction-host.d.ts +79 -0
  571. package/dist/infra/database/transaction-host.js +159 -3
  572. package/dist/infra/database/xact-lock.d.ts +17 -0
  573. package/dist/infra/database/xact-lock.js +34 -1
  574. package/dist/infra/events/kernel-events.d.ts +14 -28
  575. package/dist/infra/health/health.controller.js +8 -0
  576. package/dist/infra/health/process-fault.d.ts +16 -0
  577. package/dist/infra/health/process-fault.js +49 -0
  578. package/dist/infra/lifecycle/process-guards.d.ts +8 -2
  579. package/dist/infra/lifecycle/process-guards.js +12 -3
  580. package/dist/infra/lifecycle/shutdown-signals.d.ts +10 -1
  581. package/dist/infra/lifecycle/shutdown-signals.js +28 -13
  582. package/dist/infra/lock/lock.service.d.ts +8 -0
  583. package/dist/infra/lock/lock.service.js +27 -0
  584. package/dist/infra/outbox/outbox-relay.module.d.ts +6 -0
  585. package/dist/infra/outbox/outbox-relay.module.js +18 -0
  586. package/dist/infra/outbox/outbox.dispatcher.d.ts +103 -0
  587. package/dist/infra/outbox/outbox.dispatcher.js +310 -0
  588. package/dist/infra/outbox/outbox.module.d.ts +24 -0
  589. package/dist/infra/outbox/outbox.module.js +50 -0
  590. package/dist/infra/outbox/outbox.relay.d.ts +31 -0
  591. package/dist/infra/outbox/outbox.relay.js +76 -0
  592. package/dist/infra/outbox/outbox.service.d.ts +60 -0
  593. package/dist/infra/outbox/outbox.service.js +161 -0
  594. package/dist/infra/outbox/registry.d.ts +386 -0
  595. package/dist/infra/outbox/registry.js +352 -0
  596. package/dist/infra/presence/presence.module.d.ts +6 -0
  597. package/dist/infra/presence/presence.module.js +22 -0
  598. package/dist/infra/presence/replica-presence.d.ts +87 -0
  599. package/dist/infra/presence/replica-presence.js +189 -0
  600. package/dist/infra/queue/queue-names.d.ts +8 -0
  601. package/dist/infra/queue/queue-names.js +18 -0
  602. package/dist/infra/throttler/credential-throttler.d.ts +4 -1
  603. package/dist/infra/throttler/credential-throttler.js +5 -2
  604. package/dist/infra/throttler/named-throttlers.d.ts +16 -0
  605. package/dist/infra/throttler/named-throttlers.js +97 -0
  606. package/dist/infra/throttler/throttler.guard.d.ts +2 -1
  607. package/dist/infra/throttler/throttler.guard.js +3 -2
  608. package/dist/kernel.module.js +21 -1
  609. package/dist/lifecycle/kernel-lifecycle.d.ts +12 -2
  610. package/dist/lifecycle/kernel-lifecycle.js +101 -39
  611. package/dist/local-devices/device-auth.controller.d.ts +42 -0
  612. package/dist/local-devices/device-auth.controller.js +116 -0
  613. package/dist/local-devices/device-auth.d.ts +125 -0
  614. package/dist/local-devices/device-auth.js +410 -0
  615. package/dist/local-devices/device-auth.module.d.ts +7 -0
  616. package/dist/local-devices/device-auth.module.js +25 -0
  617. package/dist/local-devices/device-policy.service.d.ts +204 -0
  618. package/dist/local-devices/device-policy.service.js +645 -0
  619. package/dist/local-devices/device-routes.d.ts +38 -0
  620. package/dist/local-devices/device-routes.js +91 -0
  621. package/dist/local-devices/dto.d.ts +66 -0
  622. package/dist/local-devices/dto.js +44 -0
  623. package/dist/local-devices/instance-bindings.d.ts +82 -0
  624. package/dist/local-devices/instance-bindings.js +304 -0
  625. package/dist/local-devices/keys.d.ts +30 -0
  626. package/dist/local-devices/keys.js +30 -0
  627. package/dist/local-devices/local-device-gateway.d.ts +151 -0
  628. package/dist/local-devices/local-device-gateway.js +703 -0
  629. package/dist/local-devices/local-device-provider.d.ts +119 -0
  630. package/dist/local-devices/local-device-provider.js +298 -0
  631. package/dist/local-devices/local-devices.module.d.ts +31 -0
  632. package/dist/local-devices/local-devices.module.js +98 -0
  633. package/dist/local-devices/machines.d.ts +187 -0
  634. package/dist/local-devices/machines.js +738 -0
  635. package/dist/local-devices/network-grants.d.ts +88 -0
  636. package/dist/local-devices/network-grants.js +267 -0
  637. package/dist/local-devices/network-grants.module.d.ts +2 -0
  638. package/dist/local-devices/network-grants.module.js +14 -0
  639. package/dist/local-devices/owner-report.d.ts +79 -0
  640. package/dist/local-devices/owner-report.js +155 -0
  641. package/dist/local-devices/owner-reports.d.ts +48 -0
  642. package/dist/local-devices/owner-reports.js +190 -0
  643. package/dist/local-devices/policy-op-jobs.d.ts +15 -0
  644. package/dist/local-devices/policy-op-jobs.js +12 -0
  645. package/dist/local-devices/policy-summary.d.ts +121 -0
  646. package/dist/local-devices/policy-summary.js +200 -0
  647. package/dist/local-devices/relay.d.ts +165 -0
  648. package/dist/local-devices/relay.js +532 -0
  649. package/dist/local-devices/targets.d.ts +48 -0
  650. package/dist/local-devices/targets.js +120 -0
  651. package/dist/models/embeddings.d.ts +82 -0
  652. package/dist/models/embeddings.js +319 -0
  653. package/dist/models/enablement.controller.d.ts +40 -0
  654. package/dist/models/enablement.controller.js +74 -0
  655. package/dist/models/enablement.d.ts +100 -0
  656. package/dist/models/enablement.js +257 -0
  657. package/dist/models/image-usable.d.ts +46 -0
  658. package/dist/models/image-usable.js +60 -0
  659. package/dist/models/images.d.ts +125 -0
  660. package/dist/models/images.js +442 -0
  661. package/dist/models/models.module.d.ts +6 -1
  662. package/dist/models/models.module.js +30 -4
  663. package/dist/models/org-models.schemas.d.ts +8 -0
  664. package/dist/models/org-models.schemas.js +23 -0
  665. package/dist/models/prices.d.ts +3 -1
  666. package/dist/models/prices.js +7 -5
  667. package/dist/models/purposes.controller.d.ts +7 -0
  668. package/dist/models/purposes.controller.js +9 -0
  669. package/dist/models/purposes.d.ts +64 -8
  670. package/dist/models/purposes.js +115 -26
  671. package/dist/net/public-address.d.ts +35 -5
  672. package/dist/net/public-address.js +78 -22
  673. package/dist/net/safe-fetch.d.ts +6 -2
  674. package/dist/net/safe-fetch.js +31 -8
  675. package/dist/orgs/cloud-network-setting.d.ts +33 -0
  676. package/dist/orgs/cloud-network-setting.js +47 -0
  677. package/dist/orgs/directory-sync.js +3 -1
  678. package/dist/orgs/members.service.js +6 -1
  679. package/dist/orgs/network-allowances.service.d.ts +79 -0
  680. package/dist/orgs/network-allowances.service.js +371 -0
  681. package/dist/orgs/offboarding.d.ts +59 -58
  682. package/dist/orgs/offboarding.js +146 -168
  683. package/dist/orgs/org-lock.d.ts +34 -2
  684. package/dist/orgs/org-lock.js +65 -4
  685. package/dist/orgs/orgs.controller.d.ts +12 -6
  686. package/dist/orgs/orgs.controller.js +21 -8
  687. package/dist/orgs/orgs.module.d.ts +3 -2
  688. package/dist/orgs/orgs.module.js +13 -12
  689. package/dist/orgs/orgs.schemas.d.ts +20 -0
  690. package/dist/orgs/orgs.schemas.js +21 -0
  691. package/dist/orgs/orgs.service.d.ts +19 -7
  692. package/dist/orgs/orgs.service.js +63 -18
  693. package/dist/orgs/roles.d.ts +1 -1
  694. package/dist/orgs/roles.js +6 -0
  695. package/dist/orgs/settings.controller.d.ts +5 -2
  696. package/dist/orgs/settings.controller.js +9 -4
  697. package/dist/orgs/settings.service.d.ts +381 -48
  698. package/dist/orgs/settings.service.js +615 -81
  699. package/dist/overrides.d.ts +66 -5
  700. package/dist/overrides.js +36 -2
  701. package/dist/packages/npm.d.ts +28 -9
  702. package/dist/packages/npm.js +30 -19
  703. package/dist/packages/provenance.d.ts +3 -1
  704. package/dist/packages/provenance.js +7 -3
  705. package/dist/packages/tgz.d.ts +0 -2
  706. package/dist/packages/tgz.js +0 -2
  707. package/dist/platform/availability.d.ts +5 -0
  708. package/dist/platform/availability.js +7 -3
  709. package/dist/platform/errors.d.ts +21 -4
  710. package/dist/platform/errors.js +45 -6
  711. package/dist/platform/exclusions.d.ts +2 -3
  712. package/dist/platform/exclusions.js +261 -778
  713. package/dist/platform/method.js +1 -1
  714. package/dist/platform/operation.d.ts +82 -5
  715. package/dist/platform/operation.js +79 -8
  716. package/dist/platform/ops/accounts.ops.d.ts +32 -0
  717. package/dist/platform/ops/accounts.ops.js +291 -0
  718. package/dist/platform/ops/admin-items.ops.d.ts +37 -0
  719. package/dist/platform/ops/admin-items.ops.js +278 -0
  720. package/dist/platform/ops/admin.ops.d.ts +38 -0
  721. package/dist/platform/ops/admin.ops.js +566 -0
  722. package/dist/platform/ops/agent-skills.ops.d.ts +50 -0
  723. package/dist/platform/ops/agent-skills.ops.js +512 -0
  724. package/dist/platform/ops/agent-templates.ops.d.ts +4 -1
  725. package/dist/platform/ops/agent-templates.ops.js +196 -16
  726. package/dist/platform/ops/agents.ops.d.ts +19 -1
  727. package/dist/platform/ops/agents.ops.js +497 -68
  728. package/dist/platform/ops/approvals.ops.d.ts +30 -0
  729. package/dist/platform/ops/approvals.ops.js +116 -0
  730. package/dist/platform/ops/background.ops.d.ts +14 -0
  731. package/dist/platform/ops/background.ops.js +134 -0
  732. package/dist/platform/ops/catalog-admin.ops.d.ts +94 -0
  733. package/dist/platform/ops/catalog-admin.ops.js +710 -0
  734. package/dist/platform/ops/channels.ops.d.ts +16 -0
  735. package/dist/platform/ops/channels.ops.js +195 -0
  736. package/dist/platform/ops/components.ops.d.ts +46 -0
  737. package/dist/platform/ops/components.ops.js +854 -0
  738. package/dist/platform/ops/connectors.ops.d.ts +4 -2
  739. package/dist/platform/ops/connectors.ops.js +115 -6
  740. package/dist/platform/ops/conversations.ops.d.ts +30 -0
  741. package/dist/platform/ops/conversations.ops.js +505 -0
  742. package/dist/platform/ops/devices.ops.d.ts +28 -0
  743. package/dist/platform/ops/devices.ops.js +454 -0
  744. package/dist/platform/ops/errors.d.ts +10 -5
  745. package/dist/platform/ops/errors.js +19 -11
  746. package/dist/platform/ops/evals.ops.d.ts +28 -0
  747. package/dist/platform/ops/evals.ops.js +731 -0
  748. package/dist/platform/ops/extensions-admin.ops.d.ts +25 -0
  749. package/dist/platform/ops/extensions-admin.ops.js +372 -0
  750. package/dist/platform/ops/extensions.ops.d.ts +7 -1
  751. package/dist/platform/ops/extensions.ops.js +248 -17
  752. package/dist/platform/ops/inbox.ops.d.ts +25 -0
  753. package/dist/platform/ops/inbox.ops.js +397 -0
  754. package/dist/platform/ops/marketplaces.ops.d.ts +7 -1
  755. package/dist/platform/ops/marketplaces.ops.js +326 -17
  756. package/dist/platform/ops/models.ops.d.ts +25 -0
  757. package/dist/platform/ops/models.ops.js +242 -0
  758. package/dist/platform/ops/org-plugins.ops.d.ts +35 -0
  759. package/dist/platform/ops/org-plugins.ops.js +388 -0
  760. package/dist/platform/ops/org-settings.ops.d.ts +18 -0
  761. package/dist/platform/ops/org-settings.ops.js +148 -0
  762. package/dist/platform/ops/orgs.ops.d.ts +36 -0
  763. package/dist/platform/ops/orgs.ops.js +439 -0
  764. package/dist/platform/ops/other-orgs.d.ts +20 -0
  765. package/dist/platform/ops/other-orgs.js +72 -0
  766. package/dist/platform/ops/outbox.ops.d.ts +21 -0
  767. package/dist/platform/ops/outbox.ops.js +125 -0
  768. package/dist/platform/ops/platform.ops.d.ts +24 -6
  769. package/dist/platform/ops/platform.ops.js +141 -38
  770. package/dist/platform/ops/plugins.ops.d.ts +11 -9
  771. package/dist/platform/ops/plugins.ops.js +178 -79
  772. package/dist/platform/ops/previewers.ops.d.ts +14 -0
  773. package/dist/platform/ops/previewers.ops.js +109 -0
  774. package/dist/platform/ops/requests.ops.js +58 -19
  775. package/dist/platform/ops/schedules.ops.d.ts +21 -0
  776. package/dist/platform/ops/schedules.ops.js +509 -0
  777. package/dist/platform/ops/setup.ops.d.ts +24 -0
  778. package/dist/platform/ops/setup.ops.js +212 -0
  779. package/dist/platform/ops/shares.ops.d.ts +16 -0
  780. package/dist/platform/ops/shares.ops.js +107 -0
  781. package/dist/platform/ops/skills.ops.d.ts +5 -1
  782. package/dist/platform/ops/skills.ops.js +99 -37
  783. package/dist/platform/ops/themes.ops.d.ts +14 -0
  784. package/dist/platform/ops/themes.ops.js +47 -0
  785. package/dist/platform/ops/ui.ops.d.ts +8 -0
  786. package/dist/platform/ops/ui.ops.js +41 -0
  787. package/dist/platform/ops/unavailable.d.ts +23 -0
  788. package/dist/platform/ops/unavailable.js +118 -0
  789. package/dist/platform/parity.d.ts +33 -0
  790. package/dist/platform/parity.js +272 -0
  791. package/dist/platform/platform-ops.module.d.ts +39 -0
  792. package/dist/platform/platform-ops.module.js +111 -11
  793. package/dist/platform/route-schemas.d.ts +18 -0
  794. package/dist/platform/route-schemas.js +97 -0
  795. package/dist/roles/gateway-role.d.ts +18 -3
  796. package/dist/roles/gateway-role.js +33 -5
  797. package/dist/roles/gateway.module.d.ts +2 -1
  798. package/dist/roles/gateway.module.js +6 -3
  799. package/dist/roles/worker-role.d.ts +16 -9
  800. package/dist/roles/worker-role.js +39 -31
  801. package/dist/roles/worker.module.js +33 -9
  802. package/dist/runtime/checkpointer.d.ts +3 -0
  803. package/dist/runtime/checkpointer.js +9 -3
  804. package/dist/runtime/compaction-progress.d.ts +62 -0
  805. package/dist/runtime/compaction-progress.js +82 -0
  806. package/dist/runtime/compaction-settings.service.d.ts +24 -0
  807. package/dist/runtime/compaction-settings.service.js +48 -0
  808. package/dist/runtime/compaction.service.d.ts +50 -0
  809. package/dist/runtime/compaction.service.js +75 -0
  810. package/dist/runtime/context/build.d.ts +79 -20
  811. package/dist/runtime/context/build.js +281 -57
  812. package/dist/runtime/context/compaction.d.ts +111 -16
  813. package/dist/runtime/context/compaction.js +419 -55
  814. package/dist/runtime/context/device-paths.d.ts +89 -0
  815. package/dist/runtime/context/device-paths.js +185 -0
  816. package/dist/runtime/context/fit.d.ts +111 -0
  817. package/dist/runtime/context/fit.js +278 -0
  818. package/dist/runtime/context/permission-profile.d.ts +46 -0
  819. package/dist/runtime/context/permission-profile.js +194 -0
  820. package/dist/runtime/context/plugin-context.d.ts +20 -0
  821. package/dist/runtime/context/plugin-context.js +30 -0
  822. package/dist/runtime/context/project-root.d.ts +43 -0
  823. package/dist/runtime/context/project-root.js +85 -0
  824. package/dist/runtime/context/run-context.d.ts +88 -0
  825. package/dist/runtime/context/run-context.js +295 -0
  826. package/dist/runtime/context/skills.d.ts +38 -54
  827. package/dist/runtime/context/skills.js +76 -117
  828. package/dist/runtime/context/tool-changes.d.ts +3 -3
  829. package/dist/runtime/context/tool-changes.js +6 -16
  830. package/dist/runtime/conversation-lock.d.ts +4 -11
  831. package/dist/runtime/conversation-lock.js +14 -18
  832. package/dist/runtime/hook-calls.d.ts +24 -7
  833. package/dist/runtime/hook-calls.js +71 -17
  834. package/dist/runtime/langgraph-loop.js +26 -8
  835. package/dist/runtime/limits.d.ts +15 -0
  836. package/dist/runtime/limits.js +25 -0
  837. package/dist/runtime/loop.d.ts +16 -3
  838. package/dist/runtime/loop.js +2 -1
  839. package/dist/runtime/maintenance.d.ts +25 -14
  840. package/dist/runtime/maintenance.js +134 -33
  841. package/dist/runtime/model-call.d.ts +187 -21
  842. package/dist/runtime/model-call.js +1024 -371
  843. package/dist/runtime/permission-context-errors.d.ts +39 -0
  844. package/dist/runtime/permission-context-errors.js +67 -0
  845. package/dist/runtime/permission-context.service.d.ts +60 -0
  846. package/dist/runtime/permission-context.service.js +286 -0
  847. package/dist/runtime/plugin-context.service.d.ts +75 -0
  848. package/dist/runtime/plugin-context.service.js +220 -0
  849. package/dist/runtime/project/knowledge.d.ts +134 -0
  850. package/dist/runtime/project/knowledge.js +251 -0
  851. package/dist/runtime/project/knowledge.service.d.ts +100 -0
  852. package/dist/runtime/project/knowledge.service.js +352 -0
  853. package/dist/runtime/providers.d.ts +160 -44
  854. package/dist/runtime/providers.js +365 -130
  855. package/dist/runtime/queue-lost-jobs.d.ts +24 -0
  856. package/dist/runtime/queue-lost-jobs.js +51 -0
  857. package/dist/runtime/run-context.service.d.ts +82 -0
  858. package/dist/runtime/run-context.service.js +255 -0
  859. package/dist/runtime/run-control.d.ts +52 -5
  860. package/dist/runtime/run-control.js +86 -12
  861. package/dist/runtime/run-deletion.d.ts +29 -0
  862. package/dist/runtime/run-deletion.js +153 -0
  863. package/dist/runtime/run-execution.d.ts +79 -0
  864. package/dist/runtime/run-execution.js +184 -0
  865. package/dist/runtime/run-finish.d.ts +49 -12
  866. package/dist/runtime/run-finish.js +140 -15
  867. package/dist/runtime/run-jobs.d.ts +112 -13
  868. package/dist/runtime/run-jobs.js +236 -29
  869. package/dist/runtime/run-liveness.d.ts +11 -0
  870. package/dist/runtime/run-liveness.js +19 -0
  871. package/dist/runtime/run-orphan-check.job.d.ts +145 -0
  872. package/dist/runtime/run-orphan-check.job.js +413 -0
  873. package/dist/runtime/run-processors.d.ts +30 -15
  874. package/dist/runtime/run-processors.js +44 -9
  875. package/dist/runtime/run-queue.d.ts +96 -68
  876. package/dist/runtime/run-queue.js +323 -299
  877. package/dist/runtime/run-status.d.ts +12 -0
  878. package/dist/runtime/run-status.js +21 -0
  879. package/dist/runtime/run-steps.d.ts +13 -4
  880. package/dist/runtime/run-steps.js +40 -13
  881. package/dist/runtime/run-worker.d.ts +74 -25
  882. package/dist/runtime/run-worker.js +468 -138
  883. package/dist/runtime/runtime.module.d.ts +3 -4
  884. package/dist/runtime/runtime.module.js +56 -7
  885. package/dist/runtime/step-log.d.ts +23 -5
  886. package/dist/runtime/step-log.js +36 -10
  887. package/dist/runtime/stream.controller.d.ts +2 -4
  888. package/dist/runtime/stream.controller.js +5 -11
  889. package/dist/runtime/stream.d.ts +7 -1
  890. package/dist/runtime/stream.js +77 -5
  891. package/dist/runtime/subagents/child.js +1 -1
  892. package/dist/runtime/subagents/definition.d.ts +41 -25
  893. package/dist/runtime/subagents/definition.js +145 -209
  894. package/dist/runtime/subagents/deliveries.d.ts +6 -3
  895. package/dist/runtime/subagents/deliveries.js +16 -7
  896. package/dist/runtime/subagents/dispatch.d.ts +18 -14
  897. package/dist/runtime/subagents/dispatch.js +32 -41
  898. package/dist/runtime/subagents/messages.d.ts +5 -1
  899. package/dist/runtime/subagents/messages.js +11 -3
  900. package/dist/runtime/subagents/org-agents.js +1 -2
  901. package/dist/runtime/subagents/preamble.d.ts +3 -1
  902. package/dist/runtime/subagents/preamble.js +3 -1
  903. package/dist/runtime/subagents/render.d.ts +1 -2
  904. package/dist/runtime/subagents/render.js +1 -2
  905. package/dist/runtime/subagents/skill-fork.d.ts +5 -7
  906. package/dist/runtime/subagents/skill-fork.js +8 -5
  907. package/dist/runtime/subagents/subagents.service.js +1 -1
  908. package/dist/runtime/subagents/template-skills.d.ts +47 -0
  909. package/dist/runtime/subagents/template-skills.js +76 -0
  910. package/dist/runtime/subagents/tree-jobs.d.ts +62 -0
  911. package/dist/runtime/subagents/tree-jobs.js +86 -0
  912. package/dist/runtime/usage-report-jobs.d.ts +63 -0
  913. package/dist/runtime/usage-report-jobs.js +106 -0
  914. package/dist/runtime/usage-report.d.ts +52 -98
  915. package/dist/runtime/usage-report.js +145 -231
  916. package/dist/runtime/waits.d.ts +64 -204
  917. package/dist/runtime/waits.js +159 -825
  918. package/dist/sandbox/attachments-path.d.ts +15 -0
  919. package/dist/sandbox/attachments-path.js +15 -0
  920. package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
  921. package/dist/sandbox/cloud-permission-snapshot.js +407 -0
  922. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
  923. package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
  924. package/dist/sandbox/held-operations.d.ts +46 -0
  925. package/dist/sandbox/held-operations.js +143 -0
  926. package/dist/sandbox/jobs.d.ts +42 -21
  927. package/dist/sandbox/jobs.js +57 -33
  928. package/dist/sandbox/kernel-read.d.ts +55 -0
  929. package/dist/sandbox/kernel-read.js +57 -0
  930. package/dist/sandbox/leases.d.ts +15 -12
  931. package/dist/sandbox/leases.js +30 -24
  932. package/dist/sandbox/legacy-retirement.d.ts +317 -0
  933. package/dist/sandbox/legacy-retirement.js +1032 -0
  934. package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
  935. package/dist/sandbox/legacy-retirement.module.js +25 -0
  936. package/dist/sandbox/managed-device-context.d.ts +106 -0
  937. package/dist/sandbox/managed-device-context.js +356 -0
  938. package/dist/sandbox/managed-device-context.module.d.ts +6 -0
  939. package/dist/sandbox/managed-device-context.module.js +33 -0
  940. package/dist/sandbox/modes.d.ts +169 -0
  941. package/dist/sandbox/modes.js +218 -0
  942. package/dist/sandbox/operation-authority-types.d.ts +25 -0
  943. package/dist/sandbox/operation-authority-types.js +51 -0
  944. package/dist/sandbox/operation-authority.d.ts +159 -0
  945. package/dist/sandbox/operation-authority.js +885 -0
  946. package/dist/sandbox/operation-authority.module.d.ts +2 -0
  947. package/dist/sandbox/operation-authority.module.js +29 -0
  948. package/dist/sandbox/operation-intents.d.ts +249 -0
  949. package/dist/sandbox/operation-intents.js +1355 -0
  950. package/dist/sandbox/operation-intents.module.d.ts +2 -0
  951. package/dist/sandbox/operation-intents.module.js +21 -0
  952. package/dist/sandbox/operation-payloads.d.ts +33 -0
  953. package/dist/sandbox/operation-payloads.js +332 -0
  954. package/dist/sandbox/operation-reconcile.job.d.ts +60 -0
  955. package/dist/sandbox/operation-reconcile.job.js +294 -0
  956. package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
  957. package/dist/sandbox/permission-authority-epochs.js +83 -0
  958. package/dist/sandbox/permission-authority-lock.d.ts +38 -0
  959. package/dist/sandbox/permission-authority-lock.js +147 -0
  960. package/dist/sandbox/permission-authority.module.d.ts +9 -0
  961. package/dist/sandbox/permission-authority.module.js +55 -0
  962. package/dist/sandbox/permission-availability.d.ts +18 -0
  963. package/dist/sandbox/permission-availability.js +19 -0
  964. package/dist/sandbox/permission-call-grants.d.ts +38 -0
  965. package/dist/sandbox/permission-call-grants.js +378 -0
  966. package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
  967. package/dist/sandbox/permission-call-grants.module.js +21 -0
  968. package/dist/sandbox/permission-call-types.d.ts +107 -0
  969. package/dist/sandbox/permission-call-types.js +1 -0
  970. package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
  971. package/dist/sandbox/permission-ceiling-writes.js +224 -0
  972. package/dist/sandbox/permission-config-publication.d.ts +76 -0
  973. package/dist/sandbox/permission-config-publication.js +339 -0
  974. package/dist/sandbox/permission-context-types.d.ts +64 -0
  975. package/dist/sandbox/permission-context-types.js +24 -0
  976. package/dist/sandbox/permission-facts.d.ts +206 -0
  977. package/dist/sandbox/permission-facts.js +635 -0
  978. package/dist/sandbox/permission-facts.module.d.ts +2 -0
  979. package/dist/sandbox/permission-facts.module.js +20 -0
  980. package/dist/sandbox/permission-instance-writes.d.ts +90 -0
  981. package/dist/sandbox/permission-instance-writes.js +305 -0
  982. package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
  983. package/dist/sandbox/permission-runtime-reports.js +354 -0
  984. package/dist/sandbox/permission-transitions.d.ts +31 -0
  985. package/dist/sandbox/permission-transitions.js +155 -0
  986. package/dist/sandbox/platform-full-access.d.ts +110 -0
  987. package/dist/sandbox/platform-full-access.js +198 -0
  988. package/dist/sandbox/providers.d.ts +56 -7
  989. package/dist/sandbox/providers.js +62 -9
  990. package/dist/sandbox/providers.module.d.ts +2 -0
  991. package/dist/sandbox/providers.module.js +19 -0
  992. package/dist/sandbox/request-not-sent.d.ts +13 -0
  993. package/dist/sandbox/request-not-sent.js +13 -0
  994. package/dist/sandbox/review/classifier.d.ts +137 -0
  995. package/dist/sandbox/review/classifier.js +440 -0
  996. package/dist/sandbox/review/index.d.ts +13 -0
  997. package/dist/sandbox/review/index.js +10 -0
  998. package/dist/sandbox/review/permission-candidate.d.ts +68 -0
  999. package/dist/sandbox/review/permission-candidate.js +312 -0
  1000. package/dist/sandbox/review/review.service.d.ts +166 -0
  1001. package/dist/sandbox/review/review.service.js +563 -0
  1002. package/dist/sandbox/review/rules.d.ts +87 -0
  1003. package/dist/sandbox/review/rules.js +5319 -0
  1004. package/dist/sandbox/review/types.d.ts +116 -0
  1005. package/dist/sandbox/review/types.js +48 -0
  1006. package/dist/sandbox/sandbox-file-reader.d.ts +52 -0
  1007. package/dist/sandbox/sandbox-file-reader.js +142 -0
  1008. package/dist/sandbox/sandbox.module.d.ts +3 -3
  1009. package/dist/sandbox/sandbox.module.js +39 -9
  1010. package/dist/sandbox/sandbox.service.d.ts +550 -134
  1011. package/dist/sandbox/sandbox.service.js +2306 -460
  1012. package/dist/sandbox/unreachable.d.ts +30 -0
  1013. package/dist/sandbox/unreachable.js +122 -0
  1014. package/dist/sandbox/use-context.d.ts +17 -0
  1015. package/dist/sandbox/use-context.js +1 -0
  1016. package/dist/schedules/calendar.d.ts +134 -0
  1017. package/dist/schedules/calendar.js +410 -0
  1018. package/dist/schedules/effective-settings.d.ts +22 -0
  1019. package/dist/schedules/effective-settings.js +18 -0
  1020. package/dist/schedules/errors.d.ts +8 -0
  1021. package/dist/schedules/errors.js +8 -0
  1022. package/dist/schedules/fire.d.ts +137 -0
  1023. package/dist/schedules/fire.js +708 -0
  1024. package/dist/schedules/grant-rules.d.ts +120 -0
  1025. package/dist/schedules/grant-rules.js +186 -0
  1026. package/dist/schedules/job-ids.d.ts +81 -0
  1027. package/dist/schedules/job-ids.js +95 -0
  1028. package/dist/schedules/pause.d.ts +9 -0
  1029. package/dist/schedules/pause.js +33 -0
  1030. package/dist/schedules/run-tracker.d.ts +76 -0
  1031. package/dist/schedules/run-tracker.js +321 -0
  1032. package/dist/schedules/scan.job.d.ts +45 -0
  1033. package/dist/schedules/scan.job.js +189 -0
  1034. package/dist/schedules/schedule-math.d.ts +73 -0
  1035. package/dist/schedules/schedule-math.js +294 -0
  1036. package/dist/schedules/scheduled-tasks.service.d.ts +362 -0
  1037. package/dist/schedules/scheduled-tasks.service.js +1253 -0
  1038. package/dist/schedules/schedules.controller.d.ts +72 -0
  1039. package/dist/schedules/schedules.controller.js +256 -0
  1040. package/dist/schedules/schedules.module.d.ts +16 -0
  1041. package/dist/schedules/schedules.module.js +61 -0
  1042. package/dist/schedules/schedules.schemas.d.ts +351 -0
  1043. package/dist/schedules/schedules.schemas.js +213 -0
  1044. package/dist/schedules/store.d.ts +86 -0
  1045. package/dist/schedules/store.js +410 -0
  1046. package/dist/schedules/store.module.d.ts +6 -0
  1047. package/dist/schedules/store.module.js +21 -0
  1048. package/dist/schedules/types.d.ts +110 -0
  1049. package/dist/schedules/types.js +1 -0
  1050. package/dist/schedules/unattended.d.ts +89 -0
  1051. package/dist/schedules/unattended.js +189 -0
  1052. package/dist/setup/kernel-checks.d.ts +91 -0
  1053. package/dist/setup/kernel-checks.js +296 -0
  1054. package/dist/setup/oauth-token-probe.d.ts +40 -0
  1055. package/dist/setup/oauth-token-probe.js +96 -0
  1056. package/dist/setup/redact-check.d.ts +18 -0
  1057. package/dist/setup/redact-check.js +46 -0
  1058. package/dist/setup/setup-check-registry.d.ts +86 -0
  1059. package/dist/setup/setup-check-registry.js +75 -0
  1060. package/dist/setup/setup-checks.controller.d.ts +28 -0
  1061. package/dist/setup/setup-checks.controller.js +78 -0
  1062. package/dist/setup/setup-checks.schemas.d.ts +38 -0
  1063. package/dist/setup/setup-checks.schemas.js +43 -0
  1064. package/dist/setup/setup-checks.service.d.ts +144 -0
  1065. package/dist/setup/setup-checks.service.js +683 -0
  1066. package/dist/setup/setup-guides.controller.d.ts +18 -0
  1067. package/dist/setup/setup-guides.controller.js +48 -0
  1068. package/dist/setup/setup-guides.schemas.d.ts +10 -0
  1069. package/dist/setup/setup-guides.schemas.js +6 -0
  1070. package/dist/setup/setup-guides.service.d.ts +126 -0
  1071. package/dist/setup/setup-guides.service.js +315 -0
  1072. package/dist/setup/setup.module.d.ts +8 -0
  1073. package/dist/setup/setup.module.js +31 -0
  1074. package/dist/shares/liveness.d.ts +59 -0
  1075. package/dist/shares/liveness.js +163 -0
  1076. package/dist/shares/revoke.d.ts +26 -0
  1077. package/dist/shares/revoke.js +43 -0
  1078. package/dist/shares/settings.d.ts +76 -0
  1079. package/dist/shares/settings.js +117 -0
  1080. package/dist/shares/share-code.d.ts +4 -0
  1081. package/dist/shares/share-code.js +28 -0
  1082. package/dist/shares/share-objects.d.ts +52 -0
  1083. package/dist/shares/share-objects.js +123 -0
  1084. package/dist/shares/share-open.controller.d.ts +35 -0
  1085. package/dist/shares/share-open.controller.js +107 -0
  1086. package/dist/shares/share-open.service.d.ts +107 -0
  1087. package/dist/shares/share-open.service.js +287 -0
  1088. package/dist/shares/share-previews.controller.d.ts +50 -0
  1089. package/dist/shares/share-previews.controller.js +115 -0
  1090. package/dist/shares/shares.controller.d.ts +34 -0
  1091. package/dist/shares/shares.controller.js +114 -0
  1092. package/dist/shares/shares.module.d.ts +8 -0
  1093. package/dist/shares/shares.module.js +41 -0
  1094. package/dist/shares/shares.schemas.d.ts +31 -0
  1095. package/dist/shares/shares.schemas.js +25 -0
  1096. package/dist/shares/shares.service.d.ts +182 -0
  1097. package/dist/shares/shares.service.js +553 -0
  1098. package/dist/shares/sweep.job.d.ts +72 -0
  1099. package/dist/shares/sweep.job.js +330 -0
  1100. package/dist/skills/agent-skills.controller.d.ts +48 -0
  1101. package/dist/skills/agent-skills.controller.js +131 -0
  1102. package/dist/skills/agent-skills.service.d.ts +258 -0
  1103. package/dist/skills/agent-skills.service.js +960 -0
  1104. package/dist/skills/catalog.d.ts +83 -71
  1105. package/dist/skills/catalog.js +144 -215
  1106. package/dist/skills/changes.controller.d.ts +6 -23
  1107. package/dist/skills/changes.controller.js +10 -57
  1108. package/dist/skills/changes.service.d.ts +69 -115
  1109. package/dist/skills/changes.service.js +249 -599
  1110. package/dist/skills/conversation-catalog.d.ts +52 -0
  1111. package/dist/skills/conversation-catalog.js +141 -0
  1112. package/dist/skills/invocable.controller.d.ts +1 -1
  1113. package/dist/skills/invocable.controller.js +2 -2
  1114. package/dist/skills/invocation-keys.d.ts +1 -1
  1115. package/dist/skills/invocation-keys.js +1 -1
  1116. package/dist/skills/invoke.d.ts +91 -6
  1117. package/dist/skills/invoke.js +288 -8
  1118. package/dist/skills/package.d.ts +0 -5
  1119. package/dist/skills/package.js +0 -14
  1120. package/dist/skills/skills.controller.d.ts +7 -14
  1121. package/dist/skills/skills.controller.js +9 -34
  1122. package/dist/skills/skills.module.js +20 -2
  1123. package/dist/skills/skills.schemas.d.ts +44 -0
  1124. package/dist/skills/skills.schemas.js +68 -0
  1125. package/dist/skills/skills.service.d.ts +76 -58
  1126. package/dist/skills/skills.service.js +277 -145
  1127. package/dist/skills/usable.d.ts +57 -7
  1128. package/dist/skills/usable.js +178 -36
  1129. package/dist/storage/storage.service.d.ts +2 -0
  1130. package/dist/storage/storage.service.js +12 -1
  1131. package/dist/themes/render-css.d.ts +13 -0
  1132. package/dist/themes/render-css.js +135 -0
  1133. package/dist/themes/theme-delivery.service.d.ts +36 -0
  1134. package/dist/themes/theme-delivery.service.js +116 -0
  1135. package/dist/themes/theme-state.d.ts +116 -0
  1136. package/dist/themes/theme-state.js +221 -0
  1137. package/dist/themes/theme-usage.d.ts +61 -0
  1138. package/dist/themes/theme-usage.js +98 -0
  1139. package/dist/themes/themes-public.controller.d.ts +33 -0
  1140. package/dist/themes/themes-public.controller.js +98 -0
  1141. package/dist/themes/themes.controller.d.ts +13 -0
  1142. package/dist/themes/themes.controller.js +38 -0
  1143. package/dist/themes/themes.module.d.ts +3 -0
  1144. package/dist/themes/themes.module.js +21 -0
  1145. package/dist/themes/themes.schemas.d.ts +3 -0
  1146. package/dist/themes/themes.schemas.js +2 -0
  1147. package/dist/themes/themes.service.d.ts +50 -0
  1148. package/dist/themes/themes.service.js +99 -0
  1149. package/dist/time-zone.d.ts +5 -0
  1150. package/dist/time-zone.js +19 -0
  1151. package/dist/tools/admin-connectors.d.ts +69 -0
  1152. package/dist/tools/admin-connectors.js +135 -0
  1153. package/dist/tools/approvals.controller.d.ts +5 -2
  1154. package/dist/tools/approvals.controller.js +19 -5
  1155. package/dist/tools/approvals.schemas.d.ts +23 -0
  1156. package/dist/tools/approvals.schemas.js +19 -0
  1157. package/dist/tools/approvals.service.d.ts +483 -17
  1158. package/dist/tools/approvals.service.js +1536 -33
  1159. package/dist/tools/builtin-names.d.ts +40 -23
  1160. package/dist/tools/builtin-names.js +77 -32
  1161. package/dist/tools/builtins/agent.js +5 -5
  1162. package/dist/tools/builtins/artifacts.d.ts +69 -0
  1163. package/dist/tools/builtins/artifacts.js +143 -0
  1164. package/dist/tools/builtins/ask-user.js +3 -2
  1165. package/dist/tools/builtins/builtin-tools.d.ts +29 -6
  1166. package/dist/tools/builtins/builtin-tools.js +111 -31
  1167. package/dist/tools/builtins/current-time.d.ts +26 -0
  1168. package/dist/tools/builtins/current-time.js +99 -0
  1169. package/dist/tools/builtins/image/generate.d.ts +62 -0
  1170. package/dist/tools/builtins/image/generate.js +591 -0
  1171. package/dist/tools/builtins/image/index.d.ts +2 -0
  1172. package/dist/tools/builtins/image/index.js +2 -0
  1173. package/dist/tools/builtins/image/paths.d.ts +12 -0
  1174. package/dist/tools/builtins/image/paths.js +26 -0
  1175. package/dist/tools/builtins/platform.d.ts +19 -4
  1176. package/dist/tools/builtins/platform.js +106 -19
  1177. package/dist/tools/builtins/sandbox/bash.d.ts +40 -3
  1178. package/dist/tools/builtins/sandbox/bash.js +279 -207
  1179. package/dist/tools/builtins/sandbox/common.d.ts +233 -47
  1180. package/dist/tools/builtins/sandbox/common.js +498 -153
  1181. package/dist/tools/builtins/sandbox/deliver.js +27 -58
  1182. package/dist/tools/builtins/sandbox/device-code.d.ts +40 -0
  1183. package/dist/tools/builtins/sandbox/device-code.js +57 -0
  1184. package/dist/tools/builtins/sandbox/device-owner.d.ts +13 -0
  1185. package/dist/tools/builtins/sandbox/device-owner.js +14 -0
  1186. package/dist/tools/builtins/sandbox/edit.js +48 -39
  1187. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +10 -0
  1188. package/dist/tools/builtins/sandbox/fetch-attachment.js +126 -0
  1189. package/dist/tools/builtins/sandbox/file-state.d.ts +31 -1
  1190. package/dist/tools/builtins/sandbox/file-state.js +33 -3
  1191. package/dist/tools/builtins/sandbox/glob.js +15 -9
  1192. package/dist/tools/builtins/sandbox/grep.js +13 -9
  1193. package/dist/tools/builtins/sandbox/index.d.ts +11 -5
  1194. package/dist/tools/builtins/sandbox/index.js +15 -5
  1195. package/dist/tools/builtins/sandbox/read.js +15 -9
  1196. package/dist/tools/builtins/sandbox/task-list.d.ts +12 -0
  1197. package/dist/tools/builtins/sandbox/task-list.js +136 -0
  1198. package/dist/tools/builtins/sandbox/task-output.d.ts +33 -40
  1199. package/dist/tools/builtins/sandbox/task-output.js +325 -201
  1200. package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -2
  1201. package/dist/tools/builtins/sandbox/task-stop.js +40 -29
  1202. package/dist/tools/builtins/sandbox/write.js +41 -33
  1203. package/dist/tools/builtins/schedules.d.ts +109 -0
  1204. package/dist/tools/builtins/schedules.js +947 -0
  1205. package/dist/tools/builtins/send-message.d.ts +1 -1
  1206. package/dist/tools/builtins/send-message.js +3 -3
  1207. package/dist/tools/builtins/skill-load.d.ts +56 -8
  1208. package/dist/tools/builtins/skill-load.js +186 -18
  1209. package/dist/tools/builtins/tool-search.d.ts +4 -7
  1210. package/dist/tools/builtins/tool-search.js +10 -13
  1211. package/dist/tools/builtins/web/extract.d.ts +2 -4
  1212. package/dist/tools/builtins/web/extract.js +3 -6
  1213. package/dist/tools/builtins/web/search.js +2 -4
  1214. package/dist/tools/connector-account-policies.d.ts +86 -0
  1215. package/dist/tools/connector-account-policies.js +220 -0
  1216. package/dist/tools/connector-content.js +1 -0
  1217. package/dist/tools/connectors.controller.d.ts +79 -9
  1218. package/dist/tools/connectors.controller.js +155 -17
  1219. package/dist/tools/connectors.schemas.d.ts +40 -0
  1220. package/dist/tools/connectors.schemas.js +46 -0
  1221. package/dist/tools/connectors.service.d.ts +124 -7
  1222. package/dist/tools/connectors.service.js +331 -24
  1223. package/dist/tools/credentials.d.ts +41 -0
  1224. package/dist/tools/credentials.js +150 -1
  1225. package/dist/tools/credentials.module.d.ts +7 -0
  1226. package/dist/tools/credentials.module.js +22 -0
  1227. package/dist/tools/device-op-resolver.d.ts +40 -0
  1228. package/dist/tools/device-op-resolver.js +131 -0
  1229. package/dist/tools/drift.d.ts +6 -2
  1230. package/dist/tools/drift.js +10 -5
  1231. package/dist/tools/elicitation.d.ts +2 -0
  1232. package/dist/tools/elicitation.js +1 -1
  1233. package/dist/tools/fixed-ask.d.ts +7 -0
  1234. package/dist/tools/fixed-ask.js +9 -0
  1235. package/dist/tools/git-asks.d.ts +113 -0
  1236. package/dist/tools/git-asks.js +174 -0
  1237. package/dist/tools/git-push-policy.d.ts +92 -0
  1238. package/dist/tools/git-push-policy.js +177 -0
  1239. package/dist/tools/info.d.ts +7 -11
  1240. package/dist/tools/info.js +8 -21
  1241. package/dist/tools/job-ids.d.ts +0 -4
  1242. package/dist/tools/job-ids.js +1 -6
  1243. package/dist/tools/network-asks.d.ts +122 -0
  1244. package/dist/tools/network-asks.js +233 -0
  1245. package/dist/tools/oauth/discovery.d.ts +38 -16
  1246. package/dist/tools/oauth/discovery.js +59 -33
  1247. package/dist/tools/oauth/flow.js +1 -1
  1248. package/dist/tools/oauth/tokens.d.ts +54 -7
  1249. package/dist/tools/oauth/tokens.js +87 -17
  1250. package/dist/tools/org-tool-switches.d.ts +19 -4
  1251. package/dist/tools/org-tool-switches.js +30 -13
  1252. package/dist/tools/permission-approval-jobs.d.ts +18 -0
  1253. package/dist/tools/permission-approval-jobs.js +92 -0
  1254. package/dist/tools/pipeline.d.ts +176 -22
  1255. package/dist/tools/pipeline.js +1194 -94
  1256. package/dist/tools/policy.d.ts +50 -13
  1257. package/dist/tools/policy.js +178 -58
  1258. package/dist/tools/questions.service.d.ts +50 -9
  1259. package/dist/tools/questions.service.js +128 -12
  1260. package/dist/tools/registry.d.ts +125 -56
  1261. package/dist/tools/registry.js +238 -235
  1262. package/dist/tools/tools.module.js +48 -9
  1263. package/dist/ui/admin-ui.controller.d.ts +56 -0
  1264. package/dist/ui/admin-ui.controller.js +192 -0
  1265. package/dist/ui/arrangement.d.ts +65 -0
  1266. package/dist/ui/arrangement.js +171 -0
  1267. package/dist/ui/embed-token.d.ts +2 -2
  1268. package/dist/ui/embed-token.js +66 -5
  1269. package/dist/ui/registry.d.ts +42 -17
  1270. package/dist/ui/registry.js +46 -14
  1271. package/dist/ui/slots.controller.d.ts +11 -0
  1272. package/dist/ui/slots.controller.js +25 -0
  1273. package/dist/ui/ui-stream.d.ts +20 -3
  1274. package/dist/ui/ui-stream.js +25 -7
  1275. package/dist/ui/ui.schemas.d.ts +70 -0
  1276. package/dist/ui/ui.schemas.js +65 -0
  1277. package/dist/ui/views.controller.d.ts +35 -49
  1278. package/dist/ui/views.controller.js +48 -70
  1279. package/dist/ui/views.d.ts +118 -19
  1280. package/dist/ui/views.js +257 -53
  1281. package/package.json +7 -3
  1282. package/src/migrations/0089_model_kinds_usage.sql +38 -0
  1283. package/src/migrations/0090_initial_passwords.sql +27 -0
  1284. package/src/migrations/0091_account_time_zone.sql +4 -0
  1285. package/src/migrations/0092_tools_default_on.sql +27 -0
  1286. package/src/migrations/0093_connected_environments.sql +37 -0
  1287. package/src/migrations/0094_environment_paths_idx.sql +7 -0
  1288. package/src/migrations/0095_environment_files_resets.sql +5 -0
  1289. package/src/migrations/0096_environment_demoted_default.sql +18 -0
  1290. package/src/migrations/0097_extension_installs_enabled_at.sql +16 -0
  1291. package/src/migrations/0098_single_provider_running_first.sql +41 -0
  1292. package/src/migrations/0099_channel_connection_guide_ack.sql +6 -0
  1293. package/src/migrations/0100_catalog_files.sql +13 -0
  1294. package/src/migrations/0101_marketplace_icons.sql +32 -0
  1295. package/src/migrations/0102_themes.sql +64 -0
  1296. package/src/migrations/0103_ui_theme_setting.sql +7 -0
  1297. package/src/migrations/0104_connector_tool_account_policies.sql +16 -0
  1298. package/src/migrations/0105_devices_rename.sql +136 -0
  1299. package/src/migrations/0106_setup_guides_v2.sql +10 -0
  1300. package/src/migrations/0107_extension_client_builds.sql +50 -0
  1301. package/src/migrations/0108_question_skipped.sql +6 -0
  1302. package/src/migrations/0109_audit_platform_idx.sql +5 -0
  1303. package/src/migrations/0110_usage_time_idx.sql +8 -0
  1304. package/src/migrations/0111_agent_skill_sharing.sql +22 -0
  1305. package/src/migrations/0112_skill_share_requests.sql +4 -0
  1306. package/src/migrations/0113_scheduled_tasks.sql +108 -0
  1307. package/src/migrations/0114_network_asks.sql +23 -0
  1308. package/src/migrations/0115_network_requests.sql +28 -0
  1309. package/src/migrations/0116_skills_default_on.sql +37 -0
  1310. package/src/migrations/0117_sandbox_tiers.sql +11 -0
  1311. package/src/migrations/0118_device_policy_ops.sql +6 -0
  1312. package/src/migrations/0119_outbox.sql +22 -0
  1313. package/src/migrations/0120_drop_usage_report_sweep.sql +7 -0
  1314. package/src/migrations/0121_drop_platform_migration_runs.sql +12 -0
  1315. package/src/migrations/0122_drop_scheduled_task_runs_rechecked_at.sql +5 -0
  1316. package/src/migrations/0123_pgvector.sql +27 -0
  1317. package/src/migrations/0124_conversation_source.sql +36 -0
  1318. package/src/migrations/0125_conversation_tree_stopped_at.sql +5 -0
  1319. package/src/migrations/0126_git_gateway.sql +10 -0
  1320. package/src/migrations/0127_git_push_policy.sql +12 -0
  1321. package/src/migrations/0128_scheduled_task_plugin_disabled.sql +10 -0
  1322. package/src/migrations/0129_connector_plugin_disabled.sql +5 -0
  1323. package/src/migrations/0130_auto_mode.sql +48 -0
  1324. package/src/migrations/0131_device_mode.sql +9 -0
  1325. package/src/migrations/0132_compact_runs.sql +6 -0
  1326. package/src/migrations/0133_project_root.sql +30 -0
  1327. package/src/migrations/0134_org_cloud_network_delta.sql +38 -0
  1328. package/src/migrations/0135_run_execution_claim.sql +2 -0
  1329. package/src/migrations/0136_run_recovery_cursor.sql +6 -0
  1330. package/src/migrations/0137_audit_org_idx.sql +5 -0
  1331. package/src/migrations/0138_plugin_install_status_no_upgrading.sql +18 -0
  1332. package/src/migrations/0139_retire_legacy_forms.sql +183 -0
  1333. package/src/migrations/0140_retire_history_forms.sql +148 -0
  1334. package/src/migrations/0141_install_ledger_promoted_rows.sql +36 -0
  1335. package/src/migrations/0142_backfill_event_fields.sql +74 -0
  1336. package/src/migrations/0143_backfill_model_call_fields.sql +105 -0
  1337. package/src/migrations/0144_retire_frozen_definition_keys.sql +163 -0
  1338. package/src/migrations/0145_org_network_allowances.sql +12 -0
  1339. package/src/migrations/0146_permission_authority_epochs.sql +6 -0
  1340. package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
  1341. package/src/migrations/0148_first_message_request_hash.sql +2 -0
  1342. package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
  1343. package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
  1344. package/src/migrations/0151_starting_execution_grants.sql +8 -0
  1345. package/src/migrations/0152_background_launch_identity.sql +66 -0
  1346. package/src/migrations/0153_background_cancel_requester.sql +13 -0
  1347. package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
  1348. package/src/migrations/0155_device_instance_generations.sql +30 -0
  1349. package/src/migrations/0156_device_owner_report.sql +7 -0
  1350. package/src/migrations/0157_legacy_retirement.sql +116 -0
  1351. package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
  1352. package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
  1353. package/src/migrations/0160_model_usage_image_kind.sql +10 -0
  1354. package/src/migrations/0161_file_shares.sql +35 -0
  1355. package/src/migrations/0162_permission_call_escalation.sql +9 -0
  1356. package/dist/background/status.d.ts +0 -35
  1357. package/dist/background/status.js +0 -57
  1358. package/dist/catalog/platform-migration.d.ts +0 -115
  1359. package/dist/catalog/platform-migration.js +0 -582
  1360. package/dist/conversations/job-ids.d.ts +0 -6
  1361. package/dist/conversations/job-ids.js +0 -6
  1362. package/dist/environments/access.d.ts +0 -41
  1363. package/dist/environments/access.js +0 -77
  1364. package/dist/environments/conversation-environments.d.ts +0 -61
  1365. package/dist/environments/conversation-environments.js +0 -170
  1366. package/dist/environments/dto.d.ts +0 -25
  1367. package/dist/environments/dto.js +0 -12
  1368. package/dist/environments/environments.controller.d.ts +0 -33
  1369. package/dist/environments/environments.controller.js +0 -110
  1370. package/dist/environments/environments.module.d.ts +0 -8
  1371. package/dist/environments/environments.module.js +0 -27
  1372. package/dist/environments/environments.service.d.ts +0 -153
  1373. package/dist/environments/environments.service.js +0 -541
  1374. package/dist/extensions/job-ids.d.ts +0 -6
  1375. package/dist/extensions/job-ids.js +0 -6
  1376. package/dist/infra/queue/add-job-once.d.ts +0 -14
  1377. package/dist/infra/queue/add-job-once.js +0 -16
  1378. package/dist/infra/queue/retired-schedulers.d.ts +0 -7
  1379. package/dist/infra/queue/retired-schedulers.js +0 -9
  1380. package/dist/orgs/job-ids.d.ts +0 -8
  1381. package/dist/orgs/job-ids.js +0 -8
  1382. package/dist/platform/redact-orgs.d.ts +0 -7
  1383. package/dist/platform/redact-orgs.js +0 -52
  1384. package/dist/runtime/context/legacy-text.d.ts +0 -22
  1385. package/dist/runtime/context/legacy-text.js +0 -37
  1386. package/dist/runtime/job-ids.d.ts +0 -10
  1387. package/dist/runtime/job-ids.js +0 -10
  1388. package/dist/runtime/retired-schedulers.d.ts +0 -7
  1389. package/dist/runtime/retired-schedulers.js +0 -31
  1390. package/dist/storage/job-ids.d.ts +0 -6
  1391. package/dist/storage/job-ids.js +0 -6
  1392. package/dist/tools/builtins/skill-write.d.ts +0 -59
  1393. package/dist/tools/builtins/skill-write.js +0 -244
  1394. package/dist/tools/legacy-data.d.ts +0 -34
  1395. package/dist/tools/legacy-data.js +0 -76
  1396. package/dist/tools/legacy-keys.d.ts +0 -51
  1397. package/dist/tools/legacy-keys.js +0 -115
@@ -7,21 +7,58 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
+ import { posix } from "node:path";
11
+ import { DEFAULT_SANDBOX_ROOTS, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
12
+ import { runOutsideTransaction } from "../infra/database/transaction-host.js";
13
+ import { createHeldOperations, createLegacyHeldProvider, withKernelGeneration, } from "./held-operations.js";
14
+ import { SandboxOperationAuthority } from "./operation-authority.js";
15
+ import { PermissionAdmissionStale, SandboxOperationIntents, } from "./operation-intents.js";
16
+ import { PermissionInstanceWrites } from "./permission-instance-writes.js";
17
+ /**
18
+ * The recorded kind of a definite pre-effect refusal: `not_sent` for a request refused before it
19
+ * was sent (`isDeviceRequestNotSent`; checked before `denied`, which it subclasses), else
20
+ * `denied` or `unsupported`.
21
+ */
22
+ const failureKindOf = (error) => isDeviceRequestNotSent(error)
23
+ ? "not_sent"
24
+ : isSandboxScopeDeniedError(error)
25
+ ? "denied"
26
+ : "unsupported";
27
+ /** The reservation fields a managed start's dispatch must match (its stable input). */
28
+ const backgroundBinding = (args, instanceId) => ({
29
+ taskId: args.taskId,
30
+ workingRoot: args.cwd,
31
+ outputPath: args.outputPath,
32
+ retainUntilMs: args.retainUntilMs,
33
+ instanceId,
34
+ });
10
35
  import { randomUUID } from "node:crypto";
11
- import { isFileSystemGoneError, isSandboxGoneError, } from "@capybara-hq/plugin-sdk";
36
+ import { isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnknownError, rootsOf, } from "@capybara-hq/plugin-sdk";
12
37
  import { Inject, Injectable } from "@nestjs/common";
13
38
  import { sql, } from "kysely";
14
- import { BackgroundTaskStore } from "../background/store.js";
15
- import { DEFAULT_MAX_COMMAND_SECONDS, DEFAULT_MAX_RUN_SECONDS, } from "../config/schema.js";
39
+ import { MANAGED_STOP_GRACE_MS } from "../background/managed.js";
40
+ import { deviceNotFound } from "../devices/errors.js";
16
41
  import { ApiError } from "../errors.js";
17
42
  import { readSandboxLimitOverride } from "../identity/settings.js";
18
43
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
19
44
  import { KernelDb } from "../infra/database/kernel-db.js";
20
45
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
21
- import { effectiveSandboxEgress, effectiveSandboxLimits, readOrgSettings, } from "../orgs/settings.service.js";
46
+ import { effectiveSandboxLimits } from "../orgs/settings.service.js";
47
+ import { isStorageError } from "../runtime/permission-context-errors.js";
22
48
  import { canonicalJson } from "../tools/canonical-json.js";
49
+ import { attachmentsDir } from "./attachments-path.js";
50
+ import { CloudPermissionSnapshots, } from "./cloud-permission-snapshot.js";
51
+ import { isKernelReadMethod, KernelReadNotAdmitted, KernelReadUnsupported, } from "./kernel-read.js";
23
52
  import { SandboxLeases, SandboxLockLostError, sandboxBusy, } from "./leases.js";
24
- import { SandboxProviders } from "./providers.js";
53
+ import { isCloudProvider, LegacyRetirementStore } from "./legacy-retirement.js";
54
+ import { ManagedDeviceContextFailed } from "./managed-device-context.js";
55
+ import { appliedOf, appliedWider, instanceLimitsJson, readInstanceLimits, sameApplied, sameAppliedExact, sameAppliedExactly, } from "./modes.js";
56
+ import { PermissionFacts } from "./permission-facts.js";
57
+ import { cloudReportOwed, cloudSupportOf } from "./permission-runtime-reports.js";
58
+ import { isInternalProvider, LOCAL_PROVIDER, providerForDevice, SandboxProviders, } from "./providers.js";
59
+ import { isDeviceRequestNotSent } from "./request-not-sent.js";
60
+ import { SandboxProviderUnreachableError } from "./unreachable.js";
61
+ export { deviceNotFound } from "../devices/errors.js";
25
62
  // Moved to leases.ts (phase C); re-exported for existing importers
26
63
  export { SANDBOX_LOCK_PREFIX, SANDBOX_LOCK_TTL_MS, SandboxLockLostError, sandboxBusy, } from "./leases.js";
27
64
  /** Margin (ms) of a holder record's TTL beyond the longest command: by then the in-sandbox limit has ended its commands. */
@@ -30,25 +67,97 @@ const HOLDER_TTL_MARGIN_MS = 10 * 60_000;
30
67
  const PATH_LEASE_WAIT_MS = 30_000;
31
68
  /** Time limit of one provider call in maintenance (suspend, destroy). */
32
69
  const SWEEP_OP_TIMEOUT_MS = 120_000;
70
+ /** How long a cloud device's lifecycle reconcile waits before the sweep tries it again (B-12). */
71
+ const RECONCILE_RETRY_SECONDS = 600;
72
+ /** Where the reconcile sweep goes on from (the last device id it visited; B-12). */
73
+ const RECONCILE_CURSOR_KEY = "capk:cloud-reconcile-cursor";
74
+ /** The bound on one cloud `permissionSupport` read under a lifecycle lease (B-15). */
75
+ const PERMISSION_SUPPORT_TIMEOUT_MS = 30_000;
33
76
  /** How long the suspension sweep holds the intent on a sandbox past `maxRunningMinutes` (ms). */
34
77
  const SWEEP_INTENT_WAIT_MS = 1000;
35
78
  /** Rows one sweep handles at most, and the provider calls it runs at once. */
36
79
  const SWEEP_BATCH = 200;
37
80
  const SWEEP_CONCURRENCY = 4;
38
- /** How long `destroyEnvironment` / `resetFileSystem` wait for the exclusive lease (running commands). */
81
+ /** How long `destroyDevice` / `resetFileSystem` wait for the exclusive lease (running commands). */
39
82
  const EXCLUSIVE_WAIT_MS = 10 * 60_000;
40
- /** The time limit of the exec that kills lost background tasks after a resume (ms). */
41
- const PENDING_KILL_TIMEOUT_MS = 30_000;
42
- /** A background task's session id as `echo $!` printed it; anything else is never put in a command. */
43
- const SID_RE = /^[1-9][0-9]{0,9}$/;
83
+ /** The time limit of one best-effort maintenance call and of one inline exact revoke (ms). */
84
+ const MAINTENANCE_CALL_TIMEOUT_MS = 30_000;
85
+ /** How many owed operation revokes a lifecycle holder delivers inline (the revoke jobs do the rest). */
86
+ const INLINE_REVOKE_LIMIT = 100;
87
+ const noticeKey = (deviceId, holder) => `capk:sandbox-notice:${deviceId}:${holder}`;
88
+ /** A stored {@link DeferredNotice}, or null (none, or not one). */
89
+ function parseDeferred(raw) {
90
+ if (raw === null)
91
+ return null;
92
+ try {
93
+ const v = JSON.parse(raw);
94
+ if (typeof v.seen !== "string")
95
+ return null;
96
+ return {
97
+ seen: v.seen,
98
+ fresh: v.fresh === true,
99
+ restarted: v.restarted === true,
100
+ filesReset: v.filesReset === true,
101
+ };
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ }
44
107
  /** The signal of one provider call in maintenance: aborted on timeout or when the lease is lost. */
45
108
  const opSignal = (lease) => AbortSignal.any([lease.signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]);
46
- /** The provider-side name of an environment's file system and instance. */
47
- export const environmentResourceName = (environmentId) => `cap-env-${environmentId}`;
48
- /** The environment is missing, deleted, or not in the caller's org (404; ids cannot be probed). */
49
- export const environmentNotFound = () => new ApiError("environment.not_found", "This environment does not exist or was deleted.");
50
- /** The environment's file system is gone at the provider (409); never replaced silently. */
51
- export const environmentFilesLost = () => new ApiError("environment.files_lost", "The environment's files are gone; reset its files from the environments page to start with an empty workspace.");
109
+ /** The provider-side name of a device's file system and instance. */
110
+ export const deviceResourceName = (deviceId) => `cap-device-${deviceId}`;
111
+ /**
112
+ * The device's file system is gone at the provider (409); never replaced silently. On a
113
+ * connected machine (`local`, details `[{ source: "local" }]`) the directory is the machine
114
+ * owner's: `capybara-device logout`, then `login` into the device, recreates it (ruling R24).
115
+ */
116
+ export const deviceFilesLost = (local = false) => local
117
+ ? new ApiError("device.files_lost", "The local device's directory is gone from its machine; run capybara-device logout, then capybara-device login into this device, on that machine to recreate it.", [{ source: "local" }])
118
+ : new ApiError("device.files_lost", "The device's files are gone; reset its files from the devices page to start with an empty workspace.");
119
+ /**
120
+ * A cloud sandbox provider refused to make (or move) an instance with the open public network
121
+ * (409; auto mode spec §4.2): a provider that cannot or is set not to offer it. The text is
122
+ * provider-neutral (hardening spec K5); the provider's own error goes only to the log: it may name
123
+ * the provider's settings.
124
+ */
125
+ export const sandboxOpenNetworkRefused = () => new ApiError("sandbox.open_network_refused", "The cloud sandbox provider refused to give this device the open network, so its sandbox was not created. An org admin can switch the organization's cloud network to an allowlist, with the device in sandbox mode (its owner switches it, or the org turns auto mode off), or a super admin can use a sandbox provider that offers the open network.");
126
+ /**
127
+ * A cloud sandbox provider failed to make a device's file system or instance for another reason
128
+ * (502): often its deployment config (image, runtime, network), sometimes a passing fault. The
129
+ * provider's own error goes only to the log.
130
+ */
131
+ export const sandboxCreateFailed = () => new ApiError("sandbox.create_failed", "The cloud sandbox provider could not create this device's sandbox. Retry; if it keeps failing, a super admin should check the sandbox extension's settings.");
132
+ /**
133
+ * What a failed `createFileSystem` / `create` / `update` of a cloud provider becomes: an abort,
134
+ * a gone error, an unreachable provider and a kernel error stay as they are (their callers and the
135
+ * tools handle them); any other error is logged (warn, redacted) and replaced by
136
+ * {@link sandboxOpenNetworkRefused} when `limits` ask for the open public network (the only
137
+ * network a provider's config refuses), else (a create) by {@link sandboxCreateFailed}; a failed
138
+ * `update` below the open network stays as it is. A kernel-internal provider (`@local`) keeps its
139
+ * own errors.
140
+ */
141
+ function providerRefusal(log, err, facts, limits, signal) {
142
+ if (signal.aborted ||
143
+ isInternalProvider(facts.provider) ||
144
+ isSandboxGoneError(err) ||
145
+ isFileSystemGoneError(err) ||
146
+ err instanceof SandboxProviderUnreachableError ||
147
+ err instanceof ApiError) {
148
+ return err;
149
+ }
150
+ // a provider that refuses the open network fails on it in either mode: auto always has it, a
151
+ // narrowed cloud device has it while the org's network is open
152
+ if (limits.network.kind === "open-public") {
153
+ log.warn("the sandbox provider refused an instance with the open public network; check the provider's network settings or switch the org's cloud network to the allowlist", { ...facts, err });
154
+ return sandboxOpenNetworkRefused();
155
+ }
156
+ if (facts.op === "update")
157
+ return err;
158
+ log.warn("the sandbox provider failed to create a device's sandbox", { ...facts, err });
159
+ return sandboxCreateFailed();
160
+ }
52
161
  /**
53
162
  * The row still records the instance `gone` (same handle and same `created_at`). Handles compare
54
163
  * canonically: a jsonb round trip reorders a multi-key handle's keys (final review m9).
@@ -76,28 +185,40 @@ function tagged(impl, tag, actor, before) {
76
185
  * Sandbox config problems to tell operators at startup (English log lines):
77
186
  * - `runtime.maxRunSeconds` below `sandbox.limits.maxCommandSeconds`: long commands are cut by the
78
187
  * run time limit (Ruling M20);
79
- * - `sandbox.limits.egress` is open but the current provider plugin has no `allowOpenEgress`: every
80
- * instance creation is refused.
81
- * With both time limits at their defaults (900 < 7200, a known trade-off) it is only info; warn
82
- * when an operator changed one and they still disagree.
188
+ * - the current provider plugin refuses the open public network (`refuseOpenNetwork: true` in its
189
+ * startup config) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
190
+ * keeps its org's cloud network, open by default, so turning auto mode off does not avoid it
191
+ * (auto mode hardening spec K3). Only the kill switch (`sandbox.limits.egress: none`) does.
192
+ * - `sandbox.limits.orgHosts: within` while the startup config does not turn auto mode off: the
193
+ * ceiling limits sandbox mode only, and auto mode (the default of every device) keeps the open
194
+ * network (org egress ceiling spec §D2). The admin console's runtime choice is not seen here.
195
+ * No run duration limit (`runtime.maxRunSeconds` 0, the default) cuts no command, so there is
196
+ * nothing to tell.
83
197
  */
84
198
  export function sandboxConfigWarnings(cfg, providerPlugin) {
85
199
  const out = [];
86
- if (cfg.sandbox.limits.egress === "open" && providerPlugin !== undefined) {
200
+ if (providerPlugin !== undefined && cfg.sandbox.limits.egress !== "none") {
87
201
  const pc = cfg.extensionConfig[providerPlugin];
88
- if (pc?.allowOpenEgress !== true) {
202
+ if (pc?.refuseOpenNetwork === true) {
89
203
  out.push({
90
204
  level: "warn",
91
- message: `sandbox.limits.egress is "open" but extensionConfig."${providerPlugin}".allowOpenEgress is not true: the ${providerPlugin} plugin refuses to create sandboxes with open egress; set allowOpenEgress to true (trusted environments only) or use "allowlist" or "none"`,
205
+ message: `extensionConfig."${providerPlugin}".refuseOpenNetwork is true: the ${providerPlugin} plugin refuses cloud devices on the open public network, which every device in auto mode and every sandbox-mode device of an organization whose cloudNetwork is open (the default) uses; set refuseOpenNetwork to false, or turn Full permission off (devices.fullAccess) and have every organization switch its cloudNetwork to the allowlist`,
92
206
  });
93
207
  }
94
208
  }
209
+ if (cfg.sandbox.limits.orgHosts === "within" &&
210
+ cfg.sandbox.limits.egress !== "none" &&
211
+ cfg.devices?.fullAccess !== "off") {
212
+ out.push({
213
+ level: "warn",
214
+ message: "sandbox.limits.orgHosts is within but devices.fullAccess is not off: the platform allowlist limits restricted execution only; devices on Full permission (allowed by default) still reach the open public network. Set devices.fullAccess to off (or turn Full permission off in the admin console) for a hard ceiling",
215
+ });
216
+ }
95
217
  const run = cfg.runtime.maxRunSeconds;
96
218
  const cmd = cfg.sandbox.limits.maxCommandSeconds;
97
- if (run < cmd) {
98
- const defaults = run === DEFAULT_MAX_RUN_SECONDS && cmd === DEFAULT_MAX_COMMAND_SECONDS;
219
+ if (run > 0 && run < cmd) {
99
220
  out.push({
100
- level: defaults ? "info" : "warn",
221
+ level: "warn",
101
222
  message: `runtime.maxRunSeconds (${run}) is less than sandbox.limits.maxCommandSeconds (${cmd}): sandbox commands are limited to the time left in the run, so commands longer than about ${run} seconds cannot finish; raise runtime.maxRunSeconds to at least ${cmd} if agents need long commands`,
102
223
  });
103
224
  }
@@ -106,10 +227,45 @@ export function sandboxConfigWarnings(cfg, providerPlugin) {
106
227
  /** No sandbox provider (503). */
107
228
  export const sandboxUnavailable = () => new ApiError("sandbox.unavailable", "Sandbox is not available in this deployment; install a sandbox plugin");
108
229
  /**
109
- * The environment's files are kept by a provider that is not the current one (503); its files are
230
+ * The device's files are kept by a provider that is not the current one (503); its files are
110
231
  * not migrated, so it stays unusable until that provider is back (spec §4.2 item 13).
111
232
  */
112
- const otherProvider = (provider) => new ApiError("environment.unavailable", `This environment's files are kept by the sandbox provider ${provider}, which is not the current provider; it can be used again once ${provider} is the deployment's sandbox provider`);
233
+ const otherProvider = (provider) => new ApiError("device.unavailable", `This device's files are kept by the sandbox provider ${provider}, which is not the current provider; it can be used again once ${provider} is the deployment's sandbox provider`);
234
+ /**
235
+ * An owner browse found no running instance of the device (409): the picker starts the device
236
+ * for its owner first ({@link SandboxService.ensureRunningForOwner}), so this is an instance that
237
+ * stopped in between (idle suspension) or one that could not be started; retrying starts it.
238
+ */
239
+ export const deviceNotRunning = () => new ApiError("device.not_running", "The device stopped before it could be read. Try again; it will be started first.");
240
+ /** The holder name of {@link SandboxService.ensureRunningForOwner}: no conversation holds it. */
241
+ const OWNER_START_HOLDER = "device-owner";
242
+ /**
243
+ * The device's old instance incarnation may still run legacy work that was never retired (503):
244
+ * the device stays unavailable until the provider confirms that incarnation destroyed, or for
245
+ * good when it is quarantined (permission runtime cutover 8.5). Never a retirement claim.
246
+ */
247
+ export class RetirementPendingError extends ApiError {
248
+ name = "RetirementPendingError";
249
+ }
250
+ export const retirementPending = () => new RetirementPendingError("device.unavailable", "This device is unavailable: background work started by an earlier version may still run on its previous instance, and that instance has not been confirmed destroyed. A cloud device becomes usable once its provider confirms the old instance destroyed.");
251
+ /**
252
+ * A local machine's old instance may still run legacy work, and a later boot of that machine is
253
+ * the evidence that ends it (503, 8.5): the person restarts the computer.
254
+ */
255
+ export const restartRequired = () => new RetirementPendingError("device.restart_required", "Background work started by an earlier version may still be running on this computer. Restart this computer to finish the upgrade, then try again.");
256
+ /**
257
+ * A cloud device's earlier instance may still run legacy work and no evidence the kernel can get
258
+ * will ever cover it (an incarnation replaced without a recorded confirmed destruction, or an
259
+ * unknown one it cannot clear) (503, 8.5): the owner deletes the device and creates it again.
260
+ */
261
+ export const recreateRequired = () => new RetirementPendingError("device.recreate_required", "Background work started by an earlier version may still be running on an earlier instance of this device, and that instance can no longer be verified as destroyed. Delete this device and create it again.");
262
+ /**
263
+ * A local machine's old instance may still run legacy work, and the computer never reported a
264
+ * boot identity, so not even a restart can prove it ended (503, 8.5): the owner replaces the
265
+ * device. A deleted device's obligations never block a new one.
266
+ */
267
+ export const replaceRequired = () => new RetirementPendingError("device.replace_required", "Background work started by an earlier version may still be running on this computer, and it cannot prove a restart. Delete this device and connect the computer again as a new device.");
268
+ const isRetirementPending = (err) => err instanceof RetirementPendingError;
113
269
  const abortReason = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
114
270
  function sleep(ms, signal) {
115
271
  return new Promise((resolve, reject) => {
@@ -139,58 +295,6 @@ async function inPool(items, limit, fn) {
139
295
  };
140
296
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
141
297
  }
142
- /**
143
- * The kernel's sandbox service over the `sandbox@2` provider, keyed by **environment** (spec
144
- * 2026-11-07-environments-design §4.2, §5.1): one file system kept until the environment is
145
- * deleted, plus one instance attached to it that comes and goes; all conversations bound to the
146
- * environment (and their sub-agents) share both.
147
- *
148
- * - **Lazy creation**: the first {@link withSandbox} creates the file system
149
- * (`createFileSystem`, name `cap-env-<environmentId>`) and then the instance on it; state lives
150
- * in `environment_instances`. A file system gone at the provider is never replaced silently:
151
- * `fs_status` becomes `lost` and uses fail with `environment.files_lost` until
152
- * {@link resetFileSystem}.
153
- * - **Leases** (phase C, spec §10, {@link SandboxLeases}), keyed by environment id: using an
154
- * instance recorded `running` with the current provider takes a **shared** lease, so up to
155
- * `sandbox.maxConcurrentCommands` holders (all sessions of the environment) run at once. Every
156
- * lifecycle change (create, resume, rebuild, suspend, destroy, reset) takes the **exclusive**
157
- * lease, alone; a caller that needs one on the use path sets the intent so new shared leases wait
158
- * for it, and downgrades to a shared lease to run its own command once the instance runs.
159
- * Waiting is capped at `sandbox.lockWaitSeconds` (`sandbox.busy`); two replicas using it for the
160
- * first time at once still build only one.
161
- * - **Fencing**: exclusive holders read `generation` and compare-and-increment it with every state
162
- * write ({@link SandboxLockLostError}); every acquisition (shared ones too) bumps it first, so a
163
- * stale exclusive holder's later writes fail. Shared holders write nothing else but
164
- * `last_used_at` (monotonic). A lost lease aborts the signal passed to `fn` and to maintenance
165
- * provider calls.
166
- * - **Suspension and destruction**: the sweeps (`SandboxSweepJobs`, crons) call
167
- * {@link suspendIdle} / {@link destroyInactive}; they try the exclusive lease once and skip an
168
- * environment with any holder; one past `maxRunningMinutes` gets the intent for a short window
169
- * (about a second) so the suspension can get in when its commands end. Inactivity destroys only
170
- * the instance (files kept); a deleted environment or org loses its files too.
171
- * - **Transparent recovery**: a suspended instance is resumed on next use; when `resume` returns
172
- * `gone`, the instance was destroyed, or `fn` throws `SandboxGoneError` (retried once), a new
173
- * instance is created on the kept files and `restarted` is true. Several holders hitting `gone`
174
- * together rebuild once: the others find the new instance.
175
- * - **Takeover** (spec §10.5; environments spec §4.2): every holder records itself in
176
- * `capk:sandbox-holders:<env>` (again before each `exec`) and its commands carry its lease token
177
- * as `tag`. An acquirer that finds a record without a live lease (a crashed holder) kills only
178
- * that holder's commands (`killTagged`): other conversations of the environment may be running
179
- * commands. `killAll` runs only under the exclusive lease, before the downgrade, on an instance
180
- * this holder just resumed from `suspended` (nobody else can hold it; a provider that keeps
181
- * memory across a pause brings old commands back); it also covers crashed holders' records,
182
- * which it claims. A freshly created instance has nothing to kill. Failures are only warned (the
183
- * in-sandbox time limit is the backstop).
184
- * - **Instance identity**: a holder that hits `gone` names the instance by its handle and the
185
- * row's `created_at` (set by the fenced write after each `create`); the handle alone is the same
186
- * after a rebuild on providers whose handle is the instance name (sandbox-docker).
187
- *
188
- * Files kept by another provider than the current one make the environment unusable
189
- * (`environment.unavailable`) until that provider is back; deleting it still works while that
190
- * provider is loaded ({@link SandboxProviders.lookup}). Without a provider {@link available} is false and
191
- * uses throw `sandbox.unavailable` (503). No in-process state: replicas share it through PG and
192
- * Redis.
193
- */
194
298
  let SandboxService = class SandboxService {
195
299
  db;
196
300
  redis;
@@ -198,62 +302,224 @@ let SandboxService = class SandboxService {
198
302
  providers;
199
303
  config;
200
304
  log;
201
- background;
305
+ facts;
306
+ operationIntents;
307
+ authority;
308
+ instanceWrites;
309
+ retirement;
310
+ snapshots;
202
311
  constructor(db,
203
312
  /** The record of the instance each holder last used (`capk:sandbox-seen:…`). */
204
313
  redis, leases,
205
- /** The `sandbox@2` provider (read at every call: providers are ready after the extension load). */
206
- providers, config, log,
207
- /** Background tasks lost while their process may live on (killed after a resume). */
208
- background) {
314
+ /** The providers (read at every call: providers are ready after the extension load). */
315
+ providers, config, log, facts, operationIntents, authority, instanceWrites,
316
+ /** The retirement obligations every lifecycle acquisition is gated on (8.5). */
317
+ retirement,
318
+ /** The cloud snapshot writer's reconcile, for the lifecycle reconcile of marked devices (B-12). */
319
+ snapshots) {
209
320
  this.db = db;
210
321
  this.redis = redis;
211
322
  this.leases = leases;
212
323
  this.providers = providers;
213
324
  this.config = config;
214
325
  this.log = log;
215
- this.background = background;
326
+ this.facts = facts;
327
+ this.operationIntents = operationIntents;
328
+ this.authority = authority;
329
+ this.instanceWrites = instanceWrites;
330
+ this.retirement = retirement;
331
+ this.snapshots = snapshots;
216
332
  }
217
333
  /** Poll interval while waiting for a lease (the leases' own). */
218
334
  get pollMs() {
219
335
  return this.leases.pollMs;
220
336
  }
221
- /** Whether there is a sandbox provider. */
222
- get available() {
223
- return this.providers.current() !== undefined;
337
+ /**
338
+ * Whether there is a cloud sandbox provider (a loaded `sandbox@2` extension). For gates that have
339
+ * no device yet (tool listing, skill files); a call on a device asks
340
+ * {@link availableFor}.
341
+ */
342
+ get cloudAvailable() {
343
+ return this.providers.cloud() !== undefined;
344
+ }
345
+ /** Whether the device's provider is there (`@local` registered, or a cloud provider). */
346
+ async availableFor(deviceId) {
347
+ return (await this.providerOf(deviceId)) !== undefined;
348
+ }
349
+ /**
350
+ * The provider the device works with, read from its row ({@link providerForDevice});
351
+ * a missing row (or one of another org, with `orgId`) reads as a cloud device, whose use
352
+ * then fails as not found.
353
+ */
354
+ async providerOf(deviceId, orgId) {
355
+ const row = await this.db
356
+ .selectFrom("devices")
357
+ .select("provider")
358
+ .where("id", "=", deviceId)
359
+ .$if(orgId !== undefined, (q) => q.where("org_id", "=", orgId))
360
+ .executeTakeFirst();
361
+ return providerForDevice(this.providers, row?.provider ?? null);
362
+ }
363
+ /** {@link providerOf}, or `sandbox.unavailable` (503) without it. */
364
+ async require(deviceId, orgId) {
365
+ const p = await this.providerOf(deviceId, orgId);
366
+ if (!p)
367
+ throw sandboxUnavailable();
368
+ return p;
224
369
  }
225
- /** Concurrent holders of one environment (`sandbox.maxConcurrentCommands`, read at every use). */
370
+ /** Concurrent holders of one device (`sandbox.maxConcurrentCommands`, read at every use). */
226
371
  get cap() {
227
372
  return this.config.get().sandbox.maxConcurrentCommands;
228
373
  }
229
374
  /**
230
- * The org's effective sandbox limits (spec §8.4): the deployment's `sandbox.limits`, egress
231
- * narrowed by the org setting `sandboxEgress` (Ruling M19), cpu / memory per the super admin's
232
- * org override (C19 / Ruling M16). Instances are created with them; phase 1 environments use
233
- * them unchanged.
375
+ * The effective device policy of a device (auto mode spec §4.3): the platform's switch and the
376
+ * org's settings with the device's own mode (a local device's reported one, read fresh; a cloud
377
+ * device and a missing one have none). Without `deviceId`: an org-level policy with no choice.
234
378
  */
235
- async orgLimits(orgId) {
379
+ async devicePolicy(device) {
380
+ return this.facts.devicePolicy(device);
381
+ }
382
+ /** The device's source (`local` for a connected machine, else `cloud`); cloud when unknown. */
383
+ async deviceSource(device) {
384
+ if (device.deviceId === undefined)
385
+ return "cloud";
386
+ const row = await this.db
387
+ .selectFrom("devices")
388
+ .select("source")
389
+ .where("id", "=", device.deviceId)
390
+ .where("org_id", "=", device.orgId)
391
+ .executeTakeFirst();
392
+ return row?.source === "local" ? "local" : "cloud";
393
+ }
394
+ /**
395
+ * The device's effective sandbox limits (spec §8.4; auto mode spec §4.2): the deployment's
396
+ * `sandbox.limits` resources, cpu / memory per the super admin's org override (C19 / Ruling
397
+ * M16), the effective mode and the network ({@link devicePolicy}). A local device always gets the
398
+ * sandbox-mode allowlist: its device intersects it with its own list in sandbox mode and ignores
399
+ * it in auto mode. `opts.policy` / `opts.source`: what the caller already read (avoids the
400
+ * policy and source queries).
401
+ */
402
+ async deviceLimits(device, opts = {}) {
236
403
  const cfg = this.config.get().sandbox;
237
- const egress = effectiveSandboxEgress(cfg.limits, (await readOrgSettings(this.db.db, orgId)).sandboxEgress);
238
- const sized = effectiveSandboxLimits({ ...cfg.limits, ...egress }, await readSandboxLimitOverride(this.db.db, orgId));
404
+ const [policy, override, source] = await Promise.all([
405
+ opts.policy ?? this.devicePolicy(device),
406
+ readSandboxLimitOverride(this.db.db, device.orgId),
407
+ opts.source ?? this.deviceSource(device),
408
+ ]);
409
+ const local = source === "local";
410
+ const network = local
411
+ ? { kind: "allowlist", hosts: [...policy.localAllowedDomains] }
412
+ : policy.network;
413
+ return effectiveSandboxLimits({
414
+ cpu: cfg.limits.cpu,
415
+ memoryMb: cfg.limits.memoryMb,
416
+ diskMb: cfg.limits.diskMb,
417
+ // a local exec carries the allowed mode (the machine cuts its own choice to it); a cloud
418
+ // instance runs its device's mode (the narrowing switch included)
419
+ mode: local ? policy.allowedMode : policy.mode,
420
+ network: { kind: network.kind, hosts: [...network.hosts] },
421
+ }, override);
422
+ }
423
+ /**
424
+ * The org's sandbox-mode limits ({@link deviceLimits} with the sandbox-mode allowlist and mode
425
+ * `sandbox`): what a local device's sandbox mode may reach at most, so what a network grant,
426
+ * approval or request is checked against.
427
+ */
428
+ async ceilingLimits(orgId) {
429
+ const [policy, override] = await Promise.all([
430
+ this.devicePolicy({ orgId }),
431
+ readSandboxLimitOverride(this.db.db, orgId),
432
+ ]);
433
+ const cfg = this.config.get().sandbox;
434
+ return effectiveSandboxLimits({
435
+ cpu: cfg.limits.cpu,
436
+ memoryMb: cfg.limits.memoryMb,
437
+ diskMb: cfg.limits.diskMb,
438
+ mode: "sandbox",
439
+ network: { kind: "allowlist", hosts: [...policy.localAllowedDomains] },
440
+ }, override);
441
+ }
442
+ /**
443
+ * The limits state of a device's instance for its page (auto mode spec §4.2), read without a
444
+ * lease: `applied` is what the instance or file system was made with or updated to (null:
445
+ * unknown, or no instance yet), `effective` what it should run with now.
446
+ * `pendingNextUse`: a cloud instance exists and differs; its next use applies the new limits
447
+ * (files kept). `pendingFilesReset`: the provider fixes limits at its file system
448
+ * (`limitsApplyAt: "fileSystem"`) and cannot `update` them, so only a file reset applies them.
449
+ * A local device (its machine gets the mode and network with each command) is never pending, and
450
+ * its `applied` is null. `opts.policy`: the device's effective policy when the caller already
451
+ * read it ({@link devicePolicy}).
452
+ */
453
+ async limitsState(device, opts = {}) {
454
+ const [policy, row, p] = await Promise.all([
455
+ opts.policy ?? this.devicePolicy(device),
456
+ this.db
457
+ .selectFrom("device_instances")
458
+ .select(["provider", "status", "handle", "fs_status", "instance_limits"])
459
+ .where("device_id", "=", device.deviceId)
460
+ .where("org_id", "=", device.orgId)
461
+ .executeTakeFirst(),
462
+ this.providerOf(device.deviceId, device.orgId),
463
+ ]);
464
+ const effective = appliedOf({
465
+ mode: policy.mode,
466
+ network: policy.network,
467
+ });
468
+ if (p === undefined || p.plugin === LOCAL_PROVIDER || row === undefined) {
469
+ return { applied: null, effective, pendingNextUse: false, pendingFilesReset: false };
470
+ }
471
+ const rec = readInstanceLimits(row.instance_limits);
472
+ const differs = row.provider === p.plugin && !sameApplied(rec.applied, effective);
473
+ const fsBound = differs && row.fs_status === "ready" && this.fsBound(p, rec, effective);
474
+ const hasInstance = row.handle !== null && (row.status === "running" || row.status === "suspended");
239
475
  return {
240
- cpu: sized.cpu,
241
- memoryMb: sized.memoryMb,
242
- diskMb: sized.diskMb,
243
- egress: sized.egress,
244
- allowHosts: sized.allowHosts,
476
+ applied: rec.applied,
477
+ effective,
478
+ pendingNextUse: differs && !fsBound && hasInstance,
479
+ pendingFilesReset: fsBound,
245
480
  };
246
481
  }
247
482
  /**
248
- * The environment's instance state as shown to people (read only, no lease): `running` /
483
+ * Whether a provider whose limits are fixed at its file system cannot apply `effective`
484
+ * without a file reset: it has no `update`, or its `update` already answered `recreate` for it.
485
+ */
486
+ fsBound(p, rec, effective) {
487
+ if (p.impl.limitsApplyAt !== "fileSystem")
488
+ return false;
489
+ return p.impl.update === undefined || sameApplied(rec.unapplied, effective);
490
+ }
491
+ /**
492
+ * Whether the running instance of `row` must get `want` before use (auto mode spec §4.2): a
493
+ * cloud instance whose recorded mode or network kind differs, or whose recorded limits are more
494
+ * permissive than `want` in any dimension (a host-only narrowing too, spec §124; a host-only
495
+ * widening still reaches instances created afterwards), unless only a file reset could apply it
496
+ * ({@link fsBound}). A provider bound to its file system still goes through the exclusive lease
497
+ * once for a narrowing, so `applyLimits` records it as `unapplied` (the device is then unprobed
498
+ * until the reset, never silently supported). `want` null: a local device (the mode travels
499
+ * with each command).
500
+ */
501
+ mustApply(row, p, want) {
502
+ if (want === null)
503
+ return false;
504
+ const rec = readInstanceLimits(row.instance_limits);
505
+ const target = appliedOf(want);
506
+ const wider = appliedWider(rec.applied, target);
507
+ if (sameApplied(rec.applied, target) && !wider)
508
+ return false;
509
+ if (!this.fsBound(p, rec, target))
510
+ return true;
511
+ return wider && !sameAppliedExact(rec.unapplied, target);
512
+ }
513
+ /**
514
+ * The device's instance state as shown to people (read only, no lease): `running` /
249
515
  * `suspended` and the last use. No instance, a destroyed one, or one stuck in `creating` (being
250
516
  * created, or a failed create the next use retries) is null.
251
517
  */
252
- async status(orgId, environmentId) {
518
+ async status(orgId, deviceId) {
253
519
  const row = await this.db
254
- .selectFrom("environment_instances")
520
+ .selectFrom("device_instances")
255
521
  .select(["status", "last_used_at"])
256
- .where("environment_id", "=", environmentId)
522
+ .where("device_id", "=", deviceId)
257
523
  .where("org_id", "=", orgId)
258
524
  .executeTakeFirst();
259
525
  if (!row || (row.status !== "running" && row.status !== "suspended"))
@@ -261,46 +527,59 @@ let SandboxService = class SandboxService {
261
527
  return { status: row.status, lastUsedAt: row.last_used_at };
262
528
  }
263
529
  /**
264
- * The instance the environment records now (its `created_at`), while it has one that runs or is
530
+ * The instance the device records now (its `created_at`), while it has one that runs or is
265
531
  * suspended; null otherwise. Read without a lease: a caller inside `withSandbox` reads the
266
532
  * instance its own lease keeps.
267
533
  */
268
- async currentInstance(environmentId) {
534
+ async currentInstance(deviceId) {
269
535
  const row = await this.db
270
- .selectFrom("environment_instances")
271
- .select(["status", "handle", "created_at"])
272
- .where("environment_id", "=", environmentId)
536
+ .selectFrom("device_instances")
537
+ .select(["status", "handle", "created_at", "provider"])
538
+ .where("device_id", "=", deviceId)
273
539
  .executeTakeFirst();
274
540
  if (!row || row.handle === null)
275
541
  return null;
276
542
  if (row.status !== "running" && row.status !== "suspended")
277
543
  return null;
278
- return { createdAt: row.created_at };
544
+ return { createdAt: row.created_at, provider: row.provider };
279
545
  }
280
546
  /**
281
- * Runs `fn` on the environment's instance only while it runs the instance created at
547
+ * Runs `fn` on the device's instance only while it runs the instance created at
282
548
  * `instance.createdAt` (background tasks, spec 2026-11-05-background-bash-design §4.3). It never
283
549
  * creates, resumes or rebuilds one: an instance that is missing, suspended, being created or
284
550
  * destroyed (or recorded with another provider) is `not_running`, one that records another
285
551
  * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a `withSandbox`
286
- * holder does (its tag on every exec, crashed holders' commands killed), and `last_used_at`
287
- * moves forward when it ends. Waits for the lease up to `sandbox.lockWaitSeconds`
552
+ * holder does (its tag on every exec, crashed holders' operations revoked exactly), and
553
+ * `last_used_at` moves forward when it ends. Waits for the lease up to `sandbox.lockWaitSeconds`
288
554
  * (`sandbox.busy`); `signal` (optional) ends the wait with its abort reason. The signal passed
289
555
  * to `fn` aborts with `signal` or when the lease is lost. Errors of `fn` (`SandboxGoneError`
290
556
  * too) are thrown as they are.
291
557
  */
292
- async ifRunning(environmentId, instance, fn, signal = new AbortController().signal) {
293
- const p = this.require();
294
- const env = environmentId;
558
+ async ifRunning(deviceId,
559
+ /**
560
+ * `exactRef`: an exact-ref managed drain (status, stop, the revoke worker), allowed on an
561
+ * incarnation under a retirement obligation; every other caller (legacy SID polls, stops and
562
+ * reads, staged browse) is refused there with a {@link RetirementPendingError} (8.5).
563
+ */
564
+ instance, fn, signal = new AbortController().signal) {
565
+ return this.ifRunningAs(deviceId, instance, fn, signal, false);
566
+ }
567
+ /**
568
+ * {@link ifRunning}; `use` (staged owner browse) also refuses a device carrying the B1
569
+ * reconcile marker under the shared lease, before any provider call (B-11).
570
+ */
571
+ async ifRunningAs(deviceId, instance, fn, signal, use) {
572
+ const p = await this.require(deviceId);
573
+ const env = deviceId;
295
574
  const deadline = Date.now() + this.config.get().sandbox.lockWaitSeconds * 1000;
296
575
  const token = randomUUID();
297
576
  for (;;) {
298
577
  if (signal.aborted)
299
578
  throw abortReason(signal);
300
579
  const row = await this.db
301
- .selectFrom("environment_instances")
580
+ .selectFrom("device_instances")
302
581
  .selectAll()
303
- .where("environment_id", "=", env)
582
+ .where("device_id", "=", env)
304
583
  .executeTakeFirst();
305
584
  if (!row)
306
585
  return { kind: "not_running", status: "gone" };
@@ -309,17 +588,32 @@ let SandboxService = class SandboxService {
309
588
  }
310
589
  if (!this.usable(row, p, null))
311
590
  return { kind: "not_running", status: row.status };
591
+ // an incarnation that may still run unretired legacy work: no SID signal, no new exec or
592
+ // admission there; only exact-ref managed drains go on (I1)
593
+ if (!instance.exactRef && (await this.retirement.hasUnresolved(env)))
594
+ throw retirementPending();
595
+ // staged owner browse never reaches an instance whose binding is not installed (B-8): the
596
+ // device admits nothing there, and only a use's exclusive holder binds it
597
+ if (use && !(await this.bound(p, env)))
598
+ return { kind: "not_running", status: row.status };
312
599
  // the instance this check saw: its handle plus `created_at` (never `generation`, which
313
600
  // every lease bumps)
314
601
  const want = { handle: row.handle, createdAt: row.created_at.getTime() };
315
602
  const lease = await this.leases.tryShared(env, this.cap, token);
316
603
  if (lease) {
317
- const e = await this.asShared({ orgId: row.org_id, environmentId: env }, p, lease, (r) => this.usable(r, p, null) && isInstance(r, want), signal);
604
+ const e = await this.asShared({ orgId: row.org_id, deviceId: env }, p, lease, (r) => this.usable(r, p, null) && isInstance(r, want), signal, !instance.exactRef, use ? "reconciled" : "none");
318
605
  if (e) {
319
606
  try {
320
607
  const impl = tagged(p.impl, lease.token, undefined, () => this.register(env, lease.token));
321
608
  const sig = AbortSignal.any([signal, lease.signal]);
322
- return { kind: "ran", value: await fn(impl, e.handle, sig) };
609
+ try {
610
+ return { kind: "ran", value: await fn(impl, e.handle, sig) };
611
+ }
612
+ catch (err) {
613
+ if (isFileSystemGoneError(err))
614
+ throw await this.filesGone(env, p, e);
615
+ throw err;
616
+ }
323
617
  }
324
618
  finally {
325
619
  await this.leave(env, e);
@@ -334,15 +628,15 @@ let SandboxService = class SandboxService {
334
628
  }
335
629
  }
336
630
  /**
337
- * A short lease on one path of the environment around the kernel's own read-modify-write of
631
+ * A short lease on one path of the device around the kernel's own read-modify-write of
338
632
  * that file (spec §10.4); waits up to 30 s, then throws `SandboxPathBusyError`. Its `signal`
339
633
  * aborts when a renewal finds it lost.
340
634
  */
341
- pathLease(environmentId, path, signal) {
342
- return this.leases.pathLease(environmentId, path, signal, PATH_LEASE_WAIT_MS);
635
+ pathLease(deviceId, path, signal) {
636
+ return this.leases.pathLease(deviceId, path, signal, PATH_LEASE_WAIT_MS);
343
637
  }
344
638
  /**
345
- * Runs `fn` on the environment's instance: take a lease → make sure the instance runs (file
639
+ * Runs `fn` on the device's instance: take a lease → make sure the instance runs (file
346
640
  * system, create / resume / rebuild, under the exclusive lease) → `fn` under a shared lease →
347
641
  * update `last_used_at` → release.
348
642
  * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
@@ -353,57 +647,337 @@ let SandboxService = class SandboxService {
353
647
  * - When `fn` throws `SandboxGoneError` (the instance is gone) the instance is rebuilt on the
354
648
  * kept files (or the one another holder rebuilt is taken) and `fn` runs once more with
355
649
  * `restarted: true`; a second `gone` is thrown. Other errors are thrown as they are.
356
- * - Lost files throw `environment.files_lost` (409).
650
+ * - Lost files throw `device.files_lost` (409), also when `fn` throws
651
+ * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
357
652
  * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
358
653
  * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
359
654
  */
655
+ /** Trusted staging only. The callback receives no exec, browsing or lifecycle methods. */
656
+ async withPreparation(ctx, purpose, roots, fn, signal) {
657
+ return this.withSandboxUse(ctx, async () => {
658
+ throw new Error("Preparation callback was not installed");
659
+ }, signal, undefined, (h, provider, info, sig) => this.prepareFor(ctx, h, provider, info, purpose, roots, fn, sig));
660
+ }
661
+ async prepareFor(ctx, h, provider, info, purpose, roots, fn, sig) {
662
+ if (!provider.prepare)
663
+ throw new SandboxPermissionUnsupportedError("Trusted preparation is unavailable on this provider");
664
+ const prepare = provider.prepare.bind(provider);
665
+ const operation = async () => {
666
+ const authority = await runOutsideTransaction(() => this.authority.resolve(ctx, "stat", sig));
667
+ // attachments: exactly the one directory FetchAttachment writes for the call's root
668
+ // conversation, derived by the same helper, nothing else under the attachments root
669
+ const base = purpose === "skills"
670
+ ? info.roots.skills
671
+ : attachmentsDir(info.roots, authority.rootConversationId);
672
+ if (roots.length === 0 ||
673
+ roots.some((root) => posix.normalize(root) !== root || (root !== base && !root.startsWith(`${base}/`))))
674
+ throw new SandboxScopeDeniedError("Preparation roots must stay inside the trusted purpose directory");
675
+ const operationId = randomUUID();
676
+ return prepare(h, parseSandboxPreparationScope({
677
+ operationId,
678
+ deviceId: ctx.deviceId,
679
+ purpose,
680
+ writeRoots: [...roots],
681
+ tag: operationId,
682
+ }), sig);
683
+ };
684
+ return fn({
685
+ readFile: async (path, opts) => (await operation()).readFile(path, {
686
+ ...opts,
687
+ signal: AbortSignal.any([sig, opts.signal]),
688
+ }),
689
+ writeFile: async (path, data, signal) => (await operation()).writeFile(path, data, AbortSignal.any([sig, signal])),
690
+ stat: async (path, signal) => (await operation()).stat(path, AbortSignal.any([sig, signal])),
691
+ }, sig);
692
+ }
693
+ /** Owner browse scopes never manufacture a conversation or Full consent. */
694
+ async withBrowse(ctx, fn, signal) {
695
+ await this.authority.resolveBrowse(ctx, signal);
696
+ const row = await this.readRow(ctx);
697
+ if (!row)
698
+ throw deviceNotRunning();
699
+ const entry = await this.require(ctx.deviceId, ctx.orgId);
700
+ const result = await this.ifRunningAs(ctx.deviceId, { createdAt: row.created_at }, async (provider, h, sig) => {
701
+ if (!provider.browse)
702
+ throw new SandboxPermissionUnsupportedError("Owner browsing is unavailable on this provider");
703
+ const browse = provider.browse.bind(provider);
704
+ const call = async (method, input, s, invoke) => {
705
+ const combined = AbortSignal.any([sig, s]);
706
+ const intent = await this.operationIntents.admitBrowse(ctx, {
707
+ provider: entry.plugin,
708
+ providerVersion: entry.version ?? "internal-v2",
709
+ generation: String(row.created_at.getTime()),
710
+ }, method, input, combined);
711
+ const admitted = await this.operationIntents.claimBrowse(ctx, intent.operation_id);
712
+ combined.throwIfAborted();
713
+ try {
714
+ const operation = await browse(h, parseSandboxBrowseScope(admitted.scope), combined);
715
+ const value = await invoke(operation, combined);
716
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, admitted.execution_id, value));
717
+ return value;
718
+ }
719
+ catch (error) {
720
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
721
+ throw error;
722
+ }
723
+ };
724
+ return fn({
725
+ stat: (path, s) => call("stat", { path }, s, (p, signal) => p.stat(path, signal)),
726
+ list: (path, opts) => call("list", { path, limit: opts.limit }, opts.signal, (p, signal) => p.list(path, { limit: opts.limit, signal })),
727
+ scan: (base, opts) => call("scan", { base }, opts.signal, (p, signal) => p.scan(base, { signal })),
728
+ }, sig);
729
+ }, signal, true);
730
+ if (result.kind !== "ran")
731
+ throw deviceNotRunning();
732
+ return result.value;
733
+ }
734
+ /**
735
+ * Makes the device's instance run for its owner (permission activation L2, Hook 3), before an
736
+ * owner browse ({@link withBrowse}) of a device that may be stopped: the owner, membership and
737
+ * browsing ceiling checks of the browse first (`resolveBrowse`), then the lifecycle `enter` a
738
+ * use takes (the exclusive lease creates or resumes the instance through the retirement gate,
739
+ * the B-11 reconcile marker, the B-8 binding, `maxRunningSandboxes` and fencing), and the lease
740
+ * is left at once. No conversation holds it and nothing runs in it; what the start caused is
741
+ * not marked seen, so each conversation's next use still learns of it.
742
+ */
743
+ async ensureRunningForOwner(ctx, signal) {
744
+ await this.authority.resolveBrowse(ctx, signal);
745
+ const p = await this.require(ctx.deviceId, ctx.orgId);
746
+ const use = {
747
+ orgId: ctx.orgId,
748
+ deviceId: ctx.deviceId,
749
+ holderConversationId: OWNER_START_HOLDER,
750
+ actor: { accountId: ctx.accountId, conversationId: OWNER_START_HOLDER },
751
+ };
752
+ const e = await this.enter(use, p, signal, null, () => this.wantedLimits(use, p));
753
+ await this.leave(ctx.deviceId, e);
754
+ }
755
+ /**
756
+ * Makes the device's instance run for a managed call before its permission review reads the
757
+ * device's facts: the lifecycle `enter` the call's own use takes (the exclusive lease creates
758
+ * or resumes the instance through the retirement gate, the binding, the limits and fencing, and
759
+ * records a cloud instance's permission evidence), then the lease is left at once. Nothing runs
760
+ * in it; what the start caused is kept for the holder's next use to tell (as a silent use).
761
+ */
762
+ async ensureRunning(use, signal) {
763
+ const p = await this.require(use.deviceId, use.orgId);
764
+ const e = await this.enter(use, p, signal, null, () => this.wantedLimits(use, p));
765
+ try {
766
+ await this.deferNotice(use.deviceId, use.holderConversationId, e);
767
+ }
768
+ finally {
769
+ await this.leave(use.deviceId, e);
770
+ }
771
+ }
772
+ /**
773
+ * A run start's kernel read of the bound project (permission activation L2, Hook 1): the use
774
+ * a tool call's would be (the instance made or resumed, the read silent for the holder), whose
775
+ * provider stats, reads and lists only, each call a kernel read admitted and claimed on its own
776
+ * (`SandboxOperationIntents.admitKernelRead`: the run's current claim with its run still
777
+ * `queued`, a random operation id, the profile scope narrowed to the root, its `AGENTS.md` and
778
+ * its `.agents/skills`). Any other method is refused before admission. Only
779
+ * `ProjectKnowledgeService` calls this: no tool context, Platform operation or route has it.
780
+ */
781
+ async withKernelRead(ctx, read, fn, signal) {
782
+ const c = read.claim;
783
+ if (read.purpose !== "project_root" ||
784
+ c.orgId !== ctx.orgId ||
785
+ c.conversationId !== ctx.holderConversationId ||
786
+ c.runId !== ctx.actor.runId ||
787
+ ctx.actor.conversationId !== ctx.holderConversationId)
788
+ throw new SandboxScopeDeniedError("The kernel read does not match its run start");
789
+ return this.withSandboxUse(ctx, fn, signal, undefined, undefined, read);
790
+ }
791
+ async withOperations(ctx, invocation, fn, signal) {
792
+ return this.withSandboxUse(ctx, fn, signal, invocation);
793
+ }
360
794
  async withSandbox(ctx, fn, signal) {
361
- const p = this.require();
362
- const env = ctx.environmentId;
795
+ return this.withSandboxUse(ctx, fn, signal);
796
+ }
797
+ async withSandboxUse(ctx, fn, signal, invocation, trusted, kernelRead) {
798
+ const p = await this.require(ctx.deviceId, ctx.orgId);
799
+ const env = ctx.deviceId;
363
800
  const holder = ctx.holderConversationId;
364
- let e = await this.seenBy(env, holder, await this.enter(ctx, p, signal, null));
801
+ // decides the shared fast path only (read again before each shared lease is used): the
802
+ // exclusive path reads it again under the lease
803
+ const want = () => this.wantedLimits(ctx, p);
804
+ const seen = (x) => ctx.silent ? this.deferNotice(env, holder, x) : this.seenBy(env, holder, x);
805
+ let e = await seen(await this.enter(ctx, p, signal, null, want));
806
+ let left = false;
365
807
  try {
366
808
  try {
367
- return await this.runAs(e, ctx, p, fn, signal);
809
+ return await this.runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead);
368
810
  }
369
811
  catch (err) {
812
+ if (isFileSystemGoneError(err))
813
+ throw await this.filesGone(env, p, e);
814
+ if (isSandboxOperationOutcomeUnknownError(err) &&
815
+ isSandboxGoneError(err.cause)) {
816
+ // gone after a durable dispatch: the outcome stays unknown and the call is never retried
817
+ // under a new identity, but the gone instance is rebuilt on the kept files now, so the
818
+ // holder's next call runs on it and is told of the restart (its seen record still names
819
+ // the gone instance)
820
+ this.log.info("sandbox instance is gone after a dispatched operation; recreating", {
821
+ deviceId: env,
822
+ });
823
+ const gone = { handle: e.handle, createdAt: e.createdAt };
824
+ await this.leave(env, e);
825
+ left = true;
826
+ try {
827
+ const rebuilt = await this.enter(ctx, p, signal, gone, want);
828
+ await this.leave(env, rebuilt);
829
+ }
830
+ catch (rebuildErr) {
831
+ this.log.warn("cannot recreate the gone sandbox instance; the next use will", {
832
+ deviceId: env,
833
+ err: rebuildErr,
834
+ });
835
+ }
836
+ throw err;
837
+ }
370
838
  if (!isSandboxGoneError(err))
371
839
  throw err;
372
- this.log.info("sandbox instance is gone during use; recreating", { environmentId: env });
840
+ this.log.info("sandbox instance is gone during use; recreating", { deviceId: env });
373
841
  const gone = { handle: e.handle, createdAt: e.createdAt };
374
842
  const prev = e;
375
843
  await this.leave(env, prev);
376
- e = await this.seenBy(env, holder, await this.enter(ctx, p, signal, gone));
377
- return await this.runAs({ ...e, info: { fresh: true, restarted: true } }, ctx, p, fn, signal);
844
+ e = await seen(await this.enter(ctx, p, signal, gone, want));
845
+ // a reset seen on the first try still has to be told (it covers the restart)
846
+ const info = prev.info.filesReset
847
+ ? { fresh: true, restarted: false, filesReset: true }
848
+ : { fresh: true, restarted: true };
849
+ try {
850
+ return await this.runAs({ ...e, info }, ctx, p, fn, signal, invocation, trusted, kernelRead);
851
+ }
852
+ catch (err2) {
853
+ if (isFileSystemGoneError(err2))
854
+ throw await this.filesGone(env, p, e);
855
+ throw err2;
856
+ }
378
857
  }
379
858
  }
380
859
  finally {
381
- await this.leave(env, e);
860
+ if (!left)
861
+ await this.leave(env, e);
382
862
  }
383
863
  }
864
+ /**
865
+ * The limits a cloud device's instance must run with for this use (auto mode spec §4.2), read
866
+ * fresh; null for a local device (its machine gets the mode and network with each command).
867
+ * A scheduled run has no separate mode grant: the effective policy applies to it as to any use.
868
+ */
869
+ async wantedLimits(_ctx, p, _row) {
870
+ if (p.plugin === LOCAL_PROVIDER)
871
+ return null;
872
+ const policy = await this.devicePolicy(_ctx);
873
+ return await this.deviceLimits(_ctx, { policy, source: "cloud" });
874
+ }
875
+ /**
876
+ * Ruling R24: an operation on the held instance `e` found its file system gone. Records
877
+ * `fs_status = 'lost'` while the row still records that instance on its file system (the
878
+ * instance handle stays, so a reset still destroys it), moving the fence on, and returns
879
+ * `device.files_lost` to throw. Uses then fail until the files are reset (a connected
880
+ * machine: until a new login, which resets the row). A failed write only logs.
881
+ */
882
+ async filesGone(env, p, e) {
883
+ this.log.warn("device file system is gone at the provider; its files are lost", {
884
+ deviceId: env,
885
+ provider: p.plugin,
886
+ });
887
+ try {
888
+ await this.db
889
+ .updateTable("device_instances")
890
+ .set((eb) => ({ fs_status: "lost", generation: eb("generation", "+", 1) }))
891
+ .where("device_id", "=", env)
892
+ .where("fs_status", "=", "ready")
893
+ // `createdAt` is the row's value read back in milliseconds
894
+ .where(sql `date_trunc('milliseconds', created_at)`, "=", new Date(e.createdAt))
895
+ .execute();
896
+ }
897
+ catch (err) {
898
+ this.log.warn("cannot record lost device files", { deviceId: env, err });
899
+ }
900
+ return deviceFilesLost(p.plugin === LOCAL_PROVIDER);
901
+ }
902
+ /**
903
+ * A silent use ({@link SandboxUseContext.silent}) of `holder`: the seen record is left alone, so
904
+ * the holder's next ordinary use compares against the instance it last saw itself (and learns
905
+ * of a restart or a files reset since); a creation or rebuild this use caused is kept
906
+ * (`capk:sandbox-notice:<env>:<holder>`, merged with an earlier one for the same instance, same
907
+ * TTL as the seen record) for {@link seenBy} to tell. Best effort: a Redis error only logs.
908
+ */
909
+ async deferNotice(deviceId, holder, e) {
910
+ if (!e.info.fresh && !e.info.restarted && e.info.filesReset !== true)
911
+ return e;
912
+ try {
913
+ const ttl = (this.config.get().sandbox.limits.destroyAfterInactiveDays + 1) * 86_400;
914
+ const seen = `${e.createdAt}:${e.fsResets}`;
915
+ const key = noticeKey(deviceId, holder);
916
+ const mine = {
917
+ seen,
918
+ fresh: e.info.fresh,
919
+ restarted: e.info.restarted,
920
+ filesReset: e.info.filesReset === true,
921
+ };
922
+ // swapped in, then merged with an earlier silent use's notice for the same instance
923
+ const prev = parseDeferred(await this.redis.set(key, JSON.stringify(mine), "EX", ttl, "GET"));
924
+ if (prev !== null && prev.seen === seen) {
925
+ const merged = {
926
+ seen,
927
+ fresh: mine.fresh || prev.fresh,
928
+ restarted: mine.restarted || prev.restarted,
929
+ filesReset: mine.filesReset || prev.filesReset,
930
+ };
931
+ await this.redis.set(key, JSON.stringify(merged), "EX", ttl);
932
+ }
933
+ }
934
+ catch (err) {
935
+ this.log.warn("cannot keep the sandbox notice of a silent use", { deviceId, holder, err });
936
+ }
937
+ return e;
938
+ }
384
939
  /**
385
940
  * Records that `holder` uses the instance of `e` (`capk:sandbox-seen:<env>:<holder>` =
386
- * `<created_at>:<file system id>`, with a TTL of the inactivity destruction plus a day). When the
387
- * holder last used another instance on the same file system `e` is marked restarted; on another
388
- * file system (the files were reset) it is not. Best effort: a Redis error only logs.
941
+ * `<created_at>:<fs_resets>`, with a TTL of the inactivity destruction plus a day). When the
942
+ * holder last used another instance under the same reset count `e` is marked restarted (files
943
+ * kept); under another count it is marked `filesReset` instead. The count, not the provider's
944
+ * file system id, tells them apart: a provider may give the new file system the old id
945
+ * (sandbox-docker's volumes are named after the device). Best effort: a Redis error only
946
+ * logs.
389
947
  */
390
- async seenBy(environmentId, holder, e) {
948
+ async seenBy(deviceId, holder, entered) {
949
+ let e = entered;
391
950
  try {
392
951
  const ttl = (this.config.get().sandbox.limits.destroyAfterInactiveDays + 1) * 86_400;
393
- const seen = `${e.createdAt}:${e.fsId}`;
394
- const prev = await this.redis.set(`capk:sandbox-seen:${environmentId}:${holder}`, seen, "EX", ttl, "GET");
952
+ const seen = `${e.createdAt}:${e.fsResets}`;
953
+ // what a silent use of this holder caused on this same instance is told now
954
+ const deferred = parseDeferred(await this.redis.getdel(noticeKey(deviceId, holder)));
955
+ if (deferred !== null && deferred.seen === seen) {
956
+ e = {
957
+ ...e,
958
+ info: e.info.filesReset === true || deferred.filesReset
959
+ ? { fresh: e.info.fresh || deferred.fresh, restarted: false, filesReset: true }
960
+ : {
961
+ fresh: e.info.fresh || deferred.fresh,
962
+ restarted: e.info.restarted || deferred.restarted,
963
+ },
964
+ };
965
+ }
966
+ const prev = await this.redis.set(`capk:sandbox-seen:${deviceId}:${holder}`, seen, "EX", ttl, "GET");
395
967
  if (prev !== null && prev !== seen) {
396
- // `<createdAt>:<fsId>`: another file system (a reset) means a fresh start, not a restart on
397
- // kept files; another instance on the same file system is a restart
398
- const sameFiles = prev.slice(prev.indexOf(":") + 1) === e.fsId;
399
- if (sameFiles !== e.info.restarted) {
400
- return { ...e, info: { fresh: e.info.fresh, restarted: sameFiles } };
968
+ // `<createdAt>:<fsResets>`: another reset count means the files were reset since; another
969
+ // instance under the same count is a restart on kept files
970
+ const sameFiles = prev.slice(prev.indexOf(":") + 1) === String(e.fsResets);
971
+ if (!sameFiles) {
972
+ return { ...e, info: { fresh: e.info.fresh, restarted: false, filesReset: true } };
401
973
  }
974
+ if (!e.info.restarted)
975
+ return { ...e, info: { fresh: e.info.fresh, restarted: true } };
402
976
  }
403
977
  }
404
978
  catch (err) {
405
979
  this.log.warn("cannot record the sandbox instance a holder uses", {
406
- environmentId,
980
+ deviceId,
407
981
  holder,
408
982
  err,
409
983
  });
@@ -411,37 +985,301 @@ let SandboxService = class SandboxService {
411
985
  return e;
412
986
  }
413
987
  /** Runs `fn` as the holder `e`: its tag and the caller's actor on every exec, its lease's signal. */
414
- runAs(e, ctx, p, fn, signal) {
988
+ async runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead) {
415
989
  const sig = AbortSignal.any([signal, e.lease.signal]);
416
- const env = ctx.environmentId;
417
- const impl = tagged(p.impl, e.lease.token, ctx.actor, () => this.register(env, e.lease.token));
418
- return fn(e.handle, impl, e.info, sig);
990
+ if (trusted)
991
+ return trusted(e.handle, p.impl, { ...e.info, roots: rootsOf(e.handle) }, sig);
992
+ const env = ctx.deviceId;
993
+ if (kernelRead)
994
+ return fn(e.handle, this.kernelReadProvider(e, ctx, p, kernelRead, sig), { ...e.info, roots: rootsOf(e.handle) }, sig);
995
+ let ordinal = 0;
996
+ // a cloud provider's background starts are told the held instance's kernel generation
997
+ const held = p.binder ? p.impl : withKernelGeneration(p.impl, String(e.createdAt));
998
+ const impl = invocation
999
+ ? createHeldOperations(held, e.handle, sig, async (method, input, invoke, preflight) => {
1000
+ const identity = { ...invocation, ordinal: ordinal++ };
1001
+ sig.throwIfAborted();
1002
+ await this.register(env, e.lease.token);
1003
+ const refreshPending = () => runOutsideTransaction(() => this.operationIntents.pending(ctx, identity, {
1004
+ provider: p.plugin,
1005
+ providerVersion: p.version ?? "internal-v2",
1006
+ generation: String(e.createdAt),
1007
+ }, method, input, e.lease.token, sig));
1008
+ const pending = await refreshPending();
1009
+ // An acknowledged start returns its recorded exact ref; it never dispatches again.
1010
+ if (pending.state === "background-running" && pending.execution_ref)
1011
+ return parseSandboxExecutionRef(pending.execution_ref);
1012
+ if (pending.state === "completed")
1013
+ return (await this.operationIntents.result(pending));
1014
+ let current;
1015
+ try {
1016
+ current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1017
+ }
1018
+ catch (error) {
1019
+ if (!(error instanceof PermissionAdmissionStale))
1020
+ throw error;
1021
+ await refreshPending();
1022
+ current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1023
+ }
1024
+ // Kernel checks on the admitted scope come before any dispatch state is written.
1025
+ if (preflight &&
1026
+ current.state !== "completed" &&
1027
+ current.state !== "background-running") {
1028
+ try {
1029
+ await preflight(parseSandboxOperationScope(current.scope), sig);
1030
+ }
1031
+ catch (error) {
1032
+ if (current.state === "admitted" &&
1033
+ (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error))) {
1034
+ const kind = failureKindOf(error);
1035
+ await runOutsideTransaction(() => this.operationIntents.refusePreDispatch(ctx, identity, {
1036
+ kind,
1037
+ message: error.message,
1038
+ }));
1039
+ }
1040
+ throw error;
1041
+ }
1042
+ }
1043
+ const admitted = ["dispatching", "started-or-unknown"].includes(pending.state)
1044
+ ? await runOutsideTransaction(() => this.operationIntents.claimReconciliation(ctx, identity, {
1045
+ provider: p.plugin,
1046
+ providerVersion: p.version ?? "internal-v2",
1047
+ generation: String(e.createdAt),
1048
+ }, method, input, e.lease.token))
1049
+ : await runOutsideTransaction(() => this.operationIntents.claimDispatch(ctx, identity, e.lease.token, method === "backgroundStart"
1050
+ ? backgroundBinding(input, e.handle.id)
1051
+ : undefined));
1052
+ if (admitted.state === "revoked")
1053
+ throw admitted.outcome_unknown
1054
+ ? new SandboxOperationOutcomeUnknownError("The background task was stopped before its start was confirmed; it is not started again and its cancellation is owed")
1055
+ : new SandboxScopeDeniedError("The background task was stopped or settled before it launched; nothing was started");
1056
+ if (admitted.state === "background-running" && admitted.execution_ref)
1057
+ return parseSandboxExecutionRef(admitted.execution_ref);
1058
+ if (admitted.state === "completed")
1059
+ return (await this.operationIntents.result(admitted));
1060
+ sig.throwIfAborted();
1061
+ let result;
1062
+ try {
1063
+ result = await invoke(parseSandboxOperationScope(admitted.scope), sig);
1064
+ }
1065
+ catch (error) {
1066
+ if (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error)) {
1067
+ if (["dispatching", "started-or-unknown"].includes(pending.state)) {
1068
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1069
+ throw new SandboxOperationOutcomeUnknownError("The recorded operation remains unknown; changed runtime authority cannot prove it had no effect", { cause: error });
1070
+ }
1071
+ const kind = failureKindOf(error);
1072
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, {
1073
+ $failure: { kind, message: error.message },
1074
+ }));
1075
+ throw error;
1076
+ }
1077
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1078
+ // The machine's files are gone (R24): the operation stays unknown, and the caller still
1079
+ // records the files lost so later calls fail without reaching the machine.
1080
+ if (isFileSystemGoneError(error))
1081
+ throw error;
1082
+ // A transport/gone error after durable dispatch cannot justify a new identity retry.
1083
+ throw new SandboxOperationOutcomeUnknownError("The operation outcome must be reconciled with its recorded identity", { cause: error });
1084
+ }
1085
+ // The provider has returned: storage/serialization errors cannot establish denial.
1086
+ if (method === "backgroundStart") {
1087
+ try {
1088
+ await runOutsideTransaction(() => this.operationIntents.acknowledgeBackground(admitted.operation_id, admitted.execution_id, result, e.handle.id));
1089
+ }
1090
+ catch (error) {
1091
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1092
+ throw new SandboxOperationOutcomeUnknownError("The start returned but could not be acknowledged; reconcile the same identity", { cause: error });
1093
+ }
1094
+ return result;
1095
+ }
1096
+ try {
1097
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, result));
1098
+ }
1099
+ catch (error) {
1100
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1101
+ throw new SandboxOperationOutcomeUnknownError("The operation returned but its result could not be retained; reconcile the same identity", { cause: error });
1102
+ }
1103
+ return result;
1104
+ })
1105
+ : createLegacyHeldProvider(p.impl, e.lease.token, ctx.actor, () => this.register(env, e.lease.token));
1106
+ const contextEvidence = invocation?.contextEvidence
1107
+ ? await this.heldContextEvidence(ctx, p, e)
1108
+ : undefined;
1109
+ const info = {
1110
+ ...e.info,
1111
+ roots: rootsOf(e.handle),
1112
+ ...(contextEvidence && { contextEvidence }),
1113
+ };
1114
+ if (invocation?.beforeUser)
1115
+ await invocation.beforeUser({
1116
+ prepare: (purpose, roots, stage) => this.prepareFor(ctx, e.handle, p.impl, info, purpose, roots, stage, sig),
1117
+ }, info, sig);
1118
+ return fn(e.handle, impl, info, sig);
1119
+ }
1120
+ /**
1121
+ * The held provider of a kernel read ({@link withKernelRead}): every call admitted and claimed
1122
+ * as its own kernel read, then dispatched inline under the held lease, as an owner browse's
1123
+ * call is ({@link withBrowse}). Exec, writes and scans are refused before any admission.
1124
+ */
1125
+ kernelReadProvider(e, ctx, p, read, sig) {
1126
+ const env = ctx.deviceId;
1127
+ return createHeldOperations(p.impl, e.handle, sig, async (method, input, invoke) => {
1128
+ const path = input.path;
1129
+ if (!isKernelReadMethod(method) || typeof path !== "string")
1130
+ throw new SandboxScopeDeniedError("A kernel read only stats, reads and lists files");
1131
+ const given = input;
1132
+ sig.throwIfAborted();
1133
+ await this.register(env, e.lease.token);
1134
+ let admitted;
1135
+ try {
1136
+ const intent = await runOutsideTransaction(() => this.operationIntents.admitKernelRead(ctx, read, {
1137
+ provider: p.plugin,
1138
+ providerVersion: p.version ?? "internal-v2",
1139
+ generation: String(e.createdAt),
1140
+ }, method, given, e.lease.token, sig));
1141
+ admitted = await runOutsideTransaction(() => this.operationIntents.claimKernelRead(ctx, read, intent.operation_id, method, given));
1142
+ }
1143
+ catch (error) {
1144
+ // a refusal before dispatch: nothing reached the device
1145
+ if (sig.aborted || error instanceof KernelReadUnsupported)
1146
+ throw error;
1147
+ throw new KernelReadNotAdmitted(error);
1148
+ }
1149
+ sig.throwIfAborted();
1150
+ try {
1151
+ const value = await invoke(parseSandboxOperationScope(admitted.scope), sig);
1152
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, admitted.execution_id, value));
1153
+ return value;
1154
+ }
1155
+ catch (error) {
1156
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1157
+ throw error;
1158
+ }
1159
+ });
1160
+ }
1161
+ /**
1162
+ * The held evidence of a managed entry (B3), read once under the shared lease the holder already
1163
+ * has: the entered provider, the held handle's id and its generation (the row's `created_at`
1164
+ * milliseconds), the installed binding of exactly that generation and provider, the handle's
1165
+ * roots and the base working root admission resolves. Undefined without an installed binding or
1166
+ * with a project binding that no longer matches: the managed writer then refuses the call. The
1167
+ * writer validates every field again under the authority locks.
1168
+ */
1169
+ async heldContextEvidence(ctx, p, e) {
1170
+ try {
1171
+ return await this.readHeldContextEvidence(ctx, p, e);
1172
+ }
1173
+ catch (error) {
1174
+ // a storage failure reading the evidence fails the managed call as unrecorded, before any
1175
+ // callback, never as a provider error
1176
+ if (isStorageError(error))
1177
+ throw new ManagedDeviceContextFailed("unavailable");
1178
+ throw error;
1179
+ }
1180
+ }
1181
+ async readHeldContextEvidence(ctx, p, e) {
1182
+ const instanceGeneration = String(e.createdAt);
1183
+ // a cloud instance is named by its installed environment as the managed writer reads it
1184
+ // under the authority locks (B-15): current evidence, nothing unapplied, nothing wider than
1185
+ // desired; otherwise the device is unavailable for managed work, not a stale retry
1186
+ const cloud = (await this.deviceSource(ctx)) === "cloud";
1187
+ const applied = cloud
1188
+ ? await this.facts.readHeldEnvironment({ orgId: ctx.orgId, deviceId: ctx.deviceId })
1189
+ : null;
1190
+ if (cloud &&
1191
+ (applied === null ||
1192
+ applied.provider !== p.plugin ||
1193
+ applied.instanceGeneration !== instanceGeneration))
1194
+ return undefined;
1195
+ const binding = applied
1196
+ ? { binding_id: applied.bindingId }
1197
+ : await this.db
1198
+ .selectFrom("device_instance_bindings")
1199
+ .select("binding_id")
1200
+ .where("device_id", "=", ctx.deviceId)
1201
+ .where("instance_generation", "=", instanceGeneration)
1202
+ .where("provider", "=", p.plugin)
1203
+ .where("status", "=", "installed")
1204
+ .executeTakeFirst();
1205
+ if (!binding)
1206
+ return undefined;
1207
+ let workingRoot;
1208
+ try {
1209
+ workingRoot = await this.authority.workingRootFor({
1210
+ orgId: ctx.orgId,
1211
+ deviceId: ctx.deviceId,
1212
+ conversationId: ctx.holderConversationId,
1213
+ });
1214
+ }
1215
+ catch (error) {
1216
+ if (error instanceof ApiError)
1217
+ return undefined;
1218
+ throw error;
1219
+ }
1220
+ const roots = rootsOf(e.handle);
1221
+ return {
1222
+ deviceId: ctx.deviceId,
1223
+ provider: p.plugin,
1224
+ instanceId: e.handle.id,
1225
+ instanceGeneration,
1226
+ bindingId: binding.binding_id,
1227
+ roots: { workspace: roots.workspace, skills: roots.skills, tmp: roots.tmp },
1228
+ workingRoot,
1229
+ };
419
1230
  }
420
1231
  /**
421
1232
  * Becomes a holder: loops until it has a shared lease on a running instance, or `sandbox.busy`.
422
1233
  * An instance recorded `running` (with the current provider, not the `gone` instance) is used
423
1234
  * under a shared lease; otherwise the exclusive lease (with intent) makes it run and is
424
- * downgraded. One token serves both, so the waiter passes its own intent.
1235
+ * downgraded. One token serves both, so the waiter passes its own intent. `wantNow` reads the
1236
+ * limits this use wants ({@link wantedLimits}), again after each wait, so a mode narrowed
1237
+ * during the wait is never used with the old, wider limits.
425
1238
  */
426
- async enter(ctx, p, signal, gone) {
427
- const env = ctx.environmentId;
1239
+ async enter(ctx, p, signal, gone, wantNow) {
1240
+ const env = ctx.deviceId;
428
1241
  const deadline = Date.now() + this.config.get().sandbox.lockWaitSeconds * 1000;
429
1242
  const token = randomUUID();
430
1243
  let intent = false;
1244
+ let want = await wantNow();
431
1245
  try {
432
- for (;;) {
1246
+ for (let waited = false;; waited = true) {
433
1247
  if (signal.aborted)
434
1248
  throw abortReason(signal);
1249
+ if (waited)
1250
+ want = await wantNow();
435
1251
  const row = await this.readRow(ctx);
436
- if (this.usable(row, p, gone)) {
1252
+ // an instance whose mode or network must change goes through the exclusive lease
1253
+ const ready = (r) => this.usable(r, p, gone) && !this.mustApply(r, p, want);
1254
+ // a device with an unresolved retirement obligation is only entered through the
1255
+ // exclusive lease, whose gate retires the old incarnation or refuses (8.5); on the
1256
+ // staged path, so is an instance whose committed binding is not installed yet (B-8)
1257
+ if (!(await this.retirement.hasUnresolved(env)) &&
1258
+ ready(row) &&
1259
+ (await this.bound(p, env))) {
437
1260
  const lease = await this.leases.tryShared(env, this.cap, token);
438
1261
  if (lease) {
439
1262
  if (intent)
440
1263
  await this.clearIntent(env, token);
441
1264
  intent = false;
442
- const e = await this.asShared(ctx, p, lease, (r) => this.usable(r, p, gone), signal);
443
- if (e)
1265
+ // after a wait, the limits again under the lease: a mode narrowed just before the
1266
+ // holder we waited for let go is applied now (asShared checks `ready` with them)
1267
+ if (waited) {
1268
+ try {
1269
+ want = await wantNow();
1270
+ }
1271
+ catch (err) {
1272
+ await lease.release();
1273
+ throw err;
1274
+ }
1275
+ }
1276
+ // an obligation recorded while the shared lease was taken: null, back to the gate
1277
+ const e = await this.asShared(ctx, p, lease, ready, signal, true, "use");
1278
+ if (e) {
1279
+ // B-15: cloud evidence gone stale while the instance ran (a provider upgrade)
1280
+ await this.refreshCloudSupport(ctx, p, e, AbortSignal.any([signal, e.lease.signal]), false);
444
1281
  return e;
1282
+ }
445
1283
  }
446
1284
  }
447
1285
  else {
@@ -461,16 +1299,112 @@ let SandboxService = class SandboxService {
461
1299
  throw err;
462
1300
  }
463
1301
  }
1302
+ /**
1303
+ * Whether this device's instances record cloud evidence (B-15): a cloud device whose provider
1304
+ * (with a known version) reads its own permission support. A local device attests through its
1305
+ * installed binding instead.
1306
+ */
1307
+ async recordsCloudSupport(ctx, p) {
1308
+ return (p.plugin !== LOCAL_PROVIDER &&
1309
+ !p.binder &&
1310
+ p.version !== undefined &&
1311
+ typeof p.impl.permissionSupport === "function" &&
1312
+ (await this.deviceSource(ctx)) === "cloud");
1313
+ }
1314
+ /**
1315
+ * The provider's permission support of the held instance `handle`, read under the caller's
1316
+ * lifecycle lease within {@link PERMISSION_SUPPORT_TIMEOUT_MS}; undefined when it cannot be
1317
+ * read in time or is not a version 1 report. Never throws: missing evidence keeps the device
1318
+ * unprobed, it never fails the lifecycle step. A failure is logged once per instance generation
1319
+ * (`warnOnce`: a Redis marker shared by the replicas; without it, every failure is logged).
1320
+ */
1321
+ async cloudSupport(deviceId, p, handle, signal, warnOnce) {
1322
+ const read = p.impl.permissionSupport?.bind(p.impl);
1323
+ if (!read || p.version === undefined)
1324
+ return undefined;
1325
+ let failure;
1326
+ try {
1327
+ const sig = AbortSignal.any([signal, AbortSignal.timeout(PERMISSION_SUPPORT_TIMEOUT_MS)]);
1328
+ const report = cloudSupportOf(await read(handle, sig));
1329
+ if (report)
1330
+ return { provider: p.plugin, version: p.version, report };
1331
+ failure = { message: "cloud provider returned an invalid permission support report" };
1332
+ }
1333
+ catch (err) {
1334
+ if (signal.aborted)
1335
+ return undefined;
1336
+ failure = {
1337
+ message: "cannot read the cloud provider's permission support; device unprobed",
1338
+ err,
1339
+ };
1340
+ }
1341
+ // a log marker, not a lock: the previous value says whether this generation was logged (two
1342
+ // replicas racing may both log, which is harmless)
1343
+ const first = warnOnce === undefined ||
1344
+ (await this.redis
1345
+ .set(`capk:cloud-support-warned:${deviceId}:${warnOnce}`, "1", "EX", 86_400, "GET")
1346
+ .then((prev) => prev === null)
1347
+ .catch(() => true));
1348
+ if (first)
1349
+ this.log.warn(failure.message, {
1350
+ deviceId,
1351
+ provider: p.plugin,
1352
+ ...(failure.err !== undefined && { err: failure.err }),
1353
+ });
1354
+ return undefined;
1355
+ }
1356
+ /**
1357
+ * Under a lifecycle lease on the running instance `e`: records its cloud evidence again when
1358
+ * `force` (a resume) or when the recorded one is stale (another provider version, handle,
1359
+ * generation or applied limits; `cloudReportOwed`). The record is written only while the row
1360
+ * still holds the probed instance with the limits read before the probe, so a holder whose
1361
+ * lease was lost never overwrites newer evidence. A forced read that fails clears the recorded
1362
+ * identity (a resumed instance is unprobed until a read succeeds); any other failure leaves the
1363
+ * evidence as it was. Never throws.
1364
+ */
1365
+ async refreshCloudSupport(ctx, p, e, signal, force) {
1366
+ try {
1367
+ if (!(await this.recordsCloudSupport(ctx, p)))
1368
+ return;
1369
+ if (!force && !(await cloudReportOwed(this.db.db, ctx.deviceId, p.plugin, p.version)))
1370
+ return;
1371
+ const row = await this.db
1372
+ .selectFrom("device_instances")
1373
+ .select("instance_limits")
1374
+ .where("device_id", "=", ctx.deviceId)
1375
+ .executeTakeFirst();
1376
+ if (!row)
1377
+ return;
1378
+ const held = { ...e, limits: row.instance_limits };
1379
+ const support = await this.cloudSupport(ctx.deviceId, p, e.handle, signal, String(e.createdAt));
1380
+ if (support)
1381
+ await runOutsideTransaction(() => this.instanceWrites.recordCloudSupport(ctx.orgId, ctx.deviceId, held, support, signal));
1382
+ else if (force && !signal.aborted)
1383
+ await runOutsideTransaction(() => this.instanceWrites.clearCloudSupport(ctx.orgId, ctx.deviceId, held, p.plugin));
1384
+ }
1385
+ catch (err) {
1386
+ if (!signal.aborted)
1387
+ this.log.warn("cannot record the cloud instance's permission evidence", {
1388
+ deviceId: ctx.deviceId,
1389
+ provider: p.plugin,
1390
+ err,
1391
+ });
1392
+ }
1393
+ }
1394
+ /** No binder (protocol 2), or the current generation's binding is installed (B-8). */
1395
+ async bound(p, env) {
1396
+ return !p.binder || (await p.binder.status(env)) === "installed";
1397
+ }
464
1398
  async clearIntent(env, token) {
465
1399
  await this.leases
466
1400
  .clearIntent(env, token)
467
- .catch((err) => this.log.warn("cannot clear sandbox intent", { environmentId: env, err }));
1401
+ .catch((err) => this.log.warn("cannot clear sandbox intent", { deviceId: env, err }));
468
1402
  }
469
1403
  async readRow(ctx) {
470
1404
  const row = await this.db
471
- .selectFrom("environment_instances")
1405
+ .selectFrom("device_instances")
472
1406
  .selectAll()
473
- .where("environment_id", "=", ctx.environmentId)
1407
+ .where("device_id", "=", ctx.deviceId)
474
1408
  .executeTakeFirst();
475
1409
  if (row && row.org_id !== ctx.orgId)
476
1410
  throw this.foreign(ctx);
@@ -478,25 +1412,48 @@ let SandboxService = class SandboxService {
478
1412
  }
479
1413
  /** The instance row belongs to another org: reported as not found, so ids cannot be probed. */
480
1414
  foreign(_ctx) {
481
- return environmentNotFound();
1415
+ return deviceNotFound();
482
1416
  }
483
- /** Recorded running with the current provider, and not the instance found gone. */
1417
+ /**
1418
+ * Recorded running with the current provider on files not lost (lost ones go through the
1419
+ * exclusive path, which refuses them), and not the instance found gone.
1420
+ */
484
1421
  usable(row, p, gone) {
485
1422
  return (row !== undefined &&
486
1423
  row.status === "running" &&
1424
+ row.fs_status !== "lost" &&
487
1425
  row.provider === p.plugin &&
488
1426
  row.handle !== null &&
489
1427
  !isInstance(row, gone));
490
1428
  }
491
1429
  /**
492
1430
  * Under a just-taken shared lease: confirms the row is still `accept`ed (else releases and
493
- * returns null), records the holder and kills crashed holders' commands.
1431
+ * returns null), records the holder and revokes crashed holders' operations exactly.
1432
+ */
1433
+ async asShared(ctx, p, lease, accept, signal,
1434
+ /**
1435
+ * Refused (null) while the device has an unresolved retirement obligation, checked under the
1436
+ * lease and before anything is revoked or bumped; false only for exact-ref managed drains.
494
1437
  */
495
- async asShared(ctx, p, lease, accept, signal) {
496
- const env = ctx.environmentId;
1438
+ gated,
1439
+ /**
1440
+ * Checked under the lease (which the B1 snapshot writer's exclusive lease excludes) before
1441
+ * anything is revoked or bumped: `reconciled` and `use` refuse a device carrying the
1442
+ * reconcile marker (B-11); `use` (entering a holder) also returns null on the staged path
1443
+ * while the instance's binding is not installed, so the caller binds it exclusively (B-8).
1444
+ * `none` for background polls, stops and drains.
1445
+ */
1446
+ check = "none") {
1447
+ const env = ctx.deviceId;
497
1448
  try {
498
1449
  const row = await this.readRow(ctx);
499
- if (!accept(row)) {
1450
+ if (!accept(row) || (gated && (await this.retirement.hasUnresolved(env)))) {
1451
+ await lease.release();
1452
+ return null;
1453
+ }
1454
+ if (check !== "none")
1455
+ await this.facts.assertCloudReconciled(ctx.orgId, env);
1456
+ if (check === "use" && !(await this.bound(p, env))) {
500
1457
  await lease.release();
501
1458
  return null;
502
1459
  }
@@ -504,19 +1461,19 @@ let SandboxService = class SandboxService {
504
1461
  // expired unnoticed (a stalled sweep) then fails its next write instead of suspending or
505
1462
  // destroying the instance under this holder. Shared holders never compare it.
506
1463
  await this.db
507
- .updateTable("environment_instances")
1464
+ .updateTable("device_instances")
508
1465
  .set((eb) => ({ generation: eb("generation", "+", 1) }))
509
- .where("environment_id", "=", env)
1466
+ .where("device_id", "=", env)
510
1467
  .execute();
511
1468
  await this.register(env, lease.token);
512
- // other holders (any conversation of the environment) may be running: only the dead
513
- // holders' own commands are killed
514
- await this.killTagged(env, row.handle, p, await this.claim(env), signal, lease);
1469
+ // other holders (any conversation of the device) may be running: only the dead holders'
1470
+ // own operations are revoked, exactly
1471
+ await this.takeOver(env, this.incarnationOf(row), row.handle, p, signal, lease);
515
1472
  return {
516
1473
  lease,
517
1474
  handle: row.handle,
518
1475
  createdAt: row.created_at.getTime(),
519
- fsId: row.fs_handle?.id ?? "",
1476
+ fsResets: row.fs_resets,
520
1477
  info: { fresh: false, restarted: false },
521
1478
  };
522
1479
  }
@@ -528,31 +1485,40 @@ let SandboxService = class SandboxService {
528
1485
  }
529
1486
  /**
530
1487
  * Under a just-taken exclusive lease: makes the instance run (file system, create / resume /
531
- * rebuild when the recorded instance is the one found gone), kills leftovers, then downgrades to
532
- * a shared lease. Crashed holders' records are claimed here: on an instance just resumed from
533
- * `suspended` one `killAll` covers them and anything else left (nobody else holds the instance),
534
- * on a new instance there is nothing to kill, and on one that already ran their tags are killed.
1488
+ * rebuild when the recorded instance is the one found gone), revokes what crashed holders left,
1489
+ * then downgrades to a shared lease. A resumed instance's started-or-unknown operations were
1490
+ * revoked by `ensure` before its row said running; here the crashed holders' records are owed and
1491
+ * forgotten and every owed revoke of the instance is delivered (nothing is `killAll`ed).
535
1492
  */
536
1493
  async asExclusive(ctx, p, lease, gone, signal) {
537
- const env = ctx.environmentId;
1494
+ const env = ctx.deviceId;
538
1495
  const sig = AbortSignal.any([signal, lease.signal]);
539
1496
  try {
1497
+ // under the lease the B1 snapshot writer needs: a device carrying the reconcile marker gets
1498
+ // no create, resume, rebuild, limits change, retirement destroy or revocation (B-11)
1499
+ await this.facts.assertCloudReconciled(ctx.orgId, env);
540
1500
  const s = await this.ensure(ctx, p, lease, sig, gone);
541
- const dead = await this.claim(env);
542
- if (s.resumed)
543
- await this.killLeftovers(env, s.handle, p, sig, dead);
544
- else if (!s.info.fresh)
545
- await this.killTagged(env, s.handle, p, dead, signal, lease);
546
- if (s.resumed || s.info.fresh) {
547
- await this.killPendingTasks(env, s.handle, s.createdAt, p, lease.token, ctx.actor, sig);
548
- }
1501
+ // the dead holders' records are forgotten only after their revocation is owed (on a fresh
1502
+ // instance too: their intents still name them); a resume delivers what `ensure` revoked
1503
+ await this.takeOver(env, { provider: p.plugin, generation: String(s.createdAt) }, s.handle, p, signal, lease, s.resumed === true);
1504
+ // B-15: a resumed cloud instance reads its permission support again; any other instance
1505
+ // whose recorded evidence is stale (a limits change, a provider version change) too
1506
+ await this.refreshCloudSupport(ctx, p, s, sig, s.resumed === true);
1507
+ // staged path (B-8): create → commit → legacy gate (ensure) → cleanup → bind → installed →
1508
+ // downgrade. The cleanup a resume or create owes runs first: a retry after a failed bind
1509
+ // finds the instance running and would not owe it again. The binder sends the committed
1510
+ // binding id again on every retry, refuses while a legacy obligation is open and runs
1511
+ // outside any transaction; a failure releases the lease.
1512
+ const binder = p.binder;
1513
+ if (binder)
1514
+ await runOutsideTransaction(() => binder.bind(env, sig));
549
1515
  const shared = await lease.downgrade();
550
1516
  await this.register(env, shared.token);
551
1517
  return {
552
1518
  lease: shared,
553
1519
  handle: s.handle,
554
1520
  createdAt: s.createdAt,
555
- fsId: s.fsId,
1521
+ fsResets: s.fsResets,
556
1522
  info: s.info,
557
1523
  };
558
1524
  }
@@ -568,63 +1534,168 @@ let SandboxService = class SandboxService {
568
1534
  await this.unregister(env, e.lease.token);
569
1535
  await e.lease.release();
570
1536
  await this.db
571
- .updateTable("environment_instances")
1537
+ .updateTable("device_instances")
572
1538
  .set({ last_used_at: sql `GREATEST(last_used_at, now())` })
573
- .where("environment_id", "=", env)
1539
+ .where("device_id", "=", env)
574
1540
  .where("status", "=", "running")
575
1541
  .execute()
576
- .catch((err) => this.log.warn("cannot update sandbox last_used_at", { environmentId: env, err }));
1542
+ .catch((err) => this.log.warn("cannot update sandbox last_used_at", { deviceId: env, err }));
577
1543
  }
578
1544
  async register(env, token) {
579
1545
  const ttl = this.config.get().sandbox.limits.maxCommandSeconds * 1000 + HOLDER_TTL_MARGIN_MS;
580
1546
  await this.leases
581
1547
  .registerHolder(env, token, ttl)
582
- .catch((err) => this.log.warn("cannot record sandbox holder", { environmentId: env, err }));
1548
+ .catch((err) => this.log.warn("cannot record sandbox holder", { deviceId: env, err }));
583
1549
  }
584
1550
  async unregister(env, token) {
585
1551
  await this.leases
586
1552
  .unregisterHolder(env, token)
587
- .catch((err) => this.log.warn("cannot clear sandbox holder record", { environmentId: env, err }));
1553
+ .catch((err) => this.log.warn("cannot clear sandbox holder record", { deviceId: env, err }));
1554
+ }
1555
+ /**
1556
+ * The crashed holders' cleanup (permission runtime cutover B-1): their tokens are read without
1557
+ * removing them, their revocation is owed durably ({@link oweDeadHolders}), it runs inline
1558
+ * (`revokeHolders`), and the owed operation revokes of the instance are delivered by operation id
1559
+ * ({@link deliverRevocations}). `delivered`: a resume under the exclusive lease, which delivers
1560
+ * the revokes `ensure` owed on the incarnation even with no crashed holder. A failure after the
1561
+ * revocation is owed is only warned (the outbox retries it); gone and abort are thrown.
1562
+ */
1563
+ async takeOver(env, instance, handle, p, signal, lease, delivered = false) {
1564
+ const dead = await this.oweDeadHolders(env);
1565
+ if (dead.length === 0 && !delivered)
1566
+ return;
1567
+ const sig = AbortSignal.any([signal, lease.signal]);
1568
+ if (dead.length > 0) {
1569
+ try {
1570
+ await runOutsideTransaction(() => this.operationIntents.revokeHolders(env, dead));
1571
+ this.log.info("sandbox taken over from a holder that did not finish; its operations revoked", {
1572
+ deviceId: env,
1573
+ });
1574
+ }
1575
+ catch (err) {
1576
+ if (sig.aborted)
1577
+ throw err;
1578
+ this.log.warn("cannot revoke a crashed sandbox holder's operations now; a worker retries", {
1579
+ deviceId: env,
1580
+ err,
1581
+ });
1582
+ }
1583
+ }
1584
+ await this.deliverRevocations(env, instance, handle, p, sig);
588
1585
  }
589
- /** Crashed holders' tags (claimed); a Redis error counts as none. */
590
- async claim(env) {
1586
+ /**
1587
+ * Crashed holders' tokens whose revocation is now owed durably: read without removing them, an
1588
+ * outbox row per token committed ({@link SandboxOperationIntents.oweHolderRevocations}), then
1589
+ * their records forgotten. A Redis or database error leaves the records for the next acquirer
1590
+ * and counts as none.
1591
+ */
1592
+ async oweDeadHolders(env) {
1593
+ let dead;
591
1594
  try {
592
- return await this.leases.claimDeadHolders(env);
1595
+ dead = await this.leases.deadHolders(env);
593
1596
  }
594
1597
  catch (err) {
595
- this.log.warn("cannot read sandbox holder records", { environmentId: env, err });
1598
+ this.log.warn("cannot read sandbox holder records", { deviceId: env, err });
1599
+ return [];
1600
+ }
1601
+ if (dead.length === 0)
1602
+ return [];
1603
+ try {
1604
+ await runOutsideTransaction(() => this.operationIntents.oweHolderRevocations(env, dead));
1605
+ }
1606
+ catch (err) {
1607
+ this.log.warn("cannot owe a crashed sandbox holder's revocation; the next acquirer will", {
1608
+ deviceId: env,
1609
+ err,
1610
+ });
596
1611
  return [];
597
1612
  }
1613
+ await this.leases
1614
+ .forgetHolders(env, dead)
1615
+ .catch((err) => this.log.warn("cannot clear crashed sandbox holder records", { deviceId: env, err }));
1616
+ return dead;
598
1617
  }
599
- /** Kills the commands of crashed holders by their tags (`killTagged`); nothing without tags. */
600
- async killTagged(env, handle, p, tags, signal, lease) {
601
- if (tags.length === 0)
1618
+ /**
1619
+ * The exact cleanup of an incarnation nobody else holds (exclusive lease), in place of a broad
1620
+ * `killAll`: revokes its started-or-unknown operations
1621
+ * ({@link SandboxOperationIntents.revokeIncarnation}) and delivers the owed revokes. Thrown when
1622
+ * the revocation cannot be recorded (`strict`), else only warned: the caller's row still says
1623
+ * suspended, so the next resume revokes again.
1624
+ */
1625
+ async revokeIncarnation(env, instance, handle, p, signal, strict) {
1626
+ try {
1627
+ await runOutsideTransaction(() => this.operationIntents.revokeIncarnation(env, instance));
1628
+ }
1629
+ catch (err) {
1630
+ if (strict || signal.aborted)
1631
+ throw err;
1632
+ this.log.warn("cannot revoke the sandbox instance's leftover operations", {
1633
+ deviceId: env,
1634
+ err,
1635
+ });
602
1636
  return;
603
- const sig = AbortSignal.any([signal, lease.signal]);
604
- await this.kill(env, "takeover", () => p.impl.killTagged(handle, tags, sig), sig);
1637
+ }
1638
+ await this.deliverRevocations(env, instance, handle, p, signal);
605
1639
  }
606
- /** Runs one kill call: gone and abort are thrown, other failures only warned. */
607
- async kill(environmentId, why, call, signal) {
1640
+ /**
1641
+ * Delivers the owed operation revokes of one instance generation inline, by operation id
1642
+ * (`revokeOperation`), acknowledging each: what the revoke jobs would deliver, sent before this
1643
+ * holder runs anything. Best effort, as the broad `killAll` it replaces was: at most
1644
+ * {@link INLINE_REVOKE_LIMIT} per call, nothing for a provider without `revokeOperation`, and any
1645
+ * failure only warned. Durability does not depend on it: every revocation wrote its
1646
+ * `sandbox-operation-revoke-<operationId>` outbox job in the same transaction, and those jobs
1647
+ * deliver until acknowledged. Gone and abort are thrown (the use rebuilds / ends).
1648
+ */
1649
+ async deliverRevocations(env, instance, handle, p, signal) {
1650
+ const revoke = p.impl.revokeOperation?.bind(p.impl);
1651
+ if (!revoke)
1652
+ return;
1653
+ let owed;
608
1654
  try {
609
- await call();
610
- if (why === "takeover") {
611
- this.log.info("sandbox taken over from a holder that did not finish; leftover commands killed", { environmentId });
612
- }
1655
+ owed = await this.operationIntents.owedRevocations(env, instance, INLINE_REVOKE_LIMIT);
613
1656
  }
614
1657
  catch (err) {
615
- if (signal?.aborted || isSandboxGoneError(err))
1658
+ if (signal.aborted)
616
1659
  throw err;
617
- this.log.warn("cannot kill leftover sandbox commands", { environmentId, err });
1660
+ this.log.warn("cannot read the sandbox instance's owed revocations", { deviceId: env, err });
1661
+ return;
1662
+ }
1663
+ for (const o of owed) {
1664
+ try {
1665
+ await revoke(handle, { operationId: o.operationId, admitBeforeMs: o.deadline.getTime() }, AbortSignal.any([signal, AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS)]));
1666
+ await runOutsideTransaction(() => this.operationIntents.acknowledgeRevocation(o.operationId));
1667
+ }
1668
+ catch (err) {
1669
+ if (signal.aborted || isSandboxGoneError(err))
1670
+ throw err;
1671
+ this.log.warn("cannot deliver an owed operation revoke now; its job retries", {
1672
+ deviceId: env,
1673
+ operationId: o.operationId,
1674
+ err,
1675
+ });
1676
+ }
618
1677
  }
619
1678
  }
1679
+ /** The {@link RevokedIncarnation} of an instance row. */
1680
+ incarnationOf(row) {
1681
+ return { provider: row.provider ?? "", generation: String(row.created_at.getTime()) };
1682
+ }
1683
+ /**
1684
+ * The owed revocation job of one crashed holder (`sandbox-holder-revoke`): revokes its intents
1685
+ * still admitted, dispatching or started-or-unknown and owes each its exact revoke job.
1686
+ */
1687
+ async revokeDeadHolder(deviceId, token) {
1688
+ await this.operationIntents.revokeHolders(deviceId, [token]);
1689
+ }
620
1690
  /**
621
1691
  * Suspends running instances idle longer than `suspendAfterIdleMinutes` or running continuously
622
- * longer than `maxRunningMinutes`. Skips an environment with any holder; one past
1692
+ * longer than `maxRunningMinutes`. Skips a device with any holder; one past
623
1693
  * `maxRunningMinutes` gets the intent for one poll window (about a second) first. Returns how
624
1694
  * many it suspended. Called every minute by the `sandbox-suspend-idle` cron.
625
1695
  */
626
1696
  async suspendIdle(now) {
627
- const p = this.providers.current();
1697
+ // cloud only: suspendDue keeps to this provider's rows, so `@local` is never suspended here
1698
+ const p = this.providers.cloud();
628
1699
  if (!p)
629
1700
  return 0;
630
1701
  const due = this.suspendDue(now, p.plugin);
@@ -633,12 +1704,12 @@ let SandboxService = class SandboxService {
633
1704
  let n = 0;
634
1705
  await inPool(rows, SWEEP_CONCURRENCY, async (c) => {
635
1706
  const overdue = c.running_since !== null && c.running_since < runningBefore;
636
- const done = await this.tryLocked(c.environment_id, async (lease) => {
637
- const id = c.environment_id;
1707
+ const done = await this.tryLocked(c.device_id, async (lease) => {
1708
+ const id = c.device_id;
638
1709
  const row = await this.db
639
- .selectFrom("environment_instances")
1710
+ .selectFrom("device_instances")
640
1711
  .selectAll()
641
- .where("environment_id", "=", id)
1712
+ .where("device_id", "=", id)
642
1713
  .where(due)
643
1714
  .executeTakeFirst();
644
1715
  if (!row?.handle)
@@ -653,7 +1724,7 @@ let SandboxService = class SandboxService {
653
1724
  running_since: null,
654
1725
  sweep_failed_at: null,
655
1726
  });
656
- this.log.info("sandbox suspended", { environmentId: id });
1727
+ this.log.info("sandbox suspended", { deviceId: id });
657
1728
  return true;
658
1729
  }, overdue);
659
1730
  if (done)
@@ -664,39 +1735,53 @@ let SandboxService = class SandboxService {
664
1735
  /**
665
1736
  * Destruction sweep: an instance unused for longer than `destroyAfterInactiveDays` is destroyed
666
1737
  * (the instance only; the file system is kept and the next use builds a new instance on it); an
667
- * environment that was deleted, or whose org was deleted, loses its instance and its file system
668
- * and its row is deleted (as {@link destroyEnvironment} does). Environments with any holder are
669
- * skipped. Returns how many it destroyed. Called hourly by the `sandbox-destroy-inactive` cron.
1738
+ * device that was deleted, or whose org was deleted, loses its instance and its file system
1739
+ * and its row is deleted (as {@link destroyDevice} does). Devices with any holder are
1740
+ * skipped. Inactivity never destroys a `@local` instance; a gone `@local` device is
1741
+ * destroyed like any other while `@local` is registered. Returns how many it destroyed. Called
1742
+ * hourly by the `sandbox-destroy-inactive` cron.
670
1743
  */
671
1744
  async destroyInactive(now) {
672
- const p = this.providers.current();
673
- if (!p)
674
- return 0;
1745
+ const p = this.providers.cloud();
1746
+ const local = this.providers.forName(LOCAL_PROVIDER) !== undefined;
675
1747
  let n = 0;
676
- const gone = (eb) => this.environmentGone(eb);
677
- await inPool(await this.candidates(gone), SWEEP_CONCURRENCY, async ({ environment_id: id }) => {
678
- const done = await this.tryLocked(id, async (lease) => {
679
- const row = await this.db
680
- .selectFrom("environment_instances")
681
- .selectAll()
682
- .where("environment_id", "=", id)
683
- .where(gone)
684
- .executeTakeFirst();
685
- if (!row)
686
- return false;
687
- await this.destroyRow(row, p, lease, "environment");
688
- return true;
1748
+ // Gone devices (deleted, or of a deleted org) on every provider that is here, `@local`
1749
+ // too (its destroy calls never need the machine online); rows whose provider is missing wait.
1750
+ const here = (eb) => eb.or([
1751
+ ...(p ? [this.cloudRow(eb)] : []),
1752
+ ...(local ? [eb("provider", "=", LOCAL_PROVIDER)] : []),
1753
+ ]);
1754
+ const gone = (eb) => eb.and([here(eb), this.deviceGone(eb)]);
1755
+ if (p || local) {
1756
+ await inPool(await this.candidates(gone), SWEEP_CONCURRENCY, async ({ device_id: id }) => {
1757
+ const done = await this.tryLocked(id, async (lease) => {
1758
+ const row = await this.db
1759
+ .selectFrom("device_instances")
1760
+ .selectAll()
1761
+ .where("device_id", "=", id)
1762
+ .where(gone)
1763
+ .executeTakeFirst();
1764
+ const owner = row && this.rowProvider(row);
1765
+ if (!row || !owner)
1766
+ return false;
1767
+ await this.destroyRow(row, owner, lease, "device");
1768
+ return true;
1769
+ });
1770
+ if (done)
1771
+ n++;
689
1772
  });
690
- if (done)
691
- n++;
692
- });
693
- const idle = this.instanceDue(now);
694
- await inPool(await this.candidates(idle), SWEEP_CONCURRENCY, async ({ environment_id: id }) => {
1773
+ }
1774
+ // inactivity destroys cloud instances only: `@local` instances are never swept
1775
+ if (!p)
1776
+ return n;
1777
+ const due = this.instanceDue(now);
1778
+ const idle = (eb) => eb.and([this.cloudRow(eb), due(eb)]);
1779
+ await inPool(await this.candidates(idle), SWEEP_CONCURRENCY, async ({ device_id: id }) => {
695
1780
  const done = await this.tryLocked(id, async (lease) => {
696
1781
  const row = await this.db
697
- .selectFrom("environment_instances")
1782
+ .selectFrom("device_instances")
698
1783
  .selectAll()
699
- .where("environment_id", "=", id)
1784
+ .where("device_id", "=", id)
700
1785
  .where(idle)
701
1786
  .executeTakeFirst();
702
1787
  if (!row)
@@ -710,53 +1795,60 @@ let SandboxService = class SandboxService {
710
1795
  return n;
711
1796
  }
712
1797
  /**
713
- * Destroys the environment's instance, then its file system, then deletes its instance row
714
- * (environment deletion, offboarding); nothing to do without a row. Waits for the exclusive lease
715
- * (with intent, so running commands finish and new ones wait) up to 10 minutes. Without a
716
- * provider it only warns (the destruction sweep finishes a deleted environment later). Files kept
717
- * by another provider that is not loaded cannot be destroyed: it throws and the row stays.
1798
+ * Destroys the device's instance, then its file system, then deletes its instance row
1799
+ * (device deletion, offboarding); nothing to do without a row. Waits for the exclusive lease
1800
+ * (with intent, so running commands finish and new ones wait) up to 10 minutes. Without the
1801
+ * device's provider it throws and the row stays, marked `sweep_failed_at` (the job is
1802
+ * retried, and the destruction sweep finishes a deleted device once the provider is back).
1803
+ * Files kept by another provider that is not loaded cannot be destroyed: it throws and the row
1804
+ * stays.
718
1805
  */
719
- async destroyEnvironment(environmentId) {
1806
+ async destroyDevice(deviceId) {
720
1807
  const row = await this.db
721
- .selectFrom("environment_instances")
722
- .select("environment_id")
723
- .where("environment_id", "=", environmentId)
1808
+ .selectFrom("device_instances")
1809
+ .select("device_id")
1810
+ .where("device_id", "=", deviceId)
724
1811
  .executeTakeFirst();
725
1812
  if (!row)
726
1813
  return;
727
- const p = this.providers.current();
1814
+ const p = await this.providerOf(deviceId);
728
1815
  if (!p) {
729
- this.log.warn("cannot destroy environment: no sandbox provider", { environmentId });
730
- return;
1816
+ await this.db
1817
+ .updateTable("device_instances")
1818
+ .set({ sweep_failed_at: sql `now()` })
1819
+ .where("device_id", "=", deviceId)
1820
+ .execute();
1821
+ throw new Error(`cannot destroy device ${deviceId}: its sandbox provider is not there; ` +
1822
+ "the destruction sweep retries it");
731
1823
  }
732
- const lease = await this.leases.acquireExclusive(environmentId, AbortSignal.timeout(EXCLUSIVE_WAIT_MS), undefined, { intent: true });
1824
+ const lease = await this.leases.acquireExclusive(deviceId, AbortSignal.timeout(EXCLUSIVE_WAIT_MS), undefined, { intent: true });
733
1825
  try {
734
1826
  const current = await this.db
735
- .selectFrom("environment_instances")
1827
+ .selectFrom("device_instances")
736
1828
  .selectAll()
737
- .where("environment_id", "=", environmentId)
1829
+ .where("device_id", "=", deviceId)
738
1830
  .executeTakeFirst();
739
1831
  if (current)
740
- await this.destroyRow(current, p, lease, "environment");
1832
+ await this.destroyRow(current, p, lease, "device");
741
1833
  }
742
1834
  finally {
743
1835
  await lease.release();
744
1836
  }
745
1837
  }
746
1838
  /**
747
- * Starts the environment over with empty files (after `environment.files_lost`, or on request):
748
- * under the exclusive lease (waited for like {@link destroyEnvironment}) destroys any instance and
1839
+ * Starts the device over with empty files (after `device.files_lost`, or on request):
1840
+ * under the exclusive lease (waited for like {@link destroyDevice}) destroys any instance and
749
1841
  * the file system (a `lost` one is only dropped), and records no file system; the next use
750
1842
  * creates a new one. Nothing to do without a row. Throws `sandbox.unavailable` without a provider.
751
1843
  */
752
- async resetFileSystem(environmentId) {
753
- const p = this.require();
754
- const lease = await this.leases.acquireExclusive(environmentId, AbortSignal.timeout(EXCLUSIVE_WAIT_MS), undefined, { intent: true });
1844
+ async resetFileSystem(deviceId) {
1845
+ const p = await this.require(deviceId);
1846
+ const lease = await this.leases.acquireExclusive(deviceId, AbortSignal.timeout(EXCLUSIVE_WAIT_MS), undefined, { intent: true });
755
1847
  try {
756
1848
  const row = await this.db
757
- .selectFrom("environment_instances")
1849
+ .selectFrom("device_instances")
758
1850
  .selectAll()
759
- .where("environment_id", "=", environmentId)
1851
+ .where("device_id", "=", deviceId)
760
1852
  .executeTakeFirst();
761
1853
  if (!row)
762
1854
  return;
@@ -765,8 +1857,8 @@ let SandboxService = class SandboxService {
765
1857
  const prev = await this.destroyInstance(row, p, signal);
766
1858
  await this.destroyFiles(row, p, signal, true);
767
1859
  if (!(await lease.renew()))
768
- throw new SandboxLockLostError(environmentId);
769
- await this.fenced(lease, environmentId, fence, {
1860
+ throw new SandboxLockLostError(deviceId);
1861
+ await this.fenced(lease, deviceId, fence, {
770
1862
  fs_handle: null,
771
1863
  fs_status: "none",
772
1864
  handle: null,
@@ -775,75 +1867,600 @@ let SandboxService = class SandboxService {
775
1867
  suspended_at: null,
776
1868
  destroyed_at: sql `now()`,
777
1869
  sweep_failed_at: null,
1870
+ // conversations that used the old files are told they were reset (seenBy)
1871
+ fs_resets: sql `fs_resets + 1`,
1872
+ // the next file system and instance record their own limits
1873
+ instance_limits: null,
778
1874
  ...prev,
779
1875
  });
780
- this.log.info("environment files reset", { environmentId });
1876
+ this.log.info("device files reset", { deviceId });
1877
+ }
1878
+ finally {
1879
+ await lease.release();
1880
+ }
1881
+ }
1882
+ /**
1883
+ * The worker's retirement of a device's old incarnations (8.5, `RetireLegacyTasksJob`): one try
1884
+ * at the exclusive lifecycle lease, then the same gate as every acquisition. `busy`: a holder
1885
+ * has the device (the inline gate runs on its next lifecycle acquisition anyway); `unavailable`:
1886
+ * an obligation stays (quarantined, or a destroy that failed); `clear`: none left.
1887
+ */
1888
+ async retireLegacy(deviceId,
1889
+ /** The worker's signal (its stop, a lost run lock): ends a destroy in flight. */
1890
+ signal) {
1891
+ const lease = await this.leases.tryExclusive(deviceId);
1892
+ if (!lease)
1893
+ return "busy";
1894
+ try {
1895
+ const row = await this.db
1896
+ .selectFrom("device_instances")
1897
+ .selectAll()
1898
+ .where("device_id", "=", deviceId)
1899
+ .executeTakeFirst();
1900
+ const fence = row ? { gen: row.generation } : null;
1901
+ if (row && fence)
1902
+ await this.fenced(lease, deviceId, fence, {});
1903
+ await this.retireIncarnations(deviceId, lease, row, fence, signal);
1904
+ return "clear";
1905
+ }
1906
+ catch (err) {
1907
+ if (isRetirementPending(err))
1908
+ return "unavailable";
1909
+ throw err;
781
1910
  }
782
1911
  finally {
783
1912
  await lease.release();
784
1913
  }
785
1914
  }
786
1915
  /**
787
- * Under the exclusive lease (before the downgrade), on an instance just resumed from
788
- * `suspended`: kills every command left in it (`killAll`), crashed holders' (`dead`, already
789
- * claimed) included. Never on the shared path: other holders may be running commands. A gone
790
- * instance (`SandboxGoneError`) and an abort are thrown (`withSandbox` rebuilds / ends); other
791
- * failures are only warned.
1916
+ * The lifecycle reconcile of a cloud device carrying `permission_reconcile_required` (B-12),
1917
+ * under one try at its exclusive lifecycle lease (`busy`: a holder has it). The snapshot
1918
+ * writer's reconcile runs first ({@link CloudPermissionSnapshots.reconcileHeld}: it narrows the
1919
+ * authority to what the instance is known to run, and may clear the marker by itself). A device
1920
+ * with an unresolved retirement obligation stops there: its incarnation is the retirement
1921
+ * gate's alone (never resumed here). When the
1922
+ * marker stays on a live instance whose provider can `update`, the provider applies the
1923
+ * reconcile target, which is never wider than the instance in any dimension, so this only
1924
+ * narrows; a suspended instance is resumed for it (its leftover operations revoked exactly,
1925
+ * nobody else holds it) and suspended again, as its row still says. `updated` records the target as
1926
+ * applied (fenced) and the reconcile runs again, which clears the marker. No `update`, a
1927
+ * `recreate` answer, a gone instance or a failure leave the marker and its file reset action.
792
1928
  */
793
- async killLeftovers(environmentId, handle, p, signal, dead) {
794
- await this.kill(environmentId, dead.length > 0 ? "takeover" : "resume", () => p.impl.killAll(handle, signal), signal);
1929
+ async reconcileLimits(deviceId, signal = AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)) {
1930
+ const lease = await this.leases.tryExclusive(deviceId);
1931
+ if (!lease)
1932
+ return "busy";
1933
+ try {
1934
+ const device = await this.db
1935
+ .selectFrom("devices")
1936
+ .select("org_id")
1937
+ .where("id", "=", deviceId)
1938
+ .executeTakeFirst();
1939
+ if (!device)
1940
+ return { state: "skipped" };
1941
+ const orgId = device.org_id;
1942
+ const row = await this.db
1943
+ .selectFrom("device_instances")
1944
+ .selectAll()
1945
+ .where("device_id", "=", deviceId)
1946
+ .executeTakeFirst();
1947
+ const fence = row ? { gen: row.generation } : null;
1948
+ if (row && fence)
1949
+ await this.fenced(lease, deviceId, fence, {});
1950
+ const before = await runOutsideTransaction(() => this.snapshots.reconcileHeld(orgId, deviceId));
1951
+ // an incarnation under a retirement obligation is never resumed or updated here: only the
1952
+ // retirement gate may touch it (C1); the marker stays until the gate cleared it
1953
+ if (before.state === "reconcile-required" && (await this.retirement.hasUnresolved(deviceId)))
1954
+ return before;
1955
+ const p = row ? this.rowProvider(row) : undefined;
1956
+ const update = p?.impl.update?.bind(p.impl);
1957
+ if (before.state !== "reconcile-required" ||
1958
+ before.target === undefined ||
1959
+ !row?.handle ||
1960
+ !fence ||
1961
+ !p ||
1962
+ !update ||
1963
+ p.plugin === LOCAL_PROVIDER ||
1964
+ row.provider !== p.plugin ||
1965
+ row.fs_status !== "ready" ||
1966
+ (row.status !== "running" && row.status !== "suspended"))
1967
+ return before;
1968
+ const handle = row.handle;
1969
+ // the effective limits with their resources, read under the lease: exactly the target, or
1970
+ // the authority moved since the reconcile (the next round sees it)
1971
+ const want = await this.deviceLimits({ orgId, deviceId }, { source: "cloud" });
1972
+ if (!sameAppliedExactly(appliedOf(want), before.target))
1973
+ return before;
1974
+ const sig = AbortSignal.any([signal, opSignal(lease)]);
1975
+ const facts = { deviceId, provider: p.plugin, to: before.target };
1976
+ const suspended = row.status === "suspended";
1977
+ let answer;
1978
+ try {
1979
+ if (suspended && (await p.impl.resume(handle, sig)) === "gone")
1980
+ answer = "gone";
1981
+ else {
1982
+ // what the pause brought back is revoked exactly before the update (the row still says
1983
+ // suspended: a failure is revoked again on the next resume)
1984
+ if (suspended)
1985
+ await this.revokeIncarnation(deviceId, { provider: p.plugin, generation: String(row.created_at.getTime()) }, handle, p, sig, false);
1986
+ answer = await update(handle, want, sig);
1987
+ }
1988
+ }
1989
+ catch (err) {
1990
+ if (sig.aborted)
1991
+ throw err;
1992
+ this.log.warn("cannot apply the reconcile limits to the sandbox instance", {
1993
+ ...facts,
1994
+ err,
1995
+ });
1996
+ answer = "recreate";
1997
+ }
1998
+ finally {
1999
+ if (suspended)
2000
+ await this.bestEffort(deviceId, "suspend the instance again after a limits update", (s) => p.impl.suspend(handle, s));
2001
+ }
2002
+ if (answer !== "updated")
2003
+ return before;
2004
+ if (!(await lease.renew()))
2005
+ throw new SandboxLockLostError(deviceId);
2006
+ await this.fenced(lease, deviceId, fence, {
2007
+ instance_limits: instanceLimitsJson(appliedOf(want)),
2008
+ });
2009
+ this.log.info("sandbox instance limits reconciled by the provider's update", facts);
2010
+ const after = await runOutsideTransaction(() => this.snapshots.reconcileHeld(orgId, deviceId));
2011
+ // a running instance records its evidence for the new limits now; a suspended one on its
2012
+ // next use's resume
2013
+ if (!suspended)
2014
+ await this.refreshCloudSupport({ orgId, deviceId }, p, { handle, createdAt: row.created_at.getTime() }, sig, false);
2015
+ return after;
2016
+ }
2017
+ finally {
2018
+ await lease.release();
2019
+ }
795
2020
  }
796
2021
  /**
797
- * Under the exclusive lease, right after a resume or a (re)build: kills the sessions of the
798
- * background tasks marked lost while their process may live on (`kill_pending`), in one exec of
799
- * `pkill -KILL -s <sid>`, then clears their flags. Tasks of another instance have no process
800
- * here and are only cleared. A gone instance and an abort are thrown; another failure is warned
801
- * and leaves the flags of this instance's tasks for the next resume.
2022
+ * The worker's sweep of {@link reconcileLimits} (`sandbox-reconcile-limits`): up to `limit`
2023
+ * live cloud devices of the loaded cloud provider carrying the marker on a live instance, in
2024
+ * id order from a shared keyset cursor that wraps around (no starvation), each tried at most
2025
+ * once per {@link RECONCILE_RETRY_SECONDS} across replicas (a Redis marker).
2026
+ * Nothing without a cloud provider that can `update`. Returns how many it reconciled.
802
2027
  */
803
- async killPendingTasks(environmentId, handle, createdAt, p, tag, actor, signal) {
804
- const rows = await this.background.pendingKills(environmentId);
805
- if (rows.length === 0)
806
- return;
807
- const mine = rows.filter((r) => r.sandboxCreatedAt?.getTime() === createdAt && r.sid !== null && SID_RE.test(r.sid));
808
- let cleared = rows;
809
- if (mine.length > 0) {
810
- // pkill exits 1 when the session has no process left: only a higher status is a failure
811
- const command = `rc=0; for sid in ${mine.map((r) => r.sid).join(" ")}; do pkill -KILL -s "$sid"; c=$?; [ "$c" -le 1 ] || rc=$c; done; exit $rc`;
2028
+ async reconcileMarked(limit = 10) {
2029
+ const p = this.providers.cloud();
2030
+ if (!p?.impl.update)
2031
+ return 0;
2032
+ const page = (after, n) => this.db
2033
+ .selectFrom("devices as d")
2034
+ .innerJoin("device_instances as i", "i.device_id", "d.id")
2035
+ .select("d.id")
2036
+ .where("d.source", "=", "cloud")
2037
+ .where("d.deleted_at", "is", null)
2038
+ .where("d.permission_reconcile_required", "=", true)
2039
+ .where("i.provider", "=", p.plugin)
2040
+ .where("i.handle", "is not", null)
2041
+ .where("i.status", "in", ["running", "suspended"])
2042
+ .where(sql `d.id COLLATE "C" > ${after}`)
2043
+ .orderBy(sql `d.id COLLATE "C"`)
2044
+ .limit(n)
2045
+ .execute();
2046
+ // a keyset cursor shared by the replicas (the cron runs once per tick): each tick goes on
2047
+ // after the last device the previous one visited and wraps around, so devices that stay
2048
+ // marked never starve the ones after them
2049
+ const after = (await this.redis.get(RECONCILE_CURSOR_KEY).catch(() => null)) ?? "";
2050
+ const rows = await page(after, limit);
2051
+ if (rows.length < limit && after !== "") {
2052
+ const seen = new Set(rows.map((r) => r.id));
2053
+ for (const r of await page("", limit - rows.length))
2054
+ if (!seen.has(r.id) && r.id <= after)
2055
+ rows.push(r);
2056
+ }
2057
+ const last = rows.at(-1)?.id;
2058
+ await this.redis
2059
+ .set(RECONCILE_CURSOR_KEY, last ?? "", "EX", 86_400)
2060
+ .catch((err) => this.log.warn("cannot record the reconcile cursor", { err }));
2061
+ let n = 0;
2062
+ for (const { id } of rows) {
2063
+ // a retry window shared by the replicas, not a lock: a second try within it waits
2064
+ const first = await this.redis
2065
+ .set(`capk:cloud-reconcile-tried:${id}`, "1", "EX", RECONCILE_RETRY_SECONDS, "GET")
2066
+ .then((prev) => prev === null)
2067
+ .catch(() => false);
2068
+ if (!first)
2069
+ continue;
812
2070
  try {
813
- const r = await p.impl.exec(handle, {
814
- command,
815
- timeoutMs: PENDING_KILL_TIMEOUT_MS,
816
- maxOutputBytes: 4096,
817
- signal,
818
- tag,
819
- actor,
2071
+ const r = await this.reconcileLimits(id);
2072
+ if (r !== "busy" && r.state === "bound")
2073
+ n++;
2074
+ }
2075
+ catch (err) {
2076
+ this.log.warn("cannot reconcile a cloud device's limits; will retry", {
2077
+ deviceId: id,
2078
+ err,
820
2079
  });
821
- if (r.exitCode !== 0) {
822
- throw new Error(`pkill exited with ${r.exitCode === null ? "no status" : r.exitCode}: ${r.stderr.slice(0, 500)}`);
2080
+ }
2081
+ }
2082
+ return n;
2083
+ }
2084
+ /**
2085
+ * The retirement gate (permission runtime cutover 8.5), under the exclusive lifecycle lease and
2086
+ * before the instance is used, resumed, rebuilt, switched to another provider, bound or
2087
+ * downgraded to shared use: every unresolved obligation of the device is settled here or the
2088
+ * device is unavailable ({@link retirementPending}).
2089
+ * - The obligation names the **current** incarnation (provider and exact generation): a cloud
2090
+ * one is destroyed whole by its provider (never resumed, never `killAll`ed, the file system
2091
+ * kept), the confirmed destruction is recorded and the row reads `destroyed`, so the use
2092
+ * creates a fresh instance; a failed destroy keeps the obligation. A kernel-internal (local)
2093
+ * one is quarantined: its destroy is a no-op and a restart proves nothing.
2094
+ * - B-22: a **suspended** current cloud incarnation whose members are all revoked managed starts
2095
+ * is not destroyed whole (its other tasks would be lost): each revoked ref gets its exact stop
2096
+ * (persisted while suspended), the instance is resumed, each stop is confirmed (`stopped` or
2097
+ * `already-exited`), and the obligation resolves as `exact-cancelled`. Any failure is noted on
2098
+ * the obligation and falls back to the whole-instance destroy above. `resumed` given (a use):
2099
+ * the resumed instance is left running for it (`resumed.resumed` set); otherwise (the worker),
2100
+ * or when the device stays refused, it is suspended again, as its row still says.
2101
+ * - It names an incarnation that is **not current** (replaced, a reused handle with another
2102
+ * generation, unknown): resolved only by a recorded provider-confirmed destruction of exactly
2103
+ * it, else quarantined. A newer generation is never evidence.
2104
+ * Returns the row as it is afterwards.
2105
+ */
2106
+ async retireIncarnations(id, held, row, fence, signal,
2107
+ /** A use's holder: a gate that resumed the instance (B-22) leaves it running and says so. */
2108
+ resumed) {
2109
+ // the device's own candidates first: the gate never depends on the worker having scanned
2110
+ // (C1); then a later boot an authenticated hello already reported settles local ones
2111
+ await this.retirement.scanUntilStable(5, id);
2112
+ await this.retirement.settleRebooted(id);
2113
+ const open = await this.retirement.unresolved(id);
2114
+ let now = row;
2115
+ // every obligation is tried (one that stays never hides another that can resolve); the
2116
+ // device is refused at the end while any stays, with the answer that tells what would help:
2117
+ // a failed or impossible destroy now → unavailable (a retry may succeed); a cloud incarnation
2118
+ // no evidence can ever cover → recreate the device; a local one whose computer never reported
2119
+ // a boot → replace the device; else only a restart of the computer is missing
2120
+ let pending = false;
2121
+ let failed = false;
2122
+ let cloudPermanent = false;
2123
+ let unknownBoot = false;
2124
+ const isLive = (r) => r !== undefined &&
2125
+ r.handle !== null &&
2126
+ (r.status === "running" || r.status === "suspended" || r.status === "creating");
2127
+ /** The instance this gate resumed for an exact cancel and still runs (B-22). */
2128
+ let resumedHere = null;
2129
+ const bounded = () => AbortSignal.any([
2130
+ opSignal(held),
2131
+ AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2132
+ ...(signal ? [signal] : []),
2133
+ ]);
2134
+ /**
2135
+ * B-22: on a suspended current cloud incarnation whose members are all revoked managed
2136
+ * starts, cancels each by its exact ref and resumes the instance in between. `skip`: the
2137
+ * shape does not apply (the destroy follows); `failed`: a cancel could not be confirmed (the
2138
+ * reason is noted, the destroy follows).
2139
+ */
2140
+ const cancelOnResume = async (o, live) => {
2141
+ if (live.status !== "suspended" || !isCloudProvider(o.provider))
2142
+ return "skip";
2143
+ const impl = this.providers.forName(o.provider)?.impl;
2144
+ const background = impl?.background;
2145
+ if (!impl || !background)
2146
+ return "skip";
2147
+ const members = await this.retirement.membersOf(o.id);
2148
+ if (members.length === 0 || members.some((m) => m.kind !== "revoked-start"))
2149
+ return "skip";
2150
+ const owed = [];
2151
+ for (const m of members) {
2152
+ const intent = await this.db
2153
+ .selectFrom("sandbox_operation_intents")
2154
+ .select([
2155
+ "method",
2156
+ "state",
2157
+ "revoke_acknowledged",
2158
+ "provider",
2159
+ "instance_generation",
2160
+ "execution_ref",
2161
+ ])
2162
+ .where("operation_id", "=", m.refId)
2163
+ .where("device_id", "=", id)
2164
+ .executeTakeFirst();
2165
+ if (intent?.revoke_acknowledged === true)
2166
+ continue;
2167
+ if (intent === undefined ||
2168
+ intent.method !== "backgroundStart" ||
2169
+ intent.state !== "revoked" ||
2170
+ intent.provider !== o.provider ||
2171
+ intent.instance_generation !== o.instanceGeneration)
2172
+ return { failed: `revoked start ${m.refId} cannot be named on this incarnation` };
2173
+ let ref;
2174
+ try {
2175
+ ref = parseSandboxExecutionRef(intent.execution_ref);
2176
+ }
2177
+ catch {
2178
+ return { failed: `revoked start ${m.refId} has no valid execution reference` };
2179
+ }
2180
+ if (ref.operationId !== m.refId ||
2181
+ ref.instanceGeneration !== o.instanceGeneration ||
2182
+ ref.instanceId !== live.handle.id)
2183
+ return { failed: `revoked start ${m.refId} names another instance` };
2184
+ owed.push(ref);
2185
+ }
2186
+ try {
2187
+ // persisted while suspended: the provider applies a pending cancel before any work of
2188
+ // the instance runs again; the answer is confirmed after the resume
2189
+ for (const ref of owed) {
2190
+ const r = await background.stop(live.handle, ref, {
2191
+ graceMs: MANAGED_STOP_GRACE_MS,
2192
+ signal: bounded(),
2193
+ });
2194
+ // anything but a recorded (or already settled) cancel: never resume into the work
2195
+ if (r.outcome !== "cancel-pending" &&
2196
+ r.outcome !== "stopped" &&
2197
+ r.outcome !== "already-exited")
2198
+ return {
2199
+ failed: `the exact stop of ${ref.operationId} answered ${r.outcome} while suspended`,
2200
+ };
2201
+ }
2202
+ if ((await impl.resume(live.handle, bounded())) === "gone")
2203
+ return { failed: "the instance is gone at the provider" };
2204
+ resumedHere = { impl, handle: live.handle };
2205
+ for (const ref of owed) {
2206
+ const r = await background.stop(live.handle, ref, {
2207
+ graceMs: MANAGED_STOP_GRACE_MS,
2208
+ signal: bounded(),
2209
+ });
2210
+ if (r.outcome !== "stopped" && r.outcome !== "already-exited")
2211
+ return { failed: `the exact stop of ${ref.operationId} answered ${r.outcome}` };
823
2212
  }
824
- this.log.info("lost background tasks killed after a sandbox resume", {
825
- environmentId,
826
- tasks: mine.map((t) => t.id),
2213
+ }
2214
+ catch (err) {
2215
+ if (held.signal.aborted || signal?.aborted)
2216
+ throw err;
2217
+ return { failed: err instanceof Error ? err.message : String(err) };
2218
+ }
2219
+ if (!(await held.renew()))
2220
+ throw new SandboxLockLostError(id);
2221
+ this.log.info("revoked starts cancelled exactly on a resumed instance", {
2222
+ deviceId: id,
2223
+ operations: owed.map((r) => r.operationId),
2224
+ });
2225
+ // every member read is covered (an acknowledged one needed no stop)
2226
+ return { cancelled: members.map((m) => m.refId) };
2227
+ };
2228
+ /**
2229
+ * Destroys the live incarnation of `now` whole with its own provider (never resumed or
2230
+ * killAll'ed, files kept), records the confirmed destruction and marks the row destroyed.
2231
+ */
2232
+ const destroyLive = async (o, live) => {
2233
+ const provider = live.provider ?? "unknown";
2234
+ const impl = isCloudProvider(provider) ? this.providers.forName(provider)?.impl : undefined;
2235
+ if (!impl) {
2236
+ await this.retirement.noteFailure(o.id, `provider ${provider} is not loaded`);
2237
+ return false;
2238
+ }
2239
+ try {
2240
+ // bounded (M5): a hung provider never holds the lease or the worker's tick
2241
+ await impl.destroy(live.handle, AbortSignal.any([
2242
+ opSignal(held),
2243
+ AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2244
+ ...(signal ? [signal] : []),
2245
+ ]));
2246
+ }
2247
+ catch (err) {
2248
+ if (held.signal.aborted || signal?.aborted)
2249
+ throw err;
2250
+ await this.retirement.noteFailure(o.id, err);
2251
+ this.log.warn("cannot destroy an instance that may run legacy work; device unavailable", {
2252
+ deviceId: id,
2253
+ err,
827
2254
  });
2255
+ return false;
2256
+ }
2257
+ if (!(await held.renew()))
2258
+ throw new SandboxLockLostError(id);
2259
+ resumedHere = null;
2260
+ await this.retirement.recordDestruction(id, provider, String(live.created_at.getTime()));
2261
+ if (fence)
2262
+ await this.fenced(held, id, fence, {
2263
+ status: "destroyed",
2264
+ destroyed_at: sql `now()`,
2265
+ running_since: null,
2266
+ suspended_at: null,
2267
+ sweep_failed_at: null,
2268
+ });
2269
+ this.log.info("instance that may run legacy work destroyed", { deviceId: id });
2270
+ now = await this.db
2271
+ .selectFrom("device_instances")
2272
+ .selectAll()
2273
+ .where("device_id", "=", id)
2274
+ .executeTakeFirst();
2275
+ return true;
2276
+ };
2277
+ /**
2278
+ * R2-I1: the row is not live (destroyed before 0157 without a record, or a create that left
2279
+ * `creating` with no handle). With no `prev_handle`, the row's own cloud provider holds at
2280
+ * most one instance of the device's name (sandbox@2 same-name replacement), so its destroy by
2281
+ * that name confirms every incarnation there; it is recorded as the destruction of the row's
2282
+ * incarnation. A provider not loaded or a failed destroy keeps the obligation open.
2283
+ */
2284
+ const destroyNamed = async (o, row) => {
2285
+ const provider = row.provider ?? "unknown";
2286
+ const impl = isCloudProvider(provider) ? this.providers.forName(provider)?.impl : undefined;
2287
+ if (!impl) {
2288
+ await this.retirement.noteFailure(o.id, `provider ${provider} is not loaded`);
2289
+ return false;
2290
+ }
2291
+ try {
2292
+ await impl.destroyByName(deviceResourceName(id), AbortSignal.any([
2293
+ opSignal(held),
2294
+ AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2295
+ ...(signal ? [signal] : []),
2296
+ ]));
828
2297
  }
829
2298
  catch (err) {
830
- if (signal.aborted || isSandboxGoneError(err))
2299
+ if (held.signal.aborted || signal?.aborted)
831
2300
  throw err;
832
- this.log.warn("cannot kill lost background tasks after a sandbox resume", {
833
- environmentId,
2301
+ await this.retirement.noteFailure(o.id, err);
2302
+ this.log.warn("cannot destroy by name an instance that may run legacy work", {
2303
+ deviceId: id,
834
2304
  err,
835
2305
  });
836
- const kept = new Set(mine.map((r) => r.id));
837
- cleared = rows.filter((r) => !kept.has(r.id));
2306
+ return false;
2307
+ }
2308
+ if (!(await held.renew()))
2309
+ throw new SandboxLockLostError(id);
2310
+ await this.retirement.recordDestruction(id, provider, String(row.created_at.getTime()));
2311
+ if (fence && row.status === "creating")
2312
+ await this.fenced(held, id, fence, {
2313
+ status: "destroyed",
2314
+ destroyed_at: sql `now()`,
2315
+ running_since: null,
2316
+ suspended_at: null,
2317
+ sweep_failed_at: null,
2318
+ });
2319
+ this.log.info("instance that may run legacy work destroyed by name", { deviceId: id });
2320
+ now = await this.db
2321
+ .selectFrom("device_instances")
2322
+ .selectAll()
2323
+ .where("device_id", "=", id)
2324
+ .executeTakeFirst();
2325
+ return true;
2326
+ };
2327
+ try {
2328
+ for (const o of open) {
2329
+ const gen = o.instanceGeneration;
2330
+ const local = isInternalProvider(o.provider);
2331
+ const current = isLive(now) && now.provider === o.provider && String(now.created_at.getTime()) === gen;
2332
+ if (current && isLive(now)) {
2333
+ if (local) {
2334
+ await this.retirement.quarantine(o.id, o.bootId === null
2335
+ ? "local instance: no boot identity was reported, so no restart can prove its legacy work ended"
2336
+ : "local instance: waiting for a restart of the computer (a later boot identity)");
2337
+ if (o.bootId === null)
2338
+ unknownBoot = true;
2339
+ pending = true;
2340
+ continue;
2341
+ }
2342
+ let cancel = await cancelOnResume(o, now);
2343
+ if (cancel !== "skip" && "cancelled" in cancel) {
2344
+ // resolved only while no member outside the stopped refs exists (a concurrent scan's)
2345
+ if (await this.retirement.resolveCancelled(o.id, cancel.cancelled))
2346
+ continue;
2347
+ cancel = { failed: "a revoked start was recorded while the cancel ran" };
2348
+ }
2349
+ if (cancel !== "skip") {
2350
+ this.log.warn("cannot cancel revoked starts exactly; destroying the instance", {
2351
+ deviceId: id,
2352
+ reason: cancel.failed,
2353
+ });
2354
+ await this.retirement.noteFailure(o.id, cancel.failed);
2355
+ }
2356
+ if (await destroyLive(o, now))
2357
+ await this.retirement.resolveDestroyed(o.id);
2358
+ else {
2359
+ pending = true;
2360
+ failed = true;
2361
+ }
2362
+ continue;
2363
+ }
2364
+ // the existing whole-instance destroy left the row `destroyed` on exactly this incarnation
2365
+ // with nothing kept for a later retry: the provider confirmed it
2366
+ const destroyedHere = now !== undefined &&
2367
+ now.status === "destroyed" &&
2368
+ now.provider === o.provider &&
2369
+ String(now.created_at.getTime()) === gen &&
2370
+ now.prev_handle === null &&
2371
+ isCloudProvider(o.provider);
2372
+ if (destroyedHere || (await this.retirement.destructionRecorded(id, o.provider, gen))) {
2373
+ await this.retirement.resolveDestroyed(o.id);
2374
+ continue;
2375
+ }
2376
+ if (!local && (gen === "unknown" || o.provider === "unknown")) {
2377
+ // R1-I1 (b): a cloud incarnation the kernel cannot name. Every incarnation the device had
2378
+ // stopped being current through a kernel destroy, a provider `gone` or a kept
2379
+ // `prev_handle`; so once the device's current incarnation is destroyed with
2380
+ // confirmation, nothing earlier is kept (`prev_handle`) and the obligation was recorded
2381
+ // under the freeze (no dispatch after it), no instance of the device can run legacy work.
2382
+ // This rests on sandbox@2 same-name replacement: every rebuild on the same provider goes
2383
+ // through `create`, which first removes the old `cap-device-<id>` instance (so a `gone`
2384
+ // answer, E2B's token-failure `gone` included, and `applyLimits`' swallowed destroy
2385
+ // failure leave nothing behind), and E2B's incarnations are one sandbox (destroying the
2386
+ // current one ends the earlier processes). A provider or kernel path that rebuilds
2387
+ // without same-name replacement breaks this barrier.
2388
+ const frozenAt = await this.retirement.frozenAt();
2389
+ const reason = frozenAt === null || o.createdAt < frozenAt
2390
+ ? "an unknown cloud incarnation recorded before the freeze"
2391
+ : now === undefined || !now.had_instance
2392
+ ? // a row (re)inserted by this acquisition knows nothing of the earlier instances
2393
+ "an unknown cloud incarnation and no instance record to destroy"
2394
+ : now.prev_handle !== null
2395
+ ? "an unknown cloud incarnation while an earlier provider's instance may still exist"
2396
+ : null;
2397
+ if (reason === null && now !== undefined) {
2398
+ if (isLive(now)) {
2399
+ if (await destroyLive(o, now))
2400
+ await this.retirement.resolveDestroyed(o.id);
2401
+ else {
2402
+ pending = true;
2403
+ failed = true;
2404
+ }
2405
+ continue;
2406
+ }
2407
+ if (now.status === "destroyed" &&
2408
+ now.provider !== null &&
2409
+ (await this.retirement.destructionRecorded(id, now.provider, String(now.created_at.getTime())))) {
2410
+ await this.retirement.resolveDestroyed(o.id);
2411
+ continue;
2412
+ }
2413
+ // not live and nothing recorded (R2-I1): confirm by name with the row's provider
2414
+ if (await destroyNamed(o, now))
2415
+ await this.retirement.resolveDestroyed(o.id);
2416
+ else {
2417
+ pending = true;
2418
+ failed = true;
2419
+ }
2420
+ continue;
2421
+ }
2422
+ await this.retirement.quarantine(o.id, reason ??
2423
+ "an unknown cloud incarnation and no confirmed destruction of the current one");
2424
+ cloudPermanent = true;
2425
+ pending = true;
2426
+ continue;
2427
+ }
2428
+ await this.retirement.quarantine(o.id, local
2429
+ ? o.bootId === null
2430
+ ? "local instance: no boot identity was reported, so no restart can prove its legacy work ended"
2431
+ : "local instance: waiting for a restart of the computer (a later boot identity)"
2432
+ : "the old instance was replaced without a recorded confirmed destruction");
2433
+ if (!local)
2434
+ cloudPermanent = true;
2435
+ else if (o.bootId === null)
2436
+ unknownBoot = true;
2437
+ pending = true;
838
2438
  }
839
2439
  }
840
- await this.background.clearKill(cleared.map((r) => r.id));
841
- }
842
- require() {
843
- const p = this.providers.current();
844
- if (!p)
845
- throw sandboxUnavailable();
846
- return p;
2440
+ catch (err) {
2441
+ // a throw after a resume (a lost lease, an abort, a failed write): the row still says
2442
+ // suspended, so the instance is suspended again (best effort) before the error goes on
2443
+ const left = resumedHere;
2444
+ if (left !== null)
2445
+ await this.bestEffort(id, "suspend the instance again after a failed retirement", (s) => left.impl.suspend(left.handle, s));
2446
+ throw err;
2447
+ }
2448
+ // a use runs on the instance this gate resumed; anything else leaves it as its row says
2449
+ const still = resumedHere;
2450
+ if (still !== null && (pending || resumed === undefined)) {
2451
+ await this.bestEffort(id, "suspend the instance again after an exact cancel", (s) => still.impl.suspend(still.handle, s));
2452
+ }
2453
+ else if (still !== null && resumed !== undefined)
2454
+ resumed.resumed = true;
2455
+ if (pending)
2456
+ throw failed
2457
+ ? retirementPending()
2458
+ : cloudPermanent
2459
+ ? recreateRequired()
2460
+ : unknownBoot
2461
+ ? replaceRequired()
2462
+ : restartRequired();
2463
+ return now;
847
2464
  }
848
2465
  /**
849
2466
  * A fenced write: only while the lease holds and the row's generation is still the one read
@@ -853,9 +2470,9 @@ let SandboxService = class SandboxService {
853
2470
  if (lease.signal.aborted)
854
2471
  throw new SandboxLockLostError(id);
855
2472
  const r = await this.db
856
- .updateTable("environment_instances")
2473
+ .updateTable("device_instances")
857
2474
  .set({ ...set, generation: fence.gen + 1 })
858
- .where("environment_id", "=", id)
2475
+ .where("device_id", "=", id)
859
2476
  .where("generation", "=", fence.gen)
860
2477
  .returning("created_at")
861
2478
  .executeTakeFirst();
@@ -867,8 +2484,8 @@ let SandboxService = class SandboxService {
867
2484
  /** Sweep candidates: those whose last sweep failed come last, the rest least recently used first. */
868
2485
  async candidates(due) {
869
2486
  return await this.db
870
- .selectFrom("environment_instances")
871
- .select(["environment_id", "running_since"])
2487
+ .selectFrom("device_instances")
2488
+ .select(["device_id", "running_since"])
872
2489
  .where(due)
873
2490
  .orderBy(sql `sweep_failed_at ASC NULLS FIRST`)
874
2491
  .orderBy("last_used_at")
@@ -877,17 +2494,17 @@ let SandboxService = class SandboxService {
877
2494
  }
878
2495
  /**
879
2496
  * One try at the exclusive lease: null → false; else runs `fn`. With `overdue` (past
880
- * `maxRunningMinutes`) a busy environment gets the intent for about a second, so new commands
2497
+ * `maxRunningMinutes`) a busy device gets the intent for about a second, so new commands
881
2498
  * wait briefly and the sweep gets in if the running ones end. Failures are warned, recorded in
882
2499
  * `sweep_failed_at` (sorted last next time) and return false.
883
2500
  */
884
- async tryLocked(environmentId, fn, overdue = false) {
2501
+ async tryLocked(deviceId, fn, overdue = false) {
885
2502
  let lease;
886
2503
  try {
887
- lease = await this.leases.tryExclusive(environmentId);
2504
+ lease = await this.leases.tryExclusive(deviceId);
888
2505
  if (!lease && overdue) {
889
2506
  lease = await this.leases
890
- .acquireExclusive(environmentId, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS), Math.max(this.pollMs * 2, SWEEP_INTENT_WAIT_MS), { intent: true })
2507
+ .acquireExclusive(deviceId, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS), Math.max(this.pollMs * 2, SWEEP_INTENT_WAIT_MS), { intent: true })
891
2508
  .catch((err) => {
892
2509
  if (err instanceof ApiError && err.code === "sandbox.busy")
893
2510
  return null;
@@ -896,7 +2513,7 @@ let SandboxService = class SandboxService {
896
2513
  }
897
2514
  }
898
2515
  catch (err) {
899
- this.log.warn("cannot take sandbox lock", { environmentId, err });
2516
+ this.log.warn("cannot take sandbox lock", { deviceId, err });
900
2517
  return false;
901
2518
  }
902
2519
  if (!lease)
@@ -905,11 +2522,11 @@ let SandboxService = class SandboxService {
905
2522
  return await fn(lease);
906
2523
  }
907
2524
  catch (err) {
908
- this.log.warn("sandbox maintenance failed; will retry", { environmentId, err });
2525
+ this.log.warn("sandbox maintenance failed; will retry", { deviceId, err });
909
2526
  await this.db
910
- .updateTable("environment_instances")
2527
+ .updateTable("device_instances")
911
2528
  .set({ sweep_failed_at: sql `now()` })
912
- .where("environment_id", "=", environmentId)
2529
+ .where("device_id", "=", deviceId)
913
2530
  .execute()
914
2531
  .catch(() => { });
915
2532
  return false;
@@ -919,124 +2536,196 @@ let SandboxService = class SandboxService {
919
2536
  }
920
2537
  }
921
2538
  /**
922
- * Under the exclusive lease: make the environment's instance run. `gone`: the instance a holder
2539
+ * Under the exclusive lease: make the device's instance run. `gone`: the instance a holder
923
2540
  * found gone; when it is still the recorded one it is rebuilt, when another holder already
924
2541
  * rebuilt it the new one is used.
925
2542
  */
926
2543
  async ensure(ctx, p, held, signal, gone) {
927
- const id = ctx.environmentId;
928
- // Only a live environment of the caller's org gets a row, with the environment's own org; a
2544
+ const id = ctx.deviceId;
2545
+ // Only a live device of the caller's org gets a row, with the device's own org; a
929
2546
  // row made earlier (another use) keeps its file system handle.
930
2547
  await this.db
931
- .insertInto("environment_instances")
932
- .columns(["environment_id", "org_id", "provider", "status"])
2548
+ .insertInto("device_instances")
2549
+ .columns(["device_id", "org_id", "provider", "status"])
933
2550
  .expression((eb) => eb
934
- .selectFrom("environments")
2551
+ .selectFrom("devices")
935
2552
  .select((e) => [
936
- "environments.id",
937
- "environments.org_id",
2553
+ "devices.id",
2554
+ "devices.org_id",
938
2555
  e.val(p.plugin).as("provider"),
939
2556
  e.val("creating").as("status"),
940
2557
  ])
941
- .where("environments.id", "=", id)
942
- .where("environments.org_id", "=", ctx.orgId)
943
- .where("environments.deleted_at", "is", null))
944
- .onConflict((oc) => oc.column("environment_id").doNothing())
2558
+ .where("devices.id", "=", id)
2559
+ .where("devices.org_id", "=", ctx.orgId)
2560
+ .where("devices.deleted_at", "is", null))
2561
+ .onConflict((oc) => oc.column("device_id").doNothing())
945
2562
  .execute();
946
- // Under the lease: a use that waited behind destroyEnvironment (or raced a deletion) must not
947
- // bring the environment's provider resources back.
2563
+ // Under the lease: a use that waited behind destroyDevice (or raced a deletion) must not
2564
+ // bring the device's provider resources back.
948
2565
  const live = await this.db
949
- .selectFrom("environments")
2566
+ .selectFrom("devices")
950
2567
  .select("id")
951
2568
  .where("id", "=", id)
952
2569
  .where("org_id", "=", ctx.orgId)
953
2570
  .where("deleted_at", "is", null)
954
2571
  .executeTakeFirst();
955
2572
  if (!live)
956
- throw environmentNotFound();
957
- const row = await this.db
958
- .selectFrom("environment_instances")
2573
+ throw deviceNotFound();
2574
+ const read = await this.db
2575
+ .selectFrom("device_instances")
959
2576
  .selectAll()
960
- .where("environment_id", "=", id)
2577
+ .where("device_id", "=", id)
961
2578
  .executeTakeFirst();
962
- if (!row)
963
- throw environmentNotFound();
964
- if (row.org_id !== ctx.orgId)
2579
+ if (!read)
2580
+ throw deviceNotFound();
2581
+ if (read.org_id !== ctx.orgId)
965
2582
  throw this.foreign(ctx);
966
- const fence = { gen: row.generation };
2583
+ const fence = { gen: read.generation };
967
2584
  // Every acquisition first does a fenced increment: an old holder whose lease expired while it
968
2585
  // kept running (a stalled sweep) then fails its next write.
969
2586
  await this.fenced(held, id, fence, {});
970
- if (row.fs_status === "lost")
971
- throw environmentFilesLost();
972
- if (row.provider !== null &&
973
- row.provider !== p.plugin &&
974
- (row.fs_status !== "none" || row.handle !== null)) {
975
- throw otherProvider(row.provider);
976
- }
977
- if (row.provider !== null &&
978
- row.provider !== p.plugin &&
979
- row.fs_status === "none" &&
980
- row.status === "creating") {
981
- // a create by the previous provider ended before its file system was recorded: that
982
- // provider may have made it by name, and nothing else would ever destroy it
983
- await this.dropUnrecordedFiles(id, row.provider, signal);
984
- }
985
- const handle = row.handle;
986
- const createdAt = row.created_at.getTime();
987
- const fsId = row.fs_handle?.id ?? "";
988
- if (handle && isInstance(row, gone) && row.status === "running") {
989
- const created = await this.create(ctx, p, held, row, fence, signal);
990
- return { ...created, info: { fresh: true, restarted: true }, fence };
991
- }
992
- if (handle && row.status === "running") {
993
- return { handle, createdAt, fsId, info: { fresh: false, restarted: false }, fence };
994
- }
995
- if (handle && row.status === "suspended") {
996
- const r = await p.impl.resume(handle, signal);
997
- if (r === "resumed") {
998
- await this.fenced(held, id, fence, {
999
- status: "running",
1000
- running_since: sql `now()`,
1001
- suspended_at: null,
1002
- sweep_failed_at: null,
2587
+ // the retirement gate (8.5), before any use, resume, rebuild, provider switch or bind: an
2588
+ // old incarnation that may run legacy work is destroyed (cloud, confirmed) or refuses
2589
+ signal.throwIfAborted();
2590
+ const gate = { resumed: false, running: false };
2591
+ const row = (await this.retireIncarnations(id, held, read, fence, undefined, gate)) ?? read;
2592
+ try {
2593
+ if (row.fs_status === "lost")
2594
+ throw deviceFilesLost(p.plugin === LOCAL_PROVIDER);
2595
+ if (row.provider !== null &&
2596
+ row.provider !== p.plugin &&
2597
+ (row.fs_status !== "none" || row.handle !== null)) {
2598
+ throw otherProvider(row.provider);
2599
+ }
2600
+ if (row.provider !== null &&
2601
+ row.provider !== p.plugin &&
2602
+ row.fs_status === "none" &&
2603
+ row.status === "creating") {
2604
+ // a create by the previous provider ended before its file system was recorded: that
2605
+ // provider may have made it by name, and nothing else would ever destroy it
2606
+ await this.dropUnrecordedFiles(id, row.provider, signal);
2607
+ }
2608
+ // read under the lease, after the fence moved: a value read before the wait may be stale
2609
+ // (another replica may have changed the mode meanwhile)
2610
+ const want = await this.wantedLimits(ctx, p, row);
2611
+ const handle = row.handle;
2612
+ const createdAt = row.created_at.getTime();
2613
+ const fsResets = row.fs_resets;
2614
+ if (handle && isInstance(row, gone) && row.status === "running") {
2615
+ const created = await this.create(ctx, p, held, row, fence, signal, want);
2616
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2617
+ }
2618
+ // the staged path's activation (B-8): an instance committed before the binder existed has no
2619
+ // binding for its generation and never can get one; past the retirement gate above, a new
2620
+ // generation is created (and committed with its binding) in its place
2621
+ if (handle &&
2622
+ p.binder &&
2623
+ (row.status === "running" || row.status === "suspended") &&
2624
+ (await p.binder.status(id)) === null) {
2625
+ this.log.info("instance without a committed binding; creating a bound generation", {
2626
+ deviceId: id,
1003
2627
  });
1004
- return {
1005
- handle,
1006
- createdAt,
1007
- fsId,
1008
- info: { fresh: false, restarted: false },
1009
- fence,
1010
- resumed: true,
1011
- };
2628
+ const created = await this.create(ctx, p, held, row, fence, signal, want);
2629
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
1012
2630
  }
1013
- this.log.info("sandbox instance is gone at the provider; recreating", {
1014
- environmentId: id,
1015
- });
2631
+ if (handle && row.status === "running") {
2632
+ if (want !== null && this.mustApply(row, p, want)) {
2633
+ const created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want);
2634
+ if (created)
2635
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2636
+ }
2637
+ return { handle, createdAt, fsResets, info: { fresh: false, restarted: false }, fence };
2638
+ }
2639
+ if (handle && row.status === "suspended") {
2640
+ // the retirement gate may have resumed it already, to cancel revoked starts exactly (B-22)
2641
+ const r = gate.resumed ? "resumed" : await p.impl.resume(handle, signal);
2642
+ if (r === "resumed") {
2643
+ const incarnation = { provider: p.plugin, generation: String(createdAt) };
2644
+ // the new limits first: the row says running only once the instance runs with them
2645
+ if (want !== null && this.mustApply(row, p, want)) {
2646
+ let created;
2647
+ try {
2648
+ created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want);
2649
+ }
2650
+ catch (err) {
2651
+ // the work a pause brought back is revoked exactly, never killed broadly; the row
2652
+ // still says suspended, so the next use resumes and revokes again
2653
+ await this.revokeIncarnation(id, incarnation, handle, p, AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS), false).catch((e) => this.log.warn("cannot revoke the operations left after a failed limits change", {
2654
+ deviceId: id,
2655
+ err: e,
2656
+ }));
2657
+ throw err;
2658
+ }
2659
+ if (created) {
2660
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2661
+ }
2662
+ }
2663
+ // the work a pause brought back (every admitted, dispatching and started-or-unknown
2664
+ // operation of this generation) is revoked before the row says running; the revokes are
2665
+ // delivered before the downgrade. A failure fails the use closed: the instance is
2666
+ // suspended again (best effort, its failure only warned), the row still says
2667
+ // suspended, and the next use resumes and revokes again
2668
+ try {
2669
+ await runOutsideTransaction(() => this.operationIntents.revokeIncarnation(id, incarnation));
2670
+ }
2671
+ catch (err) {
2672
+ await this.bestEffort(id, "suspend the instance again after a failed revocation", (s) => p.impl.suspend(handle, s));
2673
+ throw err;
2674
+ }
2675
+ await this.fenced(held, id, fence, {
2676
+ status: "running",
2677
+ running_since: sql `now()`,
2678
+ suspended_at: null,
2679
+ sweep_failed_at: null,
2680
+ });
2681
+ gate.running = true;
2682
+ return {
2683
+ handle,
2684
+ createdAt,
2685
+ fsResets,
2686
+ info: { fresh: false, restarted: false },
2687
+ fence,
2688
+ resumed: true,
2689
+ };
2690
+ }
2691
+ this.log.info("sandbox instance is gone at the provider; recreating", {
2692
+ deviceId: id,
2693
+ });
2694
+ }
2695
+ const created = await this.create(ctx, p, held, row, fence, signal, want);
2696
+ // had_instance only ever becomes true: any earlier instance (even if a rebuild failed since)
2697
+ // makes this one a restart on the kept files
2698
+ return {
2699
+ ...created,
2700
+ fsResets,
2701
+ info: { fresh: true, restarted: row.had_instance && row.fs_status === "ready" },
2702
+ fence,
2703
+ };
2704
+ }
2705
+ catch (err) {
2706
+ // the gate resumed the instance for an exact cancel (B-22) and this use failed before its
2707
+ // row said running: suspended again (best effort), as the row still says
2708
+ const resumedHandle = row.handle;
2709
+ if (gate.resumed && !gate.running && resumedHandle)
2710
+ await this.bestEffort(id, "suspend the instance again after a failed use", (s) => p.impl.suspend(resumedHandle, s));
2711
+ throw err;
1016
2712
  }
1017
- const created = await this.create(ctx, p, held, row, fence, signal);
1018
- // had_instance only ever becomes true: any earlier instance (even if a rebuild failed since)
1019
- // makes this one a restart on the kept files
1020
- return {
1021
- ...created,
1022
- info: { fresh: true, restarted: row.had_instance && row.fs_status === "ready" },
1023
- fence,
1024
- };
1025
2713
  }
1026
2714
  /**
1027
2715
  * Under the lease: fenced reset to `creating`, the file system when there is none
1028
2716
  * (`createFileSystem`, its handle written fenced), then the instance on it, then a fenced write
1029
2717
  * of the instance handle. `FileSystemGoneError` from `create` records `fs_status = 'lost'` and
1030
- * throws `environment.files_lost`. When the instance handle cannot be written (lease lost), the
2718
+ * throws `device.files_lost`. When the instance handle cannot be written (lease lost), the
1031
2719
  * new instance is destroyed (best effort) before {@link SandboxLockLostError} is thrown.
1032
2720
  */
1033
- async create(ctx, p, held, row, fence, signal) {
1034
- const id = ctx.environmentId;
1035
- const name = environmentResourceName(id);
2721
+ async create(ctx, p, held, row, fence, signal, want) {
2722
+ const id = ctx.deviceId;
2723
+ const name = deviceResourceName(id);
1036
2724
  await this.fenced(held, id, fence, {
1037
2725
  org_id: ctx.orgId,
1038
2726
  provider: p.plugin,
1039
2727
  handle: null,
2728
+ permission_roots: JSON.stringify(row.permission_roots ?? (row.handle ? rootsOf(row.handle) : DEFAULT_SANDBOX_ROOTS)),
1040
2729
  status: "creating",
1041
2730
  last_used_at: sql `now()`,
1042
2731
  running_since: null,
@@ -1044,23 +2733,36 @@ let SandboxService = class SandboxService {
1044
2733
  destroyed_at: null,
1045
2734
  sweep_failed_at: null,
1046
2735
  });
1047
- // the org's effective limits apply at creation only, so a changed setting reaches only
1048
- // instances created afterwards
1049
- const limits = await this.orgLimits(ctx.orgId);
2736
+ // the device's effective limits apply at creation (a changed mode or network kind is applied
2737
+ // on use, see applyLimits; other changes reach only instances created afterwards)
2738
+ const limits = want ??
2739
+ (await this.deviceLimits(ctx, {
2740
+ source: p.plugin === LOCAL_PROVIDER ? "local" : "cloud",
2741
+ }));
2742
+ // the record says what is in force: a provider whose limits are fixed at its file system
2743
+ // records them with the file system, any other with the instance (spec §7.1)
2744
+ const record = instanceLimitsJson(appliedOf(limits));
2745
+ const atFileSystem = p.impl.limitsApplyAt === "fileSystem";
1050
2746
  const cfg = this.config.get().sandbox;
1051
2747
  let fs = row.fs_status === "ready" && (row.provider === null || row.provider === p.plugin)
1052
2748
  ? row.fs_handle
1053
2749
  : null;
1054
2750
  if (fs === null) {
1055
- fs = await p.impl.createFileSystem({ name, limits, signal });
2751
+ try {
2752
+ fs = await p.impl.createFileSystem({ name, limits, signal });
2753
+ }
2754
+ catch (err) {
2755
+ throw providerRefusal(this.log, err, { deviceId: id, provider: p.plugin, op: "createFileSystem" }, limits, signal);
2756
+ }
1056
2757
  // A lost lease fails this write and leaves the file system alone: createFileSystem returns
1057
2758
  // the existing one for a name, so the new holder may already use it, files and all.
1058
2759
  await this.fenced(held, id, fence, {
1059
2760
  provider: p.plugin,
1060
2761
  fs_handle: JSON.stringify(fs),
1061
2762
  fs_status: "ready",
2763
+ ...(atFileSystem && { instance_limits: record }),
1062
2764
  });
1063
- this.log.info("environment file system created", { environmentId: id, provider: p.plugin });
2765
+ this.log.info("device file system created", { deviceId: id, provider: p.plugin });
1064
2766
  }
1065
2767
  let handle;
1066
2768
  try {
@@ -1073,61 +2775,180 @@ let SandboxService = class SandboxService {
1073
2775
  });
1074
2776
  }
1075
2777
  catch (err) {
1076
- if (!isFileSystemGoneError(err))
1077
- throw err;
1078
- this.log.warn("environment file system is gone at the provider; its files are lost", {
1079
- environmentId: id,
2778
+ if (!isFileSystemGoneError(err)) {
2779
+ throw providerRefusal(this.log, err, { deviceId: id, provider: p.plugin, op: "create" }, limits, signal);
2780
+ }
2781
+ this.log.warn("device file system is gone at the provider; its files are lost", {
2782
+ deviceId: id,
1080
2783
  provider: p.plugin,
1081
2784
  });
1082
2785
  await this.fenced(held, id, fence, { fs_status: "lost", status: "none" });
1083
- throw environmentFilesLost();
2786
+ throw deviceFilesLost(p.plugin === LOCAL_PROVIDER);
1084
2787
  }
1085
2788
  let createdAt;
1086
2789
  try {
1087
- createdAt = await this.fenced(held, id, fence, {
2790
+ // B-15: a cloud instance's permission support, read from it under the lease and recorded
2791
+ // with the handle commit (an unread report never fails the create: the instance stays
2792
+ // unprobed until a later use records it)
2793
+ const support = (await this.recordsCloudSupport(ctx, p))
2794
+ ? await this.cloudSupport(id, p, handle, signal)
2795
+ : undefined;
2796
+ createdAt = await runOutsideTransaction(() => this.instanceWrites.commitHandle(ctx.orgId, id, fence.gen, rootsOf(handle), {
1088
2797
  status: "running",
1089
2798
  handle: JSON.stringify(handle),
1090
2799
  had_instance: true,
1091
- created_at: sql `now()`,
2800
+ // created_at is the generation commitHandle allocates (never a reused millisecond)
1092
2801
  running_since: sql `now()`,
1093
2802
  last_used_at: sql `now()`,
1094
- });
2803
+ ...(!atFileSystem && { instance_limits: record }),
2804
+ }, held.signal, support));
2805
+ fence.gen++;
1095
2806
  }
1096
2807
  catch (e) {
1097
- // Lease lost before the handle was recorded: destroy the new instance (best effort) so it
1098
- // does not leak. A provider that reuses instances by name (Ruling M10) may then hit the one
1099
- // the new holder just resumed or created; that heals: its next provider call throws
1100
- // SandboxGoneError (or resume returns gone) and withSandbox rebuilds in place. The file
1101
- // system is never touched here.
2808
+ // Lease lost (or the device read failed) before the handle was recorded: destroy the new
2809
+ // instance (best effort) so it does not leak. A provider that reuses instances by name
2810
+ // (Ruling M10) may then hit the one the new holder just resumed or created; that heals:
2811
+ // its next provider call throws SandboxGoneError (or resume returns gone) and withSandbox
2812
+ // rebuilds in place. The file system is never touched here.
1102
2813
  await p.impl.destroy(handle, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)).catch((err) => this.log.warn("cannot destroy sandbox created after the lock was lost", {
1103
- environmentId: id,
2814
+ deviceId: id,
1104
2815
  err,
1105
2816
  }));
1106
2817
  throw e;
1107
2818
  }
1108
- this.log.info("sandbox created", { environmentId: id, provider: p.plugin });
1109
- return { handle, createdAt: createdAt.getTime(), fsId: fs.id };
2819
+ this.log.info("sandbox created", { deviceId: id, provider: p.plugin });
2820
+ return { handle, createdAt: createdAt.getTime() };
1110
2821
  }
1111
2822
  /**
1112
- * Destroys the file system another provider may have made under the environment's name without
2823
+ * Under the exclusive lease, on the running instance `handle` of `row` whose mode or network
2824
+ * kind differs from `want` (auto mode spec §4.2): the provider's `update` when it has
2825
+ * one; `updated` records `want`. Otherwise (`recreate`, no `update`, or the instance found gone
2826
+ * by `update`) the instance is destroyed and created again on the kept files, which records
2827
+ * `want` and is returned (the caller reports a restart). A provider whose limits are fixed at
2828
+ * its file system is not recreated (that would not apply them): `want` is recorded as
2829
+ * `unapplied` and the instance keeps running as is until a file reset.
2830
+ *
2831
+ * An `update` that fails otherwise never records `want`: a provider whose limits apply at
2832
+ * instance create is recreated (warned); after an abort, or for a provider bound to its file
2833
+ * system, the instance is suspended ({@link quarantine}) and the error thrown, so the next use
2834
+ * resumes it and tries again.
2835
+ */
2836
+ async applyLimits(ctx, p, held, row, handle, fence, signal, want) {
2837
+ const id = ctx.deviceId;
2838
+ const target = appliedOf(want);
2839
+ const was = readInstanceLimits(row.instance_limits).applied;
2840
+ const facts = { deviceId: id, provider: p.plugin, from: was, to: target };
2841
+ let gone = false;
2842
+ if (p.impl.update) {
2843
+ try {
2844
+ if ((await p.impl.update(handle, want, signal)) === "updated") {
2845
+ await this.fenced(held, id, fence, { instance_limits: instanceLimitsJson(target) });
2846
+ this.log.info("sandbox instance limits updated", facts);
2847
+ return null;
2848
+ }
2849
+ }
2850
+ catch (err) {
2851
+ if (isSandboxGoneError(err)) {
2852
+ gone = true;
2853
+ }
2854
+ else if (signal.aborted || p.impl.limitsApplyAt === "fileSystem") {
2855
+ // the instance may run with half-applied limits and cannot be recreated here: stop it,
2856
+ // so the next use resumes it and applies them again
2857
+ await this.quarantine(held, id, handle, p, fence, {
2858
+ provider: p.plugin,
2859
+ generation: String(row.created_at.getTime()),
2860
+ });
2861
+ // a provider bound to its file system that refuses the new network (E2B)
2862
+ throw providerRefusal(this.log, err, { deviceId: id, provider: p.plugin, op: "update" }, want, signal);
2863
+ }
2864
+ else {
2865
+ // a new instance gets the limits at create: recreate rather than trust a failed update
2866
+ this.log.warn("sandbox limits update failed; recreating the instance", {
2867
+ ...facts,
2868
+ err,
2869
+ });
2870
+ }
2871
+ }
2872
+ }
2873
+ if (p.impl.limitsApplyAt === "fileSystem" && !gone) {
2874
+ await this.fenced(held, id, fence, { instance_limits: instanceLimitsJson(was, target) });
2875
+ this.log.info("sandbox limits changed; they apply when the device's files are reset", facts);
2876
+ return null;
2877
+ }
2878
+ this.log.info("sandbox limits changed; recreating the instance on the kept files", facts);
2879
+ if (!gone) {
2880
+ try {
2881
+ await p.impl.destroy(handle, signal);
2882
+ }
2883
+ catch (err) {
2884
+ // `create` replaces an instance of the same name anyway
2885
+ if (signal.aborted)
2886
+ throw err;
2887
+ this.log.warn("cannot destroy the sandbox instance before recreating it", {
2888
+ deviceId: id,
2889
+ err,
2890
+ });
2891
+ }
2892
+ }
2893
+ return await this.create(ctx, p, held, row, fence, signal, want);
2894
+ }
2895
+ /**
2896
+ * After a failed `update` that cannot be repaired by a recreate: best effort, with fresh short
2897
+ * signals (the use's own may be aborted), suspends the instance (or revokes its operations) and
2898
+ * records it suspended (fenced: a lost lease leaves the record to the new holder).
2899
+ */
2900
+ async quarantine(held, id, handle, p, fence, incarnation) {
2901
+ const suspended = await this.bestEffort(id, "suspend after a failed limits update", (s) => p.impl.suspend(handle, s));
2902
+ if (!suspended) {
2903
+ // still running with half-applied limits: its leftover operations are revoked exactly (the
2904
+ // row is recorded suspended, so the next resume revokes again)
2905
+ await this.bestEffort(id, "revoke the operations after a failed limits update", (s) => this.revokeIncarnation(id, incarnation, handle, p, s, false));
2906
+ }
2907
+ try {
2908
+ await this.fenced(held, id, fence, {
2909
+ status: "suspended",
2910
+ suspended_at: sql `now()`,
2911
+ running_since: null,
2912
+ });
2913
+ }
2914
+ catch (err) {
2915
+ this.log.warn("cannot record the sandbox suspended after a failed limits update", {
2916
+ deviceId: id,
2917
+ err,
2918
+ });
2919
+ }
2920
+ }
2921
+ /** Runs `call` with its own short signal; a failure is warned and returns false. */
2922
+ async bestEffort(deviceId, what, call) {
2923
+ try {
2924
+ await call(AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS));
2925
+ return true;
2926
+ }
2927
+ catch (err) {
2928
+ this.log.warn(`cannot ${what}`, { deviceId, err });
2929
+ return false;
2930
+ }
2931
+ }
2932
+ /**
2933
+ * Destroys the file system another provider may have made under the device's name without
1113
2934
  * the kernel recording it (`destroyFileSystemByName`; not there is success). That provider not
1114
- * loaded, or a failure, is only warned (the files may leak there) so the environment stays
2935
+ * loaded, or a failure, is only warned (the files may leak there) so the device stays
1115
2936
  * usable; an abort is thrown.
1116
2937
  */
1117
2938
  async dropUnrecordedFiles(id, provider, signal) {
1118
- const old = this.providers.lookup(provider);
2939
+ const old = this.providers.forName(provider)?.impl;
1119
2940
  if (!old) {
1120
- this.log.warn("environment file system may have been made by a provider that is not loaded; it may leak", { environmentId: id, provider });
2941
+ this.log.warn("device file system may have been made by a provider that is not loaded; it may leak", { deviceId: id, provider });
1121
2942
  return;
1122
2943
  }
1123
2944
  try {
1124
- await old.destroyFileSystemByName(environmentResourceName(id), signal);
2945
+ await old.destroyFileSystemByName(deviceResourceName(id), signal);
1125
2946
  }
1126
2947
  catch (err) {
1127
2948
  if (signal.aborted)
1128
2949
  throw err;
1129
2950
  this.log.warn("cannot destroy the file system of the previous sandbox provider", {
1130
- environmentId: id,
2951
+ deviceId: id,
1131
2952
  provider,
1132
2953
  err,
1133
2954
  });
@@ -1137,23 +2958,27 @@ let SandboxService = class SandboxService {
1137
2958
  * Destroys an instance of another provider with that provider: still loaded and destroyed →
1138
2959
  * false; otherwise warns and returns true (the record must be kept).
1139
2960
  */
1140
- async retire(id, provider, handle, signal) {
1141
- const old = this.providers.lookup(provider);
2961
+ async retire(id, provider, handle, signal,
2962
+ /** The retired incarnation's generation when known: its confirmed destroy is recorded (M4). */
2963
+ generation) {
2964
+ const old = this.providers.forName(provider)?.impl;
1142
2965
  if (old) {
1143
2966
  try {
1144
2967
  await old.destroy(handle, AbortSignal.any([signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]));
2968
+ if (generation !== undefined && isCloudProvider(provider))
2969
+ await this.retirement.recordDestruction(id, provider, generation);
1145
2970
  return false;
1146
2971
  }
1147
2972
  catch (err) {
1148
2973
  this.log.warn("cannot destroy sandbox instance of the previous provider", {
1149
- environmentId: id,
2974
+ deviceId: id,
1150
2975
  provider,
1151
2976
  err,
1152
2977
  });
1153
2978
  return true;
1154
2979
  }
1155
2980
  }
1156
- this.log.warn("sandbox was created by another provider that is not loaded; its instance may leak", { environmentId: id, provider });
2981
+ this.log.warn("sandbox was created by another provider that is not loaded; its instance may leak", { deviceId: id, provider });
1157
2982
  return true;
1158
2983
  }
1159
2984
  /**
@@ -1162,21 +2987,21 @@ let SandboxService = class SandboxService {
1162
2987
  * name. Returns the `prev_*` patch for instances that could not be destroyed.
1163
2988
  */
1164
2989
  async destroyInstance(row, p, signal) {
1165
- const id = row.environment_id;
2990
+ const id = row.device_id;
1166
2991
  const owner = row.provider ?? p.plugin;
1167
2992
  let prev = {};
1168
2993
  if (row.handle && owner === p.plugin) {
1169
2994
  await p.impl.destroy(row.handle, signal);
1170
2995
  }
1171
2996
  else if (row.handle && row.status !== "destroyed") {
1172
- if (await this.retire(id, owner, row.handle, signal)) {
2997
+ if (await this.retire(id, owner, row.handle, signal, String(row.created_at.getTime()))) {
1173
2998
  prev = { prev_provider: owner, prev_handle: JSON.stringify(row.handle) };
1174
2999
  }
1175
3000
  }
1176
3001
  else if (!row.handle && row.status === "creating") {
1177
3002
  // the provider may have built it already: only the name finds it
1178
- const impl = owner === p.plugin ? p.impl : this.providers.lookup(owner);
1179
- await impl?.destroyByName(environmentResourceName(id), signal);
3003
+ const impl = owner === p.plugin ? p.impl : this.providers.forName(owner)?.impl;
3004
+ await impl?.destroyByName(deviceResourceName(id), signal);
1180
3005
  }
1181
3006
  if (row.prev_handle && row.prev_provider && !("prev_handle" in prev)) {
1182
3007
  if (!(await this.retire(id, row.prev_provider, row.prev_handle, signal))) {
@@ -1192,17 +3017,17 @@ let SandboxService = class SandboxService {
1192
3017
  * warns (the files leak at that provider).
1193
3018
  */
1194
3019
  async destroyFiles(row, p, signal, lenient = false) {
1195
- const id = row.environment_id;
3020
+ const id = row.device_id;
1196
3021
  const owner = row.provider ?? p.plugin;
1197
- const impl = owner === p.plugin ? p.impl : this.providers.lookup(owner);
3022
+ const impl = owner === p.plugin ? p.impl : this.providers.forName(owner)?.impl;
1198
3023
  if (!impl) {
1199
3024
  if (row.fs_handle === null)
1200
3025
  return;
1201
3026
  if (!lenient) {
1202
- throw new Error(`cannot destroy the file system of environment ${id}: its sandbox provider ${owner} is not loaded`);
3027
+ throw new Error(`cannot destroy the file system of device ${id}: its sandbox provider ${owner} is not loaded`);
1203
3028
  }
1204
- this.log.warn("environment file system of a provider that is not loaded is leaked", {
1205
- environmentId: id,
3029
+ this.log.warn("device file system of a provider that is not loaded is leaked", {
3030
+ deviceId: id,
1206
3031
  provider: owner,
1207
3032
  });
1208
3033
  return;
@@ -1210,18 +3035,23 @@ let SandboxService = class SandboxService {
1210
3035
  if (row.fs_handle !== null)
1211
3036
  await impl.destroyFileSystem(row.fs_handle, signal);
1212
3037
  else
1213
- await impl.destroyFileSystemByName(environmentResourceName(id), signal);
3038
+ await impl.destroyFileSystemByName(deviceResourceName(id), signal);
1214
3039
  }
1215
3040
  /**
1216
3041
  * Under the lease: `instance` destroys the instance and marks the row `destroyed` (the file
1217
- * system stays); `environment` also destroys the file system and deletes the row.
3042
+ * system stays); `device` also destroys the file system and deletes the row.
1218
3043
  */
1219
3044
  async destroyRow(row, p, held, mode) {
1220
- const id = row.environment_id;
3045
+ const id = row.device_id;
1221
3046
  const fence = { gen: row.generation };
1222
3047
  const signal = opSignal(held);
1223
3048
  const prev = await this.destroyInstance(row, p, signal);
1224
- if (mode === "environment")
3049
+ // the provider's destroy resolved: confirmed destruction of exactly this cloud incarnation
3050
+ // (8.5 evidence); a kernel-internal (local) destroy is a no-op and is never recorded
3051
+ const owner = row.provider ?? p.plugin;
3052
+ if (row.handle && owner === p.plugin && isCloudProvider(owner))
3053
+ await this.retirement.recordDestruction(id, owner, String(row.created_at.getTime()));
3054
+ if (mode === "device")
1225
3055
  await this.destroyFiles(row, p, signal);
1226
3056
  if (!(await held.renew()))
1227
3057
  throw new SandboxLockLostError(id);
@@ -1233,17 +3063,17 @@ let SandboxService = class SandboxService {
1233
3063
  sweep_failed_at: null,
1234
3064
  ...prev,
1235
3065
  });
1236
- this.log.info("sandbox instance destroyed", { environmentId: id });
3066
+ this.log.info("sandbox instance destroyed", { deviceId: id });
1237
3067
  return;
1238
3068
  }
1239
3069
  const r = await this.db
1240
- .deleteFrom("environment_instances")
1241
- .where("environment_id", "=", id)
3070
+ .deleteFrom("device_instances")
3071
+ .where("device_id", "=", id)
1242
3072
  .where("generation", "=", fence.gen)
1243
3073
  .executeTakeFirst();
1244
3074
  if (Number(r.numDeletedRows) !== 1)
1245
3075
  throw new SandboxLockLostError(id, "generation");
1246
- this.log.info("environment destroyed", { environmentId: id });
3076
+ this.log.info("device destroyed", { deviceId: id });
1247
3077
  }
1248
3078
  /** Due for suspension: made by this provider, running, and idle or running for too long. */
1249
3079
  suspendDue(now, plugin) {
@@ -1256,18 +3086,29 @@ let SandboxService = class SandboxService {
1256
3086
  eb.or([eb("last_used_at", "<", idleBefore), eb("running_since", "<", runningBefore)]),
1257
3087
  ]);
1258
3088
  }
1259
- /** The environment was deleted, or its org was: the instance and the files go. */
1260
- environmentGone(eb) {
3089
+ /** The provider of an instance row: an internal one (`@local`) by name, else the cloud one. */
3090
+ rowProvider(row) {
3091
+ return providerForDevice(this.providers, row.provider);
3092
+ }
3093
+ /**
3094
+ * A row the idle sweeps may touch: not on a kernel-internal provider (`@local` instances live on
3095
+ * people's machines and are never suspended or destroyed for inactivity).
3096
+ */
3097
+ cloudRow(eb) {
3098
+ return eb.or([eb("provider", "is", null), eb("provider", "not like", "@%")]);
3099
+ }
3100
+ /** The device was deleted, or its org was: the instance and the files go. */
3101
+ deviceGone(eb) {
1261
3102
  return eb.or([
1262
3103
  eb.exists(eb
1263
- .selectFrom("environments")
1264
- .select("environments.id")
1265
- .whereRef("environments.id", "=", "environment_instances.environment_id")
1266
- .where("environments.deleted_at", "is not", null)),
3104
+ .selectFrom("devices")
3105
+ .select("devices.id")
3106
+ .whereRef("devices.id", "=", "device_instances.device_id")
3107
+ .where("devices.deleted_at", "is not", null)),
1267
3108
  eb.exists(eb
1268
3109
  .selectFrom("orgs")
1269
3110
  .select("orgs.id")
1270
- .whereRef("orgs.id", "=", "environment_instances.org_id")
3111
+ .whereRef("orgs.id", "=", "device_instances.org_id")
1271
3112
  .where("orgs.deleted_at", "is not", null)),
1272
3113
  ]);
1273
3114
  }
@@ -1289,6 +3130,11 @@ SandboxService = __decorate([
1289
3130
  __param(3, Inject(SandboxProviders)),
1290
3131
  __param(4, Inject(KernelConfigService)),
1291
3132
  __param(5, Inject(KERNEL_LOGGER)),
1292
- __param(6, Inject(BackgroundTaskStore))
3133
+ __param(6, Inject(PermissionFacts)),
3134
+ __param(7, Inject(SandboxOperationIntents)),
3135
+ __param(8, Inject(SandboxOperationAuthority)),
3136
+ __param(9, Inject(PermissionInstanceWrites)),
3137
+ __param(10, Inject(LegacyRetirementStore)),
3138
+ __param(11, Inject(CloudPermissionSnapshots))
1293
3139
  ], SandboxService);
1294
3140
  export { SandboxService };