@capybara-hq/kernel 0.1.0-rc.40 → 0.1.0-rc.42

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 (326) hide show
  1. package/bootstrap.json +10 -1
  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 +1 -1
  38. package/dist/config/schema.js +11 -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 +304 -4
  47. package/dist/conversations/events.js +279 -29
  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/db/kernel-schema.d.ts +238 -3
  59. package/dist/devices/access.js +1 -1
  60. package/dist/devices/access.module.d.ts +2 -0
  61. package/dist/devices/access.module.js +19 -0
  62. package/dist/devices/conversation-devices.d.ts +8 -29
  63. package/dist/devices/conversation-devices.js +37 -73
  64. package/dist/devices/device-projects.service.d.ts +26 -28
  65. package/dist/devices/device-projects.service.js +123 -127
  66. package/dist/devices/devices.controller.js +3 -1
  67. package/dist/devices/devices.module.js +11 -9
  68. package/dist/devices/devices.service.d.ts +116 -8
  69. package/dist/devices/devices.service.js +252 -20
  70. package/dist/devices/dto.d.ts +16 -0
  71. package/dist/devices/dto.js +34 -6
  72. package/dist/devices/errors.d.ts +8 -0
  73. package/dist/devices/errors.js +10 -0
  74. package/dist/devices/project-rules.d.ts +44 -0
  75. package/dist/devices/project-rules.js +27 -0
  76. package/dist/devices/working-root.d.ts +6 -0
  77. package/dist/devices/working-root.js +12 -1
  78. package/dist/errors.d.ts +31 -0
  79. package/dist/errors.js +31 -0
  80. package/dist/evals/reconstruct.d.ts +19 -2
  81. package/dist/evals/reconstruct.js +40 -2
  82. package/dist/evals/recorded-permission-context.d.ts +77 -0
  83. package/dist/evals/recorded-permission-context.js +151 -0
  84. package/dist/evals/recorded-tools.d.ts +10 -1
  85. package/dist/evals/recorded-tools.js +27 -3
  86. package/dist/evals/run-replay.d.ts +8 -2
  87. package/dist/evals/run-replay.js +18 -2
  88. package/dist/evals/trajectory.d.ts +1 -1
  89. package/dist/evals/worker.d.ts +10 -1
  90. package/dist/evals/worker.js +23 -14
  91. package/dist/http/api.module.js +2 -0
  92. package/dist/identity/accounts.d.ts +14 -1
  93. package/dist/identity/accounts.js +61 -5
  94. package/dist/identity/identity.module.js +2 -0
  95. package/dist/identity/settings.d.ts +28 -12
  96. package/dist/identity/settings.js +89 -33
  97. package/dist/index.d.ts +6 -0
  98. package/dist/index.js +5 -0
  99. package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
  100. package/dist/infra/cli/kernel-cli.module.js +5 -2
  101. package/dist/infra/cli/permission-cutover.d.ts +59 -0
  102. package/dist/infra/cli/permission-cutover.js +107 -0
  103. package/dist/infra/config/kernel-config.service.d.ts +2 -2
  104. package/dist/infra/config/kernel-config.service.js +31 -11
  105. package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
  106. package/dist/infra/database/startup-activation-transaction.js +242 -0
  107. package/dist/infra/database/transaction-host.d.ts +47 -0
  108. package/dist/infra/database/transaction-host.js +119 -0
  109. package/dist/infra/database/xact-lock.d.ts +1 -0
  110. package/dist/infra/database/xact-lock.js +6 -0
  111. package/dist/infra/outbox/registry.d.ts +39 -0
  112. package/dist/infra/outbox/registry.js +18 -0
  113. package/dist/kernel.module.js +2 -0
  114. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  115. package/dist/lifecycle/kernel-lifecycle.js +55 -28
  116. package/dist/local-devices/device-auth.js +1 -1
  117. package/dist/local-devices/device-policy.service.d.ts +35 -5
  118. package/dist/local-devices/device-policy.service.js +188 -13
  119. package/dist/local-devices/instance-bindings.d.ts +82 -0
  120. package/dist/local-devices/instance-bindings.js +304 -0
  121. package/dist/local-devices/keys.d.ts +5 -0
  122. package/dist/local-devices/keys.js +5 -0
  123. package/dist/local-devices/local-device-gateway.d.ts +19 -4
  124. package/dist/local-devices/local-device-gateway.js +185 -17
  125. package/dist/local-devices/local-device-provider.d.ts +42 -7
  126. package/dist/local-devices/local-device-provider.js +185 -10
  127. package/dist/local-devices/local-devices.module.d.ts +17 -2
  128. package/dist/local-devices/local-devices.module.js +49 -8
  129. package/dist/local-devices/machines.d.ts +35 -12
  130. package/dist/local-devices/machines.js +203 -8
  131. package/dist/local-devices/network-grants.js +3 -3
  132. package/dist/local-devices/network-grants.module.d.ts +2 -0
  133. package/dist/local-devices/network-grants.module.js +14 -0
  134. package/dist/local-devices/owner-report.d.ts +79 -0
  135. package/dist/local-devices/owner-report.js +155 -0
  136. package/dist/local-devices/owner-reports.d.ts +48 -0
  137. package/dist/local-devices/owner-reports.js +190 -0
  138. package/dist/local-devices/policy-summary.d.ts +24 -1
  139. package/dist/local-devices/policy-summary.js +48 -0
  140. package/dist/local-devices/relay.d.ts +82 -6
  141. package/dist/local-devices/relay.js +187 -16
  142. package/dist/local-devices/targets.d.ts +16 -1
  143. package/dist/local-devices/targets.js +35 -2
  144. package/dist/orgs/cloud-network-setting.d.ts +33 -0
  145. package/dist/orgs/cloud-network-setting.js +47 -0
  146. package/dist/orgs/offboarding.d.ts +3 -1
  147. package/dist/orgs/offboarding.js +8 -2
  148. package/dist/orgs/org-lock.d.ts +10 -4
  149. package/dist/orgs/org-lock.js +10 -4
  150. package/dist/orgs/orgs.service.d.ts +3 -1
  151. package/dist/orgs/orgs.service.js +8 -2
  152. package/dist/orgs/settings.controller.d.ts +4 -1
  153. package/dist/orgs/settings.controller.js +3 -3
  154. package/dist/orgs/settings.service.d.ts +48 -56
  155. package/dist/orgs/settings.service.js +144 -101
  156. package/dist/overrides.d.ts +6 -1
  157. package/dist/overrides.js +2 -0
  158. package/dist/platform/exclusions.js +20 -0
  159. package/dist/platform/ops/admin.ops.js +14 -11
  160. package/dist/platform/ops/agent-skills.ops.js +2 -0
  161. package/dist/platform/ops/devices.ops.js +10 -2
  162. package/dist/platform/ops/org-settings.ops.js +6 -6
  163. package/dist/platform/ops/orgs.ops.js +1 -0
  164. package/dist/roles/worker.module.js +4 -0
  165. package/dist/runtime/context/build.d.ts +3 -1
  166. package/dist/runtime/context/build.js +19 -3
  167. package/dist/runtime/context/compaction.js +5 -0
  168. package/dist/runtime/context/device-paths.d.ts +9 -2
  169. package/dist/runtime/context/device-paths.js +20 -0
  170. package/dist/runtime/context/permission-profile.d.ts +46 -0
  171. package/dist/runtime/context/permission-profile.js +194 -0
  172. package/dist/runtime/maintenance.d.ts +7 -1
  173. package/dist/runtime/maintenance.js +43 -15
  174. package/dist/runtime/model-call.d.ts +32 -0
  175. package/dist/runtime/model-call.js +67 -0
  176. package/dist/runtime/permission-context-errors.d.ts +39 -0
  177. package/dist/runtime/permission-context-errors.js +67 -0
  178. package/dist/runtime/permission-context.service.d.ts +60 -0
  179. package/dist/runtime/permission-context.service.js +286 -0
  180. package/dist/runtime/project/knowledge.d.ts +7 -2
  181. package/dist/runtime/project/knowledge.js +5 -2
  182. package/dist/runtime/project/knowledge.service.d.ts +17 -2
  183. package/dist/runtime/project/knowledge.service.js +76 -12
  184. package/dist/runtime/run-execution.d.ts +4 -1
  185. package/dist/runtime/run-execution.js +14 -5
  186. package/dist/runtime/run-steps.d.ts +11 -3
  187. package/dist/runtime/run-steps.js +27 -4
  188. package/dist/runtime/runtime.module.js +11 -0
  189. package/dist/sandbox/attachments-path.d.ts +15 -0
  190. package/dist/sandbox/attachments-path.js +15 -0
  191. package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
  192. package/dist/sandbox/cloud-permission-snapshot.js +407 -0
  193. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
  194. package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
  195. package/dist/sandbox/held-operations.d.ts +39 -0
  196. package/dist/sandbox/held-operations.js +119 -0
  197. package/dist/sandbox/jobs.d.ts +14 -3
  198. package/dist/sandbox/jobs.js +20 -2
  199. package/dist/sandbox/kernel-read.d.ts +55 -0
  200. package/dist/sandbox/kernel-read.js +57 -0
  201. package/dist/sandbox/legacy-retirement.d.ts +336 -0
  202. package/dist/sandbox/legacy-retirement.js +1063 -0
  203. package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
  204. package/dist/sandbox/legacy-retirement.module.js +25 -0
  205. package/dist/sandbox/managed-device-context.d.ts +94 -0
  206. package/dist/sandbox/managed-device-context.js +308 -0
  207. package/dist/sandbox/managed-device-context.module.d.ts +6 -0
  208. package/dist/sandbox/managed-device-context.module.js +33 -0
  209. package/dist/sandbox/modes.d.ts +56 -8
  210. package/dist/sandbox/modes.js +92 -8
  211. package/dist/sandbox/operation-authority-types.d.ts +8 -0
  212. package/dist/sandbox/operation-authority-types.js +32 -0
  213. package/dist/sandbox/operation-authority.d.ts +145 -0
  214. package/dist/sandbox/operation-authority.js +783 -0
  215. package/dist/sandbox/operation-authority.module.d.ts +2 -0
  216. package/dist/sandbox/operation-authority.module.js +29 -0
  217. package/dist/sandbox/operation-intents.d.ts +206 -0
  218. package/dist/sandbox/operation-intents.js +1252 -0
  219. package/dist/sandbox/operation-intents.module.d.ts +2 -0
  220. package/dist/sandbox/operation-intents.module.js +21 -0
  221. package/dist/sandbox/operation-payloads.d.ts +33 -0
  222. package/dist/sandbox/operation-payloads.js +332 -0
  223. package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
  224. package/dist/sandbox/operation-reconcile.job.js +247 -0
  225. package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
  226. package/dist/sandbox/permission-authority-epochs.js +83 -0
  227. package/dist/sandbox/permission-authority-lock.d.ts +38 -0
  228. package/dist/sandbox/permission-authority-lock.js +147 -0
  229. package/dist/sandbox/permission-authority.module.d.ts +9 -0
  230. package/dist/sandbox/permission-authority.module.js +55 -0
  231. package/dist/sandbox/permission-availability.d.ts +18 -0
  232. package/dist/sandbox/permission-availability.js +19 -0
  233. package/dist/sandbox/permission-call-grants.d.ts +34 -0
  234. package/dist/sandbox/permission-call-grants.js +349 -0
  235. package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
  236. package/dist/sandbox/permission-call-grants.module.js +21 -0
  237. package/dist/sandbox/permission-call-types.d.ts +82 -0
  238. package/dist/sandbox/permission-call-types.js +1 -0
  239. package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
  240. package/dist/sandbox/permission-ceiling-writes.js +223 -0
  241. package/dist/sandbox/permission-config-publication.d.ts +76 -0
  242. package/dist/sandbox/permission-config-publication.js +339 -0
  243. package/dist/sandbox/permission-context-types.d.ts +64 -0
  244. package/dist/sandbox/permission-context-types.js +24 -0
  245. package/dist/sandbox/permission-facts.d.ts +206 -0
  246. package/dist/sandbox/permission-facts.js +627 -0
  247. package/dist/sandbox/permission-facts.module.d.ts +2 -0
  248. package/dist/sandbox/permission-facts.module.js +20 -0
  249. package/dist/sandbox/permission-instance-writes.d.ts +90 -0
  250. package/dist/sandbox/permission-instance-writes.js +305 -0
  251. package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
  252. package/dist/sandbox/permission-runtime-reports.js +354 -0
  253. package/dist/sandbox/permission-transitions.d.ts +31 -0
  254. package/dist/sandbox/permission-transitions.js +155 -0
  255. package/dist/sandbox/platform-full-access.d.ts +128 -0
  256. package/dist/sandbox/platform-full-access.js +210 -0
  257. package/dist/sandbox/providers.d.ts +22 -0
  258. package/dist/sandbox/providers.js +10 -2
  259. package/dist/sandbox/providers.module.d.ts +2 -0
  260. package/dist/sandbox/providers.module.js +19 -0
  261. package/dist/sandbox/request-not-sent.d.ts +13 -0
  262. package/dist/sandbox/request-not-sent.js +13 -0
  263. package/dist/sandbox/review/classifier.d.ts +2 -0
  264. package/dist/sandbox/review/classifier.js +8 -0
  265. package/dist/sandbox/review/permission-candidate.d.ts +12 -0
  266. package/dist/sandbox/review/permission-candidate.js +129 -0
  267. package/dist/sandbox/review/review.service.d.ts +4 -1
  268. package/dist/sandbox/review/review.service.js +19 -5
  269. package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
  270. package/dist/sandbox/sandbox-file-reader.js +51 -7
  271. package/dist/sandbox/sandbox.module.js +26 -6
  272. package/dist/sandbox/sandbox.service.d.ts +230 -34
  273. package/dist/sandbox/sandbox.service.js +1368 -199
  274. package/dist/sandbox/unreachable.js +17 -3
  275. package/dist/sandbox/use-context.d.ts +17 -0
  276. package/dist/sandbox/use-context.js +1 -0
  277. package/dist/skills/invoke.d.ts +27 -4
  278. package/dist/skills/invoke.js +72 -7
  279. package/dist/tools/approvals.controller.d.ts +1 -0
  280. package/dist/tools/approvals.schemas.d.ts +1 -0
  281. package/dist/tools/approvals.schemas.js +3 -1
  282. package/dist/tools/approvals.service.d.ts +23 -10
  283. package/dist/tools/approvals.service.js +104 -26
  284. package/dist/tools/builtins/builtin-tools.d.ts +16 -2
  285. package/dist/tools/builtins/builtin-tools.js +38 -10
  286. package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
  287. package/dist/tools/builtins/sandbox/bash.js +201 -5
  288. package/dist/tools/builtins/sandbox/common.d.ts +92 -20
  289. package/dist/tools/builtins/sandbox/common.js +201 -17
  290. package/dist/tools/builtins/sandbox/deliver.js +2 -2
  291. package/dist/tools/builtins/sandbox/edit.js +2 -2
  292. package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
  293. package/dist/tools/builtins/sandbox/glob.js +2 -2
  294. package/dist/tools/builtins/sandbox/grep.js +2 -2
  295. package/dist/tools/builtins/sandbox/read.js +2 -2
  296. package/dist/tools/builtins/sandbox/task-list.js +7 -1
  297. package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
  298. package/dist/tools/builtins/sandbox/task-output.js +172 -0
  299. package/dist/tools/builtins/sandbox/task-stop.js +25 -3
  300. package/dist/tools/builtins/sandbox/write.js +2 -2
  301. package/dist/tools/builtins/skill-load.js +9 -6
  302. package/dist/tools/device-op-resolver.d.ts +1 -1
  303. package/dist/tools/device-op-resolver.js +13 -3
  304. package/dist/tools/permission-approval-jobs.d.ts +18 -0
  305. package/dist/tools/permission-approval-jobs.js +92 -0
  306. package/dist/tools/pipeline.d.ts +17 -2
  307. package/dist/tools/pipeline.js +300 -19
  308. package/dist/tools/registry.d.ts +9 -0
  309. package/dist/tools/tools.module.js +12 -0
  310. package/package.json +4 -3
  311. package/src/migrations/0146_permission_authority_epochs.sql +6 -0
  312. package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
  313. package/src/migrations/0148_first_message_request_hash.sql +2 -0
  314. package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
  315. package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
  316. package/src/migrations/0151_starting_execution_grants.sql +8 -0
  317. package/src/migrations/0152_background_launch_identity.sql +66 -0
  318. package/src/migrations/0153_background_cancel_requester.sql +13 -0
  319. package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
  320. package/src/migrations/0155_device_instance_generations.sql +30 -0
  321. package/src/migrations/0156_device_owner_report.sql +7 -0
  322. package/src/migrations/0157_legacy_retirement.sql +116 -0
  323. package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
  324. package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
  325. package/dist/sandbox/platform-auto-mode.d.ts +0 -63
  326. package/dist/sandbox/platform-auto-mode.js +0 -63
