@capybara-hq/kernel 0.1.0-rc.49 → 0.1.0-rc.50

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 (128) hide show
  1. package/dist/admin/admin.schemas.d.ts +0 -6
  2. package/dist/background/launch.d.ts +7 -61
  3. package/dist/background/launch.js +8 -133
  4. package/dist/background/poll.job.d.ts +19 -23
  5. package/dist/background/poll.job.js +30 -66
  6. package/dist/background/render.d.ts +9 -0
  7. package/dist/background/render.js +19 -0
  8. package/dist/background/session.d.ts +3 -66
  9. package/dist/background/session.js +3 -114
  10. package/dist/background/stop.d.ts +26 -33
  11. package/dist/background/stop.js +59 -90
  12. package/dist/background/store.d.ts +26 -60
  13. package/dist/background/store.js +23 -108
  14. package/dist/background/tasks.service.d.ts +9 -29
  15. package/dist/background/tasks.service.js +18 -115
  16. package/dist/catalog/marketplaces.service.d.ts +1 -1
  17. package/dist/channels/cards.d.ts +3 -0
  18. package/dist/channels/cards.js +29 -2
  19. package/dist/channels/phrases.d.ts +35 -0
  20. package/dist/channels/phrases.js +32 -0
  21. package/dist/config/load.d.ts +3 -10
  22. package/dist/config/load.js +26 -21
  23. package/dist/config/schema.js +3 -3
  24. package/dist/conversations/events.d.ts +45 -2
  25. package/dist/conversations/events.js +44 -4
  26. package/dist/db/kernel-schema.d.ts +9 -4
  27. package/dist/devices/devices.service.js +1 -1
  28. package/dist/devices/errors.d.ts +5 -0
  29. package/dist/devices/errors.js +5 -0
  30. package/dist/devices/project-rules.d.ts +2 -2
  31. package/dist/errors.d.ts +9 -11
  32. package/dist/errors.js +9 -11
  33. package/dist/identity/settings.d.ts +4 -17
  34. package/dist/identity/settings.js +9 -32
  35. package/dist/infra/config/kernel-config.service.js +2 -9
  36. package/dist/infra/outbox/registry.d.ts +13 -0
  37. package/dist/infra/outbox/registry.js +8 -0
  38. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  39. package/dist/local-devices/device-auth.controller.js +1 -1
  40. package/dist/local-devices/device-auth.d.ts +4 -3
  41. package/dist/local-devices/device-auth.js +1 -1
  42. package/dist/local-devices/device-policy.service.d.ts +6 -6
  43. package/dist/local-devices/device-routes.d.ts +4 -2
  44. package/dist/local-devices/device-routes.js +7 -6
  45. package/dist/local-devices/instance-bindings.d.ts +4 -4
  46. package/dist/local-devices/instance-bindings.js +2 -2
  47. package/dist/local-devices/local-device-gateway.d.ts +12 -12
  48. package/dist/local-devices/local-device-gateway.js +94 -129
  49. package/dist/local-devices/local-device-provider.d.ts +19 -87
  50. package/dist/local-devices/local-device-provider.js +43 -158
  51. package/dist/local-devices/local-devices.module.d.ts +4 -5
  52. package/dist/local-devices/local-devices.module.js +6 -9
  53. package/dist/local-devices/machines.d.ts +6 -6
  54. package/dist/local-devices/machines.js +4 -4
  55. package/dist/local-devices/owner-report.d.ts +3 -3
  56. package/dist/local-devices/owner-report.js +4 -4
  57. package/dist/local-devices/owner-reports.js +2 -2
  58. package/dist/local-devices/policy-summary.js +2 -2
  59. package/dist/local-devices/relay.d.ts +12 -25
  60. package/dist/local-devices/relay.js +17 -31
  61. package/dist/orgs/settings.controller.d.ts +1 -4
  62. package/dist/orgs/settings.controller.js +3 -3
  63. package/dist/orgs/settings.service.d.ts +7 -21
  64. package/dist/orgs/settings.service.js +16 -40
  65. package/dist/overrides.d.ts +3 -3
  66. package/dist/platform/ops/admin.ops.js +6 -8
  67. package/dist/platform/ops/org-settings.ops.js +4 -4
  68. package/dist/platform/ops/orgs.ops.js +0 -1
  69. package/dist/runtime/maintenance.d.ts +1 -1
  70. package/dist/runtime/maintenance.js +7 -1
  71. package/dist/runtime/run-steps.js +2 -2
  72. package/dist/sandbox/held-operations.d.ts +7 -0
  73. package/dist/sandbox/held-operations.js +25 -1
  74. package/dist/sandbox/leases.d.ts +6 -3
  75. package/dist/sandbox/leases.js +16 -10
  76. package/dist/sandbox/legacy-retirement.d.ts +0 -19
  77. package/dist/sandbox/legacy-retirement.js +6 -37
  78. package/dist/sandbox/managed-device-context.d.ts +12 -0
  79. package/dist/sandbox/managed-device-context.js +49 -1
  80. package/dist/sandbox/modes.d.ts +9 -8
  81. package/dist/sandbox/modes.js +4 -15
  82. package/dist/sandbox/operation-authority-types.d.ts +18 -1
  83. package/dist/sandbox/operation-authority-types.js +20 -1
  84. package/dist/sandbox/operation-authority.d.ts +14 -0
  85. package/dist/sandbox/operation-authority.js +120 -18
  86. package/dist/sandbox/operation-intents.d.ts +43 -0
  87. package/dist/sandbox/operation-intents.js +107 -4
  88. package/dist/sandbox/operation-reconcile.job.d.ts +12 -1
  89. package/dist/sandbox/operation-reconcile.job.js +53 -6
  90. package/dist/sandbox/permission-call-grants.d.ts +4 -0
  91. package/dist/sandbox/permission-call-grants.js +32 -3
  92. package/dist/sandbox/permission-call-types.d.ts +27 -2
  93. package/dist/sandbox/permission-ceiling-writes.js +2 -1
  94. package/dist/sandbox/permission-context-types.d.ts +2 -2
  95. package/dist/sandbox/permission-context-types.js +2 -2
  96. package/dist/sandbox/permission-facts.js +10 -2
  97. package/dist/sandbox/platform-full-access.d.ts +8 -26
  98. package/dist/sandbox/platform-full-access.js +8 -20
  99. package/dist/sandbox/review/classifier.d.ts +2 -2
  100. package/dist/sandbox/review/classifier.js +18 -5
  101. package/dist/sandbox/review/permission-candidate.d.ts +59 -3
  102. package/dist/sandbox/review/permission-candidate.js +192 -25
  103. package/dist/sandbox/review/review.service.d.ts +18 -0
  104. package/dist/sandbox/review/review.service.js +158 -12
  105. package/dist/sandbox/sandbox.service.d.ts +71 -47
  106. package/dist/sandbox/sandbox.service.js +234 -133
  107. package/dist/tools/approvals.service.d.ts +6 -1
  108. package/dist/tools/approvals.service.js +10 -0
  109. package/dist/tools/builtins/builtin-tools.d.ts +1 -4
  110. package/dist/tools/builtins/builtin-tools.js +13 -18
  111. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  112. package/dist/tools/builtins/sandbox/bash.js +92 -270
  113. package/dist/tools/builtins/sandbox/common.d.ts +15 -9
  114. package/dist/tools/builtins/sandbox/common.js +55 -19
  115. package/dist/tools/builtins/sandbox/device-owner.d.ts +13 -0
  116. package/dist/tools/builtins/sandbox/device-owner.js +14 -0
  117. package/dist/tools/builtins/sandbox/task-list.js +2 -2
  118. package/dist/tools/builtins/sandbox/task-output.d.ts +14 -57
  119. package/dist/tools/builtins/sandbox/task-output.js +88 -210
  120. package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -2
  121. package/dist/tools/builtins/sandbox/task-stop.js +15 -26
  122. package/dist/tools/pipeline.d.ts +31 -2
  123. package/dist/tools/pipeline.js +273 -43
  124. package/dist/tools/registry.d.ts +7 -0
  125. package/package.json +4 -4
  126. package/src/migrations/0162_permission_call_escalation.sql +9 -0
  127. package/dist/background/status.d.ts +0 -35
  128. package/dist/background/status.js +0 -57
