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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +6 -0
  3. package/dist/admin/org-network.service.d.ts +3 -1
  4. package/dist/admin/org-network.service.js +10 -2
  5. package/dist/app.d.ts +4 -0
  6. package/dist/app.js +2 -0
  7. package/dist/background/finish.d.ts +9 -1
  8. package/dist/background/finish.js +57 -4
  9. package/dist/background/launch.d.ts +23 -0
  10. package/dist/background/launch.js +55 -1
  11. package/dist/background/managed-output.d.ts +110 -0
  12. package/dist/background/managed-output.js +219 -0
  13. package/dist/background/managed.d.ts +52 -0
  14. package/dist/background/managed.js +128 -0
  15. package/dist/background/poll.job.d.ts +35 -1
  16. package/dist/background/poll.job.js +174 -9
  17. package/dist/background/render.js +1 -0
  18. package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
  19. package/dist/background/retire-legacy-tasks.job.js +149 -0
  20. package/dist/background/session.d.ts +15 -5
  21. package/dist/background/session.js +22 -6
  22. package/dist/background/stop.d.ts +35 -5
  23. package/dist/background/stop.js +94 -8
  24. package/dist/background/store.d.ts +110 -3
  25. package/dist/background/store.js +205 -3
  26. package/dist/background/tasks.service.d.ts +18 -1
  27. package/dist/background/tasks.service.js +99 -9
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/channels/cards.js +1 -1
  30. package/dist/channels/inbound.js +2 -0
  31. package/dist/channels/phrases.d.ts +4 -0
  32. package/dist/channels/phrases.js +4 -0
  33. package/dist/config/load.d.ts +18 -0
  34. package/dist/config/load.js +39 -1
  35. package/dist/config/permission-migration.d.ts +26 -0
  36. package/dist/config/permission-migration.js +64 -0
  37. package/dist/config/schema.d.ts +4 -1
  38. package/dist/config/schema.js +41 -10
  39. package/dist/conversations/conversations.controller.d.ts +1 -1
  40. package/dist/conversations/conversations.controller.js +1 -1
  41. package/dist/conversations/conversations.module.js +12 -0
  42. package/dist/conversations/conversations.service.d.ts +11 -2
  43. package/dist/conversations/conversations.service.js +97 -27
  44. package/dist/conversations/event-log.d.ts +1 -1
  45. package/dist/conversations/event-log.js +10 -2
  46. package/dist/conversations/events.d.ts +307 -4
  47. package/dist/conversations/events.js +286 -32
  48. package/dist/conversations/permission-profile-store.d.ts +50 -0
  49. package/dist/conversations/permission-profile-store.js +67 -0
  50. package/dist/conversations/permission-profile-store.module.d.ts +2 -0
  51. package/dist/conversations/permission-profile-store.module.js +19 -0
  52. package/dist/conversations/permission-profiles.controller.d.ts +84 -0
  53. package/dist/conversations/permission-profiles.controller.js +105 -0
  54. package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
  55. package/dist/conversations/permission-profiles.schemas.js +23 -0
  56. package/dist/conversations/permission-profiles.service.d.ts +56 -0
  57. package/dist/conversations/permission-profiles.service.js +179 -0
  58. package/dist/ctx/create-ctx.d.ts +12 -5
  59. package/dist/ctx/create-ctx.js +21 -5
  60. package/dist/db/kernel-schema.d.ts +248 -3
  61. package/dist/devices/access.js +1 -1
  62. package/dist/devices/access.module.d.ts +2 -0
  63. package/dist/devices/access.module.js +19 -0
  64. package/dist/devices/conversation-devices.d.ts +8 -29
  65. package/dist/devices/conversation-devices.js +37 -73
  66. package/dist/devices/device-projects.service.d.ts +26 -28
  67. package/dist/devices/device-projects.service.js +123 -127
  68. package/dist/devices/devices.controller.js +3 -1
  69. package/dist/devices/devices.module.js +11 -9
  70. package/dist/devices/devices.service.d.ts +116 -8
  71. package/dist/devices/devices.service.js +252 -20
  72. package/dist/devices/dto.d.ts +16 -0
  73. package/dist/devices/dto.js +34 -6
  74. package/dist/devices/errors.d.ts +8 -0
  75. package/dist/devices/errors.js +10 -0
  76. package/dist/devices/project-rules.d.ts +44 -0
  77. package/dist/devices/project-rules.js +27 -0
  78. package/dist/devices/working-root.d.ts +6 -0
  79. package/dist/devices/working-root.js +12 -1
  80. package/dist/errors.d.ts +31 -0
  81. package/dist/errors.js +31 -0
  82. package/dist/evals/reconstruct.d.ts +19 -2
  83. package/dist/evals/reconstruct.js +40 -2
  84. package/dist/evals/recorded-permission-context.d.ts +77 -0
  85. package/dist/evals/recorded-permission-context.js +151 -0
  86. package/dist/evals/recorded-tools.d.ts +10 -1
  87. package/dist/evals/recorded-tools.js +27 -3
  88. package/dist/evals/run-replay.d.ts +8 -2
  89. package/dist/evals/run-replay.js +18 -2
  90. package/dist/evals/trajectory.d.ts +1 -1
  91. package/dist/evals/worker.d.ts +10 -1
  92. package/dist/evals/worker.js +23 -14
  93. package/dist/extensions/host.d.ts +4 -1
  94. package/dist/extensions/host.js +10 -6
  95. package/dist/http/api.module.js +2 -0
  96. package/dist/identity/accounts.d.ts +14 -1
  97. package/dist/identity/accounts.js +61 -5
  98. package/dist/identity/identity.module.js +2 -0
  99. package/dist/identity/settings.d.ts +28 -12
  100. package/dist/identity/settings.js +89 -33
  101. package/dist/index.d.ts +6 -0
  102. package/dist/index.js +5 -0
  103. package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
  104. package/dist/infra/cli/kernel-cli.module.js +5 -2
  105. package/dist/infra/cli/permission-cutover.d.ts +59 -0
  106. package/dist/infra/cli/permission-cutover.js +107 -0
  107. package/dist/infra/config/kernel-config.service.d.ts +2 -2
  108. package/dist/infra/config/kernel-config.service.js +35 -11
  109. package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
  110. package/dist/infra/database/startup-activation-transaction.js +242 -0
  111. package/dist/infra/database/transaction-host.d.ts +47 -0
  112. package/dist/infra/database/transaction-host.js +119 -0
  113. package/dist/infra/database/xact-lock.d.ts +1 -0
  114. package/dist/infra/database/xact-lock.js +6 -0
  115. package/dist/infra/outbox/registry.d.ts +39 -0
  116. package/dist/infra/outbox/registry.js +18 -0
  117. package/dist/kernel.module.js +2 -0
  118. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  119. package/dist/lifecycle/kernel-lifecycle.js +55 -28
  120. package/dist/local-devices/device-auth.js +1 -1
  121. package/dist/local-devices/device-policy.service.d.ts +35 -5
  122. package/dist/local-devices/device-policy.service.js +188 -13
  123. package/dist/local-devices/instance-bindings.d.ts +82 -0
  124. package/dist/local-devices/instance-bindings.js +304 -0
  125. package/dist/local-devices/keys.d.ts +5 -0
  126. package/dist/local-devices/keys.js +5 -0
  127. package/dist/local-devices/local-device-gateway.d.ts +19 -4
  128. package/dist/local-devices/local-device-gateway.js +185 -17
  129. package/dist/local-devices/local-device-provider.d.ts +42 -7
  130. package/dist/local-devices/local-device-provider.js +185 -10
  131. package/dist/local-devices/local-devices.module.d.ts +17 -2
  132. package/dist/local-devices/local-devices.module.js +49 -8
  133. package/dist/local-devices/machines.d.ts +35 -12
  134. package/dist/local-devices/machines.js +203 -8
  135. package/dist/local-devices/network-grants.js +3 -3
  136. package/dist/local-devices/network-grants.module.d.ts +2 -0
  137. package/dist/local-devices/network-grants.module.js +14 -0
  138. package/dist/local-devices/owner-report.d.ts +79 -0
  139. package/dist/local-devices/owner-report.js +155 -0
  140. package/dist/local-devices/owner-reports.d.ts +48 -0
  141. package/dist/local-devices/owner-reports.js +190 -0
  142. package/dist/local-devices/policy-summary.d.ts +24 -1
  143. package/dist/local-devices/policy-summary.js +48 -0
  144. package/dist/local-devices/relay.d.ts +82 -6
  145. package/dist/local-devices/relay.js +187 -16
  146. package/dist/local-devices/targets.d.ts +16 -1
  147. package/dist/local-devices/targets.js +35 -2
  148. package/dist/models/image-usable.d.ts +22 -0
  149. package/dist/models/image-usable.js +29 -0
  150. package/dist/models/images.d.ts +125 -0
  151. package/dist/models/images.js +440 -0
  152. package/dist/models/models.module.d.ts +3 -2
  153. package/dist/models/models.module.js +16 -5
  154. package/dist/models/org-models.schemas.js +1 -0
  155. package/dist/models/purposes.controller.d.ts +7 -0
  156. package/dist/models/purposes.controller.js +9 -0
  157. package/dist/models/purposes.d.ts +28 -3
  158. package/dist/models/purposes.js +40 -13
  159. package/dist/orgs/cloud-network-setting.d.ts +33 -0
  160. package/dist/orgs/cloud-network-setting.js +47 -0
  161. package/dist/orgs/offboarding.d.ts +3 -1
  162. package/dist/orgs/offboarding.js +8 -2
  163. package/dist/orgs/org-lock.d.ts +10 -4
  164. package/dist/orgs/org-lock.js +10 -4
  165. package/dist/orgs/orgs.service.d.ts +3 -1
  166. package/dist/orgs/orgs.service.js +8 -2
  167. package/dist/orgs/settings.controller.d.ts +4 -1
  168. package/dist/orgs/settings.controller.js +3 -3
  169. package/dist/orgs/settings.service.d.ts +48 -56
  170. package/dist/orgs/settings.service.js +144 -101
  171. package/dist/overrides.d.ts +6 -1
  172. package/dist/overrides.js +2 -0
  173. package/dist/platform/exclusions.js +20 -0
  174. package/dist/platform/ops/admin.ops.js +14 -11
  175. package/dist/platform/ops/agent-skills.ops.js +2 -0
  176. package/dist/platform/ops/devices.ops.js +10 -2
  177. package/dist/platform/ops/models.ops.js +10 -0
  178. package/dist/platform/ops/org-settings.ops.js +6 -6
  179. package/dist/platform/ops/orgs.ops.js +1 -0
  180. package/dist/roles/worker.module.js +4 -0
  181. package/dist/runtime/context/build.d.ts +3 -1
  182. package/dist/runtime/context/build.js +19 -3
  183. package/dist/runtime/context/compaction.js +5 -0
  184. package/dist/runtime/context/device-paths.d.ts +9 -2
  185. package/dist/runtime/context/device-paths.js +20 -0
  186. package/dist/runtime/context/permission-profile.d.ts +46 -0
  187. package/dist/runtime/context/permission-profile.js +194 -0
  188. package/dist/runtime/hook-calls.d.ts +11 -1
  189. package/dist/runtime/hook-calls.js +24 -1
  190. package/dist/runtime/maintenance.d.ts +7 -1
  191. package/dist/runtime/maintenance.js +43 -15
  192. package/dist/runtime/model-call.d.ts +32 -0
  193. package/dist/runtime/model-call.js +67 -0
  194. package/dist/runtime/permission-context-errors.d.ts +39 -0
  195. package/dist/runtime/permission-context-errors.js +67 -0
  196. package/dist/runtime/permission-context.service.d.ts +60 -0
  197. package/dist/runtime/permission-context.service.js +286 -0
  198. package/dist/runtime/project/knowledge.d.ts +7 -2
  199. package/dist/runtime/project/knowledge.js +5 -2
  200. package/dist/runtime/project/knowledge.service.d.ts +17 -2
  201. package/dist/runtime/project/knowledge.service.js +76 -12
  202. package/dist/runtime/providers.d.ts +9 -5
  203. package/dist/runtime/providers.js +22 -3
  204. package/dist/runtime/run-execution.d.ts +4 -1
  205. package/dist/runtime/run-execution.js +14 -5
  206. package/dist/runtime/run-steps.d.ts +11 -3
  207. package/dist/runtime/run-steps.js +27 -4
  208. package/dist/runtime/runtime.module.js +11 -0
  209. package/dist/runtime/usage-report.d.ts +10 -6
  210. package/dist/runtime/usage-report.js +31 -11
  211. package/dist/sandbox/attachments-path.d.ts +15 -0
  212. package/dist/sandbox/attachments-path.js +15 -0
  213. package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
  214. package/dist/sandbox/cloud-permission-snapshot.js +407 -0
  215. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
  216. package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
  217. package/dist/sandbox/held-operations.d.ts +39 -0
  218. package/dist/sandbox/held-operations.js +119 -0
  219. package/dist/sandbox/jobs.d.ts +14 -3
  220. package/dist/sandbox/jobs.js +20 -2
  221. package/dist/sandbox/kernel-read.d.ts +55 -0
  222. package/dist/sandbox/kernel-read.js +57 -0
  223. package/dist/sandbox/legacy-retirement.d.ts +336 -0
  224. package/dist/sandbox/legacy-retirement.js +1063 -0
  225. package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
  226. package/dist/sandbox/legacy-retirement.module.js +25 -0
  227. package/dist/sandbox/managed-device-context.d.ts +94 -0
  228. package/dist/sandbox/managed-device-context.js +308 -0
  229. package/dist/sandbox/managed-device-context.module.d.ts +6 -0
  230. package/dist/sandbox/managed-device-context.module.js +33 -0
  231. package/dist/sandbox/modes.d.ts +56 -8
  232. package/dist/sandbox/modes.js +92 -8
  233. package/dist/sandbox/operation-authority-types.d.ts +8 -0
  234. package/dist/sandbox/operation-authority-types.js +32 -0
  235. package/dist/sandbox/operation-authority.d.ts +145 -0
  236. package/dist/sandbox/operation-authority.js +783 -0
  237. package/dist/sandbox/operation-authority.module.d.ts +2 -0
  238. package/dist/sandbox/operation-authority.module.js +29 -0
  239. package/dist/sandbox/operation-intents.d.ts +206 -0
  240. package/dist/sandbox/operation-intents.js +1252 -0
  241. package/dist/sandbox/operation-intents.module.d.ts +2 -0
  242. package/dist/sandbox/operation-intents.module.js +21 -0
  243. package/dist/sandbox/operation-payloads.d.ts +33 -0
  244. package/dist/sandbox/operation-payloads.js +332 -0
  245. package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
  246. package/dist/sandbox/operation-reconcile.job.js +247 -0
  247. package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
  248. package/dist/sandbox/permission-authority-epochs.js +83 -0
  249. package/dist/sandbox/permission-authority-lock.d.ts +38 -0
  250. package/dist/sandbox/permission-authority-lock.js +147 -0
  251. package/dist/sandbox/permission-authority.module.d.ts +9 -0
  252. package/dist/sandbox/permission-authority.module.js +55 -0
  253. package/dist/sandbox/permission-availability.d.ts +18 -0
  254. package/dist/sandbox/permission-availability.js +19 -0
  255. package/dist/sandbox/permission-call-grants.d.ts +34 -0
  256. package/dist/sandbox/permission-call-grants.js +349 -0
  257. package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
  258. package/dist/sandbox/permission-call-grants.module.js +21 -0
  259. package/dist/sandbox/permission-call-types.d.ts +82 -0
  260. package/dist/sandbox/permission-call-types.js +1 -0
  261. package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
  262. package/dist/sandbox/permission-ceiling-writes.js +223 -0
  263. package/dist/sandbox/permission-config-publication.d.ts +76 -0
  264. package/dist/sandbox/permission-config-publication.js +339 -0
  265. package/dist/sandbox/permission-context-types.d.ts +64 -0
  266. package/dist/sandbox/permission-context-types.js +24 -0
  267. package/dist/sandbox/permission-facts.d.ts +206 -0
  268. package/dist/sandbox/permission-facts.js +627 -0
  269. package/dist/sandbox/permission-facts.module.d.ts +2 -0
  270. package/dist/sandbox/permission-facts.module.js +20 -0
  271. package/dist/sandbox/permission-instance-writes.d.ts +90 -0
  272. package/dist/sandbox/permission-instance-writes.js +305 -0
  273. package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
  274. package/dist/sandbox/permission-runtime-reports.js +354 -0
  275. package/dist/sandbox/permission-transitions.d.ts +31 -0
  276. package/dist/sandbox/permission-transitions.js +155 -0
  277. package/dist/sandbox/platform-full-access.d.ts +128 -0
  278. package/dist/sandbox/platform-full-access.js +210 -0
  279. package/dist/sandbox/providers.d.ts +22 -0
  280. package/dist/sandbox/providers.js +10 -2
  281. package/dist/sandbox/providers.module.d.ts +2 -0
  282. package/dist/sandbox/providers.module.js +19 -0
  283. package/dist/sandbox/request-not-sent.d.ts +13 -0
  284. package/dist/sandbox/request-not-sent.js +13 -0
  285. package/dist/sandbox/review/classifier.d.ts +2 -0
  286. package/dist/sandbox/review/classifier.js +8 -0
  287. package/dist/sandbox/review/permission-candidate.d.ts +12 -0
  288. package/dist/sandbox/review/permission-candidate.js +145 -0
  289. package/dist/sandbox/review/review.service.d.ts +5 -2
  290. package/dist/sandbox/review/review.service.js +60 -15
  291. package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
  292. package/dist/sandbox/sandbox-file-reader.js +51 -7
  293. package/dist/sandbox/sandbox.module.js +26 -6
  294. package/dist/sandbox/sandbox.service.d.ts +230 -34
  295. package/dist/sandbox/sandbox.service.js +1368 -199
  296. package/dist/sandbox/unreachable.js +17 -3
  297. package/dist/sandbox/use-context.d.ts +17 -0
  298. package/dist/sandbox/use-context.js +1 -0
  299. package/dist/skills/invoke.d.ts +27 -4
  300. package/dist/skills/invoke.js +72 -7
  301. package/dist/tools/approvals.controller.d.ts +1 -0
  302. package/dist/tools/approvals.schemas.d.ts +1 -0
  303. package/dist/tools/approvals.schemas.js +3 -1
  304. package/dist/tools/approvals.service.d.ts +23 -10
  305. package/dist/tools/approvals.service.js +104 -26
  306. package/dist/tools/builtin-names.d.ts +3 -1
  307. package/dist/tools/builtin-names.js +5 -1
  308. package/dist/tools/builtins/artifacts.d.ts +43 -0
  309. package/dist/tools/builtins/artifacts.js +67 -0
  310. package/dist/tools/builtins/builtin-tools.d.ts +20 -2
  311. package/dist/tools/builtins/builtin-tools.js +61 -10
  312. package/dist/tools/builtins/image/generate.d.ts +59 -0
  313. package/dist/tools/builtins/image/generate.js +535 -0
  314. package/dist/tools/builtins/image/index.d.ts +2 -0
  315. package/dist/tools/builtins/image/index.js +2 -0
  316. package/dist/tools/builtins/image/paths.d.ts +12 -0
  317. package/dist/tools/builtins/image/paths.js +26 -0
  318. package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
  319. package/dist/tools/builtins/sandbox/bash.js +201 -5
  320. package/dist/tools/builtins/sandbox/common.d.ts +92 -20
  321. package/dist/tools/builtins/sandbox/common.js +201 -17
  322. package/dist/tools/builtins/sandbox/deliver.js +9 -51
  323. package/dist/tools/builtins/sandbox/edit.js +2 -2
  324. package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
  325. package/dist/tools/builtins/sandbox/glob.js +2 -2
  326. package/dist/tools/builtins/sandbox/grep.js +2 -2
  327. package/dist/tools/builtins/sandbox/read.js +2 -2
  328. package/dist/tools/builtins/sandbox/task-list.js +7 -1
  329. package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
  330. package/dist/tools/builtins/sandbox/task-output.js +172 -0
  331. package/dist/tools/builtins/sandbox/task-stop.js +25 -3
  332. package/dist/tools/builtins/sandbox/write.js +2 -2
  333. package/dist/tools/builtins/skill-load.js +9 -6
  334. package/dist/tools/device-op-resolver.d.ts +1 -1
  335. package/dist/tools/device-op-resolver.js +13 -3
  336. package/dist/tools/permission-approval-jobs.d.ts +18 -0
  337. package/dist/tools/permission-approval-jobs.js +92 -0
  338. package/dist/tools/pipeline.d.ts +17 -2
  339. package/dist/tools/pipeline.js +315 -26
  340. package/dist/tools/registry.d.ts +9 -0
  341. package/dist/tools/tools.module.js +15 -0
  342. package/package.json +4 -3
  343. package/src/migrations/0146_permission_authority_epochs.sql +6 -0
  344. package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
  345. package/src/migrations/0148_first_message_request_hash.sql +2 -0
  346. package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
  347. package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
  348. package/src/migrations/0151_starting_execution_grants.sql +8 -0
  349. package/src/migrations/0152_background_launch_identity.sql +66 -0
  350. package/src/migrations/0153_background_cancel_requester.sql +13 -0
  351. package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
  352. package/src/migrations/0155_device_instance_generations.sql +30 -0
  353. package/src/migrations/0156_device_owner_report.sql +7 -0
  354. package/src/migrations/0157_legacy_retirement.sql +116 -0
  355. package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
  356. package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
  357. package/src/migrations/0160_model_usage_image_kind.sql +10 -0
  358. package/dist/sandbox/platform-auto-mode.d.ts +0 -63
  359. package/dist/sandbox/platform-auto-mode.js +0 -63
