@capybara-hq/kernel 0.1.0-rc.41 → 0.1.0-rc.43

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 (359) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +6 -0
  3. package/dist/admin/org-network.service.d.ts +3 -1
  4. package/dist/admin/org-network.service.js +10 -2
  5. package/dist/app.d.ts +4 -0
  6. package/dist/app.js +2 -0
  7. package/dist/background/finish.d.ts +9 -1
  8. package/dist/background/finish.js +57 -4
  9. package/dist/background/launch.d.ts +23 -0
  10. package/dist/background/launch.js +55 -1
  11. package/dist/background/managed-output.d.ts +110 -0
  12. package/dist/background/managed-output.js +219 -0
  13. package/dist/background/managed.d.ts +52 -0
  14. package/dist/background/managed.js +128 -0
  15. package/dist/background/poll.job.d.ts +35 -1
  16. package/dist/background/poll.job.js +174 -9
  17. package/dist/background/render.js +1 -0
  18. package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
  19. package/dist/background/retire-legacy-tasks.job.js +149 -0
  20. package/dist/background/session.d.ts +15 -5
  21. package/dist/background/session.js +22 -6
  22. package/dist/background/stop.d.ts +35 -5
  23. package/dist/background/stop.js +94 -8
  24. package/dist/background/store.d.ts +110 -3
  25. package/dist/background/store.js +205 -3
  26. package/dist/background/tasks.service.d.ts +18 -1
  27. package/dist/background/tasks.service.js +99 -9
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/channels/cards.js +1 -1
  30. package/dist/channels/inbound.js +2 -0
  31. package/dist/channels/phrases.d.ts +4 -0
  32. package/dist/channels/phrases.js +4 -0
  33. package/dist/config/load.d.ts +18 -0
  34. package/dist/config/load.js +39 -1
  35. package/dist/config/permission-migration.d.ts +26 -0
  36. package/dist/config/permission-migration.js +64 -0
  37. package/dist/config/schema.d.ts +4 -1
  38. package/dist/config/schema.js +41 -10
  39. package/dist/conversations/conversations.controller.d.ts +1 -1
  40. package/dist/conversations/conversations.controller.js +1 -1
  41. package/dist/conversations/conversations.module.js +12 -0
  42. package/dist/conversations/conversations.service.d.ts +11 -2
  43. package/dist/conversations/conversations.service.js +97 -27
  44. package/dist/conversations/event-log.d.ts +1 -1
  45. package/dist/conversations/event-log.js +10 -2
  46. package/dist/conversations/events.d.ts +307 -4
  47. package/dist/conversations/events.js +286 -32
  48. package/dist/conversations/permission-profile-store.d.ts +50 -0
  49. package/dist/conversations/permission-profile-store.js +67 -0
  50. package/dist/conversations/permission-profile-store.module.d.ts +2 -0
  51. package/dist/conversations/permission-profile-store.module.js +19 -0
  52. package/dist/conversations/permission-profiles.controller.d.ts +84 -0
  53. package/dist/conversations/permission-profiles.controller.js +105 -0
  54. package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
  55. package/dist/conversations/permission-profiles.schemas.js +23 -0
  56. package/dist/conversations/permission-profiles.service.d.ts +56 -0
  57. package/dist/conversations/permission-profiles.service.js +179 -0
  58. package/dist/ctx/create-ctx.d.ts +12 -5
  59. package/dist/ctx/create-ctx.js +21 -5
  60. package/dist/db/kernel-schema.d.ts +248 -3
  61. package/dist/devices/access.js +1 -1
  62. package/dist/devices/access.module.d.ts +2 -0
  63. package/dist/devices/access.module.js +19 -0
  64. package/dist/devices/conversation-devices.d.ts +8 -29
  65. package/dist/devices/conversation-devices.js +37 -73
  66. package/dist/devices/device-projects.service.d.ts +26 -28
  67. package/dist/devices/device-projects.service.js +123 -127
  68. package/dist/devices/devices.controller.js +3 -1
  69. package/dist/devices/devices.module.js +11 -9
  70. package/dist/devices/devices.service.d.ts +116 -8
  71. package/dist/devices/devices.service.js +252 -20
  72. package/dist/devices/dto.d.ts +16 -0
  73. package/dist/devices/dto.js +34 -6
  74. package/dist/devices/errors.d.ts +8 -0
  75. package/dist/devices/errors.js +10 -0
  76. package/dist/devices/project-rules.d.ts +44 -0
  77. package/dist/devices/project-rules.js +27 -0
  78. package/dist/devices/working-root.d.ts +6 -0
  79. package/dist/devices/working-root.js +12 -1
  80. package/dist/errors.d.ts +31 -0
  81. package/dist/errors.js +31 -0
  82. package/dist/evals/reconstruct.d.ts +19 -2
  83. package/dist/evals/reconstruct.js +40 -2
  84. package/dist/evals/recorded-permission-context.d.ts +77 -0
  85. package/dist/evals/recorded-permission-context.js +151 -0
  86. package/dist/evals/recorded-tools.d.ts +10 -1
  87. package/dist/evals/recorded-tools.js +27 -3
  88. package/dist/evals/run-replay.d.ts +8 -2
  89. package/dist/evals/run-replay.js +18 -2
  90. package/dist/evals/trajectory.d.ts +1 -1
  91. package/dist/evals/worker.d.ts +10 -1
  92. package/dist/evals/worker.js +23 -14
  93. package/dist/extensions/host.d.ts +4 -1
  94. package/dist/extensions/host.js +10 -6
  95. package/dist/http/api.module.js +2 -0
  96. package/dist/identity/accounts.d.ts +14 -1
  97. package/dist/identity/accounts.js +61 -5
  98. package/dist/identity/identity.module.js +2 -0
  99. package/dist/identity/settings.d.ts +28 -12
  100. package/dist/identity/settings.js +89 -33
  101. package/dist/index.d.ts +6 -0
  102. package/dist/index.js +5 -0
  103. package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
  104. package/dist/infra/cli/kernel-cli.module.js +5 -2
  105. package/dist/infra/cli/permission-cutover.d.ts +59 -0
  106. package/dist/infra/cli/permission-cutover.js +107 -0
  107. package/dist/infra/config/kernel-config.service.d.ts +2 -2
  108. package/dist/infra/config/kernel-config.service.js +35 -11
  109. package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
  110. package/dist/infra/database/startup-activation-transaction.js +242 -0
  111. package/dist/infra/database/transaction-host.d.ts +47 -0
  112. package/dist/infra/database/transaction-host.js +119 -0
  113. package/dist/infra/database/xact-lock.d.ts +1 -0
  114. package/dist/infra/database/xact-lock.js +6 -0
  115. package/dist/infra/outbox/registry.d.ts +39 -0
  116. package/dist/infra/outbox/registry.js +18 -0
  117. package/dist/kernel.module.js +2 -0
  118. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  119. package/dist/lifecycle/kernel-lifecycle.js +55 -28
  120. package/dist/local-devices/device-auth.js +1 -1
  121. package/dist/local-devices/device-policy.service.d.ts +35 -5
  122. package/dist/local-devices/device-policy.service.js +188 -13
  123. package/dist/local-devices/instance-bindings.d.ts +82 -0
  124. package/dist/local-devices/instance-bindings.js +304 -0
  125. package/dist/local-devices/keys.d.ts +5 -0
  126. package/dist/local-devices/keys.js +5 -0
  127. package/dist/local-devices/local-device-gateway.d.ts +19 -4
  128. package/dist/local-devices/local-device-gateway.js +185 -17
  129. package/dist/local-devices/local-device-provider.d.ts +42 -7
  130. package/dist/local-devices/local-device-provider.js +185 -10
  131. package/dist/local-devices/local-devices.module.d.ts +17 -2
  132. package/dist/local-devices/local-devices.module.js +49 -8
  133. package/dist/local-devices/machines.d.ts +35 -12
  134. package/dist/local-devices/machines.js +203 -8
  135. package/dist/local-devices/network-grants.js +3 -3
  136. package/dist/local-devices/network-grants.module.d.ts +2 -0
  137. package/dist/local-devices/network-grants.module.js +14 -0
  138. package/dist/local-devices/owner-report.d.ts +79 -0
  139. package/dist/local-devices/owner-report.js +155 -0
  140. package/dist/local-devices/owner-reports.d.ts +48 -0
  141. package/dist/local-devices/owner-reports.js +190 -0
  142. package/dist/local-devices/policy-summary.d.ts +24 -1
  143. package/dist/local-devices/policy-summary.js +48 -0
  144. package/dist/local-devices/relay.d.ts +82 -6
  145. package/dist/local-devices/relay.js +187 -16
  146. package/dist/local-devices/targets.d.ts +16 -1
  147. package/dist/local-devices/targets.js +35 -2
  148. package/dist/models/image-usable.d.ts +22 -0
  149. package/dist/models/image-usable.js +29 -0
  150. package/dist/models/images.d.ts +125 -0
  151. package/dist/models/images.js +440 -0
  152. package/dist/models/models.module.d.ts +3 -2
  153. package/dist/models/models.module.js +16 -5
  154. package/dist/models/org-models.schemas.js +1 -0
  155. package/dist/models/purposes.controller.d.ts +7 -0
  156. package/dist/models/purposes.controller.js +9 -0
  157. package/dist/models/purposes.d.ts +28 -3
  158. package/dist/models/purposes.js +40 -13
  159. package/dist/orgs/cloud-network-setting.d.ts +33 -0
  160. package/dist/orgs/cloud-network-setting.js +47 -0
  161. package/dist/orgs/offboarding.d.ts +3 -1
  162. package/dist/orgs/offboarding.js +8 -2
  163. package/dist/orgs/org-lock.d.ts +10 -4
  164. package/dist/orgs/org-lock.js +10 -4
  165. package/dist/orgs/orgs.service.d.ts +3 -1
  166. package/dist/orgs/orgs.service.js +8 -2
  167. package/dist/orgs/settings.controller.d.ts +4 -1
  168. package/dist/orgs/settings.controller.js +3 -3
  169. package/dist/orgs/settings.service.d.ts +48 -56
  170. package/dist/orgs/settings.service.js +144 -101
  171. package/dist/overrides.d.ts +6 -1
  172. package/dist/overrides.js +2 -0
  173. package/dist/platform/exclusions.js +20 -0
  174. package/dist/platform/ops/admin.ops.js +14 -11
  175. package/dist/platform/ops/agent-skills.ops.js +2 -0
  176. package/dist/platform/ops/devices.ops.js +10 -2
  177. package/dist/platform/ops/models.ops.js +10 -0
  178. package/dist/platform/ops/org-settings.ops.js +6 -6
  179. package/dist/platform/ops/orgs.ops.js +1 -0
  180. package/dist/roles/worker.module.js +4 -0
  181. package/dist/runtime/context/build.d.ts +3 -1
  182. package/dist/runtime/context/build.js +19 -3
  183. package/dist/runtime/context/compaction.js +5 -0
  184. package/dist/runtime/context/device-paths.d.ts +9 -2
  185. package/dist/runtime/context/device-paths.js +20 -0
  186. package/dist/runtime/context/permission-profile.d.ts +46 -0
  187. package/dist/runtime/context/permission-profile.js +194 -0
  188. package/dist/runtime/hook-calls.d.ts +11 -1
  189. package/dist/runtime/hook-calls.js +24 -1
  190. package/dist/runtime/maintenance.d.ts +7 -1
  191. package/dist/runtime/maintenance.js +43 -15
  192. package/dist/runtime/model-call.d.ts +32 -0
  193. package/dist/runtime/model-call.js +67 -0
  194. package/dist/runtime/permission-context-errors.d.ts +39 -0
  195. package/dist/runtime/permission-context-errors.js +67 -0
  196. package/dist/runtime/permission-context.service.d.ts +60 -0
  197. package/dist/runtime/permission-context.service.js +286 -0
  198. package/dist/runtime/project/knowledge.d.ts +7 -2
  199. package/dist/runtime/project/knowledge.js +5 -2
  200. package/dist/runtime/project/knowledge.service.d.ts +17 -2
  201. package/dist/runtime/project/knowledge.service.js +76 -12
  202. package/dist/runtime/providers.d.ts +9 -5
  203. package/dist/runtime/providers.js +22 -3
  204. package/dist/runtime/run-execution.d.ts +4 -1
  205. package/dist/runtime/run-execution.js +14 -5
  206. package/dist/runtime/run-steps.d.ts +11 -3
  207. package/dist/runtime/run-steps.js +27 -4
  208. package/dist/runtime/runtime.module.js +11 -0
  209. package/dist/runtime/usage-report.d.ts +10 -6
  210. package/dist/runtime/usage-report.js +31 -11
  211. package/dist/sandbox/attachments-path.d.ts +15 -0
  212. package/dist/sandbox/attachments-path.js +15 -0
  213. package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
  214. package/dist/sandbox/cloud-permission-snapshot.js +407 -0
  215. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
  216. package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
  217. package/dist/sandbox/held-operations.d.ts +39 -0
  218. package/dist/sandbox/held-operations.js +119 -0
  219. package/dist/sandbox/jobs.d.ts +14 -3
  220. package/dist/sandbox/jobs.js +20 -2
  221. package/dist/sandbox/kernel-read.d.ts +55 -0
  222. package/dist/sandbox/kernel-read.js +57 -0
  223. package/dist/sandbox/legacy-retirement.d.ts +336 -0
  224. package/dist/sandbox/legacy-retirement.js +1063 -0
  225. package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
  226. package/dist/sandbox/legacy-retirement.module.js +25 -0
  227. package/dist/sandbox/managed-device-context.d.ts +94 -0
  228. package/dist/sandbox/managed-device-context.js +308 -0
  229. package/dist/sandbox/managed-device-context.module.d.ts +6 -0
  230. package/dist/sandbox/managed-device-context.module.js +33 -0
  231. package/dist/sandbox/modes.d.ts +56 -8
  232. package/dist/sandbox/modes.js +92 -8
  233. package/dist/sandbox/operation-authority-types.d.ts +8 -0
  234. package/dist/sandbox/operation-authority-types.js +32 -0
  235. package/dist/sandbox/operation-authority.d.ts +145 -0
  236. package/dist/sandbox/operation-authority.js +783 -0
  237. package/dist/sandbox/operation-authority.module.d.ts +2 -0
  238. package/dist/sandbox/operation-authority.module.js +29 -0
  239. package/dist/sandbox/operation-intents.d.ts +206 -0
  240. package/dist/sandbox/operation-intents.js +1252 -0
  241. package/dist/sandbox/operation-intents.module.d.ts +2 -0
  242. package/dist/sandbox/operation-intents.module.js +21 -0
  243. package/dist/sandbox/operation-payloads.d.ts +33 -0
  244. package/dist/sandbox/operation-payloads.js +332 -0
  245. package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
  246. package/dist/sandbox/operation-reconcile.job.js +247 -0
  247. package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
  248. package/dist/sandbox/permission-authority-epochs.js +83 -0
  249. package/dist/sandbox/permission-authority-lock.d.ts +38 -0
  250. package/dist/sandbox/permission-authority-lock.js +147 -0
  251. package/dist/sandbox/permission-authority.module.d.ts +9 -0
  252. package/dist/sandbox/permission-authority.module.js +55 -0
  253. package/dist/sandbox/permission-availability.d.ts +18 -0
  254. package/dist/sandbox/permission-availability.js +19 -0
  255. package/dist/sandbox/permission-call-grants.d.ts +34 -0
  256. package/dist/sandbox/permission-call-grants.js +349 -0
  257. package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
  258. package/dist/sandbox/permission-call-grants.module.js +21 -0
  259. package/dist/sandbox/permission-call-types.d.ts +82 -0
  260. package/dist/sandbox/permission-call-types.js +1 -0
  261. package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
  262. package/dist/sandbox/permission-ceiling-writes.js +223 -0
  263. package/dist/sandbox/permission-config-publication.d.ts +76 -0
  264. package/dist/sandbox/permission-config-publication.js +339 -0
  265. package/dist/sandbox/permission-context-types.d.ts +64 -0
  266. package/dist/sandbox/permission-context-types.js +24 -0
  267. package/dist/sandbox/permission-facts.d.ts +206 -0
  268. package/dist/sandbox/permission-facts.js +627 -0
  269. package/dist/sandbox/permission-facts.module.d.ts +2 -0
  270. package/dist/sandbox/permission-facts.module.js +20 -0
  271. package/dist/sandbox/permission-instance-writes.d.ts +90 -0
  272. package/dist/sandbox/permission-instance-writes.js +305 -0
  273. package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
  274. package/dist/sandbox/permission-runtime-reports.js +354 -0
  275. package/dist/sandbox/permission-transitions.d.ts +31 -0
  276. package/dist/sandbox/permission-transitions.js +155 -0
  277. package/dist/sandbox/platform-full-access.d.ts +128 -0
  278. package/dist/sandbox/platform-full-access.js +210 -0
  279. package/dist/sandbox/providers.d.ts +22 -0
  280. package/dist/sandbox/providers.js +10 -2
  281. package/dist/sandbox/providers.module.d.ts +2 -0
  282. package/dist/sandbox/providers.module.js +19 -0
  283. package/dist/sandbox/request-not-sent.d.ts +13 -0
  284. package/dist/sandbox/request-not-sent.js +13 -0
  285. package/dist/sandbox/review/classifier.d.ts +2 -0
  286. package/dist/sandbox/review/classifier.js +8 -0
  287. package/dist/sandbox/review/permission-candidate.d.ts +12 -0
  288. package/dist/sandbox/review/permission-candidate.js +145 -0
  289. package/dist/sandbox/review/review.service.d.ts +5 -2
  290. package/dist/sandbox/review/review.service.js +60 -15
  291. package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
  292. package/dist/sandbox/sandbox-file-reader.js +51 -7
  293. package/dist/sandbox/sandbox.module.js +26 -6
  294. package/dist/sandbox/sandbox.service.d.ts +230 -34
  295. package/dist/sandbox/sandbox.service.js +1368 -199
  296. package/dist/sandbox/unreachable.js +17 -3
  297. package/dist/sandbox/use-context.d.ts +17 -0
  298. package/dist/sandbox/use-context.js +1 -0
  299. package/dist/skills/invoke.d.ts +27 -4
  300. package/dist/skills/invoke.js +72 -7
  301. package/dist/tools/approvals.controller.d.ts +1 -0
  302. package/dist/tools/approvals.schemas.d.ts +1 -0
  303. package/dist/tools/approvals.schemas.js +3 -1
  304. package/dist/tools/approvals.service.d.ts +23 -10
  305. package/dist/tools/approvals.service.js +104 -26
  306. package/dist/tools/builtin-names.d.ts +3 -1
  307. package/dist/tools/builtin-names.js +5 -1
  308. package/dist/tools/builtins/artifacts.d.ts +43 -0
  309. package/dist/tools/builtins/artifacts.js +67 -0
  310. package/dist/tools/builtins/builtin-tools.d.ts +20 -2
  311. package/dist/tools/builtins/builtin-tools.js +61 -10
  312. package/dist/tools/builtins/image/generate.d.ts +59 -0
  313. package/dist/tools/builtins/image/generate.js +535 -0
  314. package/dist/tools/builtins/image/index.d.ts +2 -0
  315. package/dist/tools/builtins/image/index.js +2 -0
  316. package/dist/tools/builtins/image/paths.d.ts +12 -0
  317. package/dist/tools/builtins/image/paths.js +26 -0
  318. package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
  319. package/dist/tools/builtins/sandbox/bash.js +201 -5
  320. package/dist/tools/builtins/sandbox/common.d.ts +92 -20
  321. package/dist/tools/builtins/sandbox/common.js +201 -17
  322. package/dist/tools/builtins/sandbox/deliver.js +9 -51
  323. package/dist/tools/builtins/sandbox/edit.js +2 -2
  324. package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
  325. package/dist/tools/builtins/sandbox/glob.js +2 -2
  326. package/dist/tools/builtins/sandbox/grep.js +2 -2
  327. package/dist/tools/builtins/sandbox/read.js +2 -2
  328. package/dist/tools/builtins/sandbox/task-list.js +7 -1
  329. package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
  330. package/dist/tools/builtins/sandbox/task-output.js +172 -0
  331. package/dist/tools/builtins/sandbox/task-stop.js +25 -3
  332. package/dist/tools/builtins/sandbox/write.js +2 -2
  333. package/dist/tools/builtins/skill-load.js +9 -6
  334. package/dist/tools/device-op-resolver.d.ts +1 -1
  335. package/dist/tools/device-op-resolver.js +13 -3
  336. package/dist/tools/permission-approval-jobs.d.ts +18 -0
  337. package/dist/tools/permission-approval-jobs.js +92 -0
  338. package/dist/tools/pipeline.d.ts +17 -2
  339. package/dist/tools/pipeline.js +315 -26
  340. package/dist/tools/registry.d.ts +9 -0
  341. package/dist/tools/tools.module.js +15 -0
  342. package/package.json +4 -3
  343. package/src/migrations/0146_permission_authority_epochs.sql +6 -0
  344. package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
  345. package/src/migrations/0148_first_message_request_hash.sql +2 -0
  346. package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
  347. package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
  348. package/src/migrations/0151_starting_execution_grants.sql +8 -0
  349. package/src/migrations/0152_background_launch_identity.sql +66 -0
  350. package/src/migrations/0153_background_cancel_requester.sql +13 -0
  351. package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
  352. package/src/migrations/0155_device_instance_generations.sql +30 -0
  353. package/src/migrations/0156_device_owner_report.sql +7 -0
  354. package/src/migrations/0157_legacy_retirement.sql +116 -0
  355. package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
  356. package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
  357. package/src/migrations/0160_model_usage_image_kind.sql +10 -0
  358. package/dist/sandbox/platform-auto-mode.d.ts +0 -63
  359. package/dist/sandbox/platform-auto-mode.js +0 -63
