@capybara-hq/kernel 0.1.0-rc.41 → 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 +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 +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
@@ -8,12 +8,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { DeviceProtocolError, FileSystemGoneError, parseDeviceFrame, parseOpResult, SandboxGoneError, ToolError, } from "@capybara-hq/plugin-sdk";
11
+ import { DEVICE_PROTOCOL_VERSION, DeviceProtocolError, FileSystemGoneError, parseDeviceFrame, parseDeviceFrameV3, parseOperationResultV3, parseOpResult, SandboxGoneError, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, STAGED_DEVICE_PROTOCOL_VERSION, ToolError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
15
  import { LockService } from "../infra/lock/lock.service.js";
16
16
  import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
17
+ import { DeviceRequestNotSentError, isDeviceRequestNotSent } from "../sandbox/request-not-sent.js";
17
18
  import { deviceNotFound } from "../sandbox/sandbox.service.js";
18
19
  import { deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, } from "./keys.js";
19
20
  import { DeviceTargets } from "./targets.js";
@@ -28,6 +29,43 @@ export const machineRevoked = () => new ApiError("device.forbidden", "The machin
28
29
  export const POLICY_REFUSAL_PREFIX = "Refused by the machine's local policy: ";
29
30
  /** The text a machine's `error` result reaches the model with (ruling R28). */
30
31
  export const ON_MACHINE_PREFIX = "On the connected machine: ";
32
+ /**
33
+ * The text of a staged (protocol 3) request refused because the machine's connection changed.
34
+ * Only an output read has an offset to retry from; every other operation is simply retried.
35
+ */
36
+ export const connectionChangedMessage = (op) => op === "backgroundReadOutput"
37
+ ? "The machine's connection changed during the read; retry the read from the same offset"
38
+ : `The machine's connection changed before ${op} was sent; retry the operation`;
39
+ export { DeviceRequestNotSentError, isDeviceRequestNotSent };
40
+ /**
41
+ * The operations held under a stable operation identity (native, preparation and browsing
42
+ * operations, execution, a background start and an operation revoke): their not-sent refusal is
43
+ * typed ({@link DeviceRequestNotSentError}) so the operation path records it as definite. Exact
44
+ * status, tail, stop and reads, the policy controls and binding keep their plain errors.
45
+ */
46
+ const heldOperation = (op) => op === "backgroundStart" ||
47
+ op === "revokeOperation" ||
48
+ /^(?:exec|readFile|writeFile|stat|list|scan|prepare(?:ReadFile|WriteFile|Stat)|browse(?:Stat|List|Scan))$/.test(op);
49
+ /**
50
+ * Whether a staged operation's result is fenced to the connection its request was sent on.
51
+ * Protocol 3 (spec B5) fences every request to its connection, so an old capacity is never used on
52
+ * a replacement socket. For results, only an output read is fenced: its range was sized for the
53
+ * old connection's capacity and an in-flight read that meets a reconnect fails so the reader
54
+ * retries from the same offset. Every other operation keeps protocol 2's grace semantics: the
55
+ * machine keeps it running across a socket blip and its result, validated by the gateway against
56
+ * the capacity of the connection it arrived on, is accepted after a reconnect within the grace.
57
+ */
58
+ const connectionFenced = (op) => op === "backgroundReadOutput";
59
+ /**
60
+ * The kernel-internal field of a queued `stop` naming the machine it is for (stripped by the holder
61
+ * before the frame goes out; a frame for another machine is dropped).
62
+ */
63
+ export const STOP_MACHINE = "machineId";
64
+ /**
65
+ * Whether the deployment speaks the staged device protocol: the single gate is the SDK's protocol
66
+ * constant (flipped to 3 at the paired activation). Until then the active wire stays protocol 2.
67
+ */
68
+ export const stagedDeviceProtocolActive = () => DEVICE_PROTOCOL_VERSION === STAGED_DEVICE_PROTOCOL_VERSION;
31
69
  /** The longest one lease check of a waiting caller may take before it counts as "unknown". */
32
70
  export const LEASE_CHECK_TIMEOUT_MS = 2000;
33
71
  /** How often a waiting caller checks that a replica still holds the machine's connection. */
@@ -67,6 +105,27 @@ return 1
67
105
  /** Why a call stopped waiting without a result. */
68
106
  const ABORTED = Symbol("aborted");
69
107
  const GRACE_EXPIRED = Symbol("grace expired");
108
+ /**
109
+ * The kernel-internal fields the gateway adds to what it stores for a staged result, next to the
110
+ * device's frame: the connection it arrived on, that connection's capacity and, only on the
111
+ * gateway's own refusal of a request queued for another connection, {@link GATEWAY_NOT_SENT}. The
112
+ * device's frame is parsed strictly (unknown keys refused), so a device can never set them.
113
+ */
114
+ export const GATEWAY_NOT_SENT = "notSent";
115
+ /**
116
+ * A staged request refused because it was not sent, outside the operations held under an operation
117
+ * identity (a policy control, a status read): a protocol error that also says nothing ran, so a
118
+ * caller can record it as never received instead of unknown ({@link wasDeviceRequestNotSent}).
119
+ */
120
+ export class DeviceRequestNotSentProtocolError extends DeviceProtocolError {
121
+ notSent = true;
122
+ }
123
+ /** Any staged request the kernel knows was never sent to the machine (held or not). */
124
+ export const wasDeviceRequestNotSent = (e) => e instanceof Error && e.notSent === true;
125
+ /** The not-sent refusal of `op`: typed for held operations, a not-sent protocol error otherwise. */
126
+ const notSentError = (op) => heldOperation(op)
127
+ ? new DeviceRequestNotSentError(connectionChangedMessage(op))
128
+ : new DeviceRequestNotSentProtocolError(connectionChangedMessage(op));
70
129
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
71
130
  /**
72
131
  * The caller side of the device relay (environments spec §13.4). A request goes onto the
@@ -110,14 +169,49 @@ let LocalDeviceRelay = class LocalDeviceRelay {
110
169
  return (await this.locks.holderOf(deviceLeaseKey(deviceId))) !== null;
111
170
  }
112
171
  /**
113
- * Queues `op` for the machine without waiting for an answer (ruling R14: `stop`). The caller
114
- * checks {@link holderLive} first; the frame waits on the list for the grace like any request.
172
+ * Whether the protocol gate is open ({@link stagedDeviceProtocolActive}; a test seam opens it
173
+ * for one relay instance, the deployment never does).
174
+ */
175
+ stagedProtocolActive = stagedDeviceProtocolActive;
176
+ /**
177
+ * The negotiated transport of the device's connection when the platform's own controls (policy
178
+ * ops) must speak protocol 3 to it, else null (protocol 2). With the gate closed every
179
+ * connection is protocol 2: nothing is looked up (no lease or transport read per op). With it
180
+ * open every connection is staged, so this is {@link connection} (a missing or unready one
181
+ * throws its typed error).
115
182
  */
116
- async send(deviceId, op, args, deadlineMs) {
183
+ async stagedTransport(deviceId) {
184
+ if (!this.stagedProtocolActive())
185
+ return null;
186
+ return this.connection(deviceId);
187
+ }
188
+ /**
189
+ * The negotiated transport of the machine's current connection, for a staged call. Liveness is
190
+ * checked first (ruling R27): no holder throws `device.not_found` for a deleted device,
191
+ * `device.forbidden` for a revoked machine and `device.offline` otherwise.
192
+ */
193
+ async connection(deviceId) {
194
+ if (await this.holderLive(deviceId)) {
195
+ const transport = await this.targets.transport(deviceId);
196
+ if (transport)
197
+ return transport;
198
+ }
199
+ throw this.goneError(await this.targetState(deviceId)) ?? deviceOffline();
200
+ }
201
+ /**
202
+ * Queues `stop` for the machine without waiting for an answer (ruling R14). The caller checks
203
+ * {@link holderLive} first; the frame waits on the list for the grace like any request. It is
204
+ * fenced to the machine `machineId` ({@link STOP_MACHINE}): a holder hands it only to that
205
+ * machine's connection (on a staged connection as a protocol 3 `stop`, across a socket blip
206
+ * too), never to a newer machine of the device. Only `stop` is ever queued this way: a broad
207
+ * kill (`killAll` / `killTagged`) has no frame on protocol 3.
208
+ */
209
+ async send(deviceId, op, args, deadlineMs, machineId) {
117
210
  const id = randomUUID();
118
211
  const d = Math.max(1, Math.ceil(deadlineMs));
119
212
  const req = { type: "req", id, op, args, deadlineMs: d };
120
- await this.push(deviceId, JSON.stringify(req), this.graceMs() + d + LIST_TTL_MARGIN_MS);
213
+ const tagged = { ...req, [STOP_MACHINE]: machineId };
214
+ await this.push(deviceId, JSON.stringify(tagged), this.graceMs() + d + LIST_TTL_MARGIN_MS);
121
215
  await this.bus.publish(deviceReqTopic(deviceId), { id });
122
216
  }
123
217
  /**
@@ -131,17 +225,36 @@ let LocalDeviceRelay = class LocalDeviceRelay {
131
225
  * abort reason is thrown.
132
226
  */
133
227
  async call(deviceId, op, args, opts) {
228
+ return this.callWithCodec(deviceId, op, args, opts, false);
229
+ }
230
+ /** Development staging: the active gateway continues rejecting protocol 3 until coordinated cutover. */
231
+ async callV3(deviceId, op, args, opts) {
232
+ parseDeviceFrameV3(JSON.stringify({ type: "req", id: "validation", op, args, deadlineMs: opts.deadlineMs }), "kernel");
233
+ return this.callWithCodec(deviceId, op, args, opts, true);
234
+ }
235
+ async callWithCodec(deviceId, op, args, opts, staged) {
134
236
  const { signal } = opts;
135
237
  signal.throwIfAborted();
136
- if (!(await this.holderLive(deviceId))) {
238
+ // liveness first: a deleted device or a revoked machine keeps its typed error (R27)
239
+ const connection = staged ? await this.connection(deviceId) : undefined;
240
+ if (!staged && !(await this.holderLive(deviceId))) {
137
241
  throw this.goneError(await this.targetState(deviceId)) ?? deviceOffline();
138
242
  }
243
+ if (opts.connection &&
244
+ (connection?.connectionId !== opts.connection.connectionId ||
245
+ connection?.maxFrameBytes !== opts.connection.maxFrameBytes))
246
+ // nothing was queued: the request was definitely not sent
247
+ throw notSentError(op);
248
+ const fenced = staged && connectionFenced(op);
139
249
  signal.throwIfAborted();
140
250
  const id = randomUUID();
141
251
  const deadlineMs = Math.max(1, Math.ceil(opts.deadlineMs));
142
252
  const graceMs = this.graceMs();
143
253
  const listTtlMs = graceMs + deadlineMs + LIST_TTL_MARGIN_MS;
144
- const reqJson = JSON.stringify({ type: "req", id, op, args, deadlineMs });
254
+ const frame = { type: "req", id, op, args, deadlineMs };
255
+ if (connection)
256
+ parseDeviceFrameV3(JSON.stringify(frame), "kernel", connection.maxFrameBytes);
257
+ const reqJson = JSON.stringify({ ...frame, ...connection });
145
258
  let settle;
146
259
  const outcome = new Promise((resolve) => {
147
260
  let done = false;
@@ -154,7 +267,7 @@ let LocalDeviceRelay = class LocalDeviceRelay {
154
267
  });
155
268
  const onStored = (raw) => {
156
269
  if (raw !== null)
157
- settle(this.parseRes(raw, id));
270
+ settle(this.parseRes(raw, id, op, connection, fenced));
158
271
  };
159
272
  const onAbort = () => settle({ error: ABORTED });
160
273
  const unsubscribe = await this.bus.subscribe(deviceResTopic(id), (payload) => {
@@ -181,6 +294,16 @@ let LocalDeviceRelay = class LocalDeviceRelay {
181
294
  try {
182
295
  // a stalled Redis must not hold the give-up back: no answer in time means "unknown"
183
296
  const live = await this.leaseCheck(deviceId);
297
+ if (fenced && connection && live === true) {
298
+ // an output read never waits across a reconnect: its range was sized for this socket
299
+ const current = await this.targets.transport(deviceId);
300
+ if (current &&
301
+ (current.connectionId !== connection.connectionId ||
302
+ current.maxFrameBytes !== connection.maxFrameBytes)) {
303
+ settle({ error: new DeviceProtocolError(connectionChangedMessage(op)) });
304
+ return;
305
+ }
306
+ }
184
307
  if (live === true && capped) {
185
308
  capped = false;
186
309
  giveUpAt = fullGiveUpAt;
@@ -221,14 +344,24 @@ let LocalDeviceRelay = class LocalDeviceRelay {
221
344
  stopped = true;
222
345
  clearTimeout(timer);
223
346
  if ("res" in r) {
347
+ // the result's connection tag was checked in parseRes: a later reconnect changes nothing
224
348
  await this.quietly("delete the result", deviceId, () => this.redis.del(deviceResKey(id)));
225
- return this.resultOf(op, r.res);
349
+ // only the gateway's marker says a request never reached the machine: never its text
350
+ if (connection && r.notSent)
351
+ throw notSentError(op);
352
+ return staged && r.res.ok
353
+ ? parseOperationResultV3(op, r.res.result, op === "backgroundReadOutput"
354
+ ? args
355
+ : op === "bindInstance"
356
+ ? args
357
+ : undefined)
358
+ : this.resultOf(op, r.res);
226
359
  }
227
360
  if (r.error instanceof Error) {
228
361
  // a bad answer: drop it, give the request up, report the protocol error
229
362
  await this.quietly("delete the result", deviceId, () => this.redis.del(deviceResKey(id)));
230
363
  }
231
- await this.giveUp(deviceId, id, reqJson, listTtlMs);
364
+ await this.giveUp(deviceId, id, reqJson, listTtlMs, connection);
232
365
  if (r.error === ABORTED)
233
366
  throw signal.reason;
234
367
  if (r.error === GRACE_EXPIRED)
@@ -307,8 +440,8 @@ let LocalDeviceRelay = class LocalDeviceRelay {
307
440
  });
308
441
  }
309
442
  /** Removes the request from the list, or queues a cancel when the machine took it (R15). */
310
- async giveUp(deviceId, id, reqJson, ttlMs) {
311
- const cancel = JSON.stringify({ type: "cancel", id });
443
+ async giveUp(deviceId, id, reqJson, ttlMs, connection) {
444
+ const cancel = JSON.stringify({ type: "cancel", id, ...connection });
312
445
  await this.quietly("give the request up", deviceId, async () => {
313
446
  const queued = await this.redis.eval(GIVE_UP, 1, deviceReqKey(deviceId), reqJson, cancel, String(ttlMs));
314
447
  if (queued === 1)
@@ -324,14 +457,46 @@ let LocalDeviceRelay = class LocalDeviceRelay {
324
457
  this.log.warn(`device relay could not ${what}`, { deviceId, error: errMsg(e) });
325
458
  }
326
459
  }
327
- /** A stored / published `res` frame for request `id`, or the protocol error it carries. */
328
- parseRes(raw, id) {
460
+ /**
461
+ * A stored / published `res` frame for request `id`, or the protocol error it carries. A staged
462
+ * frame carries the tag of the connection it arrived on (added by the gateway); a fenced
463
+ * operation ({@link connectionFenced}) accepts only its request's connection, any other staged
464
+ * operation a well-formed tag, and the frame is parsed against that connection's capacity.
465
+ */
466
+ parseRes(raw, id, op, connection, fenced = false) {
329
467
  try {
330
- const f = parseDeviceFrame(raw, "device");
468
+ let wire = raw;
469
+ let cap;
470
+ let arrivedOn;
471
+ let notSent = false;
472
+ if (connection) {
473
+ const { connectionId, maxFrameBytes, [GATEWAY_NOT_SENT]: marker, ...frame } = JSON.parse(raw);
474
+ if (typeof connectionId !== "string" ||
475
+ connectionId === "" ||
476
+ typeof maxFrameBytes !== "number" ||
477
+ !Number.isSafeInteger(maxFrameBytes) ||
478
+ maxFrameBytes < 1024)
479
+ throw new DeviceProtocolError("the gateway stored a result without its connection");
480
+ if (fenced &&
481
+ (connectionId !== connection.connectionId || maxFrameBytes !== connection.maxFrameBytes))
482
+ throw new DeviceProtocolError(connectionChangedMessage(op));
483
+ cap = maxFrameBytes;
484
+ arrivedOn = connectionId;
485
+ notSent = marker === true;
486
+ wire = JSON.stringify(frame);
487
+ }
488
+ const f = connection
489
+ ? parseDeviceFrameV3(wire, "device", cap)
490
+ : parseDeviceFrame(wire, "device");
331
491
  if (f.type !== "res" || f.id !== id) {
332
492
  return { error: new DeviceProtocolError("the connected machine sent an unexpected frame") };
333
493
  }
334
- return { res: f };
494
+ if (arrivedOn === undefined)
495
+ return { res: f };
496
+ // a refusal only: a successful result never carries the marker
497
+ return notSent && !f.ok
498
+ ? { res: f, connectionId: arrivedOn, notSent: true }
499
+ : { res: f, connectionId: arrivedOn };
335
500
  }
336
501
  catch (e) {
337
502
  return {
@@ -352,6 +517,12 @@ let LocalDeviceRelay = class LocalDeviceRelay {
352
517
  }
353
518
  const { kind, message } = res.error;
354
519
  switch (kind) {
520
+ case "denied":
521
+ throw new SandboxScopeDeniedError(message);
522
+ case "unsupported":
523
+ throw new SandboxPermissionUnsupportedError(message);
524
+ case "unknown":
525
+ throw new SandboxOperationOutcomeUnknownError(message);
355
526
  case "gone":
356
527
  throw new SandboxGoneError(message);
357
528
  case "fs_gone":
@@ -1,5 +1,7 @@
1
1
  import type { DeviceFeature, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import type { Redis } from "ioredis";
2
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { LockService } from "../infra/lock/lock.service.js";
3
5
  /**
4
6
  * Whether a local device can still be served: `active` (live and an unrevoked machine),
5
7
  * `revoked` (live, no active machine: disconnected or signed out) or `deleted` (missing or
@@ -16,7 +18,20 @@ export declare const sameRoots: (a: SandboxRoots, b: SandboxRoots) => boolean;
16
18
  */
17
19
  export declare class DeviceTargets {
18
20
  private readonly db;
19
- constructor(db: KernelDb);
21
+ private readonly redis;
22
+ private readonly locks;
23
+ constructor(db: KernelDb, redis: Redis, locks: Pick<LockService, "holderOf">);
24
+ /**
25
+ * The negotiated transport of the machine's current connection, read only under its exact
26
+ * authenticated gateway lease (never current config): the random connection id the gateway sent
27
+ * in `ready` and the effective frame capacity. Null when no replica holds the machine's
28
+ * connection, so the caller maps that through the device's state (deleted, revoked, offline);
29
+ * throws while the holder has not published its capacity yet.
30
+ */
31
+ transport(deviceId: string): Promise<{
32
+ connectionId: string;
33
+ maxFrameBytes: number;
34
+ } | null>;
20
35
  state(deviceId: string): Promise<DeviceTargetState>;
21
36
  /** The org of a live device, or null (missing or deleted). */
22
37
  orgOf(deviceId: string): Promise<string | null>;
@@ -9,6 +9,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { KernelDb } from "../infra/database/kernel-db.js";
12
+ import { LockService } from "../infra/lock/lock.service.js";
13
+ import { REDIS } from "../infra/tokens.js";
14
+ import { deviceLeaseKey, deviceTransportKey } from "./keys.js";
12
15
  import { deviceFeaturesOf } from "./policy-summary.js";
13
16
  const ROOT_KEYS = ["workspace", "skills", "tmp"];
14
17
  /** Whether two sets of roots name the same three directories. */
@@ -21,8 +24,36 @@ export const sameRoots = (a, b) => ROOT_KEYS.every((k) => a[k] === b[k]);
21
24
  */
22
25
  let DeviceTargets = class DeviceTargets {
23
26
  db;
24
- constructor(db) {
27
+ redis;
28
+ locks;
29
+ constructor(db, redis, locks) {
25
30
  this.db = db;
31
+ this.redis = redis;
32
+ this.locks = locks;
33
+ }
34
+ /**
35
+ * The negotiated transport of the machine's current connection, read only under its exact
36
+ * authenticated gateway lease (never current config): the random connection id the gateway sent
37
+ * in `ready` and the effective frame capacity. Null when no replica holds the machine's
38
+ * connection, so the caller maps that through the device's state (deleted, revoked, offline);
39
+ * throws while the holder has not published its capacity yet.
40
+ */
41
+ async transport(deviceId) {
42
+ const lease = await this.locks.holderOf(deviceLeaseKey(deviceId));
43
+ if (!lease)
44
+ return null;
45
+ const raw = await this.redis.get(deviceTransportKey(deviceId, lease));
46
+ const cap = raw === null ? null : JSON.parse(raw);
47
+ const ok = cap !== null &&
48
+ typeof cap === "object" &&
49
+ typeof cap.connectionId === "string" &&
50
+ cap.connectionId !== "" &&
51
+ Number.isSafeInteger(cap.maxFrameBytes) &&
52
+ cap.maxFrameBytes >= 1024;
53
+ if (!ok || (await this.locks.holderOf(deviceLeaseKey(deviceId))) !== lease)
54
+ throw new Error("The machine's connection is not ready yet; retry once capybara-device has reconnected");
55
+ const { connectionId, maxFrameBytes } = cap;
56
+ return { connectionId, maxFrameBytes };
26
57
  }
27
58
  async state(deviceId) {
28
59
  const row = await this.db
@@ -82,6 +113,8 @@ let DeviceTargets = class DeviceTargets {
82
113
  };
83
114
  DeviceTargets = __decorate([
84
115
  Injectable(),
85
- __param(0, Inject(KernelDb))
116
+ __param(0, Inject(KernelDb)),
117
+ __param(1, Inject(REDIS)),
118
+ __param(2, Inject(LockService))
86
119
  ], DeviceTargets);
87
120
  export { DeviceTargets };
@@ -0,0 +1,33 @@
1
+ import { z } from "zod";
2
+ /** The org cloud-network allowlist's host limit. */
3
+ export declare const ORG_SANDBOX_ALLOW_HOSTS_MAX = 200;
4
+ /**
5
+ * The org's sandbox-mode network (org egress ceiling spec §D1), stored as a delta over the
6
+ * platform's `sandbox.limits.allowHosts`, never a copy of it, so platform changes keep reaching the
7
+ * org:
8
+ * - `mode`: the cloud network of a cloud device in sandbox mode, `open` (any public host; loopback,
9
+ * private and cloud metadata addresses are blocked outside the container) or `allowlist`; absent
10
+ * follows the platform's default (open). `sandbox.limits.orgHosts: within` makes it the allowlist.
11
+ * - `base`: `platform` (the default: start from the platform's list) or `none` (only the org's own
12
+ * hosts).
13
+ * - `extraHosts`: hosts the org adds (ignored outside the platform list under `within`).
14
+ * - `excludedHosts`: platform entries the org drops (exact entries; any host is accepted, since the
15
+ * platform may drop an entry later).
16
+ * The effective hosts ({@link orgEffectiveHosts} in `sandbox/modes.ts`) are also the ceiling a local
17
+ * device in sandbox mode reaches (the device intersects them with its own list).
18
+ */
19
+ export declare const CloudNetworkSettingSchema: z.ZodObject<{
20
+ mode: z.ZodOptional<z.ZodEnum<{
21
+ allowlist: "allowlist";
22
+ open: "open";
23
+ }>>;
24
+ base: z.ZodOptional<z.ZodEnum<{
25
+ none: "none";
26
+ platform: "platform";
27
+ }>>;
28
+ extraHosts: z.ZodOptional<z.ZodArray<z.ZodString>>;
29
+ excludedHosts: z.ZodOptional<z.ZodArray<z.ZodString>>;
30
+ }, z.core.$strict>;
31
+ export type CloudNetworkSetting = z.infer<typeof CloudNetworkSettingSchema>;
32
+ /** What an invalid stored `cloudNetwork` reads as: the allowlist with no host (never wider). */
33
+ export declare const invalidCloudNetwork: () => CloudNetworkSetting;
@@ -0,0 +1,47 @@
1
+ import { validateAllowHost } from "@capybara-hq/plugin-sdk";
2
+ import { z } from "zod";
3
+ /** The org cloud-network allowlist's host limit. */
4
+ export const ORG_SANDBOX_ALLOW_HOSTS_MAX = 200;
5
+ /** One host list of the org's cloud network: at most {@link ORG_SANDBOX_ALLOW_HOSTS_MAX} valid, unique hosts. */
6
+ const orgHostList = (name) => z
7
+ .array(z.string())
8
+ .max(ORG_SANDBOX_ALLOW_HOSTS_MAX)
9
+ .superRefine((hosts, ctx) => {
10
+ hosts.forEach((h, i) => {
11
+ for (const message of validateAllowHost(h)) {
12
+ ctx.addIssue({ code: "custom", path: [i], message: `${h}: ${message}` });
13
+ }
14
+ });
15
+ if (new Set(hosts).size !== hosts.length) {
16
+ ctx.addIssue({ code: "custom", message: `${name} must not contain duplicates` });
17
+ }
18
+ })
19
+ .optional();
20
+ /**
21
+ * The org's sandbox-mode network (org egress ceiling spec §D1), stored as a delta over the
22
+ * platform's `sandbox.limits.allowHosts`, never a copy of it, so platform changes keep reaching the
23
+ * org:
24
+ * - `mode`: the cloud network of a cloud device in sandbox mode, `open` (any public host; loopback,
25
+ * private and cloud metadata addresses are blocked outside the container) or `allowlist`; absent
26
+ * follows the platform's default (open). `sandbox.limits.orgHosts: within` makes it the allowlist.
27
+ * - `base`: `platform` (the default: start from the platform's list) or `none` (only the org's own
28
+ * hosts).
29
+ * - `extraHosts`: hosts the org adds (ignored outside the platform list under `within`).
30
+ * - `excludedHosts`: platform entries the org drops (exact entries; any host is accepted, since the
31
+ * platform may drop an entry later).
32
+ * The effective hosts ({@link orgEffectiveHosts} in `sandbox/modes.ts`) are also the ceiling a local
33
+ * device in sandbox mode reaches (the device intersects them with its own list).
34
+ */
35
+ export const CloudNetworkSettingSchema = z
36
+ .object({
37
+ mode: z.enum(["open", "allowlist"]).optional(),
38
+ base: z.enum(["platform", "none"]).optional(),
39
+ extraHosts: orgHostList("extraHosts"),
40
+ excludedHosts: orgHostList("excludedHosts"),
41
+ })
42
+ .strict();
43
+ /** What an invalid stored `cloudNetwork` reads as: the allowlist with no host (never wider). */
44
+ export const invalidCloudNetwork = () => ({
45
+ mode: "allowlist",
46
+ base: "none",
47
+ });
@@ -6,6 +6,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
7
7
  import { OutboxService } from "../infra/outbox/outbox.service.js";
8
8
  import type { KernelLogger } from "../log.js";
9
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
9
10
  import { ApprovalsService } from "../tools/approvals.service.js";
10
11
  import { Credentials } from "../tools/credentials.js";
11
12
  import { QuestionsService } from "../tools/questions.service.js";
@@ -84,6 +85,7 @@ export declare class Offboarding {
84
85
  /** Owes `org.member_removed` to the subscribing plugins, in the offboard transaction. */
85
86
  private readonly lifecycle;
86
87
  readonly log: KernelLogger;
88
+ private readonly ceilings;
87
89
  private readonly orgLock;
88
90
  constructor(db: KernelDb, txHost: TransactionHost, sessions: Pick<SessionService, "markRevoked">, registry: Pick<ExtensionRegistry, "list">, eventLog: Pick<EventLog, "notify" | "publishChanged">,
89
91
  /** Owes the run stops and device destroys in the offboard transaction. */
@@ -91,7 +93,7 @@ export declare class Offboarding {
91
93
  /** Stops the departed member's runs (`by: null`, a system action) in the `run-stop` job. */
92
94
  runs: OffboardingRunControl, credentials: Pick<Credentials, "clearAccount">, approvals: Pick<ApprovalsService, "pendingConversationsFor" | "cancelPendingFor">, questions: Pick<QuestionsService, "pendingConversationsFor" | "cancelPendingFor">,
93
95
  /** Owes `org.member_removed` to the subscribing plugins, in the offboard transaction. */
94
- lifecycle: Pick<LifecycleHooks, "recordIn">, log: KernelLogger, orgLock: Pick<OrgLock, "lockForRemoval">);
96
+ lifecycle: Pick<LifecycleHooks, "recordIn">, log: KernelLogger, ceilings: PermissionCeilingWrites, orgLock: Pick<OrgLock, "lockForRemoval">);
95
97
  /**
96
98
  * In the caller's transaction (`mandatory`: the caller holds the org row lock, order org row →
97
99
  * membership, and did the "last owner" checks):
@@ -27,6 +27,7 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
27
27
  import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
28
28
  import { RunControl } from "../runtime/run-control.js";
29
29
  import { oweDeviceDestroy } from "../sandbox/jobs.js";
30
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
30
31
  import { ApprovalsService } from "../tools/approvals.service.js";
31
32
  import { Credentials } from "../tools/credentials.js";
32
33
  import { QuestionsService } from "../tools/questions.service.js";
@@ -66,6 +67,7 @@ let Offboarding = class Offboarding {
66
67
  questions;
67
68
  lifecycle;
68
69
  log;
70
+ ceilings;
69
71
  orgLock;
70
72
  constructor(db, txHost, sessions, registry, eventLog,
71
73
  /** Owes the run stops and device destroys in the offboard transaction. */
@@ -73,7 +75,7 @@ let Offboarding = class Offboarding {
73
75
  /** Stops the departed member's runs (`by: null`, a system action) in the `run-stop` job. */
74
76
  runs, credentials, approvals, questions,
75
77
  /** Owes `org.member_removed` to the subscribing plugins, in the offboard transaction. */
76
- lifecycle, log, orgLock) {
78
+ lifecycle, log, ceilings, orgLock) {
77
79
  this.db = db;
78
80
  this.txHost = txHost;
79
81
  this.sessions = sessions;
@@ -86,6 +88,7 @@ let Offboarding = class Offboarding {
86
88
  this.questions = questions;
87
89
  this.lifecycle = lifecycle;
88
90
  this.log = log;
91
+ this.ceilings = ceilings;
89
92
  this.orgLock = orgLock;
90
93
  }
91
94
  /**
@@ -114,6 +117,8 @@ let Offboarding = class Offboarding {
114
117
  // the org admission lock exclusively (the callers take it first, before the org row; a no-op
115
118
  // then): it waits for the run writes the fence admitted shared and keeps new ones out
116
119
  await this.orgLock.lockForRemoval(orgId);
120
+ await this.ceilings.lock({ orgId }, "org");
121
+ await this.ceilings.publishLocked({ orgId }, "org", (_scope, row) => row.account_id === accountId);
117
122
  const deleted = await this.db
118
123
  .deleteFrom("memberships")
119
124
  .where("org_id", "=", orgId)
@@ -470,6 +475,7 @@ Offboarding = __decorate([
470
475
  __param(9, Inject(QuestionsService)),
471
476
  __param(10, Inject(LifecycleHooks)),
472
477
  __param(11, Inject(KERNEL_LOGGER)),
473
- __param(12, Inject(OrgLock))
478
+ __param(12, Inject(PermissionCeilingWrites)),
479
+ __param(13, Inject(OrgLock))
474
480
  ], Offboarding);
475
481
  export { Offboarding };
@@ -20,10 +20,16 @@ export interface LockedOrg {
20
20
  * `FOR UPDATE`: org deletion's `deleted_at` update is a no-key update too.
21
21
  *
22
22
  * The global lock order: the org admission lock ({@link lockForRemoval}; the run fence's shared
23
- * admission, `RunExecution`) → this org row lock (also the run fence's exclusive admission) → the
24
- * root conversation → the conversation. A writer that locks several conversation or run rows of
25
- * one tree locks the tree's root conversation first. A transaction the run fence admitted shared
26
- * takes none of these org-level locks (each method throws in one, `assertNotSharedAdmission`).
23
+ * admission, `RunExecution`) → this org row lock (also the run fence's exclusive admission) → a
24
+ * membership row → a device row (`DevicesService.lockOwn`, the device project writes, the cloud
25
+ * permission snapshot) → the super admin advisory lock (`SuperAdminLock`) → the permission
26
+ * authority locks (`PermissionAuthorityLock`: platform, org, device, root; inside a run's fence
27
+ * an ordered prelude takes them and the locks before them, `withOrderedLocks` /
28
+ * `withTransactionFencePrelude`) → the root conversation → the conversation (then what a writer
29
+ * locks under its conversation: an approval, a run, a machine row). A writer that locks several
30
+ * conversation or run rows of one tree locks the tree's root conversation first. A transaction
31
+ * the run fence admitted shared takes none of these org-level locks (each method throws in one,
32
+ * `assertNotSharedAdmission`).
27
33
  */
28
34
  export declare class OrgLock {
29
35
  private readonly db;
@@ -27,10 +27,16 @@ import { can } from "./roles.js";
27
27
  * `FOR UPDATE`: org deletion's `deleted_at` update is a no-key update too.
28
28
  *
29
29
  * The global lock order: the org admission lock ({@link lockForRemoval}; the run fence's shared
30
- * admission, `RunExecution`) → this org row lock (also the run fence's exclusive admission) → the
31
- * root conversation → the conversation. A writer that locks several conversation or run rows of
32
- * one tree locks the tree's root conversation first. A transaction the run fence admitted shared
33
- * takes none of these org-level locks (each method throws in one, `assertNotSharedAdmission`).
30
+ * admission, `RunExecution`) → this org row lock (also the run fence's exclusive admission) → a
31
+ * membership row → a device row (`DevicesService.lockOwn`, the device project writes, the cloud
32
+ * permission snapshot) → the super admin advisory lock (`SuperAdminLock`) → the permission
33
+ * authority locks (`PermissionAuthorityLock`: platform, org, device, root; inside a run's fence
34
+ * an ordered prelude takes them and the locks before them, `withOrderedLocks` /
35
+ * `withTransactionFencePrelude`) → the root conversation → the conversation (then what a writer
36
+ * locks under its conversation: an approval, a run, a machine row). A writer that locks several
37
+ * conversation or run rows of one tree locks the tree's root conversation first. A transaction
38
+ * the run fence admitted shared takes none of these org-level locks (each method throws in one,
39
+ * `assertNotSharedAdmission`).
34
40
  */
35
41
  let OrgLock = class OrgLock {
36
42
  db;
@@ -9,6 +9,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
9
9
  import { TransactionHost } from "../infra/database/transaction-host.js";
10
10
  import { KernelEvents } from "../infra/events/kernel-events.js";
11
11
  import { OutboxService } from "../infra/outbox/outbox.service.js";
12
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
12
13
  import { OrgLock } from "./org-lock.js";
13
14
  import type { OrgRole } from "./roles.js";
14
15
  export type Org = {
@@ -41,6 +42,7 @@ export declare class OrgsService {
41
42
  private readonly ownedItems;
42
43
  /** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
43
44
  private readonly lifecycle;
45
+ private readonly ceilings;
44
46
  constructor(db: KernelDb, outbox: Pick<OutboxService, "add">, txHost: TransactionHost, settings: SettingsService, apiTokens: ApiTokenService, orgLock: OrgLock, events: KernelEvents,
45
47
  /** Cancels the deleted org's running eval runs (in the delete's transaction). */
46
48
  evalBudget: Pick<EvalBudget, "cancelRuns">,
@@ -49,7 +51,7 @@ export declare class OrgsService {
49
51
  /** What the deleted org owns is transferred or removed in the delete's transaction (P3-20). */
50
52
  ownedItems: Pick<OwnedItems, "onOrgDeleted">,
51
53
  /** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
52
- lifecycle: Pick<LifecycleHooks, "recordIn">);
54
+ lifecycle: Pick<LifecycleHooks, "recordIn">, ceilings: PermissionCeilingWrites);
53
55
  /**
54
56
  * Creates an org with the actor as owner, in the caller's transaction when there is one (the
55
57
  * setup wizard creates it with the account); a slug conflict is `org.slug_taken` either way, but