@capybara-hq/kernel 0.1.0-rc.41 → 0.1.0-rc.43
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 +3 -3
- 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 +4 -1
- package/dist/config/schema.js +41 -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 +307 -4
- package/dist/conversations/events.js +286 -32
- 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/ctx/create-ctx.d.ts +12 -5
- package/dist/ctx/create-ctx.js +21 -5
- package/dist/db/kernel-schema.d.ts +248 -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/extensions/host.d.ts +4 -1
- package/dist/extensions/host.js +10 -6
- 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 +35 -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/models/image-usable.d.ts +22 -0
- package/dist/models/image-usable.js +29 -0
- package/dist/models/images.d.ts +125 -0
- package/dist/models/images.js +440 -0
- package/dist/models/models.module.d.ts +3 -2
- package/dist/models/models.module.js +16 -5
- package/dist/models/org-models.schemas.js +1 -0
- package/dist/models/purposes.controller.d.ts +7 -0
- package/dist/models/purposes.controller.js +9 -0
- package/dist/models/purposes.d.ts +28 -3
- package/dist/models/purposes.js +40 -13
- 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/models.ops.js +10 -0
- 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/hook-calls.d.ts +11 -1
- package/dist/runtime/hook-calls.js +24 -1
- 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/providers.d.ts +9 -5
- package/dist/runtime/providers.js +22 -3
- 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/runtime/usage-report.d.ts +10 -6
- package/dist/runtime/usage-report.js +31 -11
- 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 +145 -0
- package/dist/sandbox/review/review.service.d.ts +5 -2
- package/dist/sandbox/review/review.service.js +60 -15
- 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/builtin-names.d.ts +3 -1
- package/dist/tools/builtin-names.js +5 -1
- package/dist/tools/builtins/artifacts.d.ts +43 -0
- package/dist/tools/builtins/artifacts.js +67 -0
- package/dist/tools/builtins/builtin-tools.d.ts +20 -2
- package/dist/tools/builtins/builtin-tools.js +61 -10
- package/dist/tools/builtins/image/generate.d.ts +59 -0
- package/dist/tools/builtins/image/generate.js +535 -0
- package/dist/tools/builtins/image/index.d.ts +2 -0
- package/dist/tools/builtins/image/index.js +2 -0
- package/dist/tools/builtins/image/paths.d.ts +12 -0
- package/dist/tools/builtins/image/paths.js +26 -0
- 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 +9 -51
- 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 +315 -26
- package/dist/tools/registry.d.ts +9 -0
- package/dist/tools/tools.module.js +15 -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/src/migrations/0160_model_usage_image_kind.sql +10 -0
- package/dist/sandbox/platform-auto-mode.d.ts +0 -63
- package/dist/sandbox/platform-auto-mode.js +0 -63
|
@@ -8,12 +8,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
10
|
import { randomUUID } from "node:crypto";
|
|
11
|
-
import { DeviceProtocolError, FileSystemGoneError, parseDeviceFrame, parseOpResult, SandboxGoneError, ToolError, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { DEVICE_PROTOCOL_VERSION, DeviceProtocolError, FileSystemGoneError, parseDeviceFrame, parseDeviceFrameV3, parseOperationResultV3, parseOpResult, SandboxGoneError, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, STAGED_DEVICE_PROTOCOL_VERSION, ToolError, } from "@capybara-hq/plugin-sdk";
|
|
12
12
|
import { Inject, Injectable } from "@nestjs/common";
|
|
13
13
|
import { ApiError } from "../errors.js";
|
|
14
14
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
15
15
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
16
16
|
import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
17
|
+
import { DeviceRequestNotSentError, isDeviceRequestNotSent } from "../sandbox/request-not-sent.js";
|
|
17
18
|
import { deviceNotFound } from "../sandbox/sandbox.service.js";
|
|
18
19
|
import { deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, } from "./keys.js";
|
|
19
20
|
import { DeviceTargets } from "./targets.js";
|
|
@@ -28,6 +29,43 @@ export const machineRevoked = () => new ApiError("device.forbidden", "The machin
|
|
|
28
29
|
export const POLICY_REFUSAL_PREFIX = "Refused by the machine's local policy: ";
|
|
29
30
|
/** The text a machine's `error` result reaches the model with (ruling R28). */
|
|
30
31
|
export const ON_MACHINE_PREFIX = "On the connected machine: ";
|
|
32
|
+
/**
|
|
33
|
+
* The text of a staged (protocol 3) request refused because the machine's connection changed.
|
|
34
|
+
* Only an output read has an offset to retry from; every other operation is simply retried.
|
|
35
|
+
*/
|
|
36
|
+
export const connectionChangedMessage = (op) => op === "backgroundReadOutput"
|
|
37
|
+
? "The machine's connection changed during the read; retry the read from the same offset"
|
|
38
|
+
: `The machine's connection changed before ${op} was sent; retry the operation`;
|
|
39
|
+
export { DeviceRequestNotSentError, isDeviceRequestNotSent };
|
|
40
|
+
/**
|
|
41
|
+
* The operations held under a stable operation identity (native, preparation and browsing
|
|
42
|
+
* operations, execution, a background start and an operation revoke): their not-sent refusal is
|
|
43
|
+
* typed ({@link DeviceRequestNotSentError}) so the operation path records it as definite. Exact
|
|
44
|
+
* status, tail, stop and reads, the policy controls and binding keep their plain errors.
|
|
45
|
+
*/
|
|
46
|
+
const heldOperation = (op) => op === "backgroundStart" ||
|
|
47
|
+
op === "revokeOperation" ||
|
|
48
|
+
/^(?:exec|readFile|writeFile|stat|list|scan|prepare(?:ReadFile|WriteFile|Stat)|browse(?:Stat|List|Scan))$/.test(op);
|
|
49
|
+
/**
|
|
50
|
+
* Whether a staged operation's result is fenced to the connection its request was sent on.
|
|
51
|
+
* Protocol 3 (spec B5) fences every request to its connection, so an old capacity is never used on
|
|
52
|
+
* a replacement socket. For results, only an output read is fenced: its range was sized for the
|
|
53
|
+
* old connection's capacity and an in-flight read that meets a reconnect fails so the reader
|
|
54
|
+
* retries from the same offset. Every other operation keeps protocol 2's grace semantics: the
|
|
55
|
+
* machine keeps it running across a socket blip and its result, validated by the gateway against
|
|
56
|
+
* the capacity of the connection it arrived on, is accepted after a reconnect within the grace.
|
|
57
|
+
*/
|
|
58
|
+
const connectionFenced = (op) => op === "backgroundReadOutput";
|
|
59
|
+
/**
|
|
60
|
+
* The kernel-internal field of a queued `stop` naming the machine it is for (stripped by the holder
|
|
61
|
+
* before the frame goes out; a frame for another machine is dropped).
|
|
62
|
+
*/
|
|
63
|
+
export const STOP_MACHINE = "machineId";
|
|
64
|
+
/**
|
|
65
|
+
* Whether the deployment speaks the staged device protocol: the single gate is the SDK's protocol
|
|
66
|
+
* constant (flipped to 3 at the paired activation). Until then the active wire stays protocol 2.
|
|
67
|
+
*/
|
|
68
|
+
export const stagedDeviceProtocolActive = () => DEVICE_PROTOCOL_VERSION === STAGED_DEVICE_PROTOCOL_VERSION;
|
|
31
69
|
/** The longest one lease check of a waiting caller may take before it counts as "unknown". */
|
|
32
70
|
export const LEASE_CHECK_TIMEOUT_MS = 2000;
|
|
33
71
|
/** How often a waiting caller checks that a replica still holds the machine's connection. */
|
|
@@ -67,6 +105,27 @@ return 1
|
|
|
67
105
|
/** Why a call stopped waiting without a result. */
|
|
68
106
|
const ABORTED = Symbol("aborted");
|
|
69
107
|
const GRACE_EXPIRED = Symbol("grace expired");
|
|
108
|
+
/**
|
|
109
|
+
* The kernel-internal fields the gateway adds to what it stores for a staged result, next to the
|
|
110
|
+
* device's frame: the connection it arrived on, that connection's capacity and, only on the
|
|
111
|
+
* gateway's own refusal of a request queued for another connection, {@link GATEWAY_NOT_SENT}. The
|
|
112
|
+
* device's frame is parsed strictly (unknown keys refused), so a device can never set them.
|
|
113
|
+
*/
|
|
114
|
+
export const GATEWAY_NOT_SENT = "notSent";
|
|
115
|
+
/**
|
|
116
|
+
* A staged request refused because it was not sent, outside the operations held under an operation
|
|
117
|
+
* identity (a policy control, a status read): a protocol error that also says nothing ran, so a
|
|
118
|
+
* caller can record it as never received instead of unknown ({@link wasDeviceRequestNotSent}).
|
|
119
|
+
*/
|
|
120
|
+
export class DeviceRequestNotSentProtocolError extends DeviceProtocolError {
|
|
121
|
+
notSent = true;
|
|
122
|
+
}
|
|
123
|
+
/** Any staged request the kernel knows was never sent to the machine (held or not). */
|
|
124
|
+
export const wasDeviceRequestNotSent = (e) => e instanceof Error && e.notSent === true;
|
|
125
|
+
/** The not-sent refusal of `op`: typed for held operations, a not-sent protocol error otherwise. */
|
|
126
|
+
const notSentError = (op) => heldOperation(op)
|
|
127
|
+
? new DeviceRequestNotSentError(connectionChangedMessage(op))
|
|
128
|
+
: new DeviceRequestNotSentProtocolError(connectionChangedMessage(op));
|
|
70
129
|
const errMsg = (e) => (e instanceof Error ? e.message : String(e));
|
|
71
130
|
/**
|
|
72
131
|
* The caller side of the device relay (environments spec §13.4). A request goes onto the
|
|
@@ -110,14 +169,49 @@ let LocalDeviceRelay = class LocalDeviceRelay {
|
|
|
110
169
|
return (await this.locks.holderOf(deviceLeaseKey(deviceId))) !== null;
|
|
111
170
|
}
|
|
112
171
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
172
|
+
* Whether the protocol gate is open ({@link stagedDeviceProtocolActive}; a test seam opens it
|
|
173
|
+
* for one relay instance, the deployment never does).
|
|
174
|
+
*/
|
|
175
|
+
stagedProtocolActive = stagedDeviceProtocolActive;
|
|
176
|
+
/**
|
|
177
|
+
* The negotiated transport of the device's connection when the platform's own controls (policy
|
|
178
|
+
* ops) must speak protocol 3 to it, else null (protocol 2). With the gate closed every
|
|
179
|
+
* connection is protocol 2: nothing is looked up (no lease or transport read per op). With it
|
|
180
|
+
* open every connection is staged, so this is {@link connection} (a missing or unready one
|
|
181
|
+
* throws its typed error).
|
|
115
182
|
*/
|
|
116
|
-
async
|
|
183
|
+
async stagedTransport(deviceId) {
|
|
184
|
+
if (!this.stagedProtocolActive())
|
|
185
|
+
return null;
|
|
186
|
+
return this.connection(deviceId);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The negotiated transport of the machine's current connection, for a staged call. Liveness is
|
|
190
|
+
* checked first (ruling R27): no holder throws `device.not_found` for a deleted device,
|
|
191
|
+
* `device.forbidden` for a revoked machine and `device.offline` otherwise.
|
|
192
|
+
*/
|
|
193
|
+
async connection(deviceId) {
|
|
194
|
+
if (await this.holderLive(deviceId)) {
|
|
195
|
+
const transport = await this.targets.transport(deviceId);
|
|
196
|
+
if (transport)
|
|
197
|
+
return transport;
|
|
198
|
+
}
|
|
199
|
+
throw this.goneError(await this.targetState(deviceId)) ?? deviceOffline();
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Queues `stop` for the machine without waiting for an answer (ruling R14). The caller checks
|
|
203
|
+
* {@link holderLive} first; the frame waits on the list for the grace like any request. It is
|
|
204
|
+
* fenced to the machine `machineId` ({@link STOP_MACHINE}): a holder hands it only to that
|
|
205
|
+
* machine's connection (on a staged connection as a protocol 3 `stop`, across a socket blip
|
|
206
|
+
* too), never to a newer machine of the device. Only `stop` is ever queued this way: a broad
|
|
207
|
+
* kill (`killAll` / `killTagged`) has no frame on protocol 3.
|
|
208
|
+
*/
|
|
209
|
+
async send(deviceId, op, args, deadlineMs, machineId) {
|
|
117
210
|
const id = randomUUID();
|
|
118
211
|
const d = Math.max(1, Math.ceil(deadlineMs));
|
|
119
212
|
const req = { type: "req", id, op, args, deadlineMs: d };
|
|
120
|
-
|
|
213
|
+
const tagged = { ...req, [STOP_MACHINE]: machineId };
|
|
214
|
+
await this.push(deviceId, JSON.stringify(tagged), this.graceMs() + d + LIST_TTL_MARGIN_MS);
|
|
121
215
|
await this.bus.publish(deviceReqTopic(deviceId), { id });
|
|
122
216
|
}
|
|
123
217
|
/**
|
|
@@ -131,17 +225,36 @@ let LocalDeviceRelay = class LocalDeviceRelay {
|
|
|
131
225
|
* abort reason is thrown.
|
|
132
226
|
*/
|
|
133
227
|
async call(deviceId, op, args, opts) {
|
|
228
|
+
return this.callWithCodec(deviceId, op, args, opts, false);
|
|
229
|
+
}
|
|
230
|
+
/** Development staging: the active gateway continues rejecting protocol 3 until coordinated cutover. */
|
|
231
|
+
async callV3(deviceId, op, args, opts) {
|
|
232
|
+
parseDeviceFrameV3(JSON.stringify({ type: "req", id: "validation", op, args, deadlineMs: opts.deadlineMs }), "kernel");
|
|
233
|
+
return this.callWithCodec(deviceId, op, args, opts, true);
|
|
234
|
+
}
|
|
235
|
+
async callWithCodec(deviceId, op, args, opts, staged) {
|
|
134
236
|
const { signal } = opts;
|
|
135
237
|
signal.throwIfAborted();
|
|
136
|
-
|
|
238
|
+
// liveness first: a deleted device or a revoked machine keeps its typed error (R27)
|
|
239
|
+
const connection = staged ? await this.connection(deviceId) : undefined;
|
|
240
|
+
if (!staged && !(await this.holderLive(deviceId))) {
|
|
137
241
|
throw this.goneError(await this.targetState(deviceId)) ?? deviceOffline();
|
|
138
242
|
}
|
|
243
|
+
if (opts.connection &&
|
|
244
|
+
(connection?.connectionId !== opts.connection.connectionId ||
|
|
245
|
+
connection?.maxFrameBytes !== opts.connection.maxFrameBytes))
|
|
246
|
+
// nothing was queued: the request was definitely not sent
|
|
247
|
+
throw notSentError(op);
|
|
248
|
+
const fenced = staged && connectionFenced(op);
|
|
139
249
|
signal.throwIfAborted();
|
|
140
250
|
const id = randomUUID();
|
|
141
251
|
const deadlineMs = Math.max(1, Math.ceil(opts.deadlineMs));
|
|
142
252
|
const graceMs = this.graceMs();
|
|
143
253
|
const listTtlMs = graceMs + deadlineMs + LIST_TTL_MARGIN_MS;
|
|
144
|
-
const
|
|
254
|
+
const frame = { type: "req", id, op, args, deadlineMs };
|
|
255
|
+
if (connection)
|
|
256
|
+
parseDeviceFrameV3(JSON.stringify(frame), "kernel", connection.maxFrameBytes);
|
|
257
|
+
const reqJson = JSON.stringify({ ...frame, ...connection });
|
|
145
258
|
let settle;
|
|
146
259
|
const outcome = new Promise((resolve) => {
|
|
147
260
|
let done = false;
|
|
@@ -154,7 +267,7 @@ let LocalDeviceRelay = class LocalDeviceRelay {
|
|
|
154
267
|
});
|
|
155
268
|
const onStored = (raw) => {
|
|
156
269
|
if (raw !== null)
|
|
157
|
-
settle(this.parseRes(raw, id));
|
|
270
|
+
settle(this.parseRes(raw, id, op, connection, fenced));
|
|
158
271
|
};
|
|
159
272
|
const onAbort = () => settle({ error: ABORTED });
|
|
160
273
|
const unsubscribe = await this.bus.subscribe(deviceResTopic(id), (payload) => {
|
|
@@ -181,6 +294,16 @@ let LocalDeviceRelay = class LocalDeviceRelay {
|
|
|
181
294
|
try {
|
|
182
295
|
// a stalled Redis must not hold the give-up back: no answer in time means "unknown"
|
|
183
296
|
const live = await this.leaseCheck(deviceId);
|
|
297
|
+
if (fenced && connection && live === true) {
|
|
298
|
+
// an output read never waits across a reconnect: its range was sized for this socket
|
|
299
|
+
const current = await this.targets.transport(deviceId);
|
|
300
|
+
if (current &&
|
|
301
|
+
(current.connectionId !== connection.connectionId ||
|
|
302
|
+
current.maxFrameBytes !== connection.maxFrameBytes)) {
|
|
303
|
+
settle({ error: new DeviceProtocolError(connectionChangedMessage(op)) });
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
184
307
|
if (live === true && capped) {
|
|
185
308
|
capped = false;
|
|
186
309
|
giveUpAt = fullGiveUpAt;
|
|
@@ -221,14 +344,24 @@ let LocalDeviceRelay = class LocalDeviceRelay {
|
|
|
221
344
|
stopped = true;
|
|
222
345
|
clearTimeout(timer);
|
|
223
346
|
if ("res" in r) {
|
|
347
|
+
// the result's connection tag was checked in parseRes: a later reconnect changes nothing
|
|
224
348
|
await this.quietly("delete the result", deviceId, () => this.redis.del(deviceResKey(id)));
|
|
225
|
-
|
|
349
|
+
// only the gateway's marker says a request never reached the machine: never its text
|
|
350
|
+
if (connection && r.notSent)
|
|
351
|
+
throw notSentError(op);
|
|
352
|
+
return staged && r.res.ok
|
|
353
|
+
? parseOperationResultV3(op, r.res.result, op === "backgroundReadOutput"
|
|
354
|
+
? args
|
|
355
|
+
: op === "bindInstance"
|
|
356
|
+
? args
|
|
357
|
+
: undefined)
|
|
358
|
+
: this.resultOf(op, r.res);
|
|
226
359
|
}
|
|
227
360
|
if (r.error instanceof Error) {
|
|
228
361
|
// a bad answer: drop it, give the request up, report the protocol error
|
|
229
362
|
await this.quietly("delete the result", deviceId, () => this.redis.del(deviceResKey(id)));
|
|
230
363
|
}
|
|
231
|
-
await this.giveUp(deviceId, id, reqJson, listTtlMs);
|
|
364
|
+
await this.giveUp(deviceId, id, reqJson, listTtlMs, connection);
|
|
232
365
|
if (r.error === ABORTED)
|
|
233
366
|
throw signal.reason;
|
|
234
367
|
if (r.error === GRACE_EXPIRED)
|
|
@@ -307,8 +440,8 @@ let LocalDeviceRelay = class LocalDeviceRelay {
|
|
|
307
440
|
});
|
|
308
441
|
}
|
|
309
442
|
/** Removes the request from the list, or queues a cancel when the machine took it (R15). */
|
|
310
|
-
async giveUp(deviceId, id, reqJson, ttlMs) {
|
|
311
|
-
const cancel = JSON.stringify({ type: "cancel", id });
|
|
443
|
+
async giveUp(deviceId, id, reqJson, ttlMs, connection) {
|
|
444
|
+
const cancel = JSON.stringify({ type: "cancel", id, ...connection });
|
|
312
445
|
await this.quietly("give the request up", deviceId, async () => {
|
|
313
446
|
const queued = await this.redis.eval(GIVE_UP, 1, deviceReqKey(deviceId), reqJson, cancel, String(ttlMs));
|
|
314
447
|
if (queued === 1)
|
|
@@ -324,14 +457,46 @@ let LocalDeviceRelay = class LocalDeviceRelay {
|
|
|
324
457
|
this.log.warn(`device relay could not ${what}`, { deviceId, error: errMsg(e) });
|
|
325
458
|
}
|
|
326
459
|
}
|
|
327
|
-
/**
|
|
328
|
-
|
|
460
|
+
/**
|
|
461
|
+
* A stored / published `res` frame for request `id`, or the protocol error it carries. A staged
|
|
462
|
+
* frame carries the tag of the connection it arrived on (added by the gateway); a fenced
|
|
463
|
+
* operation ({@link connectionFenced}) accepts only its request's connection, any other staged
|
|
464
|
+
* operation a well-formed tag, and the frame is parsed against that connection's capacity.
|
|
465
|
+
*/
|
|
466
|
+
parseRes(raw, id, op, connection, fenced = false) {
|
|
329
467
|
try {
|
|
330
|
-
|
|
468
|
+
let wire = raw;
|
|
469
|
+
let cap;
|
|
470
|
+
let arrivedOn;
|
|
471
|
+
let notSent = false;
|
|
472
|
+
if (connection) {
|
|
473
|
+
const { connectionId, maxFrameBytes, [GATEWAY_NOT_SENT]: marker, ...frame } = JSON.parse(raw);
|
|
474
|
+
if (typeof connectionId !== "string" ||
|
|
475
|
+
connectionId === "" ||
|
|
476
|
+
typeof maxFrameBytes !== "number" ||
|
|
477
|
+
!Number.isSafeInteger(maxFrameBytes) ||
|
|
478
|
+
maxFrameBytes < 1024)
|
|
479
|
+
throw new DeviceProtocolError("the gateway stored a result without its connection");
|
|
480
|
+
if (fenced &&
|
|
481
|
+
(connectionId !== connection.connectionId || maxFrameBytes !== connection.maxFrameBytes))
|
|
482
|
+
throw new DeviceProtocolError(connectionChangedMessage(op));
|
|
483
|
+
cap = maxFrameBytes;
|
|
484
|
+
arrivedOn = connectionId;
|
|
485
|
+
notSent = marker === true;
|
|
486
|
+
wire = JSON.stringify(frame);
|
|
487
|
+
}
|
|
488
|
+
const f = connection
|
|
489
|
+
? parseDeviceFrameV3(wire, "device", cap)
|
|
490
|
+
: parseDeviceFrame(wire, "device");
|
|
331
491
|
if (f.type !== "res" || f.id !== id) {
|
|
332
492
|
return { error: new DeviceProtocolError("the connected machine sent an unexpected frame") };
|
|
333
493
|
}
|
|
334
|
-
|
|
494
|
+
if (arrivedOn === undefined)
|
|
495
|
+
return { res: f };
|
|
496
|
+
// a refusal only: a successful result never carries the marker
|
|
497
|
+
return notSent && !f.ok
|
|
498
|
+
? { res: f, connectionId: arrivedOn, notSent: true }
|
|
499
|
+
: { res: f, connectionId: arrivedOn };
|
|
335
500
|
}
|
|
336
501
|
catch (e) {
|
|
337
502
|
return {
|
|
@@ -352,6 +517,12 @@ let LocalDeviceRelay = class LocalDeviceRelay {
|
|
|
352
517
|
}
|
|
353
518
|
const { kind, message } = res.error;
|
|
354
519
|
switch (kind) {
|
|
520
|
+
case "denied":
|
|
521
|
+
throw new SandboxScopeDeniedError(message);
|
|
522
|
+
case "unsupported":
|
|
523
|
+
throw new SandboxPermissionUnsupportedError(message);
|
|
524
|
+
case "unknown":
|
|
525
|
+
throw new SandboxOperationOutcomeUnknownError(message);
|
|
355
526
|
case "gone":
|
|
356
527
|
throw new SandboxGoneError(message);
|
|
357
528
|
case "fs_gone":
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { DeviceFeature, SandboxRoots } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { Redis } from "ioredis";
|
|
2
3
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
4
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
3
5
|
/**
|
|
4
6
|
* Whether a local device can still be served: `active` (live and an unrevoked machine),
|
|
5
7
|
* `revoked` (live, no active machine: disconnected or signed out) or `deleted` (missing or
|
|
@@ -16,7 +18,20 @@ export declare const sameRoots: (a: SandboxRoots, b: SandboxRoots) => boolean;
|
|
|
16
18
|
*/
|
|
17
19
|
export declare class DeviceTargets {
|
|
18
20
|
private readonly db;
|
|
19
|
-
|
|
21
|
+
private readonly redis;
|
|
22
|
+
private readonly locks;
|
|
23
|
+
constructor(db: KernelDb, redis: Redis, locks: Pick<LockService, "holderOf">);
|
|
24
|
+
/**
|
|
25
|
+
* The negotiated transport of the machine's current connection, read only under its exact
|
|
26
|
+
* authenticated gateway lease (never current config): the random connection id the gateway sent
|
|
27
|
+
* in `ready` and the effective frame capacity. Null when no replica holds the machine's
|
|
28
|
+
* connection, so the caller maps that through the device's state (deleted, revoked, offline);
|
|
29
|
+
* throws while the holder has not published its capacity yet.
|
|
30
|
+
*/
|
|
31
|
+
transport(deviceId: string): Promise<{
|
|
32
|
+
connectionId: string;
|
|
33
|
+
maxFrameBytes: number;
|
|
34
|
+
} | null>;
|
|
20
35
|
state(deviceId: string): Promise<DeviceTargetState>;
|
|
21
36
|
/** The org of a live device, or null (missing or deleted). */
|
|
22
37
|
orgOf(deviceId: string): Promise<string | null>;
|
|
@@ -9,6 +9,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
9
9
|
};
|
|
10
10
|
import { Inject, Injectable } from "@nestjs/common";
|
|
11
11
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
12
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
13
|
+
import { REDIS } from "../infra/tokens.js";
|
|
14
|
+
import { deviceLeaseKey, deviceTransportKey } from "./keys.js";
|
|
12
15
|
import { deviceFeaturesOf } from "./policy-summary.js";
|
|
13
16
|
const ROOT_KEYS = ["workspace", "skills", "tmp"];
|
|
14
17
|
/** Whether two sets of roots name the same three directories. */
|
|
@@ -21,8 +24,36 @@ export const sameRoots = (a, b) => ROOT_KEYS.every((k) => a[k] === b[k]);
|
|
|
21
24
|
*/
|
|
22
25
|
let DeviceTargets = class DeviceTargets {
|
|
23
26
|
db;
|
|
24
|
-
|
|
27
|
+
redis;
|
|
28
|
+
locks;
|
|
29
|
+
constructor(db, redis, locks) {
|
|
25
30
|
this.db = db;
|
|
31
|
+
this.redis = redis;
|
|
32
|
+
this.locks = locks;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The negotiated transport of the machine's current connection, read only under its exact
|
|
36
|
+
* authenticated gateway lease (never current config): the random connection id the gateway sent
|
|
37
|
+
* in `ready` and the effective frame capacity. Null when no replica holds the machine's
|
|
38
|
+
* connection, so the caller maps that through the device's state (deleted, revoked, offline);
|
|
39
|
+
* throws while the holder has not published its capacity yet.
|
|
40
|
+
*/
|
|
41
|
+
async transport(deviceId) {
|
|
42
|
+
const lease = await this.locks.holderOf(deviceLeaseKey(deviceId));
|
|
43
|
+
if (!lease)
|
|
44
|
+
return null;
|
|
45
|
+
const raw = await this.redis.get(deviceTransportKey(deviceId, lease));
|
|
46
|
+
const cap = raw === null ? null : JSON.parse(raw);
|
|
47
|
+
const ok = cap !== null &&
|
|
48
|
+
typeof cap === "object" &&
|
|
49
|
+
typeof cap.connectionId === "string" &&
|
|
50
|
+
cap.connectionId !== "" &&
|
|
51
|
+
Number.isSafeInteger(cap.maxFrameBytes) &&
|
|
52
|
+
cap.maxFrameBytes >= 1024;
|
|
53
|
+
if (!ok || (await this.locks.holderOf(deviceLeaseKey(deviceId))) !== lease)
|
|
54
|
+
throw new Error("The machine's connection is not ready yet; retry once capybara-device has reconnected");
|
|
55
|
+
const { connectionId, maxFrameBytes } = cap;
|
|
56
|
+
return { connectionId, maxFrameBytes };
|
|
26
57
|
}
|
|
27
58
|
async state(deviceId) {
|
|
28
59
|
const row = await this.db
|
|
@@ -82,6 +113,8 @@ let DeviceTargets = class DeviceTargets {
|
|
|
82
113
|
};
|
|
83
114
|
DeviceTargets = __decorate([
|
|
84
115
|
Injectable(),
|
|
85
|
-
__param(0, Inject(KernelDb))
|
|
116
|
+
__param(0, Inject(KernelDb)),
|
|
117
|
+
__param(1, Inject(REDIS)),
|
|
118
|
+
__param(2, Inject(LockService))
|
|
86
119
|
], DeviceTargets);
|
|
87
120
|
export { DeviceTargets };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Logger } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { type ProviderRegistry } from "../runtime/providers.js";
|
|
3
|
+
import type { StorageService } from "../storage/storage.service.js";
|
|
4
|
+
import type { ModelPurposesService } from "./purposes.js";
|
|
5
|
+
/** The model purpose `GenerateImage` calls (image generation spec §5.4; no fallback). */
|
|
6
|
+
export declare const IMAGE_PURPOSE = "image";
|
|
7
|
+
/** Whether `GenerateImage` can run in an org now, and if not, why. */
|
|
8
|
+
export type ImageUsable = "usable" | "no-model" | "no-storage";
|
|
9
|
+
/**
|
|
10
|
+
* The one predicate of `GenerateImage`'s availability (image generation spec §5.3), shared by the
|
|
11
|
+
* tool's listing and the member-readable purpose availability the agent form reads, so the two
|
|
12
|
+
* never disagree: the org's `image` purpose resolves to an image model the org can call now (an
|
|
13
|
+
* unmapped, disabled or unavailable model, or a provider whose model list fails, is `no-model`),
|
|
14
|
+
* and an object store is there to deliver the images (`no-storage`). Any other failure is logged
|
|
15
|
+
* and rethrown: it is a kernel fault, not an unavailable model.
|
|
16
|
+
*/
|
|
17
|
+
export declare function imagePurposeUsable(deps: {
|
|
18
|
+
purposes: Pick<ModelPurposesService, "resolve">;
|
|
19
|
+
providers: Pick<ProviderRegistry, "resolve">;
|
|
20
|
+
storage: Pick<StorageService, "available">;
|
|
21
|
+
log: Pick<Logger, "warn">;
|
|
22
|
+
}, orgId: string): Promise<ImageUsable>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { ApiError } from "../errors.js";
|
|
2
|
+
import { ProviderListError } from "../runtime/providers.js";
|
|
3
|
+
/** The model purpose `GenerateImage` calls (image generation spec §5.4; no fallback). */
|
|
4
|
+
export const IMAGE_PURPOSE = "image";
|
|
5
|
+
/**
|
|
6
|
+
* The one predicate of `GenerateImage`'s availability (image generation spec §5.3), shared by the
|
|
7
|
+
* tool's listing and the member-readable purpose availability the agent form reads, so the two
|
|
8
|
+
* never disagree: the org's `image` purpose resolves to an image model the org can call now (an
|
|
9
|
+
* unmapped, disabled or unavailable model, or a provider whose model list fails, is `no-model`),
|
|
10
|
+
* and an object store is there to deliver the images (`no-storage`). Any other failure is logged
|
|
11
|
+
* and rethrown: it is a kernel fault, not an unavailable model.
|
|
12
|
+
*/
|
|
13
|
+
export async function imagePurposeUsable(deps, orgId) {
|
|
14
|
+
try {
|
|
15
|
+
const target = await deps.purposes.resolve(orgId, IMAGE_PURPOSE);
|
|
16
|
+
await deps.providers.resolve(orgId, target.model, { kind: "image_generation" });
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
if (e instanceof ProviderListError)
|
|
20
|
+
return "no-model";
|
|
21
|
+
if (e instanceof ApiError &&
|
|
22
|
+
(e.code === "model.unconfigured" || e.code === "agent.model_unavailable")) {
|
|
23
|
+
return "no-model";
|
|
24
|
+
}
|
|
25
|
+
deps.log.warn("image purpose availability check failed", { orgId, err: e });
|
|
26
|
+
throw e;
|
|
27
|
+
}
|
|
28
|
+
return deps.storage.available ? "usable" : "no-storage";
|
|
29
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { type ExtensionImageGenerateRequest, type ExtensionImageGenerateResult, type ExtensionModelTarget, type HookScope, type ImageAspectRatio, type ImageGenerateRequest, type ImageGenerateResult, type ImageMediaType, type ImageSize, type Logger, type ModelImageGenerationInfo } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
3
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
4
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
5
|
+
import { type HookDenial, type HookRunner } from "../runtime/hook-calls.js";
|
|
6
|
+
import { ProviderRegistry } from "../runtime/providers.js";
|
|
7
|
+
import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
|
|
8
|
+
import type { DeclaredModelPurposes } from "./embeddings.js";
|
|
9
|
+
import { ModelPurposesService } from "./purposes.js";
|
|
10
|
+
/** What a caller asks for (the tool or `ctx.models.generateImage`); references are bytes already. */
|
|
11
|
+
export interface ImageCallInput {
|
|
12
|
+
prompt: string;
|
|
13
|
+
/** An exact size (only `ctx.models`); must be one the model declares. */
|
|
14
|
+
size?: ImageSize;
|
|
15
|
+
aspectRatio?: ImageAspectRatio;
|
|
16
|
+
/** Images to produce (default 1). */
|
|
17
|
+
n?: number;
|
|
18
|
+
/** Base64 reference images. */
|
|
19
|
+
referenceImages?: {
|
|
20
|
+
mediaType: ImageMediaType;
|
|
21
|
+
data: string;
|
|
22
|
+
}[];
|
|
23
|
+
}
|
|
24
|
+
/** A validated call, ready for {@link ModelImages.run}. */
|
|
25
|
+
export interface PreparedImageCall {
|
|
26
|
+
ref: {
|
|
27
|
+
provider: string;
|
|
28
|
+
model: string;
|
|
29
|
+
};
|
|
30
|
+
info: ModelImageGenerationInfo;
|
|
31
|
+
request: ImageGenerateRequest;
|
|
32
|
+
}
|
|
33
|
+
/** Who makes the call, as the hook payloads name it. */
|
|
34
|
+
export type ImageHookIdentity = {
|
|
35
|
+
kind: "conversation";
|
|
36
|
+
scope: HookScope;
|
|
37
|
+
step: number;
|
|
38
|
+
callId: string;
|
|
39
|
+
} | {
|
|
40
|
+
kind: "extension";
|
|
41
|
+
extension: string;
|
|
42
|
+
imagePurpose: string;
|
|
43
|
+
};
|
|
44
|
+
/** A `model.request` policy hook denied the call; nothing was sent. The caller records it. */
|
|
45
|
+
export declare class ImageCallDenied extends Error {
|
|
46
|
+
readonly verdict: HookDenial;
|
|
47
|
+
constructor(verdict: HookDenial);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Image generation calls (image generation spec §5.1, §5.2, §5.6, §6), shared by the
|
|
51
|
+
* `GenerateImage` tool and `ctx.models.generateImage`:
|
|
52
|
+
* - {@link prepare} resolves the org's target for a purpose of kind `image_generation` (no
|
|
53
|
+
* fallback: unmapped is `model.unconfigured`), checks the prompt (code points, at most
|
|
54
|
+
* `models.imagePromptMaxChars`), the count (at most `models.imageMaxPerCall` and the model's
|
|
55
|
+
* `maxImages`), the reference images (count, media type, `MEDIA_LIMITS.imageBytes`), picks the
|
|
56
|
+
* size ({@link pickImageSize}) and sanitizes the mapping's params against the model's
|
|
57
|
+
* declarations. Every refusal is `ApiError("validation_failed")` with an actionable text.
|
|
58
|
+
* - {@link run} fires `model.request` (placeholders for references; a denial throws
|
|
59
|
+
* {@link ImageCallDenied} and sends nothing), calls `generateImage` within
|
|
60
|
+
* `models.imageTimeoutMs`, checks the result ({@link validateImageGenerateResult}: invalid is a
|
|
61
|
+
* `ModelError("server")`) and fires `model.response` (observe; media types and byte sizes, never
|
|
62
|
+
* bytes), also when the call failed, but not when the caller's signal aborted it.
|
|
63
|
+
* They store nothing and record no usage: the callers do. For extensions (spec §5.5, §8, §9),
|
|
64
|
+
* {@link generateForExtension} is `ctx.models.generateImage`: the admission of `ctx.models.embed`
|
|
65
|
+
* for kind `image_generation` (a purpose the extension declared with that kind, otherwise
|
|
66
|
+
* `model.purpose_unknown`; an org that enabled the extension, otherwise `extension.not_enabled`),
|
|
67
|
+
* then {@link prepare} and {@link run}; a policy denial writes one `hook.denied` audit row and
|
|
68
|
+
* rejects with `ApiError("model.hook_denied")`; a successful call writes one `model_usage` row
|
|
69
|
+
* (`kind = 'image_generation'`, its input tokens and images) and owes its `usage.report` delivery
|
|
70
|
+
* in the same transaction ({@link recordExtensionUsage}). A call that fails or is denied records
|
|
71
|
+
* no usage. The kernel stores no image of an extension call: the extension gets the bytes.
|
|
72
|
+
*/
|
|
73
|
+
export declare class ModelImages {
|
|
74
|
+
private readonly purposes;
|
|
75
|
+
private readonly providers;
|
|
76
|
+
private readonly log;
|
|
77
|
+
/** `models.imageTimeoutMs`, `imageMaxPerCall`, `imagePromptMaxChars` (hot, read per call). */
|
|
78
|
+
private readonly config;
|
|
79
|
+
private readonly kdb;
|
|
80
|
+
readonly txHost: TransactionHost;
|
|
81
|
+
/** An extension call's `usage.report` delivery, owed with its `model_usage` row. */
|
|
82
|
+
private readonly usage;
|
|
83
|
+
constructor(purposes: Pick<ModelPurposesService, "resolve">, providers: Pick<ProviderRegistry, "resolve">, log: Pick<Logger, "warn">,
|
|
84
|
+
/** `models.imageTimeoutMs`, `imageMaxPerCall`, `imagePromptMaxChars` (hot, read per call). */
|
|
85
|
+
config: Pick<KernelConfigService, "get">, kdb: KernelDb, txHost: TransactionHost,
|
|
86
|
+
/** An extension call's `usage.report` delivery, owed with its `model_usage` row. */
|
|
87
|
+
usage: Pick<UsageReportJobs, "oweModelUsage">);
|
|
88
|
+
/** Refuses a purpose `plugin` did not declare with kind `image_generation`, or an org it is off in. */
|
|
89
|
+
private admit;
|
|
90
|
+
/**
|
|
91
|
+
* `ctx.models.generateImage` for `plugin` (its declared purposes), aborted by `signal` (the
|
|
92
|
+
* instance's) and the request's own signal; `hooks` is the host's hook registry
|
|
93
|
+
* (`model.request`, `model.response`), absent only for a ctx built without a host (tests).
|
|
94
|
+
*/
|
|
95
|
+
generateForExtension(plugin: string, declared: DeclaredModelPurposes, request: ExtensionImageGenerateRequest, signal: AbortSignal, hooks: HookRunner | undefined): Promise<ExtensionImageGenerateResult>;
|
|
96
|
+
/**
|
|
97
|
+
* `ctx.models.describe` of an image generation purpose for `plugin`: the org's effective target
|
|
98
|
+
* with its `imageGeneration` facts, or null when the purpose maps to no model the org can use.
|
|
99
|
+
*/
|
|
100
|
+
describeForExtension(plugin: string, declared: DeclaredModelPurposes, req: {
|
|
101
|
+
orgId: string;
|
|
102
|
+
purpose: string;
|
|
103
|
+
}): Promise<ExtensionModelTarget | null>;
|
|
104
|
+
/**
|
|
105
|
+
* One `model_usage` row of an extension call (`kind = 'image_generation'`, the result's tokens
|
|
106
|
+
* and images) with its owed `usage.report` delivery, in one transaction.
|
|
107
|
+
*/
|
|
108
|
+
private recordExtensionUsage;
|
|
109
|
+
prepare(orgId: string, purpose: string, input: ImageCallInput): Promise<PreparedImageCall>;
|
|
110
|
+
run(orgId: string, prepared: PreparedImageCall, who: ImageHookIdentity, signal: AbortSignal, hooks: HookRunner | undefined): Promise<ImageGenerateResult & {
|
|
111
|
+
latencyMs: number;
|
|
112
|
+
}>;
|
|
113
|
+
/**
|
|
114
|
+
* One `generateImage` call, limited by `models.imageTimeoutMs` (hot, read per call): at the limit
|
|
115
|
+
* the call's signal aborts and the call fails with `ModelError("timeout")`, even when the
|
|
116
|
+
* provider ignores the signal (its late answer is dropped).
|
|
117
|
+
*/
|
|
118
|
+
private callWithTimeout;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* The images a validated answer is billed for: the answer's own `usage.outputImages`, else the
|
|
122
|
+
* images it carries, never more than it carries (a vendor count above them is not trusted). The
|
|
123
|
+
* one rule of the tool's `usage` event and an extension call's `model_usage` row.
|
|
124
|
+
*/
|
|
125
|
+
export declare function billedImages(res: Pick<ImageGenerateResult, "images" | "usage">): number;
|