@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
@@ -0,0 +1,242 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { Kysely, PostgresDialect } from "kysely";
3
+ import pg from "pg";
4
+ import { pgConnectOptions } from "../../db/pool.js";
5
+ /** Server-side bound on one statement of the owned startup session. */
6
+ export const STARTUP_STATEMENT_TIMEOUT_MS = 500;
7
+ /** Server-side bound on one lock wait of the owned startup session. */
8
+ export const STARTUP_LOCK_TIMEOUT_MS = 500;
9
+ /**
10
+ * Server-side bound on the gap between two statements of the owned startup transaction. A client
11
+ * pause (OS scheduling, GC, CPU throttling) counts against it, so it is longer than the statement
12
+ * and lock bounds; it still bounds how long a stalled process can hold the platform permission
13
+ * lock (activation design spec, "Timeouts precede all SQL").
14
+ */
15
+ export const STARTUP_IDLE_IN_TRANSACTION_TIMEOUT_MS = 5_000;
16
+ /** Deliberately safe diagnostics: driver errors may contain connection or statement inputs. */
17
+ export class StartupActivationError extends Error {
18
+ outcome;
19
+ constructor(outcome) {
20
+ super(`Permission configuration startup transaction ${outcome}; retry the same resolved configuration and expected hash`);
21
+ this.outcome = outcome;
22
+ this.name = "StartupActivationError";
23
+ }
24
+ }
25
+ const startup = new AsyncLocalStorage();
26
+ export function startupActivationGuard() {
27
+ return startup.getStore();
28
+ }
29
+ const internal = (client) => client;
30
+ /** Bounded await; timeout never means the remote transaction rolled back. */
31
+ async function within(promise, deadline) {
32
+ const ms = deadline - performance.now();
33
+ if (ms <= 0) {
34
+ void promise.catch(() => { });
35
+ return undefined;
36
+ }
37
+ let timer;
38
+ try {
39
+ return await Promise.race([
40
+ promise.then((value) => ({ value })),
41
+ new Promise((resolve) => {
42
+ timer = setTimeout(() => resolve(undefined), ms);
43
+ }),
44
+ ]);
45
+ }
46
+ finally {
47
+ clearTimeout(timer);
48
+ }
49
+ }
50
+ async function cancelSession(connectionString, identity, deadline) {
51
+ if (deadline <= performance.now())
52
+ return;
53
+ const client = new pg.Client({ connectionString });
54
+ const { connection, connectionParameters } = internal(client);
55
+ const closed = new Promise((resolve) => {
56
+ connection.stream.once("close", () => resolve());
57
+ connection.stream.once("error", () => resolve());
58
+ connection.once("error", () => resolve());
59
+ connection.once("connect", () => {
60
+ connection.cancel(identity.pid, identity.key);
61
+ });
62
+ });
63
+ try {
64
+ if (connectionParameters.host.startsWith("/"))
65
+ connection.connect(`${connectionParameters.host}/.s.PGSQL.${connectionParameters.port}`);
66
+ else
67
+ connection.connect(connectionParameters.port, connectionParameters.host);
68
+ await within(closed, deadline);
69
+ }
70
+ finally {
71
+ connection.stream.destroy();
72
+ await within(closed, deadline);
73
+ }
74
+ }
75
+ /** A one-use owned session. Neither this pool nor its client can reach the shared pool. */
76
+ export async function runOwnedStartupActivation(
77
+ // biome-ignore lint/suspicious/noExplicitAny: TransactionHost provides the schema view
78
+ fn, options) {
79
+ const workDeadline = performance.now() + Math.max(0, Math.min(30_000, options.remainingMs()));
80
+ const idleMs = options.idleInTransactionTimeoutMs ?? STARTUP_IDLE_IN_TRANSACTION_TIMEOUT_MS;
81
+ let cleanupDeadline = workDeadline;
82
+ const cleanupControl = new AsyncLocalStorage();
83
+ let transaction;
84
+ let closed = false;
85
+ let committed = false;
86
+ let commitDispatched = false;
87
+ let connected = false;
88
+ let released = false;
89
+ let client;
90
+ let identity;
91
+ let rawQuery;
92
+ let tail = Promise.resolve();
93
+ let rejectAborted;
94
+ const aborted = new Promise((_, reject) => {
95
+ rejectAborted = reject;
96
+ });
97
+ // A synchronous entry failure can occur before Promise.race installs its handler.
98
+ void aborted.catch(() => { });
99
+ const close = () => {
100
+ if (closed)
101
+ return;
102
+ closed = true;
103
+ cleanupDeadline = performance.now() + Math.max(0, Math.min(1_500, options.remainingMs()));
104
+ rejectAborted(new StartupActivationError(commitDispatched ? "uncertain" : "aborted"));
105
+ if (!connected && client)
106
+ internal(client).connection.stream.destroy();
107
+ };
108
+ const guard = {
109
+ check() {
110
+ if (options.signal.aborted || performance.now() >= workDeadline || options.remainingMs() <= 0)
111
+ close();
112
+ if (closed)
113
+ throw new StartupActivationError(commitDispatched ? "uncertain" : "aborted");
114
+ },
115
+ };
116
+ const timer = setTimeout(close, Math.max(1, workDeadline - performance.now()));
117
+ options.signal.addEventListener("abort", close, { once: true });
118
+ // pg parses connectionString after object options. Pin defaults on the parsed parameters,
119
+ // before the first handshake; no SQL is needed to establish the protected session defaults.
120
+ class OwnedClient extends pg.Client {
121
+ constructor(config = {}) {
122
+ super(config);
123
+ client = this;
124
+ const params = internal(this).connectionParameters;
125
+ params.options = `${params.options ?? ""} -c statement_timeout=${STARTUP_STATEMENT_TIMEOUT_MS} -c lock_timeout=${STARTUP_LOCK_TIMEOUT_MS} -c idle_in_transaction_session_timeout=${idleMs}`;
126
+ // pg also sends direct startup GUC fields after options, so pin both DSN spellings.
127
+ params.statement_timeout = STARTUP_STATEMENT_TIMEOUT_MS;
128
+ params.lock_timeout = STARTUP_LOCK_TIMEOUT_MS;
129
+ params.idle_in_transaction_session_timeout = idleMs;
130
+ // A client read timeout rejects before server completion and would advance our tail
131
+ // into pg's unguarded queue. Server timeouts and our owned deadline bound this session.
132
+ params.query_timeout = 0;
133
+ this.on("error", () => { });
134
+ const dispatch = super.query.bind(this);
135
+ rawQuery = dispatch;
136
+ // Kysely calls only the promise text+parameters form. Keep pg's own queue empty:
137
+ // every dispatch checks the guard after dequeue, immediately before sending SQL.
138
+ this.query = ((text, values) => {
139
+ const ownerRollback = cleanupControl.getStore() === true && text === "rollback";
140
+ const pending = tail.then(() => {
141
+ if (!ownerRollback)
142
+ guard.check();
143
+ if (text === "commit")
144
+ commitDispatched = true;
145
+ return dispatch(text, values);
146
+ });
147
+ tail = pending.catch(() => { });
148
+ return pending;
149
+ });
150
+ }
151
+ }
152
+ const pool = new pg.Pool({
153
+ connectionString: options.connectionString,
154
+ max: 1,
155
+ ...pgConnectOptions({
156
+ connectTimeoutMs: Math.max(1, Math.min(options.connectTimeoutMs ?? 30_000, workDeadline - performance.now(), options.remainingMs())),
157
+ }),
158
+ keepAlive: true,
159
+ Client: OwnedClient,
160
+ });
161
+ pool.on("error", () => { });
162
+ pool.on("release", () => {
163
+ released = true;
164
+ });
165
+ pool.on("connect", (owned) => {
166
+ connected = true;
167
+ const original = internal(owned);
168
+ identity = Object.freeze({ pid: original.processID, key: original.secretKey });
169
+ if (closed)
170
+ original.connection.stream.destroy();
171
+ });
172
+ const db = new Kysely({ dialect: new PostgresDialect({ pool }) });
173
+ let rollbackConfirmed = false;
174
+ try {
175
+ guard.check();
176
+ return await startup.run(guard, async () => {
177
+ const work = (async () => {
178
+ const trx = await db.startTransaction().execute();
179
+ transaction = trx;
180
+ guard.check();
181
+ const result = await fn(trx);
182
+ guard.check();
183
+ await trx.commit().execute();
184
+ committed = true;
185
+ return result;
186
+ })();
187
+ return await Promise.race([work, aborted]);
188
+ });
189
+ }
190
+ catch (error) {
191
+ close();
192
+ const deadline = cleanupDeadline;
193
+ if (identity && !committed)
194
+ await cancelSession(options.connectionString, identity, Math.min(deadline, performance.now() + 500));
195
+ // Only this fixed owner-private command bypasses the closed dispatch gate. Domain work
196
+ // retains the closed guard, including captured transactions and late ALS descendants.
197
+ if (!commitDispatched && connected && rawQuery) {
198
+ try {
199
+ const settled = await within(tail, deadline);
200
+ if (settled) {
201
+ const current = transaction;
202
+ const rollback = current
203
+ ? cleanupControl.run(true, () => current.rollback().execute())
204
+ : rawQuery("rollback");
205
+ rollbackConfirmed = (await within(rollback, deadline)) !== undefined;
206
+ }
207
+ }
208
+ catch {
209
+ /* Disposal below closes a failed rollback session. */
210
+ }
211
+ }
212
+ if (commitDispatched || (connected && !rollbackConfirmed))
213
+ throw new StartupActivationError("uncertain");
214
+ // Preserve safe domain errors such as a fingerprint CAS conflict. Driver errors carry
215
+ // SQL/connection details and are replaced with a bounded outcome diagnostic.
216
+ if (error instanceof Error &&
217
+ ["PermissionConfigActivationConflict", "SandboxScopeDeniedError"].includes(error.name))
218
+ throw error;
219
+ throw new StartupActivationError(rollbackConfirmed ? "rolled-back" : "aborted");
220
+ }
221
+ finally {
222
+ close();
223
+ clearTimeout(timer);
224
+ options.signal.removeEventListener("abort", close);
225
+ // Destroy the owned socket, including a half-authenticated or busy client, before ending
226
+ // its private pool. Never wait indefinitely for pool.end() on a checked-out connection.
227
+ if (client) {
228
+ const stream = internal(client).connection.stream;
229
+ const ended = new Promise((resolve) => {
230
+ if (stream.closed)
231
+ resolve();
232
+ else
233
+ stream.once("close", () => resolve());
234
+ });
235
+ stream.destroy();
236
+ if (connected && !released && "release" in client)
237
+ client.release(true);
238
+ await within(ended, cleanupDeadline);
239
+ }
240
+ await within(db.destroy().catch(() => { }), cleanupDeadline);
241
+ }
242
+ }
@@ -1,5 +1,6 @@
1
1
  import type { AccessMode, IsolationLevel, Kysely, Transaction } from "kysely";
