@capybara-hq/kernel 0.1.0-rc.75 → 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 (74) hide show
  1. package/dist/agents/readiness.controller.d.ts +4 -3
  2. package/dist/agents/readiness.controller.js +4 -3
  3. package/dist/agents/readiness.service.d.ts +44 -11
  4. package/dist/agents/readiness.service.js +59 -16
  5. package/dist/catalog/catalog-import.module.d.ts +1 -1
  6. package/dist/catalog/catalog-import.module.js +1 -1
  7. package/dist/catalog/cli.d.ts +9 -2
  8. package/dist/catalog/cli.js +10 -4
  9. package/dist/catalog/marketplaces.service.d.ts +1 -1
  10. package/dist/catalog/plugin-upgrade.d.ts +4 -2
  11. package/dist/catalog/plugin-upgrade.js +9 -3
  12. package/dist/db/kernel-schema.d.ts +5 -0
  13. package/dist/devices/device-projects.service.d.ts +3 -12
  14. package/dist/devices/device-projects.service.js +16 -59
  15. package/dist/extensions/bootstrap.d.ts +17 -3
  16. package/dist/extensions/bootstrap.js +56 -14
  17. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  18. package/dist/lifecycle/kernel-lifecycle.js +16 -11
  19. package/dist/overrides.d.ts +0 -5
  20. package/dist/overrides.js +0 -2
  21. package/dist/platform/file-ref.d.ts +6 -5
  22. package/dist/platform/ops/agent-skills.ops.js +1 -1
  23. package/dist/platform/ops/agents.ops.js +1 -1
  24. package/dist/runtime/model-call.d.ts +2 -2
  25. package/dist/runtime/project/knowledge.d.ts +1 -1
  26. package/dist/runtime/project/knowledge.js +1 -1
  27. package/dist/runtime/project/knowledge.service.d.ts +5 -11
  28. package/dist/runtime/project/knowledge.service.js +12 -23
  29. package/dist/runtime/providers.d.ts +34 -1
  30. package/dist/runtime/providers.js +56 -7
  31. package/dist/runtime/run-steps.d.ts +4 -6
  32. package/dist/runtime/run-steps.js +7 -15
  33. package/dist/runtime/runtime.module.js +1 -1
  34. package/dist/sandbox/held-operations.d.ts +2 -5
  35. package/dist/sandbox/held-operations.js +0 -14
  36. package/dist/sandbox/managed-device-context.d.ts +1 -1
  37. package/dist/sandbox/managed-device-context.js +1 -1
  38. package/dist/sandbox/permission-context-types.d.ts +0 -11
  39. package/dist/sandbox/permission-context-types.js +0 -13
  40. package/dist/sandbox/providers.d.ts +5 -0
  41. package/dist/sandbox/providers.js +1 -1
  42. package/dist/sandbox/sandbox-file-reader.d.ts +7 -12
  43. package/dist/sandbox/sandbox-file-reader.js +12 -29
  44. package/dist/sandbox/sandbox.service.d.ts +53 -32
  45. package/dist/sandbox/sandbox.service.js +217 -141
  46. package/dist/sandbox/use-context.d.ts +4 -1
  47. package/dist/skills/invoke.d.ts +13 -35
  48. package/dist/skills/invoke.js +23 -162
  49. package/dist/tools/builtins/builtin-tools.d.ts +2 -11
  50. package/dist/tools/builtins/builtin-tools.js +5 -23
  51. package/dist/tools/builtins/image/generate.js +2 -2
  52. package/dist/tools/builtins/sandbox/common.d.ts +32 -80
  53. package/dist/tools/builtins/sandbox/common.js +61 -173
  54. package/dist/tools/builtins/sandbox/deliver.js +2 -2
  55. package/dist/tools/builtins/sandbox/device-owner.d.ts +4 -5
  56. package/dist/tools/builtins/sandbox/device-owner.js +5 -6
  57. package/dist/tools/builtins/sandbox/fetch-attachment.js +2 -2
  58. package/dist/tools/builtins/sandbox/glob.js +1 -1
  59. package/dist/tools/builtins/sandbox/grep.js +1 -1
  60. package/dist/tools/builtins/sandbox/index.d.ts +2 -2
  61. package/dist/tools/builtins/sandbox/index.js +2 -2
  62. package/dist/tools/builtins/sandbox/read.js +1 -1
  63. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -3
  64. package/dist/tools/builtins/sandbox/task-output.js +4 -4
  65. package/dist/tools/builtins/sandbox/task-stop.js +1 -1
  66. package/dist/tools/builtins/skill-load.js +2 -2
  67. package/dist/tools/connectors.service.d.ts +4 -2
  68. package/dist/tools/connectors.service.js +15 -3
  69. package/dist/tools/pipeline.d.ts +0 -2
  70. package/dist/tools/pipeline.js +7 -14
  71. package/dist/tools/tools.module.js +1 -1
  72. package/package.json +2 -2
  73. package/src/migrations/0179_device_report_limit_text.sql +28 -0
  74. package/src/migrations/0180_device_instance_abandoned.sql +6 -0
