@capybara-hq/kernel 0.1.0-rc.40 → 0.1.0-rc.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.json +10 -1
- package/dist/admin/admin.schemas.d.ts +6 -0
- package/dist/admin/org-network.service.d.ts +3 -1
- package/dist/admin/org-network.service.js +10 -2
- package/dist/app.d.ts +4 -0
- package/dist/app.js +2 -0
- package/dist/background/finish.d.ts +9 -1
- package/dist/background/finish.js +57 -4
- package/dist/background/launch.d.ts +23 -0
- package/dist/background/launch.js +55 -1
- package/dist/background/managed-output.d.ts +110 -0
- package/dist/background/managed-output.js +219 -0
- package/dist/background/managed.d.ts +52 -0
- package/dist/background/managed.js +128 -0
- package/dist/background/poll.job.d.ts +35 -1
- package/dist/background/poll.job.js +174 -9
- package/dist/background/render.js +1 -0
- package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
- package/dist/background/retire-legacy-tasks.job.js +149 -0
- package/dist/background/session.d.ts +15 -5
- package/dist/background/session.js +22 -6
- package/dist/background/stop.d.ts +35 -5
- package/dist/background/stop.js +94 -8
- package/dist/background/store.d.ts +110 -3
- package/dist/background/store.js +205 -3
- package/dist/background/tasks.service.d.ts +18 -1
- package/dist/background/tasks.service.js +99 -9
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/cards.js +1 -1
- package/dist/channels/inbound.js +2 -0
- package/dist/channels/phrases.d.ts +4 -0
- package/dist/channels/phrases.js +4 -0
- package/dist/config/load.d.ts +18 -0
- package/dist/config/load.js +39 -1
- package/dist/config/permission-migration.d.ts +26 -0
- package/dist/config/permission-migration.js +64 -0
- package/dist/config/schema.d.ts +1 -1
- package/dist/config/schema.js +11 -10
- package/dist/conversations/conversations.controller.d.ts +1 -1
- package/dist/conversations/conversations.controller.js +1 -1
- package/dist/conversations/conversations.module.js +12 -0
- package/dist/conversations/conversations.service.d.ts +11 -2
- package/dist/conversations/conversations.service.js +97 -27
- package/dist/conversations/event-log.d.ts +1 -1
- package/dist/conversations/event-log.js +10 -2
- package/dist/conversations/events.d.ts +304 -4
- package/dist/conversations/events.js +279 -29
- package/dist/conversations/permission-profile-store.d.ts +50 -0
- package/dist/conversations/permission-profile-store.js +67 -0
- package/dist/conversations/permission-profile-store.module.d.ts +2 -0
- package/dist/conversations/permission-profile-store.module.js +19 -0
- package/dist/conversations/permission-profiles.controller.d.ts +84 -0
- package/dist/conversations/permission-profiles.controller.js +105 -0
- package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
- package/dist/conversations/permission-profiles.schemas.js +23 -0
- package/dist/conversations/permission-profiles.service.d.ts +56 -0
- package/dist/conversations/permission-profiles.service.js +179 -0
- package/dist/db/kernel-schema.d.ts +238 -3
- package/dist/devices/access.js +1 -1
- package/dist/devices/access.module.d.ts +2 -0
- package/dist/devices/access.module.js +19 -0
- package/dist/devices/conversation-devices.d.ts +8 -29
- package/dist/devices/conversation-devices.js +37 -73
- package/dist/devices/device-projects.service.d.ts +26 -28
- package/dist/devices/device-projects.service.js +123 -127
- package/dist/devices/devices.controller.js +3 -1
- package/dist/devices/devices.module.js +11 -9
- package/dist/devices/devices.service.d.ts +116 -8
- package/dist/devices/devices.service.js +252 -20
- package/dist/devices/dto.d.ts +16 -0
- package/dist/devices/dto.js +34 -6
- package/dist/devices/errors.d.ts +8 -0
- package/dist/devices/errors.js +10 -0
- package/dist/devices/project-rules.d.ts +44 -0
- package/dist/devices/project-rules.js +27 -0
- package/dist/devices/working-root.d.ts +6 -0
- package/dist/devices/working-root.js +12 -1
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +31 -0
- package/dist/evals/reconstruct.d.ts +19 -2
- package/dist/evals/reconstruct.js +40 -2
- package/dist/evals/recorded-permission-context.d.ts +77 -0
- package/dist/evals/recorded-permission-context.js +151 -0
- package/dist/evals/recorded-tools.d.ts +10 -1
- package/dist/evals/recorded-tools.js +27 -3
- package/dist/evals/run-replay.d.ts +8 -2
- package/dist/evals/run-replay.js +18 -2
- package/dist/evals/trajectory.d.ts +1 -1
- package/dist/evals/worker.d.ts +10 -1
- package/dist/evals/worker.js +23 -14
- package/dist/http/api.module.js +2 -0
- package/dist/identity/accounts.d.ts +14 -1
- package/dist/identity/accounts.js +61 -5
- package/dist/identity/identity.module.js +2 -0
- package/dist/identity/settings.d.ts +28 -12
- package/dist/identity/settings.js +89 -33
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
- package/dist/infra/cli/kernel-cli.module.js +5 -2
- package/dist/infra/cli/permission-cutover.d.ts +59 -0
- package/dist/infra/cli/permission-cutover.js +107 -0
- package/dist/infra/config/kernel-config.service.d.ts +2 -2
- package/dist/infra/config/kernel-config.service.js +31 -11
- package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
- package/dist/infra/database/startup-activation-transaction.js +242 -0
- package/dist/infra/database/transaction-host.d.ts +47 -0
- package/dist/infra/database/transaction-host.js +119 -0
- package/dist/infra/database/xact-lock.d.ts +1 -0
- package/dist/infra/database/xact-lock.js +6 -0
- package/dist/infra/outbox/registry.d.ts +39 -0
- package/dist/infra/outbox/registry.js +18 -0
- package/dist/kernel.module.js +2 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +55 -28
- package/dist/local-devices/device-auth.js +1 -1
- package/dist/local-devices/device-policy.service.d.ts +35 -5
- package/dist/local-devices/device-policy.service.js +188 -13
- package/dist/local-devices/instance-bindings.d.ts +82 -0
- package/dist/local-devices/instance-bindings.js +304 -0
- package/dist/local-devices/keys.d.ts +5 -0
- package/dist/local-devices/keys.js +5 -0
- package/dist/local-devices/local-device-gateway.d.ts +19 -4
- package/dist/local-devices/local-device-gateway.js +185 -17
- package/dist/local-devices/local-device-provider.d.ts +42 -7
- package/dist/local-devices/local-device-provider.js +185 -10
- package/dist/local-devices/local-devices.module.d.ts +17 -2
- package/dist/local-devices/local-devices.module.js +49 -8
- package/dist/local-devices/machines.d.ts +35 -12
- package/dist/local-devices/machines.js +203 -8
- package/dist/local-devices/network-grants.js +3 -3
- package/dist/local-devices/network-grants.module.d.ts +2 -0
- package/dist/local-devices/network-grants.module.js +14 -0
- package/dist/local-devices/owner-report.d.ts +79 -0
- package/dist/local-devices/owner-report.js +155 -0
- package/dist/local-devices/owner-reports.d.ts +48 -0
- package/dist/local-devices/owner-reports.js +190 -0
- package/dist/local-devices/policy-summary.d.ts +24 -1
- package/dist/local-devices/policy-summary.js +48 -0
- package/dist/local-devices/relay.d.ts +82 -6
- package/dist/local-devices/relay.js +187 -16
- package/dist/local-devices/targets.d.ts +16 -1
- package/dist/local-devices/targets.js +35 -2
- package/dist/orgs/cloud-network-setting.d.ts +33 -0
- package/dist/orgs/cloud-network-setting.js +47 -0
- package/dist/orgs/offboarding.d.ts +3 -1
- package/dist/orgs/offboarding.js +8 -2
- package/dist/orgs/org-lock.d.ts +10 -4
- package/dist/orgs/org-lock.js +10 -4
- package/dist/orgs/orgs.service.d.ts +3 -1
- package/dist/orgs/orgs.service.js +8 -2
- package/dist/orgs/settings.controller.d.ts +4 -1
- package/dist/orgs/settings.controller.js +3 -3
- package/dist/orgs/settings.service.d.ts +48 -56
- package/dist/orgs/settings.service.js +144 -101
- package/dist/overrides.d.ts +6 -1
- package/dist/overrides.js +2 -0
- package/dist/platform/exclusions.js +20 -0
- package/dist/platform/ops/admin.ops.js +14 -11
- package/dist/platform/ops/agent-skills.ops.js +2 -0
- package/dist/platform/ops/devices.ops.js +10 -2
- package/dist/platform/ops/org-settings.ops.js +6 -6
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/roles/worker.module.js +4 -0
- package/dist/runtime/context/build.d.ts +3 -1
- package/dist/runtime/context/build.js +19 -3
- package/dist/runtime/context/compaction.js +5 -0
- package/dist/runtime/context/device-paths.d.ts +9 -2
- package/dist/runtime/context/device-paths.js +20 -0
- package/dist/runtime/context/permission-profile.d.ts +46 -0
- package/dist/runtime/context/permission-profile.js +194 -0
- package/dist/runtime/maintenance.d.ts +7 -1
- package/dist/runtime/maintenance.js +43 -15
- package/dist/runtime/model-call.d.ts +32 -0
- package/dist/runtime/model-call.js +67 -0
- package/dist/runtime/permission-context-errors.d.ts +39 -0
- package/dist/runtime/permission-context-errors.js +67 -0
- package/dist/runtime/permission-context.service.d.ts +60 -0
- package/dist/runtime/permission-context.service.js +286 -0
- package/dist/runtime/project/knowledge.d.ts +7 -2
- package/dist/runtime/project/knowledge.js +5 -2
- package/dist/runtime/project/knowledge.service.d.ts +17 -2
- package/dist/runtime/project/knowledge.service.js +76 -12
- package/dist/runtime/run-execution.d.ts +4 -1
- package/dist/runtime/run-execution.js +14 -5
- package/dist/runtime/run-steps.d.ts +11 -3
- package/dist/runtime/run-steps.js +27 -4
- package/dist/runtime/runtime.module.js +11 -0
- package/dist/sandbox/attachments-path.d.ts +15 -0
- package/dist/sandbox/attachments-path.js +15 -0
- package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
- package/dist/sandbox/cloud-permission-snapshot.js +407 -0
- package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
- package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
- package/dist/sandbox/held-operations.d.ts +39 -0
- package/dist/sandbox/held-operations.js +119 -0
- package/dist/sandbox/jobs.d.ts +14 -3
- package/dist/sandbox/jobs.js +20 -2
- package/dist/sandbox/kernel-read.d.ts +55 -0
- package/dist/sandbox/kernel-read.js +57 -0
- package/dist/sandbox/legacy-retirement.d.ts +336 -0
- package/dist/sandbox/legacy-retirement.js +1063 -0
- package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
- package/dist/sandbox/legacy-retirement.module.js +25 -0
- package/dist/sandbox/managed-device-context.d.ts +94 -0
- package/dist/sandbox/managed-device-context.js +308 -0
- package/dist/sandbox/managed-device-context.module.d.ts +6 -0
- package/dist/sandbox/managed-device-context.module.js +33 -0
- package/dist/sandbox/modes.d.ts +56 -8
- package/dist/sandbox/modes.js +92 -8
- package/dist/sandbox/operation-authority-types.d.ts +8 -0
- package/dist/sandbox/operation-authority-types.js +32 -0
- package/dist/sandbox/operation-authority.d.ts +145 -0
- package/dist/sandbox/operation-authority.js +783 -0
- package/dist/sandbox/operation-authority.module.d.ts +2 -0
- package/dist/sandbox/operation-authority.module.js +29 -0
- package/dist/sandbox/operation-intents.d.ts +206 -0
- package/dist/sandbox/operation-intents.js +1252 -0
- package/dist/sandbox/operation-intents.module.d.ts +2 -0
- package/dist/sandbox/operation-intents.module.js +21 -0
- package/dist/sandbox/operation-payloads.d.ts +33 -0
- package/dist/sandbox/operation-payloads.js +332 -0
- package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
- package/dist/sandbox/operation-reconcile.job.js +247 -0
- package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
- package/dist/sandbox/permission-authority-epochs.js +83 -0
- package/dist/sandbox/permission-authority-lock.d.ts +38 -0
- package/dist/sandbox/permission-authority-lock.js +147 -0
- package/dist/sandbox/permission-authority.module.d.ts +9 -0
- package/dist/sandbox/permission-authority.module.js +55 -0
- package/dist/sandbox/permission-availability.d.ts +18 -0
- package/dist/sandbox/permission-availability.js +19 -0
- package/dist/sandbox/permission-call-grants.d.ts +34 -0
- package/dist/sandbox/permission-call-grants.js +349 -0
- package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
- package/dist/sandbox/permission-call-grants.module.js +21 -0
- package/dist/sandbox/permission-call-types.d.ts +82 -0
- package/dist/sandbox/permission-call-types.js +1 -0
- package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
- package/dist/sandbox/permission-ceiling-writes.js +223 -0
- package/dist/sandbox/permission-config-publication.d.ts +76 -0
- package/dist/sandbox/permission-config-publication.js +339 -0
- package/dist/sandbox/permission-context-types.d.ts +64 -0
- package/dist/sandbox/permission-context-types.js +24 -0
- package/dist/sandbox/permission-facts.d.ts +206 -0
- package/dist/sandbox/permission-facts.js +627 -0
- package/dist/sandbox/permission-facts.module.d.ts +2 -0
- package/dist/sandbox/permission-facts.module.js +20 -0
- package/dist/sandbox/permission-instance-writes.d.ts +90 -0
- package/dist/sandbox/permission-instance-writes.js +305 -0
- package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
- package/dist/sandbox/permission-runtime-reports.js +354 -0
- package/dist/sandbox/permission-transitions.d.ts +31 -0
- package/dist/sandbox/permission-transitions.js +155 -0
- package/dist/sandbox/platform-full-access.d.ts +128 -0
- package/dist/sandbox/platform-full-access.js +210 -0
- package/dist/sandbox/providers.d.ts +22 -0
- package/dist/sandbox/providers.js +10 -2
- package/dist/sandbox/providers.module.d.ts +2 -0
- package/dist/sandbox/providers.module.js +19 -0
- package/dist/sandbox/request-not-sent.d.ts +13 -0
- package/dist/sandbox/request-not-sent.js +13 -0
- package/dist/sandbox/review/classifier.d.ts +2 -0
- package/dist/sandbox/review/classifier.js +8 -0
- package/dist/sandbox/review/permission-candidate.d.ts +12 -0
- package/dist/sandbox/review/permission-candidate.js +129 -0
- package/dist/sandbox/review/review.service.d.ts +4 -1
- package/dist/sandbox/review/review.service.js +19 -5
- package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
- package/dist/sandbox/sandbox-file-reader.js +51 -7
- package/dist/sandbox/sandbox.module.js +26 -6
- package/dist/sandbox/sandbox.service.d.ts +230 -34
- package/dist/sandbox/sandbox.service.js +1368 -199
- package/dist/sandbox/unreachable.js +17 -3
- package/dist/sandbox/use-context.d.ts +17 -0
- package/dist/sandbox/use-context.js +1 -0
- package/dist/skills/invoke.d.ts +27 -4
- package/dist/skills/invoke.js +72 -7
- package/dist/tools/approvals.controller.d.ts +1 -0
- package/dist/tools/approvals.schemas.d.ts +1 -0
- package/dist/tools/approvals.schemas.js +3 -1
- package/dist/tools/approvals.service.d.ts +23 -10
- package/dist/tools/approvals.service.js +104 -26
- package/dist/tools/builtins/builtin-tools.d.ts +16 -2
- package/dist/tools/builtins/builtin-tools.js +38 -10
- package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
- package/dist/tools/builtins/sandbox/bash.js +201 -5
- package/dist/tools/builtins/sandbox/common.d.ts +92 -20
- package/dist/tools/builtins/sandbox/common.js +201 -17
- package/dist/tools/builtins/sandbox/deliver.js +2 -2
- package/dist/tools/builtins/sandbox/edit.js +2 -2
- package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
- package/dist/tools/builtins/sandbox/glob.js +2 -2
- package/dist/tools/builtins/sandbox/grep.js +2 -2
- package/dist/tools/builtins/sandbox/read.js +2 -2
- package/dist/tools/builtins/sandbox/task-list.js +7 -1
- package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
- package/dist/tools/builtins/sandbox/task-output.js +172 -0
- package/dist/tools/builtins/sandbox/task-stop.js +25 -3
- package/dist/tools/builtins/sandbox/write.js +2 -2
- package/dist/tools/builtins/skill-load.js +9 -6
- package/dist/tools/device-op-resolver.d.ts +1 -1
- package/dist/tools/device-op-resolver.js +13 -3
- package/dist/tools/permission-approval-jobs.d.ts +18 -0
- package/dist/tools/permission-approval-jobs.js +92 -0
- package/dist/tools/pipeline.d.ts +17 -2
- package/dist/tools/pipeline.js +300 -19
- package/dist/tools/registry.d.ts +9 -0
- package/dist/tools/tools.module.js +12 -0
- package/package.json +4 -3
- package/src/migrations/0146_permission_authority_epochs.sql +6 -0
- package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
- package/src/migrations/0148_first_message_request_hash.sql +2 -0
- package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
- package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
- package/src/migrations/0151_starting_execution_grants.sql +8 -0
- package/src/migrations/0152_background_launch_identity.sql +66 -0
- package/src/migrations/0153_background_cancel_requester.sql +13 -0
- package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
- package/src/migrations/0155_device_instance_generations.sql +30 -0
- package/src/migrations/0156_device_owner_report.sql +7 -0
- package/src/migrations/0157_legacy_retirement.sql +116 -0
- package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
- package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
- package/dist/sandbox/platform-auto-mode.d.ts +0 -63
- package/dist/sandbox/platform-auto-mode.js +0 -63
|
@@ -0,0 +1,1252 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
11
|
+
import { parseSandboxExecutionRef, parseSandboxOperationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
|
|
12
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
13
|
+
import { sql } from "kysely";
|
|
14
|
+
import { STOP_CLAIM_TTL_MS } from "../background/store.js";
|
|
15
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
16
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
17
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
18
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
19
|
+
import { SandboxOperationAuthority } from "./operation-authority.js";
|
|
20
|
+
import { describeOperationPayload, OperationPayloads, payloadReference, } from "./operation-payloads.js";
|
|
21
|
+
import { PermissionAuthorityEpochStore } from "./permission-authority-epochs.js";
|
|
22
|
+
import { PermissionAuthorityLock } from "./permission-authority-lock.js";
|
|
23
|
+
import { permissionScopeHash } from "./permission-facts.js";
|
|
24
|
+
import { DeviceRequestNotSentError } from "./request-not-sent.js";
|
|
25
|
+
export class PermissionAdmissionStale extends Error {
|
|
26
|
+
}
|
|
27
|
+
export const OPERATION_RECONCILE = "sandbox-operation-reconcile";
|
|
28
|
+
export const OPERATION_REVOKE = "sandbox-operation-revoke";
|
|
29
|
+
const stopClaimed = sql `(stopping_at IS NOT NULL AND stopping_at >= now() - ${STOP_CLAIM_TTL_MS}::integer * interval '1 millisecond')`;
|
|
30
|
+
/** A live stop claim, or a recorded cancellation request (it outlives the claim's TTL). */
|
|
31
|
+
const stopRequested = sql `(${stopClaimed} OR cancel_requested_at IS NOT NULL)`;
|
|
32
|
+
/** {@link stopRequested} for a task row already read. */
|
|
33
|
+
const stopRequestedOf = (task) => task.cancel_requested_at !== null ||
|
|
34
|
+
(task.stopping_at !== null && task.stopping_at.getTime() >= Date.now() - STOP_CLAIM_TTL_MS);
|
|
35
|
+
export function operationIdFor(i) {
|
|
36
|
+
return createHash("sha256")
|
|
37
|
+
.update(JSON.stringify([i.claim.runId, i.callId, i.ordinal]))
|
|
38
|
+
.digest("hex");
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Why a managed background start was refused, as `background_tasks.lost_reason` keeps it after
|
|
42
|
+
* `launch refused: ` (TaskOutput, TaskList, the HTTP task view and the Platform tool show it):
|
|
43
|
+
* kernel text by the failure's kind only, never the provider's own message, which stays in the
|
|
44
|
+
* operation's recorded result and the dispatcher's log.
|
|
45
|
+
*/
|
|
46
|
+
export function launchRefusedText(kind) {
|
|
47
|
+
switch (kind) {
|
|
48
|
+
case "not_sent":
|
|
49
|
+
return "the device's machine reconnected before the start was sent; retry the call";
|
|
50
|
+
case "denied":
|
|
51
|
+
return "the command or its output file is outside what this conversation may use on the device; choose a working directory this conversation may write to";
|
|
52
|
+
case "unsupported":
|
|
53
|
+
return "this device cannot run background tasks with this conversation's permissions; ask the user to choose another permission profile or device";
|
|
54
|
+
default:
|
|
55
|
+
return "the device refused the start";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export function operationResult(value) {
|
|
59
|
+
if (value && typeof value === "object" && "$expired" in value)
|
|
60
|
+
throw new SandboxOperationOutcomeUnknownError("The retained operation result has expired; this consumed identity cannot run again");
|
|
61
|
+
if (value && typeof value === "object" && "$failure" in value) {
|
|
62
|
+
const f = value.$failure;
|
|
63
|
+
if (f.kind === "denied")
|
|
64
|
+
throw new SandboxScopeDeniedError(f.message);
|
|
65
|
+
if (f.kind === "not_sent")
|
|
66
|
+
throw new DeviceRequestNotSentError(f.message);
|
|
67
|
+
if (f.kind === "unsupported")
|
|
68
|
+
throw new SandboxPermissionUnsupportedError(f.message);
|
|
69
|
+
}
|
|
70
|
+
return hydrateOperationBytes(value);
|
|
71
|
+
}
|
|
72
|
+
function hydrateOperationBytes(value) {
|
|
73
|
+
if (value instanceof Uint8Array)
|
|
74
|
+
return value;
|
|
75
|
+
if (Array.isArray(value))
|
|
76
|
+
return value.map(hydrateOperationBytes);
|
|
77
|
+
if (value && typeof value === "object") {
|
|
78
|
+
if ("$bytes" in value && typeof value.$bytes === "string" && Object.keys(value).length === 1)
|
|
79
|
+
return new Uint8Array(Buffer.from(value.$bytes, "base64"));
|
|
80
|
+
return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, hydrateOperationBytes(v)]));
|
|
81
|
+
}
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
const subjectOf = (r) => ({
|
|
85
|
+
orgId: r.org_id,
|
|
86
|
+
deviceId: r.device_id,
|
|
87
|
+
...(r.root_conversation_id ? { rootConversationId: r.root_conversation_id } : {}),
|
|
88
|
+
});
|
|
89
|
+
const denied = (message) => {
|
|
90
|
+
throw new SandboxScopeDeniedError(message);
|
|
91
|
+
};
|
|
92
|
+
/** No provider effects occur in this service. Each public mutation owns its transaction. */
|
|
93
|
+
let SandboxOperationIntents = class SandboxOperationIntents {
|
|
94
|
+
db;
|
|
95
|
+
txHost;
|
|
96
|
+
locks;
|
|
97
|
+
epochs;
|
|
98
|
+
authority;
|
|
99
|
+
outbox;
|
|
100
|
+
payloads;
|
|
101
|
+
constructor(db, txHost, locks, epochs, authority, outbox, payloads) {
|
|
102
|
+
this.db = db;
|
|
103
|
+
this.txHost = txHost;
|
|
104
|
+
this.locks = locks;
|
|
105
|
+
this.epochs = epochs;
|
|
106
|
+
this.authority = authority;
|
|
107
|
+
this.outbox = outbox;
|
|
108
|
+
this.payloads = payloads;
|
|
109
|
+
}
|
|
110
|
+
/** Current run claim plus its actual tool_call_started row authorize an internal invocation identity. */
|
|
111
|
+
async assertClaim(ctx, invocation) {
|
|
112
|
+
const c = invocation.claim;
|
|
113
|
+
if (!Number.isSafeInteger(invocation.ordinal) ||
|
|
114
|
+
invocation.ordinal < 0 ||
|
|
115
|
+
c.orgId !== ctx.orgId ||
|
|
116
|
+
c.conversationId !== ctx.holderConversationId ||
|
|
117
|
+
c.runId !== ctx.actor.runId)
|
|
118
|
+
denied("Operation invocation does not match its executing run");
|
|
119
|
+
const run = await this.db
|
|
120
|
+
.selectFrom("runs")
|
|
121
|
+
.select(["execution_id", "trigger_account_id", "status"])
|
|
122
|
+
.where("id", "=", c.runId)
|
|
123
|
+
.where("conversation_id", "=", c.conversationId)
|
|
124
|
+
.forShare()
|
|
125
|
+
.executeTakeFirst();
|
|
126
|
+
if (!run ||
|
|
127
|
+
run.execution_id !== c.executionId ||
|
|
128
|
+
run.trigger_account_id !== ctx.actor.accountId ||
|
|
129
|
+
run.status !== "running")
|
|
130
|
+
denied("The tool execution claim is no longer current");
|
|
131
|
+
const call = await this.db
|
|
132
|
+
.selectFrom("conversation_events")
|
|
133
|
+
.select("seq")
|
|
134
|
+
.where("conversation_id", "=", c.conversationId)
|
|
135
|
+
.where("run_id", "=", c.runId)
|
|
136
|
+
.where("type", "=", "tool_call_started")
|
|
137
|
+
.where(sql `payload->>'callId'`, "=", invocation.callId)
|
|
138
|
+
.executeTakeFirst();
|
|
139
|
+
if (!call)
|
|
140
|
+
denied("The operation has no recorded tool invocation");
|
|
141
|
+
}
|
|
142
|
+
async pending(ctx, invocation, instance, method, input, holderTag, signal) {
|
|
143
|
+
signal.throwIfAborted();
|
|
144
|
+
const id = operationIdFor(invocation);
|
|
145
|
+
const described = describeOperationPayload(input);
|
|
146
|
+
const payload = payloadReference("input", described);
|
|
147
|
+
const hash = permissionScopeHash({ method, inputDigest: described.digest });
|
|
148
|
+
const previous = await this.db
|
|
149
|
+
.selectFrom("sandbox_operation_intents")
|
|
150
|
+
.selectAll()
|
|
151
|
+
.where("operation_id", "=", id)
|
|
152
|
+
.executeTakeFirst();
|
|
153
|
+
if (previous) {
|
|
154
|
+
this.assertIdentity(previous, ctx, instance, method, hash);
|
|
155
|
+
if (previous.state === "pending" &&
|
|
156
|
+
(previous.execution_id !== invocation.claim.executionId ||
|
|
157
|
+
previous.deadline.getTime() <= Date.now()))
|
|
158
|
+
denied("Pending operation claim changed or admission deadline elapsed");
|
|
159
|
+
if (previous.state !== "pending") {
|
|
160
|
+
await this.locks.acquire(subjectOf(previous), { kind: "admit" });
|
|
161
|
+
await this.assertClaim(ctx, invocation);
|
|
162
|
+
return previous;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// resolve joins this transaction and holds every shared ancestor through the insert commit.
|
|
166
|
+
const { scope: resolved, permissionGrantId, grantedHosts, executionGrants, } = await this.authority.resolveInvocation(ctx, method, { runId: invocation.claim.runId, callId: invocation.callId }, signal);
|
|
167
|
+
await this.assertClaim(ctx, invocation);
|
|
168
|
+
if (resolved.rootConversationId !== invocation.claim.rootId)
|
|
169
|
+
denied("The operation root no longer matches the execution claim");
|
|
170
|
+
const deadline = Math.min(resolved.admitBeforeMs, invocation.deadlineMs, previous?.deadline.getTime() ?? Infinity);
|
|
171
|
+
if (!Number.isSafeInteger(deadline) || deadline <= Date.now())
|
|
172
|
+
denied("Operation admission deadline elapsed");
|
|
173
|
+
const scope = parseSandboxOperationScope({
|
|
174
|
+
...resolved,
|
|
175
|
+
operationId: id,
|
|
176
|
+
tag: id,
|
|
177
|
+
admitBeforeMs: deadline,
|
|
178
|
+
});
|
|
179
|
+
const vector = await this.epochs.readLocked({
|
|
180
|
+
orgId: ctx.orgId,
|
|
181
|
+
deviceId: ctx.deviceId,
|
|
182
|
+
rootConversationId: scope.rootConversationId,
|
|
183
|
+
});
|
|
184
|
+
await this.db
|
|
185
|
+
.insertInto("sandbox_operation_intents")
|
|
186
|
+
.values({
|
|
187
|
+
operation_id: id,
|
|
188
|
+
org_id: ctx.orgId,
|
|
189
|
+
account_id: ctx.actor.accountId,
|
|
190
|
+
device_id: ctx.deviceId,
|
|
191
|
+
root_conversation_id: scope.rootConversationId,
|
|
192
|
+
conversation_id: ctx.holderConversationId,
|
|
193
|
+
run_id: invocation.claim.runId,
|
|
194
|
+
call_id: invocation.callId,
|
|
195
|
+
ordinal: invocation.ordinal,
|
|
196
|
+
method,
|
|
197
|
+
input_hash: hash,
|
|
198
|
+
permission_grant_id: permissionGrantId,
|
|
199
|
+
granted_hosts: JSON.stringify(grantedHosts),
|
|
200
|
+
execution_grants: executionGrants === null ? null : JSON.stringify(executionGrants),
|
|
201
|
+
admission_hash: permissionScopeHash({
|
|
202
|
+
method,
|
|
203
|
+
inputDigest: described.digest,
|
|
204
|
+
scope,
|
|
205
|
+
executionGrants,
|
|
206
|
+
}),
|
|
207
|
+
input: payload,
|
|
208
|
+
scope: JSON.stringify(scope),
|
|
209
|
+
epochs: JSON.stringify(vector),
|
|
210
|
+
provider: instance.provider,
|
|
211
|
+
provider_version: instance.providerVersion,
|
|
212
|
+
instance_generation: instance.generation,
|
|
213
|
+
deadline: new Date(deadline),
|
|
214
|
+
retain_until: new Date(deadline + 86_400_000),
|
|
215
|
+
execution_id: invocation.claim.executionId,
|
|
216
|
+
holder_token: holderTag,
|
|
217
|
+
})
|
|
218
|
+
.onConflict((oc) => oc.column("operation_id").doNothing())
|
|
219
|
+
.execute();
|
|
220
|
+
if (previous?.state === "pending")
|
|
221
|
+
await this.db
|
|
222
|
+
.updateTable("sandbox_operation_intents")
|
|
223
|
+
.set({
|
|
224
|
+
input: payload,
|
|
225
|
+
scope: JSON.stringify(scope),
|
|
226
|
+
permission_grant_id: permissionGrantId,
|
|
227
|
+
granted_hosts: JSON.stringify(grantedHosts),
|
|
228
|
+
execution_grants: executionGrants === null ? null : JSON.stringify(executionGrants),
|
|
229
|
+
admission_hash: permissionScopeHash({
|
|
230
|
+
method,
|
|
231
|
+
inputDigest: described.digest,
|
|
232
|
+
scope,
|
|
233
|
+
executionGrants,
|
|
234
|
+
}),
|
|
235
|
+
epochs: JSON.stringify(vector),
|
|
236
|
+
deadline: new Date(deadline),
|
|
237
|
+
retain_until: new Date(deadline + 86_400_000),
|
|
238
|
+
updated_at: new Date(),
|
|
239
|
+
})
|
|
240
|
+
.where("operation_id", "=", id)
|
|
241
|
+
.where("state", "=", "pending")
|
|
242
|
+
.execute();
|
|
243
|
+
const row = await this.read(id);
|
|
244
|
+
this.assertIdentity(row, ctx, instance, method, hash);
|
|
245
|
+
if (row.state === "pending")
|
|
246
|
+
await this.payloads.save(id, "input", input, described);
|
|
247
|
+
await this.scheduleExpiry(row);
|
|
248
|
+
return row;
|
|
249
|
+
}
|
|
250
|
+
/** Owner-native reads have their own admission, without a manufactured conversation or run. */
|
|
251
|
+
async admitBrowse(ctx, instance, method, input, signal) {
|
|
252
|
+
const scope = await this.authority.resolveBrowse(ctx, signal);
|
|
253
|
+
const described = describeOperationPayload(input);
|
|
254
|
+
const payload = payloadReference("input", described);
|
|
255
|
+
const vector = await this.epochs.readLocked({ orgId: ctx.orgId, deviceId: ctx.deviceId });
|
|
256
|
+
const row = await this.db
|
|
257
|
+
.insertInto("sandbox_operation_intents")
|
|
258
|
+
.values({
|
|
259
|
+
operation_id: scope.operationId,
|
|
260
|
+
org_id: ctx.orgId,
|
|
261
|
+
account_id: ctx.accountId,
|
|
262
|
+
device_id: ctx.deviceId,
|
|
263
|
+
root_conversation_id: null,
|
|
264
|
+
conversation_id: null,
|
|
265
|
+
run_id: null,
|
|
266
|
+
call_id: null,
|
|
267
|
+
ordinal: 0,
|
|
268
|
+
method,
|
|
269
|
+
input_hash: permissionScopeHash({ method, inputDigest: described.digest }),
|
|
270
|
+
admission_hash: permissionScopeHash({ method, inputDigest: described.digest, scope }),
|
|
271
|
+
input: payload,
|
|
272
|
+
scope: JSON.stringify(scope),
|
|
273
|
+
epochs: JSON.stringify(vector),
|
|
274
|
+
provider: instance.provider,
|
|
275
|
+
provider_version: instance.providerVersion,
|
|
276
|
+
instance_generation: instance.generation,
|
|
277
|
+
deadline: new Date(scope.admitBeforeMs),
|
|
278
|
+
retain_until: new Date(scope.admitBeforeMs + 86_400_000),
|
|
279
|
+
state: "admitted",
|
|
280
|
+
execution_id: scope.operationId,
|
|
281
|
+
})
|
|
282
|
+
.returningAll()
|
|
283
|
+
.executeTakeFirstOrThrow();
|
|
284
|
+
await this.outbox.add({
|
|
285
|
+
queue: "cap-kernel-maintenance",
|
|
286
|
+
name: OPERATION_RECONCILE,
|
|
287
|
+
jobId: `${OPERATION_RECONCILE}-${row.operation_id}`,
|
|
288
|
+
data: { operationId: row.operation_id },
|
|
289
|
+
orgId: ctx.orgId,
|
|
290
|
+
runAt: row.deadline,
|
|
291
|
+
});
|
|
292
|
+
await this.payloads.save(row.operation_id, "input", input, described);
|
|
293
|
+
await this.scheduleExpiry(row);
|
|
294
|
+
return row;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* The run start's kernel read (permission activation L2, Hook 1): the run must still be the
|
|
298
|
+
* claim's execution, triggered by the actor and `queued` (a run start reads before its run is
|
|
299
|
+
* running), checked in PG under the authority locks the caller already holds.
|
|
300
|
+
*/
|
|
301
|
+
async assertKernelReadRun(ctx, c) {
|
|
302
|
+
const run = await this.db
|
|
303
|
+
.selectFrom("runs")
|
|
304
|
+
.select(["execution_id", "trigger_account_id", "status"])
|
|
305
|
+
.where("id", "=", c.runId)
|
|
306
|
+
.where("conversation_id", "=", c.conversationId)
|
|
307
|
+
.forShare()
|
|
308
|
+
.executeTakeFirst();
|
|
309
|
+
if (!run ||
|
|
310
|
+
run.execution_id !== c.executionId ||
|
|
311
|
+
run.trigger_account_id !== ctx.actor.accountId ||
|
|
312
|
+
run.status !== "queued")
|
|
313
|
+
denied("The run start's execution claim is no longer current");
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Admits one kernel read (Hook 1), modelled on {@link admitBrowse}: a random operation id per
|
|
317
|
+
* read, so nothing is a consumed identity and a retried run start reads again; the run is
|
|
318
|
+
* recorded for audit (`run_id`, no `call_id`). The scope is the profile scope narrowed to the
|
|
319
|
+
* one path the read may reach (`SandboxOperationAuthority.resolveKernelRead`); the claim is
|
|
320
|
+
* re-checked under the admit lock ({@link assertKernelReadRun}). The read's `holderTag` is its
|
|
321
|
+
* lease token, so a dead holder's read is revoked with the holder.
|
|
322
|
+
*/
|
|
323
|
+
async admitKernelRead(ctx, read, instance, method, input, holderTag, signal) {
|
|
324
|
+
signal.throwIfAborted();
|
|
325
|
+
const c = read.claim;
|
|
326
|
+
if (c.orgId !== ctx.orgId ||
|
|
327
|
+
c.conversationId !== ctx.holderConversationId ||
|
|
328
|
+
c.runId !== ctx.actor.runId)
|
|
329
|
+
denied("The kernel read does not match its run start");
|
|
330
|
+
// resolve takes the authority locks of the root subject and holds them through the insert
|
|
331
|
+
const scope = await this.authority.resolveKernelRead(ctx, read, method, input.path, signal);
|
|
332
|
+
if (scope.rootConversationId !== c.rootId)
|
|
333
|
+
denied("The kernel read's root no longer matches the execution claim");
|
|
334
|
+
await this.assertKernelReadRun(ctx, c);
|
|
335
|
+
const described = describeOperationPayload(input);
|
|
336
|
+
const payload = payloadReference("input", described);
|
|
337
|
+
const vector = await this.epochs.readLocked({
|
|
338
|
+
orgId: ctx.orgId,
|
|
339
|
+
deviceId: ctx.deviceId,
|
|
340
|
+
rootConversationId: scope.rootConversationId,
|
|
341
|
+
});
|
|
342
|
+
const row = await this.db
|
|
343
|
+
.insertInto("sandbox_operation_intents")
|
|
344
|
+
.values({
|
|
345
|
+
operation_id: scope.operationId,
|
|
346
|
+
org_id: ctx.orgId,
|
|
347
|
+
account_id: ctx.actor.accountId,
|
|
348
|
+
device_id: ctx.deviceId,
|
|
349
|
+
root_conversation_id: scope.rootConversationId,
|
|
350
|
+
conversation_id: ctx.holderConversationId,
|
|
351
|
+
run_id: c.runId,
|
|
352
|
+
call_id: null,
|
|
353
|
+
ordinal: 0,
|
|
354
|
+
method,
|
|
355
|
+
input_hash: permissionScopeHash({ method, inputDigest: described.digest }),
|
|
356
|
+
admission_hash: permissionScopeHash({ method, inputDigest: described.digest, scope }),
|
|
357
|
+
input: payload,
|
|
358
|
+
scope: JSON.stringify(scope),
|
|
359
|
+
epochs: JSON.stringify(vector),
|
|
360
|
+
provider: instance.provider,
|
|
361
|
+
provider_version: instance.providerVersion,
|
|
362
|
+
instance_generation: instance.generation,
|
|
363
|
+
deadline: new Date(scope.admitBeforeMs),
|
|
364
|
+
retain_until: new Date(scope.admitBeforeMs + 86_400_000),
|
|
365
|
+
state: "admitted",
|
|
366
|
+
execution_id: c.executionId,
|
|
367
|
+
holder_token: holderTag,
|
|
368
|
+
})
|
|
369
|
+
.returningAll()
|
|
370
|
+
.executeTakeFirstOrThrow();
|
|
371
|
+
await this.outbox.add({
|
|
372
|
+
queue: "cap-kernel-maintenance",
|
|
373
|
+
name: OPERATION_RECONCILE,
|
|
374
|
+
jobId: `${OPERATION_RECONCILE}-${row.operation_id}`,
|
|
375
|
+
data: { operationId: row.operation_id },
|
|
376
|
+
orgId: ctx.orgId,
|
|
377
|
+
runAt: row.deadline,
|
|
378
|
+
});
|
|
379
|
+
await this.payloads.save(row.operation_id, "input", input, described);
|
|
380
|
+
await this.scheduleExpiry(row);
|
|
381
|
+
return row;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Claims an admitted kernel read for dispatch: under the admit lock, the run claim is checked
|
|
385
|
+
* again, the row must be this read's (same actor, conversation, run and execution, no tool
|
|
386
|
+
* call) and still admitted before its deadline, and the authority is resolved again: a scope
|
|
387
|
+
* that changed since admission refuses.
|
|
388
|
+
*/
|
|
389
|
+
async claimKernelRead(ctx, read, id, method, input) {
|
|
390
|
+
const initial = await this.read(id);
|
|
391
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
392
|
+
const c = read.claim;
|
|
393
|
+
await this.assertKernelReadRun(ctx, c);
|
|
394
|
+
const row = await this.db
|
|
395
|
+
.selectFrom("sandbox_operation_intents")
|
|
396
|
+
.selectAll()
|
|
397
|
+
.where("operation_id", "=", id)
|
|
398
|
+
.forUpdate()
|
|
399
|
+
.executeTakeFirstOrThrow();
|
|
400
|
+
if (row.org_id !== ctx.orgId ||
|
|
401
|
+
row.device_id !== ctx.deviceId ||
|
|
402
|
+
row.account_id !== ctx.actor.accountId ||
|
|
403
|
+
row.conversation_id !== ctx.holderConversationId ||
|
|
404
|
+
row.run_id !== c.runId ||
|
|
405
|
+
row.call_id !== null ||
|
|
406
|
+
row.execution_id !== c.executionId ||
|
|
407
|
+
row.method !== method ||
|
|
408
|
+
row.input_hash !==
|
|
409
|
+
permissionScopeHash({ method, inputDigest: describeOperationPayload(input).digest }))
|
|
410
|
+
denied("The kernel read admission does not match this read");
|
|
411
|
+
if (row.state !== "admitted" || row.deadline.getTime() <= Date.now())
|
|
412
|
+
denied("Kernel read admission was revoked or expired");
|
|
413
|
+
const fresh = await this.authority.resolveKernelRead(ctx, read, method, input.path, new AbortController().signal);
|
|
414
|
+
const admitted = parseSandboxOperationScope(row.scope);
|
|
415
|
+
if (permissionScopeHash(fresh.filesystem) !== permissionScopeHash(admitted.filesystem) ||
|
|
416
|
+
fresh.profileRevision !== admitted.profileRevision ||
|
|
417
|
+
fresh.ceilingRevision !== admitted.ceilingRevision)
|
|
418
|
+
denied("Authority changed before the kernel read was dispatched");
|
|
419
|
+
await this.db
|
|
420
|
+
.updateTable("sandbox_operation_intents")
|
|
421
|
+
.set({ state: "dispatching", updated_at: new Date() })
|
|
422
|
+
.where("operation_id", "=", id)
|
|
423
|
+
.execute();
|
|
424
|
+
return { ...row, state: "dispatching" };
|
|
425
|
+
}
|
|
426
|
+
async claimBrowse(ctx, id) {
|
|
427
|
+
await this.locks.acquire({ orgId: ctx.orgId, deviceId: ctx.deviceId }, { kind: "admit" });
|
|
428
|
+
const row = await this.db
|
|
429
|
+
.selectFrom("sandbox_operation_intents")
|
|
430
|
+
.selectAll()
|
|
431
|
+
.where("operation_id", "=", id)
|
|
432
|
+
.forUpdate()
|
|
433
|
+
.executeTakeFirstOrThrow();
|
|
434
|
+
if (row.org_id !== ctx.orgId ||
|
|
435
|
+
row.device_id !== ctx.deviceId ||
|
|
436
|
+
row.account_id !== ctx.accountId ||
|
|
437
|
+
row.run_id !== null)
|
|
438
|
+
denied("The browse admission does not match this owner");
|
|
439
|
+
if (row.state !== "admitted" || row.deadline.getTime() <= Date.now())
|
|
440
|
+
denied("Browse admission was revoked or expired");
|
|
441
|
+
await this.authority.resolveBrowse(ctx, new AbortController().signal);
|
|
442
|
+
await this.db
|
|
443
|
+
.updateTable("sandbox_operation_intents")
|
|
444
|
+
.set({ state: "dispatching", updated_at: new Date() })
|
|
445
|
+
.where("operation_id", "=", id)
|
|
446
|
+
.execute();
|
|
447
|
+
return { ...row, state: "dispatching" };
|
|
448
|
+
}
|
|
449
|
+
assertIdentity(r, ctx, instance, method, hash) {
|
|
450
|
+
if (r.org_id !== ctx.orgId ||
|
|
451
|
+
r.account_id !== ctx.actor.accountId ||
|
|
452
|
+
r.device_id !== ctx.deviceId ||
|
|
453
|
+
r.conversation_id !== ctx.holderConversationId ||
|
|
454
|
+
r.method !== method ||
|
|
455
|
+
r.input_hash !== hash)
|
|
456
|
+
denied("Stable operation identity was reused with different input");
|
|
457
|
+
if (r.provider !== instance.provider ||
|
|
458
|
+
r.provider_version !== instance.providerVersion ||
|
|
459
|
+
r.instance_generation !== instance.generation)
|
|
460
|
+
throw new SandboxOperationOutcomeUnknownError("The recorded operation belongs to another instance; do not repeat it");
|
|
461
|
+
}
|
|
462
|
+
async read(id) {
|
|
463
|
+
return this.db
|
|
464
|
+
.selectFrom("sandbox_operation_intents")
|
|
465
|
+
.selectAll()
|
|
466
|
+
.where("operation_id", "=", id)
|
|
467
|
+
.executeTakeFirstOrThrow();
|
|
468
|
+
}
|
|
469
|
+
async admit(ctx, invocation) {
|
|
470
|
+
const id = operationIdFor(invocation), initial = await this.read(id);
|
|
471
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
472
|
+
await this.assertClaim(ctx, invocation);
|
|
473
|
+
const r = await this.db
|
|
474
|
+
.selectFrom("sandbox_operation_intents")
|
|
475
|
+
.selectAll()
|
|
476
|
+
.where("operation_id", "=", id)
|
|
477
|
+
.forUpdate()
|
|
478
|
+
.executeTakeFirstOrThrow();
|
|
479
|
+
if (r.state === "revoked") {
|
|
480
|
+
if (r.outcome_unknown)
|
|
481
|
+
throw new SandboxOperationOutcomeUnknownError("Operation authority was revoked after dispatch; its outcome remains unknown");
|
|
482
|
+
denied("Operation authority was revoked");
|
|
483
|
+
}
|
|
484
|
+
if (r.state !== "pending")
|
|
485
|
+
return r;
|
|
486
|
+
if (r.deadline.getTime() <= Date.now())
|
|
487
|
+
denied("Operation admission deadline elapsed");
|
|
488
|
+
const current = await this.epochs.readLocked(subjectOf(r));
|
|
489
|
+
if (permissionScopeHash(current) !== permissionScopeHash(r.epochs))
|
|
490
|
+
throw new PermissionAdmissionStale("Authority changed before admission; refresh this pending method only");
|
|
491
|
+
if (r.deadline.getTime() <= Date.now())
|
|
492
|
+
denied("Operation admission deadline elapsed");
|
|
493
|
+
// Re-read live access/project/tool state, not only the profile epoch.
|
|
494
|
+
const { scope: fresh, permissionGrantId, grantedHosts, executionGrants, } = await this.authority.resolveInvocation(ctx, r.method, { runId: invocation.claim.runId, callId: invocation.callId }, new AbortController().signal);
|
|
495
|
+
if (permissionGrantId !== r.permission_grant_id ||
|
|
496
|
+
permissionScopeHash(executionGrants) !== permissionScopeHash(r.execution_grants) ||
|
|
497
|
+
permissionScopeHash(grantedHosts) !== permissionScopeHash(r.granted_hosts) ||
|
|
498
|
+
permissionScopeHash(fresh.filesystem) !==
|
|
499
|
+
permissionScopeHash(parseSandboxOperationScope(r.scope).filesystem) ||
|
|
500
|
+
permissionScopeHash(fresh.network) !==
|
|
501
|
+
permissionScopeHash(parseSandboxOperationScope(r.scope).network) ||
|
|
502
|
+
fresh.ceilingRevision !== r.scope.ceilingRevision ||
|
|
503
|
+
fresh.profileRevision !== parseSandboxOperationScope(r.scope).profileRevision)
|
|
504
|
+
throw new PermissionAdmissionStale("Authority changed before admission; refresh this pending method only");
|
|
505
|
+
await this.db
|
|
506
|
+
.updateTable("sandbox_operation_intents")
|
|
507
|
+
.set({ state: "admitted", updated_at: new Date() })
|
|
508
|
+
.where("operation_id", "=", id)
|
|
509
|
+
.execute();
|
|
510
|
+
await this.outbox.add({
|
|
511
|
+
queue: "cap-kernel-maintenance",
|
|
512
|
+
name: OPERATION_RECONCILE,
|
|
513
|
+
jobId: `${OPERATION_RECONCILE}-${id}`,
|
|
514
|
+
data: { operationId: id },
|
|
515
|
+
orgId: r.org_id,
|
|
516
|
+
runAt: r.deadline,
|
|
517
|
+
});
|
|
518
|
+
return { ...r, state: "admitted" };
|
|
519
|
+
}
|
|
520
|
+
async claimDispatch(ctx, invocation, holderTag, background) {
|
|
521
|
+
const id = operationIdFor(invocation), initial = await this.read(id);
|
|
522
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
523
|
+
await this.assertClaim(ctx, invocation);
|
|
524
|
+
const r = await this.db
|
|
525
|
+
.selectFrom("sandbox_operation_intents")
|
|
526
|
+
.selectAll()
|
|
527
|
+
.where("operation_id", "=", id)
|
|
528
|
+
.forUpdate()
|
|
529
|
+
.executeTakeFirstOrThrow();
|
|
530
|
+
if (r.state === "completed" || r.state === "background-running")
|
|
531
|
+
return r;
|
|
532
|
+
if (r.state === "revoked") {
|
|
533
|
+
if (r.outcome_unknown)
|
|
534
|
+
throw new SandboxOperationOutcomeUnknownError("Operation authority was revoked after dispatch; its outcome remains unknown");
|
|
535
|
+
denied("Operation authority was revoked");
|
|
536
|
+
}
|
|
537
|
+
// Reconciliation on another current execution may only ask the provider about the SAME ID.
|
|
538
|
+
if (r.state !== "admitted")
|
|
539
|
+
throw new SandboxOperationOutcomeUnknownError("Operation already dispatched; reconcile its recorded identity before continuing");
|
|
540
|
+
if (r.deadline.getTime() <= Date.now())
|
|
541
|
+
denied("Operation admission deadline elapsed");
|
|
542
|
+
if (r.method === "backgroundStart" || background) {
|
|
543
|
+
if (r.method !== "backgroundStart" || !background)
|
|
544
|
+
return denied("A background start needs its exact task reservation");
|
|
545
|
+
if (!(await this.bindBackgroundDispatch(r, invocation, background))) {
|
|
546
|
+
// Pre-effect: the reservation was stopped or settled first. Nothing was dispatched.
|
|
547
|
+
await this.db
|
|
548
|
+
.updateTable("sandbox_operation_intents")
|
|
549
|
+
.set({ state: "revoked", outcome_unknown: false, updated_at: new Date() })
|
|
550
|
+
.where("operation_id", "=", id)
|
|
551
|
+
.execute();
|
|
552
|
+
return { ...r, state: "revoked", outcome_unknown: false };
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
await this.db
|
|
556
|
+
.updateTable("sandbox_operation_intents")
|
|
557
|
+
.set({
|
|
558
|
+
state: "dispatching",
|
|
559
|
+
execution_id: invocation.claim.executionId,
|
|
560
|
+
holder_token: holderTag,
|
|
561
|
+
updated_at: new Date(),
|
|
562
|
+
})
|
|
563
|
+
.where("operation_id", "=", id)
|
|
564
|
+
.execute();
|
|
565
|
+
return {
|
|
566
|
+
...r,
|
|
567
|
+
state: "dispatching",
|
|
568
|
+
execution_id: invocation.claim.executionId,
|
|
569
|
+
holder_token: holderTag,
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Binds a managed task's reservation to its admitted start in the dispatch transaction: the
|
|
574
|
+
* operation, per-method input hash, run claim, task-owned tag, exact instance and generation,
|
|
575
|
+
* starting profile/ceiling revisions, grant locator and network authority. Conditional on the
|
|
576
|
+
* reservation still being `pending`, running and not claimed by a stop, and on the persisted
|
|
577
|
+
* working root, artifact and retention matching the start input. False: nothing dispatches; a
|
|
578
|
+
* stop's claim settles the reservation as `stopped`.
|
|
579
|
+
*/
|
|
580
|
+
async bindBackgroundDispatch(r, invocation, b) {
|
|
581
|
+
const scope = parseSandboxOperationScope(r.scope);
|
|
582
|
+
const bound = await this.db
|
|
583
|
+
.updateTable("background_tasks")
|
|
584
|
+
.set({
|
|
585
|
+
launch_state: "dispatched",
|
|
586
|
+
input_digest: r.input_hash,
|
|
587
|
+
run_execution_id: invocation.claim.executionId,
|
|
588
|
+
task_tag: scope.tag,
|
|
589
|
+
instance_id: b.instanceId,
|
|
590
|
+
instance_provider: r.provider,
|
|
591
|
+
instance_provider_version: r.provider_version,
|
|
592
|
+
instance_generation: r.instance_generation,
|
|
593
|
+
profile_revision: scope.profileRevision,
|
|
594
|
+
ceiling_revision: scope.ceilingRevision,
|
|
595
|
+
permission_grant_id: r.permission_grant_id,
|
|
596
|
+
network_authority: r.execution_grants === null ? null : JSON.stringify(r.execution_grants),
|
|
597
|
+
})
|
|
598
|
+
.where("id", "=", b.taskId)
|
|
599
|
+
.where("operation_id", "=", r.operation_id)
|
|
600
|
+
.where("org_id", "=", r.org_id)
|
|
601
|
+
.where("device_id", "=", r.device_id)
|
|
602
|
+
.where("run_id", "=", invocation.claim.runId)
|
|
603
|
+
.where("call_id", "=", invocation.callId)
|
|
604
|
+
.where("launch_state", "=", "pending")
|
|
605
|
+
.where("status", "=", "running")
|
|
606
|
+
.where("working_root", "=", b.workingRoot)
|
|
607
|
+
.where("output_path", "=", b.outputPath)
|
|
608
|
+
.where("retain_until", "=", new Date(b.retainUntilMs))
|
|
609
|
+
.where(sql `NOT ${stopRequested}`)
|
|
610
|
+
.executeTakeFirst();
|
|
611
|
+
if (Number(bound.numUpdatedRows) > 0)
|
|
612
|
+
return true;
|
|
613
|
+
await this.db
|
|
614
|
+
.updateTable("background_tasks")
|
|
615
|
+
.set({
|
|
616
|
+
status: "stopped",
|
|
617
|
+
launch_state: "terminal",
|
|
618
|
+
finished_at: new Date(),
|
|
619
|
+
stopping_at: null,
|
|
620
|
+
})
|
|
621
|
+
.where("id", "=", b.taskId)
|
|
622
|
+
.where("operation_id", "=", r.operation_id)
|
|
623
|
+
.where("launch_state", "=", "pending")
|
|
624
|
+
.where("status", "=", "running")
|
|
625
|
+
.where(stopRequested)
|
|
626
|
+
.execute();
|
|
627
|
+
return false;
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Records a typed start result. A current dispatch (the same execution claim, or a recovery
|
|
631
|
+
* claim) moves the intent to `background-running` and the task to `acknowledged` together; the
|
|
632
|
+
* intent stays live revocable authority and is never completed like a foreground call. When a
|
|
633
|
+
* writer revoked the intent first, or a stop claimed the task, the ref is attached to the
|
|
634
|
+
* already owed cancellation (`cancel-pending`) and the exact revoke is enqueued; the revoked
|
|
635
|
+
* intent is never resurrected. The launching run need not still be running.
|
|
636
|
+
*/
|
|
637
|
+
async acknowledgeBackground(id, executionId, result, instanceId) {
|
|
638
|
+
const initial = await this.read(id);
|
|
639
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
640
|
+
const r = await this.db
|
|
641
|
+
.selectFrom("sandbox_operation_intents")
|
|
642
|
+
.selectAll()
|
|
643
|
+
.where("operation_id", "=", id)
|
|
644
|
+
.forUpdate()
|
|
645
|
+
.executeTakeFirstOrThrow();
|
|
646
|
+
const ref = parseSandboxExecutionRef(result);
|
|
647
|
+
if (r.method !== "backgroundStart" ||
|
|
648
|
+
ref.operationId !== r.operation_id ||
|
|
649
|
+
ref.instanceGeneration !== r.instance_generation ||
|
|
650
|
+
ref.instanceId !== instanceId)
|
|
651
|
+
throw new SandboxOperationOutcomeUnknownError("The start result does not name this operation's exact instance; reconcile the same identity");
|
|
652
|
+
if (r.execution_ref && permissionScopeHash(r.execution_ref) !== permissionScopeHash(ref))
|
|
653
|
+
throw new SandboxOperationOutcomeUnknownError("The start result conflicts with the recorded execution; reconcile the same identity");
|
|
654
|
+
const task = await this.db
|
|
655
|
+
.selectFrom("background_tasks")
|
|
656
|
+
.selectAll()
|
|
657
|
+
.where("operation_id", "=", id)
|
|
658
|
+
.forUpdate()
|
|
659
|
+
.executeTakeFirst();
|
|
660
|
+
if (!task || task.instance_id !== instanceId)
|
|
661
|
+
throw new SandboxOperationOutcomeUnknownError("The start result has no matching task reservation; reconcile the same identity");
|
|
662
|
+
const refJson = JSON.stringify(ref);
|
|
663
|
+
if (r.state === "background-running") {
|
|
664
|
+
if (task.launch_state !== "acknowledged")
|
|
665
|
+
throw new SandboxOperationOutcomeUnknownError("The task record diverged from its start");
|
|
666
|
+
return "acknowledged";
|
|
667
|
+
}
|
|
668
|
+
const live = ["dispatching", "started-or-unknown"].includes(r.state) && r.execution_id === executionId;
|
|
669
|
+
if (!live && r.state !== "revoked")
|
|
670
|
+
throw new SandboxOperationOutcomeUnknownError("The start is not held by this dispatch; reconcile the same identity");
|
|
671
|
+
const stopped = task.status !== "running" || task.launch_state !== "dispatched" || stopRequestedOf(task);
|
|
672
|
+
if (live && !stopped) {
|
|
673
|
+
await this.db
|
|
674
|
+
.updateTable("sandbox_operation_intents")
|
|
675
|
+
.set({
|
|
676
|
+
state: "background-running",
|
|
677
|
+
execution_ref: refJson,
|
|
678
|
+
outcome_unknown: false,
|
|
679
|
+
updated_at: new Date(),
|
|
680
|
+
})
|
|
681
|
+
.where("operation_id", "=", id)
|
|
682
|
+
.execute();
|
|
683
|
+
await this.db
|
|
684
|
+
.updateTable("background_tasks")
|
|
685
|
+
.set({
|
|
686
|
+
launch_state: "acknowledged",
|
|
687
|
+
execution_ref: refJson,
|
|
688
|
+
sandbox_created_at: new Date(Number(r.instance_generation)),
|
|
689
|
+
})
|
|
690
|
+
.where("id", "=", task.id)
|
|
691
|
+
.execute();
|
|
692
|
+
return "acknowledged";
|
|
693
|
+
}
|
|
694
|
+
// Revoked by a writer, or stopped by a person or tool: the cancellation is owed for this ref.
|
|
695
|
+
// A newly attached ref owes its own exact revoke, even if an earlier one was acknowledged.
|
|
696
|
+
await this.db
|
|
697
|
+
.updateTable("sandbox_operation_intents")
|
|
698
|
+
.set({
|
|
699
|
+
state: "revoked",
|
|
700
|
+
execution_ref: refJson,
|
|
701
|
+
revoke_acknowledged: false,
|
|
702
|
+
updated_at: new Date(),
|
|
703
|
+
})
|
|
704
|
+
.where("operation_id", "=", id)
|
|
705
|
+
.execute();
|
|
706
|
+
await this.db
|
|
707
|
+
.updateTable("background_tasks")
|
|
708
|
+
.set({
|
|
709
|
+
launch_state: "cancel-pending",
|
|
710
|
+
execution_ref: refJson,
|
|
711
|
+
sandbox_created_at: new Date(Number(r.instance_generation)),
|
|
712
|
+
cancel_requested_at: sql `COALESCE(cancel_requested_at, now())`,
|
|
713
|
+
// the stop's claim has done its work: the poller owes the exact stop of this ref now
|
|
714
|
+
stopping_at: null,
|
|
715
|
+
})
|
|
716
|
+
.where("id", "=", task.id)
|
|
717
|
+
.where("launch_state", "in", ["dispatched", "cancel-pending"])
|
|
718
|
+
.execute();
|
|
719
|
+
await this.outbox.add({
|
|
720
|
+
queue: "cap-kernel-maintenance",
|
|
721
|
+
name: OPERATION_REVOKE,
|
|
722
|
+
jobId: `${OPERATION_REVOKE}-${id}-ack`,
|
|
723
|
+
data: { operationId: id },
|
|
724
|
+
orgId: r.org_id,
|
|
725
|
+
});
|
|
726
|
+
return "cancel-pending";
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* A task-specific recovery claim for a start whose acknowledgement was lost: a new durable
|
|
730
|
+
* execution identity (never a borrowed run or holder token) that may only ask the provider about
|
|
731
|
+
* the same operation and input. Only a start its dispatcher itself left `started-or-unknown` is
|
|
732
|
+
* taken over; a `dispatching` one still has a live (or not yet proven dead) holder. A task a stop
|
|
733
|
+
* claimed, or that is no longer a running dispatched task, is never started: the intent is
|
|
734
|
+
* revoked and the exact revoke (the operation tombstone) owed instead. Null: nothing to start.
|
|
735
|
+
*/
|
|
736
|
+
async claimBackgroundRecovery(id) {
|
|
737
|
+
const initial = await this.read(id);
|
|
738
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
739
|
+
const r = await this.db
|
|
740
|
+
.selectFrom("sandbox_operation_intents")
|
|
741
|
+
.selectAll()
|
|
742
|
+
.where("operation_id", "=", id)
|
|
743
|
+
.forUpdate()
|
|
744
|
+
.executeTakeFirstOrThrow();
|
|
745
|
+
if (r.method !== "backgroundStart" ||
|
|
746
|
+
r.state !== "started-or-unknown" ||
|
|
747
|
+
r.retain_until.getTime() <= Date.now())
|
|
748
|
+
return null;
|
|
749
|
+
const task = await this.db
|
|
750
|
+
.selectFrom("background_tasks")
|
|
751
|
+
.selectAll()
|
|
752
|
+
.where("operation_id", "=", id)
|
|
753
|
+
.forUpdate()
|
|
754
|
+
.executeTakeFirst();
|
|
755
|
+
if (!task) {
|
|
756
|
+
await this.revokeUnknownLocked(r, "recover");
|
|
757
|
+
return null;
|
|
758
|
+
}
|
|
759
|
+
if (!(await this.dispatchStillWanted(r, task, "recover")))
|
|
760
|
+
return null;
|
|
761
|
+
const executionId = `recovery-${randomUUID()}`;
|
|
762
|
+
await this.db
|
|
763
|
+
.updateTable("sandbox_operation_intents")
|
|
764
|
+
.set({ execution_id: executionId, outcome_unknown: true, updated_at: new Date() })
|
|
765
|
+
.where("operation_id", "=", id)
|
|
766
|
+
.execute();
|
|
767
|
+
return { ...r, execution_id: executionId, outcome_unknown: true };
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Whether a possibly dispatched start (its task row locked by the caller) may still be sent to
|
|
771
|
+
* the provider: its task still runs `dispatched` and no stop asked for it. Otherwise nothing is
|
|
772
|
+
* started: the intent is revoked with an unknown outcome, the exact revoke (the operation
|
|
773
|
+
* tombstone) owed, and a running dispatched task becomes `cancel-pending`.
|
|
774
|
+
*/
|
|
775
|
+
async dispatchStillWanted(r, task, why) {
|
|
776
|
+
const live = task.status === "running" && task.launch_state === "dispatched";
|
|
777
|
+
if (live && !stopRequestedOf(task))
|
|
778
|
+
return true;
|
|
779
|
+
await this.revokeUnknownLocked(r, why);
|
|
780
|
+
if (live)
|
|
781
|
+
await this.db
|
|
782
|
+
.updateTable("background_tasks")
|
|
783
|
+
.set({
|
|
784
|
+
launch_state: "cancel-pending",
|
|
785
|
+
cancel_requested_at: sql `COALESCE(cancel_requested_at, now())`,
|
|
786
|
+
})
|
|
787
|
+
.where("id", "=", task.id)
|
|
788
|
+
.execute();
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
/** Revokes a possibly dispatched start; its outcome stays unknown and the exact revoke owed. */
|
|
792
|
+
async revokeUnknownLocked(r, why) {
|
|
793
|
+
await this.db
|
|
794
|
+
.updateTable("sandbox_operation_intents")
|
|
795
|
+
.set({
|
|
796
|
+
state: "revoked",
|
|
797
|
+
outcome_unknown: true,
|
|
798
|
+
revoke_acknowledged: false,
|
|
799
|
+
updated_at: new Date(),
|
|
800
|
+
})
|
|
801
|
+
.where("operation_id", "=", r.operation_id)
|
|
802
|
+
.execute();
|
|
803
|
+
await this.outbox.add({
|
|
804
|
+
queue: "cap-kernel-maintenance",
|
|
805
|
+
name: OPERATION_REVOKE,
|
|
806
|
+
jobId: `${OPERATION_REVOKE}-${r.operation_id}-${why}`,
|
|
807
|
+
data: { operationId: r.operation_id },
|
|
808
|
+
orgId: r.org_id,
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* The kernel refused a start before dispatching it (the artifact or runtime checks on the
|
|
813
|
+
* admitted scope): recorded as a pre-effect failure, the reservation settled `failed`. Only an
|
|
814
|
+
* `admitted` intent of the current claim; anything else is left as it is.
|
|
815
|
+
*/
|
|
816
|
+
async refusePreDispatch(ctx, invocation, failure) {
|
|
817
|
+
const id = operationIdFor(invocation), initial = await this.read(id);
|
|
818
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
819
|
+
await this.assertClaim(ctx, invocation);
|
|
820
|
+
const r = await this.db
|
|
821
|
+
.selectFrom("sandbox_operation_intents")
|
|
822
|
+
.selectAll()
|
|
823
|
+
.where("operation_id", "=", id)
|
|
824
|
+
.forUpdate()
|
|
825
|
+
.executeTakeFirstOrThrow();
|
|
826
|
+
if (r.state !== "admitted")
|
|
827
|
+
return;
|
|
828
|
+
await this.settleFailureLocked(r, failure, "pending");
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* The provider refused a recovered start with a typed pre-effect error for this exact operation
|
|
832
|
+
* (it owns the identity, so a launched operation would have returned its ref): a failure.
|
|
833
|
+
*/
|
|
834
|
+
async settleBackgroundRefusal(id, executionId, failure) {
|
|
835
|
+
const initial = await this.read(id);
|
|
836
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
837
|
+
const r = await this.db
|
|
838
|
+
.selectFrom("sandbox_operation_intents")
|
|
839
|
+
.selectAll()
|
|
840
|
+
.where("operation_id", "=", id)
|
|
841
|
+
.where("execution_id", "=", executionId)
|
|
842
|
+
.where("state", "=", "started-or-unknown")
|
|
843
|
+
.forUpdate()
|
|
844
|
+
.executeTakeFirst();
|
|
845
|
+
if (r)
|
|
846
|
+
await this.settleFailureLocked(r, failure, "dispatched");
|
|
847
|
+
}
|
|
848
|
+
async settleFailureLocked(r, failure, from) {
|
|
849
|
+
const payload = await this.payloads.save(r.operation_id, "result", { $failure: failure });
|
|
850
|
+
await this.db
|
|
851
|
+
.updateTable("sandbox_operation_intents")
|
|
852
|
+
.set({ state: "completed", result: payload, outcome_unknown: false, updated_at: new Date() })
|
|
853
|
+
.where("operation_id", "=", r.operation_id)
|
|
854
|
+
.execute();
|
|
855
|
+
await this.db
|
|
856
|
+
.updateTable("background_tasks")
|
|
857
|
+
.set({
|
|
858
|
+
status: "failed",
|
|
859
|
+
launch_state: "terminal",
|
|
860
|
+
finished_at: new Date(),
|
|
861
|
+
lost_reason: `launch refused: ${launchRefusedText(failure.kind)}`,
|
|
862
|
+
stopping_at: null,
|
|
863
|
+
})
|
|
864
|
+
.where("operation_id", "=", r.operation_id)
|
|
865
|
+
.where("launch_state", "=", from)
|
|
866
|
+
.where("status", "=", "running")
|
|
867
|
+
.execute();
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Gives up on an unknown start (its retention ended, or the kernel would not send it again): the
|
|
871
|
+
* task becomes terminal `lost` (`launch_unknown`), freeing its slot of `maxTasks`, while the
|
|
872
|
+
* intent is revoked with an unknown outcome so the exact revoke (the operation tombstone) stays
|
|
873
|
+
* owed. A reservation that never dispatched settles as a pre-effect failure instead.
|
|
874
|
+
*/
|
|
875
|
+
async abandonBackgroundLaunch(id, why) {
|
|
876
|
+
const initial = await this.read(id);
|
|
877
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
878
|
+
const r = await this.db
|
|
879
|
+
.selectFrom("sandbox_operation_intents")
|
|
880
|
+
.selectAll()
|
|
881
|
+
.where("operation_id", "=", id)
|
|
882
|
+
.forUpdate()
|
|
883
|
+
.executeTakeFirstOrThrow();
|
|
884
|
+
if (r.method !== "backgroundStart")
|
|
885
|
+
return;
|
|
886
|
+
const task = await this.db
|
|
887
|
+
.selectFrom("background_tasks")
|
|
888
|
+
.selectAll()
|
|
889
|
+
.where("operation_id", "=", id)
|
|
890
|
+
.forUpdate()
|
|
891
|
+
.executeTakeFirst();
|
|
892
|
+
if (r.state === "pending" || r.state === "admitted") {
|
|
893
|
+
await this.db
|
|
894
|
+
.updateTable("sandbox_operation_intents")
|
|
895
|
+
.set({ state: "revoked", outcome_unknown: false, updated_at: new Date() })
|
|
896
|
+
.where("operation_id", "=", id)
|
|
897
|
+
.execute();
|
|
898
|
+
if (task?.launch_state === "pending")
|
|
899
|
+
await this.db
|
|
900
|
+
.updateTable("background_tasks")
|
|
901
|
+
.set({
|
|
902
|
+
status: "failed",
|
|
903
|
+
launch_state: "terminal",
|
|
904
|
+
finished_at: new Date(),
|
|
905
|
+
lost_reason: "launch_abandoned",
|
|
906
|
+
stopping_at: null,
|
|
907
|
+
})
|
|
908
|
+
.where("id", "=", task.id)
|
|
909
|
+
.where("status", "=", "running")
|
|
910
|
+
.execute();
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
if (r.state === "dispatching" || r.state === "started-or-unknown")
|
|
914
|
+
await this.revokeUnknownLocked(r, why);
|
|
915
|
+
else if (r.state === "revoked" && !r.revoke_acknowledged)
|
|
916
|
+
await this.outbox.add({
|
|
917
|
+
queue: "cap-kernel-maintenance",
|
|
918
|
+
name: OPERATION_REVOKE,
|
|
919
|
+
jobId: `${OPERATION_REVOKE}-${id}-${why}`,
|
|
920
|
+
data: { operationId: id },
|
|
921
|
+
orgId: r.org_id,
|
|
922
|
+
});
|
|
923
|
+
// only a task without an exact ref: an acknowledged one is settled by its consumers
|
|
924
|
+
if (task &&
|
|
925
|
+
task.status === "running" &&
|
|
926
|
+
task.execution_ref === null &&
|
|
927
|
+
(task.launch_state === "dispatched" || task.launch_state === "cancel-pending"))
|
|
928
|
+
await this.db
|
|
929
|
+
.updateTable("background_tasks")
|
|
930
|
+
.set({
|
|
931
|
+
status: "lost",
|
|
932
|
+
launch_state: "terminal",
|
|
933
|
+
finished_at: new Date(),
|
|
934
|
+
lost_reason: "launch_unknown",
|
|
935
|
+
stopping_at: null,
|
|
936
|
+
})
|
|
937
|
+
.where("id", "=", task.id)
|
|
938
|
+
.execute();
|
|
939
|
+
}
|
|
940
|
+
/** The recorded input of an operation (for a same-identity retry only). */
|
|
941
|
+
async input(row) {
|
|
942
|
+
return hydrateOperationBytes(await this.payloads.load(row.operation_id, "input", row.input));
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* A deferred recovery check: a new deterministic persisted attempt with exponential backoff
|
|
946
|
+
* (30 s doubling, at most an hour), while the start is still unresolved and retained. The
|
|
947
|
+
* retention expiry job settles what is never resolved.
|
|
948
|
+
*/
|
|
949
|
+
async deferBackgroundRecovery(id) {
|
|
950
|
+
const row = await this.db
|
|
951
|
+
.updateTable("sandbox_operation_intents")
|
|
952
|
+
.set((eb) => ({ reconcile_attempt: eb("reconcile_attempt", "+", 1), updated_at: new Date() }))
|
|
953
|
+
.where("operation_id", "=", id)
|
|
954
|
+
.where("method", "=", "backgroundStart")
|
|
955
|
+
.where("state", "in", ["dispatching", "started-or-unknown"])
|
|
956
|
+
.where("retain_until", ">", new Date())
|
|
957
|
+
.returning(["org_id", "reconcile_attempt", "retain_until"])
|
|
958
|
+
.executeTakeFirst();
|
|
959
|
+
if (!row)
|
|
960
|
+
return;
|
|
961
|
+
const delay = Math.min(30_000 * 2 ** Math.min(row.reconcile_attempt - 1, 20), 3_600_000);
|
|
962
|
+
const runAt = new Date(Math.min(Date.now() + delay, row.retain_until.getTime()));
|
|
963
|
+
await this.outbox.add({
|
|
964
|
+
queue: "cap-kernel-maintenance",
|
|
965
|
+
name: OPERATION_RECONCILE,
|
|
966
|
+
jobId: `${OPERATION_RECONCILE}-${id}-recover-${row.reconcile_attempt}`,
|
|
967
|
+
data: { operationId: id },
|
|
968
|
+
orgId: row.org_id,
|
|
969
|
+
runAt,
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
async complete(id, executionId, result) {
|
|
973
|
+
const initial = await this.read(id);
|
|
974
|
+
if (initial.run_id !== null) {
|
|
975
|
+
// a kernel read (no tool call) serves a run start, which reads while its run is queued
|
|
976
|
+
const run = await this.db
|
|
977
|
+
.selectFrom("runs")
|
|
978
|
+
.select("id")
|
|
979
|
+
.where("id", "=", initial.run_id)
|
|
980
|
+
.where("execution_id", "=", executionId)
|
|
981
|
+
.where("status", "=", initial.call_id === null ? "queued" : "running")
|
|
982
|
+
.forShare()
|
|
983
|
+
.executeTakeFirst();
|
|
984
|
+
if (!run)
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
const row = await this.db
|
|
988
|
+
.selectFrom("sandbox_operation_intents")
|
|
989
|
+
.selectAll()
|
|
990
|
+
.where("operation_id", "=", id)
|
|
991
|
+
.where("execution_id", "=", executionId)
|
|
992
|
+
.where("state", "in", ["dispatching", "started-or-unknown"])
|
|
993
|
+
.forUpdate()
|
|
994
|
+
.executeTakeFirst();
|
|
995
|
+
if (!row)
|
|
996
|
+
return;
|
|
997
|
+
const failure = result && typeof result === "object" && "$failure" in result
|
|
998
|
+
? result.$failure
|
|
999
|
+
: null;
|
|
1000
|
+
if (row.method === "backgroundStart") {
|
|
1001
|
+
// A start's success is acknowledged as live authority, never completed like foreground.
|
|
1002
|
+
if (!failure)
|
|
1003
|
+
throw new Error("A background start result must be acknowledged");
|
|
1004
|
+
await this.db
|
|
1005
|
+
.updateTable("background_tasks")
|
|
1006
|
+
.set({
|
|
1007
|
+
status: "failed",
|
|
1008
|
+
launch_state: "terminal",
|
|
1009
|
+
finished_at: new Date(),
|
|
1010
|
+
lost_reason: `launch refused: ${launchRefusedText(failure.kind)}`,
|
|
1011
|
+
stopping_at: null,
|
|
1012
|
+
})
|
|
1013
|
+
.where("operation_id", "=", id)
|
|
1014
|
+
.where("launch_state", "=", "dispatched")
|
|
1015
|
+
.where("status", "=", "running")
|
|
1016
|
+
.execute();
|
|
1017
|
+
}
|
|
1018
|
+
const payload = row.retain_until.getTime() <= Date.now()
|
|
1019
|
+
? JSON.stringify({ $expired: true })
|
|
1020
|
+
: await this.payloads.save(id, "result", result);
|
|
1021
|
+
await this.db
|
|
1022
|
+
.updateTable("sandbox_operation_intents")
|
|
1023
|
+
.set({ state: "completed", result: payload, outcome_unknown: false, updated_at: new Date() })
|
|
1024
|
+
.where("operation_id", "=", id)
|
|
1025
|
+
.execute();
|
|
1026
|
+
}
|
|
1027
|
+
async result(row) {
|
|
1028
|
+
return operationResult(await this.payloads.load(row.operation_id, "result", row.result));
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* The dispatcher with `executionId` gave up on its dispatch: its outcome is unknown. Fenced by
|
|
1032
|
+
* the execution, so a superseded dispatcher never clears a newer retry's `dispatching` marker
|
|
1033
|
+
* (without `executionId`: the orphan cleanup of the reconcile job).
|
|
1034
|
+
*/
|
|
1035
|
+
async unknown(id, executionId) {
|
|
1036
|
+
let q = this.db
|
|
1037
|
+
.updateTable("sandbox_operation_intents")
|
|
1038
|
+
.set({ state: "started-or-unknown", outcome_unknown: true, updated_at: new Date() })
|
|
1039
|
+
.where("operation_id", "=", id)
|
|
1040
|
+
.where("state", "=", "dispatching");
|
|
1041
|
+
if (executionId !== undefined)
|
|
1042
|
+
q = q.where("execution_id", "=", executionId);
|
|
1043
|
+
await q.execute();
|
|
1044
|
+
}
|
|
1045
|
+
/** Recovery never borrows a holder token. Only a new live run claim can reconcile by ID. */
|
|
1046
|
+
async claimReconciliation(ctx, invocation, instance, method, input, holderTag) {
|
|
1047
|
+
const id = operationIdFor(invocation), initial = await this.read(id);
|
|
1048
|
+
await this.locks.acquire(subjectOf(initial), { kind: "admit" });
|
|
1049
|
+
await this.assertClaim(ctx, invocation);
|
|
1050
|
+
const r = await this.db
|
|
1051
|
+
.selectFrom("sandbox_operation_intents")
|
|
1052
|
+
.selectAll()
|
|
1053
|
+
.where("operation_id", "=", id)
|
|
1054
|
+
.forUpdate()
|
|
1055
|
+
.executeTakeFirstOrThrow();
|
|
1056
|
+
this.assertIdentity(r, ctx, instance, method, permissionScopeHash({ method, inputDigest: describeOperationPayload(input).digest }));
|
|
1057
|
+
if (r.state === "completed" || r.state === "background-running")
|
|
1058
|
+
return r;
|
|
1059
|
+
if (r.state === "revoked") {
|
|
1060
|
+
if (r.outcome_unknown)
|
|
1061
|
+
throw new SandboxOperationOutcomeUnknownError("Operation authority was revoked after dispatch; its outcome remains unknown");
|
|
1062
|
+
denied("Operation authority was revoked");
|
|
1063
|
+
}
|
|
1064
|
+
if (!["dispatching", "started-or-unknown"].includes(r.state) ||
|
|
1065
|
+
r.execution_id === invocation.claim.executionId)
|
|
1066
|
+
throw new SandboxOperationOutcomeUnknownError("Reconciliation requires a newly claimed run execution");
|
|
1067
|
+
if (r.method === "backgroundStart") {
|
|
1068
|
+
// A stop asked for since the first dispatch: never send the start again, owe its revoke.
|
|
1069
|
+
const task = await this.db
|
|
1070
|
+
.selectFrom("background_tasks")
|
|
1071
|
+
.selectAll()
|
|
1072
|
+
.where("operation_id", "=", id)
|
|
1073
|
+
.forUpdate()
|
|
1074
|
+
.executeTakeFirst();
|
|
1075
|
+
if (!task)
|
|
1076
|
+
await this.revokeUnknownLocked(r, "retry");
|
|
1077
|
+
if (!task || !(await this.dispatchStillWanted(r, task, "retry")))
|
|
1078
|
+
return { ...r, state: "revoked", outcome_unknown: true };
|
|
1079
|
+
}
|
|
1080
|
+
// A background start in flight again is `dispatching` under this holder (as at first
|
|
1081
|
+
// dispatch), so scheduled recovery leaves it to this dispatcher until it gives up (`unknown`)
|
|
1082
|
+
// or its holder is found dead (`revokeHolders`).
|
|
1083
|
+
const state = r.method === "backgroundStart" ? "dispatching" : "started-or-unknown";
|
|
1084
|
+
await this.db
|
|
1085
|
+
.updateTable("sandbox_operation_intents")
|
|
1086
|
+
.set({
|
|
1087
|
+
execution_id: invocation.claim.executionId,
|
|
1088
|
+
holder_token: holderTag,
|
|
1089
|
+
state,
|
|
1090
|
+
updated_at: new Date(),
|
|
1091
|
+
})
|
|
1092
|
+
.where("operation_id", "=", id)
|
|
1093
|
+
.execute();
|
|
1094
|
+
return {
|
|
1095
|
+
...r,
|
|
1096
|
+
execution_id: invocation.claim.executionId,
|
|
1097
|
+
state,
|
|
1098
|
+
holder_token: holderTag,
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
async scheduleExpiry(row) {
|
|
1102
|
+
await this.outbox.add({
|
|
1103
|
+
queue: "cap-kernel-maintenance",
|
|
1104
|
+
name: OPERATION_RECONCILE,
|
|
1105
|
+
jobId: `${OPERATION_RECONCILE}-expiry-${row.operation_id}-${row.retain_until.getTime()}`,
|
|
1106
|
+
data: { operationId: row.operation_id },
|
|
1107
|
+
runAt: row.retain_until,
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
/** Keep the consumed ID/hash and cleanup obligations; expired bytes cannot authorize replay. */
|
|
1111
|
+
async expirePayload(id) {
|
|
1112
|
+
const expired = await this.db
|
|
1113
|
+
.updateTable("sandbox_operation_intents")
|
|
1114
|
+
.set({ input: "null", result: JSON.stringify({ $expired: true }), updated_at: new Date() })
|
|
1115
|
+
.where("operation_id", "=", id)
|
|
1116
|
+
.where("retain_until", "<=", new Date())
|
|
1117
|
+
.returning("operation_id")
|
|
1118
|
+
.executeTakeFirst();
|
|
1119
|
+
if (expired)
|
|
1120
|
+
await this.payloads.expire(id);
|
|
1121
|
+
}
|
|
1122
|
+
/** Cleanup association only: a claimed dead holder can never authorize dispatch. */
|
|
1123
|
+
async revokeHolders(deviceId, tokens) {
|
|
1124
|
+
if (!tokens.length)
|
|
1125
|
+
return;
|
|
1126
|
+
const device = await this.db
|
|
1127
|
+
.selectFrom("devices")
|
|
1128
|
+
.select("org_id")
|
|
1129
|
+
.where("id", "=", deviceId)
|
|
1130
|
+
.executeTakeFirst();
|
|
1131
|
+
if (!device)
|
|
1132
|
+
return;
|
|
1133
|
+
await this.locks.acquire({ orgId: device.org_id, deviceId }, { kind: "admit" });
|
|
1134
|
+
const rows = await this.db
|
|
1135
|
+
.updateTable("sandbox_operation_intents")
|
|
1136
|
+
.set({ state: "revoked", outcome_unknown: true, updated_at: new Date() })
|
|
1137
|
+
.where("device_id", "=", deviceId)
|
|
1138
|
+
.where("holder_token", "in", [...tokens])
|
|
1139
|
+
.where("state", "in", ["admitted", "dispatching", "started-or-unknown"])
|
|
1140
|
+
.returning("operation_id")
|
|
1141
|
+
.execute();
|
|
1142
|
+
for (const row of rows)
|
|
1143
|
+
await this.outbox.add({
|
|
1144
|
+
queue: "cap-kernel-maintenance",
|
|
1145
|
+
name: OPERATION_REVOKE,
|
|
1146
|
+
jobId: `${OPERATION_REVOKE}-${row.operation_id}`,
|
|
1147
|
+
data: { operationId: row.operation_id },
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* A disconnected or still-pending revoke remains owed; every retry is a new deterministic
|
|
1152
|
+
* persisted attempt, backing off (30 s doubling, at most an hour) so an obligation that only
|
|
1153
|
+
* retirement can resolve (a lost or replaced instance) never spins.
|
|
1154
|
+
*/
|
|
1155
|
+
async deferRevocation(id) {
|
|
1156
|
+
const row = await this.db
|
|
1157
|
+
.updateTable("sandbox_operation_intents")
|
|
1158
|
+
.set((eb) => ({ reconcile_attempt: eb("reconcile_attempt", "+", 1), updated_at: new Date() }))
|
|
1159
|
+
.where("operation_id", "=", id)
|
|
1160
|
+
.where("state", "=", "revoked")
|
|
1161
|
+
.where("revoke_acknowledged", "=", false)
|
|
1162
|
+
.returning(["org_id", "reconcile_attempt"])
|
|
1163
|
+
.executeTakeFirst();
|
|
1164
|
+
if (row)
|
|
1165
|
+
await this.outbox.add({
|
|
1166
|
+
queue: "cap-kernel-maintenance",
|
|
1167
|
+
name: OPERATION_REVOKE,
|
|
1168
|
+
jobId: `${OPERATION_REVOKE}-${id}-${row.reconcile_attempt}`,
|
|
1169
|
+
data: { operationId: id },
|
|
1170
|
+
runAt: new Date(Date.now() + Math.min(30_000 * 2 ** Math.min(row.reconcile_attempt - 1, 20), 3_600_000)),
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
async acknowledgeRevocation(id) {
|
|
1174
|
+
await this.db
|
|
1175
|
+
.updateTable("sandbox_operation_intents")
|
|
1176
|
+
.set({ revoke_acknowledged: true, updated_at: new Date() })
|
|
1177
|
+
.where("operation_id", "=", id)
|
|
1178
|
+
.where("state", "=", "revoked")
|
|
1179
|
+
.execute();
|
|
1180
|
+
}
|
|
1181
|
+
};
|
|
1182
|
+
__decorate([
|
|
1183
|
+
Transactional({ propagation: "requires_new" })
|
|
1184
|
+
], SandboxOperationIntents.prototype, "pending", null);
|
|
1185
|
+
__decorate([
|
|
1186
|
+
Transactional({ propagation: "requires_new" })
|
|
1187
|
+
], SandboxOperationIntents.prototype, "admitBrowse", null);
|
|
1188
|
+
__decorate([
|
|
1189
|
+
Transactional({ propagation: "requires_new" })
|
|
1190
|
+
], SandboxOperationIntents.prototype, "admitKernelRead", null);
|
|
1191
|
+
__decorate([
|
|
1192
|
+
Transactional({ propagation: "requires_new" })
|
|
1193
|
+
], SandboxOperationIntents.prototype, "claimKernelRead", null);
|
|
1194
|
+
__decorate([
|
|
1195
|
+
Transactional({ propagation: "requires_new" })
|
|
1196
|
+
], SandboxOperationIntents.prototype, "claimBrowse", null);
|
|
1197
|
+
__decorate([
|
|
1198
|
+
Transactional({ propagation: "requires_new" })
|
|
1199
|
+
], SandboxOperationIntents.prototype, "admit", null);
|
|
1200
|
+
__decorate([
|
|
1201
|
+
Transactional({ propagation: "requires_new" })
|
|
1202
|
+
], SandboxOperationIntents.prototype, "claimDispatch", null);
|
|
1203
|
+
__decorate([
|
|
1204
|
+
Transactional({ propagation: "requires_new" })
|
|
1205
|
+
], SandboxOperationIntents.prototype, "acknowledgeBackground", null);
|
|
1206
|
+
__decorate([
|
|
1207
|
+
Transactional({ propagation: "requires_new" })
|
|
1208
|
+
], SandboxOperationIntents.prototype, "claimBackgroundRecovery", null);
|
|
1209
|
+
__decorate([
|
|
1210
|
+
Transactional({ propagation: "requires_new" })
|
|
1211
|
+
], SandboxOperationIntents.prototype, "refusePreDispatch", null);
|
|
1212
|
+
__decorate([
|
|
1213
|
+
Transactional({ propagation: "requires_new" })
|
|
1214
|
+
], SandboxOperationIntents.prototype, "settleBackgroundRefusal", null);
|
|
1215
|
+
__decorate([
|
|
1216
|
+
Transactional({ propagation: "requires_new" })
|
|
1217
|
+
], SandboxOperationIntents.prototype, "abandonBackgroundLaunch", null);
|
|
1218
|
+
__decorate([
|
|
1219
|
+
Transactional({ propagation: "requires_new" })
|
|
1220
|
+
], SandboxOperationIntents.prototype, "deferBackgroundRecovery", null);
|
|
1221
|
+
__decorate([
|
|
1222
|
+
Transactional({ propagation: "requires_new" })
|
|
1223
|
+
], SandboxOperationIntents.prototype, "complete", null);
|
|
1224
|
+
__decorate([
|
|
1225
|
+
Transactional({ propagation: "requires_new" })
|
|
1226
|
+
], SandboxOperationIntents.prototype, "unknown", null);
|
|
1227
|
+
__decorate([
|
|
1228
|
+
Transactional({ propagation: "requires_new" })
|
|
1229
|
+
], SandboxOperationIntents.prototype, "claimReconciliation", null);
|
|
1230
|
+
__decorate([
|
|
1231
|
+
Transactional({ propagation: "requires_new" })
|
|
1232
|
+
], SandboxOperationIntents.prototype, "expirePayload", null);
|
|
1233
|
+
__decorate([
|
|
1234
|
+
Transactional({ propagation: "requires_new" })
|
|
1235
|
+
], SandboxOperationIntents.prototype, "revokeHolders", null);
|
|
1236
|
+
__decorate([
|
|
1237
|
+
Transactional({ propagation: "requires_new" })
|
|
1238
|
+
], SandboxOperationIntents.prototype, "deferRevocation", null);
|
|
1239
|
+
__decorate([
|
|
1240
|
+
Transactional({ propagation: "requires_new" })
|
|
1241
|
+
], SandboxOperationIntents.prototype, "acknowledgeRevocation", null);
|
|
1242
|
+
SandboxOperationIntents = __decorate([
|
|
1243
|
+
Injectable(),
|
|
1244
|
+
__param(0, Inject(KernelDb)),
|
|
1245
|
+
__param(1, Inject(TransactionHost)),
|
|
1246
|
+
__param(2, Inject(PermissionAuthorityLock)),
|
|
1247
|
+
__param(3, Inject(PermissionAuthorityEpochStore)),
|
|
1248
|
+
__param(4, Inject(SandboxOperationAuthority)),
|
|
1249
|
+
__param(5, Inject(OutboxService)),
|
|
1250
|
+
__param(6, Inject(OperationPayloads))
|
|
1251
|
+
], SandboxOperationIntents);
|
|
1252
|
+
export { SandboxOperationIntents };
|