@@ -8,10 +8,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { parseSandboxBrowseScope, parseSandboxOperationScope, } from "@capybara-hq/plugin-sdk";
11
+ import { parseSandboxBrowseScope, parseSandboxOperationScope, SandboxPermissionUnsupportedError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
- import { PermissionContextV1Schema, permissionCodePointCompare, } from "../conversations/events.js";
14
+ import { ACTOR_DEVICE_ACCESS_REASON, ACTOR_NOT_DEVICE_OWNER_REASON, PermissionContextV1Schema, permissionCodePointCompare, } from "../conversations/events.js";
15
15
  import { PermissionProfileStore, } from "../conversations/permission-profile-store.js";
16
16
  import { canonicalRoot, workingRootOf as reviewWorkingRootOf } from "../devices/working-root.js";
17
17
  import { ApiError } from "../errors.js";
@@ -21,14 +21,14 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { NetworkGrants } from "../local-devices/network-grants.js";
22
22
  import { KernelReadUnsupported, kernelReadRoot, kernelReadRoute, } from "./kernel-read.js";
23
23
  import { coversHost, projectReachOf } from "./modes.js";
24
- import { isExecutionMethod, parseStartingExecutionGrants } from "./operation-authority-types.js";
24
+ import { EscalationGrantMissingError, isExecutionMethod, parseStartingExecutionGrants, } from "./operation-authority-types.js";
25
25
  import { PermissionAuthorityEpochStore } from "./permission-authority-epochs.js";
26
26
  import { assertAuthorityHeld, PermissionAuthorityLock } from "./permission-authority-lock.js";
27
27
  import { PermissionCallGrants } from "./permission-call-grants.js";
28
28
  import { PermissionConfigPublication } from "./permission-config-publication.js";
29
29
  import { PermissionContextSubjectChanged, } from "./permission-context-types.js";
30
30
  import { hostsWithinOuter, PermissionFacts, permissionScopeHash } from "./permission-facts.js";
31
- import { normalizePermissionExpansion } from "./review/permission-candidate.js";
31
+ import { ESCALATION_CEILING_WHY, ESCALATION_UNATTENDED_WHY, escalationRuntimeWhy, normalizePermissionExpansion, withinDirectory, } from "./review/permission-candidate.js";
32
32
  const UNPROVED_ENVIRONMENT = "The device's installed environment is not verified yet; it is checked when the device starts";
33
33
  /**
34
34
  * The one verdict over a device's runtime report and its applied environment (B1, B-16): the
@@ -66,6 +66,11 @@ const KERNEL_READ_PROFILE = "request-approval";
66
66
  export function intersectPermissionScope(f) {
67
67
  if (f.profile === "full-access" && (!f.fullConsent || !f.fullAccessCeiling))
68
68
  throw new ApiError("forbidden", "Full access requires current device authority and matching consent");
69
+ // an escalated call runs with full execution: the same device, org and platform ceiling as Full
70
+ // access, its consent the exact call grant (bound to the scope revision) instead of the profile's
71
+ if (f.escalated && (f.profile === "full-access" || !f.fullAccessCeiling))
72
+ throw new ApiError("forbidden", "A sandbox escalation requires a restricted profile and the current Full access ceiling");
73
+ const full = f.profile === "full-access" || f.escalated === true;
69
74
  return parseSandboxOperationScope({
70
75
  operationId: f.operationId,
71
76
  admitBeforeMs: f.admitBeforeMs,
@@ -76,14 +81,14 @@ export function intersectPermissionScope(f) {
76
81
  profile: f.profile,
77
82
  actor: f.actor,
78
83
  tag: f.tag,
79
- filesystem: f.profile === "full-access"
84
+ filesystem: full
80
85
  ? { kind: "device" }
81
86
  : {
82
87
  kind: "scoped",
83
88
  readRoots: [...new Set([...f.readRoots, ...f.writeRoots])].sort(),
84
89
  writeRoots: [...new Set(f.writeRoots)].sort(),
85
90
  },
86
- network: f.profile === "full-access"
91
+ network: full
87
92
  ? { kind: "environment" }
88
93
  : f.allowedHosts.length
89
94
  ? { kind: "allowlist", hosts: [...new Set(f.allowedHosts)].sort() }
@@ -91,6 +96,19 @@ export function intersectPermissionScope(f) {
91
96
  });
92
97
  }
93
98
  /** Fresh authority shape only. Provider dispatch must add durable admission fencing before use. */
99
+ /**
100
+ * The read roots of a restricted profile: the working root, plus the held instance's
101
+ * kernel-staged skills root (its committed roots), read-only, so a staged skill's scripts run
102
+ * (`sh /skills/<name>@<digest>/…`). Never writable; nothing else is added. Sorted by code point,
103
+ * as the recorded context requires.
104
+ */
105
+ export function restrictedReadRoots(workingRoot, applied) {
106
+ const skills = applied?.roots.skills;
107
+ const roots = skills?.startsWith("/") && !withinDirectory(skills, workingRoot)
108
+ ? [workingRoot, skills]
109
+ : [workingRoot];
110
+ return [...new Set(roots)].sort(permissionCodePointCompare);
111
+ }
94
112
  let SandboxOperationAuthority = class SandboxOperationAuthority {
95
113
  callGrants;
96
114
  publication;
@@ -201,8 +219,16 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
201
219
  if (!started)
202
220
  throw new ApiError("forbidden", "The operation has no canonical started call");
203
221
  const payload = started.payload;
222
+ const permissionInput = {
223
+ callInputHash: payload.permissionInput?.callInputHash,
224
+ resolvedInputHash: payload.permissionInput?.resolvedInputHash,
225
+ };
226
+ const requested = payload.permissionInput?.sandbox;
204
227
  const { orgId, rootConversationId, conversationId, deviceId, accountId, runId, callId, profile, profileRevision, scopeRevision, authorityRevision, } = f;
205
- const grant = payload.toolKey && payload.specHash && payload.permissionInput
228
+ const grant = payload.toolKey &&
229
+ payload.specHash &&
230
+ permissionInput.callInputHash !== undefined &&
231
+ permissionInput.resolvedInputHash !== undefined
206
232
  ? await this.callGrants.findForAdmission({
207
233
  orgId,
208
234
  rootConversationId,
@@ -217,10 +243,24 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
217
243
  authorityRevision,
218
244
  toolKey: payload.toolKey,
219
245
  specHash: payload.specHash,
220
- ...payload.permissionInput,
246
+ callInputHash: permissionInput.callInputHash,
247
+ resolvedInputHash: permissionInput.resolvedInputHash,
221
248
  })
222
249
  : null;
223
- if (grant) {
250
+ // full execution for this exact call's command only (a native method of the same call keeps
251
+ // the base scope): the same checks as Full access, now
252
+ const escalated = grant?.scopeKind === "sandbox-escalation" && isExecutionMethod(operation);
253
+ // a call that asked to run outside the sandbox under a restricted profile runs escalated or
254
+ // not at all: a missed grant (the device, ceiling or scope changed since the approval) or a
255
+ // ceiling that no longer allows it is a pre-effect refusal, never a sandboxed run
256
+ if (requested === "escalated" &&
257
+ f.profile !== "full-access" &&
258
+ isExecutionMethod(operation) &&
259
+ (!escalated || f.escalationRefusal))
260
+ throw new EscalationGrantMissingError(f.escalationRefusal
261
+ ? `Sandbox escalation is unavailable: ${f.escalationRefusal}`
262
+ : "The call's sandbox escalation grant no longer matches");
263
+ if (!escalated && grant && grant.scopeKind !== "sandbox-escalation") {
224
264
  normalizePermissionExpansion(grant.expansion, f);
225
265
  if ((!f.broadProjectReach &&
226
266
  (grant.expansion.readDirectories.length || grant.expansion.writeDirectories.length)) ||
@@ -233,13 +273,16 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
233
273
  const expansionHosts = hostsWithinOuter(grant?.expansion.hosts ?? [], f.outerNetwork ?? undefined);
234
274
  const scope = this.scopeOf(ctx, operation, {
235
275
  ...f,
236
- baseReadDirectories: [...f.baseReadDirectories, ...(grant?.expansion.readDirectories ?? [])],
276
+ baseReadDirectories: [
277
+ ...f.baseReadDirectories,
278
+ ...(grant?.expansion.readDirectories ?? []),
279
+ ],
237
280
  baseWriteDirectories: [
238
281
  ...f.baseWriteDirectories,
239
282
  ...(grant?.expansion.writeDirectories ?? []),
240
283
  ],
241
284
  baseHosts: [...f.baseHosts, ...expansionHosts],
242
- });
285
+ }, escalated);
243
286
  const hosts = isExecutionMethod(operation)
244
287
  ? [...new Set([...(networkGrant?.hosts ?? []), ...expansionHosts])].sort()
245
288
  : [];
@@ -257,7 +300,9 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
257
300
  : null,
258
301
  })
259
302
  : null;
260
- return { scope, permissionGrantId: grant?.id ?? null, grantedHosts: hosts, executionGrants };
303
+ // an escalation grant is provenance of its command only, never of a native method's base scope
304
+ const permissionGrantId = grant && (grant.scopeKind !== "sandbox-escalation" || escalated) ? grant.id : null;
305
+ return { scope, permissionGrantId, grantedHosts: hosts, executionGrants };
261
306
  }