2
2
  import type { KernelLogger } from "../../log.js";
3
+ import { type StartupActivationOptions } from "./startup-activation-transaction.js";
3
4
  type AfterCommitHook = () => void | Promise<void>;
4
5
  interface TransactionStore {
5
6
  pool: Kysely<any>;
@@ -8,6 +9,8 @@ interface TransactionStore {
8
9
  hooks: AfterCommitHook[];
9
10
  /** Set once the transaction settled: continuations that outlive it must not use it. */
10
11
  done: boolean;
12
+ /** Transaction-local advisory lock claims; never authority cached across requests. */
13
+ permissionLocks?: Map<string, "shared" | "exclusive">;
11
14
  /**
12
15
  * How a fence admitted it (`withTransactionFence`), once the fence ran; undefined when no fence
13
16
  * admitted it (no fence in context, or read only).
@@ -18,12 +21,54 @@ interface TransactionStore {
18
21
  export interface FenceAdmission {
19
22
  /** The transaction asked for shared admission (`admission: "shared"`). */
20
23
  shared: boolean;
24
+ /**
25
+ * The ordered authority prelude ({@link withTransactionFencePrelude}; never with `shared`): the
26
+ * fence runs it exactly once, after its org-level admission (the org row) and before any
27
+ * conversation row, the place of the permission authority locks in the global lock order.
28
+ */
29
+ prelude?: () => Promise<void>;
21
30
  }
22
31
  /** The mode a fence admitted a transaction in (a fence returning nothing admits exclusively). */
23
32
  export type AdmissionMode = "shared" | "exclusive";
24
33
  /** A fence: checks the caller's authority, takes its admission locks and says in which mode. */
25
34
  export type TransactionFence = (admission: FenceAdmission) => Promise<AdmissionMode | undefined | void>;
26
35
  export declare function withTransactionFence<T>(fence: TransactionFence, fn: () => Promise<T>): Promise<T>;
36
+ /**
37
+ * Whether a fence is installed in this context (a claimed run's `RunExecution.withClaim`). A writer
38
+ * whose transaction must hold the org row before its permission authority locks requires it: only
39
+ * an inherited fence runs the ordered prelude after the org row.
40
+ */
41
+ export declare function hasTransactionFence(): boolean;
42
+ /**
43
+ * Install once before opening a transaction: the ordered authority (the permission authority
44
+ * locks) runs inside the inherited run fence, after its org row and before its conversation rows.
45
+ * The global lock order (`OrgLock`): org admission -> org row -> membership -> device row -> super
46
+ * admin lock -> permission authority locks (platform, org, device, root) -> root conversation ->
47
+ * conversation; a prelude may take the locks before the permission locks too. Offboarding and
48
+ * the org writers hold the org row when they take an org permission lock exclusively, so a
49
+ * prelude that took its shared permission locks before the fence's org row could deadlock with
50
+ * them.
51
+ * Existing transactions are rejected because their row locks cannot be retroactively reordered.
52
+ * The inherited fence remains intact; this does not expose an unfenced callback or dispatch API.
53
+ */
54
+ export declare function withTransactionFencePrelude<T>(prelude: () => Promise<void>, fn: () => Promise<T>): Promise<T>;
55
+ /**
56
+ * A writer whose permission authority locks (with the locks it takes before them: its org row, a
57
+ * membership, its device row, the super admin lock) are its `prelude`, and whose writes are `fn`,
58
+ * which opens at most one transaction. With no transaction open, {@link withTransactionFencePrelude}:
59
+ * inside a run's fence (a Platform operation in a tool step) the prelude runs after the fence's org
60
+ * row and before its conversation rows; with no fence (an HTTP request) it runs first in the
61
+ * transaction `fn` opens, the order the writer always had. Joining a caller's transaction the
62
+ * prelude runs inline at once: the caller owns that transaction's order, and a fenced caller's new
63
+ * permission lock is refused (`PermissionAuthorityLock`). `fn` re-checks under the locks what the
64
+ * prelude read without them, and may name the same, already held, locks again.
65
+ *
66
+ * With no fence the transaction is still admitted by the prelude's own fence: its body runs as a
67
+ * fenced transaction (`admission` exclusive, `inFencedTransaction()` true), so
68
+ * `OrgLock.lockForRemoval` refuses there and the permission lock guard applies to it: every
69
+ * permission lock its body needs belongs in the prelude.
70
+ */
71
+ export declare function withOrderedLocks<T>(prelude: () => Promise<void>, fn: () => Promise<T>): Promise<T>;
27
72
  export type Propagation = "required" | "requires_new" | "mandatory";
28
73
  export interface TransactionOptions {
29
74
  /**
@@ -71,6 +116,8 @@ export declare class TransactionHost {
71
116
  constructor(pool: Kysely<any>, log: KernelLogger);
72
117
  /** The transaction of the current async context on this pool, if any. */
73
118
  current(): Transaction<any> | undefined;
119
+ /** Startup-only bounded owned session; all ordinary transaction/fence semantics are retained. */
120
+ runStartupActivation<T>(fn: () => Promise<T>, options: StartupActivationOptions): Promise<T>;
74
121
  /**
75
122
  * Runs `fn` in a transaction: a throw rolls back, a return commits. REQUIRED (default) joins the
76
123
  * transaction in context; `requires_new` always opens its own on the pool; `mandatory` joins the
@@ -12,6 +12,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
13
  import { Inject, Injectable } from "@nestjs/common";
14
14
  import { KERNEL_LOGGER, KERNEL_POOL } from "../tokens.js";
15
+ import { runOwnedStartupActivation, startupActivationGuard, } from "./startup-activation-transaction.js";
15
16
  /** One store for the process: `afterCommit` (a free function) reads it without a host instance. */
16
17
  const storage = new AsyncLocalStorage();
17
18
  /** A caller's execution authority, checked inside every new transaction before domain writes. */
@@ -19,6 +20,79 @@ const fences = new AsyncLocalStorage();
19
20
  export function withTransactionFence(fence, fn) {
20
21
  return fences.run(fence, fn);
21
22
  }
23
+ /**
24
+ * Whether a fence is installed in this context (a claimed run's `RunExecution.withClaim`). A writer
25
+ * whose transaction must hold the org row before its permission authority locks requires it: only
26
+ * an inherited fence runs the ordered prelude after the org row.
27
+ */
28
+ export function hasTransactionFence() {
29
+ return fences.getStore() !== undefined;
30
+ }
31
+ /**
32
+ * Install once before opening a transaction: the ordered authority (the permission authority
33
+ * locks) runs inside the inherited run fence, after its org row and before its conversation rows.
34
+ * The global lock order (`OrgLock`): org admission -> org row -> membership -> device row -> super
35
+ * admin lock -> permission authority locks (platform, org, device, root) -> root conversation ->
36
+ * conversation; a prelude may take the locks before the permission locks too. Offboarding and
37
+ * the org writers hold the org row when they take an org permission lock exclusively, so a
38
+ * prelude that took its shared permission locks before the fence's org row could deadlock with
39
+ * them.
40
+ * Existing transactions are rejected because their row locks cannot be retroactively reordered.
41
+ * The inherited fence remains intact; this does not expose an unfenced callback or dispatch API.
42
+ */
43
+ export function withTransactionFencePrelude(prelude, fn) {
44
+ if (liveStore())
45
+ throw new Error("An ordered fence prelude must be installed before opening a transaction");
46
+ const inherited = fences.getStore();
47
+ let entered = false;
48
+ return withTransactionFence(async () => {
49
+ if (entered)
50
+ throw new Error("An ordered fence prelude permits only one new transaction");
51
+ entered = true;
52
+ if (!inherited) {
53
+ await prelude();
54
+ return "exclusive";
55
+ }
56
+ let ran = false;
57
+ // the inherited fence admits exclusively: the prelude takes org-level locks, which a shared
58
+ // admission (no org row) must never take
59
+ const mode = await inherited({
60
+ shared: false,
61
+ prelude: async () => {
62
+ if (ran)
63
+ throw new Error("The ordered fence prelude runs once");
64
+ ran = true;
65
+ await prelude();
66
+ },
67
+ });
68
+ if (!ran)
69
+ throw new Error("The inherited fence did not run the ordered authority prelude");
70
+ return mode || "exclusive";
71
+ }, fn);
72
+ }
73
+ /**
74
+ * A writer whose permission authority locks (with the locks it takes before them: its org row, a
75
+ * membership, its device row, the super admin lock) are its `prelude`, and whose writes are `fn`,
76
+ * which opens at most one transaction. With no transaction open, {@link withTransactionFencePrelude}:
77
+ * inside a run's fence (a Platform operation in a tool step) the prelude runs after the fence's org
78
+ * row and before its conversation rows; with no fence (an HTTP request) it runs first in the
79
+ * transaction `fn` opens, the order the writer always had. Joining a caller's transaction the
80
+ * prelude runs inline at once: the caller owns that transaction's order, and a fenced caller's new
81
+ * permission lock is refused (`PermissionAuthorityLock`). `fn` re-checks under the locks what the
82
+ * prelude read without them, and may name the same, already held, locks again.
83
+ *
84
+ * With no fence the transaction is still admitted by the prelude's own fence: its body runs as a
85
+ * fenced transaction (`admission` exclusive, `inFencedTransaction()` true), so
86
+ * `OrgLock.lockForRemoval` refuses there and the permission lock guard applies to it: every
87
+ * permission lock its body needs belongs in the prelude.
88
+ */
89
+ export async function withOrderedLocks(prelude, fn) {
90
+ if (liveStore()) {
91
+ await prelude();
92
+ return fn();
93
+ }
94
+ return withTransactionFencePrelude(prelude, fn);
95
+ }
22
96
  /** Logger for hook failures outside a transaction; set by `TransactionHost`, console until then. */
23
97
  let hookLog = {
24
98
  error: (msg, fields) => console.error(`[afterCommit] ${msg}`, fields ?? ""),
@@ -26,6 +100,7 @@ let hookLog = {
26
100
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
27
101
  /** Queues `fn` on the current live root transaction; with none open, runs it at once. */
28
102
  export function queueAfterCommit(fn) {
103
+ startupActivationGuard()?.check();
29
104
  const store = liveStore();
30
105
  if (store) {
31
106
  store.hooks.push(fn);
@@ -87,9 +162,49 @@ let TransactionHost = class TransactionHost {
87
162
  /** The transaction of the current async context on this pool, if any. */
88
163
  // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
89
164
  current() {
165
+ const guard = startupActivationGuard();
166
+ guard?.check();
90
167
  const store = liveStore();
168
+ if (guard && store?.pool !== this.pool)
169
+ throw new Error("Startup activation cannot fall back to the shared pool");
91
170
  return store?.pool === this.pool ? store.trx : undefined;
92
171
  }
172
+ /** Startup-only bounded owned session; all ordinary transaction/fence semantics are retained. */
173
+ async runStartupActivation(fn, options) {
174
+ startupActivationGuard()?.check();
175
+ if (liveStore() || startupActivationGuard())
176
+ throw new Error("Startup activation refuses an existing transaction");
177
+ const hooks = [];
178
+ let store;
179
+ let result;
180
+ try {
181
+ result = await runOwnedStartupActivation(async (trx) => {
182
+ const own = { pool: this.pool, trx, hooks, done: false };
183
+ store = own;
184
+ return storage.run(own, async () => {
185
+ const fence = fences.getStore();
186
+ if (fence)
187
+ own.admission = (await fence({ shared: false })) || "exclusive";
188
+ return fn();
189
+ });
190
+ }, options);
191
+ }
192
+ finally {
193
+ if (store)
194
+ store.done = true;
195
+ }
196
+ for (const hook of hooks) {
197
+ try {
198
+ // This continuation belongs to the original caller, outside the helper's ALS guard.
199
+ // Late transaction descendants retain that guard permanently.
200
+ await runOutsideTransaction(hook);
201
+ }
202
+ catch (e) {
203
+ this.log.error("afterCommit hook failed", { error: errMsg(e) });
204
+ }
205
+ }
206
+ return result;
207
+ }
93
208
  /**
94
209
  * Runs `fn` in a transaction: a throw rolls back, a return commits. REQUIRED (default) joins the
95
210
  * transaction in context; `requires_new` always opens its own on the pool; `mandatory` joins the
@@ -97,7 +212,11 @@ let TransactionHost = class TransactionHost {
97
212
  * root's COMMIT, outside any transaction, and are dropped on rollback.
98
213
  */
99
214
  async run(fn, opts = {}) {
215
+ const guard = startupActivationGuard();
216
+ guard?.check();
100
217
  const propagation = opts.propagation ?? "required";
218
+ if (guard && propagation === "requires_new")
219
+ throw new Error("Nested requires_new is refused during startup activation");
101
220
  if (propagation === "mandatory") {
102
221
  if (!this.current()) {
103
222
  throw new Error('propagation "mandatory": no transaction in context (the caller must open one and ' +
@@ -12,6 +12,7 @@ export declare class XactLock {
12
12
  private readonly db;
13
13
  readonly txHost: TransactionHost;
14
14
  constructor(db: KernelDb, txHost: TransactionHost);
15
+ shared(key: string): Promise<void>;
15
16
  /** Takes the lock named `key` until the caller's transaction ends (waits while another holds it). */
16
17
  lock(key: string): Promise<void>;
17
18
  /**
@@ -27,6 +27,9 @@ let XactLock = class XactLock {
27
27
  this.db = db;
28
28
  this.txHost = txHost;
29
29
  }
30
+ async shared(key) {
31
+ await sql `SELECT pg_advisory_xact_lock_shared(hashtext(${key}))`.execute(this.db.db);
32
+ }
30
33
  /** Takes the lock named `key` until the caller's transaction ends (waits while another holds it). */
31
34
  async lock(key) {
32
35
  assertNotSharedAdmission(`the advisory lock ${key}`);
@@ -51,6 +54,9 @@ let XactLock = class XactLock {
51
54
  await sql `SELECT pg_advisory_xact_lock(hashtext(${ORG_ADMISSION_SPACE}), hashtext(${orgId}))`.execute(this.db.db);
52
55
  }
53
56
  };
57
+ __decorate([
58
+ Transactional({ propagation: "mandatory" })
59
+ ], XactLock.prototype, "shared", null);
54
60
  __decorate([
55
61
  Transactional({ propagation: "mandatory" })
56
62
  ], XactLock.prototype, "lock", null);
@@ -19,6 +19,45 @@ export interface OutboxJobSpec {
19
19
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
20
20
  */
21
21
  export declare const OUTBOX_JOBS: {
22
+ readonly "permission-approval-recheck": {
23
+ readonly queue: "cap-kernel-maintenance";
24
+ readonly idempotent: "Reads the current revision and resumes only waiting runs without another pending wait; queued runs are unchanged.";
25
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
26
+ readonly opts: {
27
+ readonly attempts: 5;
28
+ readonly backoff: {
29
+ readonly type: "exponential";
30
+ readonly delay: 5000;
31
+ };
32
+ readonly removeOnComplete: true;
33
+ };
34
+ };
35
+ readonly "sandbox-operation-reconcile": {
36
+ readonly queue: "cap-kernel-maintenance";
37
+ readonly idempotent: "records unknown outcomes and leaves execution to the current run/tool claim; never dispatches a native operation";
38
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
39
+ readonly opts: {
40
+ readonly attempts: 5;
41
+ readonly backoff: {
42
+ readonly type: "exponential";
43
+ readonly delay: 5000;
44
+ };
45
+ readonly removeOnComplete: true;
46
+ };
47
+ };
48
+ readonly "sandbox-operation-revoke": {
49
+ readonly queue: "cap-kernel-maintenance";
50
+ readonly idempotent: "persists an operation tombstone and acknowledges only a successful idempotent provider revoke";
51
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
52
+ readonly opts: {
53
+ readonly attempts: 10;
54
+ readonly backoff: {
55
+ readonly type: "exponential";
56
+ readonly delay: 5000;
57
+ };
58
+ readonly removeOnComplete: true;
59
+ };
60
+ };
22
61
  readonly run: {
23
62
  readonly queue: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs"];
24
63
  readonly idempotent: "the run worker starts only a run in `queued` state for this job's runId; a finished run's job only repeats the idempotent post-run ensureRun, a waiting run's does nothing";
@@ -21,6 +21,24 @@ const SCOPE_JOB_OPTS = {
21
21
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
22
22
  */
23
23
  export const OUTBOX_JOBS = {
24
+ "permission-approval-recheck": {
25
+ queue: "cap-kernel-maintenance",
26
+ idempotent: "Reads the current revision and resumes only waiting runs without another pending wait; queued runs are unchanged.",
27
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
28
+ opts: { attempts: 5, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
29
+ },
30
+ "sandbox-operation-reconcile": {
31
+ queue: "cap-kernel-maintenance",
32
+ idempotent: "records unknown outcomes and leaves execution to the current run/tool claim; never dispatches a native operation",
33
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
34
+ opts: { attempts: 5, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
35
+ },
36
+ "sandbox-operation-revoke": {
37
+ queue: "cap-kernel-maintenance",
38
+ idempotent: "persists an operation tombstone and acknowledges only a successful idempotent provider revoke",
39
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
40
+ opts: { attempts: 10, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
41
+ },
24
42
  // `runtime/run-jobs.ts` RUN_JOB: one name on both run queues (a sub-agent's runs go to the
25
43
  // sub-agent queue), under the job ids `runJobId` builds and, for a waiting run's resume
26
44
  // (`RunResume.resumeIn`), `resumeJobId`
@@ -43,6 +43,7 @@ import { PlatformOpsModule } from "./platform/platform-ops.module.js";
43
43
  import { GatewayModule } from "./roles/gateway.module.js";
44
44
  import { WorkerModule } from "./roles/worker.module.js";
45
45
  import { UsageReportModule } from "./runtime/usage-report.js";
46
+ import { PermissionAuthorityModule } from "./sandbox/permission-authority.module.js";
46
47
  /**
47
48
  * Global: the options the application was built with (`KERNEL_APP_OPTIONS`) and its `overrides`,
48
49
  * the test seams (`KernelOverride`: values for the named seam tokens the domain modules
@@ -114,6 +115,7 @@ let KernelModule = KernelModule_1 = class KernelModule {
114
115
  // KernelLifecycle's setup check, the extension host it drives, the catalog it syncs and
115
116
  // the producers its stop closes on every role (titles, usage.report, channel deliveries)
116
117
  IdentityModule,
118
+ PermissionAuthorityModule,
117
119
  ExtensionsModule,
118
120
  CatalogModule,
119
121
  TitlesModule,
@@ -26,6 +26,7 @@ import type { KernelLogger } from "../log.js";
26
26
  import { GatewayRole } from "../roles/gateway-role.js";
27
27
  import { WorkerRole } from "../roles/worker-role.js";
28
28
  import { UsageReporter } from "../runtime/usage-report.js";
29
+ import { PermissionConfigPublication } from "../sandbox/permission-config-publication.js";
29
30
  /**
30
31
  * The stop phase budgets. Each phase waits `min(its budget, what is left of the total)`, where the
31
32
  * total is `STOP_TIMEOUT_MS` (30 s, `GracefulShutdown`) counted from the moment the shutdown
@@ -62,6 +63,7 @@ export declare const STOP_BUDGET_MS: {
62
63
  * (`onApplicationShutdown`, global modules run last).
63
64
  */
64
65
  export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeApplicationShutdown, OnApplicationShutdown {
66
+ private readonly permissionConfig;
65
67
  private readonly accounts;
66
68
  private readonly configService;
67
69
  readonly log: KernelLogger;
@@ -101,7 +103,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
101
103
  private bootstrapCarry;
102
104
  /** The packages the first bootstrap pass obtained, so the second downloads nothing again. */
103
105
  private bootstrapPackages;
104
- constructor(accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, marketplaces: MarketplacesService, pluginImport: PluginImport, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
106
+ constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, marketplaces: MarketplacesService, pluginImport: PluginImport, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
105
107
  /** The kernel HTTP application (set up by `buildKernelApp` before `init()`). */
106
108
  get http(): KernelHttpApp;
107
109
  attachHttp(http: KernelHttpApp): void;