@@ -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 { createHash } from "node:crypto";
11
- import { assertValidDeclarations, isValidImageGenerationInfo, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
11
+ import { assertValidDeclarations, isModelError, isValidImageGenerationInfo, ModelError, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable, Module, Optional } from "@nestjs/common";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { deploymentConfigHash } from "../extensions/config-hash.js";
@@ -54,6 +54,26 @@ const MODELS_CACHE_FORMAT = 2;
54
54
  * it caches bumps it, so during a rolling upgrade it never reads a list an older kernel wrote.
55
55
  */
56
56
  const modelsKey = (p, hash) => `capk:models:${p.plugin}:f${MODELS_CACHE_FORMAT}:${p.version ?? "-"}:${hash ?? "-"}`;
57
+ const MODEL_ERROR_KINDS = new Set([
58
+ "rate_limited",
59
+ "overloaded",
60
+ "server",
61
+ "timeout",
62
+ "network",
63
+ "auth",
64
+ "invalid_request",
65
+ "context_overflow",
66
+ "refusal",
67
+ "aborted",
68
+ ]);
69
+ /** The kind of a failed list (the `ProviderListError`'s cause, or a failure marker's value). */
70
+ function listErrorKindOf(cause) {
71
+ if (isModelError(cause))
72
+ return cause.kind;
73
+ if (typeof cause === "string" && MODEL_ERROR_KINDS.has(cause))
74
+ return cause;
75
+ return "unknown";
76
+ }
57
77
  /** 列表视图的失败标记({@link LIST_FAILURE_TTL_SECONDS}),与模型列表同样按版本与配置摘要区分。 */
58
78
  const listFailedKey = (p, hash) => `capk:models-failed:${p.plugin}:${p.version ?? "-"}:${hash ?? "-"}`;
59
79
  const droppedKey = (plugin, hash, model) => `capk:models-dropped:${plugin}:${hash ?? "-"}:${model}`;
@@ -176,7 +196,7 @@ let ProviderRegistry = class ProviderRegistry {
176
196
  return await Promise.race([
177
197
  call$,
178
198
  new Promise((_, reject) => {
179
- timer = setTimeout(() => reject(new Error(`listModels timed out after ${ms}ms`)), ms);
199
+ timer = setTimeout(() => reject(new ModelError("timeout", `listModels timed out after ${ms}ms`)), ms);
180
200
  }),
181
201
  ]);
182
202
  }
@@ -344,6 +364,32 @@ let ProviderRegistry = class ProviderRegistry {
344
364
  .map((m) => ({ ...m, disabled: org.has(modelKey(p.provider, m.id)) })),
345
365
  }));
346
366
  }