262
307
  /**
263
308
  * The scope of one kernel read (permission activation L2, Hook 1): the conversation's profile
@@ -327,12 +372,17 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
327
372
  .executeTakeFirst();
328
373
  return row !== undefined && (row.source !== "local" || row.mode === "docker");
329
374
  }
330
- scopeOf(ctx, operation, f) {
375
+ scopeOf(ctx, operation, f, escalated = false) {
331
376
  if (!["exec", "readFile", "writeFile", "stat", "list", "scan", "backgroundStart"].includes(operation))
332
377
  throw new ApiError("forbidden", "Unknown sandbox operation");
333
378
  // the recorded context withholds its scope for exactly these states (B-16)
334
- if (f.admissionRefusal)
379
+ if (f.admissionRefusal) {
380
+ // a runtime that cannot enforce the profile is the typed pre-effect refusal: the model gets
381
+ // the actionable unsupported text, never the generic "may not have completed" one
382
+ if (f.availability.state === "unsupported")
383
+ throw new SandboxPermissionUnsupportedError(f.admissionRefusal);
335
384
  throw new ApiError("forbidden", f.admissionRefusal);
385
+ }
336
386
  const operationId = randomUUID();
337
387
  return intersectPermissionScope({
338
388
  operationId,
@@ -350,6 +400,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
350
400
  allowedHosts: isExecutionMethod(operation) ? f.baseHosts : [],
351
401
  fullAccessCeiling: f.fullAccessCeiling,
352
402
  fullConsent: f.fullConsent,
403
+ ...(escalated ? { escalated: true } : {}),
353
404
  });
354
405
  }
355
406
  async snapshot(ctx, call, signal, captureGrant, opts = {}) {
@@ -418,6 +469,23 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
418
469
  projectPath: projectRoot,
419
470
  applied,
420
471
  });
472
+ // whether this call could run outside the sandbox (per-call escalation): the Full access
473
+ // ceiling and the runtime's Full support, judged as for Full access itself
474
+ const fullWithheld = withheldScope({
475
+ availability: view.availability,
476
+ effectiveProfile: "full-access",
477
+ location: device.source === "local" ? "local" : "cloud",
478
+ workingRoot,
479
+ projectPath: projectRoot,
480
+ applied,
481
+ });
482
+ const escalationRefusal = unattended
483
+ ? ESCALATION_UNATTENDED_WHY
484
+ : !view.fullAccessCeiling
485
+ ? ESCALATION_CEILING_WHY
486
+ : fullWithheld
487
+ ? escalationRuntimeWhy(fullWithheld.reason)
488
+ : null;
421
489
  const vector = await this.epochs.readLocked(subject);
422
490
  signal.throwIfAborted();
423
491
  if (!view.scopeRevision)
@@ -435,7 +503,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
435
503
  scopeRevision: view.scopeRevision,
436
504
  authorityRevision: permissionScopeHash({ scopeRevision: view.scopeRevision, vector }),
437
505
  workingRoot,
438
- baseReadDirectories: [workingRoot],
506
+ baseReadDirectories: restrictedReadRoots(workingRoot, applied),
439
507
  baseWriteDirectories: [workingRoot],
440
508
  baseHosts: allowedHosts,
441
509
  fullAccessCeiling: view.fullAccessCeiling,
@@ -446,6 +514,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
446
514
  availability: withheld ?? view.availability,
447
515
  admissionRefusal: withheld?.reason ?? null,
448
516
  outerNetwork: applied?.outerNetwork ?? null,
517
+ escalationRefusal,
449
518
  policy: device.source === "local"
450
519
  ? { ...policy, network: { kind: "allowlist", hosts: policy.localAllowedDomains } }
451
520
  : policy,
@@ -578,7 +647,24 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
578
647
  */
