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

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