@capybara-hq/kernel 0.1.0-rc.74 → 0.1.0-rc.76

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 (94) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/agents/readiness.controller.d.ts +4 -3
  3. package/dist/agents/readiness.controller.js +4 -3
  4. package/dist/agents/readiness.service.d.ts +44 -11
  5. package/dist/agents/readiness.service.js +59 -16
  6. package/dist/catalog/catalog-import.module.d.ts +1 -1
  7. package/dist/catalog/catalog-import.module.js +1 -1
  8. package/dist/catalog/cli.d.ts +9 -2
  9. package/dist/catalog/cli.js +10 -4
  10. package/dist/catalog/marketplaces.service.d.ts +1 -1
  11. package/dist/catalog/plugin-upgrade.d.ts +4 -2
  12. package/dist/catalog/plugin-upgrade.js +9 -3
  13. package/dist/db/kernel-schema.d.ts +5 -0
  14. package/dist/devices/device-projects.service.d.ts +3 -12
  15. package/dist/devices/device-projects.service.js +20 -63
  16. package/dist/devices/devices.service.d.ts +15 -12
  17. package/dist/devices/devices.service.js +25 -19
  18. package/dist/dial-in/machines.d.ts +3 -15
  19. package/dist/dial-in/machines.js +4 -60
  20. package/dist/extensions/bootstrap.d.ts +17 -3
  21. package/dist/extensions/bootstrap.js +56 -14
  22. package/dist/http/meta.controller.d.ts +0 -1
  23. package/dist/http/meta.controller.js +2 -6
  24. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  25. package/dist/lifecycle/kernel-lifecycle.js +16 -11
  26. package/dist/overrides.d.ts +0 -5
  27. package/dist/overrides.js +0 -2
  28. package/dist/platform/file-ref.d.ts +6 -5
  29. package/dist/platform/ops/agent-skills.ops.js +1 -1
  30. package/dist/platform/ops/agents.ops.js +1 -1
  31. package/dist/runtime/model-call.d.ts +2 -2
  32. package/dist/runtime/project/knowledge.d.ts +1 -1
  33. package/dist/runtime/project/knowledge.js +1 -1
  34. package/dist/runtime/project/knowledge.service.d.ts +5 -11
  35. package/dist/runtime/project/knowledge.service.js +12 -23
  36. package/dist/runtime/providers.d.ts +34 -1
  37. package/dist/runtime/providers.js +56 -7
  38. package/dist/runtime/run-steps.d.ts +4 -6
  39. package/dist/runtime/run-steps.js +7 -15
  40. package/dist/runtime/runtime.module.js +1 -1
  41. package/dist/sandbox/device-sandbox.d.ts +16 -2
  42. package/dist/sandbox/device-sandbox.js +13 -5
  43. package/dist/sandbox/held-operations.d.ts +2 -5
  44. package/dist/sandbox/held-operations.js +0 -14
  45. package/dist/sandbox/managed-device-context.d.ts +1 -1
  46. package/dist/sandbox/managed-device-context.js +1 -1
  47. package/dist/sandbox/operation-authority.js +3 -1
  48. package/dist/sandbox/permission-authority-lock.d.ts +6 -0
  49. package/dist/sandbox/permission-authority-lock.js +14 -0
  50. package/dist/sandbox/permission-context-types.d.ts +0 -11
  51. package/dist/sandbox/permission-context-types.js +0 -13
  52. package/dist/sandbox/permission-facts.d.ts +4 -0
  53. package/dist/sandbox/permission-facts.js +6 -1
  54. package/dist/sandbox/providers.d.ts +5 -0
  55. package/dist/sandbox/providers.js +1 -1
  56. package/dist/sandbox/review/permission-candidate.d.ts +12 -7
  57. package/dist/sandbox/review/permission-candidate.js +28 -7
  58. package/dist/sandbox/sandbox-file-reader.d.ts +7 -12
  59. package/dist/sandbox/sandbox-file-reader.js +12 -29
  60. package/dist/sandbox/sandbox.service.d.ts +53 -32
  61. package/dist/sandbox/sandbox.service.js +217 -141
  62. package/dist/sandbox/use-context.d.ts +4 -1
  63. package/dist/setup/setup-guides.service.d.ts +1 -2
  64. package/dist/setup/setup-guides.service.js +1 -4
  65. package/dist/shares/sweep.job.d.ts +2 -0
  66. package/dist/shares/sweep.job.js +3 -1
  67. package/dist/skills/invoke.d.ts +13 -35
  68. package/dist/skills/invoke.js +23 -162
  69. package/dist/tools/builtins/builtin-tools.d.ts +2 -11
  70. package/dist/tools/builtins/builtin-tools.js +5 -23
  71. package/dist/tools/builtins/image/generate.js +2 -2
  72. package/dist/tools/builtins/sandbox/common.d.ts +32 -80
  73. package/dist/tools/builtins/sandbox/common.js +61 -173
  74. package/dist/tools/builtins/sandbox/deliver.js +2 -2
  75. package/dist/tools/builtins/sandbox/device-owner.d.ts +4 -5
  76. package/dist/tools/builtins/sandbox/device-owner.js +5 -6
  77. package/dist/tools/builtins/sandbox/fetch-attachment.js +2 -2
  78. package/dist/tools/builtins/sandbox/glob.js +1 -1
  79. package/dist/tools/builtins/sandbox/grep.js +1 -1
  80. package/dist/tools/builtins/sandbox/index.d.ts +2 -2
  81. package/dist/tools/builtins/sandbox/index.js +2 -2
  82. package/dist/tools/builtins/sandbox/read.js +1 -1
  83. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -3
  84. package/dist/tools/builtins/sandbox/task-output.js +4 -4
  85. package/dist/tools/builtins/sandbox/task-stop.js +1 -1
  86. package/dist/tools/builtins/skill-load.js +2 -2
  87. package/dist/tools/connectors.service.d.ts +4 -2
  88. package/dist/tools/connectors.service.js +15 -3
  89. package/dist/tools/pipeline.d.ts +0 -2
  90. package/dist/tools/pipeline.js +7 -14
  91. package/dist/tools/tools.module.js +1 -1
  92. package/package.json +2 -2
  93. package/src/migrations/0179_device_report_limit_text.sql +28 -0
  94. package/src/migrations/0180_device_instance_abandoned.sql +6 -0