579
648
  async readContextLocked(input, signal) {
580
649
  signal.throwIfAborted();
581
- const root = await this.profiles.readOwnedRoot(input.orgId, input.conversationId, input.accountId);
650
+ // a run whose trigger account is not the conversation's owner (a group-chat sender, a wake
651
+ // attributed to another member) is not refused: its context is unavailable and it runs without
652
+ // the device, which is never used by another account. A removed or disabled actor keeps the
653
+ // actor refusal (B-19), and the run must be this account's run of this conversation
654
+ let foreign = false;
655
+ let root;
656
+ try {
657
+ root = await this.profiles.readOwnedRoot(input.orgId, input.conversationId, input.accountId);
658
+ }
659
+ catch (error) {
660
+ if (!(error instanceof ApiError) || error.code !== "conversation.not_found")
661
+ throw error;
662
+ if (!(await this.isActiveMember(input.orgId, input.accountId)))
663
+ throw new ApiError("forbidden", "This run's actor is no longer authorized");
664
+ root = await this.profiles.readRoot(input.orgId, input.conversationId);
665
+ await this.runScheduledLocked(input.conversationId, input.accountId, input.runId);
666
+ foreign = true;
667
+ }
582
668
  const held = (kind, id) => {
583
669
  try {
584
670
  assertAuthorityHeld(kind, id);
@@ -608,6 +694,22 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
608
694
  signal.throwIfAborted();
609
695
  return PermissionContextV1Schema.parse(payload);
610
696
  };
697
+ if (foreign && root.device_id !== null)
698
+ return parse({
699
+ ...header,
700
+ profileRevision: null,
701
+ selectedProfile: null,
702
+ effectiveProfile: null,
703
+ deviceId: null,
704
+ scopeRevision: null,
705
+ authorityRevision: null,
706
+ availability: {
707
+ state: "unavailable",
708
+ cause: "actor-device-access",
709
+ reason: ACTOR_NOT_DEVICE_OWNER_REASON,
710
+ },
711
+ scope: null,
712
+ });
611
713
  const { view, access } = await this.facts.viewWithAccess(input.orgId, input.accountId, root);
612
714
  if (root.device_id === null || access === "no-device")
613
715
  return parse({
@@ -637,7 +739,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
637
739
  availability: {
638
740
  state: "unavailable",
639
741
  cause: "actor-device-access",
640
- reason: "This run's actor cannot use the selected device",
742
+ reason: ACTOR_DEVICE_ACCESS_REASON,
641
743
  },
642
744
  scope: null,
643
745
  });
@@ -734,7 +836,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
734
836
  ? { kind: "device" }
735
837
  : {
736
838
  kind: "scoped",
737
- readDirectories: [base.workingRoot],
839
+ readDirectories: restrictedReadRoots(base.workingRoot, applied),
738
840
  writeDirectories: [base.workingRoot],
739
841
  },
740
842
  network: full
@@ -16,6 +16,22 @@ export declare class PermissionAdmissionStale extends Error {
16
16
  }
17
17
  export declare const OPERATION_RECONCILE = "sandbox-operation-reconcile";
18
18
  export declare const OPERATION_REVOKE = "sandbox-operation-revoke";
19
+ /**
20
+ * The owed revocation of one crashed holder's intents (`revokeHolders`), written before its holder
21
+ * record is forgotten, under the job id `sandbox-holder-revoke-<deviceId>-<token>`.
22
+ */
23
+ export declare const HOLDER_REVOKE = "sandbox-holder-revoke";
24
+ /**
25
+ * Why a revoked background launch ended (`lost_reason`; `lostReasonText` renders it): its launch
26
+ * was revoked before its start was confirmed (the replica starting it stopped, or its instance was
27
+ * cleaned up). The process may have started; its exact revoke stays owed.
28
+ */
29
+ export declare const REVOKED_LAUNCH_REASON = "launch_revoked";
30
+ /** The instance whose operations an exact cleanup covers: its provider and generation. */
31
+ export interface RevokedIncarnation {
32
+ provider: string;
33
+ generation: string;
34
+ }
19
35
  export type OperationIntent = Selectable<SandboxOperationIntentsTable>;
20
36
  /** Supplied only by the executing tool worker, never tool/model arguments. */
21
37
  export interface OperationInvocation {
@@ -194,8 +210,35 @@ export declare class SandboxOperationIntents {
194
210
  private scheduleExpiry;
195
211
  /** Keep the consumed ID/hash and cleanup obligations; expired bytes cannot authorize replay. */
196
212
  expirePayload(id: string): Promise<void>;
213
+ /**
214
+ * Owes the revocation of crashed holders' intents durably (permission runtime cutover B-1): one
215
+ * outbox row per token under a deterministic job id, committed before the caller forgets the
216
+ * holder records, so a revocation that then fails inline is retried by a worker. Two acquirers
217
+ * that saw the same dead token owe one job.
218
+ */
219
+ oweHolderRevocations(deviceId: string, tokens: readonly string[]): Promise<void>;
197
220
  /** Cleanup association only: a claimed dead holder can never authorize dispatch. */
198
221
  revokeHolders(deviceId: string, tokens: readonly string[]): Promise<void>;
222
+ /**
223
+ * The exact cleanup of an incarnation nobody else holds (the caller has its exclusive lifecycle
224
+ * lease: a resume from `suspended`, a failed limits change, a quarantine), replacing the broad
225
+ * `killAll`: every admitted, dispatching and started-or-unknown intent of that instance
226
+ * generation. Under the exclusive lease none of them has a live dispatcher (a shared holder can
227
+ * not exist), including a crashed replica's whose holder record expired or was never written.
228
+ * An acknowledged background task (`background-running`) keeps its starting grant.
229
+ */
230
+ revokeIncarnation(deviceId: string, instance: RevokedIncarnation): Promise<void>;
231
+ /** Revokes the device's intents `where` selects and owes each its exact revoke job. */
232
+ private revokeMatching;
233
+ /**
234
+ * The revoked, unacknowledged operation revokes owed on one instance generation (oldest first,
235
+ * at most `limit`), which a lifecycle holder delivers before anything else runs there. A
236
+ * launched background start is left to its exact stop by the revoke job.
237
+ */
238
+ owedRevocations(deviceId: string, instance: RevokedIncarnation, limit: number): Promise<{
239
+ operationId: string;
240
+ deadline: Date;
241
+ }[]>;
199
242
  /**
200
243
  * A disconnected or still-pending revoke remains owed; every retry is a new deterministic
201
244
  * persisted attempt, backing off (30 s doubling, at most an hour) so an obligation that only
@@ -26,6 +26,17 @@ export class PermissionAdmissionStale extends Error {
26
26
  }
27
27
  export const OPERATION_RECONCILE = "sandbox-operation-reconcile";
28
28
  export const OPERATION_REVOKE = "sandbox-operation-revoke";
29
+ /**
30
+ * The owed revocation of one crashed holder's intents (`revokeHolders`), written before its holder
31
+ * record is forgotten, under the job id `sandbox-holder-revoke-<deviceId>-<token>`.
32
+ */
33
+ export const HOLDER_REVOKE = "sandbox-holder-revoke";
34
+ /**
35
+ * Why a revoked background launch ended (`lost_reason`; `lostReasonText` renders it): its launch
36
+ * was revoked before its start was confirmed (the replica starting it stopped, or its instance was
37
+ * cleaned up). The process may have started; its exact revoke stays owed.
38
+ */
39
+ export const REVOKED_LAUNCH_REASON = "launch_revoked";
29
40
  const stopClaimed = sql `(stopping_at IS NOT NULL AND stopping_at >= now() - ${STOP_CLAIM_TTL_MS}::integer * interval '1 millisecond')`;
30
41
  /** A live stop claim, or a recorded cancellation request (it outlives the claim's TTL). */
31
42
  const stopRequested = sql `(${stopClaimed} OR cancel_requested_at IS NOT NULL)`;
@@ -52,7 +63,7 @@ export function launchRefusedText(kind) {
52
63
  case "unsupported":
53
64
  return "this device cannot run background tasks with this conversation's permissions; ask the user to choose another permission profile or device";
54
65
  default:
55
- return "the device refused the start";
66
+ return "the device refused the start; check that the device is connected and its permission profile allows background tasks, then retry the call";
56
67
  }
57
68
  }
58
69
  export function operationResult(value) {
@@ -1119,10 +1130,56 @@ let SandboxOperationIntents = class SandboxOperationIntents {
1119
1130
  if (expired)
1120
1131
  await this.payloads.expire(id);
1121
1132
  }
1133
+ /**
1134
+ * Owes the revocation of crashed holders' intents durably (permission runtime cutover B-1): one
1135
+ * outbox row per token under a deterministic job id, committed before the caller forgets the
1136
+ * holder records, so a revocation that then fails inline is retried by a worker. Two acquirers
1137
+ * that saw the same dead token owe one job.
1138
+ */
1139
+ async oweHolderRevocations(deviceId, tokens) {
1140
+ if (!tokens.length)
1141
+ return;
1142
+ // the device's org, as every intent outbox row carries it: the org's deletion removes them
1143
+ const device = await this.db
1144
+ .selectFrom("devices")
1145
+ .select("org_id")
1146
+ .where("id", "=", deviceId)
1147
+ .executeTakeFirst();
1148
+ for (const token of tokens)
1149
+ await this.outbox.add({
1150
+ queue: "cap-kernel-maintenance",
1151
+ name: HOLDER_REVOKE,
1152
+ jobId: `${HOLDER_REVOKE}-${deviceId}-${token}`,
1153
+ data: { deviceId, token },
1154
+ ...(device && { orgId: device.org_id }),
1155
+ });
1156
+ }
1122
1157
  /** Cleanup association only: a claimed dead holder can never authorize dispatch. */
1123
1158
  async revokeHolders(deviceId, tokens) {
1124
1159
  if (!tokens.length)
1125
1160
  return;
1161
+ await this.revokeMatching(deviceId, (eb) => eb.and([
1162
+ eb("holder_token", "in", [...tokens]),
1163
+ eb("state", "in", ["admitted", "dispatching", "started-or-unknown"]),
1164
+ ]));
1165
+ }
1166
+ /**
1167
+ * The exact cleanup of an incarnation nobody else holds (the caller has its exclusive lifecycle
1168
+ * lease: a resume from `suspended`, a failed limits change, a quarantine), replacing the broad
1169
+ * `killAll`: every admitted, dispatching and started-or-unknown intent of that instance
1170
+ * generation. Under the exclusive lease none of them has a live dispatcher (a shared holder can
1171
+ * not exist), including a crashed replica's whose holder record expired or was never written.
1172
+ * An acknowledged background task (`background-running`) keeps its starting grant.
1173
+ */
1174
+ async revokeIncarnation(deviceId, instance) {
1175
+ await this.revokeMatching(deviceId, (eb) => eb.and([
1176
+ eb("provider", "=", instance.provider),
1177
+ eb("instance_generation", "=", instance.generation),
1178
+ eb("state", "in", ["admitted", "dispatching", "started-or-unknown"]),
1179
+ ]));
1180
+ }
1181
+ /** Revokes the device's intents `where` selects and owes each its exact revoke job. */
1182
+ async revokeMatching(deviceId, where) {
1126
1183
  const device = await this.db
1127
1184
  .selectFrom("devices")
1128
1185
  .select("org_id")
@@ -1135,18 +1192,57 @@ let SandboxOperationIntents = class SandboxOperationIntents {
1135
1192
  .updateTable("sandbox_operation_intents")
1136
1193
  .set({ state: "revoked", outcome_unknown: true, updated_at: new Date() })
1137
1194
  .where("device_id", "=", deviceId)
1138
- .where("holder_token", "in", [...tokens])
1139
- .where("state", "in", ["admitted", "dispatching", "started-or-unknown"])
1140
- .returning("operation_id")
1195
+ .where(where)
1196
+ .returning(["operation_id", "method"])
1141
1197
  .execute();
1198
+ // A revoked start never gets its exact ref: its task would keep running and hold its
1199
+ // `maxTasks` slot forever. It ends now, in the revocation's transaction; the exact revoke (the
1200
+ // operation tombstone) stays owed below, so the possibly launched process is still cancelled.
1201
+ const starts = rows.filter((r) => r.method === "backgroundStart").map((r) => r.operation_id);
1202
+ if (starts.length > 0)
1203
+ await this.db
1204
+ .updateTable("background_tasks")
1205
+ .set({
1206
+ status: "lost",
1207
+ launch_state: "terminal",
1208
+ finished_at: new Date(),
1209
+ lost_reason: REVOKED_LAUNCH_REASON,
1210
+ stopping_at: null,
1211
+ })
1212
+ .where("operation_id", "in", starts)
1213
+ .where("status", "=", "running")
1214
+ .where("execution_ref", "is", null)
1215
+ .where("launch_state", "in", ["pending", "dispatched", "cancel-pending"])
1216
+ .execute();
1142
1217
  for (const row of rows)
1143
1218
  await this.outbox.add({
1144
1219
  queue: "cap-kernel-maintenance",
1145
1220
  name: OPERATION_REVOKE,
1146
1221
  jobId: `${OPERATION_REVOKE}-${row.operation_id}`,
1147
1222
  data: { operationId: row.operation_id },
1223
+ orgId: device.org_id,
1148
1224
  });
1149
1225
  }
1226
+ /**
1227
+ * The revoked, unacknowledged operation revokes owed on one instance generation (oldest first,
1228
+ * at most `limit`), which a lifecycle holder delivers before anything else runs there. A
1229
+ * launched background start is left to its exact stop by the revoke job.
1230
+ */
1231
+ async owedRevocations(deviceId, instance, limit) {
1232
+ const rows = await this.db
1233
+ .selectFrom("sandbox_operation_intents")
1234
+ .select(["operation_id", "deadline"])
1235
+ .where("device_id", "=", deviceId)
1236
+ .where("provider", "=", instance.provider)
1237
+ .where("instance_generation", "=", instance.generation)
1238
+ .where("state", "=", "revoked")
1239
+ .where("revoke_acknowledged", "=", false)
1240
+ .where((eb) => eb.or([eb("method", "!=", "backgroundStart"), eb("execution_ref", "is", null)]))
1241
+ .orderBy("created_at")
1242
+ .limit(limit)
1243
+ .execute();
1244
+ return rows.map((r) => ({ operationId: r.operation_id, deadline: r.deadline }));
1245
+ }
1150
1246
  /**
1151
1247
  * A disconnected or still-pending revoke remains owed; every retry is a new deterministic
1152
1248
  * persisted attempt, backing off (30 s doubling, at most an hour) so an obligation that only
@@ -1167,6 +1263,7 @@ let SandboxOperationIntents = class SandboxOperationIntents {
1167
1263
  name: OPERATION_REVOKE,
1168
1264
  jobId: `${OPERATION_REVOKE}-${id}-${row.reconcile_attempt}`,
1169
1265
  data: { operationId: id },
1266
+ orgId: row.org_id,
1170
1267
  runAt: new Date(Date.now() + Math.min(30_000 * 2 ** Math.min(row.reconcile_attempt - 1, 20), 3_600_000)),
1171
1268
  });
1172
1269
  }
@@ -1230,9 +1327,15 @@ __decorate([
1230
1327
  __decorate([
1231
1328
  Transactional({ propagation: "requires_new" })
1232
1329
  ], SandboxOperationIntents.prototype, "expirePayload", null);
1330
+ __decorate([
1331
+ Transactional({ propagation: "requires_new" })
1332
+ ], SandboxOperationIntents.prototype, "oweHolderRevocations", null);
1233
1333
  __decorate([
1234
1334
  Transactional({ propagation: "requires_new" })
1235
1335
  ], SandboxOperationIntents.prototype, "revokeHolders", null);
1336
+ __decorate([
1337
+ Transactional({ propagation: "requires_new" })
1338
+ ], SandboxOperationIntents.prototype, "revokeIncarnation", null);
1236
1339
  __decorate([
1237
1340
  Transactional({ propagation: "requires_new" })
1238
1341
  ], SandboxOperationIntents.prototype, "deferRevocation", null);
@@ -1,5 +1,6 @@
1
1
  import { BackgroundTaskStopper } from "../background/stop.js";
2
2
  import { BackgroundTaskStore } from "../background/store.js";
3
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
4
5
  import type { KernelLogger } from "../log.js";
5
6
  import { SandboxOperationIntents } from "./operation-intents.js";
@@ -13,9 +14,10 @@ export declare class SandboxOperationReconcileJob {
13
14
  private readonly sandbox;
14
15
  private readonly tasks;
15
16
  private readonly stopper;
17
+ private readonly config;
16
18
  /** Where a recovered start's refusal keeps the provider's own message (never the task's). */
17
19
  private readonly log?;
18
- constructor(intents: SandboxOperationIntents, db: KernelDb, providers: SandboxProviders, sandbox: Pick<SandboxService, "ifRunning">, tasks: Pick<BackgroundTaskStore, "byOperation" | "settleOwedCancel">, stopper: Pick<BackgroundTaskStopper, "stop">,
20
+ constructor(intents: SandboxOperationIntents, db: KernelDb, providers: SandboxProviders, sandbox: Pick<SandboxService, "ifRunning">, tasks: Pick<BackgroundTaskStore, "byOperation" | "settleOwedCancel">, stopper: Pick<BackgroundTaskStopper, "stop">, config: Pick<KernelConfigService, "get">,
19
21
  /** Where a recovered start's refusal keeps the provider's own message (never the task's). */
20
22
  log?: Pick<KernelLogger, "warn"> | undefined);
21
23
  reconcile(operationId: string): Promise<void>;
@@ -36,6 +38,15 @@ export declare class SandboxOperationReconcileJob {
36
38
  recoverBackground(operationId: string): Promise<void>;
37
39
  revoke(operationId: string): Promise<void>;
38
40
  private revokeOnce;
41
+ /**
42
+ * Whether a foreground operation (exec, read, write) of an incarnation that no longer runs has
43
+ * provably ended, so its owed revoke has nothing left to reach: the provider confirmed that
44
+ * incarnation's destruction (recorded in `device_instance_destructions`), or the operation is
45
+ * past its device-enforced bound (admitted before its deadline, then cut by the in-sandbox time
46
+ * limit of `maxCommandSeconds`). Both read only PostgreSQL and the clock, so every replica
47
+ * decides alike; without either the revoke stays owed.
48
+ */
49
+ private incarnationEnded;
39
50
  /**
40
51
  * The exact cancellation a revoked background start owes (design B3): the task's own stop by its
41
52
  * exact ref with the five-second grace, which settles and reports the task; the revocation is