@@ -8,25 +8,29 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { rootsOf } from "@capybara-hq/plugin-sdk";
11
- import { Inject, Injectable } from "@nestjs/common";
11
+ import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { EventLog } from "../conversations/event-log.js";
13
13
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
14
  import { LockService } from "../infra/lock/lock.service.js";
15
15
  import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
16
16
  import { LockedInterval } from "../infra/schedule/locked-interval.js";
17
- import { KERNEL_LOGGER } from "../infra/tokens.js";
18
- import { SandboxService, } from "../sandbox/sandbox.service.js";
17
+ import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
18
+ import { PERMISSION_CONTEXT_ACTIVATION } from "../sandbox/permission-context-types.js";
19
+ import { RetirementPendingError, SandboxService, } from "../sandbox/sandbox.service.js";
19
20
  import { sandboxBaseTimeoutMs } from "../tools/builtins/sandbox/common.js";
20
21
  import { BackgroundTaskFinisher } from "./finish.js";
21
22
  import { LAUNCH_EXEC_TIMEOUT_MS } from "./launch.js";
23
+ import { exactRefOf, lastLinesByRef, onManagedInstance, statusEnd, summaryLines, } from "./managed.js";
22
24
  import { actingAs, taskActor } from "./session.js";
23
25
  import { parsePollOutput, polledAs, pollScript } from "./status.js";