@@ -93,7 +93,7 @@ class ManagedWriterRefused extends Error {
93
93
  * admission use) and admission's working root. Any difference is
94
94
  * {@link ManagedDeviceContextStale}: no rediscovery, no provisioning, no whole-handler retry. The
95
95
  * bus hint follows the commit and is lossy. A lower event writer, not a permission context
96
- * publisher; dormant until the paired activation passes it to `common.ts`.
96
+ * publisher; `BuiltinTools` passes it to `common.ts`, which requires it.
97
97
  */
98
98
  let ManagedDeviceContextRecorder = class ManagedDeviceContextRecorder {
99
99
  db;
@@ -495,6 +495,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
495
495
  layer: sandbox.layer.outsideSandbox,
496
496
  boundary: sandbox.boundary,
497
497
  description: base.description,
498
+ changeHint: base.changeHint,
498
499
  })
499
500
  : null;
500
501
  const vector = await this.epochs.readLocked(subject);
@@ -568,7 +569,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
568
569
  */
569
570
  async baseScopeLocked(input) {
570
571
  const { orgId, deviceId } = input;
571
- const { policy, sandbox, hostCeiling, hostRefusal, description } = await this.facts.readDevice(orgId, deviceId);
572
+ const { policy, sandbox, hostCeiling, hostRefusal, description, changeHint } = await this.facts.readDevice(orgId, deviceId);
572
573
  const { workingRoot, projectRoot } = await this.workingRootOf(input);
573
574
  const grant = input.runId
574
575
  ? await this.grants.forExec({ orgId, deviceId, runId: input.runId })
@@ -581,6 +582,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
581
582
  return {
582
583
  policy,
583
584
  description,
585
+ changeHint,
584
586
  workingRoot,
585
587
  projectRoot,
586
588
  grant,
@@ -36,3 +36,9 @@ export declare class PermissionAuthorityLock {
36
36
  }
37
37
  /** The current transaction holds this authority lock (exclusively when asked); else throws. */
38
38
  export declare function assertAuthorityHeld(kind: AuthorityLevel, id: string, exclusive?: boolean): void;
39
+ /**
40
+ * The current transaction holds every authority lock a write of `level` on `subject` takes
41
+ * ({@link PermissionAuthorityLock.acquire}): each level above `level` (shared or stronger) and
42
+ * `level` itself exclusively; else throws before the caller writes anything.
43
+ */
44
+ export declare function assertAuthorityWriteHeld(subject: AuthoritySubject, level: AuthorityLevel): void;
@@ -145,3 +145,17 @@ export function assertAuthorityHeld(kind, id, exclusive = false) {
145
145
  if (!held || (exclusive && held !== "exclusive"))
146
146
  throw new Error("The matching authority lock is required");
147
147
  }
148
+ /**
149
+ * The current transaction holds every authority lock a write of `level` on `subject` takes
150
+ * ({@link PermissionAuthorityLock.acquire}): each level above `level` (shared or stronger) and
151
+ * `level` itself exclusively; else throws before the caller writes anything.
152
+ */
153
+ export function assertAuthorityWriteHeld(subject, level) {
154
+ const entries = authorityEntries(subject);
155
+ const stop = entries.findIndex(([l]) => l === level);
156
+ if (stop < 0)
157
+ throw new Error("The changed authority level is missing");
158
+ entries.slice(0, stop + 1).forEach(([l, id], i) => {
159
+ assertAuthorityHeld(l, id, i === stop);
160
+ });
161
+ }
@@ -58,14 +58,3 @@ export declare class PermissionContextSubjectChanged extends Error {
58
58
  readonly name = "PermissionContextSubjectChanged";
59
59
  constructor();
60
60
  }
61
- /**
62
- * The paired activation of the recorded permission context (Gate 9.4 with Task 8 phase 8.6): the
63
- * one explicit gate for both live producers, the request boundary (`RunSteps`) and the managed
64
- * device context writer (`BuiltinTools` into `common.ts`). Production provides nothing and reads
65
- * {@link PERMISSION_CONTEXT_ACTIVE}; tests provide this token to exercise either state.
66
- */
67
- export declare const PERMISSION_CONTEXT_ACTIVATION: unique symbol;
68
- /** The production state of the gate: on since the paired activation (device protocol 3). */
69
- export declare const PERMISSION_CONTEXT_ACTIVE = true;
70
- /** Whether the live producers are on: an injected test value, else {@link PERMISSION_CONTEXT_ACTIVE}. */
71
- export declare function permissionContextActive(injected: boolean | undefined): boolean;
@@ -9,16 +9,3 @@ export class PermissionContextSubjectChanged extends Error {
9
9
  super("The conversation's root or device changed before its permission context was read");
10
10
  }
11
11
  }
12
- /**
13
- * The paired activation of the recorded permission context (Gate 9.4 with Task 8 phase 8.6): the
14
- * one explicit gate for both live producers, the request boundary (`RunSteps`) and the managed
15
- * device context writer (`BuiltinTools` into `common.ts`). Production provides nothing and reads
16
- * {@link PERMISSION_CONTEXT_ACTIVE}; tests provide this token to exercise either state.
17
- */
18
- export const PERMISSION_CONTEXT_ACTIVATION = Symbol("PERMISSION_CONTEXT_ACTIVATION");
19
- /** The production state of the gate: on since the paired activation (device protocol 3). */
20
- export const PERMISSION_CONTEXT_ACTIVE = true;
21
- /** Whether the live producers are on: an injected test value, else {@link PERMISSION_CONTEXT_ACTIVE}. */
22
- export function permissionContextActive(injected) {
23
- return injected ?? PERMISSION_CONTEXT_ACTIVE;
24
- }
@@ -47,6 +47,8 @@ export declare class PermissionFacts {
47
47
  hostRefusal: (host: string) => string | null;
48
48
  /** The provider's description of the device (its stored report, English), or null. */
49
49
  description: string | null;
50
+ /** How to change the device's limits, in its provider's words (stored report, English). */
51
+ changeHint: string | null;
50
52
  }>;
51
53
  /**
52
54
  * The effective device sandbox (approval-only profiles design, "Settings model"): the platform,
@@ -83,6 +85,8 @@ export declare class PermissionFacts {
83
85
  /** Why a host cannot be added to the device's own network list ({@link deviceListAddRefusal}). */
84
86
  listAddRefusal: (host: string) => string | null;
85
87
  description: string | null;
88
+ /** How to change the device's limits, in its provider's words (English), or null. */
89
+ changeHint: string | null;
86
90
  /**
87
91
  * The device's network is an allowlist with a host list of its own: only then can a host
88
92
  * join that list (`DevicesService.addNetworkHostsIn`); a device following its org's hosts
@@ -73,6 +73,8 @@ let PermissionFacts = class PermissionFacts {
73
73
  hostRefusal: sandbox.refusal,
74
74
  /** The provider's description of the device (its stored report, English), or null. */
75
75
  description: sandbox.description,
76
+ /** How to change the device's limits, in its provider's words (stored report, English). */
77
+ changeHint: sandbox.changeHint,
76
78
  };