367
+ /**
368
+ * Whether each provider gives an agent a model to pick in `orgId` (org readiness): the same
369
+ * cached lists, time limit and failure markers as {@link catalog}, and the same rule as the
370
+ * agent form's list (`list(orgId, { kind: "chat" })`: a chat model neither the platform nor the
371
+ * org disabled). Only providers enabled in the org with a valid effective config there are
372
+ * listed (the {@link hasProvider} gate); the others are left out, never called.
373
+ */
374
+ async chatUsability(orgId) {
375
+ const out = [];
376
+ for (const p of await this.catalog(orgId)) {
377
+ if (p.status === "error") {
378
+ // a provider that needs configuration here is not past the gate
379
+ if (p.errorKind !== undefined) {
380
+ out.push({ provider: p.provider, state: "list_failed", errorKind: p.errorKind });
381
+ }
382
+ continue;
383
+ }
384
+ if (p.status !== "ok")
385
+ continue;
386
+ const chat = p.models.filter((m) => m.kind === "chat");
387
+ out.push(chat.some((m) => !m.disabled)
388
+ ? { provider: p.provider, state: "usable" }
389
+ : { provider: p.provider, state: "no_chat_models", orgCanEnable: chat.length > 0 });
390
+ }
391
+ return out;
392
+ }
347
393
  /**
348
394
  * Every installed provider with its status (in plugin load order), for `orgId` (the providers it enabled, their enabled
349
395
  * models only), or the platform view when undefined (`/admin/models`: every model, `disabled`
@@ -390,15 +436,17 @@ let ProviderRegistry = class ProviderRegistry {
390
436
  const failed = listFailedKey(p, t.hash);
391
437
  // a provider that failed just now: mark it error for a while without waiting on it (each
392
438
  // provider has its own time limit too)
393
- if ((await this.kv.get(failed)) !== null) {
394
- throw new ProviderListError(p.plugin, new Error("listModels failed recently"));
395
- }
439
+ // the marker holds the failure's kind, so the views report it while they skip the call
440
+ const recent = await this.kv.get(failed);
441
+ if (recent !== null)
442
+ throw new ProviderListError(p.plugin, listErrorKindOf(recent));
396
443
  try {
397
444
  return await this.models(p, t);
398
445
  }
399
446
  catch (err) {
400
447
  if (err instanceof ProviderListError) {
401
- await this.kv.set(failed, "1", "EX", LIST_FAILURE_TTL_SECONDS);
448
+ const kind = listErrorKindOf(err.cause);
449
+ await this.kv.set(failed, kind, "EX", LIST_FAILURE_TTL_SECONDS);
402
450
  }
403
451
  throw err;
404
452
  }
@@ -419,7 +467,8 @@ let ProviderRegistry = class ProviderRegistry {
419
467
  const error = r.reason instanceof ApiError
420
468
  ? r.reason.message
421
469
  : `Model provider ${provider} failed to list its models`;
422
- return { provider, plugin: provider, status: "error", error, models: [] };
470
+ const errorKind = listErrorKindOf(r.reason instanceof ProviderListError ? r.reason.cause : r.reason);
471
+ return { provider, plugin: provider, status: "error", error, errorKind, models: [] };
423
472
  });
424
473
  }
425
474
  /**
@@ -33,16 +33,14 @@ export declare class AgentLoops {
33
33
  /**
34
34
  * What a run's steps use (`LoopDeps`: one model step plus the tool pipeline), over the injected
35
35
  * services. `deps` is a plain object (eval replays copy it without the hooks, the progress, the
36
- * fork dispatch and the live permission recorder). The live permission context recorder is wired
37
- * only when the paired activation gate is on ({@link PERMISSION_CONTEXT_ACTIVATION}).
36
+ * fork dispatch and the live permission recorder).
38
37
  */
39
38
  export declare class RunSteps {
40
39
  readonly deps: LoopDeps;
41
- constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder, activation?: boolean);
40
+ constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder);
42
41
  }