24
- import { notRunningAs, RECREATED } from "./stop.js";
26
+ import { BackgroundTaskStopper, notRunningAs, RECREATED } from "./stop.js";
25
27
  import { BackgroundTaskStore } from "./store.js";
26
28
  /** The poll of the running background tasks (`@LockedInterval`, every `pollSeconds`). */
27
29
  export const BACKGROUND_POLL_JOB = "background-task-poll";
28
30
  /** The daily prune of finished background tasks older than `tools.outputRetentionDays`. */
29
31
  export const BACKGROUND_PRUNE_JOB = "background-task-prune";
32
+ /** The most owed managed cancellations one poll applies (each a lease and up to a 5 s grace). */
33
+ export const MANAGED_STOPS_PER_TICK = 8;
30
34
  /** The least age at which a reservation counts as abandoned, whatever the config. */
31
35
  const LAUNCH_ABANDONED_FLOOR_MS = 120_000;
32
36
  /**
@@ -60,7 +64,17 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
60
64
  config;
61
65
  lockService;
62
66
  log;
63
- constructor(store, finisher, eventLog, sandbox, config, lockService, log) {
67
+ stopper;
68
+ activation;
69
+ redis;
70
+ constructor(store, finisher, eventLog, sandbox, config, lockService, log, stopper,
71
+ /**
72
+ * The paired activation gate: once on, a legacy (SID) task is never polled by a raw exec;
73
+ * its instance's poll is refused for the retirement gate ({@link pollSandbox}).
74
+ */
75
+ activation,
76
+ /** The marker that logs a refused legacy poll once per instance across the replicas. */
77
+ redis) {
64
78
  this.store = store;
65
79
  this.finisher = finisher;
66
80
  this.eventLog = eventLog;
@@ -68,6 +82,9 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
68
82
  this.config = config;
69
83
  this.lockService = lockService;
70
84
  this.log = log;
85
+ this.stopper = stopper;
86
+ this.activation = activation;
87
+ this.redis = redis;
71
88
  }