77
79
  }
78
80
  /**
@@ -131,6 +133,7 @@ let PermissionFacts = class PermissionFacts {
131
133
  ...(org.deviceNetwork !== undefined && { deviceNetwork: org.deviceNetwork }),
132
134
  };
133
135
  const box = effectiveDeviceSandbox(platform, orgLayer, device, providerLayerOf(support));
136
+ const report = storedReport(row?.report);
134
137
  const hostCeiling = hostGrantCeiling(box, platform, orgLayer);
135
138
  return {
136
139
  box,
@@ -140,7 +143,9 @@ let PermissionFacts = class PermissionFacts {
140
143
  refusal: (host) => hostGrantRefusal(host, box, platform, orgLayer),
141
144
  /** Why a host cannot be added to the device's own network list ({@link deviceListAddRefusal}). */
142
145
  listAddRefusal: (host) => deviceListAddRefusal(host, box, platform, orgLayer),
143
- description: storedReport(row?.report)?.description.en ?? null,
146
+ description: report?.description.en ?? null,
147
+ /** How to change the device's limits, in its provider's words (English), or null. */
148
+ changeHint: report?.changeHint?.en ?? null,
144
149
  /**
145
150
  * The device's network is an allowlist with a host list of its own: only then can a host
146
151
  * join that list (`DevicesService.addNetworkHostsIn`); a device following its org's hosts
@@ -1,5 +1,10 @@
1
1
  import { type DeviceProvider } from "@capybara-hq/plugin-sdk";
2
2
  import { ExtensionRegistry } from "../extensions/registry.js";
3
+ /**
4
+ * An in-process provider name: it starts with `@`, which no extension name can
5
+ * (`EXTENSION_NAME_RE`), so it never collides with a loaded `device-provider@1` plugin.
6
+ */
7
+ export declare const isInProcessName: (name: string) => boolean;
3
8
  /**
4
9
  * Whether a provider serves its devices over the dial-in channel: it implements
5
10
  * `DeviceProvider.dialIn` (an extension may only when it declares `permissions.dialIn`, checked
@@ -15,7 +15,7 @@ import { guardProviderConnection } from "./unreachable.js";
15
15
  * An in-process provider name: it starts with `@`, which no extension name can
16
16
  * (`EXTENSION_NAME_RE`), so it never collides with a loaded `device-provider@1` plugin.
17
17
  */
