@capybara-hq/kernel 0.1.0-rc.9 → 0.1.0-rc.91

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