@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
@@ -37,6 +37,7 @@ import { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA } from "../kernel.js";
37
37
  import { GatewayRole } from "../roles/gateway-role.js";
38
38
  import { WorkerRole } from "../roles/worker-role.js";
39
39
  import { UsageReporter } from "../runtime/usage-report.js";
40
+ import { PermissionConfigPublication } from "../sandbox/permission-config-publication.js";
40
41
  import { sandboxConfigWarnings } from "../sandbox/sandbox.service.js";
41
42
  import { KERNEL_APP_OPTIONS } from "./tokens.js";
42
43
  /**
@@ -82,6 +83,7 @@ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
82
83
  * (`onApplicationShutdown`, global modules run last).
83
84
  */
84
85
  let KernelLifecycle = class KernelLifecycle {
86
+ permissionConfig;
85
87
  accounts;
86
88
  configService;
87
89
  log;
@@ -121,7 +123,7 @@ let KernelLifecycle = class KernelLifecycle {
121
123
  bootstrapCarry;
122
124
  /** The packages the first bootstrap pass obtained, so the second downloads nothing again. */
123
125
  bootstrapPackages;
124
- constructor(accounts, configService, log, options,
126
+ constructor(permissionConfig, accounts, configService, log, options,
125
127
  // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
126
128
  pool, redis, kdb, shutdown, host, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, marketplaces, pluginImport, bus,
127
129
  // the producers closed on every role (their consumers are the worker role's)
@@ -131,6 +133,7 @@ let KernelLifecycle = class KernelLifecycle {
131
133
  // The role modules' parts: a role module is imported only when `roles` names it, so each is
132
134
  // present exactly when its role is (checked at the start)
133
135
  worker, gateway) {
136
+ this.permissionConfig = permissionConfig;
134
137
  this.accounts = accounts;
135
138
  this.configService = configService;
136
139
  this.log = log;
@@ -203,6 +206,24 @@ let KernelLifecycle = class KernelLifecycle {
203
206
  // In flight for the stop: aborted when the shutdown begins, which then waits for its session to end
204
207
  await this.shutdown.trackInFlight(migrate(config.db.url, { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR }, { connectTimeoutMs: config.db.connectTimeoutMs, signal: this.shutdown.signal }));
205
208
  this.checkpoint();
209
+ const publication = await this.shutdown.trackInFlight(this.permissionConfig.initialize({
210
+ ...(opts.permissionConfigActivation !== undefined && {
211
+ activation: opts.permissionConfigActivation,
212
+ }),
213
+ startup: { signal: this.shutdown.signal, remainingMs: () => this.shutdown.remainingMs() },
214
+ }));
215
+ if (publication.outcome === "activated" || publication.outcome === "already-active")
216
+ this.log.info("permission configuration activation committed", {
217
+ outcome: publication.outcome,
218
+ activeHash: publication.activeHash,
219
+ });
220
+ else if (publication.outcome === "mismatch")
221
+ this.log.warn("Permission configuration differs from the active deployment configuration", {
222
+ activeHash: publication.activeHash,
223
+ candidateHash: publication.candidateHash,
224
+ command: `capybara start --activate-permission-config ${publication.activeHash}`,
225
+ });
226
+ this.checkpoint();
206
227
  // official 清单来源按配置同步(幂等;每个副本启动时都做)
207
228
  await this.marketplaces.syncOfficialFromConfig();
208
229
  // The bootstrap plugins (spec §7), once per manifest across replicas (the Redis lock
@@ -266,7 +287,12 @@ let KernelLifecycle = class KernelLifecycle {
266
287
  }
267
288
  if (opts.source?.watch) {
268
289
  // 热更新:重新校验;只应用 hot 字段,其余变化 warn 并列出需重启的键;校验失败保持原配置
269
- this.unwatchConfig = opts.source.watch((raw) => this.configService.apply(raw), (err) => this.log.error("config watch error", { error: err.message }));
290
+ let reload = Promise.resolve();
291
+ this.unwatchConfig = opts.source.watch((raw) => {
292
+ reload = reload
293
+ .then(() => this.configService.apply(raw, (before, next) => this.permissionConfig.publish(before, next)))
294
+ .catch((error) => this.log.error("config reload failed", { error: errMsg(error) }));
295
+ }, (err) => this.log.error("config watch error", { error: err.message }));
270
296
  }
271
297
  // Last: the process says it is alive (in its roles) only once its start went through
272
298
  this.presence.start({
@@ -454,32 +480,33 @@ let KernelLifecycle = class KernelLifecycle {
454
480
  };
455
481
  KernelLifecycle = __decorate([
456
482
  Injectable(),
457
- __param(0, Inject(AccountsService)),
458
- __param(1, Inject(KernelConfigService)),
459
- __param(2, Inject(KERNEL_LOGGER)),
460
- __param(3, Inject(KERNEL_APP_OPTIONS)),
461
- __param(4, Inject(KERNEL_POOL)),
462
- __param(5, Inject(REDIS)),
463
- __param(6, Inject(KernelDb)),
464
- __param(7, Inject(GracefulShutdown)),
465
- __param(8, Inject(ExtensionHost)),
466
- __param(9, Inject(ExtensionRegistry)),
467
- __param(10, Inject(ExtensionInstalls)),
468
- __param(11, Inject(ExtensionBlobs)),
469
- __param(12, Inject(ExtensionLifecycle)),
470
- __param(13, Inject(ReplicaStatusStore)),
471
- __param(14, Inject(BootstrapService)),
472
- __param(15, Inject(MarketplacesService)),
473
- __param(16, Inject(PluginImport)),
474
- __param(17, Inject(KERNEL_BUS)),
475
- __param(18, Inject(UsageReporter)),
476
- __param(19, Inject(TitleQueue)),
477
- __param(20, Inject(ChannelJobs)),
478
- __param(21, Inject(ChannelOutbound)),
479
- __param(22, Inject(ReplicaPresence)),
480
- __param(23, Optional()),
481
- __param(23, Inject(WorkerRole)),
483
+ __param(0, Inject(PermissionConfigPublication)),
484
+ __param(1, Inject(AccountsService)),
485
+ __param(2, Inject(KernelConfigService)),
486
+ __param(3, Inject(KERNEL_LOGGER)),
487
+ __param(4, Inject(KERNEL_APP_OPTIONS)),
488
+ __param(5, Inject(KERNEL_POOL)),
489
+ __param(6, Inject(REDIS)),
490
+ __param(7, Inject(KernelDb)),
491
+ __param(8, Inject(GracefulShutdown)),
492
+ __param(9, Inject(ExtensionHost)),
493
+ __param(10, Inject(ExtensionRegistry)),
494
+ __param(11, Inject(ExtensionInstalls)),
495
+ __param(12, Inject(ExtensionBlobs)),
496
+ __param(13, Inject(ExtensionLifecycle)),
497
+ __param(14, Inject(ReplicaStatusStore)),
498
+ __param(15, Inject(BootstrapService)),
499
+ __param(16, Inject(MarketplacesService)),
500
+ __param(17, Inject(PluginImport)),
501
+ __param(18, Inject(KERNEL_BUS)),
502
+ __param(19, Inject(UsageReporter)),
503
+ __param(20, Inject(TitleQueue)),
504
+ __param(21, Inject(ChannelJobs)),
505
+ __param(22, Inject(ChannelOutbound)),
506
+ __param(23, Inject(ReplicaPresence)),
482
507
  __param(24, Optional()),
483
- __param(24, Inject(GatewayRole))
508
+ __param(24, Inject(WorkerRole)),
509
+ __param(25, Optional()),
510
+ __param(25, Inject(GatewayRole))
484
511
  ], KernelLifecycle);
485
512
  export { KernelLifecycle };
@@ -192,7 +192,7 @@ let DeviceAuthService = class DeviceAuthService {
192
192
  connectUrl,
193
193
  reconnectGraceSeconds: local.reconnectGraceSeconds,
194
194
  maxFrameBytes: local.maxFrameBytes,
195
- autoMode: allowedDeviceMode(deployment.autoMode, settings.autoMode) === "auto"
195
+ autoMode: allowedDeviceMode(deployment.fullAccess, settings.fullAccess) === "auto"
196
196
  ? "allowed"
197
197
  : "off",
198
198
  };
@@ -1,17 +1,19 @@
1
- import { type DeviceFeature, type DeviceLocalPolicySummary, type DevicePolicyArgs, type DevicePolicyStatus } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceFeature, type DeviceLocalPolicySummary, type DevicePolicyArgs, type DevicePolicyArgsV3, type DevicePolicyStatus } from "@capybara-hq/plugin-sdk";
2
2
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import { TransactionHost } from "../infra/database/transaction-host.js";
5
5
  import { OutboxService } from "../infra/outbox/outbox.service.js";
6
6
  import type { KernelLogger } from "../log.js";
7
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
7
8
  import { MachinesService } from "./machines.js";
9
+ import { OwnerReports } from "./owner-reports.js";
8
10
  import { LocalDeviceRelay } from "./relay.js";
9
11
  /** How long the machine may take to apply a policy change. */
10
12
  export declare const POLICY_DEADLINE_MS = 30000;
11
13
  /** How long an op left `unknown` waits for the machine's hello to report it (from its intent). */
12
14
  export declare const UNKNOWN_OP_MS: number;
13
15
  /** A policy change as callers ask for it: the op id and the source are added here. */
14
- type PolicyChange = Omit<DevicePolicyArgs, "source" | "opId">;
16
+ type PolicyChange = Omit<DevicePolicyArgsV3, "source" | "opId">;
15
17
  /**
16
18
  * Test seam (`KernelOverride`): called by {@link DevicePolicyService.send} right after the `policy`
17
19
  * op's call returned, before its outcome is recorded (by `apply` or a network ask's decision);
@@ -37,7 +39,16 @@ export interface PolicyIntent {
37
39
  deviceId: string;
38
40
  machineId: string;
39
41
  opId: string;
40
- args: DevicePolicyArgs;
42
+ args: DevicePolicyArgsV3;
43
+ /**
44
+ * The staged (protocol 3) connection the op goes to, when the device's machine is connected
45
+ * over one: the op is sent as a v3 `policy` request fenced to it (not sent at all once it
46
+ * changed), and its answer's owner report is recorded with its id. Absent: protocol 2.
47
+ */
48
+ connection?: {
49
+ connectionId: string;
50
+ maxFrameBytes: number;
51
+ };
41
52
  }
42
53
  /**
43
54
  * What became of a sent op, as recorded by {@link DevicePolicyService.settleIn}: `applied` (with
@@ -47,6 +58,10 @@ export interface PolicyIntent {
47
58
  export type PolicyOpResult = {
48
59
  outcome: "applied";
49
60
  policy?: DeviceLocalPolicySummary;
61
+ /** A staged (v3) answer's owner report: recorded before the outcome is accepted (B2). */
62
+ ownerCeiling?: unknown;
63
+ /** The authenticated connection the answer arrived on (recorded with the report). */
64
+ connectionId?: string | null;
50
65
  } | {
51
66
  outcome: "refused";
52
67
  message: string;
@@ -58,7 +73,10 @@ export type PolicyOpResult = {
58
73
  outcome: "unknown";
59
74
  };
60
75
  /** What a machine says of an op id ({@link DevicePolicyService.outcomeOf}). */
61
- export type PolicyOpStatus = DevicePolicyStatus | {
76
+ export type PolicyOpStatus = (DevicePolicyStatus & {
77
+ ownerCeiling?: unknown;
78
+ connectionId?: string | null;
79
+ }) | {
62
80
  outcome: "offline";
63
81
  };
64
82
  /**
@@ -87,8 +105,10 @@ export declare class DevicePolicyService {
87
105
  private readonly outbox;
88
106
  private readonly config;
89
107
  private readonly log;
108
+ private readonly ceilings;
109
+ private readonly owners;
90
110
  private readonly afterCall;
91
- constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<LocalDeviceRelay, "call" | "holderLive">, machines: Pick<MachinesService, "activeFor">, outbox: Pick<OutboxService, "add">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn">, afterCall?: (opId: string) => void);
111
+ constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<LocalDeviceRelay, "call" | "callV3" | "holderLive" | "connection" | "stagedTransport">, machines: Pick<MachinesService, "activeFor">, outbox: Pick<OutboxService, "add">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn">, ceilings: PermissionCeilingWrites, owners: Pick<OwnerReports, "recordLocked">, afterCall?: (opId: string) => void);
92
112
  /**
93
113
  * Changes the policy: {@link begin}, the call, then the outcome recorded in its own transaction
94
114
  * (no transaction may be open). Never throws for an offline machine, a refusal or a program
@@ -133,6 +153,8 @@ export declare class DevicePolicyService {
133
153
  }>;
134
154
  /** The `policy` op's call and its classification ({@link send}). */
135
155
  private call;
156
+ /** The authenticated connection a call goes to now, or null when unknown (M4). */
157
+ private connectionIdOf;
136
158
  /**
137
159
  * What the machine says became of the op `opId` (a read-only `policyStatus`), or `offline` when
138
160
  * no replica holds its connection or it does not answer. Never sends the change.
@@ -162,6 +184,14 @@ export declare class DevicePolicyService {
162
184
  * that does not know the op id by then never will.
163
185
  */
164
186
  resolveDelayMs(): number;
187
+ /**
188
+ * The ordered prelude of a transaction that records an op's outcome ({@link settleIn}) after it
189
+ * locked other rows (a network ask's conversation, its approval, its run): the permission
190
+ * authority lock of the machine's device, read without a lock first. The global order puts it
191
+ * before every conversation row (`withOrderedLocks`); {@link settleIn} re-reads the machine
192
+ * under it. A machine that is gone locks nothing (its settle is a no-op).
193
+ */
194
+ lockMachineDevice(machineId: string): Promise<void>;
165
195
  /** {@link settleIn} in its own transaction (the {@link apply} path). */
166
196
  private settle;
167
197
  /**
@@ -20,11 +20,14 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
20
20
  import { OutboxService } from "../infra/outbox/outbox.service.js";
21
21
  import { KERNEL_LOGGER } from "../infra/tokens.js";
22
22
  import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
23
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
23
24
  import { deviceNotFound } from "../sandbox/sandbox.service.js";
24
25
  import { MachinesService } from "./machines.js";
26
+ import { ownerFactsOf } from "./owner-report.js";
27
+ import { OwnerReports } from "./owner-reports.js";
25
28
  import { DEVICE_OP_RESOLVE_JOB, deviceOpResolveJobId } from "./policy-op-jobs.js";
26
- import { localPolicyOf, pendingPolicyOpsOf } from "./policy-summary.js";
27
- import { LIST_TTL_MARGIN_MS, LocalDeviceRelay, ON_MACHINE_PREFIX } from "./relay.js";
29
+ import { localPolicyOf, ownerPolicyRevokes, pendingPolicyOpsOf, } from "./policy-summary.js";
30
+ import { LIST_TTL_MARGIN_MS, LocalDeviceRelay, ON_MACHINE_PREFIX, wasDeviceRequestNotSent, } from "./relay.js";
28
31
  /** How long the machine may take to apply a policy change. */
29
32
  export const POLICY_DEADLINE_MS = 30_000;
30
33
  /** How long the machine may take to answer a `policyStatus` (it only reads its op log). */
@@ -47,6 +50,7 @@ const INTERRUPTED_MESSAGE = "capybara-device stopped while applying the policy c
47
50
  /** The longest text of the machine's own error the caller is told (as its op log keeps it). */
48
51
  const MAX_MACHINE_MESSAGE = 500;
49
52
  const NOT_RECEIVED_MESSAGE = "The device's machine never received the policy change.";
53
+ const OWNER_CEILING_UNSUPPORTED_MESSAGE = "The device's capybara-device program cannot narrow its owner ceiling from the platform. Update capybara-device on the machine, or run capybara-device ceiling set there.";
50
54
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
51
55
  /**
52
56
  * Changes a local device's policy on its machine (network ask-to-allow spec §5.2; auto mode spec
@@ -74,8 +78,10 @@ let DevicePolicyService = class DevicePolicyService {
74
78
  outbox;
75
79
  config;
76
80
  log;
81
+ ceilings;
82
+ owners;
77
83
  afterCall;
78
- constructor(db, txHost, relay, machines, outbox, config, log, afterCall = () => { }) {
84
+ constructor(db, txHost, relay, machines, outbox, config, log, ceilings, owners, afterCall = () => { }) {
79
85
  this.db = db;
80
86
  this.txHost = txHost;
81
87
  this.relay = relay;
@@ -83,6 +89,8 @@ let DevicePolicyService = class DevicePolicyService {
83
89
  this.outbox = outbox;
84
90
  this.config = config;
85
91
  this.log = log;
92
+ this.ceilings = ceilings;
93
+ this.owners = owners;
86
94
  this.afterCall = afterCall;
87
95
  }
88
96
  /**
@@ -138,13 +146,51 @@ let DevicePolicyService = class DevicePolicyService {
138
146
  // not connected: nothing is sent (a queued op would wait for a reconnect nobody watches)
139
147
  if (!(await this.relay.holderLive(input.deviceId)))
140
148
  return { outcome: offline() };
149
+ // the codec follows the connection the protocol gate accepted: a staged one takes v3 ops
150
+ let connection;
151
+ try {
152
+ connection = (await this.relay.stagedTransport(input.deviceId)) ?? undefined;
153
+ }
154
+ catch (e) {
155
+ // the gate is open and the connection went away or is not ready: nothing is sent
156
+ if (e instanceof ApiError && e.code === "device.not_found")
157
+ throw e;
158
+ return { outcome: offline() };
159
+ }
160
+ const change = connection ? stagedChange(input.change) : input.change;
161
+ // B2: an owner-ceiling narrowing needs a program that reports authenticated owner facts over
162
+ // a staged connection; protocol 2 cannot express it (its `mode: sandbox` narrows both at once)
163
+ if (change.ownerCeiling !== undefined) {
164
+ const row = connection
165
+ ? await this.db
166
+ .selectFrom("device_machines")
167
+ .select(["owner_report", "local_policy"])
168
+ .where("id", "=", machine.id)
169
+ .executeTakeFirst()
170
+ : undefined;
171
+ if (!row || ownerFactsOf(row).state !== "report")
172
+ return {
173
+ outcome: {
174
+ applied: false,
175
+ reason: "unsupported",
176
+ message: OWNER_CEILING_UNSUPPORTED_MESSAGE,
177
+ },
178
+ };
179
+ }
141
180
  const opId = randomUUID();
142
- const args = { ...input.change, opId, source: input.source };
143
- const recorded = await this.recordIntent({ ...input, machineId: machine.id, opId });
181
+ const args = { ...change, opId, source: input.source };
182
+ const recorded = await this.recordIntent({ ...input, change, machineId: machine.id, opId });
144
183
  if (!recorded)
145
184
  return { outcome: offline() };
146
185
  return {
147
- intent: { orgId: input.orgId, deviceId: input.deviceId, machineId: machine.id, opId, args },
186
+ intent: {
187
+ orgId: input.orgId,
188
+ deviceId: input.deviceId,
189
+ machineId: machine.id,
190
+ opId,
191
+ args,
192
+ ...(connection && { connection }),
193
+ },
148
194
  };
149
195
  }
150
196
  /**
@@ -166,14 +212,39 @@ let DevicePolicyService = class DevicePolicyService {
166
212
  /** The `policy` op's call and its classification ({@link send}). */
167
213
  async call(intent) {
168
214
  try {
169
- const { policy } = await this.relay.call(intent.deviceId, "policy", intent.args, {
215
+ const { connection } = intent;
216
+ const connectionId = connection
217
+ ? connection.connectionId
218
+ : await this.connectionIdOf(intent.deviceId);
219
+ const opts = {
170
220
  deadlineMs: POLICY_DEADLINE_MS,
171
221
  // the relay gives up by itself (deadline plus the reconnect grace)
172
222
  signal: new AbortController().signal,
173
- });
174
- return { result: { outcome: "applied", policy }, outcome: { applied: true, policy } };
223
+ };
224
+ // a staged connection takes a v3 `policy` request fenced to it; its answer carries the
225
+ // owner report issued for the change
226
+ const answer = (connection
227
+ ? await this.relay.callV3(intent.deviceId, "policy", intent.args, { ...opts, connection })
228
+ : await this.relay.call(intent.deviceId, "policy", intent.args, opts));
229
+ const { policy } = answer;
230
+ return {
231
+ result: {
232
+ outcome: "applied",
233
+ policy,
234
+ // a staged (v3) answer's owner report, recorded with the connection it came on
235
+ ...(answer.ownerCeiling !== undefined && { ownerCeiling: answer.ownerCeiling }),
236
+ connectionId,
237
+ },
238
+ outcome: { applied: true, policy },
239
+ };
175
240
  }
176
241
  catch (e) {
242
+ // the gateway (or the relay before queuing) says it never reached the machine: definite
243
+ if (wasDeviceRequestNotSent(e))
244
+ return {
245
+ result: { outcome: "not_received" },
246
+ outcome: { applied: false, reason: "offline", message: NOT_RECEIVED_MESSAGE },
247
+ };
177
248
  if (e instanceof ApiError) {
178
249
  // device.offline (the wait ran out: the machine may still apply it), device.forbidden
179
250
  // (the machine was disconnected meanwhile), device.not_found (the device was deleted)
@@ -209,6 +280,15 @@ let DevicePolicyService = class DevicePolicyService {
209
280
  };
210
281
  }
211
282
  }
283
+ /** The authenticated connection a call goes to now, or null when unknown (M4). */
284
+ async connectionIdOf(deviceId) {
285
+ try {
286
+ return (await this.relay.connection(deviceId)).connectionId;
287
+ }
288
+ catch {
289
+ return null;
290
+ }
291
+ }
212
292
  /**
213
293
  * What the machine says became of the op `opId` (a read-only `policyStatus`), or `offline` when
214
294
  * no replica holds its connection or it does not answer. Never sends the change.
@@ -217,7 +297,16 @@ let DevicePolicyService = class DevicePolicyService {
217
297
  if (!(await this.relay.holderLive(deviceId)))
218
298
  return { outcome: "offline" };
219
299
  try {
220
- return await this.relay.call(deviceId, "policyStatus", { opId }, { deadlineMs: STATUS_DEADLINE_MS, signal: new AbortController().signal });
300
+ const opts = { deadlineMs: STATUS_DEADLINE_MS, signal: new AbortController().signal };
301
+ const connection = await this.relay.stagedTransport(deviceId);
302
+ if (connection) {
303
+ // a staged connection answers in v3: an applied outcome carries the owner report
304
+ const status = (await this.relay.callV3(deviceId, "policyStatus", { opId }, { ...opts, connection }));
305
+ return { ...status, connectionId: connection.connectionId };
306
+ }
307
+ const connectionId = await this.connectionIdOf(deviceId);
308
+ const status = await this.relay.call(deviceId, "policyStatus", { opId }, opts);
309
+ return { ...status, connectionId };
221
310
  }
222
311
  catch (e) {
223
312
  this.log.warn("could not ask a machine what became of a policy op", {
@@ -238,10 +327,25 @@ let DevicePolicyService = class DevicePolicyService {
238
327
  * the caller, or null when the op has no live entry (resolved already, or expired: a no-op).
239
328
  */
240
329
  async settleIn(ref, result) {
330
+ const subject = await this.db
331
+ .selectFrom("device_machines")
332
+ .select(["org_id", "device_id"])
333
+ .where("id", "=", ref.machineId)
334
+ .executeTakeFirst();
335
+ if (!subject)
336
+ return null;
337
+ // a caller that locked the machine's device first ({@link lockMachineDevice}, before the rows
338
+ // its transaction locks later) must have locked this one: a machine that moved since is retried
339
+ const held = currentStore()?.permissionLocks;
340
+ if (held?.size && !held.has(`permission-authority-device-${subject.device_id}`))
341
+ throw new ApiError("conflict", "The machine's device changed; retry");
342
+ await this.ceilings.lock({ orgId: subject.org_id, deviceId: subject.device_id }, "device");
241
343
  const row = await this.db
242
344
  .selectFrom("device_machines")
243
345
  .select(["org_id", "device_id", "local_policy", "pending_policy_ops", "revoked_at"])
244
346
  .where("id", "=", ref.machineId)
347
+ .where("org_id", "=", subject.org_id)
348
+ .where("device_id", "=", subject.device_id)
245
349
  .forUpdate()
246
350
  .executeTakeFirst();
247
351
  const op = pendingPolicyOpsOf(row?.pending_policy_ops).find((o) => o.id === ref.opId);
@@ -257,6 +361,28 @@ let DevicePolicyService = class DevicePolicyService {
257
361
  target: row.device_id,
258
362
  detail: { ...changeDetail(op), ...extra },
259
363
  });
364
+ // B2: an applied answer carrying an owner report is accepted only once that report is
365
+ // committed by the common owner writer; an out-of-order report leaves the op unknown
366
+ let v3Report = false;
367
+ if (result.outcome === "applied" && result.ownerCeiling !== undefined) {
368
+ const recorded = await this.owners.recordLocked(ref.machineId, result.ownerCeiling, {
369
+ connectionId: result.connectionId ?? null,
370
+ via: "policy-result",
371
+ // the op explains the owner change: audited once, as the op's source made it
372
+ explainedBy: {
373
+ accountId: op.source.accountId,
374
+ via: op.source.via,
375
+ opId: op.id,
376
+ ...(op.actorTokenId !== undefined && { actorTokenId: op.actorTokenId }),
377
+ },
378
+ });
379
+ // a lower sequence is a late delivery (ignored by the writer), the op still applied; only
380
+ // a conflicting report or a revoked machine leaves it unknown
381
+ if (recorded === "conflict" || recorded === "revoked")
382
+ result = { outcome: "unknown" };
383
+ else
384
+ v3Report = true;
385
+ }
260
386
  if (result.outcome === "unknown") {
261
387
  // a hello reported the op meanwhile (its job records it), or it is unknown already
262
388
  if (op.reported !== undefined || op.status === "unknown")
@@ -287,13 +413,20 @@ let DevicePolicyService = class DevicePolicyService {
287
413
  })
288
414
  .where("id", "=", ref.machineId)
289
415
  .execute();
416
+ if (!v3Report &&
417
+ policy !== undefined &&
418
+ live &&
419
+ JSON.stringify(policy) !== JSON.stringify(localPolicyOf(row.local_policy)))
420
+ await this.ceilings.publishLocked({ orgId: row.org_id, deviceId: row.device_id }, "device", (scope, intent) => ownerPolicyRevokes(policy, scope, intent.method, intent.granted_hosts), modeNow !== undefined);
290
421
  if (result.outcome === "applied") {
291
422
  if (op.add.length > 0 || op.remove.length > 0) {
292
423
  await auditOp("device.policy_changed", {
293
424
  ...(op.status === "unknown" && { late: true }),
294
425
  });
295
426
  }
296
- if (modeNow !== undefined) {
427
+ // a v3 answer's Full change is the owner report's, audited once by its writer
428
+ // (`device.owner_ceiling_changed`): the summary's derived mode is not audited again
429
+ if (modeNow !== undefined && !v3Report) {
297
430
  await auditOp("device.mode_changed", {
298
431
  from: modeBefore,
299
432
  to: modeNow,
@@ -329,6 +462,23 @@ let DevicePolicyService = class DevicePolicyService {
329
462
  const graceMs = this.config.get().devices.local.reconnectGraceSeconds * 1000;
330
463
  return POLICY_DEADLINE_MS + graceMs + LIST_TTL_MARGIN_MS + 5_000;
331
464
  }
465
+ /**
466
+ * The ordered prelude of a transaction that records an op's outcome ({@link settleIn}) after it
467
+ * locked other rows (a network ask's conversation, its approval, its run): the permission
468
+ * authority lock of the machine's device, read without a lock first. The global order puts it
469
+ * before every conversation row (`withOrderedLocks`); {@link settleIn} re-reads the machine
470
+ * under it. A machine that is gone locks nothing (its settle is a no-op).
471
+ */
472
+ async lockMachineDevice(machineId) {
473
+ const subject = await this.db
474
+ .selectFrom("device_machines")
475
+ .select(["org_id", "device_id"])
476
+ .where("id", "=", machineId)
477
+ .executeTakeFirst();
478
+ if (!subject)
479
+ return;
480
+ await this.ceilings.lock({ orgId: subject.org_id, deviceId: subject.device_id }, "device");
481
+ }
332
482
  /** {@link settleIn} in its own transaction (the {@link apply} path). */
333
483
  settle(intent, result) {
334
484
  return this.settleIn(intent, result);
@@ -356,6 +506,7 @@ let DevicePolicyService = class DevicePolicyService {
356
506
  add: change.add ?? [],
357
507
  remove: change.remove ?? [],
358
508
  ...(change.mode !== undefined && { mode: change.mode }),
509
+ ...(change.ownerCeiling !== undefined && { ownerCeiling: change.ownerCeiling }),
359
510
  source: {
360
511
  accountId: source.accountId,
361
512
  via: source.via,
@@ -400,6 +551,9 @@ let DevicePolicyService = class DevicePolicyService {
400
551
  __decorate([
401
552
  Transactional({ propagation: "mandatory" })
402
553
  ], DevicePolicyService.prototype, "settleIn", null);
554
+ __decorate([
555
+ Transactional({ propagation: "mandatory" })
556
+ ], DevicePolicyService.prototype, "lockMachineDevice", null);
403
557
  __decorate([
404
558
  Transactional()
405
559
  ], DevicePolicyService.prototype, "settle", null);
@@ -415,10 +569,31 @@ DevicePolicyService = __decorate([
415
569
  __param(4, Inject(OutboxService)),
416
570
  __param(5, Inject(KernelConfigService)),
417
571
  __param(6, Inject(KERNEL_LOGGER)),
418
- __param(7, Optional()),
419
- __param(7, Inject(DEVICE_POLICY_AFTER_CALL))
572
+ __param(7, Inject(PermissionCeilingWrites)),
573
+ __param(8, Inject(OwnerReports)),
574
+ __param(9, Optional()),
575
+ __param(9, Inject(DEVICE_POLICY_AFTER_CALL))
420
576
  ], DevicePolicyService);
421
577
  export { DevicePolicyService };
578
+ /**
579
+ * A change as a staged (v3) machine takes it: protocol 2's one narrowing (`mode: "sandbox"`, Full
580
+ * access off and the project reach to the workspace at once) becomes the owner-ceiling narrowing
581
+ * it stands for; the protocol 3 machine keeps its owner ceiling, not a daily mode. Never wider:
582
+ * only `false` / `workspace` can come out of it (the frame parser refuses anything else).
583
+ */
584
+ function stagedChange(change) {
585
+ if (change.mode !== "sandbox")
586
+ return change;
587
+ const { mode: _narrowed, ...rest } = change;
588
+ return {
589
+ ...rest,
590
+ ownerCeiling: {
591
+ ...change.ownerCeiling,
592
+ fullAccess: false,
593
+ restrictedProjectReach: "workspace",
594
+ },
595
+ };
596
+ }
422
597
  const offline = () => ({
423
598
  applied: false,
424
599
  reason: "offline",
@@ -0,0 +1,82 @@
1
+ import { type BindInstanceRequestV3, type BindInstanceResultV3, type SandboxPermissionSupport } from "@capybara-hq/plugin-sdk";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { TransactionHost } from "../infra/database/transaction-host.js";
4
+ import { LegacyRetirementStore } from "../sandbox/legacy-retirement.js";
5
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
6
+ import { PermissionRuntimeReports } from "../sandbox/permission-runtime-reports.js";
7
+ import { type SandboxInstanceBinder } from "../sandbox/providers.js";
8
+ import { OwnerReports } from "./owner-reports.js";
9
+ import { LocalDeviceRelay } from "./relay.js";
10
+ /** The committed binding of a local instance generation, as the coordinator sends it. */
11
+ export interface CommittedBinding {
12
+ orgId: string;
13
+ request: BindInstanceRequestV3;
14
+ status: "awaiting-device" | "installed";
15
+ /** The machine the binding was committed for (null: none was active). */
16
+ machineId: string | null;
17
+ }
18
+ /** The binding cannot be completed; the instance stays unprobed and admits nothing. */
19
+ export declare class InstanceBindingError extends Error {
20
+ name: string;
21
+ }
22
+ /**
23
+ * Post-commit binding of a local instance generation (permission runtime cutover B4, staged on the
24
+ * v3 path; protocol 2 stays active). `commitHandle` allocated the generation and committed an
25
+ * `awaiting-device` binding; before the lifecycle holder downgrades to shared use it calls
26
+ * {@link bind}, which sends the private `bindInstance` RPC to the authenticated machine outside
27
+ * any transaction and then, under the device authority writer, verifies the exact instance row,
28
+ * generation, binding id and machine, records the runtime report and marks the binding
29
+ * `installed`. A retry (reconnect, lost reply, another replica) resends the identical binding; it
30
+ * never allocates a new generation. A delayed answer for an old generation cannot populate a
31
+ * replacement row.
32
+ */
33
+ export declare class LocalInstanceBindings implements SandboxInstanceBinder {
34
+ private readonly db;
35
+ readonly txHost: TransactionHost;
36
+ private readonly relay;
37
+ private readonly ceilings;
38
+ private readonly reports;
39
+ private readonly owners;
40
+ /** The durable legacy gate checked before any bind is sent (8.5). */
41
+ private readonly retirement;
42
+ constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<LocalDeviceRelay, "callV3" | "connection">, ceilings: PermissionCeilingWrites, reports: PermissionRuntimeReports, owners: Pick<OwnerReports, "recordLocked">,
43
+ /** The durable legacy gate checked before any bind is sent (8.5). */
44
+ retirement: Pick<LegacyRetirementStore, "hasUnresolved">);
45
+ /** The binding committed for the device's current local instance, or null (no allocation). */
46
+ committed(deviceId: string): Promise<CommittedBinding | null>;
47
+ /**
48
+ * Whether the device's current local instance generation has an installed binding (the staged
49
+ * acquire path's shared-use condition). No committed binding reads as not installed.
50
+ */
51
+ installed(deviceId: string): Promise<boolean>;
52
+ /** The current generation's committed binding status, or null when none was committed. */
53
+ status(deviceId: string): Promise<"installed" | "awaiting-device" | null>;
54
+ /**
55
+ * The permission support the device attested for its current instance generation (the staged
56
+ * provider's `permissionSupport`): only the report recorded with an installed binding of that
57
+ * generation, for the active machine's program version. Anything else (unbound, awaiting, a
58
+ * changed identity) reads as no support with its reason: nothing is probed, and a missing
59
+ * report never admits an operation.
60
+ */
61
+ permissionSupport(deviceId: string): Promise<SandboxPermissionSupport>;
62
+ /**
63
+ * Sends the committed binding and installs the verified answer. The caller holds the device's
64
+ * lifecycle lease; no transaction is open across the RPC.
65
+ */
66
+ bind(deviceId: string, signal: AbortSignal): Promise<BindInstanceResultV3 | null>;
67
+ /**
68
+ * Moves a still awaiting binding to the active machine: its previous becomes the last binding
69
+ * committed for that machine. Under the device writer, against the exact generation and id.
70
+ */
71
+ retarget(deviceId: string, committed: CommittedBinding, machineId: string): Promise<void>;
72
+ private activeMachine;
73
+ /**
74
+ * Under the device authority writer: the answer must be for the exact committed generation and
75
+ * binding of the current row, from the machine the request went to. A different environment
76
+ * fingerprint than the previous installed generation resets Full consent; the first verified
77
+ * proof of an unprobed device does not (its semantic scope was what the person consented to).
78
+ */
79
+ install(deviceId: string, machineId: string, committed: CommittedBinding, answer: BindInstanceResultV3,
80
+ /** The authenticated connection the answer came on (recorded with its owner report). */
81
+ connectionId?: string | null): Promise<void>;
82
+ }