@capybara-hq/kernel 0.1.0-rc.8 → 0.1.0-rc.80

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