@capybara-hq/kernel 0.1.0-rc.7 → 0.1.0-rc.71

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