18
- const isInProcessName = (name) => name.startsWith("@");
18
+ export const isInProcessName = (name) => name.startsWith("@");
19
19
  /**
20
20
  * Whether a provider serves its devices over the dial-in channel: it implements
21
21
  * `DeviceProvider.dialIn` (an extension may only when it declares `permissions.dialIn`, checked
@@ -36,27 +36,32 @@ export declare const ESCALATION_JUSTIFICATION_MISSING_TEXT = "This Bash call ask
36
36
  /** Why an escalation cannot be reviewed: an unattended run (no one can approve it). */
37
37
  export declare const ESCALATION_UNATTENDED_WHY = "this is an unattended run (a scheduled task) where no one can approve running outside the sandbox";
38
38
  /**
39
- * Why an escalation cannot be reviewed because a layer's outside-sandbox setting is off: one text
40
- * per layer that blocks it (`DeviceSandbox.layer.outsideSandbox`), each naming who lifts it and how.
39
+ * Why an escalation cannot be reviewed because the device's provider does not allow running
40
+ * outside its sandbox now, with the provider's own description of the device and how to change it
41
+ * (its report's `description` and `changeHint`).
41
42
  */
43
+ export declare const escalationDeviceOffWhy: (description: string | null, changeHint?: string | null) => string;
42
44
  /**
43
- * Why an escalation cannot be reviewed because the device's provider does not allow running
44
- * outside its sandbox now, with the provider's own description of the device (its report).
45
+ * Why an escalation cannot be reviewed because the owner of the machine the device runs on keeps
46
+ * running outside the sandbox off (the provider names that layer, support `limitedBy`), with the
47
+ * provider's description of the device and how to change it.
45
48
  */
46
- export declare const escalationDeviceOffWhy: (description: string | null) => string;
49
+ export declare const escalationOwnerOffWhy: (description: string | null, changeHint?: string | null) => string;
47
50
  export declare const ESCALATION_ORG_OFF_WHY = "running commands outside the sandbox is off in this organization; an organization admin can allow running outside the sandbox";
48
51
  export declare const ESCALATION_PLATFORM_OFF_WHY = "running commands outside the sandbox is off on this platform; a super admin can allow running outside the sandbox";
49
52
  export declare const ESCALATION_NO_OUTSIDE_WHY = "this device is an instance that is itself the sandbox, so this device has no outside of its sandbox to run a command in";
50
53
  /**
51
54
  * The refusal text of an escalation that a layer's outside-sandbox setting blocks, the same for
52
55
  * every provider: an instance-boundary provider has no outside at all, whichever layer is off;
53
- * otherwise the platform or the org names who lifts it, and a provider whose support does not
54
- * allow it now says so with its description of the device (`description`, its report's).
56
+ * otherwise the platform or the org names who lifts it, and the owner of the machine or a provider
57
+ * whose support does not allow it now says so with the device's report (`description`, and
58
+ * `changeHint`: how to change it, in the provider's words).
55
59
  */
56
60
  export declare const escalationCeilingWhy: (input: {
57
61
  layer: DeviceSandboxLayer | null;
58
62
  boundary: "operation" | "instance";
59
63
  description?: string | null;
64
+ changeHint?: string | null;
60
65
  }) => string;
61
66
  /** Why an escalation cannot be reviewed: the runtime cannot run a command outside its sandbox now. */
62
67
  export declare const escalationRuntimeWhy: (reason: string) => string;
@@ -80,22 +80,41 @@ export const ESCALATION_JUSTIFICATION_MISSING_TEXT = 'This Bash call asked to ru
80
80
  /** Why an escalation cannot be reviewed: an unattended run (no one can approve it). */
81
81
  export const ESCALATION_UNATTENDED_WHY = "this is an unattended run (a scheduled task) where no one can approve running outside the sandbox";
82
82
  /**
83
- * Why an escalation cannot be reviewed because a layer's outside-sandbox setting is off: one text
84
- * per layer that blocks it (`DeviceSandbox.layer.outsideSandbox`), each naming who lifts it and how.
83
+ * The device's own words appended to a refusal that cites its report: its description (what the
84
+ * device may do now) and its change hint (who changes that and how), each without a final period,
85
+ * as one parenthesis-free tail of a clause.
85
86
  */
87
+ function reportTail(description, changeHint) {
88
+ const clean = (t) => t.trim().replace(/\.$/, "");
89
+ const parts = [
90
+ ...(description ? [`: ${clean(description)}`] : []),
91
+ ...(changeHint
92
+ ? [` (to change this, as the device's provider says: ${clean(changeHint)})`]
93
+ : []),
94
+ ];
95
+ return parts.join("");
96
+ }
86
97
  /**
87
98
  * Why an escalation cannot be reviewed because the device's provider does not allow running
88
- * outside its sandbox now, with the provider's own description of the device (its report).
99
+ * outside its sandbox now, with the provider's own description of the device and how to change it
100
+ * (its report's `description` and `changeHint`).
101
+ */
102
+ export const escalationDeviceOffWhy = (description, changeHint = null) => `this device's provider does not allow running outside the sandbox now${reportTail(description, changeHint)}`;
103
+ /**
104
+ * Why an escalation cannot be reviewed because the owner of the machine the device runs on keeps
105
+ * running outside the sandbox off (the provider names that layer, support `limitedBy`), with the
106
+ * provider's description of the device and how to change it.
89
107
  */