@@ -7,24 +7,60 @@ 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 { DEFAULT_SANDBOX_ROOTS, 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, } 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
36
  import { isFileSystemGoneError, isSandboxGoneError, rootsOf, } from "@capybara-hq/plugin-sdk";
12
37
  import { Inject, Injectable } from "@nestjs/common";
13
38
  import { sql, } from "kysely";
14
39
  import { SESSION_MODE_SCRIPT } from "../background/launch.js";
40
+ import { MANAGED_STOP_GRACE_MS } from "../background/managed.js";
15
41
  import { BackgroundTaskStore } from "../background/store.js";
42
+ import { deviceNotFound } from "../devices/errors.js";
16
43
  import { ApiError } from "../errors.js";
17
44
  import { readSandboxLimitOverride } from "../identity/settings.js";
18
45
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
19
46
  import { KernelDb } from "../infra/database/kernel-db.js";
20
47
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
21
- import { localModeOf } from "../local-devices/policy-summary.js";
22
- import { effectiveSandboxLimits, readOrgSettings } from "../orgs/settings.service.js";
48
+ import { effectiveSandboxLimits } from "../orgs/settings.service.js";
49
+ import { isStorageError } from "../runtime/permission-context-errors.js";
23
50
  import { canonicalJson } from "../tools/canonical-json.js";
51
+ import { attachmentsDir } from "./attachments-path.js";
52
+ import { CloudPermissionSnapshots, } from "./cloud-permission-snapshot.js";
53
+ import { isKernelReadMethod, KernelReadNotAdmitted, KernelReadUnsupported, } from "./kernel-read.js";
24
54
  import { SandboxLeases, SandboxLockLostError, sandboxBusy, } from "./leases.js";
25
- import { appliedOf, effectiveDevicePolicy, instanceLimitsJson, readDeploymentDevicePolicy, readInstanceLimits, sameApplied, } from "./modes.js";
55
+ import { isCloudProvider, LegacyRetirementStore } from "./legacy-retirement.js";
56
+ import { ManagedDeviceContextFailed } from "./managed-device-context.js";
57
+ import { appliedOf, appliedWider, instanceLimitsJson, readInstanceLimits, sameApplied, sameAppliedExact, sameAppliedExactly, } from "./modes.js";
58
+ import { PermissionFacts } from "./permission-facts.js";
59
+ import { cloudReportOwed, cloudSupportOf } from "./permission-runtime-reports.js";
26
60
  import { isInternalProvider, LOCAL_PROVIDER, providerForDevice, SandboxProviders, } from "./providers.js";
61
+ import { isDeviceRequestNotSent } from "./request-not-sent.js";
27
62
  import { SandboxProviderUnreachableError } from "./unreachable.js";
63
+ export { deviceNotFound } from "../devices/errors.js";
28
64
  // Moved to leases.ts (phase C); re-exported for existing importers
29
65
  export { SANDBOX_LOCK_PREFIX, SANDBOX_LOCK_TTL_MS, SandboxLockLostError, sandboxBusy, } from "./leases.js";
30
66
  /** Margin (ms) of a holder record's TTL beyond the longest command: by then the in-sandbox limit has ended its commands. */
@@ -33,6 +69,12 @@ const HOLDER_TTL_MARGIN_MS = 10 * 60_000;
33
69
  const PATH_LEASE_WAIT_MS = 30_000;
34
70
  /** Time limit of one provider call in maintenance (suspend, destroy). */
35
71
  const SWEEP_OP_TIMEOUT_MS = 120_000;
72
+ /** How long a cloud device's lifecycle reconcile waits before the sweep tries it again (B-12). */
73
+ const RECONCILE_RETRY_SECONDS = 600;
74
+ /** Where the reconcile sweep goes on from (the last device id it visited; B-12). */
75
+ const RECONCILE_CURSOR_KEY = "capk:cloud-reconcile-cursor";
76
+ /** The bound on one cloud `permissionSupport` read under a lifecycle lease (B-15). */
77
+ const PERMISSION_SUPPORT_TIMEOUT_MS = 30_000;
36
78
  /** How long the suspension sweep holds the intent on a sandbox past `maxRunningMinutes` (ms). */
37
79
  const SWEEP_INTENT_WAIT_MS = 1000;
38
80
  /** Rows one sweep handles at most, and the provider calls it runs at once. */
