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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +6 -0
  3. package/dist/admin/org-network.service.d.ts +3 -1
  4. package/dist/admin/org-network.service.js +10 -2
  5. package/dist/app.d.ts +4 -0
  6. package/dist/app.js +2 -0
  7. package/dist/background/finish.d.ts +9 -1
  8. package/dist/background/finish.js +57 -4
  9. package/dist/background/launch.d.ts +23 -0
  10. package/dist/background/launch.js +55 -1
  11. package/dist/background/managed-output.d.ts +110 -0
  12. package/dist/background/managed-output.js +219 -0
  13. package/dist/background/managed.d.ts +52 -0
  14. package/dist/background/managed.js +128 -0
  15. package/dist/background/poll.job.d.ts +35 -1
  16. package/dist/background/poll.job.js +174 -9
  17. package/dist/background/render.js +1 -0
  18. package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
  19. package/dist/background/retire-legacy-tasks.job.js +149 -0
  20. package/dist/background/session.d.ts +15 -5
  21. package/dist/background/session.js +22 -6
  22. package/dist/background/stop.d.ts +35 -5
  23. package/dist/background/stop.js +94 -8
  24. package/dist/background/store.d.ts +110 -3
  25. package/dist/background/store.js +205 -3
  26. package/dist/background/tasks.service.d.ts +18 -1
  27. package/dist/background/tasks.service.js +99 -9
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/channels/cards.js +1 -1
  30. package/dist/channels/inbound.js +2 -0
  31. package/dist/channels/phrases.d.ts +4 -0
  32. package/dist/channels/phrases.js +4 -0
  33. package/dist/config/load.d.ts +18 -0
  34. package/dist/config/load.js +39 -1
  35. package/dist/config/permission-migration.d.ts +26 -0
  36. package/dist/config/permission-migration.js +64 -0
  37. package/dist/config/schema.d.ts +4 -1
  38. package/dist/config/schema.js +41 -10
  39. package/dist/conversations/conversations.controller.d.ts +1 -1
  40. package/dist/conversations/conversations.controller.js +1 -1
  41. package/dist/conversations/conversations.module.js +12 -0
  42. package/dist/conversations/conversations.service.d.ts +11 -2
  43. package/dist/conversations/conversations.service.js +97 -27
  44. package/dist/conversations/event-log.d.ts +1 -1
  45. package/dist/conversations/event-log.js +10 -2
  46. package/dist/conversations/events.d.ts +307 -4
  47. package/dist/conversations/events.js +286 -32
  48. package/dist/conversations/permission-profile-store.d.ts +50 -0
  49. package/dist/conversations/permission-profile-store.js +67 -0
  50. package/dist/conversations/permission-profile-store.module.d.ts +2 -0
  51. package/dist/conversations/permission-profile-store.module.js +19 -0
  52. package/dist/conversations/permission-profiles.controller.d.ts +84 -0
  53. package/dist/conversations/permission-profiles.controller.js +105 -0
  54. package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
  55. package/dist/conversations/permission-profiles.schemas.js +23 -0
  56. package/dist/conversations/permission-profiles.service.d.ts +56 -0
  57. package/dist/conversations/permission-profiles.service.js +179 -0
  58. package/dist/ctx/create-ctx.d.ts +12 -5
  59. package/dist/ctx/create-ctx.js +21 -5
  60. package/dist/db/kernel-schema.d.ts +248 -3
  61. package/dist/devices/access.js +1 -1
  62. package/dist/devices/access.module.d.ts +2 -0
  63. package/dist/devices/access.module.js +19 -0
  64. package/dist/devices/conversation-devices.d.ts +8 -29
  65. package/dist/devices/conversation-devices.js +37 -73
  66. package/dist/devices/device-projects.service.d.ts +26 -28
  67. package/dist/devices/device-projects.service.js +123 -127
  68. package/dist/devices/devices.controller.js +3 -1
  69. package/dist/devices/devices.module.js +11 -9
  70. package/dist/devices/devices.service.d.ts +116 -8
  71. package/dist/devices/devices.service.js +252 -20
  72. package/dist/devices/dto.d.ts +16 -0
  73. package/dist/devices/dto.js +34 -6
  74. package/dist/devices/errors.d.ts +8 -0
  75. package/dist/devices/errors.js +10 -0
  76. package/dist/devices/project-rules.d.ts +44 -0
  77. package/dist/devices/project-rules.js +27 -0
  78. package/dist/devices/working-root.d.ts +6 -0
  79. package/dist/devices/working-root.js +12 -1
  80. package/dist/errors.d.ts +31 -0
  81. package/dist/errors.js +31 -0
  82. package/dist/evals/reconstruct.d.ts +19 -2
  83. package/dist/evals/reconstruct.js +40 -2
  84. package/dist/evals/recorded-permission-context.d.ts +77 -0
  85. package/dist/evals/recorded-permission-context.js +151 -0
  86. package/dist/evals/recorded-tools.d.ts +10 -1
  87. package/dist/evals/recorded-tools.js +27 -3
  88. package/dist/evals/run-replay.d.ts +8 -2
  89. package/dist/evals/run-replay.js +18 -2
  90. package/dist/evals/trajectory.d.ts +1 -1
  91. package/dist/evals/worker.d.ts +10 -1
  92. package/dist/evals/worker.js +23 -14
  93. package/dist/extensions/host.d.ts +4 -1
  94. package/dist/extensions/host.js +10 -6
  95. package/dist/http/api.module.js +2 -0
  96. package/dist/identity/accounts.d.ts +14 -1
  97. package/dist/identity/accounts.js +61 -5
  98. package/dist/identity/identity.module.js +2 -0
  99. package/dist/identity/settings.d.ts +28 -12
  100. package/dist/identity/settings.js +89 -33
  101. package/dist/index.d.ts +6 -0
  102. package/dist/index.js +5 -0
  103. package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
  104. package/dist/infra/cli/kernel-cli.module.js +5 -2
  105. package/dist/infra/cli/permission-cutover.d.ts +59 -0
  106. package/dist/infra/cli/permission-cutover.js +107 -0
  107. package/dist/infra/config/kernel-config.service.d.ts +2 -2
  108. package/dist/infra/config/kernel-config.service.js +35 -11
  109. package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
  110. package/dist/infra/database/startup-activation-transaction.js +242 -0
  111. package/dist/infra/database/transaction-host.d.ts +47 -0
  112. package/dist/infra/database/transaction-host.js +119 -0
  113. package/dist/infra/database/xact-lock.d.ts +1 -0
  114. package/dist/infra/database/xact-lock.js +6 -0
  115. package/dist/infra/outbox/registry.d.ts +39 -0
  116. package/dist/infra/outbox/registry.js +18 -0
  117. package/dist/kernel.module.js +2 -0
  118. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  119. package/dist/lifecycle/kernel-lifecycle.js +55 -28
  120. package/dist/local-devices/device-auth.js +1 -1
  121. package/dist/local-devices/device-policy.service.d.ts +35 -5
  122. package/dist/local-devices/device-policy.service.js +188 -13
  123. package/dist/local-devices/instance-bindings.d.ts +82 -0
  124. package/dist/local-devices/instance-bindings.js +304 -0
  125. package/dist/local-devices/keys.d.ts +5 -0
  126. package/dist/local-devices/keys.js +5 -0
  127. package/dist/local-devices/local-device-gateway.d.ts +19 -4
  128. package/dist/local-devices/local-device-gateway.js +185 -17
  129. package/dist/local-devices/local-device-provider.d.ts +42 -7
  130. package/dist/local-devices/local-device-provider.js +185 -10
  131. package/dist/local-devices/local-devices.module.d.ts +17 -2
  132. package/dist/local-devices/local-devices.module.js +49 -8
  133. package/dist/local-devices/machines.d.ts +35 -12
  134. package/dist/local-devices/machines.js +203 -8
  135. package/dist/local-devices/network-grants.js +3 -3
  136. package/dist/local-devices/network-grants.module.d.ts +2 -0
  137. package/dist/local-devices/network-grants.module.js +14 -0
  138. package/dist/local-devices/owner-report.d.ts +79 -0
  139. package/dist/local-devices/owner-report.js +155 -0
  140. package/dist/local-devices/owner-reports.d.ts +48 -0
  141. package/dist/local-devices/owner-reports.js +190 -0
  142. package/dist/local-devices/policy-summary.d.ts +24 -1
  143. package/dist/local-devices/policy-summary.js +48 -0
  144. package/dist/local-devices/relay.d.ts +82 -6
  145. package/dist/local-devices/relay.js +187 -16
  146. package/dist/local-devices/targets.d.ts +16 -1
  147. package/dist/local-devices/targets.js +35 -2
  148. package/dist/models/image-usable.d.ts +22 -0
  149. package/dist/models/image-usable.js +29 -0
  150. package/dist/models/images.d.ts +125 -0
  151. package/dist/models/images.js +440 -0
  152. package/dist/models/models.module.d.ts +3 -2
  153. package/dist/models/models.module.js +16 -5
  154. package/dist/models/org-models.schemas.js +1 -0
  155. package/dist/models/purposes.controller.d.ts +7 -0
  156. package/dist/models/purposes.controller.js +9 -0
  157. package/dist/models/purposes.d.ts +28 -3
  158. package/dist/models/purposes.js +40 -13
  159. package/dist/orgs/cloud-network-setting.d.ts +33 -0
  160. package/dist/orgs/cloud-network-setting.js +47 -0
  161. package/dist/orgs/offboarding.d.ts +3 -1
  162. package/dist/orgs/offboarding.js +8 -2
  163. package/dist/orgs/org-lock.d.ts +10 -4
  164. package/dist/orgs/org-lock.js +10 -4
  165. package/dist/orgs/orgs.service.d.ts +3 -1
  166. package/dist/orgs/orgs.service.js +8 -2
  167. package/dist/orgs/settings.controller.d.ts +4 -1
  168. package/dist/orgs/settings.controller.js +3 -3
  169. package/dist/orgs/settings.service.d.ts +48 -56
  170. package/dist/orgs/settings.service.js +144 -101
  171. package/dist/overrides.d.ts +6 -1
  172. package/dist/overrides.js +2 -0
  173. package/dist/platform/exclusions.js +20 -0
  174. package/dist/platform/ops/admin.ops.js +14 -11
  175. package/dist/platform/ops/agent-skills.ops.js +2 -0
  176. package/dist/platform/ops/devices.ops.js +10 -2
  177. package/dist/platform/ops/models.ops.js +10 -0
  178. package/dist/platform/ops/org-settings.ops.js +6 -6
  179. package/dist/platform/ops/orgs.ops.js +1 -0
  180. package/dist/roles/worker.module.js +4 -0
  181. package/dist/runtime/context/build.d.ts +3 -1
  182. package/dist/runtime/context/build.js +19 -3
  183. package/dist/runtime/context/compaction.js +5 -0
  184. package/dist/runtime/context/device-paths.d.ts +9 -2
  185. package/dist/runtime/context/device-paths.js +20 -0
  186. package/dist/runtime/context/permission-profile.d.ts +46 -0
  187. package/dist/runtime/context/permission-profile.js +194 -0
  188. package/dist/runtime/hook-calls.d.ts +11 -1
  189. package/dist/runtime/hook-calls.js +24 -1
  190. package/dist/runtime/maintenance.d.ts +7 -1
  191. package/dist/runtime/maintenance.js +43 -15
  192. package/dist/runtime/model-call.d.ts +32 -0
  193. package/dist/runtime/model-call.js +67 -0
  194. package/dist/runtime/permission-context-errors.d.ts +39 -0
  195. package/dist/runtime/permission-context-errors.js +67 -0
  196. package/dist/runtime/permission-context.service.d.ts +60 -0
  197. package/dist/runtime/permission-context.service.js +286 -0
  198. package/dist/runtime/project/knowledge.d.ts +7 -2
  199. package/dist/runtime/project/knowledge.js +5 -2
  200. package/dist/runtime/project/knowledge.service.d.ts +17 -2
  201. package/dist/runtime/project/knowledge.service.js +76 -12
  202. package/dist/runtime/providers.d.ts +9 -5
  203. package/dist/runtime/providers.js +22 -3
  204. package/dist/runtime/run-execution.d.ts +4 -1
  205. package/dist/runtime/run-execution.js +14 -5
  206. package/dist/runtime/run-steps.d.ts +11 -3
  207. package/dist/runtime/run-steps.js +27 -4
  208. package/dist/runtime/runtime.module.js +11 -0
  209. package/dist/runtime/usage-report.d.ts +10 -6
  210. package/dist/runtime/usage-report.js +31 -11
  211. package/dist/sandbox/attachments-path.d.ts +15 -0
  212. package/dist/sandbox/attachments-path.js +15 -0
  213. package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
  214. package/dist/sandbox/cloud-permission-snapshot.js +407 -0
  215. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
  216. package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
  217. package/dist/sandbox/held-operations.d.ts +39 -0
  218. package/dist/sandbox/held-operations.js +119 -0
  219. package/dist/sandbox/jobs.d.ts +14 -3
  220. package/dist/sandbox/jobs.js +20 -2
  221. package/dist/sandbox/kernel-read.d.ts +55 -0
  222. package/dist/sandbox/kernel-read.js +57 -0
  223. package/dist/sandbox/legacy-retirement.d.ts +336 -0
  224. package/dist/sandbox/legacy-retirement.js +1063 -0
  225. package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
  226. package/dist/sandbox/legacy-retirement.module.js +25 -0
  227. package/dist/sandbox/managed-device-context.d.ts +94 -0
  228. package/dist/sandbox/managed-device-context.js +308 -0
  229. package/dist/sandbox/managed-device-context.module.d.ts +6 -0
  230. package/dist/sandbox/managed-device-context.module.js +33 -0
  231. package/dist/sandbox/modes.d.ts +56 -8
  232. package/dist/sandbox/modes.js +92 -8
  233. package/dist/sandbox/operation-authority-types.d.ts +8 -0
  234. package/dist/sandbox/operation-authority-types.js +32 -0
  235. package/dist/sandbox/operation-authority.d.ts +145 -0
  236. package/dist/sandbox/operation-authority.js +783 -0
  237. package/dist/sandbox/operation-authority.module.d.ts +2 -0
  238. package/dist/sandbox/operation-authority.module.js +29 -0
  239. package/dist/sandbox/operation-intents.d.ts +206 -0
  240. package/dist/sandbox/operation-intents.js +1252 -0
  241. package/dist/sandbox/operation-intents.module.d.ts +2 -0
  242. package/dist/sandbox/operation-intents.module.js +21 -0
  243. package/dist/sandbox/operation-payloads.d.ts +33 -0
  244. package/dist/sandbox/operation-payloads.js +332 -0
  245. package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
  246. package/dist/sandbox/operation-reconcile.job.js +247 -0
  247. package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
  248. package/dist/sandbox/permission-authority-epochs.js +83 -0
  249. package/dist/sandbox/permission-authority-lock.d.ts +38 -0
  250. package/dist/sandbox/permission-authority-lock.js +147 -0
  251. package/dist/sandbox/permission-authority.module.d.ts +9 -0
  252. package/dist/sandbox/permission-authority.module.js +55 -0
  253. package/dist/sandbox/permission-availability.d.ts +18 -0
  254. package/dist/sandbox/permission-availability.js +19 -0
  255. package/dist/sandbox/permission-call-grants.d.ts +34 -0
  256. package/dist/sandbox/permission-call-grants.js +349 -0
  257. package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
  258. package/dist/sandbox/permission-call-grants.module.js +21 -0
  259. package/dist/sandbox/permission-call-types.d.ts +82 -0
  260. package/dist/sandbox/permission-call-types.js +1 -0
  261. package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
  262. package/dist/sandbox/permission-ceiling-writes.js +223 -0
  263. package/dist/sandbox/permission-config-publication.d.ts +76 -0
  264. package/dist/sandbox/permission-config-publication.js +339 -0
  265. package/dist/sandbox/permission-context-types.d.ts +64 -0
  266. package/dist/sandbox/permission-context-types.js +24 -0
  267. package/dist/sandbox/permission-facts.d.ts +206 -0
  268. package/dist/sandbox/permission-facts.js +627 -0
  269. package/dist/sandbox/permission-facts.module.d.ts +2 -0
  270. package/dist/sandbox/permission-facts.module.js +20 -0
  271. package/dist/sandbox/permission-instance-writes.d.ts +90 -0
  272. package/dist/sandbox/permission-instance-writes.js +305 -0
  273. package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
  274. package/dist/sandbox/permission-runtime-reports.js +354 -0
  275. package/dist/sandbox/permission-transitions.d.ts +31 -0
  276. package/dist/sandbox/permission-transitions.js +155 -0
  277. package/dist/sandbox/platform-full-access.d.ts +128 -0
  278. package/dist/sandbox/platform-full-access.js +210 -0
  279. package/dist/sandbox/providers.d.ts +22 -0
  280. package/dist/sandbox/providers.js +10 -2
  281. package/dist/sandbox/providers.module.d.ts +2 -0
  282. package/dist/sandbox/providers.module.js +19 -0
  283. package/dist/sandbox/request-not-sent.d.ts +13 -0
  284. package/dist/sandbox/request-not-sent.js +13 -0
  285. package/dist/sandbox/review/classifier.d.ts +2 -0
  286. package/dist/sandbox/review/classifier.js +8 -0
  287. package/dist/sandbox/review/permission-candidate.d.ts +12 -0
  288. package/dist/sandbox/review/permission-candidate.js +145 -0
  289. package/dist/sandbox/review/review.service.d.ts +5 -2
  290. package/dist/sandbox/review/review.service.js +60 -15
  291. package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
  292. package/dist/sandbox/sandbox-file-reader.js +51 -7
  293. package/dist/sandbox/sandbox.module.js +26 -6
  294. package/dist/sandbox/sandbox.service.d.ts +230 -34
  295. package/dist/sandbox/sandbox.service.js +1368 -199
  296. package/dist/sandbox/unreachable.js +17 -3
  297. package/dist/sandbox/use-context.d.ts +17 -0
  298. package/dist/sandbox/use-context.js +1 -0
  299. package/dist/skills/invoke.d.ts +27 -4
  300. package/dist/skills/invoke.js +72 -7
  301. package/dist/tools/approvals.controller.d.ts +1 -0
  302. package/dist/tools/approvals.schemas.d.ts +1 -0
  303. package/dist/tools/approvals.schemas.js +3 -1
  304. package/dist/tools/approvals.service.d.ts +23 -10
  305. package/dist/tools/approvals.service.js +104 -26
  306. package/dist/tools/builtin-names.d.ts +3 -1
  307. package/dist/tools/builtin-names.js +5 -1
  308. package/dist/tools/builtins/artifacts.d.ts +43 -0
  309. package/dist/tools/builtins/artifacts.js +67 -0
  310. package/dist/tools/builtins/builtin-tools.d.ts +20 -2
  311. package/dist/tools/builtins/builtin-tools.js +61 -10
  312. package/dist/tools/builtins/image/generate.d.ts +59 -0
  313. package/dist/tools/builtins/image/generate.js +535 -0
  314. package/dist/tools/builtins/image/index.d.ts +2 -0
  315. package/dist/tools/builtins/image/index.js +2 -0
  316. package/dist/tools/builtins/image/paths.d.ts +12 -0
  317. package/dist/tools/builtins/image/paths.js +26 -0
  318. package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
  319. package/dist/tools/builtins/sandbox/bash.js +201 -5
  320. package/dist/tools/builtins/sandbox/common.d.ts +92 -20
  321. package/dist/tools/builtins/sandbox/common.js +201 -17
  322. package/dist/tools/builtins/sandbox/deliver.js +9 -51
  323. package/dist/tools/builtins/sandbox/edit.js +2 -2
  324. package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
  325. package/dist/tools/builtins/sandbox/glob.js +2 -2
  326. package/dist/tools/builtins/sandbox/grep.js +2 -2
  327. package/dist/tools/builtins/sandbox/read.js +2 -2
  328. package/dist/tools/builtins/sandbox/task-list.js +7 -1
  329. package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
  330. package/dist/tools/builtins/sandbox/task-output.js +172 -0
  331. package/dist/tools/builtins/sandbox/task-stop.js +25 -3
  332. package/dist/tools/builtins/sandbox/write.js +2 -2
  333. package/dist/tools/builtins/skill-load.js +9 -6
  334. package/dist/tools/device-op-resolver.d.ts +1 -1
  335. package/dist/tools/device-op-resolver.js +13 -3
  336. package/dist/tools/permission-approval-jobs.d.ts +18 -0
  337. package/dist/tools/permission-approval-jobs.js +92 -0
  338. package/dist/tools/pipeline.d.ts +17 -2
  339. package/dist/tools/pipeline.js +315 -26
  340. package/dist/tools/registry.d.ts +9 -0
  341. package/dist/tools/tools.module.js +15 -0
  342. package/package.json +4 -3
  343. package/src/migrations/0146_permission_authority_epochs.sql +6 -0
  344. package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
  345. package/src/migrations/0148_first_message_request_hash.sql +2 -0
  346. package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
  347. package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
  348. package/src/migrations/0151_starting_execution_grants.sql +8 -0
  349. package/src/migrations/0152_background_launch_identity.sql +66 -0
  350. package/src/migrations/0153_background_cancel_requester.sql +13 -0
  351. package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
  352. package/src/migrations/0155_device_instance_generations.sql +30 -0
  353. package/src/migrations/0156_device_owner_report.sql +7 -0
  354. package/src/migrations/0157_legacy_retirement.sql +116 -0
  355. package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
  356. package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
  357. package/src/migrations/0160_model_usage_image_kind.sql +10 -0
  358. package/dist/sandbox/platform-auto-mode.d.ts +0 -63
  359. package/dist/sandbox/platform-auto-mode.js +0 -63