@@ -0,0 +1,407 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { isSandboxScopeDeniedError } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
+ import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { TransactionHost } from "../infra/database/transaction-host.js";
16
+ import { Transactional } from "../infra/database/transactional.decorator.js";
17
+ import { readOrgSettings } from "../orgs/settings.service.js";
18
+ import { SandboxLeases } from "./leases.js";
19
+ import { LegacyRetirementStore } from "./legacy-retirement.js";
20
+ import { appliedOf, cloudChosenMode, cloudSnapshotOf, coversHost, effectiveDevicePolicy, normalizeNetwork, readDeploymentDevicePolicy, readInstanceLimits, sameAppliedExactly, } from "./modes.js";
21
+ import { isExecutionMethod } from "./operation-authority-types.js";
22
+ import { PermissionAuthorityLock } from "./permission-authority-lock.js";
23
+ import { needsFullCeiling, PermissionCeilingWrites } from "./permission-ceiling-writes.js";
24
+ import { PermissionConfigPublication } from "./permission-config-publication.js";
25
+ import { PermissionFacts } from "./permission-facts.js";
26
+ import { providerForDevice, SandboxProviders } from "./providers.js";
27
+ /** How long the writer waits for the device's exclusive lifecycle lease (running commands). */
28
+ const LEASE_WAIT_MS = 120_000;
29
+ /** Devices the driver reads per page. */
30
+ const DRIVER_PAGE = 100;
31
+ const liveCloud = (db) => db
32
+ .selectFrom("devices as d")
33
+ .innerJoin("orgs as g", "g.id", "d.org_id")
34
+ .where("d.source", "=", "cloud")
35
+ .where("d.deleted_at", "is", null)
36
+ .where("g.deleted_at", "is", null);
37
+ /** Reads the cloud snapshot's progress; no lock, no lease (a report). */
38
+ export async function readCloudSnapshotProgress(db) {
39
+ const counts = await liveCloud(db)
40
+ .select((eb) => [
41
+ eb.fn.countAll().as("n"),
42
+ eb.fn.count(sql `CASE WHEN d.owner_full_access IS NULL THEN 1 END`).as("pending"),
43
+ ])
44
+ .executeTakeFirstOrThrow();
45
+ const marked = await liveCloud(db)
46
+ .select("d.id")
47
+ .where("d.permission_reconcile_required", "=", true)
48
+ .orderBy("d.id")
49
+ .execute();
50
+ return {
51
+ cloudDevices: Number(counts.n),
52
+ pending: Number(counts.pending),
53
+ reconcileRequired: marked.map((r) => r.id),
54
+ };
55
+ }
56
+ /**
57
+ * The B1 cloud per-device authority writer: replaces the old daily mode of a cloud device by an
58
+ * explicit owner Full ceiling and outer network, computed from the device's OLD effective
59
+ * authority (platform switch with its configured / stored precedence, the org's switch and cloud
60
+ * network, the device's narrowing switch, `egress: none`), narrowed by what its instance is known
61
+ * to run, never widened. Each device: the exclusive lifecycle lease outside the transaction, then
62
+ * the device authority write lock (platform -> org -> device order) before the row locks. Written
63
+ * once: a snapshot is never recomputed (a later false stays explicit after a widening). A device
64
+ * whose applied limits are not exactly the desired ones keeps a durable marker that blocks
65
+ * admission ({@link PermissionFacts.assertCloudReconciled}) until {@link reconcile} finds them
66
+ * established: after a file reset (the next create applies them exactly), or once a provider
67
+ * `update` under the lifecycle lease applied the reconcile target (B-12,
68
+ * `SandboxService.reconcileLimits`). Reconciling keeps any stricter boundary the instance is
69
+ * known to run by intersection: the owner ceiling and outer network are narrowed to it (a real
70
+ * narrowing, published like the snapshot's), never the instance widened to the authority.
71
+ */
72
+ let CloudPermissionSnapshots = class CloudPermissionSnapshots {
73
+ db;
74
+ txHost;
75
+ leases;
76
+ locks;
77
+ config;
78
+ facts;
79
+ publication;
80
+ ceilings;
81
+ retirement;
82
+ providers;
83
+ constructor(db, txHost, leases, locks, config, facts, publication, ceilings, retirement,
84
+ /** Whether a device's provider fixes limits at its file system (B-12 intersection). */
85
+ providers) {
86
+ this.db = db;
87
+ this.txHost = txHost;
88
+ this.leases = leases;
89
+ this.locks = locks;
90
+ this.config = config;
91
+ this.facts = facts;
92
+ this.publication = publication;
93
+ this.ceilings = ceilings;
94
+ this.retirement = retirement;
95
+ this.providers = providers;
96
+ }
97
+ /**
98
+ * The production driver (B-10, `capybara permissions cutover snapshot`): snapshots every live
99
+ * cloud device that has none yet, one device at a time, each under its exclusive lifecycle
100
+ * lease and in its own transaction ({@link snapshot}).
101
+ *
102
+ * - **Barrier.** Refuses unless legacy admission is closed (the freeze published and enumerated,
103
+ * {@link LegacyRetirementStore.assertCutoverBarrier}) and this replica's permission
104
+ * configuration is the published one; each device re-checks the latter under the platform
105
+ * lock, and a failure there stops the run.
106
+ * - **Idempotent.** Only devices without a snapshot are visited, and {@link snapshot} keeps an
107
+ * existing one under the row lock, so a rerun takes no lease and publishes nothing.
108
+ * - **Resumable.** A device's snapshot, its narrowing publication (epoch, Full consent reset,
109
+ * exact revocation) and its marker commit together or not at all; a crash or a failed device
110
+ * leaves it without a snapshot for the next run, never half written or published twice.
111
+ * - Devices whose applied limits are not established keep `permission_reconcile_required`
112
+ * (listed in the answer) until a file reset reconciles them.
113
+ */
114
+ async snapshotAll(opts = {}) {
115
+ await this.retirement.assertCutoverBarrier();
116
+ await this.publication.assertCurrent();
117
+ const results = [];
118
+ const failed = [];
119
+ let after = "";
120
+ for (;;) {
121
+ opts.signal?.throwIfAborted();
122
+ const page = await liveCloud(this.db)
123
+ .select(["d.id", "d.org_id"])
124
+ .where("d.owner_full_access", "is", null)
125
+ .where(sql `d.id COLLATE "C" > ${after}`)
126
+ .orderBy(sql `d.id COLLATE "C"`)
127
+ .limit(DRIVER_PAGE)
128
+ .execute();
129
+ for (const d of page) {
130
+ opts.signal?.throwIfAborted();
131
+ const wait = AbortSignal.timeout(opts.leaseWaitMs ?? LEASE_WAIT_MS);
132
+ const signal = opts.signal ? AbortSignal.any([opts.signal, wait]) : wait;
133
+ try {
134
+ const outcome = await this.snapshot(d.org_id, d.id, signal);
135
+ results.push({ deviceId: d.id, orgId: d.org_id, ...outcome });
136
+ }
137
+ catch (e) {
138
+ // a replica that is not (or no longer) current stops the whole run; the caller's abort too
139
+ if (isSandboxScopeDeniedError(e) || opts.signal?.aborted)
140
+ throw e;
141
+ failed.push({
142
+ deviceId: d.id,
143
+ orgId: d.org_id,
144
+ error: e instanceof Error ? e.message : String(e),
145
+ });
146
+ }
147
+ }
148
+ if (page.length < DRIVER_PAGE)
149
+ break;
150
+ after = page.at(-1).id;
151
+ }
152
+ const progress = await readCloudSnapshotProgress(this.db);
153
+ return {
154
+ results,
155
+ failed,
156
+ pending: progress.pending,
157
+ reconcileRequired: progress.reconcileRequired,
158
+ };
159
+ }
160
+ /** Snapshots one device under its exclusive lifecycle lease. */
161
+ async snapshot(orgId, deviceId, signal = AbortSignal.timeout(LEASE_WAIT_MS)) {
162
+ return this.underLease(deviceId, signal, () => this.snapshotLocked(orgId, deviceId));
163
+ }
164
+ /** Re-checks a device carrying the marker; clears it once its limits are established. */
165
+ async reconcile(orgId, deviceId, signal = AbortSignal.timeout(LEASE_WAIT_MS)) {
166
+ return this.underLease(deviceId, signal, () => this.reconcileLocked(orgId, deviceId));
167
+ }
168
+ /**
169
+ * {@link reconcile} for a caller that already holds the device's exclusive lifecycle lease
170
+ * (`SandboxService.reconcileLimits`): the same transaction, no lease taken here.
171
+ */
172
+ async reconcileHeld(orgId, deviceId) {
173
+ return this.txHost.run(() => this.reconcileLocked(orgId, deviceId), {
174
+ propagation: "requires_new",
175
+ });
176
+ }
177
+ /** {@link reconcile} by device id alone (after a file reset); nothing for an unknown device. */
178
+ async reconcileDevice(deviceId) {
179
+ const row = await this.db
180
+ .selectFrom("devices")
181
+ .select(["org_id", "permission_reconcile_required"])
182
+ .where("id", "=", deviceId)
183
+ .executeTakeFirst();
184
+ if (!row?.permission_reconcile_required)
185
+ return { state: "existing" };
186
+ return this.reconcile(row.org_id, deviceId);
187
+ }
188
+ async underLease(deviceId, signal, fn) {
189
+ // the lease is a distributed lock: taken outside the transaction, released after the commit
190
+ const lease = await this.leases.acquireExclusive(deviceId, signal, undefined, {
191
+ intent: true,
192
+ });
193
+ try {
194
+ return await this.txHost.run(fn, { propagation: "requires_new" });
195
+ }
196
+ finally {
197
+ await lease.release();
198
+ }
199
+ }
200
+ async snapshotLocked(orgId, deviceId) {
201
+ const device = await this.lockedDevice(orgId, deviceId);
202
+ if (device === undefined)
203
+ return { state: "skipped" };
204
+ if (device.owner_full_access !== null)
205
+ return { state: "existing" };
206
+ // under the platform shared lock: proves this replica reads the converted (current) inputs
207
+ await this.publication.assertCurrent();
208
+ const [deployment, settings] = await Promise.all([
209
+ readDeploymentDevicePolicy(this.db.db, this.config),
210
+ readOrgSettings(this.db.db, orgId),
211
+ ]);
212
+ // the OLD algorithm on the old inputs: the snapshot columns are still empty here
213
+ const old = effectiveDevicePolicy(deployment, settings, cloudChosenMode(device));
214
+ const instance = await this.lockedInstance(deviceId);
215
+ const rec = instance === null ? null : readInstanceLimits(instance.instance_limits);
216
+ // what the instance really runs narrows the snapshot even when a newer value is pending
217
+ const known = rec?.applied ?? null;
218
+ const snap = cloudSnapshotOf(old, known);
219
+ const desired = this.desired(snap.fullAccess, snap.outerNetwork);
220
+ const state = instance === null
221
+ ? "unprobed"
222
+ : rec?.unapplied === null && sameAppliedExactly(known, desired)
223
+ ? "bound"
224
+ : "reconcile-required";
225
+ await this.db
226
+ .updateTable("devices")
227
+ .set({
228
+ owner_full_access: snap.fullAccess,
229
+ outer_network: JSON.stringify(snap.outerNetwork),
230
+ permission_migration: JSON.stringify({
231
+ from: "auto-mode",
232
+ old: { mode: old.mode, network: old.network },
233
+ instance: instance === null ? null : { generation: instance.generation, applied: known, state },
234
+ }),
235
+ permission_reconcile_required: state === "reconcile-required",
236
+ })
237
+ .where("id", "=", deviceId)
238
+ .execute();
239
+ // A snapshot narrowed by what the instance really runs changes the device's authority: it
240
+ // goes through the device ceiling writer (epoch, Full consent, exact revocation) in this
241
+ // transaction, under the device write lock already held.
242
+ const fullNarrowed = old.mode === "auto" && !snap.fullAccess;
243
+ const networkNarrowed = JSON.stringify(normalizeNetwork(old.network)) !== JSON.stringify(snap.outerNetwork);
244
+ if (fullNarrowed || networkNarrowed)
245
+ await this.publishNarrowing(orgId, deviceId, snap, fullNarrowed);
246
+ return state === "reconcile-required" ? { state, action: "reset-files" } : { state };
247
+ }
248
+ /**
249
+ * A narrowed owner ceiling or outer network changes the device's authority: it goes through the
250
+ * device ceiling writer (epoch, Full consent, exact revocation) in the caller's transaction,
251
+ * under the device write lock already held.
252
+ */
253
+ async publishNarrowing(orgId, deviceId, snap, fullNarrowed) {
254
+ const outer = snap.outerNetwork;
255
+ await this.ceilings.publishLocked({ orgId, deviceId }, "device", (scope, row) => {
256
+ if (needsFullCeiling(scope))
257
+ return !snap.fullAccess;
258
+ if (outer.kind !== "allowlist" || !("network" in scope) || !isExecutionMethod(row.method))
259
+ return false;
260
+ // an execution outside any allowlist (environment networking) is wider than the outer
261
+ // allowlist; `none` is narrower; an allowlist must be covered host by host
262
+ if (scope.network.kind === "environment")
263
+ return true;
264
+ if (scope.network.kind !== "allowlist")
265
+ return false;
266
+ return scope.network.hosts.some((h) => !outer.hosts.some((p) => coversHost(p, h)));
267
+ }, fullNarrowed);
268
+ }
269
+ /**
270
+ * Re-checks a marked device under its write lock. With an instance whose applied limits are
271
+ * known (in force, even with a newer value pending a reset), the device's authority is first
272
+ * narrowed to them by intersection (B-12): Full only where the instance runs auto, the outer
273
+ * network cut to the applied network; a real narrowing is published. Then the marker clears
274
+ * when the applied limits are exactly the (narrowed) effective ones with nothing pending;
275
+ * otherwise it stays, with the target that would establish them: the effective limits, which
276
+ * are now never wider than the instance in any dimension, so applying them only narrows.
277
+ */
278
+ async reconcileLocked(orgId, deviceId) {
279
+ const device = await this.lockedDevice(orgId, deviceId);
280
+ if (device === undefined)
281
+ return { state: "skipped" };
282
+ if (!device.permission_reconcile_required)
283
+ return { state: "existing" };
284
+ const instance = await this.lockedInstance(deviceId);
285
+ let state = "unprobed";
286
+ let target;
287
+ if (instance !== null) {
288
+ const rec = readInstanceLimits(instance.instance_limits);
289
+ // only a record in force narrows: a live instance's, or the file system's of a provider
290
+ // that fixes limits there; a destroyed instance's record is stale (the next create applies
291
+ // the desired limits)
292
+ const inForce = (instance.handle !== null &&
293
+ (instance.status === "running" || instance.status === "suspended")) ||
294
+ providerForDevice(this.providers, device.provider)?.impl.limitsApplyAt === "fileSystem";
295
+ if (inForce && rec.applied !== null && device.owner_full_access !== null) {
296
+ const outer = device.outer_network ?? { kind: "open-public", hosts: [] };
297
+ const narrowed = cloudSnapshotOf({ mode: device.owner_full_access ? "auto" : "sandbox", network: outer }, rec.applied);
298
+ const fullNarrowed = device.owner_full_access && !narrowed.fullAccess;
299
+ const networkNarrowed = JSON.stringify(normalizeNetwork(outer)) !== JSON.stringify(narrowed.outerNetwork);
300
+ if (fullNarrowed || networkNarrowed) {
301
+ await this.db
302
+ .updateTable("devices")
303
+ .set({
304
+ owner_full_access: narrowed.fullAccess,
305
+ outer_network: JSON.stringify(narrowed.outerNetwork),
306
+ })
307
+ .where("id", "=", deviceId)
308
+ .execute();
309
+ await this.publishNarrowing(orgId, deviceId, narrowed, fullNarrowed);
310
+ }
311
+ }
312
+ // what the instance must run with now: the snapshot as the current effective policy
313
+ const policy = await this.facts.devicePolicy({ orgId, deviceId });
314
+ const effective = appliedOf({ mode: policy.mode, network: policy.network });
315
+ const known = rec.unapplied !== null ? null : rec.applied;
316
+ state = sameAppliedExactly(known, effective) ? "bound" : "reconcile-required";
317
+ target = effective;
318
+ }
319
+ if (state !== "reconcile-required")
320
+ await this.db
321
+ .updateTable("devices")
322
+ .set({ permission_reconcile_required: false })
323
+ .where("id", "=", deviceId)
324
+ .execute();
325
+ return state === "reconcile-required"
326
+ ? { state, action: "reset-files", ...(target !== undefined && { target }) }
327
+ : { state };
328
+ }
329
+ desired(fullAccess, outer) {
330
+ return { mode: fullAccess ? "auto" : "sandbox", network: outer };
331
+ }
332
+ /**
333
+ * The device row under the device authority write lock, or undefined (not a live cloud one). The
334
+ * row is locked first (`FOR NO KEY UPDATE`: only non-key columns change), then the permission
335
+ * lock, the order the device writers take (`DevicesService.lockOwn`, the device project writes),
336
+ * then the row is read again under both.
337
+ */
338
+ async lockedDevice(orgId, deviceId) {
339
+ const exists = await this.db
340
+ .selectFrom("devices")
341
+ .select("org_id")
342
+ .where("id", "=", deviceId)
343
+ .where("org_id", "=", orgId)
344
+ .forNoKeyUpdate()
345
+ .executeTakeFirst();
346
+ if (exists === undefined)
347
+ return undefined;
348
+ await this.locks.acquire({ orgId, deviceId }, { kind: "write", level: "device" });
349
+ const device = await this.db
350
+ .selectFrom("devices")
351
+ .select([
352
+ "source",
353
+ "provider",
354
+ "mode",
355
+ "owner_full_access",
356
+ "outer_network",
357
+ "permission_reconcile_required",
358
+ "deleted_at",
359
+ ])
360
+ .where("id", "=", deviceId)
361
+ .where("org_id", "=", orgId)
362
+ .forNoKeyUpdate()
363
+ .executeTakeFirst();
364
+ if (device === undefined || device.deleted_at !== null || device.source !== "cloud")
365
+ return undefined;
366
+ return device;
367
+ }
368
+ /**
369
+ * The device's instance row when an instance or a file system exists (their limits are in
370
+ * force); null when neither does (the next create applies the desired limits exactly).
371
+ */
372
+ async lockedInstance(deviceId) {
373
+ const row = await this.db
374
+ .selectFrom("device_instances")
375
+ .select(["handle", "status", "fs_status", "instance_limits", "generation"])
376
+ .where("device_id", "=", deviceId)
377
+ .forUpdate()
378
+ .executeTakeFirst();
379
+ if (row === undefined)
380
+ return null;
381
+ // a create that may have acted (creating, even without a handle yet) or any file system left
382
+ // counts: its limits are not established
383
+ const live = row.status === "creating" ||
384
+ (row.handle !== null && (row.status === "running" || row.status === "suspended"));
385
+ return live || row.fs_status !== "none" ? row : null;
386
+ }
387
+ };
388
+ __decorate([
389
+ Transactional({ propagation: "mandatory" })
390
+ ], CloudPermissionSnapshots.prototype, "snapshotLocked", null);
391
+ __decorate([
392
+ Transactional({ propagation: "mandatory" })
393
+ ], CloudPermissionSnapshots.prototype, "reconcileLocked", null);
394
+ CloudPermissionSnapshots = __decorate([
395
+ Injectable(),
396
+ __param(0, Inject(KernelDb)),
397
+ __param(1, Inject(TransactionHost)),
398
+ __param(2, Inject(SandboxLeases)),
399
+ __param(3, Inject(PermissionAuthorityLock)),
400
+ __param(4, Inject(KernelConfigService)),
401
+ __param(5, Inject(PermissionFacts)),
402
+ __param(6, Inject(PermissionConfigPublication)),
403
+ __param(7, Inject(PermissionCeilingWrites)),
404
+ __param(8, Inject(LegacyRetirementStore)),
405
+ __param(9, Inject(SandboxProviders))
406
+ ], CloudPermissionSnapshots);
407
+ export { CloudPermissionSnapshots };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The cloud snapshot writer (permission runtime cutover B1) and its driver (B-10), with the
3
+ * sandbox leases it takes: the one {@link SandboxLeases} of the application (the sandbox service
4
+ * uses it through {@link SandboxModule}'s import). Small enough for a CLI context
5
+ * (`capybara permissions cutover snapshot`), which has Redis but no extension host.
6
+ */
7
+ export declare class CloudPermissionSnapshotsModule {
8
+ }
@@ -0,0 +1,34 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from "@nestjs/common";
8
+ import { CloudPermissionSnapshots } from "./cloud-permission-snapshot.js";
9
+ import { SandboxLeases } from "./leases.js";
10
+ import { LegacyRetirementModule } from "./legacy-retirement.module.js";
11
+ import { PermissionAuthorityModule } from "./permission-authority.module.js";
12
+ import { PermissionFactsModule } from "./permission-facts.module.js";
13
+ import { SandboxProviderRegistryModule } from "./providers.module.js";
14
+ /**
15
+ * The cloud snapshot writer (permission runtime cutover B1) and its driver (B-10), with the
16
+ * sandbox leases it takes: the one {@link SandboxLeases} of the application (the sandbox service
17
+ * uses it through {@link SandboxModule}'s import). Small enough for a CLI context
18
+ * (`capybara permissions cutover snapshot`), which has Redis but no extension host.
19
+ */
20
+ let CloudPermissionSnapshotsModule = class CloudPermissionSnapshotsModule {
21
+ };
22
+ CloudPermissionSnapshotsModule = __decorate([
23
+ Module({
24
+ imports: [
25
+ PermissionAuthorityModule,
26
+ PermissionFactsModule,
27
+ LegacyRetirementModule,
28
+ SandboxProviderRegistryModule,
29
+ ],
30
+ providers: [SandboxLeases, CloudPermissionSnapshots],
31
+ exports: [SandboxLeases, CloudPermissionSnapshots],
32
+ })
33
+ ], CloudPermissionSnapshotsModule);
34
+ export { CloudPermissionSnapshotsModule };
@@ -0,0 +1,39 @@
1
+ import { type ExecResult, type SandboxExecOptions, type SandboxExecutionRef, type SandboxHandle, type SandboxOperationScope, type SandboxProvider } from "@capybara-hq/plugin-sdk";
2
+ /** A callback can use native operations; it cannot obtain a new authority or change lifecycle. */
3
+ export type HeldProvider = Pick<SandboxProvider, "readFile" | "writeFile" | "stat" | "list" | "scan"> & {
4
+ exec(h: SandboxHandle, args: Omit<Parameters<SandboxProvider["exec"]>[1], "tag" | "actor">): Promise<ExecResult>;
5
+ /**
6
+ * A managed background start (dormant until the paired activation): admitted, persisted and
7
+ * acknowledged by the service under the same stable operation identity. Present only on the
8
+ * operation-held provider; the protocol-2 adapter has none.
9
+ */
10
+ backgroundStart?(h: SandboxHandle, args: ManagedStartArgs): Promise<SandboxExecutionRef>;
11
+ };
12
+ /** A managed start's input: hashed as the stable start input (without the signal). */
13
+ export type ManagedStartArgs = SandboxExecOptions & {
14
+ /** The trusted working root; the artifact is placed under it. */
15
+ cwd: string;
16
+ taskId: string;
17
+ outputPath: string;
18
+ retainUntilMs: number;
19
+ };
20
+ export type NativeMethod = "exec" | "readFile" | "writeFile" | "stat" | "list" | "scan";
21
+ export type OperationMethod = NativeMethod | "backgroundStart";
22
+ /** The service admits and claims durably before invoking this closure inline under its lease. */
23
+ export type OperationDispatch = <T>(method: OperationMethod, input: unknown, invoke: (scope: SandboxOperationScope, signal: AbortSignal) => Promise<T>,
24
+ /**
25
+ * Kernel checks on the admitted scope that run before any dispatch state is written; a typed
26
+ * refusal here is recorded as a pre-effect failure and nothing is dispatched.
27
+ */
28
+ preflight?: (scope: SandboxOperationScope, signal: AbortSignal) => Promise<void>) => Promise<T>;
29
+ /** The provider's runtime must enforce the scope's profile (and own background executions). */
30
+ export declare function assertPermissionSupport(provider: SandboxProvider, handle: SandboxHandle, scope: SandboxOperationScope, method: OperationMethod, signal: AbortSignal): Promise<void>;
31
+ /**
32
+ * Every check a managed start needs before it may reach the provider, for the first dispatch and
33
+ * for a same-identity recovery alike: the artifact is covered by the admitted starting authority,
34
+ * then the runtime supports the profile and owns background executions.
35
+ */
36
+ export declare function checkManagedStart(provider: SandboxProvider, handle: SandboxHandle, scope: SandboxOperationScope, input: Omit<ManagedStartArgs, "signal">, signal: AbortSignal): Promise<void>;
37
+ export declare function createHeldOperations(provider: SandboxProvider, handle: SandboxHandle, heldSignal: AbortSignal, dispatch: OperationDispatch): HeldProvider;
38
+ /** Temporary v2 callback adapter. Removed with the coordinated Task 8 cutover. */
39
+ export declare function createLegacyHeldProvider(provider: SandboxProvider, tag: string, actor: Parameters<SandboxProvider["exec"]>[1]["actor"], before: () => Promise<void>): HeldProvider;
@@ -0,0 +1,119 @@
1
+ import { SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
2
+ import { assertManagedArtifactAdmitted } from "../background/launch.js";
3
+ /** The provider's runtime must enforce the scope's profile (and own background executions). */
4
+ export async function assertPermissionSupport(provider, handle, scope, method, signal) {
5
+ if (!provider.operation || !provider.permissionSupport || !provider.revokeOperation)
6
+ throw new SandboxPermissionUnsupportedError("This provider does not support permission operations");
7
+ const support = await provider.permissionSupport(handle, signal);
8
+ if (support.version !== 1 ||
9
+ (method === "backgroundStart" && (!support.background || !provider.background)) ||
10
+ (scope.profile === "full-access"
11
+ ? !support.fullAccess
12
+ : !support.restricted?.filesystem ||
13
+ !support.restricted.network ||
14
+ !support.restricted.native ||
15
+ !support.restricted.concurrentScopes))
16
+ throw new SandboxPermissionUnsupportedError(support.unavailableReason ?? "This runtime cannot enforce the selected permissions");
17
+ }
18
+ /**
19
+ * Every check a managed start needs before it may reach the provider, for the first dispatch and
20
+ * for a same-identity recovery alike: the artifact is covered by the admitted starting authority,
21
+ * then the runtime supports the profile and owns background executions.
22
+ */
23
+ export async function checkManagedStart(provider, handle, scope, input, signal) {
24
+ assertManagedArtifactAdmitted(scope, input);
25
+ await assertPermissionSupport(provider, handle, scope, "backgroundStart", signal);
26
+ }
27
+ export function createHeldOperations(provider, handle, heldSignal, dispatch) {
28
+ const call = (h, method, input, signal, invoke, preflight) => {
29
+ if (h.id !== handle.id)
30
+ throw new SandboxScopeDeniedError("Use the currently held instance");
31
+ const combined = signal === heldSignal ? signal : AbortSignal.any([signal, heldSignal]);
32
+ combined.throwIfAborted();
33
+ return dispatch(method, input, async (scope, admittedSignal) => {
34
+ const sig = admittedSignal === combined ? combined : AbortSignal.any([combined, admittedSignal]);
35
+ sig.throwIfAborted();
36
+ await assertPermissionSupport(provider, handle, scope, method, sig);
37
+ sig.throwIfAborted();
38
+ // A background start has no operation object: the provider owns it by exact identity.
39
+ if (method === "backgroundStart")
40
+ return invoke(null, sig, scope);
41
+ const op = await provider.operation(handle, scope, sig);
42
+ return invoke(op, sig, scope);
43
+ }, preflight && ((scope, sig) => preflight(scope, AbortSignal.any([combined, sig]))));
44
+ };
45
+ const native = (op) => {
46
+ if (!op)
47
+ throw new SandboxPermissionUnsupportedError("Native operation is unavailable");
48
+ return op;
49
+ };
50
+ return {
51
+ exec(h, args) {
52
+ const { signal, ...given } = args;
53
+ const input = structuredClone(given);
54
+ return call(h, "exec", input, signal, (op, sig) => native(op).exec({ ...input, signal: sig }));
55
+ },
56
+ readFile(h, path, opts) {
57
+ const { maxBytes, signal } = opts;
58
+ return call(h, "readFile", { path, maxBytes }, signal, (op, sig) => native(op).readFile(path, { maxBytes, signal: sig }));
59
+ },
60
+ writeFile(h, path, data, signal) {
61
+ const copy = new Uint8Array(data);
62
+ return call(h, "writeFile", { path, data: copy }, signal, (op, sig) => native(op).writeFile(path, copy, sig));
63
+ },
64
+ stat(h, path, signal) {
65
+ return call(h, "stat", { path }, signal, (op, sig) => native(op).stat(path, sig));
66
+ },
67
+ ...(provider.list && provider.scan
68
+ ? {
69
+ list: (h, path, opts) => {
70
+ const { limit, signal } = opts;
71
+ return call(h, "list", { path, limit }, signal, (o, sig) => {
72
+ const op = native(o);
73
+ if (!op.list)
74
+ throw new SandboxPermissionUnsupportedError("Native listing is unavailable");
75
+ return op.list(path, { limit, signal: sig });
76
+ });
77
+ },
78
+ scan: (h, base, opts) => call(h, "scan", { base }, opts.signal, (o, sig) => {
79
+ const op = native(o);
80
+ if (!op.scan)
81
+ throw new SandboxPermissionUnsupportedError("Native scanning is unavailable");
82
+ return op.scan(base, { signal: sig });
83
+ }),
84
+ }
85
+ : {}),
86
+ // Only a provider with exact background ownership offers a start; none falls back to exec.
87
+ ...(provider.background
88
+ ? {
89
+ backgroundStart: (h, args) => {
90
+ const { signal, ...given } = args;
91
+ const input = structuredClone(given);
92
+ return call(h, "backgroundStart", input, signal, (_op, sig, scope) => {
93
+ const background = provider.background;
94
+ if (!background)
95
+ throw new SandboxPermissionUnsupportedError("Managed background tasks are unavailable");
96
+ return background.start(handle, scope, { ...input, signal: sig });
97
+ },
98
+ // Before any dispatch state: the artifact must already be covered by the admitted
99
+ // starting authority, and the runtime must own background executions.
100
+ (scope, sig) => checkManagedStart(provider, handle, scope, input, sig));
101
+ },
102
+ }
103
+ : {}),
104
+ };
105
+ }
106
+ /** Temporary v2 callback adapter. Removed with the coordinated Task 8 cutover. */
107
+ export function createLegacyHeldProvider(provider, tag, actor, before) {
108
+ return {
109
+ exec: async (h, args) => {
110
+ await before();
111
+ return provider.exec(h, { ...args, tag, actor });
112
+ },
113
+ readFile: provider.readFile.bind(provider),
114
+ writeFile: provider.writeFile.bind(provider),
115
+ stat: provider.stat.bind(provider),
116
+ ...(provider.list ? { list: provider.list.bind(provider) } : {}),
117
+ ...(provider.scan ? { scan: provider.scan.bind(provider) } : {}),
118
+ };
119
+ }
@@ -2,9 +2,15 @@ import type { Job, Queue } from "bullmq";
2
2
  import { LockService } from "../infra/lock/lock.service.js";
3
3
  import type { OutboxService } from "../infra/outbox/outbox.service.js";
4
4
  import type { KernelLogger } from "../log.js";
5
+ import type { CloudPermissionSnapshots } from "./cloud-permission-snapshot.js";
5
6
  import { SandboxService } from "./sandbox.service.js";
6
7
  /** The idle suspension sweep (every minute, once per tick across replicas). */
7
8
  export declare const SANDBOX_SUSPEND_JOB = "sandbox-suspend-idle";
9
+ /**
10
+ * The lifecycle reconcile of cloud devices carrying the reconcile marker through their provider's
11
+ * `update` (permission activation B-12; every minute, once per tick across replicas).
12
+ */
13
+ export declare const SANDBOX_RECONCILE_JOB = "sandbox-reconcile-limits";
8
14
  /** The inactivity destruction sweep (hourly, once per tick across replicas). */
9
15
  export declare const SANDBOX_DESTROY_JOB = "sandbox-destroy-inactive";
10
16
  /**
@@ -55,7 +61,9 @@ export declare class SandboxJobs {
55
61
  * The worker side of {@link SANDBOX_RESET_FILES_JOB}: `resetFileSystem` under the exclusive lease;
56
62
  * a failure fails the job (retried).
57
63
  */
58
- export declare function runSandboxResetFiles(sandbox: Pick<SandboxService, "resetFileSystem">, job: Pick<Job, "data">): Promise<void>;
64
+ export declare function runSandboxResetFiles(sandbox: Pick<SandboxService, "resetFileSystem">, job: Pick<Job, "data">,
65
+ /** B1: a reset establishes the device's exact limits; clears its reconciliation marker. */
66
+ snapshots?: Pick<CloudPermissionSnapshots, "reconcileDevice">): Promise<void>;
59
67
  /**
60
68
  * The worker side of {@link SANDBOX_DESTROY_FOR_JOB}: `destroyDevice` one by one; a failure is
61
69
  * warned and fails the job (the whole batch is retried) after the others were destroyed.
@@ -64,7 +72,9 @@ export declare function runSandboxDestroyFor(sandbox: Pick<SandboxService, "dest
64
72
  /**
65
73
  * The sandbox sweeps (exactly once per tick across replicas): every minute the idle and overdue
66
74
  * running instances are suspended, every hour the inactive instances are destroyed (files kept)
67
- * and deleted devices, or those of deleted orgs, are destroyed with their files. Both do nothing without a sandbox provider. They replace the
75
+ * and deleted devices, or those of deleted orgs, are destroyed with their files. Every minute,
76
+ * too, cloud devices whose limits must be established again get them through their provider's
77
+ * `update` when it has one (B-12). All do nothing without a sandbox provider. They replace the
68
78
  * maintenance schedulers `sandbox-suspend-idle-every-minute` and `sandbox-destroy-inactive-hourly`
69
79
  * (retired at worker start).
70
80
  */
@@ -72,7 +82,8 @@ export declare class SandboxSweepJobs {
72
82
  private readonly sandbox;
73
83
  readonly lockService: LockService;
74
84
  readonly log: KernelLogger;
75
- constructor(sandbox: Pick<SandboxService, "suspendIdle" | "destroyInactive">, lockService: LockService, log: KernelLogger);
85
+ constructor(sandbox: Pick<SandboxService, "suspendIdle" | "destroyInactive" | "reconcileMarked">, lockService: LockService, log: KernelLogger);
76
86
  suspendIdle(): Promise<void>;
87
+ reconcileLimits(): Promise<void>;
77
88
  destroyInactive(): Promise<void>;
78
89
  }