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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/bootstrap.json +10 -1
  2. package/dist/admin/admin.schemas.d.ts +6 -0
  3. package/dist/admin/org-network.service.d.ts +3 -1
  4. package/dist/admin/org-network.service.js +10 -2
  5. package/dist/app.d.ts +4 -0
  6. package/dist/app.js +2 -0
  7. package/dist/background/finish.d.ts +9 -1
  8. package/dist/background/finish.js +57 -4
  9. package/dist/background/launch.d.ts +23 -0
  10. package/dist/background/launch.js +55 -1
  11. package/dist/background/managed-output.d.ts +110 -0
  12. package/dist/background/managed-output.js +219 -0
  13. package/dist/background/managed.d.ts +52 -0
  14. package/dist/background/managed.js +128 -0
  15. package/dist/background/poll.job.d.ts +35 -1
  16. package/dist/background/poll.job.js +174 -9
  17. package/dist/background/render.js +1 -0
  18. package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
  19. package/dist/background/retire-legacy-tasks.job.js +149 -0
  20. package/dist/background/session.d.ts +15 -5
  21. package/dist/background/session.js +22 -6
  22. package/dist/background/stop.d.ts +35 -5
  23. package/dist/background/stop.js +94 -8
  24. package/dist/background/store.d.ts +110 -3
  25. package/dist/background/store.js +205 -3
  26. package/dist/background/tasks.service.d.ts +18 -1
  27. package/dist/background/tasks.service.js +99 -9
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/channels/cards.js +1 -1
  30. package/dist/channels/inbound.js +2 -0
  31. package/dist/channels/phrases.d.ts +4 -0
  32. package/dist/channels/phrases.js +4 -0
  33. package/dist/config/load.d.ts +18 -0
  34. package/dist/config/load.js +39 -1
  35. package/dist/config/permission-migration.d.ts +26 -0
  36. package/dist/config/permission-migration.js +64 -0
  37. package/dist/config/schema.d.ts +1 -1
  38. package/dist/config/schema.js +11 -10
  39. package/dist/conversations/conversations.controller.d.ts +1 -1
  40. package/dist/conversations/conversations.controller.js +1 -1
  41. package/dist/conversations/conversations.module.js +12 -0
  42. package/dist/conversations/conversations.service.d.ts +11 -2
  43. package/dist/conversations/conversations.service.js +97 -27
  44. package/dist/conversations/event-log.d.ts +1 -1
  45. package/dist/conversations/event-log.js +10 -2
  46. package/dist/conversations/events.d.ts +304 -4
  47. package/dist/conversations/events.js +279 -29
  48. package/dist/conversations/permission-profile-store.d.ts +50 -0
  49. package/dist/conversations/permission-profile-store.js +67 -0
  50. package/dist/conversations/permission-profile-store.module.d.ts +2 -0
  51. package/dist/conversations/permission-profile-store.module.js +19 -0
  52. package/dist/conversations/permission-profiles.controller.d.ts +84 -0
  53. package/dist/conversations/permission-profiles.controller.js +105 -0
  54. package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
  55. package/dist/conversations/permission-profiles.schemas.js +23 -0
  56. package/dist/conversations/permission-profiles.service.d.ts +56 -0
  57. package/dist/conversations/permission-profiles.service.js +179 -0
  58. package/dist/db/kernel-schema.d.ts +238 -3
  59. package/dist/devices/access.js +1 -1
  60. package/dist/devices/access.module.d.ts +2 -0
  61. package/dist/devices/access.module.js +19 -0
  62. package/dist/devices/conversation-devices.d.ts +8 -29
  63. package/dist/devices/conversation-devices.js +37 -73
  64. package/dist/devices/device-projects.service.d.ts +26 -28
  65. package/dist/devices/device-projects.service.js +123 -127
  66. package/dist/devices/devices.controller.js +3 -1
  67. package/dist/devices/devices.module.js +11 -9
  68. package/dist/devices/devices.service.d.ts +116 -8
  69. package/dist/devices/devices.service.js +252 -20
  70. package/dist/devices/dto.d.ts +16 -0
  71. package/dist/devices/dto.js +34 -6
  72. package/dist/devices/errors.d.ts +8 -0
  73. package/dist/devices/errors.js +10 -0
  74. package/dist/devices/project-rules.d.ts +44 -0
  75. package/dist/devices/project-rules.js +27 -0
  76. package/dist/devices/working-root.d.ts +6 -0
  77. package/dist/devices/working-root.js +12 -1
  78. package/dist/errors.d.ts +31 -0
  79. package/dist/errors.js +31 -0
  80. package/dist/evals/reconstruct.d.ts +19 -2
  81. package/dist/evals/reconstruct.js +40 -2
  82. package/dist/evals/recorded-permission-context.d.ts +77 -0
  83. package/dist/evals/recorded-permission-context.js +151 -0
  84. package/dist/evals/recorded-tools.d.ts +10 -1
  85. package/dist/evals/recorded-tools.js +27 -3
  86. package/dist/evals/run-replay.d.ts +8 -2
  87. package/dist/evals/run-replay.js +18 -2
  88. package/dist/evals/trajectory.d.ts +1 -1
  89. package/dist/evals/worker.d.ts +10 -1
  90. package/dist/evals/worker.js +23 -14
  91. package/dist/http/api.module.js +2 -0
  92. package/dist/identity/accounts.d.ts +14 -1
  93. package/dist/identity/accounts.js +61 -5
  94. package/dist/identity/identity.module.js +2 -0
  95. package/dist/identity/settings.d.ts +28 -12
  96. package/dist/identity/settings.js +89 -33
  97. package/dist/index.d.ts +6 -0
  98. package/dist/index.js +5 -0
  99. package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
  100. package/dist/infra/cli/kernel-cli.module.js +5 -2
  101. package/dist/infra/cli/permission-cutover.d.ts +59 -0
  102. package/dist/infra/cli/permission-cutover.js +107 -0
  103. package/dist/infra/config/kernel-config.service.d.ts +2 -2
  104. package/dist/infra/config/kernel-config.service.js +31 -11
  105. package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
  106. package/dist/infra/database/startup-activation-transaction.js +242 -0
  107. package/dist/infra/database/transaction-host.d.ts +47 -0
  108. package/dist/infra/database/transaction-host.js +119 -0
  109. package/dist/infra/database/xact-lock.d.ts +1 -0
  110. package/dist/infra/database/xact-lock.js +6 -0
  111. package/dist/infra/outbox/registry.d.ts +39 -0
  112. package/dist/infra/outbox/registry.js +18 -0
  113. package/dist/kernel.module.js +2 -0
  114. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  115. package/dist/lifecycle/kernel-lifecycle.js +55 -28
  116. package/dist/local-devices/device-auth.js +1 -1
  117. package/dist/local-devices/device-policy.service.d.ts +35 -5
  118. package/dist/local-devices/device-policy.service.js +188 -13
  119. package/dist/local-devices/instance-bindings.d.ts +82 -0
  120. package/dist/local-devices/instance-bindings.js +304 -0
  121. package/dist/local-devices/keys.d.ts +5 -0
  122. package/dist/local-devices/keys.js +5 -0
  123. package/dist/local-devices/local-device-gateway.d.ts +19 -4
  124. package/dist/local-devices/local-device-gateway.js +185 -17
  125. package/dist/local-devices/local-device-provider.d.ts +42 -7
  126. package/dist/local-devices/local-device-provider.js +185 -10
  127. package/dist/local-devices/local-devices.module.d.ts +17 -2
  128. package/dist/local-devices/local-devices.module.js +49 -8
  129. package/dist/local-devices/machines.d.ts +35 -12
  130. package/dist/local-devices/machines.js +203 -8
  131. package/dist/local-devices/network-grants.js +3 -3
  132. package/dist/local-devices/network-grants.module.d.ts +2 -0
  133. package/dist/local-devices/network-grants.module.js +14 -0
  134. package/dist/local-devices/owner-report.d.ts +79 -0
  135. package/dist/local-devices/owner-report.js +155 -0
  136. package/dist/local-devices/owner-reports.d.ts +48 -0
  137. package/dist/local-devices/owner-reports.js +190 -0
  138. package/dist/local-devices/policy-summary.d.ts +24 -1
  139. package/dist/local-devices/policy-summary.js +48 -0
  140. package/dist/local-devices/relay.d.ts +82 -6
  141. package/dist/local-devices/relay.js +187 -16
  142. package/dist/local-devices/targets.d.ts +16 -1
  143. package/dist/local-devices/targets.js +35 -2
  144. package/dist/orgs/cloud-network-setting.d.ts +33 -0
  145. package/dist/orgs/cloud-network-setting.js +47 -0
  146. package/dist/orgs/offboarding.d.ts +3 -1
  147. package/dist/orgs/offboarding.js +8 -2
  148. package/dist/orgs/org-lock.d.ts +10 -4
  149. package/dist/orgs/org-lock.js +10 -4
  150. package/dist/orgs/orgs.service.d.ts +3 -1
  151. package/dist/orgs/orgs.service.js +8 -2
  152. package/dist/orgs/settings.controller.d.ts +4 -1
  153. package/dist/orgs/settings.controller.js +3 -3
  154. package/dist/orgs/settings.service.d.ts +48 -56
  155. package/dist/orgs/settings.service.js +144 -101
  156. package/dist/overrides.d.ts +6 -1
  157. package/dist/overrides.js +2 -0
  158. package/dist/platform/exclusions.js +20 -0
  159. package/dist/platform/ops/admin.ops.js +14 -11
  160. package/dist/platform/ops/agent-skills.ops.js +2 -0
  161. package/dist/platform/ops/devices.ops.js +10 -2
  162. package/dist/platform/ops/org-settings.ops.js +6 -6
  163. package/dist/platform/ops/orgs.ops.js +1 -0
  164. package/dist/roles/worker.module.js +4 -0
  165. package/dist/runtime/context/build.d.ts +3 -1
  166. package/dist/runtime/context/build.js +19 -3
  167. package/dist/runtime/context/compaction.js +5 -0
  168. package/dist/runtime/context/device-paths.d.ts +9 -2
  169. package/dist/runtime/context/device-paths.js +20 -0
  170. package/dist/runtime/context/permission-profile.d.ts +46 -0
  171. package/dist/runtime/context/permission-profile.js +194 -0
  172. package/dist/runtime/maintenance.d.ts +7 -1
  173. package/dist/runtime/maintenance.js +43 -15
  174. package/dist/runtime/model-call.d.ts +32 -0
  175. package/dist/runtime/model-call.js +67 -0
  176. package/dist/runtime/permission-context-errors.d.ts +39 -0
  177. package/dist/runtime/permission-context-errors.js +67 -0
  178. package/dist/runtime/permission-context.service.d.ts +60 -0
  179. package/dist/runtime/permission-context.service.js +286 -0
  180. package/dist/runtime/project/knowledge.d.ts +7 -2
  181. package/dist/runtime/project/knowledge.js +5 -2
  182. package/dist/runtime/project/knowledge.service.d.ts +17 -2
  183. package/dist/runtime/project/knowledge.service.js +76 -12
  184. package/dist/runtime/run-execution.d.ts +4 -1
  185. package/dist/runtime/run-execution.js +14 -5
  186. package/dist/runtime/run-steps.d.ts +11 -3
  187. package/dist/runtime/run-steps.js +27 -4
  188. package/dist/runtime/runtime.module.js +11 -0
  189. package/dist/sandbox/attachments-path.d.ts +15 -0
  190. package/dist/sandbox/attachments-path.js +15 -0
  191. package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
  192. package/dist/sandbox/cloud-permission-snapshot.js +407 -0
  193. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
  194. package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
  195. package/dist/sandbox/held-operations.d.ts +39 -0
  196. package/dist/sandbox/held-operations.js +119 -0
  197. package/dist/sandbox/jobs.d.ts +14 -3
  198. package/dist/sandbox/jobs.js +20 -2
  199. package/dist/sandbox/kernel-read.d.ts +55 -0
  200. package/dist/sandbox/kernel-read.js +57 -0
  201. package/dist/sandbox/legacy-retirement.d.ts +336 -0
  202. package/dist/sandbox/legacy-retirement.js +1063 -0
  203. package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
  204. package/dist/sandbox/legacy-retirement.module.js +25 -0
  205. package/dist/sandbox/managed-device-context.d.ts +94 -0
  206. package/dist/sandbox/managed-device-context.js +308 -0
  207. package/dist/sandbox/managed-device-context.module.d.ts +6 -0
  208. package/dist/sandbox/managed-device-context.module.js +33 -0
  209. package/dist/sandbox/modes.d.ts +56 -8
  210. package/dist/sandbox/modes.js +92 -8
  211. package/dist/sandbox/operation-authority-types.d.ts +8 -0
  212. package/dist/sandbox/operation-authority-types.js +32 -0
  213. package/dist/sandbox/operation-authority.d.ts +145 -0
  214. package/dist/sandbox/operation-authority.js +783 -0
  215. package/dist/sandbox/operation-authority.module.d.ts +2 -0
  216. package/dist/sandbox/operation-authority.module.js +29 -0
  217. package/dist/sandbox/operation-intents.d.ts +206 -0
  218. package/dist/sandbox/operation-intents.js +1252 -0
  219. package/dist/sandbox/operation-intents.module.d.ts +2 -0
  220. package/dist/sandbox/operation-intents.module.js +21 -0
  221. package/dist/sandbox/operation-payloads.d.ts +33 -0
  222. package/dist/sandbox/operation-payloads.js +332 -0
  223. package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
  224. package/dist/sandbox/operation-reconcile.job.js +247 -0
  225. package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
  226. package/dist/sandbox/permission-authority-epochs.js +83 -0
  227. package/dist/sandbox/permission-authority-lock.d.ts +38 -0
  228. package/dist/sandbox/permission-authority-lock.js +147 -0
  229. package/dist/sandbox/permission-authority.module.d.ts +9 -0
  230. package/dist/sandbox/permission-authority.module.js +55 -0
  231. package/dist/sandbox/permission-availability.d.ts +18 -0
  232. package/dist/sandbox/permission-availability.js +19 -0
  233. package/dist/sandbox/permission-call-grants.d.ts +34 -0
  234. package/dist/sandbox/permission-call-grants.js +349 -0
  235. package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
  236. package/dist/sandbox/permission-call-grants.module.js +21 -0
  237. package/dist/sandbox/permission-call-types.d.ts +82 -0
  238. package/dist/sandbox/permission-call-types.js +1 -0
  239. package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
  240. package/dist/sandbox/permission-ceiling-writes.js +223 -0
  241. package/dist/sandbox/permission-config-publication.d.ts +76 -0
  242. package/dist/sandbox/permission-config-publication.js +339 -0
  243. package/dist/sandbox/permission-context-types.d.ts +64 -0
  244. package/dist/sandbox/permission-context-types.js +24 -0
  245. package/dist/sandbox/permission-facts.d.ts +206 -0
  246. package/dist/sandbox/permission-facts.js +627 -0
  247. package/dist/sandbox/permission-facts.module.d.ts +2 -0
  248. package/dist/sandbox/permission-facts.module.js +20 -0
  249. package/dist/sandbox/permission-instance-writes.d.ts +90 -0
  250. package/dist/sandbox/permission-instance-writes.js +305 -0
  251. package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
  252. package/dist/sandbox/permission-runtime-reports.js +354 -0
  253. package/dist/sandbox/permission-transitions.d.ts +31 -0
  254. package/dist/sandbox/permission-transitions.js +155 -0
  255. package/dist/sandbox/platform-full-access.d.ts +128 -0
  256. package/dist/sandbox/platform-full-access.js +210 -0
  257. package/dist/sandbox/providers.d.ts +22 -0
  258. package/dist/sandbox/providers.js +10 -2
  259. package/dist/sandbox/providers.module.d.ts +2 -0
  260. package/dist/sandbox/providers.module.js +19 -0
  261. package/dist/sandbox/request-not-sent.d.ts +13 -0
  262. package/dist/sandbox/request-not-sent.js +13 -0
  263. package/dist/sandbox/review/classifier.d.ts +2 -0
  264. package/dist/sandbox/review/classifier.js +8 -0
  265. package/dist/sandbox/review/permission-candidate.d.ts +12 -0
  266. package/dist/sandbox/review/permission-candidate.js +129 -0
  267. package/dist/sandbox/review/review.service.d.ts +4 -1
  268. package/dist/sandbox/review/review.service.js +19 -5
  269. package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
  270. package/dist/sandbox/sandbox-file-reader.js +51 -7
  271. package/dist/sandbox/sandbox.module.js +26 -6
  272. package/dist/sandbox/sandbox.service.d.ts +230 -34
  273. package/dist/sandbox/sandbox.service.js +1368 -199
  274. package/dist/sandbox/unreachable.js +17 -3
  275. package/dist/sandbox/use-context.d.ts +17 -0
  276. package/dist/sandbox/use-context.js +1 -0
  277. package/dist/skills/invoke.d.ts +27 -4
  278. package/dist/skills/invoke.js +72 -7
  279. package/dist/tools/approvals.controller.d.ts +1 -0
  280. package/dist/tools/approvals.schemas.d.ts +1 -0
  281. package/dist/tools/approvals.schemas.js +3 -1
  282. package/dist/tools/approvals.service.d.ts +23 -10
  283. package/dist/tools/approvals.service.js +104 -26
  284. package/dist/tools/builtins/builtin-tools.d.ts +16 -2
  285. package/dist/tools/builtins/builtin-tools.js +38 -10
  286. package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
  287. package/dist/tools/builtins/sandbox/bash.js +201 -5
  288. package/dist/tools/builtins/sandbox/common.d.ts +92 -20
  289. package/dist/tools/builtins/sandbox/common.js +201 -17
  290. package/dist/tools/builtins/sandbox/deliver.js +2 -2
  291. package/dist/tools/builtins/sandbox/edit.js +2 -2
  292. package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
  293. package/dist/tools/builtins/sandbox/glob.js +2 -2
  294. package/dist/tools/builtins/sandbox/grep.js +2 -2
  295. package/dist/tools/builtins/sandbox/read.js +2 -2
  296. package/dist/tools/builtins/sandbox/task-list.js +7 -1
  297. package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
  298. package/dist/tools/builtins/sandbox/task-output.js +172 -0
  299. package/dist/tools/builtins/sandbox/task-stop.js +25 -3
  300. package/dist/tools/builtins/sandbox/write.js +2 -2
  301. package/dist/tools/builtins/skill-load.js +9 -6
  302. package/dist/tools/device-op-resolver.d.ts +1 -1
  303. package/dist/tools/device-op-resolver.js +13 -3
  304. package/dist/tools/permission-approval-jobs.d.ts +18 -0
  305. package/dist/tools/permission-approval-jobs.js +92 -0
  306. package/dist/tools/pipeline.d.ts +17 -2
  307. package/dist/tools/pipeline.js +300 -19
  308. package/dist/tools/registry.d.ts +9 -0
  309. package/dist/tools/tools.module.js +12 -0
  310. package/package.json +4 -3
  311. package/src/migrations/0146_permission_authority_epochs.sql +6 -0
  312. package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
  313. package/src/migrations/0148_first_message_request_hash.sql +2 -0
  314. package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
  315. package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
  316. package/src/migrations/0151_starting_execution_grants.sql +8 -0
  317. package/src/migrations/0152_background_launch_identity.sql +66 -0
  318. package/src/migrations/0153_background_cancel_requester.sql +13 -0
  319. package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
  320. package/src/migrations/0155_device_instance_generations.sql +30 -0
  321. package/src/migrations/0156_device_owner_report.sql +7 -0
  322. package/src/migrations/0157_legacy_retirement.sql +116 -0
  323. package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
  324. package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
  325. package/dist/sandbox/platform-auto-mode.d.ts +0 -63
  326. package/dist/sandbox/platform-auto-mode.js +0 -63