72
89
  async poll(signal) {
73
90
  await this.pollOnce(signal);
@@ -119,17 +136,141 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
119
136
  });
120
137
  }
121
138
  }
139
+ finished += await this.pollManaged(signal);
122
140
  if (finished > 0)
123
141
  this.log.info("background tasks finished", { count: finished });
124
142
  return finished;
125
143
  }
144
+ /**
145
+ * The managed tasks (permission runtime cutover phase 8.3), by exact ref only: an acknowledged
146
+ * task's status on its exact instance (one lease per instance, never resumed; an exit or a lost
147
+ * supervision finishes it with the exact tail's last lines), and a `cancel-pending` task's owed
148
+ * exact stop (through the stopper, so its claim, outcome and requester's wake rule hold). A
149
+ * malformed ref is never used; an unavailable provider leaves its tasks as they are.
150
+ */
151
+ async pollManaged(signal) {
152
+ const groups = new Map();
153
+ const cancels = [];
154
+ for (const t of [...(await this.store.runningManaged()), ...(await this.store.owedCancels())]) {
155
+ try {
156
+ exactRefOf(t);
157
+ }
158
+ catch (err) {
159
+ this.log.warn("a managed background task has a malformed reference; skipped", {
160
+ taskId: t.id,
161
+ err,
162
+ });
163
+ continue;
164
+ }
165
+ if (t.launchState === "cancel-pending") {
166
+ cancels.push(t);
167
+ continue;
168
+ }
169
+ const key = `${t.deviceId} ${t.instanceGeneration}`;
170
+ groups.set(key, [...(groups.get(key) ?? []), t]);
171
+ }
172
+ let n = 0;
173
+ for (const tasks of groups.values()) {
174
+ if (signal.aborted)
175
+ break;
176
+ const [first] = tasks;
177
+ try {
178
+ if (!(await this.sandbox.availableFor(first.deviceId)))
179
+ continue;
180
+ n += await this.pollManagedInstance(tasks, signal);
181
+ }
182
+ catch (err) {
183
+ if (signal.aborted)
184
+ break;
185
+ this.log.warn("cannot poll managed background tasks; retrying next tick", {
186
+ deviceId: first.deviceId,
187
+ err,
188
+ });
189
+ }
190
+ }
191
+ // Bounded per tick: at most this many stops that reach a provider, least recently attempted
192
+ // first (an attempt moves a task to the back, so one that keeps failing never holds the head);
193
+ // a task whose provider is not loaded takes no turn. The rest stay owed for the next ticks.
194
+ let attempts = 0;
195
+ for (const t of cancels) {
196
+ if (signal.aborted || attempts >= MANAGED_STOPS_PER_TICK)
197
+ break;
198
+ try {
199
+ if (!(await this.sandbox.availableFor(t.deviceId)))
200
+ continue;
201
+ attempts++;
202
+ const after = await this.stopper.stop(t, "revoked", signal);
203
+ if (after.status !== "running")
204
+ n++;
205
+ }
206
+ catch (err) {
207
+ this.log.warn("cannot apply an owed background task cancellation; retrying next tick", {
208
+ taskId: t.id,
209
+ err,
210
+ });
211
+ }
212
+ }
213
+ return n;
214
+ }
215
+ /** The exact statuses of one instance's acknowledged managed tasks; returns how many finished. */
216
+ async pollManagedInstance(tasks, signal) {
217
+ const [first] = tasks;
218
+ const r = await onManagedInstance(this.sandbox.ifRunning.bind(this.sandbox), first, async (bg, h, _ref, sig) => {
219
+ const ends = new Map();
220
+ for (const t of tasks) {
221
+ // one task's failing status never holds back the others of its instance
222
+ try {
223
+ const { ref } = exactRefOf(t);
224
+ const to = statusEnd(await bg.status(h, ref, sig));
225
+ if (to) {
226
+ ends.set(t.id, {
227
+ to,
228
+ lastLines: summaryLines(await lastLinesByRef(bg, h, ref, sig)),
229
+ });
230
+ }
231
+ }
232
+ catch (err) {
233
+ sig.throwIfAborted();
234
+ this.log.warn("cannot read a managed background task's status; retrying next tick", {
235
+ taskId: t.id,
236
+ err,
237
+ });
238
+ }
239
+ }
240
+ return ends;
241
+ }, signal);
242
+ let n = 0;
243
+ for (const t of tasks) {
244
+ const end = r.kind === "ran"
245
+ ? r.value.get(t.id)
246
+ : r.kind === "not_running"
247
+ ? { to: notRunningAs(r.status, false), lastLines: "" }
248
+ : { to: RECREATED, lastLines: "" };
249
+ // a stop that claimed the task after the read above finishes it itself
250
+ if (end && (await this.finisher.finish(t, end.to, end.lastLines, false, { unclaimed: true })))
251
+ n++;
252
+ }
253
+ return n;
254
+ }
126
255
  /** Polls the tasks of one device instance; returns how many finished. */