43
42
  /**
44
43
  * The live request boundary of a run's steps (spec B2): every agent-history request construction
45
- * records the root's current permission context first. Present only when the one activation gate
46
- * is on ({@link PERMISSION_CONTEXT_ACTIVATION}); otherwise no key at all.
44
+ * records the root's current permission context first.
47
45
  */
48
- export declare function livePermissionContext(recorder: Pick<PermissionContextRecorder, "record">, activation: boolean | undefined): Pick<LoopDeps, "permissionContext">;
46
+ export declare function livePermissionContext(recorder: Pick<PermissionContextRecorder, "record">): Required<Pick<LoopDeps, "permissionContext">>;
@@ -14,7 +14,6 @@ import { ExtensionHost } from "../extensions/host.js";
14
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
16
  import { KERNEL_LOGGER } from "../infra/tokens.js";
17
- import { PERMISSION_CONTEXT_ACTIVATION, permissionContextActive, } from "../sandbox/permission-context-types.js";
18
17
  import { ToolPipeline } from "../tools/pipeline.js";
19
18
  import { ToolRegistry } from "../tools/registry.js";
20
19
  import { KyselyCheckpointSaver } from "./checkpointer.js";
@@ -51,12 +50,11 @@ export { AgentLoops };
51
50
  /**
52
51
  * What a run's steps use (`LoopDeps`: one model step plus the tool pipeline), over the injected
53
52
  * services. `deps` is a plain object (eval replays copy it without the hooks, the progress, the
54
- * fork dispatch and the live permission recorder). The live permission context recorder is wired
55
- * only when the paired activation gate is on ({@link PERMISSION_CONTEXT_ACTIVATION}).
53
+ * fork dispatch and the live permission recorder).
56
54
  */
57
55
  let RunSteps = class RunSteps {
58
56
  deps;
59
- constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments, compactionSettings, compactionProgress, permissionContext, activation) {
57
+ constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments, compactionSettings, compactionProgress, permissionContext) {
60
58
  this.deps = {
61
59
  get db() {
62
60
  return kdb.db;
@@ -81,9 +79,8 @@ let RunSteps = class RunSteps {
81
79
  info: (orgId, conversationId, ids) => attachments.mediaInfo(orgId, conversationId, ids),
82
80
  fetch: (orgId, conversationId, ids, caps) => attachments.fetchMedia(orgId, conversationId, ids, caps),
83
81
  },
84
- // the request boundary of the recorded permission context (spec B2); on since the paired
85
- // activation (device protocol 3), off only where a test provides the gate as false
86
- ...livePermissionContext(permissionContext, activation),
82
+ // the request boundary of the recorded permission context (spec B2)
83
+ ...livePermissionContext(permissionContext),
87
84
  };
88
85
  }
89
86
  };
@@ -102,19 +99,14 @@ RunSteps = __decorate([
102
99
  __param(10, Inject(AttachmentsService)),
103
100
  __param(11, Inject(CompactionSettingsService)),
104
101
  __param(12, Inject(CompactionProgressService)),
105
- __param(13, Inject(PermissionContextRecorder)),
106
- __param(14, Optional()),
107
- __param(14, Inject(PERMISSION_CONTEXT_ACTIVATION))
102
+ __param(13, Inject(PermissionContextRecorder))
108
103
  ], RunSteps);
109
104
  export { RunSteps };
110
105
  /**
111
106
  * The live request boundary of a run's steps (spec B2): every agent-history request construction
112
- * records the root's current permission context first. Present only when the one activation gate
113
- * is on ({@link PERMISSION_CONTEXT_ACTIVATION}); otherwise no key at all.
107
+ * records the root's current permission context first.
114
108
  */