90
- export const escalationDeviceOffWhy = (description) => `this device's provider does not allow running outside the sandbox now${description ? `: ${description.replace(/\.$/, "")}` : ""}`;
108
+ export const escalationOwnerOffWhy = (description, changeHint = null) => `the owner of the machine this device runs on does not allow running outside the sandbox on it now${reportTail(description, changeHint)}`;
91
109
  export const ESCALATION_ORG_OFF_WHY = "running commands outside the sandbox is off in this organization; an organization admin can allow running outside the sandbox";
92
110
  export const ESCALATION_PLATFORM_OFF_WHY = "running commands outside the sandbox is off on this platform; a super admin can allow running outside the sandbox";
93
111
  export const ESCALATION_NO_OUTSIDE_WHY = "this device is an instance that is itself the sandbox, so this device has no outside of its sandbox to run a command in";
94
112
  /**
95
113
  * The refusal text of an escalation that a layer's outside-sandbox setting blocks, the same for
96
114
  * every provider: an instance-boundary provider has no outside at all, whichever layer is off;
97
- * otherwise the platform or the org names who lifts it, and a provider whose support does not
98
- * allow it now says so with its description of the device (`description`, its report's).
115
+ * otherwise the platform or the org names who lifts it, and the owner of the machine or a provider
116
+ * whose support does not allow it now says so with the device's report (`description`, and
117
+ * `changeHint`: how to change it, in the provider's words).
99
118
  */
100
119
  export const escalationCeilingWhy = (input) => {
101
120
  if (input.boundary === "instance")
@@ -105,8 +124,10 @@ export const escalationCeilingWhy = (input) => {
105
124
  return ESCALATION_PLATFORM_OFF_WHY;
106
125
  case "org":
107
126
  return ESCALATION_ORG_OFF_WHY;
127
+ case "owner":
128
+ return escalationOwnerOffWhy(input.description ?? null, input.changeHint ?? null);
108
129
  default:
109
- return escalationDeviceOffWhy(input.description ?? null);
130
+ return escalationDeviceOffWhy(input.description ?? null, input.changeHint ?? null);
110
131
  }
111
132
  };
112
133
  /** Why an escalation cannot be reviewed: the runtime cannot run a command outside its sandbox now. */
@@ -16,20 +16,19 @@ export interface SandboxFileReadInput {
16
16
  maxBytes: number;
17
17
  signal: AbortSignal;
18
18
  /**
19
- * The tool call the read serves (the `Platform` call): once the activation gate is on, the read
20
- * is a managed operation of that call under the run's current execution claim.
19
+ * The tool call the read serves (the `Platform` call): the read is a managed operation of that
20
+ * call under the run's current execution claim.
21
21
  */
22
22
  callId?: string;
23
23
  }
24
24
  /**
25
25
  * Reads one file from a conversation's sandbox for the kernel (skill authoring spec: a package
26
26
  * the agent built is registered from its sandbox). The same stat -> readFile sequence as the
27
- * `Deliver` tool, with the same path checks, in the device of the conversation's tree (holder =
28
- * the root conversation); no attachment sync and no `device_paths` record.
27
+ * `Deliver` tool, with the same path checks, in the device of the conversation's tree (the root's
28
+ * device, the calling conversation its holder); no attachment sync and no `device_paths` record.
29
29
  *
30
- * Once the activation gate is on, {@link read} never takes the raw use: it is a managed operation
31
- * of the serving tool call (`input.callId`) under the run's current execution claim, and without
32
- * them nothing is entered (permission activation W3-L).
30
+ * {@link read} is a managed operation of the serving tool call (`input.callId`) under the run's
31
+ * current execution claim, and without them nothing is entered (permission activation W3-L).
33
32
  *
34
33
  * Throws `ApiError` 422 `sandbox.file_invalid_path` / `sandbox.file_not_found` /
35
34
  * `sandbox.file_is_directory` / `sandbox.file_too_large`; provider and device failures go through
@@ -40,11 +39,7 @@ export declare class SandboxFileReader {
40
39
  private readonly devices;
41
40
  private readonly sandbox;
42
41
  private readonly log;
43
- /** The paired activation gate: once on, every read is a managed operation. */
44
- private readonly activation?;
45
- constructor(db: KernelDb, devices: Pick<ConversationDevices, "forTool">, sandbox: Pick<SandboxService, "withSandbox"> & Partial<Pick<SandboxService, "withOperations">>, log: Pick<KernelLogger, "warn">,
46
- /** The paired activation gate: once on, every read is a managed operation. */
47
- activation?: boolean | undefined);
42
+ constructor(db: KernelDb, devices: Pick<ConversationDevices, "forTool">, sandbox: Pick<SandboxService, "withOperations">, log: Pick<KernelLogger, "warn">);
48
43
  read(input: SandboxFileReadInput): Promise<Uint8Array>;
