@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
@@ -10,7 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { posix } from "node:path";
11
11
  import { isDeviceOfflineError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
12
12
  import { runOutsideTransaction } from "../infra/database/transaction-host.js";
13
- import { createHeldOperations, createLegacyHeldProvider, withKernelGeneration, } from "./held-operations.js";
13
+ import { createHeldOperations, withKernelGeneration, } from "./held-operations.js";
14
14
  import { SandboxOperationAuthority } from "./operation-authority.js";
15
15
  import { PermissionAdmissionStale, SandboxOperationIntents, } from "./operation-intents.js";
16
16
  import { PermissionInstanceWrites } from "./permission-instance-writes.js";
@@ -65,7 +65,7 @@ import { ManagedDeviceContextFailed } from "./managed-device-context.js";
65
65
  import { appliedLacksHost, appliedOf, appliedWider, instanceLimitsJson, orgEffectiveHosts, providerLimits, readInstanceLimits, sameApplied, sameAppliedExact, sameAppliedExactly, } from "./modes.js";
66
66
  import { PermissionFacts } from "./permission-facts.js";
67
67
  import { reportOwed, supportOf } from "./permission-runtime-reports.js";
68
- import { DeviceProviders, servesDialIn } from "./providers.js";
68
+ import { DeviceProviders, isInProcessName, servesDialIn, } from "./providers.js";
69
69
  import { isDeviceRequestNotSent } from "./request-not-sent.js";
70
70
  import { SandboxProviderUnreachableError } from "./unreachable.js";
71
71
  // Moved to leases.ts (phase C); re-exported for existing importers
@@ -589,7 +589,7 @@ let SandboxService = class SandboxService {
589
589
  }
590
590
  /**
591
591
  * The instance the device records now (its `created_at`), while it has one that runs or is
592
- * suspended; null otherwise. Read without a lease: a caller inside `withSandbox` reads the
592
+ * suspended; null otherwise. Read without a lease: a caller inside a use reads the
593
593
  * instance its own lease keeps.
594
594
  */
595
595
  async currentInstance(deviceId) {
@@ -609,8 +609,8 @@ let SandboxService = class SandboxService {
609
609
  * `instance.createdAt` (background tasks, spec 2026-11-05-background-bash-design §4.3). It never
610
610
  * creates, resumes or rebuilds one: an instance that is missing, suspended, being created or
611
611
  * destroyed (or recorded with another provider) is `not_running`, one that records another
612
- * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a `withSandbox`
613
- * holder does (its tag on every exec, crashed holders' operations revoked exactly), and
612
+ * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a use's
613
+ * holder does (crashed holders' operations revoked exactly), with its tag on every exec, and
614
614
  * `last_used_at` moves forward when it ends. Waits for the lease up to `sandbox.lockWaitSeconds`
615
615
  * (`sandbox.busy`); `signal` (optional) ends the wait with its abort reason. The signal passed
616
616
  * to `fn` aborts with `signal` or when the lease is lost. Errors of `fn` (`SandboxGoneError`
@@ -692,28 +692,12 @@ let SandboxService = class SandboxService {
692
692
  pathLease(deviceId, path, signal) {
693
693
  return this.leases.pathLease(deviceId, path, signal, PATH_LEASE_WAIT_MS);
694
694
  }
695
- /**
696
- * Runs `fn` on the device's instance: take a lease → make sure the instance runs (file
697
- * system, create / resume / rebuild, under the exclusive lease) → `fn` under a shared lease →
698
- * update `last_used_at` → release.
699
- * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
700
- * the wait and the creation / resume.
701
- * - The fourth argument of `fn` combines `signal` with the lease's: use it for commands, so they
702
- * stop when the lease is lost.
703
- * - The provider passed to `fn` labels every `exec` with this holder's tag and `ctx.actor`.
704
- * - When `fn` throws `SandboxGoneError` (the instance is gone) the instance is rebuilt on the
705
- * kept files (or the one another holder rebuilt is taken) and `fn` runs once more with
706
- * `restarted: true`; a second `gone` is thrown. Other errors are thrown as they are.
707
- * - Lost files throw `device.files_lost` (409), also when `fn` throws
708
- * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
709
- * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
710
- * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
711
- */
712
695
  /** Trusted staging only. The callback receives no exec, browsing or lifecycle methods. */
713
696
  async withPreparation(ctx, purpose, roots, fn, signal) {
714
- return this.withSandboxUse(ctx, async () => {
715
- throw new Error("Preparation callback was not installed");
716
- }, signal, undefined, (h, provider, info, sig) => this.prepareFor(ctx, h, provider, info, purpose, roots, fn, sig));
697
+ return this.withSandboxUse(ctx, {
698
+ kind: "preparation",
699
+ run: (h, provider, info, sig) => this.prepareFor(ctx, h, provider, info, purpose, roots, fn, sig),
700
+ }, signal);
717
701
  }
718
702
  async prepareFor(ctx, h, provider, info, purpose, roots, fn, sig) {
719
703
  if (!provider.prepare)
@@ -843,15 +827,33 @@ let SandboxService = class SandboxService {
843
827
  c.runId !== ctx.actor.runId ||
844
828
  ctx.actor.conversationId !== ctx.holderConversationId)
845
829
  throw new SandboxScopeDeniedError("The kernel read does not match its run start");
846
- return this.withSandboxUse(ctx, fn, signal, undefined, undefined, read);
830
+ return this.withSandboxUse(ctx, { kind: "kernelRead", read, fn }, signal);
847
831
  }
848
832
  async withOperations(ctx, invocation, fn, signal) {
849
- return this.withSandboxUse(ctx, fn, signal, invocation);
850
- }
851
- async withSandbox(ctx, fn, signal) {
852
- return this.withSandboxUse(ctx, fn, signal);
833
+ return this.withSandboxUse(ctx, { kind: "operations", invocation, fn }, signal);
853
834
  }
854
- async withSandboxUse(ctx, fn, signal, invocation, trusted, kernelRead) {
835
+ /**
836
+ * Every use of the device's instance ({@link withOperations}, {@link withPreparation},
837
+ * {@link withKernelRead}; there is no raw route): take a lease → make sure the instance runs
838
+ * (file system, create / resume / rebuild, under the exclusive lease) → the route's callback
839
+ * under a shared lease → update `last_used_at` → release.
840
+ * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
841
+ * the wait and the creation / resume.
842
+ * - The fourth argument of `fn` combines `signal` with the lease's: use it for commands, so they
843
+ * stop when the lease is lost.
844
+ * - The provider passed to `fn` admits and claims every call (an operation or a kernel read)
845
+ * before it reaches the provider; a preparation gets only the staging methods.
846
+ * - When `SandboxGoneError` is raised outside a dispatched operation (staging, context
847
+ * evidence), the instance is rebuilt on the kept files (or the one another holder rebuilt is
848
+ * taken) and the route runs once more with `restarted: true`; a second `gone` is thrown. A
849
+ * gone after a durable dispatch stays unknown: the instance is rebuilt, the call is not
850
+ * retried. Other errors are thrown as they are.
851
+ * - Lost files throw `device.files_lost` (409), also when `fn` throws
852
+ * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
853
+ * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
854
+ * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
855
+ */
856
+ async withSandboxUse(ctx, route, signal) {
855
857
  const p = await this.require(ctx.deviceId, ctx.orgId);
856
858
  const env = ctx.deviceId;
857
859
  const holder = ctx.holderConversationId;
@@ -863,7 +865,7 @@ let SandboxService = class SandboxService {
863
865
  let left = false;
864
866
  try {
865
867
  try {
866
- return await this.runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead);
868
+ return await this.runAs(e, ctx, p, route, signal);
867
869
  }
868
870
  catch (err) {
869
871
  if (isFileSystemGoneError(err))
@@ -909,7 +911,7 @@ let SandboxService = class SandboxService {
909
911
  ? { fresh: true, restarted: false, filesReset: true }
910
912
  : { fresh: true, restarted: true };
911
913
  try {
912
- return await this.runAs({ ...e, info }, ctx, p, fn, signal, invocation, trusted, kernelRead);
914
+ return await this.runAs({ ...e, info }, ctx, p, route, signal);
913
915
  }
914
916
  catch (err2) {
915
917
  if (isFileSystemGoneError(err2))
@@ -1043,131 +1045,128 @@ let SandboxService = class SandboxService {
1043
1045
  }
1044
1046
  return e;
1045
1047
  }
1046
- /** Runs `fn` as the holder `e`: its tag and the caller's actor on every exec, its lease's signal. */
1047
- async runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead) {
1048
+ /** Runs the route as the holder `e`, under its lease's signal. */
1049
+ async runAs(e, ctx, p, route, signal) {
1048
1050
  const sig = AbortSignal.any([signal, e.lease.signal]);
1049
- if (trusted)
1050
- return trusted(e.handle, p.impl, { ...e.info, roots: rootsOf(e.handle) }, sig);
1051
+ if (route.kind === "preparation")
1052
+ return route.run(e.handle, p.impl, { ...e.info, roots: rootsOf(e.handle) }, sig);
1051
1053
  const env = ctx.deviceId;
1052
- if (kernelRead)
1053
- return fn(e.handle, this.kernelReadProvider(e, ctx, p, kernelRead, sig), { ...e.info, roots: rootsOf(e.handle) }, sig);
1054
+ if (route.kind === "kernelRead")
1055
+ return route.fn(e.handle, this.kernelReadProvider(e, ctx, p, route.read, sig), { ...e.info, roots: rootsOf(e.handle) }, sig);
1056
+ const { invocation, fn } = route;
1054
1057
  let ordinal = 0;
1055
1058
  // a provider's background starts are told the held instance's kernel generation
1056
1059
  const held = withKernelGeneration(p.impl, String(e.createdAt));
1057
- const impl = invocation
1058
- ? createHeldOperations(held, e.handle, sig, async (method, input, invoke, preflight) => {
1059
- const identity = { ...invocation, ordinal: ordinal++ };
1060
- sig.throwIfAborted();
1061
- await this.register(env, e.lease.token);
1062
- const refreshPending = () => runOutsideTransaction(() => this.operationIntents.pending(ctx, identity, {
1063
- provider: p.plugin,
1064
- providerVersion: p.version,
1065
- generation: String(e.createdAt),
1066
- }, method, input, e.lease.token, sig));
1067
- const pending = await refreshPending();
1068
- // An acknowledged start returns its recorded exact ref; it never dispatches again.
1069
- if (pending.state === "background-running" && pending.execution_ref)
1070
- return parseSandboxExecutionRef(pending.execution_ref);
1071
- if (pending.state === "completed")
1072
- return (await this.operationIntents.result(pending));
1073
- let current;
1074
- try {
1075
- current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1076
- }
1077
- catch (error) {
1078
- if (!(error instanceof PermissionAdmissionStale))
1079
- throw error;
1080
- await refreshPending();
1081
- current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1082
- }
1083
- // Kernel checks on the admitted scope come before any dispatch state is written.
1084
- if (preflight &&
1085
- current.state !== "completed" &&
1086
- current.state !== "background-running") {
1087
- try {
1088
- await preflight(parseSandboxOperationScope(current.scope), sig);
1089
- }
1090
- catch (error) {
1091
- if (current.state === "admitted" &&
1092
- (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error))) {
1093
- const kind = failureKindOf(error);
1094
- await runOutsideTransaction(() => this.operationIntents.refusePreDispatch(ctx, identity, {
1095
- kind,
1096
- message: error.message,
1097
- }));
1098
- }
1099
- throw error;
1100
- }
1101
- }
1102
- const reconciling = ["dispatching", "started-or-unknown"].includes(pending.state);
1103
- // a dial-in device's machine must be connected before a new dispatch is recorded: its
1104
- // typed answer (offline, machine revoked, device deleted) proves nothing was sent
1105
- if (!reconciling && current.state === "admitted" && this.relay && servesDialIn(p))
1106
- await this.relay.connection(env);
1107
- const admitted = reconciling
1108
- ? await runOutsideTransaction(() => this.operationIntents.claimReconciliation(ctx, identity, {
1109
- provider: p.plugin,
1110
- providerVersion: p.version,
1111
- generation: String(e.createdAt),
1112
- }, method, input, e.lease.token))
1113
- : await runOutsideTransaction(() => this.operationIntents.claimDispatch(ctx, identity, e.lease.token, method === "backgroundStart"
1114
- ? backgroundBinding(input, e.handle.id)
1115
- : undefined));
1116
- if (admitted.state === "revoked")
1117
- throw admitted.outcome_unknown
1118
- ? new SandboxOperationOutcomeUnknownError("The background task was stopped before its start was confirmed; it is not started again and its cancellation is owed")
1119
- : new SandboxScopeDeniedError("The background task was stopped or settled before it launched; nothing was started");
1120
- if (admitted.state === "background-running" && admitted.execution_ref)
1121
- return parseSandboxExecutionRef(admitted.execution_ref);
1122
- if (admitted.state === "completed")
1123
- return (await this.operationIntents.result(admitted));
1124
- sig.throwIfAborted();
1125
- let result;
1060
+ const impl = createHeldOperations(held, e.handle, sig, async (method, input, invoke, preflight) => {
1061
+ const identity = { ...invocation, ordinal: ordinal++ };
1062
+ sig.throwIfAborted();
1063
+ await this.register(env, e.lease.token);
1064
+ const refreshPending = () => runOutsideTransaction(() => this.operationIntents.pending(ctx, identity, {
1065
+ provider: p.plugin,
1066
+ providerVersion: p.version,
1067
+ generation: String(e.createdAt),
1068
+ }, method, input, e.lease.token, sig));
1069
+ const pending = await refreshPending();
1070
+ // An acknowledged start returns its recorded exact ref; it never dispatches again.
1071
+ if (pending.state === "background-running" && pending.execution_ref)
1072
+ return parseSandboxExecutionRef(pending.execution_ref);
1073
+ if (pending.state === "completed")
1074
+ return (await this.operationIntents.result(pending));
1075
+ let current;
1076
+ try {
1077
+ current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1078
+ }
1079
+ catch (error) {
1080
+ if (!(error instanceof PermissionAdmissionStale))
1081
+ throw error;
1082
+ await refreshPending();
1083
+ current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1084
+ }
1085
+ // Kernel checks on the admitted scope come before any dispatch state is written.
1086
+ if (preflight && current.state !== "completed" && current.state !== "background-running") {
1126
1087
  try {
1127
- result = await invoke(parseSandboxOperationScope(admitted.scope), sig);
1088
+ await preflight(parseSandboxOperationScope(current.scope), sig);
1128
1089
  }
1129
1090
  catch (error) {
1130
- if (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error)) {
1131
- if (["dispatching", "started-or-unknown"].includes(pending.state)) {
1132
- await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1133
- throw new SandboxOperationOutcomeUnknownError("The recorded operation remains unknown; changed runtime authority cannot prove it had no effect", { cause: error });
1134
- }
1091
+ if (current.state === "admitted" &&
1092
+ (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error))) {
1135
1093
  const kind = failureKindOf(error);
1136
- await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, {
1137
- $failure: { kind, message: error.message },
1094
+ await runOutsideTransaction(() => this.operationIntents.refusePreDispatch(ctx, identity, {
1095
+ kind,
1096
+ message: error.message,
1138
1097
  }));
1139
- throw error;
1140
1098
  }
1141
- await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1142
- // The machine's files are gone (R24): the operation stays unknown, and the caller still
1143
- // records the files lost so later calls fail without reaching the machine.
1144
- if (isFileSystemGoneError(error))
1145
- throw error;
1146
- // A transport/gone error after durable dispatch cannot justify a new identity retry.
1147
- throw new SandboxOperationOutcomeUnknownError("The operation outcome must be reconciled with its recorded identity", { cause: error });
1099
+ throw error;
1148
1100
  }
1149
- // The provider has returned: storage/serialization errors cannot establish denial.
1150
- if (method === "backgroundStart") {
1151
- try {
1152
- await runOutsideTransaction(() => this.operationIntents.acknowledgeBackground(admitted.operation_id, admitted.execution_id, result, e.handle.id));
1153
- }
1154
- catch (error) {
1101
+ }
1102
+ const reconciling = ["dispatching", "started-or-unknown"].includes(pending.state);
1103
+ // a dial-in device's machine must be connected before a new dispatch is recorded: its
1104
+ // typed answer (offline, machine revoked, device deleted) proves nothing was sent
1105
+ if (!reconciling && current.state === "admitted" && this.relay && servesDialIn(p))
1106
+ await this.relay.connection(env);
1107
+ const admitted = reconciling
1108
+ ? await runOutsideTransaction(() => this.operationIntents.claimReconciliation(ctx, identity, {
1109
+ provider: p.plugin,
1110
+ providerVersion: p.version,
1111
+ generation: String(e.createdAt),
1112
+ }, method, input, e.lease.token))
1113
+ : await runOutsideTransaction(() => this.operationIntents.claimDispatch(ctx, identity, e.lease.token, method === "backgroundStart"
1114
+ ? backgroundBinding(input, e.handle.id)
1115
+ : undefined));
1116
+ if (admitted.state === "revoked")
1117
+ throw admitted.outcome_unknown
1118
+ ? new SandboxOperationOutcomeUnknownError("The background task was stopped before its start was confirmed; it is not started again and its cancellation is owed")
1119
+ : new SandboxScopeDeniedError("The background task was stopped or settled before it launched; nothing was started");
1120
+ if (admitted.state === "background-running" && admitted.execution_ref)
1121
+ return parseSandboxExecutionRef(admitted.execution_ref);
1122
+ if (admitted.state === "completed")
1123
+ return (await this.operationIntents.result(admitted));
1124
+ sig.throwIfAborted();
1125
+ let result;
1126
+ try {
1127
+ result = await invoke(parseSandboxOperationScope(admitted.scope), sig);
1128
+ }
1129
+ catch (error) {
1130
+ if (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error)) {
1131
+ if (["dispatching", "started-or-unknown"].includes(pending.state)) {
1155
1132
  await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1156
- throw new SandboxOperationOutcomeUnknownError("The start returned but could not be acknowledged; reconcile the same identity", { cause: error });
1133
+ throw new SandboxOperationOutcomeUnknownError("The recorded operation remains unknown; changed runtime authority cannot prove it had no effect", { cause: error });
1157
1134
  }
1158
- return result;
1135
+ const kind = failureKindOf(error);
1136
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, {
1137
+ $failure: { kind, message: error.message },
1138
+ }));
1139
+ throw error;
1159
1140
  }
1141
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1142
+ // The machine's files are gone (R24): the operation stays unknown, and the caller still
1143
+ // records the files lost so later calls fail without reaching the machine.
1144
+ if (isFileSystemGoneError(error))
1145
+ throw error;
1146
+ // A transport/gone error after durable dispatch cannot justify a new identity retry.
1147
+ throw new SandboxOperationOutcomeUnknownError("The operation outcome must be reconciled with its recorded identity", { cause: error });
1148
+ }
1149
+ // The provider has returned: storage/serialization errors cannot establish denial.
1150
+ if (method === "backgroundStart") {
1160
1151
  try {
1161
- await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, result));
1152
+ await runOutsideTransaction(() => this.operationIntents.acknowledgeBackground(admitted.operation_id, admitted.execution_id, result, e.handle.id));
1162
1153
  }
1163
1154
  catch (error) {
1164
1155
  await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1165
- throw new SandboxOperationOutcomeUnknownError("The operation returned but its result could not be retained; reconcile the same identity", { cause: error });
1156
+ throw new SandboxOperationOutcomeUnknownError("The start returned but could not be acknowledged; reconcile the same identity", { cause: error });
1166
1157
  }
1167
1158
  return result;
1168
- })
1169
- : createLegacyHeldProvider(p.impl, e.lease.token, ctx.actor, () => this.register(env, e.lease.token));
1170
- const contextEvidence = invocation?.contextEvidence
1159
+ }
1160
+ try {
1161
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, result));
1162
+ }
1163
+ catch (error) {
1164
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1165
+ throw new SandboxOperationOutcomeUnknownError("The operation returned but its result could not be retained; reconcile the same identity", { cause: error });
1166
+ }
1167
+ return result;
1168
+ });
1169
+ const contextEvidence = invocation.contextEvidence
1171
1170
  ? await this.heldContextEvidence(ctx, p, e)
1172
1171
  : undefined;
1173
1172
  const info = {
@@ -1175,7 +1174,7 @@ let SandboxService = class SandboxService {
1175
1174
  roots: rootsOf(e.handle),
1176
1175
  ...(contextEvidence && { contextEvidence }),
1177
1176
  };
1178
- if (invocation?.beforeUser)
1177
+ if (invocation.beforeUser)
1179
1178
  await invocation.beforeUser({
1180
1179
  prepare: (purpose, roots, stage) => this.prepareFor(ctx, e.handle, p.impl, info, purpose, roots, stage, sig),
1181
1180
  }, info, sig);
@@ -1821,8 +1820,10 @@ let SandboxService = class SandboxService {
1821
1820
  * (with intent, so running commands finish and new ones wait) up to 10 minutes. Without the
1822
1821
  * provider of its instance row loaded it throws and the row stays, marked `sweep_failed_at` (the
1823
1822
  * job is retried, and the destruction sweep finishes a deleted device once the provider is
1824
- * back). The provider only needs to be loaded: a device is deleted while its org has the
1825
- * provider off too.
1823
+ * back). A provider that is no longer installed on this deployment (no install record, or its
1824
+ * catalog item removed; never an in-process `@…` one) will not be back: the instance is
1825
+ * abandoned instead ({@link abandonInstance}) and the call returns (#675). The provider only
1826
+ * needs to be loaded: a device is deleted while its org has the provider off too.
1826
1827
  */
1827
1828
  async destroyDevice(deviceId) {
1828
1829
  const row = await this.db
@@ -1835,6 +1836,10 @@ let SandboxService = class SandboxService {
1835
1836
  const p = row.provider !== null
1836
1837
  ? this.providers.forDevice(row.provider)
1837
1838
  : await this.providerOf(deviceId);
1839
+ if (!p && row.provider !== null && !(await this.providerInstalled(row.provider))) {
1840
+ await this.abandonInstance(deviceId, row.provider);
1841
+ return;
1842
+ }
1838
1843
  if (!p) {
1839
1844
  await this.db
1840
1845
  .updateTable("device_instances")
@@ -1861,6 +1866,77 @@ let SandboxService = class SandboxService {
1861
1866
  await lease.release();
1862
1867
  }
1863
1868
  }
1869
+ /**
1870
+ * Whether `provider` is still installed on this deployment: an in-process `@…` provider always
1871
+ * counts (code, not an install), a plugin while its install record exists and the catalog item
1872
+ * it was installed from (if any) is not removed. Not loaded on this replica is a separate case.
1873
+ */
1874
+ async providerInstalled(provider) {
1875
+ if (isInProcessName(provider))
1876
+ return true;
1877
+ const install = await this.db
1878
+ .selectFrom("extension_installs as i")
1879
+ .leftJoin("catalog_items as c", "c.id", "i.catalog_item_id")
1880
+ .select(["i.catalog_item_id", "c.id as item_id", "c.deleted_at"])
1881
+ .where("i.name", "=", provider)
1882
+ .executeTakeFirst();
1883
+ if (!install)
1884
+ return false;
1885
+ return install.catalog_item_id === null || (install.item_id !== null && !install.deleted_at);
1886
+ }
1887
+ /**
1888
+ * Abandons the instance of a deleted device whose provider is no longer installed (#675): the
1889
+ * kernel can never destroy it, so the row is kept as the record of the provider-side names
1890
+ * (`handle`, `fs_handle`, `prev_handle`), marked `abandoned_at`, and one platform audit event
1891
+ * (`device.instance_abandoned`, for the super admin) carries the same names. One statement, so
1892
+ * the mark and its event commit together, and only the first call writes either (a retried job
1893
+ * finds the row abandoned and does nothing). The sweeps iterate loaded providers only, so
1894
+ * nothing retries the row; a plugin of that name installed again destroys it as before.
1895
+ */
1896
+ async abandonInstance(deviceId, provider) {
1897
+ const written = await this.db
1898
+ .with("a", (db) => db
1899
+ .updateTable("device_instances")
1900
+ .set({ abandoned_at: sql `now()`, sweep_failed_at: null })
1901
+ .where("device_id", "=", deviceId)
1902
+ .where("provider", "=", provider)
1903
+ .where("abandoned_at", "is", null)
1904
+ .returning([
1905
+ "device_id",
1906
+ "provider",
1907
+ "handle",
1908
+ "fs_handle",
1909
+ "prev_provider",
1910
+ "prev_handle",
1911
+ ]))
1912
+ .insertInto("audit_events")
1913
+ .columns(["action", "target", "detail"])
1914
+ .expression((eb) => eb
1915
+ .selectFrom("a")
1916
+ .leftJoin("devices as d", "d.id", "a.device_id")
1917
+ .select([
1918
+ sql `'device.instance_abandoned'`.as("action"),
1919
+ "a.device_id as target",
1920
+ sql `jsonb_build_object(
1921
+ 'orgId', d.org_id,
1922
+ 'provider', a.provider,
1923
+ 'handle', a.handle,
1924
+ 'fsHandle', a.fs_handle,
1925
+ 'prevProvider', a.prev_provider,
1926
+ 'prevHandle', a.prev_handle,
1927
+ 'reason', 'provider_uninstalled'
1928
+ )`.as("detail"),
1929
+ ]))
1930
+ .returning("detail")
1931
+ .execute();
1932
+ if (written.length > 0) {
1933
+ this.log.warn("device instance abandoned: its provider is no longer installed", {
1934
+ deviceId,
1935
+ provider,
1936
+ detail: written[0]?.detail,
1937
+ });
1938
+ }
1939
+ }
1864
1940
  /**
1865
1941
  * Starts the device over with empty files (after `device.files_lost`, or on request):
1866
1942
  * under the exclusive lease (waited for like {@link destroyDevice}) destroys any instance and
@@ -2801,7 +2877,7 @@ let SandboxService = class SandboxService {
2801
2877
  // Lease lost (or the device read failed) before the handle was recorded: destroy the new
2802
2878
  // instance (best effort) so it does not leak. A provider that reuses instances by name
2803
2879
  // (Ruling M10) may then hit the one the new holder just resumed or created; that heals:
2804
- // its next provider call throws SandboxGoneError (or resume returns gone) and withSandbox
2880
+ // its next provider call throws SandboxGoneError (or resume returns gone) and the use
2805
2881
  // rebuilds in place. The file system is never touched here.
2806
2882
  await p.impl.destroy(handle, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)).catch((err) => this.log.warn("cannot destroy sandbox created after the lock was lost", {
2807
2883
  deviceId: id,
@@ -1,5 +1,8 @@
1
1
  import type { SandboxActor } from "@capybara-hq/plugin-sdk";
2
- /** Who uses the sandbox in {@link SandboxService.withSandbox}. */
2
+ /**
3
+ * Who uses the sandbox in {@link SandboxService.withOperations} and the service's other use
4
+ * entries (trusted preparation, the run start's kernel read).
5
+ */
3
6
  export interface SandboxUseContext {
4
7
  orgId: string;
5
8
  deviceId: string;
@@ -3,12 +3,10 @@ import { type AgentDefinition } from "../agents/definition.js";
3
3
  import { EventLog } from "../conversations/event-log.js";
4
4
  import type { EventPayload } from "../conversations/events.js";
5
5
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
6
- import { ConversationDevices } from "../devices/conversation-devices.js";
7
6
  import { ApiError } from "../errors.js";
8
7
  import { KernelDb } from "../infra/database/kernel-db.js";
9
8
  import type { KernelLogger } from "../log.js";
10
9
  import { type ProjectRootPayload } from "../runtime/context/project-root.js";
11
- import { SandboxService } from "../sandbox/sandbox.service.js";
12
10
  import { StorageService } from "../storage/storage.service.js";
13
11
  import { type ResolvedSkill } from "./catalog.js";
14
12
  /**
@@ -103,12 +101,12 @@ export declare function recordedSkillBlocked(db: KernelSchemaDb, a: {
103
101
  /** The model-visible text of a fork invocation in the parent's log (spec §6.3, frozen). */
104
102
  export declare const forkLeadText: (name: string, agentType: string, args: string) => string;
105
103
  /**
106
- * A person's `/project:<name>` invocation once the activation gate is on (permission activation
107
- * L2, Hook 2): no device read at send time (a person's send has no run, so nothing could admit
108
- * it). The message is a stub rendered from the conversation's latest `project_root` (the skill's
109
- * name, its recorded digest, its directory in the project and the person's arguments) telling the
110
- * agent to load `project:<name>` with its `Skill` tool, which reads it under the run's admission.
111
- * Model-visible, so English; tags in the arguments stay inert. Always inline, as before.
104
+ * A person's `/project:<name>` invocation (permission activation L2, Hook 2): no device read at
105
+ * send time (a person's send has no run, so nothing could admit it). The message is a stub
106
+ * rendered from the conversation's latest `project_root` (the skill's name, its recorded digest,
107
+ * its directory in the project and the person's arguments) telling the agent to load
108
+ * `project:<name>` with its `Skill` tool, which reads it under the run's admission. Model-visible,
109
+ * so English; tags in the arguments stay inert. Always inline, as before.
112
110
  */
113
111
  export declare function projectSkillStub(a: {
114
112
  name: string;
@@ -128,18 +126,9 @@ export declare class SkillInvoker {
128
126
  private readonly log;
129
127
  /** A bound conversation's latest `project_root` (its project skills). */
130
128
  private readonly eventLog;
131
- /** A project skill's SKILL.md is read through the conversation's device. */
132
- private readonly sandbox;
133
- private readonly devices;
134
- /** The paired activation gate: once on, no raw device use reads a project skill. */
135
- private readonly activation?;
136
129
  constructor(db: KernelDb, storage: StorageService, agents: Pick<AgentLookup, "get">, log: KernelLogger,
137
130
  /** A bound conversation's latest `project_root` (its project skills). */
138
- eventLog: Pick<EventLog, "latestOfType">,
139
- /** A project skill's SKILL.md is read through the conversation's device. */
140
- sandbox: Pick<SandboxService, "withSandbox">, devices: Pick<ConversationDevices, "forTool" | "modeLevel" | "workingFacts">,
141
- /** The paired activation gate: once on, no raw device use reads a project skill. */
142
- activation?: boolean | undefined);
131
+ eventLog: Pick<EventLog, "latestOfType">);
143
132
  /**
144
133
  * The `/` menu for `accountId`: the agent must be usable by them (`agent.not_found`), and with
145
134
  * `conversationId` the conversation must be theirs and the agent's (`conversation.not_found`);
@@ -177,25 +166,14 @@ export declare class SkillInvoker {
177
166
  }): Promise<RenderedInvocation>;
178
167
  /**
179
168
  * A person's invocation of `project:<name>` (project root spec §4.6): resolved from the
180
- * conversation's latest `project_root` (what the model saw), then its SKILL.md is read through
181
- * the conversation's device as `Skill` reads it ({@link readProjectSkill}) and rendered like any
182
- * invocation, `${CLAUDE_SKILL_DIR}` being the skill's directory in the project. Always inline
183
- * (`context: fork` is not honoured for project skills, as in `Skill`). Refusals:
184
- * `skill.not_invocable` `not_found` (no conversation yet, no project, a name it does not list),
185
- * `skill.project_unavailable` with its reason (the latest project is unavailable, or its file
186
- * cannot be used), the device's own refusals as they are (`device.offline`, ...),
187
- * `device.projects_unavailable` when the device cannot be asked. Once the activation gate is on
188
- * the device is not read at send time: the invocation is the recorded stub
189
- * ({@link projectSkillStub}) and only the first two refusals remain, plus
190
- * `skill.project_unavailable` `skill_tool_off` for an agent without the `Skill` tool.
169
+ * conversation's latest `project_root` (what the model saw). The device is not read at send
170
+ * time: the invocation is the recorded stub ({@link projectSkillStub}), which the agent's
171
+ * `Skill` tool loads. Refusals: `skill.not_invocable` `not_found` (no conversation yet, no
172
+ * project, a name it does not list), `skill.project_unavailable` with its reason (the latest
173
+ * project is unavailable), and `skill.project_unavailable` `skill_tool_off` for an agent without
174
+ * the `Skill` tool.
191
175
  */
192
176
  private prepareProject;
193
- /**
194
- * {@link readProjectSkill} in a silent use of the conversation's device, as its owner (gate off
195
- * only: once activated a person's invocation renders {@link projectSkillStub} and never reads
196
- * the device at send time).
197
- */
198
- private readProjectFile;
199
177
  /**
200
178
  * The task of a fork invocation's sub-agent (spec §6.2), rendered at dispatch from the version
201
179
  * the person's message recorded (`skill.{id, source, version, arguments}`), never by name, so a