@@ -8,14 +8,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, } from "@capybara-hq/plugin-sdk";
11
+ import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, parseDeviceFrameV3, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
14
  import { LockService } from "../infra/lock/lock.service.js";
15
15
  import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
16
- import { DEVICE_TAKEN_PREFIX, deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, deviceRevokedTopic, deviceTakenKey, deviceTakeoverTopic, } from "./keys.js";
16
+ import { DEVICE_TAKEN_PREFIX, deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, deviceRevokedTopic, deviceTakenKey, deviceTakeoverTopic, deviceTransportKey, } from "./keys.js";
17
17
  import { MachinesService } from "./machines.js";
18
- import { LIST_TTL_MARGIN_MS } from "./relay.js";
18
+ import { connectionChangedMessage, GATEWAY_NOT_SENT, LIST_TTL_MARGIN_MS, STOP_MACHINE, } from "./relay.js";
19
19
  /** WebSocket close codes the gateway uses (the program reads 4002 and 4003). */
20
20
  export const DEVICE_CLOSE = {
21
21
  /** The kernel is shutting down: reconnect (another gateway replica takes over). */
@@ -45,6 +45,11 @@ export const CLAIM_TIMEOUT_MS = 5_000;
45
45
  export const CLAIM_RETRY_MS = 250;
46
46
  /** Traffic marks the machine seen at most this often per connection (the row has its own gate). */
47
47
  const TOUCH_EVERY_MS = 30_000;
48
+ /**
49
+ * Consecutive failed capacity publications on ping after which a staged connection closes (its
50
+ * transport key lives three pings, so two misses still leave it readable).
51
+ */
52
+ const MAX_PUBLISH_FAILURES = 3;
48
53
  /** How often a held connection re-checks its credential (membership, org, device). */
49
54
  const REAUTH_EVERY_MS = 60_000;
50
55
  /**
@@ -101,6 +106,7 @@ class DeviceConnection {
101
106
  socket;
102
107
  identity;
103
108
  credential;
109
+ staged;
104
110
  token = randomUUID();
105
111
  state = "hello";
106
112
  lease;
@@ -116,11 +122,30 @@ class DeviceConnection {
116
122
  released;
117
123
  /** The hello's record, then each policy frame's, one after another (never rejects). */
118
124
  recorded = Promise.resolve();
119
- constructor(gw, socket, identity, credential) {
125
+ constructor(gw, socket, identity, credential, staged = false) {
120
126
  this.gw = gw;
121
127
  this.socket = socket;
122
128
  this.identity = identity;
123
129
  this.credential = credential;
130
+ this.staged = staged;
131
+ }
132
+ /**
133
+ * The id a staged connection fences requests and results with (sent to the machine in `ready`).
134
+ * Random and separate from the lease token, which stays internal to the kernel.
135
+ */
136
+ connectionId = randomUUID();
137
+ effectiveCap;
138
+ ready = false;
139
+ /** Consecutive failed capacity publications on ping (this socket's own state). */
140
+ publishFailures = 0;
141
+ async publishCapacity() {
142
+ if (!this.staged || this.effectiveCap === undefined || this.state !== "holding")
143
+ return;
144
+ if (this.gw.maxFrameBytes() < this.effectiveCap) {
145
+ await this.close(DEVICE_CLOSE.protocol, "Frame capacity changed; reconnect");
146
+ return;
147
+ }
148
+ await this.gw.redis.set(deviceTransportKey(this.deviceId, this.token), JSON.stringify({ connectionId: this.connectionId, maxFrameBytes: this.effectiveCap }), "PX", Math.max(this.gw.leaseTtlMs(), this.gw.pingIntervalMs * 3));
124
149
  }
125
150
  get deviceId() {
126
151
  return this.identity.deviceId;
@@ -155,7 +180,13 @@ class DeviceConnection {
155
180
  async onFrame(text) {
156
181
  let frame;
157
182
  try {
158
- frame = parseDeviceFrame(text, "device");
183
+ frame = this.staged
184
+ ? parseDeviceFrameV3(text, "device", this.effectiveCap ?? this.gw.maxFrameBytes())
185
+ : parseDeviceFrame(text, "device");
186
+ if (this.staged &&
187
+ this.effectiveCap !== undefined &&
188
+ this.gw.maxFrameBytes() < this.effectiveCap)
189
+ throw new Error("Frame capacity changed; reconnect");
159
190
  }
160
191
  catch (e) {
161
192
  this.gw.log.warn("device sent an invalid frame", {
@@ -170,10 +201,21 @@ class DeviceConnection {
170
201
  this.close(DEVICE_CLOSE.protocol, "hello sent twice");
171
202
  return;
172
203
  }
173
- if (frame.protocol !== DEVICE_PROTOCOL_VERSION) {
204
+ if (frame.protocol !== (this.staged ? 3 : DEVICE_PROTOCOL_VERSION)) {
174
205
  this.close(DEVICE_CLOSE.protocol, "unsupported protocol");
175
206
  return;
176
207
  }
208
+ if (this.staged) {
209
+ if (!("transport" in frame)) {
210
+ this.close(DEVICE_CLOSE.protocol, "Expected staged hello");
211
+ return;
212
+ }
213
+ this.effectiveCap = Math.min(frame.transport.maxFrameBytes, this.gw.maxFrameBytes());
214
+ if (this.effectiveCap < 1024 || Buffer.byteLength(text) > this.effectiveCap) {
215
+ this.close(DEVICE_CLOSE.protocol, "Check frame limits: hello cannot fit");
216
+ return;
217
+ }
218
+ }
177
219
  clearTimeout(this.helloTimer);
178
220
  this.state = "claiming";
179
221
  // the raw summary too: the frame parser drops one it cannot read whole, and its
@@ -184,7 +226,12 @@ class DeviceConnection {
184
226
  if (!(await this.claim()))
185
227
  return;
186
228
  try {
187
- await this.gw.machines.recordHello(this.identity.machineId, frame, rawPolicy);
229
+ // a staged hello carries the authenticated owner report and runtime facts: recorded
230
+ // with the connection it opened (the id the machine gets in `ready`)
231
+ if (this.staged)
232
+ await this.gw.machines.recordHelloV3(this.identity.machineId, frame, this.connectionId);
233
+ else
234
+ await this.gw.machines.recordHello(this.identity.machineId, frame, rawPolicy);
188
235
  }
189
236
  catch (e) {
190
237
  this.gw.log.warn("could not record a device hello", {
@@ -203,7 +250,10 @@ class DeviceConnection {
203
250
  if (this.state === "closed")
204
251
  return;
205
252
  try {
206
- await this.gw.machines.recordPolicy(this.identity.machineId, frame.policy, rawPolicy);
253
+ if (this.staged)
254
+ await this.gw.machines.recordPolicyV3(this.identity.machineId, frame, this.connectionId);
255
+ else
256
+ await this.gw.machines.recordPolicy(this.identity.machineId, frame.policy, rawPolicy);
207
257
  }
208
258
  catch (e) {
209
259
  this.gw.log.warn("could not record a device policy change", {
@@ -215,7 +265,7 @@ class DeviceConnection {
215
265
  await this.recorded;
216
266
  return;
217
267
  }
218
- if (frame.type !== "res" || this.state === "hello") {
268
+ if (frame.type !== "res" || this.state === "hello" || (this.staged && !this.ready)) {
219
269
  this.close(DEVICE_CLOSE.protocol, "hello expected");
220
270
  return;
221
271
  }
@@ -227,16 +277,30 @@ class DeviceConnection {
227
277
  * Stores one result and announces it (the relay's wire, relay.ts), only for a request taken for
228
278
  * this device (ruling R20); anything else is dropped.
229
279
  */
230
- async store(res) {
280
+ async store(res,
281
+ /** The gateway's own refusal of a request it never sent (never a device's frame). */
282
+ notSent = false) {
231
283
  try {
232
- const stored = await this.gw.redis.eval(ACCEPT, 2, deviceTakenKey(res.id), deviceResKey(res.id), this.deviceId, JSON.stringify(res));
284
+ // the kernel-internal fields go next to the device's frame, which the relay strips before
285
+ // its strict parse. The device's frame was rebuilt by the strict parser; the marker is
286
+ // dropped from it all the same, so only this gateway's own refusal can carry it
287
+ const { [GATEWAY_NOT_SENT]: _never, ...frame } = res;
288
+ const tagged = this.staged
289
+ ? {
290
+ ...frame,
291
+ connectionId: this.connectionId,
292
+ maxFrameBytes: this.effectiveCap,
293
+ ...(notSent && { [GATEWAY_NOT_SENT]: true }),
294
+ }
295
+ : res;
296
+ const stored = await this.gw.redis.eval(ACCEPT, 2, deviceTakenKey(res.id), deviceResKey(res.id), this.deviceId, JSON.stringify(tagged));
233
297
  if (Number(stored) !== 1) {
234
298
  this.gw.log.warn("dropping a device result for a request not taken for its device", {
235
299
  deviceId: this.deviceId,
236
300
  });
237
301
  return;
238
302
  }
239
- await this.gw.bus.publish(deviceResTopic(res.id), res);
303
+ await this.gw.bus.publish(deviceResTopic(res.id), tagged);
240
304
  }
241
305
  catch (e) {
242
306
  this.gw.log.warn("could not store a device result", {
@@ -307,6 +371,22 @@ class DeviceConnection {
307
371
  deviceId: env,
308
372
  machineId: this.identity.machineId,
309
373
  });
374
+ if (this.staged) {
375
+ const raw = JSON.stringify({
376
+ type: "ready",
377
+ connectionId: this.connectionId,
378
+ maxFrameBytes: this.effectiveCap,
379
+ });
380
+ if (this.effectiveCap === undefined || Buffer.byteLength(raw) > this.effectiveCap)
381
+ throw new Error("Check frame limits: ready cannot fit");
382
+ parseDeviceFrameV3(raw, "kernel", this.effectiveCap);
383
+ // published before ready: a reader that sees the machine ready also finds its capacity
384
+ await this.publishCapacity();
385
+ if (this.state !== "holding")
386
+ return false;
387
+ this.socket.send(raw);
388
+ this.ready = true;
389
+ }
310
390
  // what was queued while nobody held the machine
311
391
  this.drain();
312
392
  return true;
@@ -341,15 +421,58 @@ class DeviceConnection {
341
421
  }
342
422
  async drainOnce() {
343
423
  const key = deviceReqKey(this.deviceId);
344
- while (this.state === "holding") {
424
+ while (this.state === "holding" && (!this.staged || this.ready)) {
425
+ if (this.staged &&
426
+ this.effectiveCap !== undefined &&
427
+ this.gw.maxFrameBytes() < this.effectiveCap) {
428
+ await this.close(DEVICE_CLOSE.protocol, "Frame capacity changed; reconnect");
429
+ return;
430
+ }
345
431
  // no lease fencing needed: the pop is atomic, so each frame reaches one connection only, and
346
432
  // a holder that lost its lease still talks to the device's own machine (or puts it back)
347
433
  const raw = (await this.gw.redis.eval(TAKE, 1, key, DEVICE_TAKEN_PREFIX, this.deviceId, String(this.gw.graceMs()), String(LIST_TTL_MARGIN_MS)));
348
434
  if (raw === null)
349
435
  return;
350
436
  let frame;
437
+ let wire = raw;
351
438
  try {
352
- frame = parseDeviceFrame(raw, "kernel");
439
+ const { connectionId, maxFrameBytes, [STOP_MACHINE]: stopFor, ...request } = JSON.parse(raw);
440
+ // a `stop` is fenced to the machine it was queued for (relay.send): a newer machine of
441
+ // the device never gets an older one's stop
442
+ if (stopFor !== undefined && stopFor !== this.identity.machineId) {
443
+ this.gw.log.warn("dropping a stop queued for another machine of the device", {
444
+ deviceId: this.deviceId,
445
+ });
446
+ continue;
447
+ }
448
+ if (this.staged) {
449
+ // a cancel carries no capacity-sized payload and must reach the machine after a
450
+ // reconnect too (an operation keeps running across a socket blip, as in protocol 2);
451
+ // so does a machine's `stop`, fenced to the machine above instead of the socket
452
+ const unfenced = request.type === "cancel" || (request.op === "stop" && stopFor !== undefined);
453
+ if (!unfenced &&
454
+ (connectionId !== this.connectionId || maxFrameBytes !== this.effectiveCap)) {
455
+ if (request.type === "req" && typeof request.id === "string")
456
+ await this.store({
457
+ type: "res",
458
+ id: request.id,
459
+ ok: false,
460
+ error: {
461
+ kind: "error",
462
+ message: connectionChangedMessage(String(request.op)),
463
+ },
464
+ }, true);
465
+ continue;
466
+ }
467
+ wire = JSON.stringify(request);
468
+ frame = parseDeviceFrameV3(wire, "kernel", this.effectiveCap);
469
+ }
470
+ else {
471
+ // protocol 2's wire stays byte for byte what the relay queued, minus the stop's fence
472
+ if (stopFor !== undefined)
473
+ wire = JSON.stringify(request);
474
+ frame = parseDeviceFrame(wire, "kernel");
475
+ }
353
476
  }
354
477
  catch (e) {
355
478
  this.gw.log.warn("dropping an invalid device request", {
@@ -364,7 +487,8 @@ class DeviceConnection {
364
487
  await this.gw.redis.eval(PUT_BACK, 1, key, raw, String(ttlMs));
365
488
  return;
366
489
  }
367
- if (frame.type === "req" && Buffer.byteLength(raw) > this.gw.maxFrameBytes()) {
490
+ if (frame.type === "req" &&
491
+ Buffer.byteLength(wire) > (this.effectiveCap ?? this.gw.maxFrameBytes())) {
368
492
  await this.store({
369
493
  type: "res",
370
494
  id: frame.id,
@@ -376,7 +500,7 @@ class DeviceConnection {
376
500
  });
377
501
  continue;
378
502
  }
379
- this.socket.send(raw);
503
+ this.socket.send(wire);
380
504
  }
381
505
  }
382
506
  /** The next ping (a chain of timeouts; the lease renewal is LockService's, not this timer's). */
@@ -399,8 +523,24 @@ class DeviceConnection {
399
523
  this.missedPongs++;
400
524
  this.socket.ping();
401
525
  // a backstop for a lost nudge (the bus delivers at most once)
402
- if (this.state === "holding")
526
+ if (this.state === "holding") {
527
+ if (this.staged)
528
+ void this.publishCapacity().then(() => {
529
+ this.publishFailures = 0;
530
+ }, (e) => {
531
+ // the key lives three pings: a transient failure is retried on the next ping, and
532
+ // only failures that would let the key expire close the connection
533
+ this.publishFailures++;
534
+ this.gw.log.warn("could not publish a device connection's capacity", {
535
+ deviceId: this.deviceId,
536
+ failures: this.publishFailures,
537
+ error: errMsg(e),
538
+ });
539
+ if (this.publishFailures >= MAX_PUBLISH_FAILURES)
540
+ void this.close(DEVICE_CLOSE.internal, "Capacity publication failed; reconnect");
541
+ });
403
542
  this.drain();
543
+ }
404
544
  if (this.state === "holding" && Date.now() - this.lastAuth >= REAUTH_EVERY_MS) {
405
545
  this.lastAuth = Date.now();
406
546
  void this.reauthenticate();
@@ -450,11 +590,14 @@ class DeviceConnection {
450
590
  if (this.released)
451
591
  return this.released;
452
592
  this.state = "closed";
593
+ this.ready = false;
453
594
  clearTimeout(this.helloTimer);
454
595
  clearTimeout(this.pingTimer);
455
596
  const lease = this.lease;
456
597
  this.released = (async () => {
457
598
  try {
599
+ if (this.staged)
600
+ await this.gw.redis.del(deviceTransportKey(this.deviceId, this.token));
458
601
  if (lease) {
459
602
  if (lease.lost.aborted)
460
603
  lease.abandon();
@@ -536,6 +679,27 @@ let LocalDeviceGateway = class LocalDeviceGateway {
536
679
  this.connections.add(conn);
537
680
  conn.start();
538
681
  }
682
+ /** Dormant authenticated seam; the production HTTP route never calls this until full cutover. */
683
+ async acceptStaged(socket, credential) {
684
+ socket.pause();
685
+ try {
686
+ const identity = await this.authenticate(credential);
687
+ if (!identity || this.stopping || socket.readyState !== socket.OPEN) {
688
+ socket.close(DEVICE_CLOSE.revoked, "Reconnect with a current credential");
689
+ return;
690
+ }
691
+ const conn = new DeviceConnection(this, socket, identity, credential, true);
692
+ this.connections.add(conn);
693
+ conn.start();
694
+ }
695
+ catch (error) {
696
+ this.log.warn("could not authenticate staged device connection", { error: errMsg(error) });
697
+ socket.close(DEVICE_CLOSE.internal, "Authentication unavailable; reconnect");
698
+ }
699
+ finally {
700
+ socket.resume();
701
+ }
702
+ }
539
703
  /**
540
704
  * How many devices this process holds the connection of (replica presence reports it): only
541
705
  * sockets past the hello that hold their device's lease, so a socket still claiming or being
@@ -568,3 +732,7 @@ LocalDeviceGateway = __decorate([
568
732
  __param(5, Inject(KERNEL_LOGGER))
569
733
  ], LocalDeviceGateway);
570
734
  export { LocalDeviceGateway };
735
+ /** Staged validation only; active connection acceptance above remains protocol 2. */
736
+ export function validateDeviceOperationFrameV3(raw, from) {
737
+ return parseDeviceFrameV3(raw, from);
738
+ }
@@ -1,7 +1,8 @@
1
1
  import type { ExecResult, FileSystemHandle, SandboxHandle, SandboxLimits, SandboxProvider, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
- import { ApiError } from "../errors.js";
2
+ import { type DeviceOperationV3, type SandboxPermissionSupport } from "@capybara-hq/plugin-sdk";
3
3
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
4
  import type { KernelLogger } from "../log.js";
5
+ import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
5
6
  import { SandboxService } from "../sandbox/sandbox.service.js";
6
7
  import { NetworkGrants } from "./network-grants.js";
7
8
  import { LocalDeviceRelay } from "./relay.js";
@@ -16,19 +17,27 @@ export declare const OP_DEADLINE_MS = 30000;
16
17
  * (ruling R26).
17
18
  */
18
19
  export declare const FRAME_ENVELOPE_BYTES: number;
20
+ export { projectsUnsupported } from "../devices/errors.js";
19
21
  /** The most raw bytes whose base64 plus {@link FRAME_ENVELOPE_BYTES} fit in `maxFrameBytes`. */
20
22
  export declare const maxReadBytes: (maxFrameBytes: number) => number;
21
- /**
22
- * The device offers no projects (project root §4.1): a local machine whose `capybara-device`
23
- * does not announce `projects`, or a cloud provider without `list` / `scan`.
24
- */
25
- export declare const projectsUnsupported: (local: boolean) => ApiError;
26
23
  /**
27
24
  * The refusal of a command on a machine whose local policy is auto mode while the organization (or
28
25
  * the platform) allows only sandbox mode (auto mode spec §4.3): re-checked at every exec, so a
29
26
  * machine switched locally is refused at the next command.
30
27
  */
31
28
  export declare const AUTO_MODE_NOT_ALLOWED_TEXT = "This device's machine runs in auto mode, which your organization does not allow. Run `capybara-device mode sandbox` on that machine to switch it to sandbox mode.";
29
+ /** What the staged provider sends through: the relay's protocol 3 call and the attested support. */
30
+ export interface StagedDeviceTransport {
31
+ call(deviceId: string, op: DeviceOperationV3, args: Record<string, unknown>, opts: {
32
+ deadlineMs: number;
33
+ signal: AbortSignal;
34
+ connection?: {
35
+ connectionId: string;
36
+ maxFrameBytes: number;
37
+ };
38
+ }): Promise<unknown>;
39
+ permissionSupport(deviceId: string, signal: AbortSignal): Promise<SandboxPermissionSupport>;
40
+ }
32
41
  /**
33
42
  * The handle of an instance on a machine: the device id (ruling R1: the relay is keyed by
34
43
  * device), the roots the machine reported at `create`, and the org's effective limits at
@@ -58,9 +67,35 @@ export declare class LocalDeviceProvider implements SandboxProvider {
58
67
  private readonly config;
59
68
  private readonly grants;
60
69
  private readonly log;
70
+ private readonly callGrants?;
61
71
  readonly concurrentExec: true;
62
72
  readonly sessionIsolation = false;
63
- constructor(relay: LocalDeviceRelay, targets: Pick<DeviceTargets, "orgOf" | "machineRoots" | "machineFeatures">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits">, config: Pick<KernelConfigService, "get">, grants: Pick<NetworkGrants, "forExec" | "reportedMode">, log: Pick<KernelLogger, "warn">);
73
+ constructor(relay: LocalDeviceRelay, targets: Pick<DeviceTargets, "orgOf" | "machineRoots" | "machineFeatures">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits">, config: Pick<KernelConfigService, "get">, grants: Pick<NetworkGrants, "forExec" | "reportedMode">, log: Pick<KernelLogger, "warn">, callGrants?: PermissionCallGrants | undefined);
74
+ /**
75
+ * The `@local` provider as the staged (protocol 3) registration hands it out
76
+ * (`LocalDevicesModule`): the protocol 2 lifecycle methods that send no frame (file system,
77
+ * resume, suspend, destroy), the v3 operation adapter ({@link stagedOperations}), `create` as a
78
+ * protocol 3 request, no raw protocol 2 call and no broad kill. Dormant until the protocol gate
79
+ * selects it.
80
+ *
81
+ * The raw methods (`exec`, `readFile`, `writeFile`, `stat`, `list`, `scan`) refuse before
82
+ * anything is queued: a v3 machine runs work only under an admitted operation scope, and
83
+ * missing operation support never falls back to them.
84
+ *
85
+ * A v3 machine has no `killAll` / `killTagged` (permission runtime cutover B-1), so both are
86
+ * no-ops that queue nothing. What reaches the machine instead is only what the kernel revokes
87
+ * exactly (`revokeOperation` per intent): `SandboxService` calls `OperationIntents.revokeHolders`
88
+ * with the crashed holders' tokens before `killTagged` and before `killLeftovers`' `killAll`, and
89
+ * that revokes those holders' admitted, dispatching and started-or-unknown intents only. Not
90
+ * covered today: the `killAll` after a failed limits change on a resumed instance and the one
91
+ * in `quarantine` (unreachable for `@local`) revoke nothing first; `killLeftovers` revokes only
92
+ * the dead tokens, not the started-or-unknown intents of live holders of the instance; and
93
+ * tokens `claimDeadHolders` already deleted are lost when `revokeHolders` then throws. Revoking
94
+ * every started-or-unknown intent of the generation on a v3 resume is W5-P3a's kernel change.
95
+ */
96
+ staged(transport: StagedDeviceTransport): SandboxProvider;
97
+ /** Dormant v3 adapter. It is not installed on the active v2 registered provider. */
98
+ stagedOperations(transport: StagedDeviceTransport): Required<Pick<SandboxProvider, "operation" | "prepare" | "browse" | "permissionSupport" | "revokeOperation" | "background">>;
64
99
  createFileSystem(args: {
65
100
  name: string;
66
101
  limits: SandboxLimits;