@@ -0,0 +1,247 @@
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 { isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxExecutionRef, parseSandboxOperationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable, Optional } from "@nestjs/common";
12
+ import { MANAGED_STOP_GRACE_MS, ManagedInstanceMismatchError } from "../background/managed.js";
13
+ import { BackgroundTaskStopper } from "../background/stop.js";
14
+ import { BackgroundTaskStore } from "../background/store.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
17
+ import { isDeviceRequestNotSent } from "../local-devices/relay.js";
18
+ import { checkManagedStart } from "./held-operations.js";
19
+ import { SandboxOperationIntents } from "./operation-intents.js";
20
+ import { SandboxProviders } from "./providers.js";
21
+ import { SandboxService } from "./sandbox.service.js";
22
+ /** Called only by the maintenance consumer. It has no native dispatch or lease token API. */
23
+ let SandboxOperationReconcileJob = class SandboxOperationReconcileJob {
24
+ intents;
25
+ db;
26
+ providers;
27
+ sandbox;
28
+ tasks;
29
+ stopper;
30
+ log;
31
+ constructor(intents, db, providers, sandbox, tasks, stopper,
32
+ /** Where a recovered start's refusal keeps the provider's own message (never the task's). */
33
+ log) {
34
+ this.intents = intents;
35
+ this.db = db;
36
+ this.providers = providers;
37
+ this.sandbox = sandbox;
38
+ this.tasks = tasks;
39
+ this.stopper = stopper;
40
+ this.log = log;
41
+ }
42
+ async reconcile(operationId) {
43
+ await this.intents.expirePayload(operationId);
44
+ const row = await this.intents.read(operationId);
45
+ if (row.method === "backgroundStart") {
46
+ await this.reconcileBackground(row);
47
+ return;
48
+ }
49
+ if (row.state === "revoked") {
50
+ await this.revoke(operationId);
51
+ return;
52
+ }
53
+ // Existing run/tool claim recovery owns continuation. A failed orphan never gets new authority.
54
+ if (row.state === "dispatching")
55
+ await this.intents.unknown(operationId);
56
+ }
57
+ /**
58
+ * A managed start: past its retention an unresolved launch is given up (terminal task, owed
59
+ * exact revoke); a revoked one owes its revoke; a `dispatching` one still has its dispatcher
60
+ * (or a holder cleanup that revokes it) and is only checked again later; a `started-or-unknown`
61
+ * one is recovered under the same identity.
62
+ */
63
+ async reconcileBackground(row) {
64
+ if (row.retain_until.getTime() <= Date.now()) {
65
+ await this.intents.abandonBackgroundLaunch(row.operation_id, "expired");
66
+ const now = await this.intents.read(row.operation_id);
67
+ if (now.state === "revoked" && !now.revoke_acknowledged)
68
+ await this.revoke(row.operation_id);
69
+ return;
70
+ }
71
+ if (row.state === "revoked") {
72
+ await this.revoke(row.operation_id);
73
+ return;
74
+ }
75
+ if (row.state === "dispatching") {
76
+ await this.intents.deferBackgroundRecovery(row.operation_id);
77
+ return;
78
+ }
79
+ if (row.state === "started-or-unknown")
80
+ await this.recoverBackground(row.operation_id);
81
+ }
82
+ /**
83
+ * Recovers a managed start whose acknowledgement was lost, under a task-specific recovery claim:
84
+ * asks the provider about the same operation, recorded scope and recorded input on the exact
85
+ * recorded provider, version and instance generation only (never resumed), after the same
86
+ * artifact and runtime checks as the first dispatch. A launch that happened returns its original
87
+ * ref; one that did not happens once. Never a new operation ID, never refreshed authority.
88
+ */
89
+ async recoverBackground(operationId) {
90
+ const claimed = await this.intents.claimBackgroundRecovery(operationId);
91
+ if (!claimed)
92
+ return;
93
+ // set by the callback: a refusal from the checks and one from the provider settle differently
94
+ const at = { phase: "check" };
95
+ try {
96
+ const input = (await this.intents.input(claimed));
97
+ if (!input || typeof input !== "object")
98
+ throw new SandboxOperationOutcomeUnknownError("The recorded start input has expired");
99
+ const scope = parseSandboxOperationScope(claimed.scope);
100
+ const generation = Number(claimed.instance_generation);
101
+ const instance = await this.db
102
+ .selectFrom("device_instances")
103
+ .select("provider")
104
+ .where("device_id", "=", claimed.device_id)
105
+ .executeTakeFirst();
106
+ const entry = this.providers.forName(claimed.provider);
107
+ if (!Number.isSafeInteger(generation) ||
108
+ instance?.provider !== claimed.provider ||
109
+ !entry ||
110
+ (entry.version ?? "internal-v2") !== claimed.provider_version)
111
+ throw new SandboxOperationOutcomeUnknownError("The recorded provider or instance is not current; the start outcome remains unknown");
112
+ const r = await this.sandbox.ifRunning(claimed.device_id, { createdAt: new Date(generation) }, async (p, h, signal) => {
113
+ await checkManagedStart(p, h, scope, input, signal);
114
+ const background = p.background;
115
+ if (!background)
116
+ throw new SandboxPermissionUnsupportedError("Managed background tasks are unavailable");
117
+ at.phase = "start";
118
+ return { ref: await background.start(h, scope, { ...input, signal }), instanceId: h.id };
119
+ }, AbortSignal.timeout(60_000));
120
+ if (r.kind !== "ran")
121
+ throw new SandboxOperationOutcomeUnknownError("The recorded instance is not running; the start outcome remains unknown");
122
+ await this.intents.acknowledgeBackground(operationId, claimed.execution_id, r.value.ref, r.value.instanceId);
123
+ }
124
+ catch (error) {
125
+ // never sent (the device's connection changed): nothing learned about the first dispatch
126
+ if (isDeviceRequestNotSent(error)) {
127
+ await this.intents.deferBackgroundRecovery(operationId);
128
+ return;
129
+ }
130
+ if (at.phase === "check" && isSandboxScopeDeniedError(error)) {
131
+ // The kernel will not send it again, but cannot prove the first dispatch had no effect.
132
+ await this.intents.abandonBackgroundLaunch(operationId, "refused");
133
+ return;
134
+ }
135
+ if (at.phase === "start" &&
136
+ (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error))) {
137
+ // the task keeps the kernel's reason; the provider's message stays here
138
+ this.log?.warn("a recovered background start was refused", { operationId, err: error });
139
+ await this.intents.settleBackgroundRefusal(operationId, claimed.execution_id, {
140
+ // a not-sent refusal was deferred above; kept distinct should it ever reach here
141
+ kind: isDeviceRequestNotSent(error)
142
+ ? "not_sent"
143
+ : isSandboxScopeDeniedError(error)
144
+ ? "denied"
145
+ : "unsupported",
146
+ message: error.message,
147
+ });
148
+ return;
149
+ }
150
+ await this.intents.deferBackgroundRecovery(operationId);
151
+ }
152
+ }
153
+ async revoke(operationId) {
154
+ try {
155
+ await this.revokeOnce(operationId);
156
+ }
157
+ catch {
158
+ await this.intents.deferRevocation(operationId);
159
+ }
160
+ }
161
+ async revokeOnce(operationId) {
162
+ const row = await this.intents.read(operationId);
163
+ if (row.state !== "revoked" || row.revoke_acknowledged)
164
+ return;
165
+ // a launched background start is cancelled by its exact ref, never by the operation revoke;
166
+ // one revoked before its ref is known keeps the exact operation revoke below
167
+ if (row.method === "backgroundStart" && row.execution_ref !== null) {
168
+ await this.revokeBackground(row);
169
+ return;
170
+ }
171
+ const instance = await this.db
172
+ .selectFrom("device_instances")
173
+ .select(["provider", "handle", "created_at"])
174
+ .where("device_id", "=", row.device_id)
175
+ .executeTakeFirst();
176
+ // Do not use a new instance as proof that the old execution was cleaned up.
177
+ if (!instance?.handle ||
178
+ instance.provider !== row.provider ||
179
+ String(instance.created_at.getTime()) !== row.instance_generation)
180
+ throw new SandboxOperationOutcomeUnknownError("The revoked operation's instance must be reconciled before cleanup is acknowledged");
181
+ const provider = this.providers.forName(row.provider)?.impl;
182
+ if (!provider?.revokeOperation)
183
+ throw new SandboxOperationOutcomeUnknownError("The operation's provider is unavailable; revocation remains owed");
184
+ await provider.revokeOperation(instance.handle, { operationId: row.operation_id, admitBeforeMs: row.deadline.getTime() }, AbortSignal.timeout(30_000));
185
+ await this.intents.acknowledgeRevocation(operationId);
186
+ }
187
+ /**
188
+ * The exact cancellation a revoked background start owes (design B3): the task's own stop by its
189
+ * exact ref with the five-second grace, which settles and reports the task; the revocation is
190
+ * acknowledged only on verified settlement (a stop or an exit). A pending cancellation, an
191
+ * unreachable or replaced instance and lost supervision keep it owed. The intent alone carries
192
+ * the obligation: a finished-lost task or a task row removed with its conversation is still
193
+ * stopped by the intent's recorded ref on the recorded instance generation, never by a PID, a
194
+ * tag or a newer instance.
195
+ */
196
+ async revokeBackground(row) {
197
+ const owed = (why) => new SandboxOperationOutcomeUnknownError(`${why}; the exact cancellation remains owed`);
198
+ const ref = parseSandboxExecutionRef(row.execution_ref);
199
+ const task = await this.tasks.byOperation(row.operation_id);
200
+ if (task?.status === "running") {
201
+ const after = await this.stopper.stop(task, "revoked", AbortSignal.timeout(30_000));
202
+ if (after.status === "running")
203
+ throw owed("The task's stop is pending or claimed elsewhere");
204
+ if (after.launchState === "terminal") {
205
+ await this.intents.acknowledgeRevocation(row.operation_id);
206
+ return;
207
+ }
208
+ }
209
+ else if (task?.launchState === "terminal") {
210
+ await this.intents.acknowledgeRevocation(row.operation_id);
211
+ return;
212
+ }
213
+ const generation = Number(row.instance_generation);
214
+ if (!Number.isSafeInteger(generation) ||
215
+ ref.operationId !== row.operation_id ||
216
+ ref.instanceGeneration !== row.instance_generation)
217
+ throw owed("The recorded execution reference does not match its start");
218
+ const r = await this.sandbox.ifRunning(row.device_id,
219
+ // the exact stop of a revoked start: an exact-ref drain (8.5)
220
+ { createdAt: new Date(generation), exactRef: true }, async (p, h, signal) => {
221
+ if (h.id !== ref.instanceId)
222
+ throw new ManagedInstanceMismatchError();
223
+ if (!p.background)
224
+ throw new SandboxPermissionUnsupportedError("Managed background tasks are unavailable");
225
+ return p.background.stop(h, ref, { graceMs: MANAGED_STOP_GRACE_MS, signal });
226
+ }, AbortSignal.timeout(30_000));
227
+ if (r.kind !== "ran")
228
+ throw owed("The recorded instance is not running");
229
+ if (r.value.outcome !== "stopped" && r.value.outcome !== "already-exited")
230
+ throw owed(`The device answered ${r.value.outcome}`);
231
+ if (task)
232
+ await this.tasks.settleOwedCancel(task.id);
233
+ await this.intents.acknowledgeRevocation(row.operation_id);
234
+ }
235
+ };
236
+ SandboxOperationReconcileJob = __decorate([
237
+ Injectable(),
238
+ __param(0, Inject(SandboxOperationIntents)),
239
+ __param(1, Inject(KernelDb)),
240
+ __param(2, Inject(SandboxProviders)),
241
+ __param(3, Inject(SandboxService)),
242
+ __param(4, Inject(BackgroundTaskStore)),
243
+ __param(5, Inject(BackgroundTaskStopper)),
244
+ __param(6, Optional()),
245
+ __param(6, Inject(KERNEL_LOGGER))
246
+ ], SandboxOperationReconcileJob);
247
+ export { SandboxOperationReconcileJob };
@@ -0,0 +1,18 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { type AuthorityLevel, type AuthoritySubject, PermissionAuthorityLock } from "./permission-authority-lock.js";
4
+ export type AuthorityEpochVector = {
5
+ platform: number;
6
+ org: number | null;
7
+ device: number | null;
8
+ root: number | null;
9
+ };
10
+ export declare class PermissionAuthorityEpochStore {
11
+ private readonly db;
12
+ readonly txHost: TransactionHost;
13
+ private readonly locks;
14
+ constructor(db: KernelDb, txHost: TransactionHost, locks: PermissionAuthorityLock);
15
+ readLocked(subject: AuthoritySubject): Promise<AuthorityEpochVector>;
16
+ private read;
17
+ bumpLocked(kind: AuthorityLevel, id: string, expected: number): Promise<number>;
18
+ }
@@ -0,0 +1,83 @@
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 { Inject, Injectable } from "@nestjs/common";
11
+ import { ApiError } from "../errors.js";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { TransactionHost } from "../infra/database/transaction-host.js";
14
+ import { Transactional } from "../infra/database/transactional.decorator.js";
15
+ import { authorityEntries, PermissionAuthorityLock, } from "./permission-authority-lock.js";
16
+ let PermissionAuthorityEpochStore = class PermissionAuthorityEpochStore {
17
+ db;
18
+ txHost;
19
+ locks;
20
+ constructor(db, txHost, locks) {
21
+ this.db = db;
22
+ this.txHost = txHost;
23
+ this.locks = locks;
24
+ }
25
+ async readLocked(subject) {
26
+ const result = { platform: 0, org: null, device: null, root: null };
27
+ for (const [kind, id] of authorityEntries(subject)) {
28
+ this.locks.assertHeld(kind, id);
29
+ result[kind] = await this.read(kind, id);
30
+ }
31
+ return result;
32
+ }
33
+ async read(kind, id) {
34
+ let row = await this.db
35
+ .selectFrom("permission_authority_epochs")
36
+ .select("revision")
37
+ .where("kind", "=", kind)
38
+ .where("id", "=", id)
39
+ .executeTakeFirst();
40
+ if (!row) {
41
+ await this.db
42
+ .insertInto("permission_authority_epochs")
43
+ .values({ kind, id })
44
+ .onConflict((oc) => oc.columns(["kind", "id"]).doNothing())
45
+ .execute();
46
+ row = await this.db
47
+ .selectFrom("permission_authority_epochs")
48
+ .select("revision")
49
+ .where("kind", "=", kind)
50
+ .where("id", "=", id)
51
+ .executeTakeFirstOrThrow();
52
+ }
53
+ return row.revision;
54
+ }
55
+ async bumpLocked(kind, id, expected) {
56
+ this.locks.assertHeld(kind, id, true);
57
+ await this.read(kind, id);
58
+ const row = await this.db
59
+ .updateTable("permission_authority_epochs")
60
+ .set({ revision: expected + 1 })
61
+ .where("kind", "=", kind)
62
+ .where("id", "=", id)
63
+ .where("revision", "=", expected)
64
+ .returning("revision")
65
+ .executeTakeFirst();
66
+ if (!row)
67
+ throw new ApiError("conflict", "Authority changed; refresh and retry");
68
+ return row.revision;
69
+ }
70
+ };
71
+ __decorate([
72
+ Transactional({ propagation: "mandatory" })
73
+ ], PermissionAuthorityEpochStore.prototype, "readLocked", null);
74
+ __decorate([
75
+ Transactional({ propagation: "mandatory" })
76
+ ], PermissionAuthorityEpochStore.prototype, "bumpLocked", null);
77
+ PermissionAuthorityEpochStore = __decorate([
78
+ Injectable(),
79
+ __param(0, Inject(KernelDb)),
80
+ __param(1, Inject(TransactionHost)),
81
+ __param(2, Inject(PermissionAuthorityLock))
82
+ ], PermissionAuthorityEpochStore);
83
+ export { PermissionAuthorityEpochStore };
@@ -0,0 +1,38 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { XactLock } from "../infra/database/xact-lock.js";
4
+ export type AuthorityLevel = "platform" | "org" | "device" | "root";
5
+ export type AuthoritySubject = {
6
+ orgId?: string;
7
+ deviceId?: string;
8
+ rootConversationId?: string;
9
+ };
10
+ export type AuthorityLockIntent = {
11
+ kind: "admit";
12
+ } | {
13
+ kind: "write";
14
+ level: AuthorityLevel;
15
+ };
16
+ export declare const authorityEntries: (s: AuthoritySubject) => [AuthorityLevel, string][];
17
+ /**
18
+ * An internal error (a kernel bug, never a user refusal): a permission authority lock was asked for
19
+ * inside a transaction a run fence already admitted, outside its ordered prelude, which would take
20
+ * it after the fence's conversation rows and invert the global lock order (org row → permission
21
+ * authority locks → root conversation → conversation).
22
+ */
23
+ export declare class PermissionLockOrderError extends Error {
24
+ readonly keys: readonly string[];
25
+ readonly name = "PermissionLockOrderError";
26
+ constructor(keys: readonly string[]);
27
+ }
28
+ /** Shared readers and exclusive changed-level writers, held until the caller commits. */
29
+ export declare class PermissionAuthorityLock {
30
+ private readonly db;
31
+ readonly txHost: TransactionHost;
32
+ private readonly locks;
33
+ constructor(db: KernelDb, txHost: TransactionHost, locks: XactLock);
34
+ acquire(subject: AuthoritySubject, intent: AuthorityLockIntent): Promise<void>;
35
+ assertHeld(kind: AuthorityLevel, id: string, exclusive?: boolean): void;
36
+ }
37
+ /** The current transaction holds this authority lock (exclusively when asked); else throws. */
38
+ export declare function assertAuthorityHeld(kind: AuthorityLevel, id: string, exclusive?: boolean): void;
@@ -0,0 +1,147 @@
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 { Inject, Injectable } from "@nestjs/common";
11
+ import { ApiError } from "../errors.js";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { assertNotSharedAdmission, currentStore, TransactionHost, } from "../infra/database/transaction-host.js";
14
+ import { Transactional } from "../infra/database/transactional.decorator.js";
15
+ import { XactLock } from "../infra/database/xact-lock.js";
16
+ export const authorityEntries = (s) => [
17
+ ["platform", "platform"],
18
+ ...(s.orgId ? [["org", s.orgId]] : []),
19
+ ...(s.deviceId ? [["device", s.deviceId]] : []),
20
+ ...(s.rootConversationId ? [["root", s.rootConversationId]] : []),
21
+ ];
22
+ const keyOf = (kind, id) => `permission-authority-${kind}-${id}`;
23
+ /**
24
+ * An internal error (a kernel bug, never a user refusal): a permission authority lock was asked for
25
+ * inside a transaction a run fence already admitted, outside its ordered prelude, which would take
26
+ * it after the fence's conversation rows and invert the global lock order (org row → permission
27
+ * authority locks → root conversation → conversation).
28
+ */
29
+ export class PermissionLockOrderError extends Error {
30
+ keys;
31
+ name = "PermissionLockOrderError";
32
+ constructor(keys) {
33
+ super(`Permission authority locks inside a fenced transaction are taken only in its ordered prelude ` +
34
+ `(missing: ${keys.join(", ")}); take them with withOrderedLocks / withTransactionFencePrelude ` +
35
+ "before the transaction opens");
36
+ this.keys = keys;
37
+ }
38
+ }
39
+ /** Shared readers and exclusive changed-level writers, held until the caller commits. */
40
+ let PermissionAuthorityLock = class PermissionAuthorityLock {
41
+ db;
42
+ txHost;
43
+ locks;
44
+ constructor(db, txHost, locks) {
45
+ this.db = db;
46
+ this.txHost = txHost;
47
+ this.locks = locks;
48
+ }
49
+ async acquire(subject, intent) {
50
+ assertNotSharedAdmission("the permission authority lock");
51
+ if (intent.kind === "write" && intent.level === "platform") {
52
+ if (subject.orgId || subject.deviceId || subject.rootConversationId)
53
+ throw new Error("Platform writes cannot acquire descendant locks");
54
+ }
55
+ else {
56
+ if (!subject.orgId ||
57
+ !(await this.db
58
+ .selectFrom("orgs")
59
+ .select("id")
60
+ .where("id", "=", subject.orgId)
61
+ .executeTakeFirst()))
62
+ throw new ApiError("org.not_found", "The authority organization does not exist");
63
+ }
64
+ const entries = authorityEntries(subject);
65
+ const stop = intent.kind === "write"
66
+ ? entries.findIndex(([level]) => level === intent.level)
67
+ : entries.length - 1;
68
+ if (stop < 0)
69
+ throw new Error("The changed authority level is missing");
70
+ const store = currentStore();
71
+ if (!store)
72
+ throw new Error("Authority locks require a transaction");
73
+ store.permissionLocks ??= new Map();
74
+ const claims = store.permissionLocks;
75
+ // Validate the whole acquisition before taking any locks; upgrading or reordering can deadlock.
76
+ const wanted = entries.slice(0, stop + 1).map(([level, id], index) => ({
77
+ key: keyOf(level, id),
78
+ mode: intent.kind === "write" && index === stop ? "exclusive" : "shared",
79
+ }));
80
+ for (const item of wanted) {
81
+ const held = claims.get(item.key);
82
+ if (held === "shared" && item.mode === "exclusive")
83
+ throw new Error("Authority lock upgrades are forbidden; choose the highest write intent first");
84
+ }
85
+ if (claims.size && wanted.some((item) => !claims.has(item.key)))
86
+ throw new Error("Acquire the complete authority subject once in fixed order");
87
+ // the global lock order puts these locks after the org row and before the conversation rows:
88
+ // a transaction a run fence already admitted holds its conversation rows, so a new authority
89
+ // lock there (shared or exclusive) would invert the order. Readers (context, managed writer,
90
+ // admission, review) and ceiling writers (deletion, device, org, platform and account writes
91
+ // a Platform operation reaches from a tool step) take theirs in the ordered prelude instead
92
+ // (`withTransactionFencePrelude`, `withOrderedLocks`), which runs inside the fence before
93
+ // those rows; the body may then name the same, already held, subject again
94
+ const missing = wanted.filter((item) => !claims.has(item.key));
95
+ if (store.admission !== undefined && missing.length)
96
+ throw new PermissionLockOrderError(missing.map((item) => item.key));
97
+ for (const item of wanted) {
98
+ if (claims.has(item.key))
99
+ continue;
100
+ if (item.mode === "exclusive")
101
+ await this.locks.lock(item.key);
102
+ else
103
+ await this.locks.shared(item.key);
104
+ claims.set(item.key, item.mode);
105
+ }
106
+ if (subject.deviceId) {
107
+ const row = await this.db
108
+ .selectFrom("devices")
109
+ .select("org_id")
110
+ .where("id", "=", subject.deviceId)
111
+ .executeTakeFirst();
112
+ if (!row || row.org_id !== subject.orgId)
113
+ throw new ApiError("device.not_found", "Device not found");
114
+ }
115
+ if (subject.rootConversationId) {
116
+ const row = await this.db
117
+ .selectFrom("conversations")
118
+ .select("org_id")
119
+ .where("id", "=", subject.rootConversationId)
120
+ .executeTakeFirst();
121
+ if (row && row.org_id !== subject.orgId)
122
+ throw new ApiError("conversation.not_found", "Conversation not found");
123
+ // A root-write may reserve the random ID before its first insert.
124
+ if (!row && !(intent.kind === "write" && intent.level === "root"))
125
+ throw new ApiError("conversation.not_found", "Conversation not found");
126
+ }
127
+ }
128
+ assertHeld(kind, id, exclusive = false) {
129
+ assertAuthorityHeld(kind, id, exclusive);
130
+ }
131
+ };
132
+ __decorate([
133
+ Transactional({ propagation: "mandatory" })
134
+ ], PermissionAuthorityLock.prototype, "acquire", null);
135
+ PermissionAuthorityLock = __decorate([
136
+ Injectable(),
137
+ __param(0, Inject(KernelDb)),
138
+ __param(1, Inject(TransactionHost)),
139
+ __param(2, Inject(XactLock))
140
+ ], PermissionAuthorityLock);
141
+ export { PermissionAuthorityLock };
142
+ /** The current transaction holds this authority lock (exclusively when asked); else throws. */
143
+ export function assertAuthorityHeld(kind, id, exclusive = false) {
144
+ const held = currentStore()?.permissionLocks?.get(keyOf(kind, id));
145
+ if (!held || (exclusive && held !== "exclusive"))
146
+ throw new Error("The matching authority lock is required");
147
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The writers that narrow or revoke authority (ceiling writes, transitions and their locks) without
3
+ * the config publication: for modules that only revoke (an account disabled) and whose context
4
+ * has no kernel config, such as the Redis-free CLI and contexts over a borrowed pool.
5
+ */
6
+ export declare class PermissionCeilingWritesModule {
7
+ }
8
+ export declare class PermissionAuthorityModule {
9
+ }
@@ -0,0 +1,55 @@
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 { EventLogModule } from "../conversations/event-log.js";
9
+ import { PermissionAuthorityEpochStore } from "./permission-authority-epochs.js";
10
+ import { PermissionAuthorityLock } from "./permission-authority-lock.js";
11
+ import { PermissionCeilingWrites } from "./permission-ceiling-writes.js";
12
+ import { PermissionConfigPublication } from "./permission-config-publication.js";
13
+ import { PermissionInstanceWrites } from "./permission-instance-writes.js";
14
+ import { PermissionRuntimeReports } from "./permission-runtime-reports.js";
15
+ import { PermissionTransitions } from "./permission-transitions.js";
16
+ /**
17
+ * The writers that narrow or revoke authority (ceiling writes, transitions and their locks) without
18
+ * the config publication: for modules that only revoke (an account disabled) and whose context
19
+ * has no kernel config, such as the Redis-free CLI and contexts over a borrowed pool.
20
+ */
21
+ let PermissionCeilingWritesModule = class PermissionCeilingWritesModule {
22
+ };
23
+ PermissionCeilingWritesModule = __decorate([
24
+ Module({
25
+ imports: [EventLogModule],
26
+ providers: [
27
+ PermissionTransitions,
28
+ PermissionCeilingWrites,
29
+ PermissionAuthorityLock,
30
+ PermissionAuthorityEpochStore,
31
+ ],
32
+ exports: [
33
+ PermissionTransitions,
34
+ PermissionCeilingWrites,
35
+ PermissionAuthorityLock,
36
+ PermissionAuthorityEpochStore,
37
+ ],
38
+ })
39
+ ], PermissionCeilingWritesModule);
40
+ export { PermissionCeilingWritesModule };
41
+ let PermissionAuthorityModule = class PermissionAuthorityModule {
42
+ };
43
+ PermissionAuthorityModule = __decorate([
44
+ Module({
45
+ imports: [EventLogModule, PermissionCeilingWritesModule],
46
+ providers: [PermissionInstanceWrites, PermissionRuntimeReports, PermissionConfigPublication],
47
+ exports: [
48
+ PermissionCeilingWritesModule,
49
+ PermissionInstanceWrites,
50
+ PermissionRuntimeReports,
51
+ PermissionConfigPublication,
52
+ ],
53
+ })
54
+ ], PermissionAuthorityModule);
55
+ export { PermissionAuthorityModule };
@@ -0,0 +1,18 @@
1
+ import type { SandboxPermissionSupport, SandboxProvider } from "@capybara-hq/plugin-sdk";
2
+ /** Read models never provision or probe. Runtime activation will persist provenance-bound reports. */
3
+ export type PermissionAvailability = {
4
+ state: "supported";
5
+ report: SandboxPermissionSupport;
6
+ } | {
7
+ state: "unsupported";
8
+ reason: string;
9
+ } | {
10
+ state: "unprobed";
11
+ reason: string;
12
+ };
13
+ export declare const unprobedPermissionAvailability: () => PermissionAvailability;
14
+ /** Method presence is only an unknown runtime candidate, never evidence of enforcement support.
15
+ * No capability probe or lifecycle operation runs here, even for an empty or suspended device.
16
+ * Task 6 records provenance-bound runtime reports before user execution can be admitted.
17
+ */
18
+ export declare function permissionAvailabilityFor(provider: SandboxProvider | undefined): PermissionAvailability;
@@ -0,0 +1,19 @@
1
+ export const unprobedPermissionAvailability = () => ({
2
+ state: "unprobed",
3
+ reason: "Checked when this device starts",
4
+ });
5
+ /** Method presence is only an unknown runtime candidate, never evidence of enforcement support.
6
+ * No capability probe or lifecycle operation runs here, even for an empty or suspended device.
7
+ * Task 6 records provenance-bound runtime reports before user execution can be admitted.
8
+ */
9
+ export function permissionAvailabilityFor(provider) {
10
+ if (!provider ||
11
+ typeof provider.operation !== "function" ||
12
+ typeof provider.permissionSupport !== "function" ||
13
+ typeof provider.revokeOperation !== "function")
14
+ return {
15
+ state: "unsupported",
16
+ reason: "This provider does not implement permission-scoped operations; update its plugin or device program",
17
+ };
18
+ return unprobedPermissionAvailability();
19
+ }