127
256
  async pollSandbox(tasks, signal) {
128
257
  const [first] = tasks;
129
258
  // a task from before devices has no instance any more
130
- const r = first.deviceId === null
131
- ? { kind: "not_running", status: "gone" }
132
- : await this.sandbox.ifRunning(first.deviceId, { createdAt: first.sandboxCreatedAt }, (p, h, sig) => this.pollExec(actingAs(p, taskActor(first)), h, tasks, sig), signal);
259
+ let r;
260
+ try {
261
+ r =
262
+ first.deviceId === null
263
+ ? { kind: "not_running", status: "gone" }
264
+ : await this.sandbox.ifRunning(first.deviceId, { createdAt: first.sandboxCreatedAt }, (p, h, sig) => this.pollExec(actingAs(p, taskActor(first), this.activation), h, tasks, sig), signal);
265
+ }
266
+ catch (err) {
267
+ // once activated, a running legacy instance is the retirement gate's: its tasks stay as
268
+ // they are until it retires them; said once per instance, not as a warning every tick
269
+ if (!(err instanceof RetirementPendingError))
270
+ throw err;
271
+ await this.noteRetirementOnce(first);
272
+ return 0;
273
+ }
133
274
  const now = new Date();
134
275
  let n = 0;
135
276
  for (const t of tasks) {
@@ -154,6 +295,25 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
154
295
  }
155
296
  return n;
156
297
  }
298
+ /**
299
+ * Logs at `info`, once per legacy instance across the replicas (a Redis marker; every time
300
+ * without one), that its tasks are left to the retirement gate. A Redis failure logs anyway.
301
+ */
302
+ async noteRetirementOnce(first) {
303
+ const instance = `${first.deviceId}:${first.sandboxCreatedAt?.getTime() ?? 0}`;
304
+ // a log marker, not a lock: the previous value says whether this instance was logged (two
305
+ // replicas racing may both log, which is harmless)
306
+ const firstTime = this.redis === undefined ||
307
+ (await this.redis
308
+ .set(`capk:bg-legacy-retirement-noted:${instance}`, "1", "EX", 86_400, "GET")
309
+ .then((prev) => prev === null)
310
+ .catch(() => true));
311
+ if (firstTime)
312
+ this.log.info("legacy background tasks left to the retirement gate; not polled", {
313
+ deviceId: first.deviceId,
314
+ instanceGeneration: first.sandboxCreatedAt?.getTime(),
315
+ });
316
+ }
157
317
  /** The poll exec of one instance: each task's report by id. */