49
44
  /** Dormant caller adapter; the invoking tool supplies its actual current server execution identity. */
50
45
  readOperation(input: SandboxFileReadInput, invocation: Omit<OperationInvocation, "ordinal">): Promise<Uint8Array>;
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { SandboxScopeDeniedError, ToolError } from "@capybara-hq/plugin-sdk";
11
- import { Inject, Injectable, Optional } from "@nestjs/common";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
12
  import { ConversationDevices } from "../devices/conversation-devices.js";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -16,19 +16,17 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
16
16
  import { currentExecutionClaim } from "../runtime/run-execution.js";
17
17
  import { rootConversationOf } from "../runtime/subagents/child.js";
18
18
  import { checkPath, checkPathShape, clip, mapSandboxError, } from "../tools/builtins/sandbox/common.js";
19
- import { PERMISSION_CONTEXT_ACTIVATION, permissionContextActive, } from "./permission-context-types.js";
20
19
  import { SandboxService } from "./sandbox.service.js";
21
- /** How long one gate-on read may wait for admission (as a builtin tool call's operations). */
20
+ /** How long one read may wait for admission (as a builtin tool call's operations). */
22
21
  const READ_OPERATION_DEADLINE_MS = 30_000;
23
22
  /**
24
23
  * Reads one file from a conversation's sandbox for the kernel (skill authoring spec: a package
25
24
  * the agent built is registered from its sandbox). The same stat -> readFile sequence as the
26
- * `Deliver` tool, with the same path checks, in the device of the conversation's tree (holder =
27
- * the root conversation); no attachment sync and no `device_paths` record.
25
+ * `Deliver` tool, with the same path checks, in the device of the conversation's tree (the root's
26
+ * device, the calling conversation its holder); no attachment sync and no `device_paths` record.
28
27
  *
29
- * Once the activation gate is on, {@link read} never takes the raw use: it is a managed operation
30
- * of the serving tool call (`input.callId`) under the run's current execution claim, and without
31
- * them nothing is entered (permission activation W3-L).
28
+ * {@link read} is a managed operation of the serving tool call (`input.callId`) under the run's
29
+ * current execution claim, and without them nothing is entered (permission activation W3-L).
32
30
  *
33
31
  * Throws `ApiError` 422 `sandbox.file_invalid_path` / `sandbox.file_not_found` /
34
32
  * `sandbox.file_is_directory` / `sandbox.file_too_large`; provider and device failures go through
@@ -39,19 +37,13 @@ let SandboxFileReader = class SandboxFileReader {
39
37
  devices;
40
38
  sandbox;
41
39
  log;
42
- activation;
43
- constructor(db, devices, sandbox, log,
44
- /** The paired activation gate: once on, every read is a managed operation. */
45
- activation) {
40
+ constructor(db, devices, sandbox, log) {
46
41
  this.db = db;
47
42
  this.devices = devices;
48
43
  this.sandbox = sandbox;
49
44
  this.log = log;
50
- this.activation = activation;
51
45
  }
52
46
  async read(input) {
53
- if (!permissionContextActive(this.activation))
54
- return this.readWith(input);
55
47
  // the run this read serves: its current execution claim and the tool call, else nothing runs
56
48
  const claim = currentExecutionClaim();
57
49
  if (!claim || input.callId === undefined || claim.conversationId !== input.conversationId) {
@@ -75,23 +67,16 @@ let SandboxFileReader = class SandboxFileReader {
75
67
  try {
76
68
  const root = await rootConversationOf(this.db.db, input.conversationId);
77
69
  const deviceId = await this.devices.forTool(orgId, root);
78
- const enter = invocation
79
- ? (ctx, fn, signal) => {
80
- if (!this.sandbox.withOperations)
81
- throw new SandboxScopeDeniedError("Operation admission is unavailable");
82
- return this.sandbox.withOperations(ctx, invocation, fn, signal);
83
- }
84
- : this.sandbox.withSandbox.bind(this.sandbox);
85
- return await enter({
70
+ return await this.sandbox.withOperations({
86
71
  orgId,
87
72
  deviceId,
88
- holderConversationId: invocation ? input.conversationId : root,
73
+ holderConversationId: input.conversationId,
89
74
  actor: {
90
75
  accountId: input.actorAccountId,
91
76
  conversationId: input.conversationId,
92
- ...(invocation && { runId: invocation.claim.runId }),
77
+ runId: invocation.claim.runId,
93
78
  },
94
- }, async (h, p, info, signal) => {
79
+ }, invocation, async (h, p, info, signal) => {
95
80
  const path = invalidPathAsApiError(() => checkPath(given, info.roots));
96
81
  const st = await p.stat(h, path, signal);
97
82
  if (st === null)
@@ -121,9 +106,7 @@ SandboxFileReader = __decorate([
121
106
  __param(0, Inject(KernelDb)),
122
107
  __param(1, Inject(ConversationDevices)),
123
108
  __param(2, Inject(SandboxService)),
124
- __param(3, Inject(KERNEL_LOGGER)),
125
- __param(4, Optional()),
126
- __param(4, Inject(PERMISSION_CONTEXT_ACTIVATION))
109
+ __param(3, Inject(KERNEL_LOGGER))
127
110
  ], SandboxFileReader);
128
111
  export { SandboxFileReader };
129
112
  /** Runs a path check of the sandbox tools, turning its `ToolError` into `sandbox.file_invalid_path`. */
@@ -28,7 +28,7 @@ import { DeviceProviders } from "./providers.js";
28
28
  import type { SandboxUseContext } from "./use-context.js";
29
29
  export { SANDBOX_LOCK_PREFIX, SANDBOX_LOCK_TTL_MS, SandboxLockLostError, sandboxBusy, } from "./leases.js";
30
30
  export type { SandboxUseContext } from "./use-context.js";
31
- /** The third argument of the `withSandbox` callback. */
31
+ /** The third argument of a use's callback ({@link SandboxService.withOperations} and others). */
32
32
  export interface SandboxUseInfo {
33
33
  /** This call created the instance (first use, or a rebuild). */
34
34
  fresh: boolean;
@@ -56,6 +56,10 @@ export interface SandboxUseInfo {
56
56
  */
57
57
  contextEvidence?: HeldDeviceContextEvidence;
58
58
  }
59
+ /** The callback of an operation use or a kernel read: every provider call admitted first. */
60
+ export type SandboxUseCallback<T> = (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>;
61
+ /** An entry bound to one route (its invocation or kernel read), as a caller hands it on. */
62
+ export type SandboxUseEntry = <T>(ctx: SandboxUseContext, fn: SandboxUseCallback<T>, signal: AbortSignal) => Promise<T>;
59
63
  type Row = Selectable<DeviceInstancesTable>;
60
64
  type ExecArgs = Parameters<DeviceProvider["exec"]>[1];
61
65
  /**
@@ -67,10 +71,6 @@ interface Instance {
67
71
  handle: SandboxHandle;
68
72
  createdAt: number;
69
73
  }
70
- /**
71
- * The provider {@link SandboxService.withSandbox} passes to its callback: every `exec` carries the
72
- * holder's tag and the caller's actor, so the callback passes neither.
73
- */
74
74
  /**
75
75
  * The provider {@link SandboxService.ifRunning} passes to its callback: every `exec` carries the
76
76
  * holder's tag; the caller names the actor.
@@ -178,9 +178,9 @@ export declare const recreateRequired: () => ApiError;
178
178
  * deleted, plus one instance attached to it that comes and goes; all conversations bound to the
179
179
  * device (and their sub-agents) share both.
180
180
  *
181
- * - **Lazy creation**: the first {@link withSandbox} creates the file system
182
- * (`createFileSystem`, name `cap-device-<deviceId>`) and then the instance on it; state lives
183
- * in `device_instances`. A file system gone at the provider is never replaced silently:
181
+ * - **Lazy creation**: the first use ({@link withOperations} and the others) creates the file
182
+ * system (`createFileSystem`, name `cap-device-<deviceId>`) and then the instance on it; state
183
+ * lives in `device_instances`. A file system gone at the provider is never replaced silently:
184
184
  * `fs_status` becomes `lost` and uses fail with `device.files_lost` until
185
185
  * {@link resetFileSystem}.
186
186
  * - **Leases** (phase C, spec §10, {@link SandboxLeases}), keyed by device id: using an
@@ -423,7 +423,7 @@ export declare class SandboxService {
423
423
  } | null>;
424
424
  /**
425
425
  * The instance the device records now (its `created_at`), while it has one that runs or is
426
- * suspended; null otherwise. Read without a lease: a caller inside `withSandbox` reads the
426
+ * suspended; null otherwise. Read without a lease: a caller inside a use reads the
427
427
  * instance its own lease keeps.
428
428
  */
429
429
  currentInstance(deviceId: string): Promise<{
@@ -435,8 +435,8 @@ export declare class SandboxService {
435
435
  * `instance.createdAt` (background tasks, spec 2026-11-05-background-bash-design §4.3). It never
436
436
  * creates, resumes or rebuilds one: an instance that is missing, suspended, being created or
437
437
  * destroyed (or recorded with another provider) is `not_running`, one that records another
438
- * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a `withSandbox`
439
- * holder does (its tag on every exec, crashed holders' operations revoked exactly), and
438
+ * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a use's
439
+ * holder does (crashed holders' operations revoked exactly), with its tag on every exec, and
440
440
  * `last_used_at` moves forward when it ends. Waits for the lease up to `sandbox.lockWaitSeconds`
441
441
  * (`sandbox.busy`); `signal` (optional) ends the wait with its abort reason. The signal passed
442
442
  * to `fn` aborts with `signal` or when the lease is lost. Errors of `fn` (`SandboxGoneError`
@@ -463,23 +463,6 @@ export declare class SandboxService {
463
463
  * aborts when a renewal finds it lost.
464
464
  */
465
465
  pathLease(deviceId: string, path: string, signal: AbortSignal): Promise<SandboxPathLease>;
466
- /**
467
- * Runs `fn` on the device's instance: take a lease → make sure the instance runs (file
468
- * system, create / resume / rebuild, under the exclusive lease) → `fn` under a shared lease →
469
- * update `last_used_at` → release.
470
- * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
471
- * the wait and the creation / resume.
472
- * - The fourth argument of `fn` combines `signal` with the lease's: use it for commands, so they
473
- * stop when the lease is lost.
474
- * - The provider passed to `fn` labels every `exec` with this holder's tag and `ctx.actor`.
475
- * - When `fn` throws `SandboxGoneError` (the instance is gone) the instance is rebuilt on the
476
- * kept files (or the one another holder rebuilt is taken) and `fn` runs once more with
477
- * `restarted: true`; a second `gone` is thrown. Other errors are thrown as they are.
478
- * - Lost files throw `device.files_lost` (409), also when `fn` throws
479
- * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
480
- * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
481
- * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
482
- */
483
466
  /** Trusted staging only. The callback receives no exec, browsing or lifecycle methods. */
484
467
  withPreparation<T>(ctx: SandboxUseContext, purpose: SandboxPreparationScope["purpose"], roots: readonly string[], fn: (p: SandboxPreparation, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
485
468
  private prepareFor;
@@ -522,7 +505,27 @@ export declare class SandboxService {
522
505
  */
523
506
  withKernelRead<T>(ctx: SandboxUseContext, read: KernelReadInvocation, fn: (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
524
507
  withOperations<T>(ctx: SandboxUseContext, invocation: OperationSessionInvocation, fn: (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
525
- withSandbox<T>(ctx: SandboxUseContext, fn: (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
508
+ /**
509
+ * Every use of the device's instance ({@link withOperations}, {@link withPreparation},
510
+ * {@link withKernelRead}; there is no raw route): take a lease → make sure the instance runs
511
+ * (file system, create / resume / rebuild, under the exclusive lease) → the route's callback
512
+ * under a shared lease → update `last_used_at` → release.
513
+ * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
514
+ * the wait and the creation / resume.
515
+ * - The fourth argument of `fn` combines `signal` with the lease's: use it for commands, so they
516
+ * stop when the lease is lost.
517
+ * - The provider passed to `fn` admits and claims every call (an operation or a kernel read)
518
+ * before it reaches the provider; a preparation gets only the staging methods.
519
+ * - When `SandboxGoneError` is raised outside a dispatched operation (staging, context
520
+ * evidence), the instance is rebuilt on the kept files (or the one another holder rebuilt is
521
+ * taken) and the route runs once more with `restarted: true`; a second `gone` is thrown. A
522
+ * gone after a durable dispatch stays unknown: the instance is rebuilt, the call is not
523
+ * retried. Other errors are thrown as they are.
524
+ * - Lost files throw `device.files_lost` (409), also when `fn` throws
525
+ * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
526
+ * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
527
+ * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
528
+ */
526
529
  private withSandboxUse;
527
530
  /**
528
531
  * The limits a device's instance must run with for this use (auto mode spec §4.2), read fresh,
@@ -556,7 +559,7 @@ export declare class SandboxService {
556
559
  * logs.
557
560
  */
558
561
  private seenBy;
559
- /** Runs `fn` as the holder `e`: its tag and the caller's actor on every exec, its lease's signal. */
562
+ /** Runs the route as the holder `e`, under its lease's signal. */
560
563
  private runAs;
561
564
  /**
562
565
  * The held provider of a kernel read ({@link withKernelRead}): every call admitted and claimed
@@ -702,10 +705,28 @@ export declare class SandboxService {
702
705
  * (with intent, so running commands finish and new ones wait) up to 10 minutes. Without the
703
706
  * provider of its instance row loaded it throws and the row stays, marked `sweep_failed_at` (the
704
707
  * job is retried, and the destruction sweep finishes a deleted device once the provider is
705
- * back). The provider only needs to be loaded: a device is deleted while its org has the
706
- * provider off too.
708
+ * back). A provider that is no longer installed on this deployment (no install record, or its
709
+ * catalog item removed; never an in-process `@…` one) will not be back: the instance is
710
+ * abandoned instead ({@link abandonInstance}) and the call returns (#675). The provider only
711
+ * needs to be loaded: a device is deleted while its org has the provider off too.
707
712
  */
708
713
  destroyDevice(deviceId: string): Promise<void>;
714
+ /**
715
+ * Whether `provider` is still installed on this deployment: an in-process `@…` provider always
716
+ * counts (code, not an install), a plugin while its install record exists and the catalog item
717
+ * it was installed from (if any) is not removed. Not loaded on this replica is a separate case.
718
+ */
719
+ private providerInstalled;
720
+ /**
721
+ * Abandons the instance of a deleted device whose provider is no longer installed (#675): the
722
+ * kernel can never destroy it, so the row is kept as the record of the provider-side names
723
+ * (`handle`, `fs_handle`, `prev_handle`), marked `abandoned_at`, and one platform audit event
724
+ * (`device.instance_abandoned`, for the super admin) carries the same names. One statement, so
725
+ * the mark and its event commit together, and only the first call writes either (a retried job
726
+ * finds the row abandoned and does nothing). The sweeps iterate loaded providers only, so
727
+ * nothing retries the row; a plugin of that name installed again destroys it as before.
728
+ */
729
+ private abandonInstance;
709
730
  /**
710
731
  * Starts the device over with empty files (after `device.files_lost`, or on request):
711
732
  * under the exclusive lease (waited for like {@link destroyDevice}) destroys any instance and