@@ -68,8 +110,6 @@ function parseDeferred(raw) {
68
110
  const opSignal = (lease) => AbortSignal.any([lease.signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]);
69
111
  /** The provider-side name of a device's file system and instance. */
70
112
  export const deviceResourceName = (deviceId) => `cap-device-${deviceId}`;
71
- /** The device is missing, deleted, or not in the caller's org (404; ids cannot be probed). */
72
- export const deviceNotFound = () => new ApiError("device.not_found", "This device does not exist or was deleted.");
73
113
  /**
74
114
  * The device's file system is gone at the provider (409); never replaced silently. On a
75
115
  * connected machine (`local`, details `[{ source: "local" }]`) the directory is the machine
@@ -164,16 +204,16 @@ export function sandboxConfigWarnings(cfg, providerPlugin) {
164
204
  if (pc?.refuseOpenNetwork === true) {
165
205
  out.push({
166
206
  level: "warn",
167
- message: `extensionConfig."${providerPlugin}".refuseOpenNetwork is true: the ${providerPlugin} plugin refuses cloud devices on the open public network, which every device in auto mode and every sandbox-mode device of an organization whose cloudNetwork is open (the default) uses; set refuseOpenNetwork to false, or turn auto mode off (devices.autoMode) and have every organization switch its cloudNetwork to the allowlist`,
207
+ message: `extensionConfig."${providerPlugin}".refuseOpenNetwork is true: the ${providerPlugin} plugin refuses cloud devices on the open public network, which every device in auto mode and every sandbox-mode device of an organization whose cloudNetwork is open (the default) uses; set refuseOpenNetwork to false, or turn Full permission off (devices.fullAccess) and have every organization switch its cloudNetwork to the allowlist`,
168
208
  });
169
209
  }
170
210
  }
171
211
  if (cfg.sandbox.limits.orgHosts === "within" &&
172
212
  cfg.sandbox.limits.egress !== "none" &&
173
- cfg.devices?.autoMode !== "off") {
213
+ cfg.devices?.fullAccess !== "off") {
174
214
  out.push({
175
215
  level: "warn",
176
- message: "sandbox.limits.orgHosts is within but devices.autoMode is not off: the platform allowlist limits sandbox mode only; devices in auto mode (the default) still reach the open public network. Set devices.autoMode to off (or turn auto mode off in the admin console) for a hard ceiling",
216
+ message: "sandbox.limits.orgHosts is within but devices.fullAccess is not off: the platform allowlist limits restricted execution only; devices on Full permission (allowed by default) still reach the open public network. Set devices.fullAccess to off (or turn Full permission off in the admin console) for a hard ceiling",
177
217
  });
178
218
  }
179
219
  const run = cfg.runtime.maxRunSeconds;
@@ -193,6 +233,41 @@ export const sandboxUnavailable = () => new ApiError("sandbox.unavailable", "San
193
233
  * not migrated, so it stays unusable until that provider is back (spec §4.2 item 13).
194
234
  */
195
235
  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`);
236
+ /**
237
+ * An owner browse found no running instance of the device (409): the picker starts the device
238
+ * for its owner first ({@link SandboxService.ensureRunningForOwner}), so this is an instance that
239
+ * stopped in between (idle suspension) or one that could not be started; retrying starts it.
240
+ */
241
+ export const deviceNotRunning = () => new ApiError("device.not_running", "The device stopped before it could be read. Try again; it will be started first.");
242
+ /** The holder name of {@link SandboxService.ensureRunningForOwner}: no conversation holds it. */
243
+ const OWNER_START_HOLDER = "device-owner";
244
+ /**
245
+ * The device's old instance incarnation may still run legacy work that was never retired (503):
246
+ * the device stays unavailable until the provider confirms that incarnation destroyed, or for
247
+ * good when it is quarantined (permission runtime cutover 8.5). Never a retirement claim.
248
+ */
249
+ export class RetirementPendingError extends ApiError {
250
+ name = "RetirementPendingError";
251
+ }
252
+ 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.");
253
+ /**
254
+ * A local machine's old instance may still run legacy work, and a later boot of that machine is
255
+ * the evidence that ends it (503, 8.5): the person restarts the computer.
256
+ */
257
+ 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.");
258
+ /**
259
+ * A cloud device's earlier instance may still run legacy work and no evidence the kernel can get
260
+ * will ever cover it (an incarnation replaced without a recorded confirmed destruction, or an
261
+ * unknown one it cannot clear) (503, 8.5): the owner deletes the device and creates it again.
262
+ */
263
+ 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.");
264
+ /**
265
+ * A local machine's old instance may still run legacy work, and the computer never reported a
266
+ * boot identity, so not even a restart can prove it ended (503, 8.5): the owner replaces the
267
+ * device. A deleted device's obligations never block a new one.
268
+ */
269
+ 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.");
270
+ const isRetirementPending = (err) => err instanceof RetirementPendingError;
196
271
  const abortReason = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
197
272
  function sleep(ms, signal) {
198
273
  return new Promise((resolve, reject) => {
@@ -222,65 +297,6 @@ async function inPool(items, limit, fn) {
222
297
  };
223
298
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
224
299
  }
225
- /**
226
- * The kernel's sandbox service over the `sandbox@2` provider, keyed by **device** (spec
227
- * 2026-11-07-environments-design §4.2, §5.1): one file system kept until the device is
228
- * deleted, plus one instance attached to it that comes and goes; all conversations bound to the
229
- * device (and their sub-agents) share both.
230
- *
231
- * - **Lazy creation**: the first {@link withSandbox} creates the file system
232
- * (`createFileSystem`, name `cap-device-<deviceId>`) and then the instance on it; state lives
233
- * in `device_instances`. A file system gone at the provider is never replaced silently:
234
- * `fs_status` becomes `lost` and uses fail with `device.files_lost` until
235
- * {@link resetFileSystem}.
236
- * - **Leases** (phase C, spec §10, {@link SandboxLeases}), keyed by device id: using an
237
- * instance recorded `running` with the current provider takes a **shared** lease, so up to
238
- * `sandbox.maxConcurrentCommands` holders (all sessions of the device) run at once. Every
239
- * lifecycle change (create, resume, rebuild, suspend, destroy, reset) takes the **exclusive**
240
- * lease, alone; a caller that needs one on the use path sets the intent so new shared leases wait
241
- * for it, and downgrades to a shared lease to run its own command once the instance runs.
242
- * Waiting is capped at `sandbox.lockWaitSeconds` (`sandbox.busy`); two replicas using it for the
243
- * first time at once still build only one.
244
- * - **Fencing**: exclusive holders read `generation` and compare-and-increment it with every state
245
- * write ({@link SandboxLockLostError}); every acquisition (shared ones too) bumps it first, so a
246
- * stale exclusive holder's later writes fail. Shared holders write nothing else but
247
- * `last_used_at` (monotonic). A lost lease aborts the signal passed to `fn` and to maintenance
248
- * provider calls.
249
- * - **Suspension and destruction**: the sweeps (`SandboxSweepJobs`, crons) call
250
- * {@link suspendIdle} / {@link destroyInactive}; they try the exclusive lease once and skip an
251
- * device with any holder; one past `maxRunningMinutes` gets the intent for a short window
252
- * (about a second) so the suspension can get in when its commands end. Inactivity destroys only
253
- * the instance (files kept); a deleted device or org loses its files too.
254
- * - **Transparent recovery**: a suspended instance is resumed on next use; when `resume` returns
255
- * `gone`, the instance was destroyed, or `fn` throws `SandboxGoneError` (retried once), a new
256
- * instance is created on the kept files and `restarted` is true. Several holders hitting `gone`
257
- * together rebuild once: the others find the new instance.
258
- * - **Takeover** (spec §10.5; environments spec §4.2): every holder records itself in
259
- * `capk:sandbox-holders:<env>` (again before each `exec`) and its commands carry its lease token
260
- * as `tag`. An acquirer that finds a record without a live lease (a crashed holder) kills only
261
- * that holder's commands (`killTagged`): other conversations of the device may be running
262
- * commands. `killAll` runs only under the exclusive lease, before the downgrade, on an instance
263
- * this holder just resumed from `suspended` (nobody else can hold it; a provider that keeps
264
- * memory across a pause brings old commands back); it also covers crashed holders' records,
265
- * which it claims. A freshly created instance has nothing to kill. Failures are only warned (the
266
- * in-sandbox time limit is the backstop).
267
- * - **Instance identity**: a holder that hits `gone` names the instance by its handle and the
268
- * row's `created_at` (set by the fenced write after each `create`); the handle alone is the same
269
- * after a rebuild on providers whose handle is the instance name (sandbox-docker).
270
- *
271
- * - **Provider per device** (environments spec §6): each call resolves the provider from
272
- * the device's `devices.provider` ({@link providerForDevice}): a `device`
273
- * device runs on the kernel-internal `@local` provider (never the cloud one), a cloud
274
- * device on the loaded `sandbox@2` extension. A `@local` instance is never suspended or
275
- * destroyed for inactivity; a deleted `@local` device (or one of a deleted org) is
276
- * destroyed by the sweep like any other.
277
- *
278
- * Files kept by another provider than the current one make the device unusable
279
- * (`device.unavailable`) until that provider is back; deleting it still works while that
280
- * provider is loaded ({@link SandboxProviders.forName}). Without the device's provider
281
- * {@link availableFor} is false and uses throw `sandbox.unavailable` (503). No in-process state:
282
- * replicas share it through PG and Redis.
283
- */
284
300
  let SandboxService = class SandboxService {
285
301
  db;
286
302
  redis;
@@ -289,13 +305,23 @@ let SandboxService = class SandboxService {
289
305
  config;
290
306
  log;
291
307
  background;
308
+ facts;
309
+ operationIntents;
310
+ authority;
311
+ instanceWrites;
312
+ retirement;
313
+ snapshots;
292
314
  constructor(db,
293
315
  /** The record of the instance each holder last used (`capk:sandbox-seen:…`). */
294
316
  redis, leases,
295
317
  /** The providers (read at every call: providers are ready after the extension load). */
296
318
  providers, config, log,
297
319
  /** Background tasks lost while their process may live on (killed after a resume). */
298
- background) {
320
+ background, facts, operationIntents, authority, instanceWrites,
321
+ /** The retirement obligations every lifecycle acquisition is gated on (8.5). */
322
+ retirement,
323
+ /** The cloud snapshot writer's reconcile, for the lifecycle reconcile of marked devices (B-12). */
324
+ snapshots) {
299
325
  this.db = db;
300
326
  this.redis = redis;
301
327
  this.leases = leases;
@@ -303,6 +329,12 @@ let SandboxService = class SandboxService {
303
329
  this.config = config;
304
330
  this.log = log;
305
331
  this.background = background;
332
+ this.facts = facts;
333
+ this.operationIntents = operationIntents;
334
+ this.authority = authority;
335
+ this.instanceWrites = instanceWrites;
336
+ this.retirement = retirement;
337
+ this.snapshots = snapshots;
306
338
  }
307
339
  /** Poll interval while waiting for a lease (the leases' own). */
308
340
  get pollMs() {
@@ -351,33 +383,7 @@ let SandboxService = class SandboxService {
351
383
  * device and a missing one have none). Without `deviceId`: an org-level policy with no choice.
352
384
  */
353
385
  async devicePolicy(device) {
354
- const [deployment, settings, mode] = await Promise.all([
355
- readDeploymentDevicePolicy(this.db.db, this.config),
356
- readOrgSettings(this.db.db, device.orgId),
357
- device.deviceId === undefined ? null : this.deviceChosenMode(device.orgId, device.deviceId),
358
- ]);
359
- return effectiveDevicePolicy(deployment, settings, mode);
360
- }
361
- /**
362
- * The mode a device chose: a local device's derived one (`localModeOf`, which never returns null
363
- * — a machine with no summary or no mode feature is sandbox); a cloud device's narrowing switch
364
- * (`devices.mode`, `sandbox` only), or null for a cloud device that follows the platform and the
365
- * org.
366
- */
367
- async deviceChosenMode(orgId, deviceId) {
368
- const row = await this.db
369
- .selectFrom("devices as e")
370
- .leftJoin("device_machines as m", (j) => j.onRef("m.device_id", "=", "e.id").on("m.revoked_at", "is", null))
371
- .select(["e.source", "e.mode", "m.features", "m.local_policy"])
372
- .where("e.id", "=", deviceId)
373
- .where("e.org_id", "=", orgId)
374
- .where("e.deleted_at", "is", null)
375
- .executeTakeFirst();
376
- if (row === undefined)
377
- return null;
378
- if (row.source === "local")
379
- return localModeOf(row.features, row.local_policy);
380
- return row.mode === "sandbox" ? "sandbox" : null;
386
+ return this.facts.devicePolicy(device);
381
387
  }
382
388
  /** The device's source (`local` for a connected machine, else `cloud`); cloud when unknown. */
383
389
  async deviceSource(device) {
@@ -490,17 +496,25 @@ let SandboxService = class SandboxService {
490
496
  }
491
497
  /**
492
498
  * Whether the running instance of `row` must get `want` before use (auto mode spec §4.2): a
493
- * cloud instance whose recorded mode or network kind differs, unless only a file reset could
494
- * apply it ({@link fsBound}). `want` null: a local device (the mode travels with each command).
499
+ * cloud instance whose recorded mode or network kind differs, or whose recorded limits are more
500
+ * permissive than `want` in any dimension (a host-only narrowing too, spec §124; a host-only
501
+ * widening still reaches instances created afterwards), unless only a file reset could apply it
502
+ * ({@link fsBound}). A provider bound to its file system still goes through the exclusive lease
503
+ * once for a narrowing, so `applyLimits` records it as `unapplied` (the device is then unprobed
504
+ * until the reset, never silently supported). `want` null: a local device (the mode travels
505
+ * with each command).
495
506
  */
496
507
  mustApply(row, p, want) {
497
508
  if (want === null)
498
509
  return false;
499
510
  const rec = readInstanceLimits(row.instance_limits);
500
511
  const target = appliedOf(want);
501
- if (sameApplied(rec.applied, target))
512
+ const wider = appliedWider(rec.applied, target);
513
+ if (sameApplied(rec.applied, target) && !wider)
502
514
  return false;
503
- return !this.fsBound(p, rec, target);
515
+ if (!this.fsBound(p, rec, target))
516
+ return true;
517
+ return wider && !sameAppliedExact(rec.unapplied, target);
504
518
  }
505
519
  /**
506
520
  * The device's instance state as shown to people (read only, no lease): `running` /
@@ -526,14 +540,14 @@ let SandboxService = class SandboxService {
526
540
  async currentInstance(deviceId) {
527
541
  const row = await this.db
528
542
  .selectFrom("device_instances")
529
- .select(["status", "handle", "created_at"])
543
+ .select(["status", "handle", "created_at", "provider"])
530
544
  .where("device_id", "=", deviceId)
531
545
  .executeTakeFirst();
532
546
  if (!row || row.handle === null)
533
547
  return null;
534
548
  if (row.status !== "running" && row.status !== "suspended")
535
549
  return null;
536
- return { createdAt: row.created_at };
550
+ return { createdAt: row.created_at, provider: row.provider };
537
551
  }
538
552
  /**
539
553
  * Runs `fn` on the device's instance only while it runs the instance created at
@@ -547,7 +561,20 @@ let SandboxService = class SandboxService {
547
561
  * to `fn` aborts with `signal` or when the lease is lost. Errors of `fn` (`SandboxGoneError`
548
562
  * too) are thrown as they are.
549
563
  */
550
- async ifRunning(deviceId, instance, fn, signal = new AbortController().signal) {
564
+ async ifRunning(deviceId,
565
+ /**
566
+ * `exactRef`: an exact-ref managed drain (status, stop, the revoke worker), allowed on an
567
+ * incarnation under a retirement obligation; every other caller (legacy SID polls, stops and
568
+ * reads, staged browse) is refused there with a {@link RetirementPendingError} (8.5).
569
+ */
570
+ instance, fn, signal = new AbortController().signal) {
571
+ return this.ifRunningAs(deviceId, instance, fn, signal, false);
572
+ }
573
+ /**
574
+ * {@link ifRunning}; `use` (staged owner browse) also refuses a device carrying the B1
575
+ * reconcile marker under the shared lease, before any provider call (B-11).
576
+ */
577
+ async ifRunningAs(deviceId, instance, fn, signal, use) {
551
578
  const p = await this.require(deviceId);
552
579
  const env = deviceId;
553
580
  const deadline = Date.now() + this.config.get().sandbox.lockWaitSeconds * 1000;
@@ -567,12 +594,20 @@ let SandboxService = class SandboxService {
567
594
  }
568
595
  if (!this.usable(row, p, null))
569
596
  return { kind: "not_running", status: row.status };
597
+ // an incarnation that may still run unretired legacy work: no SID signal, no new exec or
598
+ // admission there; only exact-ref managed drains go on (I1)
599
+ if (!instance.exactRef && (await this.retirement.hasUnresolved(env)))
600
+ throw retirementPending();
601
+ // staged owner browse never reaches an instance whose binding is not installed (B-8): the
602
+ // device admits nothing there, and only a use's exclusive holder binds it
603
+ if (use && !(await this.bound(p, env)))
604
+ return { kind: "not_running", status: row.status };
570
605
  // the instance this check saw: its handle plus `created_at` (never `generation`, which
571
606
  // every lease bumps)
572
607
  const want = { handle: row.handle, createdAt: row.created_at.getTime() };
573
608
  const lease = await this.leases.tryShared(env, this.cap, token);
574
609
  if (lease) {
575
- const e = await this.asShared({ orgId: row.org_id, deviceId: env }, p, lease, (r) => this.usable(r, p, null) && isInstance(r, want), signal);
610
+ 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");
576
611
  if (e) {
577
612
  try {
578
613
  const impl = tagged(p.impl, lease.token, undefined, () => this.register(env, lease.token));
@@ -623,7 +658,132 @@ let SandboxService = class SandboxService {
623
658
  * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
624
659
  * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
625
660
  */
661
+ /** Trusted staging only. The callback receives no exec, browsing or lifecycle methods. */
662
+ async withPreparation(ctx, purpose, roots, fn, signal) {
663
+ return this.withSandboxUse(ctx, async () => {
664
+ throw new Error("Preparation callback was not installed");
665
+ }, signal, undefined, (h, provider, info, sig) => this.prepareFor(ctx, h, provider, info, purpose, roots, fn, sig));
666
+ }
667
+ async prepareFor(ctx, h, provider, info, purpose, roots, fn, sig) {
668
+ if (!provider.prepare)
669
+ throw new SandboxPermissionUnsupportedError("Trusted preparation is unavailable on this provider");
670
+ const prepare = provider.prepare.bind(provider);
671
+ const operation = async () => {
672
+ const authority = await runOutsideTransaction(() => this.authority.resolve(ctx, "stat", sig));
673
+ // attachments: exactly the one directory FetchAttachment writes for the call's root
674
+ // conversation, derived by the same helper, nothing else under the attachments root
675
+ const base = purpose === "skills"
676
+ ? info.roots.skills
677
+ : attachmentsDir(info.roots, authority.rootConversationId);
678
+ if (roots.length === 0 ||
679
+ roots.some((root) => posix.normalize(root) !== root || (root !== base && !root.startsWith(`${base}/`))))
680
+ throw new SandboxScopeDeniedError("Preparation roots must stay inside the trusted purpose directory");
681
+ const operationId = randomUUID();
682
+ return prepare(h, parseSandboxPreparationScope({
683
+ operationId,
684
+ deviceId: ctx.deviceId,
685
+ purpose,
686
+ writeRoots: [...roots],
687
+ tag: operationId,
688
+ }), sig);
689
+ };
690
+ return fn({
691
+ readFile: async (path, opts) => (await operation()).readFile(path, {
692
+ ...opts,
693
+ signal: AbortSignal.any([sig, opts.signal]),
694
+ }),
695
+ writeFile: async (path, data, signal) => (await operation()).writeFile(path, data, AbortSignal.any([sig, signal])),
696
+ stat: async (path, signal) => (await operation()).stat(path, AbortSignal.any([sig, signal])),
697
+ }, sig);
698
+ }
699
+ /** Owner browse scopes never manufacture a conversation or Full consent. */
700
+ async withBrowse(ctx, fn, signal) {
701
+ await this.authority.resolveBrowse(ctx, signal);
702
+ const row = await this.readRow(ctx);
703
+ if (!row)
704
+ throw deviceNotRunning();
705
+ const entry = await this.require(ctx.deviceId, ctx.orgId);
706
+ const result = await this.ifRunningAs(ctx.deviceId, { createdAt: row.created_at }, async (provider, h, sig) => {
707
+ if (!provider.browse)
708
+ throw new SandboxPermissionUnsupportedError("Owner browsing is unavailable on this provider");
709
+ const browse = provider.browse.bind(provider);
710
+ const call = async (method, input, s, invoke) => {
711
+ const combined = AbortSignal.any([sig, s]);
712
+ const intent = await this.operationIntents.admitBrowse(ctx, {
713
+ provider: entry.plugin,
714
+ providerVersion: entry.version ?? "internal-v2",
715
+ generation: String(row.created_at.getTime()),
716
+ }, method, input, combined);
717
+ const admitted = await this.operationIntents.claimBrowse(ctx, intent.operation_id);
718
+ combined.throwIfAborted();
719
+ try {
720
+ const operation = await browse(h, parseSandboxBrowseScope(admitted.scope), combined);
721
+ const value = await invoke(operation, combined);
722
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, admitted.execution_id, value));
723
+ return value;
724
+ }
725
+ catch (error) {
726
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
727
+ throw error;
728
+ }
729
+ };
730
+ return fn({
731
+ stat: (path, s) => call("stat", { path }, s, (p, signal) => p.stat(path, signal)),
732
+ list: (path, opts) => call("list", { path, limit: opts.limit }, opts.signal, (p, signal) => p.list(path, { limit: opts.limit, signal })),
733
+ scan: (base, opts) => call("scan", { base }, opts.signal, (p, signal) => p.scan(base, { signal })),
734
+ }, sig);
735
+ }, signal, true);
736
+ if (result.kind !== "ran")
737
+ throw deviceNotRunning();
738
+ return result.value;
739
+ }
740
+ /**
741
+ * Makes the device's instance run for its owner (permission activation L2, Hook 3), before an
742
+ * owner browse ({@link withBrowse}) of a device that may be stopped: the owner, membership and
743
+ * browsing ceiling checks of the browse first (`resolveBrowse`), then the lifecycle `enter` a
744
+ * use takes (the exclusive lease creates or resumes the instance through the retirement gate,
745
+ * the B-11 reconcile marker, the B-8 binding, `maxRunningSandboxes` and fencing), and the lease
746
+ * is left at once. No conversation holds it and nothing runs in it; what the start caused is
747
+ * not marked seen, so each conversation's next use still learns of it.
748
+ */
749
+ async ensureRunningForOwner(ctx, signal) {
750
+ await this.authority.resolveBrowse(ctx, signal);
751
+ const p = await this.require(ctx.deviceId, ctx.orgId);
752
+ const use = {
753
+ orgId: ctx.orgId,
754
+ deviceId: ctx.deviceId,
755
+ holderConversationId: OWNER_START_HOLDER,
756
+ actor: { accountId: ctx.accountId, conversationId: OWNER_START_HOLDER },
757
+ };
758
+ const e = await this.enter(use, p, signal, null, () => this.wantedLimits(use, p));
759
+ await this.leave(ctx.deviceId, e);
760
+ }
761
+ /**
762
+ * A run start's kernel read of the bound project (permission activation L2, Hook 1): the use
763
+ * a tool call's would be (the instance made or resumed, the read silent for the holder), whose
764
+ * provider stats, reads and lists only, each call a kernel read admitted and claimed on its own
765
+ * (`SandboxOperationIntents.admitKernelRead`: the run's current claim with its run still
766
+ * `queued`, a random operation id, the profile scope narrowed to the root, its `AGENTS.md` and
767
+ * its `.agents/skills`). Any other method is refused before admission. Only
768
+ * `ProjectKnowledgeService` calls this: no tool context, Platform operation or route has it.
769
+ */
770
+ async withKernelRead(ctx, read, fn, signal) {
771
+ const c = read.claim;
772
+ if (read.purpose !== "project_root" ||
773
+ c.orgId !== ctx.orgId ||
774
+ c.conversationId !== ctx.holderConversationId ||
775
+ c.runId !== ctx.actor.runId ||
776
+ ctx.actor.conversationId !== ctx.holderConversationId)
777
+ throw new SandboxScopeDeniedError("The kernel read does not match its run start");
778
+ return this.withSandboxUse(ctx, fn, signal, undefined, undefined, read);
779
+ }
780
+ async withOperations(ctx, invocation, fn, signal) {
781
+ return this.withSandboxUse(ctx, fn, signal, invocation);
782
+ }
626
783
  async withSandbox(ctx, fn, signal) {
784
+ return this.withSandboxUse(ctx, fn, signal);
785
+ }
786
+ async withSandboxUse(ctx, fn, signal, invocation, trusted, kernelRead) {
627
787
  const p = await this.require(ctx.deviceId, ctx.orgId);
628
788
  const env = ctx.deviceId;
629
789
  const holder = ctx.holderConversationId;
@@ -634,7 +794,7 @@ let SandboxService = class SandboxService {
634
794
  let e = await seen(await this.enter(ctx, p, signal, null, want));
635
795
  try {
636
796
  try {
637
- return await this.runAs(e, ctx, p, fn, signal);
797
+ return await this.runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead);
638
798
  }
639
799
  catch (err) {
640
800
  if (isFileSystemGoneError(err))
@@ -651,7 +811,7 @@ let SandboxService = class SandboxService {
651
811
  ? { fresh: true, restarted: false, filesReset: true }
652
812
  : { fresh: true, restarted: true };
653
813
  try {
654
- return await this.runAs({ ...e, info }, ctx, p, fn, signal);
814
+ return await this.runAs({ ...e, info }, ctx, p, fn, signal, invocation, trusted, kernelRead);
655
815
  }
656
816
  catch (err2) {
657
817
  if (isFileSystemGoneError(err2))
@@ -788,11 +948,242 @@ let SandboxService = class SandboxService {
788
948
  return e;
789
949
  }
790
950
  /** Runs `fn` as the holder `e`: its tag and the caller's actor on every exec, its lease's signal. */
791
- runAs(e, ctx, p, fn, signal) {
951
+ async runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead) {
792
952
  const sig = AbortSignal.any([signal, e.lease.signal]);
953
+ if (trusted)
954
+ return trusted(e.handle, p.impl, { ...e.info, roots: rootsOf(e.handle) }, sig);
793
955
  const env = ctx.deviceId;
794
- const impl = tagged(p.impl, e.lease.token, ctx.actor, () => this.register(env, e.lease.token));
795
- return fn(e.handle, impl, { ...e.info, roots: rootsOf(e.handle) }, sig);
956
+ if (kernelRead)
957
+ return fn(e.handle, this.kernelReadProvider(e, ctx, p, kernelRead, sig), { ...e.info, roots: rootsOf(e.handle) }, sig);
958
+ let ordinal = 0;
959
+ const impl = invocation
960
+ ? createHeldOperations(p.impl, e.handle, sig, async (method, input, invoke, preflight) => {
961
+ const identity = { ...invocation, ordinal: ordinal++ };
962
+ sig.throwIfAborted();
963
+ await this.register(env, e.lease.token);
964
+ const refreshPending = () => runOutsideTransaction(() => this.operationIntents.pending(ctx, identity, {
965
+ provider: p.plugin,
966
+ providerVersion: p.version ?? "internal-v2",
967
+ generation: String(e.createdAt),
968
+ }, method, input, e.lease.token, sig));
969
+ const pending = await refreshPending();
970
+ // An acknowledged start returns its recorded exact ref; it never dispatches again.
971
+ if (pending.state === "background-running" && pending.execution_ref)
972
+ return parseSandboxExecutionRef(pending.execution_ref);
973
+ if (pending.state === "completed")
974
+ return (await this.operationIntents.result(pending));
975
+ let current;
976
+ try {
977
+ current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
978
+ }
979
+ catch (error) {
980
+ if (!(error instanceof PermissionAdmissionStale))
981
+ throw error;
982
+ await refreshPending();
983
+ current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
984
+ }
985
+ // Kernel checks on the admitted scope come before any dispatch state is written.
986
+ if (preflight &&
987
+ current.state !== "completed" &&
988
+ current.state !== "background-running") {
989
+ try {
990
+ await preflight(parseSandboxOperationScope(current.scope), sig);
991
+ }
992
+ catch (error) {
993
+ if (current.state === "admitted" &&
994
+ (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error))) {
995
+ const kind = failureKindOf(error);
996
+ await runOutsideTransaction(() => this.operationIntents.refusePreDispatch(ctx, identity, {
997
+ kind,
998
+ message: error.message,
999
+ }));
1000
+ }
1001
+ throw error;
1002
+ }
1003
+ }
1004
+ const admitted = ["dispatching", "started-or-unknown"].includes(pending.state)
1005
+ ? await runOutsideTransaction(() => this.operationIntents.claimReconciliation(ctx, identity, {
1006
+ provider: p.plugin,
1007
+ providerVersion: p.version ?? "internal-v2",
1008
+ generation: String(e.createdAt),
1009
+ }, method, input, e.lease.token))
1010
+ : await runOutsideTransaction(() => this.operationIntents.claimDispatch(ctx, identity, e.lease.token, method === "backgroundStart"
1011
+ ? backgroundBinding(input, e.handle.id)
1012
+ : undefined));
1013
+ if (admitted.state === "revoked")
1014
+ throw admitted.outcome_unknown
1015
+ ? new SandboxOperationOutcomeUnknownError("The background task was stopped before its start was confirmed; it is not started again and its cancellation is owed")
1016
+ : new SandboxScopeDeniedError("The background task was stopped or settled before it launched; nothing was started");
1017
+ if (admitted.state === "background-running" && admitted.execution_ref)
1018
+ return parseSandboxExecutionRef(admitted.execution_ref);
1019
+ if (admitted.state === "completed")
1020
+ return (await this.operationIntents.result(admitted));
1021
+ sig.throwIfAborted();
1022
+ let result;
1023
+ try {
1024
+ result = await invoke(parseSandboxOperationScope(admitted.scope), sig);
1025
+ }
1026
+ catch (error) {
1027
+ if (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error)) {
1028
+ if (["dispatching", "started-or-unknown"].includes(pending.state)) {
1029
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1030
+ throw new SandboxOperationOutcomeUnknownError("The recorded operation remains unknown; changed runtime authority cannot prove it had no effect", { cause: error });
1031
+ }
1032
+ const kind = failureKindOf(error);
1033
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, {
1034
+ $failure: { kind, message: error.message },
1035
+ }));
1036
+ throw error;
1037
+ }
1038
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1039
+ // A transport/gone error after durable dispatch cannot justify a new identity retry.
1040
+ throw new SandboxOperationOutcomeUnknownError("The operation outcome must be reconciled with its recorded identity", { cause: error });
1041
+ }
1042
+ // The provider has returned: storage/serialization errors cannot establish denial.
1043
+ if (method === "backgroundStart") {
1044
+ try {
1045
+ await runOutsideTransaction(() => this.operationIntents.acknowledgeBackground(admitted.operation_id, admitted.execution_id, result, e.handle.id));
1046
+ }
1047
+ catch (error) {
1048
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1049
+ throw new SandboxOperationOutcomeUnknownError("The start returned but could not be acknowledged; reconcile the same identity", { cause: error });
1050
+ }
1051
+ return result;
1052
+ }
1053
+ try {
1054
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, result));
1055
+ }
1056
+ catch (error) {
1057
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1058
+ throw new SandboxOperationOutcomeUnknownError("The operation returned but its result could not be retained; reconcile the same identity", { cause: error });
1059
+ }
1060
+ return result;
1061
+ })
1062
+ : createLegacyHeldProvider(p.impl, e.lease.token, ctx.actor, () => this.register(env, e.lease.token));
1063
+ const contextEvidence = invocation?.contextEvidence
1064
+ ? await this.heldContextEvidence(ctx, p, e)
1065
+ : undefined;
1066
+ const info = {
1067
+ ...e.info,
1068
+ roots: rootsOf(e.handle),
1069
+ ...(contextEvidence && { contextEvidence }),
1070
+ };
1071
+ if (invocation?.beforeUser)
1072
+ await invocation.beforeUser({
1073
+ prepare: (purpose, roots, stage) => this.prepareFor(ctx, e.handle, p.impl, info, purpose, roots, stage, sig),
1074
+ }, info, sig);
1075
+ return fn(e.handle, impl, info, sig);
1076
+ }
1077
+ /**
1078
+ * The held provider of a kernel read ({@link withKernelRead}): every call admitted and claimed
1079
+ * as its own kernel read, then dispatched inline under the held lease, as an owner browse's
1080
+ * call is ({@link withBrowse}). Exec, writes and scans are refused before any admission.
1081
+ */
1082
+ kernelReadProvider(e, ctx, p, read, sig) {
1083
+ const env = ctx.deviceId;
1084
+ return createHeldOperations(p.impl, e.handle, sig, async (method, input, invoke) => {
1085
+ const path = input.path;
1086
+ if (!isKernelReadMethod(method) || typeof path !== "string")
1087
+ throw new SandboxScopeDeniedError("A kernel read only stats, reads and lists files");
1088
+ const given = input;
1089
+ sig.throwIfAborted();
1090
+ await this.register(env, e.lease.token);
1091
+ let admitted;
1092
+ try {
1093
+ const intent = await runOutsideTransaction(() => this.operationIntents.admitKernelRead(ctx, read, {
1094
+ provider: p.plugin,
1095
+ providerVersion: p.version ?? "internal-v2",
1096
+ generation: String(e.createdAt),
1097
+ }, method, given, e.lease.token, sig));
1098
+ admitted = await runOutsideTransaction(() => this.operationIntents.claimKernelRead(ctx, read, intent.operation_id, method, given));
1099
+ }
1100
+ catch (error) {
1101
+ // a refusal before dispatch: nothing reached the device
1102
+ if (sig.aborted || error instanceof KernelReadUnsupported)
1103
+ throw error;
1104
+ throw new KernelReadNotAdmitted(error);
1105
+ }
1106
+ sig.throwIfAborted();
1107
+ try {
1108
+ const value = await invoke(parseSandboxOperationScope(admitted.scope), sig);
1109
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, admitted.execution_id, value));
1110
+ return value;
1111
+ }
1112
+ catch (error) {
1113
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1114
+ throw error;
1115
+ }
1116
+ });
1117
+ }
1118
+ /**
1119
+ * The held evidence of a managed entry (B3), read once under the shared lease the holder already
1120
+ * has: the entered provider, the held handle's id and its generation (the row's `created_at`
1121
+ * milliseconds), the installed binding of exactly that generation and provider, the handle's
1122
+ * roots and the base working root admission resolves. Undefined without an installed binding or
1123
+ * with a project binding that no longer matches: the managed writer then refuses the call. The
1124
+ * writer validates every field again under the authority locks.
1125
+ */
1126
+ async heldContextEvidence(ctx, p, e) {
1127
+ try {
1128
+ return await this.readHeldContextEvidence(ctx, p, e);
1129
+ }
1130
+ catch (error) {
1131
+ // a storage failure reading the evidence fails the managed call as unrecorded, before any
1132
+ // callback, never as a provider error
1133
+ if (isStorageError(error))
1134
+ throw new ManagedDeviceContextFailed("unavailable");
1135
+ throw error;
1136
+ }
1137
+ }
1138
+ async readHeldContextEvidence(ctx, p, e) {
1139
+ const instanceGeneration = String(e.createdAt);
1140
+ // a cloud instance is named by its installed environment as the managed writer reads it
1141
+ // under the authority locks (B-15): current evidence, nothing unapplied, nothing wider than
1142
+ // desired; otherwise the device is unavailable for managed work, not a stale retry
1143
+ const cloud = (await this.deviceSource(ctx)) === "cloud";
1144
+ const applied = cloud
1145
+ ? await this.facts.readHeldEnvironment({ orgId: ctx.orgId, deviceId: ctx.deviceId })
1146
+ : null;
1147
+ if (cloud &&
1148
+ (applied === null ||
1149
+ applied.provider !== p.plugin ||
1150
+ applied.instanceGeneration !== instanceGeneration))
1151
+ return undefined;
1152
+ const binding = applied
1153
+ ? { binding_id: applied.bindingId }
1154
+ : await this.db
1155
+ .selectFrom("device_instance_bindings")
1156
+ .select("binding_id")
1157
+ .where("device_id", "=", ctx.deviceId)
1158
+ .where("instance_generation", "=", instanceGeneration)
1159
+ .where("provider", "=", p.plugin)
1160
+ .where("status", "=", "installed")
1161
+ .executeTakeFirst();
1162
+ if (!binding)
1163
+ return undefined;
1164
+ let workingRoot;
1165
+ try {
1166
+ workingRoot = await this.authority.workingRootFor({
1167
+ orgId: ctx.orgId,
1168
+ deviceId: ctx.deviceId,
1169
+ conversationId: ctx.holderConversationId,
1170
+ });
1171
+ }
1172
+ catch (error) {
1173
+ if (error instanceof ApiError)
1174
+ return undefined;
1175
+ throw error;
1176
+ }
1177
+ const roots = rootsOf(e.handle);
1178
+ return {
1179
+ deviceId: ctx.deviceId,
1180
+ provider: p.plugin,
1181
+ instanceId: e.handle.id,
1182
+ instanceGeneration,
1183
+ bindingId: binding.binding_id,
1184
+ roots: { workspace: roots.workspace, skills: roots.skills, tmp: roots.tmp },
1185
+ workingRoot,
1186
+ };
796
1187
  }
797
1188
  /**
798
1189
  * Becomes a holder: loops until it has a shared lease on a running instance, or `sandbox.busy`.
@@ -817,7 +1208,12 @@ let SandboxService = class SandboxService {
817
1208
  const row = await this.readRow(ctx);
818
1209
  // an instance whose mode or network must change goes through the exclusive lease
819
1210
  const ready = (r) => this.usable(r, p, gone) && !this.mustApply(r, p, want);
820
- if (ready(row)) {
1211
+ // a device with an unresolved retirement obligation is only entered through the
1212
+ // exclusive lease, whose gate retires the old incarnation or refuses (8.5); on the
1213
+ // staged path, so is an instance whose committed binding is not installed yet (B-8)
1214
+ if (!(await this.retirement.hasUnresolved(env)) &&
1215
+ ready(row) &&
1216
+ (await this.bound(p, env))) {
821
1217
  const lease = await this.leases.tryShared(env, this.cap, token);
822
1218
  if (lease) {
823
1219
  if (intent)
@@ -834,9 +1230,13 @@ let SandboxService = class SandboxService {
834
1230
  throw err;
835
1231
  }
836
1232
  }
837
- const e = await this.asShared(ctx, p, lease, ready, signal);
838
- if (e)
1233
+ // an obligation recorded while the shared lease was taken: null, back to the gate
1234
+ const e = await this.asShared(ctx, p, lease, ready, signal, true, "use");
1235
+ if (e) {
1236
+ // B-15: cloud evidence gone stale while the instance ran (a provider upgrade)
1237
+ await this.refreshCloudSupport(ctx, p, e, AbortSignal.any([signal, e.lease.signal]), false);
839
1238
  return e;
1239
+ }
840
1240
  }
841
1241
  }
842
1242
  else {
@@ -856,6 +1256,102 @@ let SandboxService = class SandboxService {
856
1256
  throw err;
857
1257
  }
858
1258
  }
1259
+ /**
1260
+ * Whether this device's instances record cloud evidence (B-15): a cloud device whose provider
1261
+ * (with a known version) reads its own permission support. A local device attests through its
1262
+ * installed binding instead.
1263
+ */
1264
+ async recordsCloudSupport(ctx, p) {
1265
+ return (p.plugin !== LOCAL_PROVIDER &&
1266
+ !p.binder &&
1267
+ p.version !== undefined &&
1268
+ typeof p.impl.permissionSupport === "function" &&
1269
+ (await this.deviceSource(ctx)) === "cloud");
1270
+ }
1271
+ /**
1272
+ * The provider's permission support of the held instance `handle`, read under the caller's
1273
+ * lifecycle lease within {@link PERMISSION_SUPPORT_TIMEOUT_MS}; undefined when it cannot be
1274
+ * read in time or is not a version 1 report. Never throws: missing evidence keeps the device
1275
+ * unprobed, it never fails the lifecycle step. A failure is logged once per instance generation
1276
+ * (`warnOnce`: a Redis marker shared by the replicas; without it, every failure is logged).
1277
+ */
1278
+ async cloudSupport(deviceId, p, handle, signal, warnOnce) {
1279
+ const read = p.impl.permissionSupport?.bind(p.impl);
1280
+ if (!read || p.version === undefined)
1281
+ return undefined;
1282
+ let failure;
1283
+ try {
1284
+ const sig = AbortSignal.any([signal, AbortSignal.timeout(PERMISSION_SUPPORT_TIMEOUT_MS)]);
1285
+ const report = cloudSupportOf(await read(handle, sig));
1286
+ if (report)
1287
+ return { provider: p.plugin, version: p.version, report };
1288
+ failure = { message: "cloud provider returned an invalid permission support report" };
1289
+ }
1290
+ catch (err) {
1291
+ if (signal.aborted)
1292
+ return undefined;
1293
+ failure = {
1294
+ message: "cannot read the cloud provider's permission support; device unprobed",
1295
+ err,
1296
+ };
1297
+ }
1298
+ // a log marker, not a lock: the previous value says whether this generation was logged (two
1299
+ // replicas racing may both log, which is harmless)
1300
+ const first = warnOnce === undefined ||
1301
+ (await this.redis
1302
+ .set(`capk:cloud-support-warned:${deviceId}:${warnOnce}`, "1", "EX", 86_400, "GET")
1303
+ .then((prev) => prev === null)
1304
+ .catch(() => true));
1305
+ if (first)
1306
+ this.log.warn(failure.message, {
1307
+ deviceId,
1308
+ provider: p.plugin,
1309
+ ...(failure.err !== undefined && { err: failure.err }),
1310
+ });
1311
+ return undefined;
1312
+ }
1313
+ /**
1314
+ * Under a lifecycle lease on the running instance `e`: records its cloud evidence again when
1315
+ * `force` (a resume) or when the recorded one is stale (another provider version, handle,
1316
+ * generation or applied limits; `cloudReportOwed`). The record is written only while the row
1317
+ * still holds the probed instance with the limits read before the probe, so a holder whose
1318
+ * lease was lost never overwrites newer evidence. A forced read that fails clears the recorded
1319
+ * identity (a resumed instance is unprobed until a read succeeds); any other failure leaves the
1320
+ * evidence as it was. Never throws.
1321
+ */
1322
+ async refreshCloudSupport(ctx, p, e, signal, force) {
1323
+ try {
1324
+ if (!(await this.recordsCloudSupport(ctx, p)))
1325
+ return;
1326
+ if (!force && !(await cloudReportOwed(this.db.db, ctx.deviceId, p.plugin, p.version)))
1327
+ return;
1328
+ const row = await this.db
1329
+ .selectFrom("device_instances")
1330
+ .select("instance_limits")
1331
+ .where("device_id", "=", ctx.deviceId)
1332
+ .executeTakeFirst();
1333
+ if (!row)
1334
+ return;
1335
+ const held = { ...e, limits: row.instance_limits };
1336
+ const support = await this.cloudSupport(ctx.deviceId, p, e.handle, signal, String(e.createdAt));
1337
+ if (support)
1338
+ await runOutsideTransaction(() => this.instanceWrites.recordCloudSupport(ctx.orgId, ctx.deviceId, held, support, signal));
1339
+ else if (force && !signal.aborted)
1340
+ await runOutsideTransaction(() => this.instanceWrites.clearCloudSupport(ctx.orgId, ctx.deviceId, held, p.plugin));
1341
+ }
1342
+ catch (err) {
1343
+ if (!signal.aborted)
1344
+ this.log.warn("cannot record the cloud instance's permission evidence", {
1345
+ deviceId: ctx.deviceId,
1346
+ provider: p.plugin,
1347
+ err,
1348
+ });
1349
+ }
1350
+ }
1351
+ /** No binder (protocol 2), or the current generation's binding is installed (B-8). */
1352
+ async bound(p, env) {
1353
+ return !p.binder || (await p.binder.status(env)) === "installed";
1354
+ }
859
1355
  async clearIntent(env, token) {
860
1356
  await this.leases
861
1357
  .clearIntent(env, token)
@@ -891,11 +1387,30 @@ let SandboxService = class SandboxService {
891
1387
  * Under a just-taken shared lease: confirms the row is still `accept`ed (else releases and
892
1388
  * returns null), records the holder and kills crashed holders' commands.
893
1389
  */
894
- async asShared(ctx, p, lease, accept, signal) {
1390
+ async asShared(ctx, p, lease, accept, signal,
1391
+ /**
1392
+ * Refused (null) while the device has an unresolved retirement obligation, checked under the
1393
+ * lease and before anything is killed or bumped; false only for exact-ref managed drains.
1394
+ */
1395
+ gated,
1396
+ /**
1397
+ * Checked under the lease (which the B1 snapshot writer's exclusive lease excludes) before
1398
+ * anything is killed or bumped: `reconciled` and `use` refuse a device carrying the
1399
+ * reconcile marker (B-11); `use` (entering a holder) also returns null on the staged path
1400
+ * while the instance's binding is not installed, so the caller binds it exclusively (B-8).
1401
+ * `none` for background polls, stops and drains.
1402
+ */
1403
+ check = "none") {
895
1404
  const env = ctx.deviceId;
896
1405
  try {
897
1406
  const row = await this.readRow(ctx);
898
- if (!accept(row)) {
1407
+ if (!accept(row) || (gated && (await this.retirement.hasUnresolved(env)))) {
1408
+ await lease.release();
1409
+ return null;
1410
+ }
1411
+ if (check !== "none")
1412
+ await this.facts.assertCloudReconciled(ctx.orgId, env);
1413
+ if (check === "use" && !(await this.bound(p, env))) {
899
1414
  await lease.release();
900
1415
  return null;
901
1416
  }
@@ -936,6 +1451,9 @@ let SandboxService = class SandboxService {
936
1451
  const env = ctx.deviceId;
937
1452
  const sig = AbortSignal.any([signal, lease.signal]);
938
1453
  try {
1454
+ // under the lease the B1 snapshot writer needs: a device carrying the reconcile marker gets
1455
+ // no create, resume, rebuild, limits change, retirement destroy or kill (B-11)
1456
+ await this.facts.assertCloudReconciled(ctx.orgId, env);
939
1457
  const s = await this.ensure(ctx, p, lease, sig, gone);
940
1458
  const dead = await this.claim(env);
941
1459
  if (s.resumed)
@@ -945,6 +1463,17 @@ let SandboxService = class SandboxService {
945
1463
  if (s.resumed || s.info.fresh) {
946
1464
  await this.killPendingTasks(env, s.handle, s.createdAt, p, lease.token, ctx.actor, sig);
947
1465
  }
1466
+ // B-15: a resumed cloud instance reads its permission support again; any other instance
1467
+ // whose recorded evidence is stale (a limits change, a provider version change) too
1468
+ await this.refreshCloudSupport(ctx, p, s, sig, s.resumed === true);
1469
+ // staged path (B-8): create → commit → legacy gate (ensure) → cleanup → bind → installed →
1470
+ // downgrade. The cleanup a resume or create owes runs first: a retry after a failed bind
1471
+ // finds the instance running and would not owe it again. The binder sends the committed
1472
+ // binding id again on every retry, refuses while a legacy obligation is open and runs
1473
+ // outside any transaction; a failure releases the lease.
1474
+ const binder = p.binder;
1475
+ if (binder)
1476
+ await runOutsideTransaction(() => binder.bind(env, sig));
948
1477
  const shared = await lease.downgrade();
949
1478
  await this.register(env, shared.token);
950
1479
  return {
@@ -999,6 +1528,7 @@ let SandboxService = class SandboxService {
999
1528
  async killTagged(env, handle, p, tags, signal, lease) {
1000
1529
  if (tags.length === 0)
1001
1530
  return;
1531
+ await runOutsideTransaction(() => this.operationIntents.revokeHolders(env, tags));
1002
1532
  const sig = AbortSignal.any([signal, lease.signal]);
1003
1533
  await this.kill(env, "takeover", () => p.impl.killTagged(handle, tags, sig), sig);
1004
1534
  }
@@ -1208,6 +1738,587 @@ let SandboxService = class SandboxService {
1208
1738
  await lease.release();
1209
1739
  }
1210
1740
  }
1741
+ /**
1742
+ * The worker's retirement of a device's old incarnations (8.5, `RetireLegacyTasksJob`): one try
1743
+ * at the exclusive lifecycle lease, then the same gate as every acquisition. `busy`: a holder
1744
+ * has the device (the inline gate runs on its next lifecycle acquisition anyway); `unavailable`:
1745
+ * an obligation stays (quarantined, or a destroy that failed); `clear`: none left.
1746
+ */
1747
+ async retireLegacy(deviceId,
1748
+ /** The worker's signal (its stop, a lost run lock): ends a destroy in flight. */
1749
+ signal) {
1750
+ const lease = await this.leases.tryExclusive(deviceId);
1751
+ if (!lease)
1752
+ return "busy";
1753
+ try {
1754
+ const row = await this.db
1755
+ .selectFrom("device_instances")
1756
+ .selectAll()
1757
+ .where("device_id", "=", deviceId)
1758
+ .executeTakeFirst();
1759
+ const fence = row ? { gen: row.generation } : null;
1760
+ if (row && fence)
1761
+ await this.fenced(lease, deviceId, fence, {});
1762
+ await this.retireIncarnations(deviceId, lease, row, fence, signal);
1763
+ return "clear";
1764
+ }
1765
+ catch (err) {
1766
+ if (isRetirementPending(err))
1767
+ return "unavailable";
1768
+ throw err;
1769
+ }
1770
+ finally {
1771
+ await lease.release();
1772
+ }
1773
+ }
1774
+ /**
1775
+ * The lifecycle reconcile of a cloud device carrying `permission_reconcile_required` (B-12),
1776
+ * under one try at its exclusive lifecycle lease (`busy`: a holder has it). The snapshot
1777
+ * writer's reconcile runs first ({@link CloudPermissionSnapshots.reconcileHeld}: it narrows the
1778
+ * authority to what the instance is known to run, and may clear the marker by itself). A device
1779
+ * with an unresolved retirement obligation stops there: its incarnation is the retirement
1780
+ * gate's alone (never resumed here). When the
1781
+ * marker stays on a live instance whose provider can `update`, the provider applies the
1782
+ * reconcile target, which is never wider than the instance in any dimension, so this only
1783
+ * narrows; a suspended instance is resumed for it (its leftover commands killed, nobody else
1784
+ * holds it) and suspended again, as its row still says. `updated` records the target as
1785
+ * applied (fenced) and the reconcile runs again, which clears the marker. No `update`, a
1786
+ * `recreate` answer, a gone instance or a failure leave the marker and its file reset action.
1787
+ */
1788
+ async reconcileLimits(deviceId, signal = AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)) {
1789
+ const lease = await this.leases.tryExclusive(deviceId);
1790
+ if (!lease)
1791
+ return "busy";
1792
+ try {
1793
+ const device = await this.db
1794
+ .selectFrom("devices")
1795
+ .select("org_id")
1796
+ .where("id", "=", deviceId)
1797
+ .executeTakeFirst();
1798
+ if (!device)
1799
+ return { state: "skipped" };
1800
+ const orgId = device.org_id;
1801
+ const row = await this.db
1802
+ .selectFrom("device_instances")
1803
+ .selectAll()
1804
+ .where("device_id", "=", deviceId)
1805
+ .executeTakeFirst();
1806
+ const fence = row ? { gen: row.generation } : null;
1807
+ if (row && fence)
1808
+ await this.fenced(lease, deviceId, fence, {});
1809
+ const before = await runOutsideTransaction(() => this.snapshots.reconcileHeld(orgId, deviceId));
1810
+ // an incarnation under a retirement obligation is never resumed or updated here: only the
1811
+ // retirement gate may touch it (C1); the marker stays until the gate cleared it
1812
+ if (before.state === "reconcile-required" && (await this.retirement.hasUnresolved(deviceId)))
1813
+ return before;
1814
+ const p = row ? this.rowProvider(row) : undefined;
1815
+ const update = p?.impl.update?.bind(p.impl);
1816
+ if (before.state !== "reconcile-required" ||
1817
+ before.target === undefined ||
1818
+ !row?.handle ||
1819
+ !fence ||
1820
+ !p ||
1821
+ !update ||
1822
+ p.plugin === LOCAL_PROVIDER ||
1823
+ row.provider !== p.plugin ||
1824
+ row.fs_status !== "ready" ||
1825
+ (row.status !== "running" && row.status !== "suspended"))
1826
+ return before;
1827
+ const handle = row.handle;
1828
+ // the effective limits with their resources, read under the lease: exactly the target, or
1829
+ // the authority moved since the reconcile (the next round sees it)
1830
+ const want = await this.deviceLimits({ orgId, deviceId }, { source: "cloud" });
1831
+ if (!sameAppliedExactly(appliedOf(want), before.target))
1832
+ return before;
1833
+ const sig = AbortSignal.any([signal, opSignal(lease)]);
1834
+ const facts = { deviceId, provider: p.plugin, to: before.target };
1835
+ const suspended = row.status === "suspended";
1836
+ let answer;
1837
+ try {
1838
+ if (suspended && (await p.impl.resume(handle, sig)) === "gone")
1839
+ answer = "gone";
1840
+ else {
1841
+ if (suspended)
1842
+ await this.kill(deviceId, "resume", () => p.impl.killAll(handle, sig), sig);
1843
+ answer = await update(handle, want, sig);
1844
+ }
1845
+ }
1846
+ catch (err) {
1847
+ if (sig.aborted)
1848
+ throw err;
1849
+ this.log.warn("cannot apply the reconcile limits to the sandbox instance", {
1850
+ ...facts,
1851
+ err,
1852
+ });
1853
+ answer = "recreate";
1854
+ }
1855
+ finally {
1856
+ if (suspended)
1857
+ await this.bestEffort(deviceId, "suspend the instance again after a limits update", (s) => p.impl.suspend(handle, s));
1858
+ }
1859
+ if (answer !== "updated")
1860
+ return before;
1861
+ if (!(await lease.renew()))
1862
+ throw new SandboxLockLostError(deviceId);
1863
+ await this.fenced(lease, deviceId, fence, {
1864
+ instance_limits: instanceLimitsJson(appliedOf(want)),
1865
+ });
1866
+ this.log.info("sandbox instance limits reconciled by the provider's update", facts);
1867
+ const after = await runOutsideTransaction(() => this.snapshots.reconcileHeld(orgId, deviceId));
1868
+ // a running instance records its evidence for the new limits now; a suspended one on its
1869
+ // next use's resume
1870
+ if (!suspended)
1871
+ await this.refreshCloudSupport({ orgId, deviceId }, p, { handle, createdAt: row.created_at.getTime() }, sig, false);
1872
+ return after;
1873
+ }
1874
+ finally {
1875
+ await lease.release();
1876
+ }
1877
+ }
1878
+ /**
1879
+ * The worker's sweep of {@link reconcileLimits} (`sandbox-reconcile-limits`): up to `limit`
1880
+ * live cloud devices of the loaded cloud provider carrying the marker on a live instance, in
1881
+ * id order from a shared keyset cursor that wraps around (no starvation), each tried at most
1882
+ * once per {@link RECONCILE_RETRY_SECONDS} across replicas (a Redis marker).
1883
+ * Nothing without a cloud provider that can `update`. Returns how many it reconciled.
1884
+ */
1885
+ async reconcileMarked(limit = 10) {
1886
+ const p = this.providers.cloud();
1887
+ if (!p?.impl.update)
1888
+ return 0;
1889
+ const page = (after, n) => this.db
1890
+ .selectFrom("devices as d")
1891
+ .innerJoin("device_instances as i", "i.device_id", "d.id")
1892
+ .select("d.id")
1893
+ .where("d.source", "=", "cloud")
1894
+ .where("d.deleted_at", "is", null)
1895
+ .where("d.permission_reconcile_required", "=", true)
1896
+ .where("i.provider", "=", p.plugin)
1897
+ .where("i.handle", "is not", null)
1898
+ .where("i.status", "in", ["running", "suspended"])
1899
+ .where(sql `d.id COLLATE "C" > ${after}`)
1900
+ .orderBy(sql `d.id COLLATE "C"`)
1901
+ .limit(n)
1902
+ .execute();
1903
+ // a keyset cursor shared by the replicas (the cron runs once per tick): each tick goes on
1904
+ // after the last device the previous one visited and wraps around, so devices that stay
1905
+ // marked never starve the ones after them
1906
+ const after = (await this.redis.get(RECONCILE_CURSOR_KEY).catch(() => null)) ?? "";
1907
+ const rows = await page(after, limit);
1908
+ if (rows.length < limit && after !== "") {
1909
+ const seen = new Set(rows.map((r) => r.id));
1910
+ for (const r of await page("", limit - rows.length))
1911
+ if (!seen.has(r.id) && r.id <= after)
1912
+ rows.push(r);
1913
+ }
1914
+ const last = rows.at(-1)?.id;
1915
+ await this.redis
1916
+ .set(RECONCILE_CURSOR_KEY, last ?? "", "EX", 86_400)
1917
+ .catch((err) => this.log.warn("cannot record the reconcile cursor", { err }));
1918
+ let n = 0;
1919
+ for (const { id } of rows) {
1920
+ // a retry window shared by the replicas, not a lock: a second try within it waits
1921
+ const first = await this.redis
1922
+ .set(`capk:cloud-reconcile-tried:${id}`, "1", "EX", RECONCILE_RETRY_SECONDS, "GET")
1923
+ .then((prev) => prev === null)
1924
+ .catch(() => false);
1925
+ if (!first)
1926
+ continue;
1927
+ try {
1928
+ const r = await this.reconcileLimits(id);
1929
+ if (r !== "busy" && r.state === "bound")
1930
+ n++;
1931
+ }
1932
+ catch (err) {
1933
+ this.log.warn("cannot reconcile a cloud device's limits; will retry", {
1934
+ deviceId: id,
1935
+ err,
1936
+ });
1937
+ }
1938
+ }
1939
+ return n;
1940
+ }
1941
+ /**
1942
+ * The retirement gate (permission runtime cutover 8.5), under the exclusive lifecycle lease and
1943
+ * before the instance is used, resumed, rebuilt, switched to another provider, bound or
1944
+ * downgraded to shared use: every unresolved obligation of the device is settled here or the
1945
+ * device is unavailable ({@link retirementPending}).
1946
+ * - The obligation names the **current** incarnation (provider and exact generation): a cloud
1947
+ * one is destroyed whole by its provider (never resumed, never `killAll`ed, the file system
1948
+ * kept), the confirmed destruction is recorded and the row reads `destroyed`, so the use
1949
+ * creates a fresh instance; a failed destroy keeps the obligation. A kernel-internal (local)
1950
+ * one is quarantined: its destroy is a no-op and a restart proves nothing.
1951
+ * - B-22: a **suspended** current cloud incarnation whose members are all revoked managed starts
1952
+ * is not destroyed whole (its other tasks would be lost): each revoked ref gets its exact stop
1953
+ * (persisted while suspended), the instance is resumed, each stop is confirmed (`stopped` or
1954
+ * `already-exited`), and the obligation resolves as `exact-cancelled`. Any failure is noted on
1955
+ * the obligation and falls back to the whole-instance destroy above. `resumed` given (a use):
1956
+ * the resumed instance is left running for it (`resumed.resumed` set); otherwise (the worker),
1957
+ * or when the device stays refused, it is suspended again, as its row still says.
1958
+ * - It names an incarnation that is **not current** (replaced, a reused handle with another
1959
+ * generation, unknown): resolved only by a recorded provider-confirmed destruction of exactly
1960
+ * it, else quarantined. A newer generation is never evidence.
1961
+ * Returns the row as it is afterwards.
1962
+ */
1963
+ async retireIncarnations(id, held, row, fence, signal,
1964
+ /** A use's holder: a gate that resumed the instance (B-22) leaves it running and says so. */
1965
+ resumed) {
1966
+ // the device's own candidates first: the gate never depends on the worker having scanned
1967
+ // (C1); then a later boot an authenticated hello already reported settles local ones
1968
+ await this.retirement.scanUntilStable(5, id);
1969
+ await this.retirement.settleRebooted(id);
1970
+ const open = await this.retirement.unresolved(id);
1971
+ let now = row;
1972
+ // every obligation is tried (one that stays never hides another that can resolve); the
1973
+ // device is refused at the end while any stays, with the answer that tells what would help:
1974
+ // a failed or impossible destroy now → unavailable (a retry may succeed); a cloud incarnation
1975
+ // no evidence can ever cover → recreate the device; a local one whose computer never reported
1976
+ // a boot → replace the device; else only a restart of the computer is missing
1977
+ let pending = false;
1978
+ let failed = false;
1979
+ let cloudPermanent = false;
1980
+ let unknownBoot = false;
1981
+ const isLive = (r) => r !== undefined &&
1982
+ r.handle !== null &&
1983
+ (r.status === "running" || r.status === "suspended" || r.status === "creating");
1984
+ /** The instance this gate resumed for an exact cancel and still runs (B-22). */
1985
+ let resumedHere = null;
1986
+ const bounded = () => AbortSignal.any([
1987
+ opSignal(held),
1988
+ AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
1989
+ ...(signal ? [signal] : []),
1990
+ ]);
1991
+ /**
1992
+ * B-22: on a suspended current cloud incarnation whose members are all revoked managed
1993
+ * starts, cancels each by its exact ref and resumes the instance in between. `skip`: the
1994
+ * shape does not apply (the destroy follows); `failed`: a cancel could not be confirmed (the
1995
+ * reason is noted, the destroy follows).
1996
+ */
1997
+ const cancelOnResume = async (o, live) => {
1998
+ if (live.status !== "suspended" || !isCloudProvider(o.provider))
1999
+ return "skip";
2000
+ const impl = this.providers.forName(o.provider)?.impl;
2001
+ const background = impl?.background;
2002
+ if (!impl || !background)
2003
+ return "skip";
2004
+ const members = await this.retirement.membersOf(o.id);
2005
+ if (members.length === 0 || members.some((m) => m.kind !== "revoked-start"))
2006
+ return "skip";
2007
+ const owed = [];
2008
+ for (const m of members) {
2009
+ const intent = await this.db
2010
+ .selectFrom("sandbox_operation_intents")
2011
+ .select([
2012
+ "method",
2013
+ "state",
2014
+ "revoke_acknowledged",
2015
+ "provider",
2016
+ "instance_generation",
2017
+ "execution_ref",
2018
+ ])
2019
+ .where("operation_id", "=", m.refId)
2020
+ .where("device_id", "=", id)
2021
+ .executeTakeFirst();
2022
+ if (intent?.revoke_acknowledged === true)
2023
+ continue;
2024
+ if (intent === undefined ||
2025
+ intent.method !== "backgroundStart" ||
2026
+ intent.state !== "revoked" ||
2027
+ intent.provider !== o.provider ||
2028
+ intent.instance_generation !== o.instanceGeneration)
2029
+ return { failed: `revoked start ${m.refId} cannot be named on this incarnation` };
2030
+ let ref;
2031
+ try {
2032
+ ref = parseSandboxExecutionRef(intent.execution_ref);
2033
+ }
2034
+ catch {
2035
+ return { failed: `revoked start ${m.refId} has no valid execution reference` };
2036
+ }
2037
+ if (ref.operationId !== m.refId ||
2038
+ ref.instanceGeneration !== o.instanceGeneration ||
2039
+ ref.instanceId !== live.handle.id)
2040
+ return { failed: `revoked start ${m.refId} names another instance` };
2041
+ owed.push(ref);
2042
+ }
2043
+ try {
2044
+ // persisted while suspended: the provider applies a pending cancel before any work of
2045
+ // the instance runs again; the answer is confirmed after the resume
2046
+ for (const ref of owed) {
2047
+ const r = await background.stop(live.handle, ref, {
2048
+ graceMs: MANAGED_STOP_GRACE_MS,
2049
+ signal: bounded(),
2050
+ });
2051
+ // anything but a recorded (or already settled) cancel: never resume into the work
2052
+ if (r.outcome !== "cancel-pending" &&
2053
+ r.outcome !== "stopped" &&
2054
+ r.outcome !== "already-exited")
2055
+ return {
2056
+ failed: `the exact stop of ${ref.operationId} answered ${r.outcome} while suspended`,
2057
+ };
2058
+ }
2059
+ if ((await impl.resume(live.handle, bounded())) === "gone")
2060
+ return { failed: "the instance is gone at the provider" };
2061
+ resumedHere = { impl, handle: live.handle };
2062
+ for (const ref of owed) {
2063
+ const r = await background.stop(live.handle, ref, {
2064
+ graceMs: MANAGED_STOP_GRACE_MS,
2065
+ signal: bounded(),
2066
+ });
2067
+ if (r.outcome !== "stopped" && r.outcome !== "already-exited")
2068
+ return { failed: `the exact stop of ${ref.operationId} answered ${r.outcome}` };
2069
+ }
2070
+ }
2071
+ catch (err) {
2072
+ if (held.signal.aborted || signal?.aborted)
2073
+ throw err;
2074
+ return { failed: err instanceof Error ? err.message : String(err) };
2075
+ }
2076
+ if (!(await held.renew()))
2077
+ throw new SandboxLockLostError(id);
2078
+ this.log.info("revoked starts cancelled exactly on a resumed instance", {
2079
+ deviceId: id,
2080
+ operations: owed.map((r) => r.operationId),
2081
+ });
2082
+ // every member read is covered (an acknowledged one needed no stop)
2083
+ return { cancelled: members.map((m) => m.refId) };
2084
+ };
2085
+ /**
2086
+ * Destroys the live incarnation of `now` whole with its own provider (never resumed or
2087
+ * killAll'ed, files kept), records the confirmed destruction and marks the row destroyed.
2088
+ */
2089
+ const destroyLive = async (o, live) => {
2090
+ const provider = live.provider ?? "unknown";
2091
+ const impl = isCloudProvider(provider) ? this.providers.forName(provider)?.impl : undefined;
2092
+ if (!impl) {
2093
+ await this.retirement.noteFailure(o.id, `provider ${provider} is not loaded`);
2094
+ return false;
2095
+ }
2096
+ try {
2097
+ // bounded (M5): a hung provider never holds the lease or the worker's tick
2098
+ await impl.destroy(live.handle, AbortSignal.any([
2099
+ opSignal(held),
2100
+ AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2101
+ ...(signal ? [signal] : []),
2102
+ ]));
2103
+ }
2104
+ catch (err) {
2105
+ if (held.signal.aborted || signal?.aborted)
2106
+ throw err;
2107
+ await this.retirement.noteFailure(o.id, err);
2108
+ this.log.warn("cannot destroy an instance that may run legacy work; device unavailable", {
2109
+ deviceId: id,
2110
+ err,
2111
+ });
2112
+ return false;
2113
+ }
2114
+ if (!(await held.renew()))
2115
+ throw new SandboxLockLostError(id);
2116
+ resumedHere = null;
2117
+ await this.retirement.recordDestruction(id, provider, String(live.created_at.getTime()));
2118
+ if (fence)
2119
+ await this.fenced(held, id, fence, {
2120
+ status: "destroyed",
2121
+ destroyed_at: sql `now()`,
2122
+ running_since: null,
2123
+ suspended_at: null,
2124
+ sweep_failed_at: null,
2125
+ });
2126
+ this.log.info("instance that may run legacy work destroyed", { deviceId: id });
2127
+ now = await this.db
2128
+ .selectFrom("device_instances")
2129
+ .selectAll()
2130
+ .where("device_id", "=", id)
2131
+ .executeTakeFirst();
2132
+ return true;
2133
+ };
2134
+ /**
2135
+ * R2-I1: the row is not live (destroyed before 0157 without a record, or a create that left
2136
+ * `creating` with no handle). With no `prev_handle`, the row's own cloud provider holds at
2137
+ * most one instance of the device's name (sandbox@2 same-name replacement), so its destroy by
2138
+ * that name confirms every incarnation there; it is recorded as the destruction of the row's
2139
+ * incarnation. A provider not loaded or a failed destroy keeps the obligation open.
2140
+ */
2141
+ const destroyNamed = async (o, row) => {
2142
+ const provider = row.provider ?? "unknown";
2143
+ const impl = isCloudProvider(provider) ? this.providers.forName(provider)?.impl : undefined;
2144
+ if (!impl) {
2145
+ await this.retirement.noteFailure(o.id, `provider ${provider} is not loaded`);
2146
+ return false;
2147
+ }
2148
+ try {
2149
+ await impl.destroyByName(deviceResourceName(id), AbortSignal.any([
2150
+ opSignal(held),
2151
+ AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2152
+ ...(signal ? [signal] : []),
2153
+ ]));
2154
+ }
2155
+ catch (err) {
2156
+ if (held.signal.aborted || signal?.aborted)
2157
+ throw err;
2158
+ await this.retirement.noteFailure(o.id, err);
2159
+ this.log.warn("cannot destroy by name an instance that may run legacy work", {
2160
+ deviceId: id,
2161
+ err,
2162
+ });
2163
+ return false;
2164
+ }
2165
+ if (!(await held.renew()))
2166
+ throw new SandboxLockLostError(id);
2167
+ await this.retirement.recordDestruction(id, provider, String(row.created_at.getTime()));
2168
+ if (fence && row.status === "creating")
2169
+ await this.fenced(held, id, fence, {
2170
+ status: "destroyed",
2171
+ destroyed_at: sql `now()`,
2172
+ running_since: null,
2173
+ suspended_at: null,
2174
+ sweep_failed_at: null,
2175
+ });
2176
+ this.log.info("instance that may run legacy work destroyed by name", { deviceId: id });
2177
+ now = await this.db
2178
+ .selectFrom("device_instances")
2179
+ .selectAll()
2180
+ .where("device_id", "=", id)
2181
+ .executeTakeFirst();
2182
+ return true;
2183
+ };
2184
+ try {
2185
+ for (const o of open) {
2186
+ const gen = o.instanceGeneration;
2187
+ const local = isInternalProvider(o.provider);
2188
+ const current = isLive(now) && now.provider === o.provider && String(now.created_at.getTime()) === gen;
2189
+ if (current && isLive(now)) {
2190
+ if (local) {
2191
+ await this.retirement.quarantine(o.id, o.bootId === null
2192
+ ? "local instance: no boot identity was reported, so no restart can prove its legacy work ended"
2193
+ : "local instance: waiting for a restart of the computer (a later boot identity)");
2194
+ if (o.bootId === null)
2195
+ unknownBoot = true;
2196
+ pending = true;
2197
+ continue;
2198
+ }
2199
+ let cancel = await cancelOnResume(o, now);
2200
+ if (cancel !== "skip" && "cancelled" in cancel) {
2201
+ // resolved only while no member outside the stopped refs exists (a concurrent scan's)
2202
+ if (await this.retirement.resolveCancelled(o.id, cancel.cancelled))
2203
+ continue;
2204
+ cancel = { failed: "a revoked start was recorded while the cancel ran" };
2205
+ }
2206
+ if (cancel !== "skip") {
2207
+ this.log.warn("cannot cancel revoked starts exactly; destroying the instance", {
2208
+ deviceId: id,
2209
+ reason: cancel.failed,
2210
+ });
2211
+ await this.retirement.noteFailure(o.id, cancel.failed);
2212
+ }
2213
+ if (await destroyLive(o, now))
2214
+ await this.retirement.resolveDestroyed(o.id);
2215
+ else {
2216
+ pending = true;
2217
+ failed = true;
2218
+ }
2219
+ continue;
2220
+ }
2221
+ // the existing whole-instance destroy left the row `destroyed` on exactly this incarnation
2222
+ // with nothing kept for a later retry: the provider confirmed it
2223
+ const destroyedHere = now !== undefined &&
2224
+ now.status === "destroyed" &&
2225
+ now.provider === o.provider &&
2226
+ String(now.created_at.getTime()) === gen &&
2227
+ now.prev_handle === null &&
2228
+ isCloudProvider(o.provider);
2229
+ if (destroyedHere || (await this.retirement.destructionRecorded(id, o.provider, gen))) {
2230
+ await this.retirement.resolveDestroyed(o.id);
2231
+ continue;
2232
+ }
2233
+ if (!local && (gen === "unknown" || o.provider === "unknown")) {
2234
+ // R1-I1 (b): a cloud incarnation the kernel cannot name. Every incarnation the device had
2235
+ // stopped being current through a kernel destroy, a provider `gone` or a kept
2236
+ // `prev_handle`; so once the device's current incarnation is destroyed with
2237
+ // confirmation, nothing earlier is kept (`prev_handle`) and the obligation was recorded
2238
+ // under the freeze (no dispatch after it), no instance of the device can run legacy work.
2239
+ // This rests on sandbox@2 same-name replacement: every rebuild on the same provider goes
2240
+ // through `create`, which first removes the old `cap-device-<id>` instance (so a `gone`
2241
+ // answer, E2B's token-failure `gone` included, and `applyLimits`' swallowed destroy
2242
+ // failure leave nothing behind), and E2B's incarnations are one sandbox (destroying the
2243
+ // current one ends the earlier processes). A provider or kernel path that rebuilds
2244
+ // without same-name replacement breaks this barrier.
2245
+ const frozenAt = await this.retirement.frozenAt();
2246
+ const reason = frozenAt === null || o.createdAt < frozenAt
2247
+ ? "an unknown cloud incarnation recorded before the freeze"
2248
+ : now === undefined || !now.had_instance
2249
+ ? // a row (re)inserted by this acquisition knows nothing of the earlier instances
2250
+ "an unknown cloud incarnation and no instance record to destroy"
2251
+ : now.prev_handle !== null
2252
+ ? "an unknown cloud incarnation while an earlier provider's instance may still exist"
2253
+ : null;
2254
+ if (reason === null && now !== undefined) {
2255
+ if (isLive(now)) {
2256
+ if (await destroyLive(o, now))
2257
+ await this.retirement.resolveDestroyed(o.id);
2258
+ else {
2259
+ pending = true;
2260
+ failed = true;
2261
+ }
2262
+ continue;
2263
+ }
2264
+ if (now.status === "destroyed" &&
2265
+ now.provider !== null &&
2266
+ (await this.retirement.destructionRecorded(id, now.provider, String(now.created_at.getTime())))) {
2267
+ await this.retirement.resolveDestroyed(o.id);
2268
+ continue;
2269
+ }
2270
+ // not live and nothing recorded (R2-I1): confirm by name with the row's provider
2271
+ if (await destroyNamed(o, now))
2272
+ await this.retirement.resolveDestroyed(o.id);
2273
+ else {
2274
+ pending = true;
2275
+ failed = true;
2276
+ }
2277
+ continue;
2278
+ }
2279
+ await this.retirement.quarantine(o.id, reason ??
2280
+ "an unknown cloud incarnation and no confirmed destruction of the current one");
2281
+ cloudPermanent = true;
2282
+ pending = true;
2283
+ continue;
2284
+ }
2285
+ await this.retirement.quarantine(o.id, local
2286
+ ? o.bootId === null
2287
+ ? "local instance: no boot identity was reported, so no restart can prove its legacy work ended"
2288
+ : "local instance: waiting for a restart of the computer (a later boot identity)"
2289
+ : "the old instance was replaced without a recorded confirmed destruction");
2290
+ if (!local)
2291
+ cloudPermanent = true;
2292
+ else if (o.bootId === null)
2293
+ unknownBoot = true;
2294
+ pending = true;
2295
+ }
2296
+ }
2297
+ catch (err) {
2298
+ // a throw after a resume (a lost lease, an abort, a failed write): the row still says
2299
+ // suspended, so the instance is suspended again (best effort) before the error goes on
2300
+ const left = resumedHere;
2301
+ if (left !== null)
2302
+ await this.bestEffort(id, "suspend the instance again after a failed retirement", (s) => left.impl.suspend(left.handle, s));
2303
+ throw err;
2304
+ }
2305
+ // a use runs on the instance this gate resumed; anything else leaves it as its row says
2306
+ const still = resumedHere;
2307
+ if (still !== null && (pending || resumed === undefined)) {
2308
+ await this.bestEffort(id, "suspend the instance again after an exact cancel", (s) => still.impl.suspend(still.handle, s));
2309
+ }
2310
+ else if (still !== null && resumed !== undefined)
2311
+ resumed.resumed = true;
2312
+ if (pending)
2313
+ throw failed
2314
+ ? retirementPending()
2315
+ : cloudPermanent
2316
+ ? recreateRequired()
2317
+ : unknownBoot
2318
+ ? replaceRequired()
2319
+ : restartRequired();
2320
+ return now;
2321
+ }
1211
2322
  /**
1212
2323
  * Under the exclusive lease (before the downgrade), on an instance just resumed from
1213
2324
  * `suspended`: kills every command left in it (`killAll`), crashed holders' (`dead`, already
@@ -1216,6 +2327,7 @@ let SandboxService = class SandboxService {
1216
2327
  * failures are only warned.
1217
2328
  */
1218
2329
  async killLeftovers(deviceId, handle, p, signal, dead) {
2330
+ await runOutsideTransaction(() => this.operationIntents.revokeHolders(deviceId, dead));
1219
2331
  await this.kill(deviceId, dead.length > 0 ? "takeover" : "resume", () => p.impl.killAll(handle, signal), signal);
1220
2332
  }
1221
2333
  /**
@@ -1226,6 +2338,10 @@ let SandboxService = class SandboxService {
1226
2338
  * and leaves the flags of this instance's tasks for the next resume.
1227
2339
  */
1228
2340
  async killPendingTasks(deviceId, handle, createdAt, p, tag, actor, signal) {
2341
+ // after the legacy-launch freeze a SID is no authority and the kill marks belong to the
2342
+ // retirement obligations: nothing is signalled or cleared (C1)
2343
+ if (await this.retirement.frozen())
2344
+ return;
1229
2345
  const rows = await this.background.pendingKills(deviceId);
1230
2346
  if (rows.length === 0)
1231
2347
  return;
@@ -1375,98 +2491,128 @@ let SandboxService = class SandboxService {
1375
2491
  .executeTakeFirst();
1376
2492
  if (!live)
1377
2493
  throw deviceNotFound();
1378
- const row = await this.db
2494
+ const read = await this.db
1379
2495
  .selectFrom("device_instances")
1380
2496
  .selectAll()
1381
2497
  .where("device_id", "=", id)
1382
2498
  .executeTakeFirst();
1383
- if (!row)
2499
+ if (!read)
1384
2500
  throw deviceNotFound();
1385
- if (row.org_id !== ctx.orgId)
2501
+ if (read.org_id !== ctx.orgId)
1386
2502
  throw this.foreign(ctx);
1387
- const fence = { gen: row.generation };
2503
+ const fence = { gen: read.generation };
1388
2504
  // Every acquisition first does a fenced increment: an old holder whose lease expired while it
1389
2505
  // kept running (a stalled sweep) then fails its next write.
1390
2506
  await this.fenced(held, id, fence, {});
1391
- if (row.fs_status === "lost")
1392
- throw deviceFilesLost(p.plugin === LOCAL_PROVIDER);
1393
- if (row.provider !== null &&
1394
- row.provider !== p.plugin &&
1395
- (row.fs_status !== "none" || row.handle !== null)) {
1396
- throw otherProvider(row.provider);
1397
- }
1398
- if (row.provider !== null &&
1399
- row.provider !== p.plugin &&
1400
- row.fs_status === "none" &&
1401
- row.status === "creating") {
1402
- // a create by the previous provider ended before its file system was recorded: that
1403
- // provider may have made it by name, and nothing else would ever destroy it
1404
- await this.dropUnrecordedFiles(id, row.provider, signal);
1405
- }
1406
- // read under the lease, after the fence moved: a value read before the wait may be stale
1407
- // (another replica may have changed the mode meanwhile)
1408
- const want = await this.wantedLimits(ctx, p, row);
1409
- const handle = row.handle;
1410
- const createdAt = row.created_at.getTime();
1411
- const fsResets = row.fs_resets;
1412
- if (handle && isInstance(row, gone) && row.status === "running") {
1413
- const created = await this.create(ctx, p, held, row, fence, signal, want);
1414
- return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
1415
- }
1416
- if (handle && row.status === "running") {
1417
- if (want !== null && this.mustApply(row, p, want)) {
1418
- const created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want);
1419
- if (created)
1420
- return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2507
+ // the retirement gate (8.5), before any use, resume, rebuild, provider switch or bind: an
2508
+ // old incarnation that may run legacy work is destroyed (cloud, confirmed) or refuses
2509
+ signal.throwIfAborted();
2510
+ const gate = { resumed: false, running: false };
2511
+ const row = (await this.retireIncarnations(id, held, read, fence, undefined, gate)) ?? read;
2512
+ try {
2513
+ if (row.fs_status === "lost")
2514
+ throw deviceFilesLost(p.plugin === LOCAL_PROVIDER);
2515
+ if (row.provider !== null &&
2516
+ row.provider !== p.plugin &&
2517
+ (row.fs_status !== "none" || row.handle !== null)) {
2518
+ throw otherProvider(row.provider);
1421
2519
  }
1422
- return { handle, createdAt, fsResets, info: { fresh: false, restarted: false }, fence };
1423
- }
1424
- if (handle && row.status === "suspended") {
1425
- const r = await p.impl.resume(handle, signal);
1426
- if (r === "resumed") {
1427
- // the new limits first: the row says running only once the instance runs with them
2520
+ if (row.provider !== null &&
2521
+ row.provider !== p.plugin &&
2522
+ row.fs_status === "none" &&
2523
+ row.status === "creating") {
2524
+ // a create by the previous provider ended before its file system was recorded: that
2525
+ // provider may have made it by name, and nothing else would ever destroy it
2526
+ await this.dropUnrecordedFiles(id, row.provider, signal);
2527
+ }
2528
+ // read under the lease, after the fence moved: a value read before the wait may be stale
2529
+ // (another replica may have changed the mode meanwhile)
2530
+ const want = await this.wantedLimits(ctx, p, row);
2531
+ const handle = row.handle;
2532
+ const createdAt = row.created_at.getTime();
2533
+ const fsResets = row.fs_resets;
2534
+ if (handle && isInstance(row, gone) && row.status === "running") {
2535
+ const created = await this.create(ctx, p, held, row, fence, signal, want);
2536
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2537
+ }
2538
+ // the staged path's activation (B-8): an instance committed before the binder existed has no
2539
+ // binding for its generation and never can get one; past the retirement gate above, a new
2540
+ // generation is created (and committed with its binding) in its place
2541
+ if (handle &&
2542
+ p.binder &&
2543
+ (row.status === "running" || row.status === "suspended") &&
2544
+ (await p.binder.status(id)) === null) {
2545
+ this.log.info("instance without a committed binding; creating a bound generation", {
2546
+ deviceId: id,
2547
+ });
2548
+ const created = await this.create(ctx, p, held, row, fence, signal, want);
2549
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2550
+ }
2551
+ if (handle && row.status === "running") {
1428
2552
  if (want !== null && this.mustApply(row, p, want)) {
1429
- let created;
1430
- try {
1431
- created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want);
1432
- }
1433
- catch (err) {
1434
- // the row still says suspended; the next use resumes and kills what is left
1435
- await this.bestEffort(id, "kill the commands left after a failed limits change", (s) => p.impl.killAll(handle, s));
1436
- throw err;
1437
- }
1438
- if (created) {
2553
+ const created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want);
2554
+ if (created)
1439
2555
  return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2556
+ }
2557
+ return { handle, createdAt, fsResets, info: { fresh: false, restarted: false }, fence };
2558
+ }
2559
+ if (handle && row.status === "suspended") {
2560
+ // the retirement gate may have resumed it already, to cancel revoked starts exactly (B-22)
2561
+ const r = gate.resumed ? "resumed" : await p.impl.resume(handle, signal);
2562
+ if (r === "resumed") {
2563
+ // the new limits first: the row says running only once the instance runs with them
2564
+ if (want !== null && this.mustApply(row, p, want)) {
2565
+ let created;
2566
+ try {
2567
+ created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want);
2568
+ }
2569
+ catch (err) {
2570
+ // the row still says suspended; the next use resumes and kills what is left
2571
+ await this.bestEffort(id, "kill the commands left after a failed limits change", (s) => p.impl.killAll(handle, s));
2572
+ throw err;
2573
+ }
2574
+ if (created) {
2575
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2576
+ }
1440
2577
  }
2578
+ await this.fenced(held, id, fence, {
2579
+ status: "running",
2580
+ running_since: sql `now()`,
2581
+ suspended_at: null,
2582
+ sweep_failed_at: null,
2583
+ });
2584
+ gate.running = true;
2585
+ return {
2586
+ handle,
2587
+ createdAt,
2588
+ fsResets,
2589
+ info: { fresh: false, restarted: false },
2590
+ fence,
2591
+ resumed: true,
2592
+ };
1441
2593
  }
1442
- await this.fenced(held, id, fence, {
1443
- status: "running",
1444
- running_since: sql `now()`,
1445
- suspended_at: null,
1446
- sweep_failed_at: null,
2594
+ this.log.info("sandbox instance is gone at the provider; recreating", {
2595
+ deviceId: id,
1447
2596
  });
1448
- return {
1449
- handle,
1450
- createdAt,
1451
- fsResets,
1452
- info: { fresh: false, restarted: false },
1453
- fence,
1454
- resumed: true,
1455
- };
1456
2597
  }
1457
- this.log.info("sandbox instance is gone at the provider; recreating", {
1458
- deviceId: id,
1459
- });
2598
+ const created = await this.create(ctx, p, held, row, fence, signal, want);
2599
+ // had_instance only ever becomes true: any earlier instance (even if a rebuild failed since)
2600
+ // makes this one a restart on the kept files
2601
+ return {
2602
+ ...created,
2603
+ fsResets,
2604
+ info: { fresh: true, restarted: row.had_instance && row.fs_status === "ready" },
2605
+ fence,
2606
+ };
2607
+ }
2608
+ catch (err) {
2609
+ // the gate resumed the instance for an exact cancel (B-22) and this use failed before its
2610
+ // row said running: suspended again (best effort), as the row still says
2611
+ const resumedHandle = row.handle;
2612
+ if (gate.resumed && !gate.running && resumedHandle)
2613
+ await this.bestEffort(id, "suspend the instance again after a failed use", (s) => p.impl.suspend(resumedHandle, s));
2614
+ throw err;
1460
2615
  }
1461
- const created = await this.create(ctx, p, held, row, fence, signal, want);
1462
- // had_instance only ever becomes true: any earlier instance (even if a rebuild failed since)
1463
- // makes this one a restart on the kept files
1464
- return {
1465
- ...created,
1466
- fsResets,
1467
- info: { fresh: true, restarted: row.had_instance && row.fs_status === "ready" },
1468
- fence,
1469
- };
1470
2616
  }
1471
2617
  /**
1472
2618
  * Under the lease: fenced reset to `creating`, the file system when there is none
@@ -1482,6 +2628,7 @@ let SandboxService = class SandboxService {
1482
2628
  org_id: ctx.orgId,
1483
2629
  provider: p.plugin,
1484
2630
  handle: null,
2631
+ permission_roots: JSON.stringify(row.permission_roots ?? (row.handle ? rootsOf(row.handle) : DEFAULT_SANDBOX_ROOTS)),
1485
2632
  status: "creating",
1486
2633
  last_used_at: sql `now()`,
1487
2634
  running_since: null,
@@ -1543,22 +2690,29 @@ let SandboxService = class SandboxService {
1543
2690
  }
1544
2691
  let createdAt;
1545
2692
  try {
1546
- createdAt = await this.fenced(held, id, fence, {
2693
+ // B-15: a cloud instance's permission support, read from it under the lease and recorded
2694
+ // with the handle commit (an unread report never fails the create: the instance stays
2695
+ // unprobed until a later use records it)
2696
+ const support = (await this.recordsCloudSupport(ctx, p))
2697
+ ? await this.cloudSupport(id, p, handle, signal)
2698
+ : undefined;
2699
+ createdAt = await runOutsideTransaction(() => this.instanceWrites.commitHandle(ctx.orgId, id, fence.gen, rootsOf(handle), {
1547
2700
  status: "running",
1548
2701
  handle: JSON.stringify(handle),
1549
2702
  had_instance: true,
1550
- created_at: sql `now()`,
2703
+ // created_at is the generation commitHandle allocates (never a reused millisecond)
1551
2704
  running_since: sql `now()`,
1552
2705
  last_used_at: sql `now()`,
1553
2706
  ...(!atFileSystem && { instance_limits: record }),
1554
- });
2707
+ }, held.signal, support));
2708
+ fence.gen++;
1555
2709
  }
1556
2710
  catch (e) {
1557
- // Lease lost before the handle was recorded: destroy the new instance (best effort) so it
1558
- // does not leak. A provider that reuses instances by name (Ruling M10) may then hit the one
1559
- // the new holder just resumed or created; that heals: its next provider call throws
1560
- // SandboxGoneError (or resume returns gone) and withSandbox rebuilds in place. The file
1561
- // system is never touched here.
2711
+ // Lease lost (or the device read failed) before the handle was recorded: destroy the new
2712
+ // instance (best effort) so it does not leak. A provider that reuses instances by name
2713
+ // (Ruling M10) may then hit the one the new holder just resumed or created; that heals:
2714
+ // its next provider call throws SandboxGoneError (or resume returns gone) and withSandbox
2715
+ // rebuilds in place. The file system is never touched here.
1562
2716
  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", {
1563
2717
  deviceId: id,
1564
2718
  err,
@@ -1702,11 +2856,15 @@ let SandboxService = class SandboxService {
1702
2856
  * Destroys an instance of another provider with that provider: still loaded and destroyed →
1703
2857
  * false; otherwise warns and returns true (the record must be kept).
1704
2858
  */
1705
- async retire(id, provider, handle, signal) {
2859
+ async retire(id, provider, handle, signal,
2860
+ /** The retired incarnation's generation when known: its confirmed destroy is recorded (M4). */
2861
+ generation) {
1706
2862
  const old = this.providers.forName(provider)?.impl;
1707
2863
  if (old) {
1708
2864
  try {
1709
2865
  await old.destroy(handle, AbortSignal.any([signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]));
2866
+ if (generation !== undefined && isCloudProvider(provider))
2867
+ await this.retirement.recordDestruction(id, provider, generation);
1710
2868
  return false;
1711
2869
  }
1712
2870
  catch (err) {
@@ -1734,7 +2892,7 @@ let SandboxService = class SandboxService {
1734
2892
  await p.impl.destroy(row.handle, signal);
1735
2893
  }
1736
2894
  else if (row.handle && row.status !== "destroyed") {
1737
- if (await this.retire(id, owner, row.handle, signal)) {
2895
+ if (await this.retire(id, owner, row.handle, signal, String(row.created_at.getTime()))) {
1738
2896
  prev = { prev_provider: owner, prev_handle: JSON.stringify(row.handle) };
1739
2897
  }
1740
2898
  }
@@ -1786,6 +2944,11 @@ let SandboxService = class SandboxService {
1786
2944
  const fence = { gen: row.generation };
1787
2945
  const signal = opSignal(held);
1788
2946
  const prev = await this.destroyInstance(row, p, signal);
2947
+ // the provider's destroy resolved: confirmed destruction of exactly this cloud incarnation
2948
+ // (8.5 evidence); a kernel-internal (local) destroy is a no-op and is never recorded
2949
+ const owner = row.provider ?? p.plugin;
2950
+ if (row.handle && owner === p.plugin && isCloudProvider(owner))
2951
+ await this.retirement.recordDestruction(id, owner, String(row.created_at.getTime()));
1789
2952
  if (mode === "device")
1790
2953
  await this.destroyFiles(row, p, signal);
1791
2954
  if (!(await held.renew()))
@@ -1865,6 +3028,12 @@ SandboxService = __decorate([
1865
3028
  __param(3, Inject(SandboxProviders)),
1866
3029
  __param(4, Inject(KernelConfigService)),
1867
3030
  __param(5, Inject(KERNEL_LOGGER)),
1868
- __param(6, Inject(BackgroundTaskStore))
3031
+ __param(6, Inject(BackgroundTaskStore)),
3032
+ __param(7, Inject(PermissionFacts)),
3033
+ __param(8, Inject(SandboxOperationIntents)),
3034
+ __param(9, Inject(SandboxOperationAuthority)),
3035
+ __param(10, Inject(PermissionInstanceWrites)),
3036
+ __param(11, Inject(LegacyRetirementStore)),
3037
+ __param(12, Inject(CloudPermissionSnapshots))
1869
3038
  ], SandboxService);
1870
3039
  export { SandboxService };