158
318
  async pollExec(p, h, tasks, signal) {
159
319
  const res = await p.exec(h, {
@@ -190,6 +350,11 @@ BackgroundTaskPollJob = __decorate([
190
350
  __param(3, Inject(SandboxService)),
191
351
  __param(4, Inject(KernelConfigService)),
192
352
  __param(5, Inject(LockService)),
193
- __param(6, Inject(KERNEL_LOGGER))
353
+ __param(6, Inject(KERNEL_LOGGER)),
354
+ __param(7, Inject(BackgroundTaskStopper)),
355
+ __param(8, Optional()),
356
+ __param(8, Inject(PERMISSION_CONTEXT_ACTIVATION)),
357
+ __param(9, Optional()),
358
+ __param(9, Inject(REDIS))
194
359
  ], BackgroundTaskPollJob);
195
360
  export { BackgroundTaskPollJob };
@@ -14,6 +14,7 @@ const LOST_REASONS = {
14
14
  sandbox_recreated: "the sandbox was recreated",
15
15
  process_gone: "its processes ended without an exit code",
16
16
  launch_abandoned: "its launch was interrupted",
17
+ supervision_lost: "its supervision was lost",
17
18
  };
18
19
  /** Why a task was lost, as the model reads it (an unknown reason as is). */
19
20
  export const lostReasonText = (reason) => LOST_REASONS[reason] ?? reason;
@@ -0,0 +1,57 @@
1
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
+ import { LockService } from "../infra/lock/lock.service.js";
3
+ import type { KernelLogger } from "../log.js";
4
+ import { LegacyRetirementStore } from "../sandbox/legacy-retirement.js";
5
+ import { SandboxOperationIntents } from "../sandbox/operation-intents.js";
6
+ import { SandboxService } from "../sandbox/sandbox.service.js";
7
+ import { BackgroundTaskStore } from "./store.js";
8
+ /** The job's name (`@LockedInterval`, run lock `cron:background-retire-legacy-tasks`). */
9
+ export declare const RETIRE_LEGACY_TASKS_JOB = "background-retire-legacy-tasks";
10
+ /** Devices one tick tries (each one exclusive lease and at most one provider destroy each). */
11
+ export declare const RETIRE_DEVICES_PER_TICK = 10;
12
+ /** What one run did. */
13
+ export interface RetireLegacyResult {
14
+ /** New obligation members the enumeration recorded. */
15
+ added: number;
16
+ /** Devices left without an unresolved obligation. */
17
+ cleared: number;
18
+ /** Devices still unavailable (quarantined, or a destroy that failed). */
19
+ unavailable: number;
20
+ /** Devices held by someone: their next lifecycle acquisition runs the gate inline. */
21
+ busy: number;
22
+ /** Members whose own records were settled. */
23
+ settled: number;
24
+ /** Obligations abandoned with their deleted devices this tick. */
25
+ abandoned: number;
26
+ }
27
+ /**
28
+ * Legacy retirement (permission runtime cutover phase 8.5), once per tick across replicas:
29
+ * 1. enumerates, until a pass adds nothing ({@link LegacyRetirementStore.scanUntilStable}),
30
+ * the legacy rows (once the legacy-launch freeze is published) and the revoked managed starts
31
+ * on incarnations that no longer run, as members of their device incarnation's obligation;
32
+ * 2. for up to {@link RETIRE_DEVICES_PER_TICK} devices with an obligation due (backoff per
33
+ * attempt), runs the sandbox service's retirement gate under one try at the exclusive
34
+ * lifecycle lease (`SandboxService.retireLegacy`): a cloud incarnation is destroyed whole by its
35
+ * provider, a local or unverifiable one is quarantined, a failure keeps the obligation;
36
+ * 3. settles the members of resolved obligations: a revoked start's revocation is acknowledged
37
+ * and its task's owed cancellation settled (`settleOwedCancel`; finish and event stay the
38
+ * task's own), a legacy row's `kill_pending` is cleared (no process of a confirmed destroyed
39
+ * incarnation can exist).
40
+ * Retryable and bounded; the job missing or late never lets a device be used: every lifecycle
41
+ * acquisition runs the same gate inline.
42
+ */
43
+ export declare class RetireLegacyTasksJob {
44
+ private readonly retirement;
45
+ private readonly sandbox;
46
+ private readonly intents;
47
+ private readonly tasks;
48
+ readonly config: KernelConfigService;
49
+ readonly lockService: LockService;
50
+ readonly log: KernelLogger;
51
+ constructor(retirement: Pick<LegacyRetirementStore, "scanUntilStable" | "due" | "unsettledMembers" | "markSettled" | "abandonDeleted">, sandbox: Pick<SandboxService, "retireLegacy">, intents: Pick<SandboxOperationIntents, "acknowledgeRevocation">, tasks: Pick<BackgroundTaskStore, "byOperation" | "settleOwedCancel" | "clearKill">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
52
+ tick(signal?: AbortSignal): Promise<void>;
53
+ /** One run (see the class); `signal` (the stop, or a lost run lock) is read between devices. */
54
+ runOnce(signal?: AbortSignal): Promise<RetireLegacyResult>;
55
+ /** Settles one member of a resolved obligation; false while its task still runs. */
56
+ private settle;
57
+ }
@@ -0,0 +1,149 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
12
+ import { LockService } from "../infra/lock/lock.service.js";
13
+ import { LockedInterval } from "../infra/schedule/locked-interval.js";
14
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
15
+ import { LegacyRetirementStore } from "../sandbox/legacy-retirement.js";
16
+ import { SandboxOperationIntents } from "../sandbox/operation-intents.js";
17
+ import { SandboxService } from "../sandbox/sandbox.service.js";
18
+ import { BackgroundTaskStore } from "./store.js";
19
+ /** The job's name (`@LockedInterval`, run lock `cron:background-retire-legacy-tasks`). */
20
+ export const RETIRE_LEGACY_TASKS_JOB = "background-retire-legacy-tasks";
21
+ /** Every minute, once per tick across replicas. */
22
+ const PERIOD_MS = 60_000;
23
+ /** Devices one tick tries (each one exclusive lease and at most one provider destroy each). */
24
+ export const RETIRE_DEVICES_PER_TICK = 10;
25
+ /** Members of resolved obligations one tick settles. */
26
+ const SETTLE_PER_TICK = 100;
27
+ /** Obligations of gone devices resolved or abandoned per tick. */
28
+ const ABANDON_PER_TICK = 100;
29
+ /** The run lock outlives the slowest tick: a destroy per device. */
30
+ const TICK_TTL_MS = 15 * 60_000;
31
+ /**
32
+ * Legacy retirement (permission runtime cutover phase 8.5), once per tick across replicas:
33
+ * 1. enumerates, until a pass adds nothing ({@link LegacyRetirementStore.scanUntilStable}),
34
+ * the legacy rows (once the legacy-launch freeze is published) and the revoked managed starts
35
+ * on incarnations that no longer run, as members of their device incarnation's obligation;
36
+ * 2. for up to {@link RETIRE_DEVICES_PER_TICK} devices with an obligation due (backoff per
37
+ * attempt), runs the sandbox service's retirement gate under one try at the exclusive
38
+ * lifecycle lease (`SandboxService.retireLegacy`): a cloud incarnation is destroyed whole by its
39
+ * provider, a local or unverifiable one is quarantined, a failure keeps the obligation;
40
+ * 3. settles the members of resolved obligations: a revoked start's revocation is acknowledged
41
+ * and its task's owed cancellation settled (`settleOwedCancel`; finish and event stay the
42
+ * task's own), a legacy row's `kill_pending` is cleared (no process of a confirmed destroyed
43
+ * incarnation can exist).
44
+ * Retryable and bounded; the job missing or late never lets a device be used: every lifecycle
45
+ * acquisition runs the same gate inline.
46
+ */
47
+ let RetireLegacyTasksJob = class RetireLegacyTasksJob {
48
+ retirement;
49
+ sandbox;
50
+ intents;
51
+ tasks;
52
+ config;
53
+ lockService;
54
+ log;
55
+ constructor(retirement, sandbox, intents, tasks, config, lockService, log) {
56
+ this.retirement = retirement;
57
+ this.sandbox = sandbox;
58
+ this.intents = intents;
59
+ this.tasks = tasks;
60
+ this.config = config;
61
+ this.lockService = lockService;
62
+ this.log = log;
63
+ }
64
+ async tick(signal) {
65
+ const r = await this.runOnce(signal);
66
+ if (r.added + r.cleared + r.unavailable + r.settled + r.abandoned > 0)
67
+ this.log.info("legacy retirement tick", { ...r });
68
+ }
69
+ /** One run (see the class); `signal` (the stop, or a lost run lock) is read between devices. */
70
+ async runOnce(signal) {
71
+ const result = {
72
+ added: 0,
73
+ cleared: 0,
74
+ unavailable: 0,
75
+ busy: 0,
76
+ settled: 0,
77
+ abandoned: 0,
78
+ };
79
+ result.added = (await this.retirement.scanUntilStable()).added;
80
+ // obligations of gone devices (deleted, or their org soft-deleted): a cloud one waits while
81
+ // its destroy is owed (instance row kept), then resolves by a recorded confirmed destroy (an
82
+ // abandoned one too), else abandoned (never evidence; no device can reuse them)
83
+ result.abandoned = (await this.retirement.abandonDeleted(ABANDON_PER_TICK)).abandoned;
84
+ for (const deviceId of await this.retirement.due(RETIRE_DEVICES_PER_TICK)) {
85
+ if (signal?.aborted)
86
+ return result;
87
+ try {
88
+ const outcome = await this.sandbox.retireLegacy(deviceId, signal);
89
+ if (outcome === "clear")
90
+ result.cleared++;
91
+ else if (outcome === "unavailable")
92
+ result.unavailable++;
93
+ else
94
+ result.busy++;
95
+ }
96
+ catch (err) {
97
+ // retried at a later tick; the inline gate keeps the device closed meanwhile
98
+ this.log.warn("legacy retirement failed; will retry", { deviceId, err });
99
+ result.unavailable++;
100
+ }
101
+ }
102
+ for (const m of await this.retirement.unsettledMembers(SETTLE_PER_TICK)) {
103
+ if (signal?.aborted)
104
+ return result;
105
+ try {
106
+ if (await this.settle(m)) {
107
+ await this.retirement.markSettled(m);
108
+ result.settled++;
109
+ }
110
+ }
111
+ catch (err) {
112
+ this.log.warn("cannot settle a retired legacy member; will retry", {
113
+ kind: m.kind,
114
+ ref: m.refId,
115
+ err,
116
+ });
117
+ }
118
+ }
119
+ return result;
120
+ }
121
+ /** Settles one member of a resolved obligation; false while its task still runs. */
122
+ async settle(m) {
123
+ if (m.kind === "legacy-task") {
124
+ await this.tasks.clearKill([m.refId]);
125
+ return true;
126
+ }
127
+ await this.intents.acknowledgeRevocation(m.refId);
128
+ const task = await this.tasks.byOperation(m.refId);
129
+ if (!task)
130
+ return true;
131
+ await this.tasks.settleOwedCancel(task.id);
132
+ const after = await this.tasks.byOperation(m.refId);
133
+ return after === undefined || after.launchState !== "cancel-pending";
134
+ }
135
+ };
136
+ __decorate([
137
+ LockedInterval(RETIRE_LEGACY_TASKS_JOB, () => PERIOD_MS, { ttl: TICK_TTL_MS })
138
+ ], RetireLegacyTasksJob.prototype, "tick", null);
139
+ RetireLegacyTasksJob = __decorate([
140
+ Injectable(),
141
+ __param(0, Inject(LegacyRetirementStore)),
142
+ __param(1, Inject(SandboxService)),
143
+ __param(2, Inject(SandboxOperationIntents)),
144
+ __param(3, Inject(BackgroundTaskStore)),
145
+ __param(4, Inject(KernelConfigService)),
146
+ __param(5, Inject(LockService)),
147
+ __param(6, Inject(KERNEL_LOGGER))
148
+ ], RetireLegacyTasksJob);
149
+ export { RetireLegacyTasksJob };
@@ -1,5 +1,5 @@
1
1
  import { type SandboxActor, type SandboxHandle } from "@capybara-hq/plugin-sdk";
2
- import type { HeldProvider, TaggedProvider } from "../sandbox/sandbox.service.js";
2
+ import { type HeldProvider, type TaggedProvider } from "../sandbox/sandbox.service.js";
3
3
  /**
4
4
  * A background task's session inside the sandbox (spec 2026-11-05-background-bash-design §4.2):
5
5
  * every process of a task is in the session `setsid` started, so liveness is `pgrep -s <sid>` and
@@ -7,11 +7,20 @@ import type { HeldProvider, TaggedProvider } from "../sandbox/sandbox.service.js
7
7
  * Linux). macOS has no `setsid` and its `pgrep` / `pkill` no `-s`: there the task is the process
8
8
  * group the launch made (`launchScript`), signalled with `kill -- -<sid>` ({@link SESSION_MODE_SCRIPT}).
9
9
  */
10
+ /**
11
+ * Whether a legacy (SID) task may still be driven by a raw exec: only while the one activation
12
+ * gate is off (`activation`: the injected gate, else the production state). Once it is on, a
13
+ * legacy row is the retirement gate's (8.5): no SID poll, read or stop runs, and its device stays
14
+ * unavailable until the old incarnation is confirmed gone (permission activation W3-L).
15
+ */
16
+ export declare const legacyBackgroundAllowed: (activation?: boolean) => boolean;
10
17
  /**
11
18
  * `p` with every `exec` carrying `actor` (`SandboxService.ifRunning` tags execs but leaves the
12
- * actor to the caller): the provider then reads like a `withSandbox` holder's.
19
+ * actor to the caller): the provider then reads like a `withSandbox` holder's. Once the
20
+ * activation gate is on ({@link legacyBackgroundAllowed}) every exec refuses before reaching the
21
+ * provider with the retirement refusal: a legacy task is never driven by a raw exec then.
13
22
  */
14
- export declare function actingAs(p: TaggedProvider, actor: SandboxActor): HeldProvider;
23
+ export declare function actingAs(p: TaggedProvider, actor: SandboxActor, activation?: boolean): HeldProvider;
15
24
  /** Who a background task's own execs (poll, stop, reads) act for: its trigger and its owner. */
16
25
  export declare const taskActor: (task: {
17
26
  triggerAccountId: string;
@@ -36,9 +45,10 @@ export declare function killSessionScript(sid: string): string;
36
45
  * Kills every process of the session `sid` ({@link killSessionScript}) in an exec of its own. Any
37
46
  * pkill status other than 0 and 1 is a failure. Runs with a fresh signal of its own (a command
38
47
  * must be killed even when the caller was just aborted). True when the session was confirmed
39
- * empty; false when it could not be (an error is never thrown).
48
+ * empty; false when it could not be (an error is never thrown). Once the activation gate is on
49
+ * ({@link legacyBackgroundAllowed}) nothing runs and the session is not confirmed empty.
40
50
  */
41
- export declare function killSession(p: Pick<HeldProvider, "exec">, h: SandboxHandle, sid: string): Promise<boolean>;
51
+ export declare function killSession(p: Pick<HeldProvider, "exec">, h: SandboxHandle, sid: string, activation?: boolean): Promise<boolean>;
42
52
  /** How long a stop waits after SIGTERM before SIGKILL (spec §2.3). */
43
53
  export declare const STOP_GRACE_MS = 5000;
44
54
  /** The time limit of the SIGTERM exec: the grace period plus some room. */
@@ -1,4 +1,6 @@
1
1
  import { rootsOf } from "@capybara-hq/plugin-sdk";
2
+ import { permissionContextActive } from "../sandbox/permission-context-types.js";
3
+ import { retirementPending, } from "../sandbox/sandbox.service.js";
2
4
  import { SESSION_MODE_SCRIPT, TASK_ID_RE, TASKS_DIR } from "./launch.js";
3
5
  /**
4
6
  * A background task's session inside the sandbox (spec 2026-11-05-background-bash-design §4.2):
@@ -7,14 +9,27 @@ import { SESSION_MODE_SCRIPT, TASK_ID_RE, TASKS_DIR } from "./launch.js";
7
9
  * Linux). macOS has no `setsid` and its `pgrep` / `pkill` no `-s`: there the task is the process
8
10
  * group the launch made (`launchScript`), signalled with `kill -- -<sid>` ({@link SESSION_MODE_SCRIPT}).
9
11
  */
12
+ /**
13
+ * Whether a legacy (SID) task may still be driven by a raw exec: only while the one activation
14
+ * gate is off (`activation`: the injected gate, else the production state). Once it is on, a
15
+ * legacy row is the retirement gate's (8.5): no SID poll, read or stop runs, and its device stays
16
+ * unavailable until the old incarnation is confirmed gone (permission activation W3-L).
17
+ */
18
+ export const legacyBackgroundAllowed = (activation) => !permissionContextActive(activation);
10
19
  /**
11
20
  * `p` with every `exec` carrying `actor` (`SandboxService.ifRunning` tags execs but leaves the
12
- * actor to the caller): the provider then reads like a `withSandbox` holder's.
21
+ * actor to the caller): the provider then reads like a `withSandbox` holder's. Once the
22
+ * activation gate is on ({@link legacyBackgroundAllowed}) every exec refuses before reaching the
23
+ * provider with the retirement refusal: a legacy task is never driven by a raw exec then.
13
24
  */
14
- export function actingAs(p, actor) {
25
+ export function actingAs(p, actor, activation) {
15
26
  const wrapped = Object.create(p);
16
27
  Object.defineProperty(wrapped, "exec", {
17
- value: (h, args) => p.exec(h, { ...args, actor }),
28
+ value: async (h, args) => {
29
+ if (!legacyBackgroundAllowed(activation))
30
+ throw retirementPending();
31
+ return p.exec(h, { ...args, actor });
32
+ },
18
33
  });
19
34
  return wrapped;
20
35
  }
@@ -48,10 +63,11 @@ export function killSessionScript(sid) {
48
63
  * Kills every process of the session `sid` ({@link killSessionScript}) in an exec of its own. Any
49
64
  * pkill status other than 0 and 1 is a failure. Runs with a fresh signal of its own (a command
50
65
  * must be killed even when the caller was just aborted). True when the session was confirmed
51
- * empty; false when it could not be (an error is never thrown).
66
+ * empty; false when it could not be (an error is never thrown). Once the activation gate is on
67
+ * ({@link legacyBackgroundAllowed}) nothing runs and the session is not confirmed empty.
52
68
  */
53
- export async function killSession(p, h, sid) {
54
- if (!SID_RE.test(sid))
69
+ export async function killSession(p, h, sid, activation) {
70
+ if (!SID_RE.test(sid) || !legacyBackgroundAllowed(activation))
55
71
  return false;
56
72
  const r = await p
57
73
  .exec(h, {
@@ -3,8 +3,11 @@ import type { KernelLogger } from "../log.js";
3
3
  import { SandboxService } from "../sandbox/sandbox.service.js";
4
4
  import { type BackgroundFinish, BackgroundTaskFinisher } from "./finish.js";
5
5
  import { type BackgroundTaskRow, BackgroundTaskStore } from "./store.js";
6
- /** Why a task is stopped. */
7
- export type StopReason = "tool" | "person" | "subagent_end" | "conversation_deleted";
6
+ /**
7
+ * Why a task is stopped. `revoked`: the cancellation a revocation owes (its finish may wake the
8
+ * conversation, unless a stop asked for it before: that asker's rule holds).
9
+ */
10
+ export type StopReason = "tool" | "person" | "subagent_end" | "conversation_deleted" | "revoked";
8
11
  /** How a task that exited by itself ends (spec §4.3): exit 137 past its deadline timed out. */
9
12
  export declare function exitedAs(task: BackgroundTaskRow, code: number, now: Date): BackgroundFinish;
10
13
  /** How a task whose sandbox is not running ends (`ifRunning`'s `not_running` status). */
@@ -26,7 +29,19 @@ export declare class BackgroundTaskStopper {
26
29
  private readonly sandbox;
27
30
  private readonly db;
28
31
  private readonly log;
29
- constructor(store: Pick<BackgroundTaskStore, "get" | "runningOwnedBy" | "runningIn" | "claimStop" | "releaseStop">, finisher: BackgroundTaskFinisher, sandbox: Pick<SandboxService, "ifRunning">, db: KernelDb, log: Pick<KernelLogger, "warn">);
32
+ /**
33
+ * The paired activation gate: once on, a legacy (SID) task's stop refuses with the retirement
34
+ * refusal exactly when it would run an exec (its instance runs); one whose instance is gone
35
+ * or replaced still finishes without one. A managed task always stops by its exact ref.
36
+ */
37
+ private readonly activation?;
38
+ constructor(store: Pick<BackgroundTaskStore, "get" | "runningOwnedBy" | "runningIn" | "claimStop" | "releaseStop" | "requestCancel" | "noteCancelAttempt">, finisher: BackgroundTaskFinisher, sandbox: Pick<SandboxService, "ifRunning">, db: KernelDb, log: Pick<KernelLogger, "warn">,
39
+ /**
40
+ * The paired activation gate: once on, a legacy (SID) task's stop refuses with the retirement
41
+ * refusal exactly when it would run an exec (its instance runs); one whose instance is gone
42
+ * or replaced still finishes without one. A managed task always stops by its exact ref.
43
+ */
44
+ activation?: boolean | undefined);
30
45
  /**
31
46
  * Stops `task` and returns its row afterwards. A task that is no longer running, or that another
32
47
  * live stop already claimed, is returned as it is now.
@@ -36,9 +51,24 @@ export declare class BackgroundTaskStopper {
36
51
  * started the command yet (no `sid`) is only claimed: the launch then kills what it starts and
37
52
  * finishes the row `stopped`. When the stop fails while the sandbox runs (busy, a provider
38
53
  * error, a session that could not be confirmed empty), the claim is given up, the task stays
39
- * `running` and the error is thrown.
54
+ * `running` and the error is thrown. `how.reported`: the caller's own result tells the model this
55
+ * finish (a managed task's cancellation settled from a TaskOutput read).
56
+ */
57
+ stop(task: BackgroundTaskRow, why: StopReason, signal?: AbortSignal, how?: {
58
+ reported?: boolean;
59
+ }): Promise<BackgroundTaskRow>;
60
+ /**
61
+ * A managed task's stop (permission runtime cutover phase 8.3), claimed by {@link stop}: by its
62
+ * exact ref on its exact instance only, with the five-second grace. The provider's atomically
63
+ * claimed outcome decides the finish: `already-exited` keeps the natural exit, `stopped` is
64
+ * stopped, `lost` is lost (the uncertainty retained), `cancel-pending` writes no finish (the
65
+ * task stays running `cancel-pending`, the claim released, so the poller owes the exact stop
66
+ * again). A task without its ref yet keeps the claim: its dispatch binding settles it unlaunched,
67
+ * or its acknowledgement attaches the ref to an owed cancellation. An instance that is not
68
+ * running (never resumed) or was replaced leaves the cancellation owed. Who asked is recorded,
69
+ * so a later finish keeps their wake rule.
40
70
  */
41
- stop(task: BackgroundTaskRow, why: StopReason, signal?: AbortSignal): Promise<BackgroundTaskRow>;
71
+ private stopManaged;
42
72
  /**
43
73
  * SIGTERM, the grace period, SIGKILL until the session is empty, then the last lines: in the
44
74
  * task's own instance only (`ifRunning`); a task from before devices has none.