@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
@@ -1,10 +1,14 @@
1
1
  import { setTimeout as sleep } from "node:timers/promises";
2
2
  import { isSandboxGoneError, rootsOf, ToolError, } from "@capybara-hq/plugin-sdk";
3
+ import { finishedEventKey } from "../../../background/finish.js";
3
4
  import { TASK_ID_RE, TASKS_DIR, taskOutputFile } from "../../../background/launch.js";
5
+ import { exactRefOf, lastLinesByRef, ManagedRefError, onManagedInstance, readerOf, statusEnd, summaryLines, } from "../../../background/managed.js";
6
+ import { assembleTaskOutput, ManagedOutputCapacityError, ManagedOutputUnavailableError, } from "../../../background/managed-output.js";
4
7
  import { formatElapsed, lostReasonText } from "../../../background/render.js";
5
8
  import { actingAs, SID_RE, taskActor } from "../../../background/session.js";
6
9
  import { parsePollOutput, polledAs, pollScript, } from "../../../background/status.js";
7
10
  import { notRunningAs, RECREATED } from "../../../background/stop.js";
11
+ import { isManagedTask } from "../../../background/store.js";
8
12
  import { clip, display, mapSandboxError, noSandboxError, runTimeLeftMs, sandboxBaseTimeoutMs, sandboxConversationOf, sandboxUsable, unavailableWhenNoSandbox, } from "./common.js";
9
13
  import { parseDeviceCode } from "./device-code.js";
10
14
  /** How long `TaskOutput` waits with `block` when `timeout` is not given (ms). */
@@ -324,6 +328,8 @@ export function taskOutputTool(deps) {
324
328
  }
325
329
  let task = await ownedTask(env, ctx, task_id);
326
330
  await recheckDevice(env, ctx);
331
+ if (isManagedTask(task))
332
+ return managedTaskOutput(deps, env, ctx, task, block, timeout);
327
333
  if (block && task.status === "running") {
328
334
  const wait = Math.max(0, Math.min(timeout ?? TASK_OUTPUT_DEFAULT_TIMEOUT_MS, TASK_OUTPUT_MAX_TIMEOUT_MS, runTimeLeftMs(ctx.runDeadline)));
329
335
  const until = Date.now() + wait;
@@ -389,6 +395,172 @@ export function taskOutputTool(deps) {
389
395
  },
390
396
  };
391
397
  }