115
- export function livePermissionContext(recorder, activation) {
116
- if (!permissionContextActive(activation))
117
- return {};
109
+ export function livePermissionContext(recorder) {
118
110
  return {
119
111
  permissionContext: {
120
112
  beforeRequest: ({ orgId, conversationId, runId, accountId, signal }) => recorder.record({ orgId, conversationId, runId, accountId }, signal),
@@ -77,7 +77,7 @@ RuntimeModule = __decorate([
77
77
  DevicesModule,
78
78
  SandboxModule,
79
79
  // the recorded permission context: the authority projection shared with admission, its locks
80
- // and publication, and the stored root (dormant until the request boundary activates)
80
+ // and publication, and the stored root
81
81
  OperationAuthorityModule,
82
82
  PermissionAuthorityModule,
83
83
  PermissionProfileStoreModule,
@@ -3,9 +3,8 @@ import { type DeviceProvider, type ExecResult, type SandboxExecOptions, type San
3
3
  export type HeldProvider = Pick<DeviceProvider, "readFile" | "writeFile" | "stat" | "list" | "scan"> & {
4
4
  exec(h: SandboxHandle, args: Omit<Parameters<DeviceProvider["exec"]>[1], "tag" | "actor">): Promise<ExecResult>;
5
5
  /**
6
- * A managed background start (dormant until the paired activation): admitted, persisted and
7
- * acknowledged by the service under the same stable operation identity. Present only on the
8
- * operation-held provider; the protocol-2 adapter has none.
6
+ * A managed background start: admitted, persisted and acknowledged by the service under the
7
+ * same stable operation identity. Present only when the provider owns background executions.
9
8
  */
10
9
  backgroundStart?(h: SandboxHandle, args: ManagedStartArgs): Promise<SandboxExecutionRef>;
11
10
  };
@@ -42,5 +41,3 @@ export declare function checkManagedStart(provider: DeviceProvider, handle: Sand
42
41
  */
43
42
  export declare function withKernelGeneration(provider: DeviceProvider, generation: string): DeviceProvider;
44
43
  export declare function createHeldOperations(provider: DeviceProvider, handle: SandboxHandle, heldSignal: AbortSignal, dispatch: OperationDispatch): HeldProvider;
45
- /** Temporary v2 callback adapter. Removed with the coordinated Task 8 cutover. */
46
- export declare function createLegacyHeldProvider(provider: DeviceProvider, tag: string, actor: Parameters<DeviceProvider["exec"]>[1]["actor"], before: () => Promise<void>): HeldProvider;
@@ -135,17 +135,3 @@ export function createHeldOperations(provider, handle, heldSignal, dispatch) {
135
135
  : {}),
136
136
  };
137
137
  }
138
- /** Temporary v2 callback adapter. Removed with the coordinated Task 8 cutover. */
139
- export function createLegacyHeldProvider(provider, tag, actor, before) {
140
- return {
141
- exec: async (h, args) => {
142
- await before();
143
- return provider.exec(h, { ...args, tag, actor });
144
- },
145
- readFile: provider.readFile.bind(provider),
146
- writeFile: provider.writeFile.bind(provider),
147
- stat: provider.stat.bind(provider),
148
- ...(provider.list ? { list: provider.list.bind(provider) } : {}),
149
- ...(provider.scan ? { scan: provider.scan.bind(provider) } : {}),
150
- };
151
- }
@@ -67,7 +67,7 @@ export type ManagedDeviceContextPort = Pick<ManagedDeviceContextRecorder, "recor
67
67
  * admission use) and admission's working root. Any difference is
68
68
  * {@link ManagedDeviceContextStale}: no rediscovery, no provisioning, no whole-handler retry. The
69
69
  * bus hint follows the commit and is lossy. A lower event writer, not a permission context
70
- * publisher; dormant until the paired activation passes it to `common.ts`.
70
+ * publisher; `BuiltinTools` passes it to `common.ts`, which requires it.
71
71
  */
72
72
  export declare class ManagedDeviceContextRecorder {
73
73
  private readonly db;
@@ -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;
@@ -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
- }
@@ -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
@@ -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