@capybara-hq/kernel 0.1.0-rc.6 → 0.1.0-rc.61

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