398
+ /** A managed task's ref or provider failure as the tool's error (never a fallback read). */
399
+ function managedReadError(env, task, e) {
400
+ if (e instanceof ManagedRefError) {
401
+ return new ToolError(`Background task ${task.id}'s recorded execution reference is malformed or inconsistent, so its output cannot be read; call TaskList to see its status, or Read ${outputFile(task)}.`);
402
+ }
403
+ if (e instanceof ManagedOutputCapacityError) {
404
+ return new ToolError(`Background task ${task.id}'s output could not be read: ${e.message}.`);
405
+ }
406
+ if (e instanceof ToolError)
407
+ return e;
408
+ const mapped = mapSandboxError(e, env.log);
409
+ if (mapped instanceof ToolError)
410
+ return mapped;
411
+ const why = e instanceof Error ? e.message : String(e);
412
+ return new ToolError(`Background task ${task.id}'s output could not be read (${clip(why, 300)}); nothing was consumed. Retry TaskOutput.`);
413
+ }
414
+ /** Why a managed task's retained output cannot be read (the cursor never moves for it). */
415
+ function retainedUnavailableText(e) {
416
+ if (e.reason === "expired")
417
+ return "[Output unavailable: the task's retained output has expired.]";
418
+ if (e.reason === "mismatch") {
419
+ return "[Output unavailable: the read position is past the task's retained output.]";
420
+ }
421
+ return "[Output unavailable: the task's retained output was lost.]";
422
+ }
423
+ /**
424
+ * `TaskOutput` of a managed task (permission runtime cutover phase 8.3): status, positional
425
+ * reads and the finish's tail by its exact ref on its exact instance (never resumed, no exec, no
426
+ * path). The output is the bytes from the persisted cursor on, assembled through bounded reads
427
+ * with a 4,096-byte parser history; the cursor advances only by the raw bytes delivered as text.
428
+ * A live incomplete trailing character is left for a later read; at a verified terminal end
429
+ * (status established before the read) every remaining byte is delivered with replacement
430
+ * decoding. Unavailable retained output moves nothing and, for a finished task, shows its labelled
431
+ * finish summary, never invented bytes.
432
+ */
433
+ async function managedTaskOutput(deps, env, ctx, first, block, timeout) {
434
+ let task = first;
435
+ if (task.executionRef === null) {
436
+ let why = "[No output: the command never started.]";
437
+ if (task.status === "running") {
438
+ why =
439
+ task.launchState === "cancel-pending"
440
+ ? "[No output: the task was stopped while it was starting.]"
441
+ : "[The task is still starting; no output yet.]";
442
+ }
443
+ else if (task.lostReason === "launch_unknown") {
444
+ why = "[No output: whether the command started could not be confirmed.]";
445
+ }
446
+ return result(task, [statusLine(task), why]);
447
+ }
448
+ try {
449
+ exactRefOf(task);
450
+ }
451
+ catch (e) {
452
+ throw managedReadError(env, task, e);
453
+ }
454
+ const ifRunning = env.ifRunning;
455
+ if (block && task.status === "running") {
456
+ const wait = Math.max(0, Math.min(timeout ?? TASK_OUTPUT_DEFAULT_TIMEOUT_MS, TASK_OUTPUT_MAX_TIMEOUT_MS, runTimeLeftMs(ctx.runDeadline)));
457
+ const until = Date.now() + wait;
458
+ while (task.status === "running" && Date.now() < until) {
459
+ let r;
460
+ try {
461
+ r = await onManagedInstance(ifRunning, task, async (bg, h, ref, sig) => statusEnd(await bg.status(h, ref, sig)), ctx.signal);
462
+ }
463
+ catch (e) {
464
+ throw managedReadError(env, task, e);
465
+ }
466
+ if (r.kind !== "ran" || r.value !== null)
467
+ break;
468
+ const left = until - Date.now();
469
+ if (left <= 0)
470
+ break;
471
+ await sleep(Math.min(TASK_CHECK_INTERVAL_MS, left), undefined, { signal: ctx.signal });
472
+ task = (await env.store.get(task.id)) ?? task;
473
+ }
474
+ }
475
+ const budget = deps.config.get().tools.outputSpillChars;
476
+ const cur = task;
477
+ // A stop was asked for: the SDK status has no stopped state (an applied cancellation reads as an
478
+ // exit), so the end is settled only by the provider's atomically claimed stop outcome.
479
+ const cancelling = cur.launchState === "cancel-pending" || cur.cancelRequestedAt !== null;
480
+ const settleEnd = async (t, end) => {
481
+ if (end === null || t.status !== "running")
482
+ return t;
483
+ if (!cancelling)
484
+ return settle(env, t, end);
485
+ try {
486
+ return await env.tasks.stopper.stop(t, "revoked", ctx.signal, { reported: true });
487
+ }
488
+ catch (e) {
489
+ // the owed stop stays with the poller; this read still answers
490
+ env.log?.warn("cannot settle a cancelled background task from TaskOutput", {
491
+ taskId: t.id,
492
+ err: e,
493
+ });
494
+ return (await env.store.get(t.id)) ?? t;
495
+ }
496
+ };
497
+ let seen;
498
+ try {
499
+ seen = await onManagedInstance(ifRunning, cur, async (bg, h, ref, sig) => {
500
+ // terminal collection is established before the metadata snapshot, never after it
501
+ const end = cur.status === "running" ? statusEnd(await bg.status(h, ref, sig)) : null;
502
+ let read;
503
+ try {
504
+ read = await assembleTaskOutput(readerOf(bg, h, ref, sig), {
505
+ offset: cur.readOffset,
506
+ budget,
507
+ terminal: cur.status !== "running" || end !== null,
508
+ signal: sig,
509
+ });
510
+ }
511
+ catch (e) {
512
+ if (!(e instanceof ManagedOutputUnavailableError))
513
+ throw e;
514
+ read = e;
515
+ }
516
+ // a cancellation's end is settled by the exact stop below, which reads its own tail
517
+ const lastLines = end === null || cancelling ? "" : summaryLines(await lastLinesByRef(bg, h, ref, sig));
518
+ return { end, read, lastLines };
519
+ }, ctx.signal);
520
+ }
521
+ catch (e) {
522
+ if (isSandboxGoneError(e))
523
+ seen = { kind: "other_instance" };
524
+ else
525
+ throw managedReadError(env, task, e);
526
+ }
527
+ if (seen.kind !== "ran") {
528
+ if (task.status === "running") {
529
+ const to = seen.kind === "not_running" ? notRunningAs(seen.status, false) : RECREATED;
530
+ task = await settleEnd(task, { to, lastLines: "" });
531
+ }
532
+ return result(task, [statusLine(task), unavailableText(task, seen)]);
533
+ }
534
+ const { end, read, lastLines } = seen.value;
535
+ if (read instanceof ManagedOutputUnavailableError) {
536
+ task = await settleEnd(task, end === null ? null : { to: end, lastLines });
537
+ const lines = [statusLine(task), retainedUnavailableText(read)];
538
+ const summary = task.status === "running" ? null : await finishSummary(deps, task);
539
+ if (summary !== null) {
540
+ lines.push(`Last lines recorded when the task finished (not new output):\n${summary}`);
541
+ }
542
+ return result(task, lines);
543
+ }
544
+ const used = read.delivered.length;
545
+ if (used > 0)
546
+ await env.store.advanceOffset(task.id, read.nextOffset);
547
+ task = await settleEnd(task, end === null ? null : { to: end, lastLines });
548
+ const parts = [];
549
+ if (read.remaining > 0) {
550
+ parts.push(`[${read.remaining} more bytes of output after this; call TaskOutput again to read them, or Read ${outputFile(task)}.]`);
551
+ }
552
+ parts.push(used === 0 ? "[No new output.]" : read.text);
553
+ // the parser sees the re-read history plus the new bytes, so a prompt split across reads matches
554
+ const loginCode = used > 0 ? parseDeviceCode(read.parserText) : null;
555
+ return result(task, [statusLine(task), ...parts], loginCode);
556
+ }
557
+ /** The last lines the task's finished event kept; null when there is none (or no event log). */
558
+ async function finishSummary(deps, task) {
559
+ const ev = await deps.eventLog.findByIdem?.(task.conversationId, finishedEventKey(task.id));
560
+ if (ev?.type !== "background_task_finished")
561
+ return null;
562
+ return ev.payload.lastLines.replace(/\n$/, "") || "(none)";
563
+ }
392
564
  function result(task, lines, loginCode = null) {
393
565
  const d = clip(task.description, 120);
394
566
  return {
@@ -1,5 +1,7 @@
1
1
  import { rootsOf, ToolError } from "@capybara-hq/plugin-sdk";
2
+ import { LAST_LINES_UNAVAILABLE, lastLinesByRef, onManagedInstance, } from "../../../background/managed.js";
2
3
  import { decodeTail, tailCommand } from "../../../background/session.js";
4
+ import { isManagedTask } from "../../../background/store.js";
3
5
  import { clip, display, mapSandboxError, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, } from "./common.js";
4
6
  import { onTaskInstance, ownedTask, recheckDevice, statusLine, taskEnv, } from "./task-output.js";
5
7
  /** The time limit of reading a stopped task's last lines. */
@@ -29,6 +31,21 @@ const SPEC = {
29
31
  async function lastLinesOf(env, task, signal) {
30
32
  if (task.sandboxCreatedAt === null)
31
33
  return null;
34
+ if (isManagedTask(task)) {
35
+ // by the exact ref only: never an exec or a file read after a stop
36
+ if (task.executionRef === null)
37
+ return null;
38
+ try {
39
+ const r = await onManagedInstance(env.ifRunning, task, (bg, h, ref, sig) => lastLinesByRef(bg, h, ref, sig), signal);
40
+ if (r.kind !== "ran")
41
+ return null;
42
+ // retained output that cannot be read is labelled, never shown as no output
43
+ return r.value ?? LAST_LINES_UNAVAILABLE;
44
+ }
45
+ catch {
46
+ return LAST_LINES_UNAVAILABLE;
47
+ }
48
+ }
32
49
  try {
33
50
  const r = await onTaskInstance(env, task, async (p, h, sig) => {
34
51
  const res = await p.exec(h, {
@@ -54,9 +71,11 @@ async function ended(env, task, what, signal) {
54
71
  ? "[No output: the command never started.]"
55
72
  : lines === null
56
73
  ? "[Last lines unavailable: the sandbox that ran this task is not running.]"
57
- : lines === ""
58
- ? "[No output.]"
59
- : `Last lines:\n${lines.replace(/\n$/, "")}`;
74
+ : lines === LAST_LINES_UNAVAILABLE
75
+ ? LAST_LINES_UNAVAILABLE
76
+ : lines === ""
77
+ ? "[No output.]"
78
+ : `Last lines:\n${lines.replace(/\n$/, "")}`;
60
79
  return text(task, `Background task ${task.id} ("${task.description}") ${what}.\n${statusLine(task)}\n${tail}`);
61
80
  }
62
81
  function text(task, body) {
@@ -99,6 +118,9 @@ export function taskStopTool(deps) {
99
118
  const why = e instanceof Error ? e.message : String(e);
100
119
  throw new ToolError(`Background task ${task.id} could not be stopped (${clip(why, 300)}); it keeps running. Retry TaskStop, or check the sandbox with Bash.`);
101
120
  }
121
+ if (after.status === "running" && after.launchState === "cancel-pending") {
122
+ return text(after, `Background task ${after.id} ("${after.description}") stop requested: the device recorded the cancellation but has not applied it yet; it is applied when the device can. Call TaskOutput to see when it has ended.`);
123
+ }
102
124
  if (after.status === "running") {
103
125
  return text(after, `Background task ${after.id} ("${after.description}") is stopping: it is still starting, or another stop is in progress. Call TaskOutput to see when it has ended.`);
104
126
  }
@@ -1,6 +1,6 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { lineDiff, TOOL_VIEW_DIFF_MAX_BYTES, viewPath } from "../../view.js";
3
- import { checkFilePathShape, checkToolWritable, clip, display, inSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, withPathLease, } from "./common.js";
3
+ import { checkFilePathShape, checkToolWritable, clip, display, inToolSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, withPathLease, } from "./common.js";
4
4
  import { assertReadAndUnchanged, FileGuardError, fileStateOf, guardResult, keepGuardRefusal, normalizeSandboxPath, recordedFile, } from "./file-state.js";
5
5
  import { READ_MAX_BYTES } from "./read.js";
6
6
  const SPEC = {
@@ -47,7 +47,7 @@ export function sandboxWriteTool(deps) {
47
47
  checkFilePathShape(input.file_path);
48
48
  let path = "";
49
49
  // a read-before-write refusal is the guard working: a result with the guard view
50
- const ran = await inSandbox(deps, ctx, (s) => {
50
+ const ran = await inToolSandbox(deps, ctx, (s) => {
51
51
  const { deviceId, h, p, signal } = s;
52
52
  path = checkToolWritable(input.file_path, s);
53
53
  // stat, read the previous content, write: one holder at a time per file
@@ -11,7 +11,7 @@ import { resolveSkillForkType } from "../../runtime/subagents/roster.js";
11
11
  import { invocationOf, resolveSkills } from "../../skills/catalog.js";
12
12
  import { PLATFORM_SOURCE, skillFileStore } from "../../skills/usable.js";
13
13
  import { AGENT_TOOL, SANDBOX_TOOL_NAMES } from "../builtin-names.js";
14
- import { checkToolPath, clip, display, inSandbox, mapSandboxError, sandboxBaseTimeoutMs, sandboxConversationOf, sandboxUsable, withNotices, withPathLease, } from "./sandbox/common.js";
14
+ import { checkToolPath, clip, display, inSandboxPreparation, inToolSandbox, mapSandboxError, sandboxBaseTimeoutMs, sandboxConversationOf, sandboxUsable, withNotices, withPathLease, } from "./sandbox/common.js";
15
15
  /**
16
16
  * Builtin tool `Skill` (M5 T14, ruling M17): resolves the name against the latest skills catalog
17
17
  * snapshot in the log to an id and version, and returns that version's SKILL.md body and file list
@@ -169,7 +169,7 @@ async function readVerified(store, key, file, skill, signal) {
169
169
  async function copySkill(s, v) {
170
170
  const { name } = v.entry;
171
171
  const markerPath = skillMarkerPath(name, v.digest, s.roots.skills);
172
- const m = await s.p.readFile(s.h, markerPath, { maxBytes: MARKER_MAX_BYTES, signal: s.signal });
172
+ const m = await s.p.readFile(markerPath, { maxBytes: MARKER_MAX_BYTES, signal: s.signal });
173
173
  const cur = m && !m.truncated ? parseMarker(m.data) : undefined;
174
174
  if (cur?.digest === v.digest)
175
175
  return;
@@ -177,10 +177,10 @@ async function copySkill(s, v) {
177
177
  const data = f.path === SKILL_ENTRY_FILE
178
178
  ? v.entryBytes
179
179
  : await readVerified(v.store, `${v.keyPrefix}${f.path}`, f, name, s.signal);
180
- await s.p.writeFile(s.h, skillSandboxPath(name, v.digest, f.path, s.roots.skills), data, s.signal);
180
+ await s.p.writeFile(skillSandboxPath(name, v.digest, f.path, s.roots.skills), data, s.signal);
181
181
  }
182
182
  const entry = { digest: v.digest, files: v.manifest.files.map((f) => f.path) };
183
- await s.p.writeFile(s.h, markerPath, new TextEncoder().encode(JSON.stringify(entry)), s.signal);
183
+ await s.p.writeFile(markerPath, new TextEncoder().encode(JSON.stringify(entry)), s.signal);
184
184
  }
185
185
  /** 本步可用的工具里是否有沙箱工具(没有时模型用不了复制进去的文件)。 */
186
186
  const hasSandboxTools = (ctx) => (ctx.tools ?? []).some((t) => t.source.kind === "builtin" &&
@@ -501,7 +501,7 @@ async function loadProjectSkill(deps, ctx, asked, bare, args) {
501
501
  if (!skills.some((s) => s.name === bare)) {
502
502
  throw new ToolError(notInProject(asked, project.project, skills.map((s) => projectSkillName(s.name))));
503
503
  }
504
- const r = await inSandbox(deps, ctx, async (s) => {
504
+ const r = await inToolSandbox(deps, ctx, async (s) => {
505
505
  try {
506
506
  return await readProjectSkill(s, project.root, bare, ctx.signal);
507
507
  }
@@ -620,7 +620,10 @@ export function skillLoadTool(deps) {
620
620
  }
621
621
  else {
622
622
  // the skill's marker is read, compared and written: one holder at a time per skill
623
- const r = await inSandbox(deps, ctx, (s) => withPathLease(deps, s, skillMarkerPath(name, digest, s.roots.skills), s.signal, (signal) => copySkill({ ...s, signal }, v).then(() => s.roots)));
623
+ const r = await inSandboxPreparation(deps, ctx, "skills", (roots) => [
624
+ skillSandboxDir(name, digest, roots.skills),
625
+ skillMarkerPath(name, digest, roots.skills),
626
+ ], (s) => withPathLease(deps, s, skillMarkerPath(name, digest, s.roots.skills), s.signal, (signal) => copySkill({ ...s, signal }, v).then(() => s.roots)));
624
627
  notices = r.notices;
625
628
  skillsRoot = r.value.skills;
626
629
  const dir = `${skillSandboxDir(name, digest, skillsRoot)}/`;
@@ -25,7 +25,7 @@ export declare class DeviceOpResolver {
25
25
  readonly txHost: TransactionHost;
26
26
  private readonly policies;
27
27
  private readonly approvals;
28
- constructor(db: KernelDb, txHost: TransactionHost, policies: Pick<DevicePolicyService, "outcomeOf" | "settleIn">, approvals: Pick<ApprovalsService, "settleFromResolver">);
28
+ constructor(db: KernelDb, txHost: TransactionHost, policies: Pick<DevicePolicyService, "outcomeOf" | "settleIn" | "lockMachineDevice">, approvals: Pick<ApprovalsService, "settleFromResolver">);
29
29
  resolve(data: DeviceOpResolveData): Promise<void>;
30
30
  /**
31
31
  * The outcome a hello reported; a refusal's message (a hello carries none) is the machine's
@@ -9,7 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { KernelDb } from "../infra/database/kernel-db.js";
12
- import { TransactionHost } from "../infra/database/transaction-host.js";
12
+ import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
13
13
  import { Transactional } from "../infra/database/transactional.decorator.js";
14
14
  import { DevicePolicyService, } from "../local-devices/device-policy.service.js";
15
15
  import { opVisibleIn, pendingPolicyOpsOf, } from "../local-devices/policy-summary.js";
@@ -54,7 +54,9 @@ let DeviceOpResolver = class DeviceOpResolver {
54
54
  const result = op.reported !== undefined
55
55
  ? await this.reportedResult(row.device_id, op, op.reported.outcome)
56
56
  : statusResult(op, await this.policies.outcomeOf(row.device_id, op.id));
57
- await this.settle(data, op.source.approvalId, result);
57
+ // the machine's device lock is the ordered prelude: the settle locks the ask's conversation,
58
+ // approval and run after it (the global order: permission locks before conversation rows)
59
+ await withOrderedLocks(() => this.policies.lockMachineDevice(data.machineId), () => this.settle(data, op.source.approvalId, result));
58
60
  }
59
61
  /**
60
62
  * The outcome a hello reported; a refusal's message (a hello carries none) is the machine's
@@ -99,7 +101,15 @@ const MAX_MESSAGE = 500;
99
101
  function statusResult(op, s) {
100
102
  switch (s.outcome) {
101
103
  case "applied":
102
- return { outcome: "applied", ...(s.policy !== undefined && { policy: s.policy }) };
104
+ return {
105
+ outcome: "applied",
106
+ ...(s.policy !== undefined && { policy: s.policy }),
107
+ // a staged (v3) applied status carries the owner report (B2)
108
+ ...(s.ownerCeiling !== undefined && {
109
+ ownerCeiling: s.ownerCeiling,
110
+ connectionId: s.connectionId ?? null,
111
+ }),
112
+ };
103
113
  case "refused":
104
114
  return { outcome: "refused", message: (s.message ?? REFUSED_MESSAGE).slice(0, MAX_MESSAGE) };
105
115
  case "started":
@@ -0,0 +1,18 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { RunResume } from "../runtime/run-jobs.js";
4
+ import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
5
+ export type PermissionRecheckData = {
6
+ orgId: string;
7
+ rootConversationId: string;
8
+ revision: number;
9
+ };
10
+ export declare class PermissionApprovalJobs {
11
+ private readonly db;
12
+ readonly txHost: TransactionHost;
13
+ private readonly locks;
14
+ private readonly resumes;
15
+ constructor(db: KernelDb, txHost: TransactionHost, locks: PermissionAuthorityLock, resumes: RunResume);
16
+ recheck(data: PermissionRecheckData): Promise<void>;
17
+ private recheckLocked;
18
+ }
@@ -0,0 +1,92 @@
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 { KernelDb } from "../infra/database/kernel-db.js";
12
+ import { TransactionHost, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
13
+ import { Transactional } from "../infra/database/transactional.decorator.js";
14
+ import { RunResume } from "../runtime/run-jobs.js";
15
+ import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
16
+ let PermissionApprovalJobs = class PermissionApprovalJobs {
17
+ db;
18
+ txHost;
19
+ locks;
20
+ resumes;
21
+ constructor(db, txHost, locks, resumes) {
22
+ this.db = db;
23
+ this.txHost = txHost;
24
+ this.locks = locks;
25
+ this.resumes = resumes;
26
+ }
27
+ async recheck(data) {
28
+ const root = await this.db
29
+ .selectFrom("conversations")
30
+ .select("device_id")
31
+ .where("id", "=", data.rootConversationId)
32
+ .where("org_id", "=", data.orgId)
33
+ .executeTakeFirst();
34
+ if (!root)
35
+ return;
36
+ await withTransactionFencePrelude(() => this.locks.acquire({
37
+ orgId: data.orgId,
38
+ rootConversationId: data.rootConversationId,
39
+ ...(root.device_id ? { deviceId: root.device_id } : {}),
40
+ }, { kind: "admit" }), () => this.recheckLocked(data));
41
+ }
42
+ async recheckLocked(data) {
43
+ const root = await this.db
44
+ .selectFrom("conversations")
45
+ .selectAll()
46
+ .where("id", "=", data.rootConversationId)
47
+ .where("org_id", "=", data.orgId)
48
+ .forUpdate()
49
+ .executeTakeFirst();
50
+ if (!root || root.permission_revision < data.revision)
51
+ return;
52
+ const tree = await this.db
53
+ .withRecursive("tree(id)", (db) => db
54
+ .selectFrom("conversations")
55
+ .select("id")
56
+ .where("id", "=", root.id)
57
+ .unionAll((q) => q
58
+ .selectFrom("conversations as c")
59
+ .innerJoin("tree", "tree.id", "c.parent_conversation_id")
60
+ .select("c.id")
61
+ .where("c.org_id", "=", data.orgId)))
62
+ .selectFrom("conversations")
63
+ .select("id")
64
+ .where("id", "in", (q) => q.selectFrom("tree").select("id"))
65
+ .orderBy("id")
66
+ .forUpdate()
67
+ .execute();
68
+ const cards = await this.db
69
+ .selectFrom("approvals")
70
+ .select(["run_id", "conversation_id"])
71
+ .where("conversation_id", "in", tree.map((c) => c.id))
72
+ .where("kind", "=", "command")
73
+ .where("status", "=", "superseded")
74
+ .where("superseded_revision", "<=", root.permission_revision)
75
+ .orderBy("conversation_id")
76
+ .orderBy("run_id")
77
+ .execute();
78
+ for (const runId of [...new Set(cards.map((c) => c.run_id))])
79
+ await this.resumes.resumeIn(runId, `permission-${root.id}-${root.permission_revision}`);
80
+ }
81
+ };
82
+ __decorate([
83
+ Transactional()
84
+ ], PermissionApprovalJobs.prototype, "recheckLocked", null);
85
+ PermissionApprovalJobs = __decorate([
86
+ Injectable(),
87
+ __param(0, Inject(KernelDb)),
88
+ __param(1, Inject(TransactionHost)),
89
+ __param(2, Inject(PermissionAuthorityLock)),
90
+ __param(3, Inject(RunResume))
91
+ ], PermissionApprovalJobs);
92
+ export { PermissionApprovalJobs };
@@ -17,6 +17,9 @@ import { type SubagentParent, type WaitingFor } from "../runtime/loop.js";
17
17
  import type { DispatchArgs, DispatchOutcome } from "../runtime/subagents/dispatch.js";
18
18
  import { SubagentMessages } from "../runtime/subagents/messages.js";
19
19
  import { SubagentsService } from "../runtime/subagents/subagents.service.js";
20
+ import { SandboxOperationAuthority } from "../sandbox/operation-authority.js";
21
+ import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
22
+ import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
20
23
  import { type CommandReview } from "../sandbox/review/index.js";
21
24
  import { type UnattendedRun } from "../schedules/unattended.js";
22
25
  import { ApprovalsService } from "./approvals.service.js";
@@ -169,6 +172,7 @@ export interface ToolPipelineHooks {
169
172
  export declare const TOOL_PIPELINE_HOOKS: unique symbol;
170
173
  /** What the pipeline calls through (the sub-agent dispatch is read at call time). */
171
174
  interface PipelineDeps {
175
+ readonly permissionOperations?: ReadonlySet<string>;
172
176
  /** The kernel-schema handle of the current context (its transaction, else the pool). */
173
177
  readonly db: KernelSchemaDb;
174
178
  readonly eventLog: EventLog;
@@ -329,6 +333,9 @@ export type ExecOutcome =
329
333
  export declare class ToolPipeline {
330
334
  private readonly config;
331
335
  readonly txHost: TransactionHost;
336
+ private readonly permissionAuthority?;
337
+ private readonly permissionGrants?;
338
+ private readonly permissionLocks?;
332
339
  private readonly decide;
333
340
  private readonly deps;
334
341
  constructor(kdb: KernelDb, eventLog: EventLog,
@@ -343,7 +350,7 @@ export declare class ToolPipeline {
343
350
  /** The command review (auto mode spec §5.4); absent in hand-built pipelines. */
344
351
  review?: CommandReview,
345
352
  /** The reviewed call's device facts; absent in hand-built pipelines. */
346
- devices?: Pick<ConversationDevices, "reviewFacts">);
353
+ devices?: Pick<ConversationDevices, "reviewFacts">, permissionAuthority?: SandboxOperationAuthority | undefined, permissionGrants?: PermissionCallGrants | undefined, permissionLocks?: PermissionAuthorityLock | undefined);
347
354
  /**
348
355
  * tools 节点:按顺序处理本步 assistant 消息里的全部 `tool_call`,每个调用都以一条 `tool_result` 结束
349
356
  * (之后才回到 prepare 构建下一次请求,保持「已记录调用、未记录结果之间不构建请求」的不变式)。
@@ -383,6 +390,11 @@ export declare class ToolPipeline {
383
390
  * asked is the whole truth on a resume: the call is never reviewed twice.
384
391
  */
385
392
  private reviewCall;
393
+ private operationScoped;
394
+ /** This branch is unreachable for production legacy handlers until the caller cutover. */
395
+ private reviewPermissionCall;
396
+ private findPermissionGrant;
397
+ private recordPermissionReview;
386
398
  /** The outcome of a call whose `command` approval was already asked (a resume). */
387
399
  private settledCommandAsk;
388
400
  /**
@@ -420,7 +432,10 @@ export declare class ToolPipeline {
420
432
  * 带 `tools.timeoutMs` 超时与 run 的中止信号(合并后传给处理函数 / 连接器,不响应信号的也按时结束)。
421
433
  * 熔断只作用于连接器工具(键为组织 × 连接器)。
422
434
  */
423
- execute(tool: ResolvedTool, input: unknown, ctx: ToolStepContext, callId: string, resume?: ToolResume, stepTools?: readonly ResolvedTool[], reviewedWorkingRoot?: string): Promise<ExecOutcome>;
435
+ execute(tool: ResolvedTool, input: unknown, ctx: ToolStepContext, callId: string, resume?: ToolResume, stepTools?: readonly ResolvedTool[], reviewed?: {
436
+ workingRoot?: string | undefined;
437
+ against?: string | undefined;
438
+ }): Promise<ExecOutcome>;
424
439
  private executeConnector;
425
440
  /** 抛出的错误 → 给模型的结果:ToolError 的消息原样(插件约定为英文、可操作),其他只给错误类名。 */
426
441
  private thrown;