@capybara-hq/kernel 0.1.0-rc.8 → 0.1.0-rc.9
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/dist/background/finish.js +2 -1
- package/dist/background/launch.d.ts +13 -7
- package/dist/background/launch.js +15 -8
- package/dist/background/poll.job.d.ts +1 -1
- package/dist/background/poll.job.js +8 -3
- package/dist/background/session.d.ts +2 -2
- package/dist/background/session.js +3 -2
- package/dist/background/status.d.ts +1 -1
- package/dist/background/status.js +1 -1
- package/dist/background/stop.js +4 -3
- package/dist/background/store.d.ts +6 -1
- package/dist/background/store.js +5 -1
- package/dist/background/tasks.service.d.ts +1 -1
- package/dist/background/tasks.service.js +4 -4
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/docs.js +2 -0
- package/dist/config/schema.d.ts +7 -0
- package/dist/config/schema.js +45 -0
- package/dist/conversations/event-log.d.ts +4 -3
- package/dist/conversations/event-log.js +4 -3
- package/dist/conversations/events.d.ts +9 -0
- package/dist/conversations/events.js +14 -0
- package/dist/db/kernel-schema.d.ts +26 -1
- package/dist/devices/device-auth.controller.d.ts +42 -0
- package/dist/devices/device-auth.controller.js +116 -0
- package/dist/devices/device-auth.d.ts +119 -0
- package/dist/devices/device-auth.js +403 -0
- package/dist/devices/device-auth.module.d.ts +7 -0
- package/dist/devices/device-auth.module.js +25 -0
- package/dist/devices/device-gateway.d.ts +128 -0
- package/dist/devices/device-gateway.js +530 -0
- package/dist/devices/device-provider.d.ts +89 -0
- package/dist/devices/device-provider.js +151 -0
- package/dist/devices/device-routes.d.ts +36 -0
- package/dist/devices/device-routes.js +90 -0
- package/dist/devices/devices.module.d.ts +16 -0
- package/dist/devices/devices.module.js +44 -0
- package/dist/devices/dto.d.ts +66 -0
- package/dist/devices/dto.js +44 -0
- package/dist/devices/keys.d.ts +25 -0
- package/dist/devices/keys.js +25 -0
- package/dist/devices/machines.d.ts +106 -0
- package/dist/devices/machines.js +301 -0
- package/dist/devices/relay.d.ts +100 -0
- package/dist/devices/relay.js +373 -0
- package/dist/devices/targets.d.ts +28 -0
- package/dist/devices/targets.js +73 -0
- package/dist/environments/access.d.ts +11 -6
- package/dist/environments/access.js +23 -8
- package/dist/environments/conversation-environments.d.ts +20 -6
- package/dist/environments/conversation-environments.js +70 -9
- package/dist/environments/environments.controller.d.ts +4 -1
- package/dist/environments/environments.controller.js +15 -1
- package/dist/environments/environments.module.js +3 -1
- package/dist/environments/environments.service.d.ts +54 -7
- package/dist/environments/environments.service.js +104 -20
- package/dist/environments/legacy-cleanup.job.d.ts +1 -1
- package/dist/environments/legacy-cleanup.job.js +4 -4
- package/dist/errors.d.ts +24 -0
- package/dist/errors.js +24 -0
- package/dist/evals/recorded-tools.d.ts +9 -0
- package/dist/evals/recorded-tools.js +27 -0
- package/dist/http/api.module.js +4 -0
- package/dist/http/gateway-routes.d.ts +7 -3
- package/dist/http/gateway-routes.js +6 -3
- package/dist/infra/config/kernel-config.service.js +2 -0
- package/dist/infra/throttler/named-throttlers.d.ts +5 -0
- package/dist/infra/throttler/named-throttlers.js +38 -0
- package/dist/kernel.module.js +3 -0
- package/dist/lifecycle/kernel-lifecycle.js +5 -0
- package/dist/platform/exclusions.js +33 -0
- package/dist/platform/ops/environments.ops.js +21 -3
- package/dist/roles/gateway-role.d.ts +14 -3
- package/dist/roles/gateway-role.js +25 -5
- package/dist/roles/gateway.module.d.ts +2 -1
- package/dist/roles/gateway.module.js +6 -3
- package/dist/runtime/context/build.d.ts +2 -0
- package/dist/runtime/context/build.js +14 -0
- package/dist/runtime/context/compaction.js +1 -0
- package/dist/runtime/context/environment-paths.d.ts +40 -0
- package/dist/runtime/context/environment-paths.js +48 -0
- package/dist/runtime/model-call.js +2 -0
- package/dist/sandbox/providers.d.ts +29 -7
- package/dist/sandbox/providers.js +43 -8
- package/dist/sandbox/sandbox.service.d.ts +70 -18
- package/dist/sandbox/sandbox.service.js +176 -59
- package/dist/tools/builtins/sandbox/bash.d.ts +2 -2
- package/dist/tools/builtins/sandbox/bash.js +39 -27
- package/dist/tools/builtins/sandbox/common.d.ts +60 -25
- package/dist/tools/builtins/sandbox/common.js +121 -30
- package/dist/tools/builtins/sandbox/deliver.js +9 -6
- package/dist/tools/builtins/sandbox/edit.js +40 -37
- package/dist/tools/builtins/sandbox/glob.js +13 -8
- package/dist/tools/builtins/sandbox/grep.js +10 -6
- package/dist/tools/builtins/sandbox/index.d.ts +6 -4
- package/dist/tools/builtins/sandbox/index.js +6 -4
- package/dist/tools/builtins/sandbox/read.js +9 -6
- package/dist/tools/builtins/sandbox/task-output.d.ts +7 -3
- package/dist/tools/builtins/sandbox/task-output.js +14 -10
- package/dist/tools/builtins/sandbox/task-stop.js +3 -3
- package/dist/tools/builtins/sandbox/write.js +33 -30
- package/dist/tools/builtins/skill-load.d.ts +8 -5
- package/dist/tools/builtins/skill-load.js +21 -15
- package/dist/tools/builtins/skill-write.js +2 -2
- package/dist/tools/pipeline.js +2 -0
- package/dist/tools/registry.d.ts +21 -4
- package/dist/tools/registry.js +10 -2
- package/package.json +5 -2
- package/src/migrations/0093_connected_environments.sql +37 -0
- package/src/migrations/0094_environment_paths_idx.sql +7 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { DeviceHello, DeviceStopArgs, ExtensionContext } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
3
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
4
|
+
import type { KernelLogger } from "../log.js";
|
|
5
|
+
import { DeviceRelay } from "./relay.js";
|
|
6
|
+
/** The machine credential's prefix (`cap_dev_` plus 32 random bytes, base64url). */
|
|
7
|
+
export declare const MACHINE_CREDENTIAL_PREFIX = "cap_dev_";
|
|
8
|
+
/** What a machine credential stands for. */
|
|
9
|
+
export interface MachineIdentity {
|
|
10
|
+
machineId: string;
|
|
11
|
+
orgId: string;
|
|
12
|
+
environmentId: string;
|
|
13
|
+
accountId: string;
|
|
14
|
+
}
|
|
15
|
+
/** The machine connected to an environment (its unrevoked row). */
|
|
16
|
+
export interface ActiveMachine {
|
|
17
|
+
id: string;
|
|
18
|
+
orgId: string;
|
|
19
|
+
accountId: string;
|
|
20
|
+
name: string;
|
|
21
|
+
os: string;
|
|
22
|
+
arch: string;
|
|
23
|
+
programVersion: string | null;
|
|
24
|
+
lastSeenAt: Date | null;
|
|
25
|
+
createdAt: Date;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Connected machines and their credentials (environments spec §13.2). One active machine per
|
|
29
|
+
* device environment: issuing a credential revokes the environment's previous machine. A
|
|
30
|
+
* credential is `cap_dev_` plus 32 random bytes; only its sha256 is stored. It is accepted only
|
|
31
|
+
* by the device connection route ({@link authenticate}), never by `/api`: it is no `Principal`.
|
|
32
|
+
*
|
|
33
|
+
* A revoked machine is told so after the commit: `stop { reason }` relayed while a replica holds
|
|
34
|
+
* its connection (fire-and-forget, ruling R14) and `device.revoked.<environmentId>` published with
|
|
35
|
+
* `{ machineId }`, so the holder closes that machine's connection.
|
|
36
|
+
*/
|
|
37
|
+
export declare class MachinesService {
|
|
38
|
+
private readonly db;
|
|
39
|
+
readonly txHost: TransactionHost;
|
|
40
|
+
private readonly relay;
|
|
41
|
+
private readonly bus;
|
|
42
|
+
private readonly log;
|
|
43
|
+
constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<DeviceRelay, "holderLive" | "send">, bus: ExtensionContext["bus"], log: Pick<KernelLogger, "warn">);
|
|
44
|
+
/**
|
|
45
|
+
* A new machine for the environment and its credential (returned once). Revokes the
|
|
46
|
+
* environment's active machine first. Joins the caller's transaction (the device confirmation),
|
|
47
|
+
* which has already checked the environment is the person's own live device environment.
|
|
48
|
+
*/
|
|
49
|
+
issue(input: {
|
|
50
|
+
orgId: string;
|
|
51
|
+
environmentId: string;
|
|
52
|
+
accountId: string;
|
|
53
|
+
name: string;
|
|
54
|
+
os: string;
|
|
55
|
+
arch: string;
|
|
56
|
+
programVersion: string;
|
|
57
|
+
}): Promise<{
|
|
58
|
+
machineId: string;
|
|
59
|
+
credential: string;
|
|
60
|
+
}>;
|
|
61
|
+
/**
|
|
62
|
+
* Ruling R23: the new machine may serve the environment from another directory or mode (other
|
|
63
|
+
* roots), and a login recreates a directory that was lost (ruling R24). So the instance row
|
|
64
|
+
* forgets its instance (status `none`, no handle) and its files count as there again; the next
|
|
65
|
+
* use creates a fresh instance on the machine (with its roots: a new `environment_paths` event
|
|
66
|
+
* follows). The fence moves on, so a lifecycle holder of the old instance fails its next write.
|
|
67
|
+
*/
|
|
68
|
+
private resetInstance;
|
|
69
|
+
/**
|
|
70
|
+
* Who a machine credential stands for, or null: the machine is not revoked, its environment is
|
|
71
|
+
* live, the org is not deleted (ruling R12), and the person is an active account still a member
|
|
72
|
+
* of the org. Read live on every call (a connection re-checks it as it sees fit).
|
|
73
|
+
*/
|
|
74
|
+
authenticate(credential: string): Promise<MachineIdentity | null>;
|
|
75
|
+
/** Stores what the program reported in its hello frame and marks the machine seen. */
|
|
76
|
+
recordHello(machineId: string, hello: DeviceHello): Promise<void>;
|
|
77
|
+
/** Marks the machine seen (a ping); writes at most once every 60 seconds. */
|
|
78
|
+
touch(machineId: string): Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* Disconnects the machine of one of the person's own live device environments (`DELETE
|
|
81
|
+
* /orgs/:orgId/environments/:id/machine`): revokes it and audits
|
|
82
|
+
* `environment.machine_revoked`. Anyone else's environment, a cloud one or a missing one →
|
|
83
|
+
* `environment.not_found`; no machine connected is a no-op.
|
|
84
|
+
*/
|
|
85
|
+
revoke(orgId: string, accountId: string, environmentId: string, actorTokenId?: string): Promise<void>;
|
|
86
|
+
/**
|
|
87
|
+
* Revokes the environment's active machine, if any, in the caller's transaction, and after the
|
|
88
|
+
* commit tells it to stop for `reason` (none: only its connection is closed) and closes its
|
|
89
|
+
* connection. Returns the revoked machine's id. Used by {@link issue} (replaced: no stop),
|
|
90
|
+
* {@link revoke} and the environment's deletion (`deleted`).
|
|
91
|
+
*/
|
|
92
|
+
revokeActive(environmentId: string, reason: DeviceStopArgs["reason"] | null): Promise<string | null>;
|
|
93
|
+
/**
|
|
94
|
+
* Revokes one machine by id (a sign-in whose credential never reached the program), with the
|
|
95
|
+
* same post-commit disconnect as a replacement (no stop frame). True when it was active.
|
|
96
|
+
*/
|
|
97
|
+
revokeMachine(machineId: string): Promise<boolean>;
|
|
98
|
+
/** The environment's active machine, or null. */
|
|
99
|
+
activeFor(environmentId: string): Promise<ActiveMachine | null>;
|
|
100
|
+
/**
|
|
101
|
+
* After a revocation commits: `stop` is queued only while a replica holds the connection (an
|
|
102
|
+
* offline machine must not find it on the list later), then the revocation is published.
|
|
103
|
+
* Failures are logged; the revocation itself stands.
|
|
104
|
+
*/
|
|
105
|
+
private disconnect;
|
|
106
|
+
}
|
|
@@ -0,0 +1,301 @@
|
|
|
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 { randomBytes } from "node:crypto";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { sql } from "kysely";
|
|
13
|
+
import { audit } from "../identity/audit.js";
|
|
14
|
+
import { sha256Hex } from "../identity/hash.js";
|
|
15
|
+
import { afterCommit } from "../infra/database/after-commit.js";
|
|
16
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
17
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
18
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
19
|
+
import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
|
|
20
|
+
import { DEVICE_PROVIDER } from "../sandbox/providers.js";
|
|
21
|
+
import { environmentNotFound } from "../sandbox/sandbox.service.js";
|
|
22
|
+
import { deviceRevokedTopic } from "./keys.js";
|
|
23
|
+
import { DeviceRelay } from "./relay.js";
|
|
24
|
+
/** The machine credential's prefix (`cap_dev_` plus 32 random bytes, base64url). */
|
|
25
|
+
export const MACHINE_CREDENTIAL_PREFIX = "cap_dev_";
|
|
26
|
+
const CREDENTIAL_RE = /^cap_dev_[A-Za-z0-9_-]{43}$/;
|
|
27
|
+
/** How long the `stop` frame told to a revoked machine may take (it only closes the connection). */
|
|
28
|
+
const STOP_DEADLINE_MS = 30_000;
|
|
29
|
+
/**
|
|
30
|
+
* Connected machines and their credentials (environments spec §13.2). One active machine per
|
|
31
|
+
* device environment: issuing a credential revokes the environment's previous machine. A
|
|
32
|
+
* credential is `cap_dev_` plus 32 random bytes; only its sha256 is stored. It is accepted only
|
|
33
|
+
* by the device connection route ({@link authenticate}), never by `/api`: it is no `Principal`.
|
|
34
|
+
*
|
|
35
|
+
* A revoked machine is told so after the commit: `stop { reason }` relayed while a replica holds
|
|
36
|
+
* its connection (fire-and-forget, ruling R14) and `device.revoked.<environmentId>` published with
|
|
37
|
+
* `{ machineId }`, so the holder closes that machine's connection.
|
|
38
|
+
*/
|
|
39
|
+
let MachinesService = class MachinesService {
|
|
40
|
+
db;
|
|
41
|
+
txHost;
|
|
42
|
+
relay;
|
|
43
|
+
bus;
|
|
44
|
+
log;
|
|
45
|
+
constructor(db, txHost, relay, bus, log) {
|
|
46
|
+
this.db = db;
|
|
47
|
+
this.txHost = txHost;
|
|
48
|
+
this.relay = relay;
|
|
49
|
+
this.bus = bus;
|
|
50
|
+
this.log = log;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A new machine for the environment and its credential (returned once). Revokes the
|
|
54
|
+
* environment's active machine first. Joins the caller's transaction (the device confirmation),
|
|
55
|
+
* which has already checked the environment is the person's own live device environment.
|
|
56
|
+
*/
|
|
57
|
+
async issue(input) {
|
|
58
|
+
// no stop frame: it would wait on the list and could reach the replacement machine instead
|
|
59
|
+
await this.revokeActive(input.environmentId, null);
|
|
60
|
+
await this.resetInstance(input.environmentId);
|
|
61
|
+
const credential = MACHINE_CREDENTIAL_PREFIX + randomBytes(32).toString("base64url");
|
|
62
|
+
const row = await this.db
|
|
63
|
+
.insertInto("environment_machines")
|
|
64
|
+
.values({
|
|
65
|
+
org_id: input.orgId,
|
|
66
|
+
environment_id: input.environmentId,
|
|
67
|
+
account_id: input.accountId,
|
|
68
|
+
credential_hash: sha256Hex(credential),
|
|
69
|
+
name: input.name,
|
|
70
|
+
os: input.os,
|
|
71
|
+
arch: input.arch,
|
|
72
|
+
program_version: input.programVersion,
|
|
73
|
+
})
|
|
74
|
+
.returning("id")
|
|
75
|
+
.executeTakeFirstOrThrow();
|
|
76
|
+
return { machineId: row.id, credential };
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Ruling R23: the new machine may serve the environment from another directory or mode (other
|
|
80
|
+
* roots), and a login recreates a directory that was lost (ruling R24). So the instance row
|
|
81
|
+
* forgets its instance (status `none`, no handle) and its files count as there again; the next
|
|
82
|
+
* use creates a fresh instance on the machine (with its roots: a new `environment_paths` event
|
|
83
|
+
* follows). The fence moves on, so a lifecycle holder of the old instance fails its next write.
|
|
84
|
+
*/
|
|
85
|
+
async resetInstance(environmentId) {
|
|
86
|
+
await this.db
|
|
87
|
+
.updateTable("environment_instances")
|
|
88
|
+
.set((eb) => ({
|
|
89
|
+
status: "none",
|
|
90
|
+
handle: null,
|
|
91
|
+
fs_status: sql `CASE WHEN fs_handle IS NULL THEN 'none' ELSE 'ready' END`,
|
|
92
|
+
running_since: null,
|
|
93
|
+
suspended_at: null,
|
|
94
|
+
destroyed_at: sql `now()`,
|
|
95
|
+
generation: eb("generation", "+", 1),
|
|
96
|
+
}))
|
|
97
|
+
.where("environment_id", "=", environmentId)
|
|
98
|
+
.execute();
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Who a machine credential stands for, or null: the machine is not revoked, its environment is
|
|
102
|
+
* live, the org is not deleted (ruling R12), and the person is an active account still a member
|
|
103
|
+
* of the org. Read live on every call (a connection re-checks it as it sees fit).
|
|
104
|
+
*/
|
|
105
|
+
async authenticate(credential) {
|
|
106
|
+
if (!CREDENTIAL_RE.test(credential))
|
|
107
|
+
return null;
|
|
108
|
+
const row = await this.db
|
|
109
|
+
.selectFrom("environment_machines as m")
|
|
110
|
+
.innerJoin("environments as e", "e.id", "m.environment_id")
|
|
111
|
+
.innerJoin("orgs as o", "o.id", "m.org_id")
|
|
112
|
+
.innerJoin("memberships as ms", (j) => j.onRef("ms.org_id", "=", "m.org_id").onRef("ms.account_id", "=", "m.account_id"))
|
|
113
|
+
.innerJoin("accounts as a", "a.id", "m.account_id")
|
|
114
|
+
.select(["m.id", "m.org_id", "m.environment_id", "m.account_id"])
|
|
115
|
+
.where("m.credential_hash", "=", sha256Hex(credential))
|
|
116
|
+
.where("m.revoked_at", "is", null)
|
|
117
|
+
.whereRef("e.org_id", "=", "m.org_id")
|
|
118
|
+
.where("e.deleted_at", "is", null)
|
|
119
|
+
.where("e.source", "=", "device")
|
|
120
|
+
.where("o.deleted_at", "is", null)
|
|
121
|
+
.where("a.status", "=", "active")
|
|
122
|
+
.executeTakeFirst();
|
|
123
|
+
return row
|
|
124
|
+
? {
|
|
125
|
+
machineId: row.id,
|
|
126
|
+
orgId: row.org_id,
|
|
127
|
+
environmentId: row.environment_id,
|
|
128
|
+
accountId: row.account_id,
|
|
129
|
+
}
|
|
130
|
+
: null;
|
|
131
|
+
}
|
|
132
|
+
/** Stores what the program reported in its hello frame and marks the machine seen. */
|
|
133
|
+
async recordHello(machineId, hello) {
|
|
134
|
+
await this.db
|
|
135
|
+
.updateTable("environment_machines")
|
|
136
|
+
.set({
|
|
137
|
+
program_version: hello.programVersion,
|
|
138
|
+
os: hello.os,
|
|
139
|
+
arch: hello.arch,
|
|
140
|
+
mode: hello.mode,
|
|
141
|
+
roots: JSON.stringify(hello.roots),
|
|
142
|
+
session_isolation: hello.sessionIsolation,
|
|
143
|
+
last_seen_at: sql `now()`,
|
|
144
|
+
})
|
|
145
|
+
.where("id", "=", machineId)
|
|
146
|
+
.where("revoked_at", "is", null)
|
|
147
|
+
.execute();
|
|
148
|
+
}
|
|
149
|
+
/** Marks the machine seen (a ping); writes at most once every 60 seconds. */
|
|
150
|
+
async touch(machineId) {
|
|
151
|
+
await this.db
|
|
152
|
+
.updateTable("environment_machines")
|
|
153
|
+
.set({ last_seen_at: sql `now()` })
|
|
154
|
+
.where("id", "=", machineId)
|
|
155
|
+
.where("revoked_at", "is", null)
|
|
156
|
+
.where((eb) => eb.or([
|
|
157
|
+
eb("last_seen_at", "is", null),
|
|
158
|
+
eb("last_seen_at", "<", sql `now() - interval '60 seconds'`),
|
|
159
|
+
]))
|
|
160
|
+
.execute();
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Disconnects the machine of one of the person's own live device environments (`DELETE
|
|
164
|
+
* /orgs/:orgId/environments/:id/machine`): revokes it and audits
|
|
165
|
+
* `environment.machine_revoked`. Anyone else's environment, a cloud one or a missing one →
|
|
166
|
+
* `environment.not_found`; no machine connected is a no-op.
|
|
167
|
+
*/
|
|
168
|
+
async revoke(orgId, accountId, environmentId, actorTokenId) {
|
|
169
|
+
const env = await this.db
|
|
170
|
+
.selectFrom("environments")
|
|
171
|
+
.select("id")
|
|
172
|
+
.where("id", "=", environmentId)
|
|
173
|
+
.where("org_id", "=", orgId)
|
|
174
|
+
.where("owner_kind", "=", "personal")
|
|
175
|
+
.where("owner_account_id", "=", accountId)
|
|
176
|
+
.where("source", "=", "device")
|
|
177
|
+
.where("provider", "=", DEVICE_PROVIDER)
|
|
178
|
+
.where("deleted_at", "is", null)
|
|
179
|
+
.forNoKeyUpdate()
|
|
180
|
+
.executeTakeFirst();
|
|
181
|
+
if (!env)
|
|
182
|
+
throw environmentNotFound();
|
|
183
|
+
const machineId = await this.revokeActive(environmentId, "revoked");
|
|
184
|
+
if (machineId === null)
|
|
185
|
+
return;
|
|
186
|
+
await audit(this.db.db, {
|
|
187
|
+
actorAccountId: accountId,
|
|
188
|
+
...(actorTokenId !== undefined && { actorTokenId }),
|
|
189
|
+
orgId,
|
|
190
|
+
action: "environment.machine_revoked",
|
|
191
|
+
target: environmentId,
|
|
192
|
+
detail: { machineId },
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Revokes the environment's active machine, if any, in the caller's transaction, and after the
|
|
197
|
+
* commit tells it to stop for `reason` (none: only its connection is closed) and closes its
|
|
198
|
+
* connection. Returns the revoked machine's id. Used by {@link issue} (replaced: no stop),
|
|
199
|
+
* {@link revoke} and the environment's deletion (`deleted`).
|
|
200
|
+
*/
|
|
201
|
+
async revokeActive(environmentId, reason) {
|
|
202
|
+
const row = await this.db
|
|
203
|
+
.updateTable("environment_machines")
|
|
204
|
+
.set({ revoked_at: sql `now()` })
|
|
205
|
+
.where("environment_id", "=", environmentId)
|
|
206
|
+
.where("revoked_at", "is", null)
|
|
207
|
+
.returning("id")
|
|
208
|
+
.executeTakeFirst();
|
|
209
|
+
if (!row)
|
|
210
|
+
return null;
|
|
211
|
+
const machineId = row.id;
|
|
212
|
+
afterCommit(() => this.disconnect(environmentId, machineId, reason));
|
|
213
|
+
return machineId;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Revokes one machine by id (a sign-in whose credential never reached the program), with the
|
|
217
|
+
* same post-commit disconnect as a replacement (no stop frame). True when it was active.
|
|
218
|
+
*/
|
|
219
|
+
async revokeMachine(machineId) {
|
|
220
|
+
const row = await this.db
|
|
221
|
+
.updateTable("environment_machines")
|
|
222
|
+
.set({ revoked_at: sql `now()` })
|
|
223
|
+
.where("id", "=", machineId)
|
|
224
|
+
.where("revoked_at", "is", null)
|
|
225
|
+
.returning("environment_id")
|
|
226
|
+
.executeTakeFirst();
|
|
227
|
+
if (!row)
|
|
228
|
+
return false;
|
|
229
|
+
const environmentId = row.environment_id;
|
|
230
|
+
afterCommit(() => this.disconnect(environmentId, machineId, null));
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
/** The environment's active machine, or null. */
|
|
234
|
+
async activeFor(environmentId) {
|
|
235
|
+
const r = await this.db
|
|
236
|
+
.selectFrom("environment_machines")
|
|
237
|
+
.select([
|
|
238
|
+
"id",
|
|
239
|
+
"org_id",
|
|
240
|
+
"account_id",
|
|
241
|
+
"name",
|
|
242
|
+
"os",
|
|
243
|
+
"arch",
|
|
244
|
+
"program_version",
|
|
245
|
+
"last_seen_at",
|
|
246
|
+
"created_at",
|
|
247
|
+
])
|
|
248
|
+
.where("environment_id", "=", environmentId)
|
|
249
|
+
.where("revoked_at", "is", null)
|
|
250
|
+
.executeTakeFirst();
|
|
251
|
+
return r
|
|
252
|
+
? {
|
|
253
|
+
id: r.id,
|
|
254
|
+
orgId: r.org_id,
|
|
255
|
+
accountId: r.account_id,
|
|
256
|
+
name: r.name,
|
|
257
|
+
os: r.os,
|
|
258
|
+
arch: r.arch,
|
|
259
|
+
programVersion: r.program_version,
|
|
260
|
+
lastSeenAt: r.last_seen_at,
|
|
261
|
+
createdAt: r.created_at,
|
|
262
|
+
}
|
|
263
|
+
: null;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* After a revocation commits: `stop` is queued only while a replica holds the connection (an
|
|
267
|
+
* offline machine must not find it on the list later), then the revocation is published.
|
|
268
|
+
* Failures are logged; the revocation itself stands.
|
|
269
|
+
*/
|
|
270
|
+
async disconnect(environmentId, machineId, reason) {
|
|
271
|
+
try {
|
|
272
|
+
if (reason !== null && (await this.relay.holderLive(environmentId))) {
|
|
273
|
+
await this.relay.send(environmentId, "stop", { reason }, STOP_DEADLINE_MS);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
catch (err) {
|
|
277
|
+
this.log.warn("could not tell a revoked machine to stop", { environmentId, machineId, err });
|
|
278
|
+
}
|
|
279
|
+
try {
|
|
280
|
+
await this.bus.publish(deviceRevokedTopic(environmentId), { machineId });
|
|
281
|
+
}
|
|
282
|
+
catch (err) {
|
|
283
|
+
this.log.warn("could not publish a machine revocation", { environmentId, machineId, err });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
__decorate([
|
|
288
|
+
Transactional()
|
|
289
|
+
], MachinesService.prototype, "issue", null);
|
|
290
|
+
__decorate([
|
|
291
|
+
Transactional()
|
|
292
|
+
], MachinesService.prototype, "revoke", null);
|
|
293
|
+
MachinesService = __decorate([
|
|
294
|
+
Injectable(),
|
|
295
|
+
__param(0, Inject(KernelDb)),
|
|
296
|
+
__param(1, Inject(TransactionHost)),
|
|
297
|
+
__param(2, Inject(DeviceRelay)),
|
|
298
|
+
__param(3, Inject(KERNEL_BUS)),
|
|
299
|
+
__param(4, Inject(KERNEL_LOGGER))
|
|
300
|
+
], MachinesService);
|
|
301
|
+
export { MachinesService };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { type DeviceOp, type DeviceOpResults, type ExtensionContext } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { Redis } from "ioredis";
|
|
3
|
+
import { ApiError } from "../errors.js";
|
|
4
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
5
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
6
|
+
import type { KernelLogger } from "../log.js";
|
|
7
|
+
import { DeviceTargets } from "./targets.js";
|
|
8
|
+
/** The environment's connected machine is not connected (no replica holds its lease). */
|
|
9
|
+
export declare const environmentOffline: () => ApiError;
|
|
10
|
+
/**
|
|
11
|
+
* The environment's machine was disconnected (revoked, signed out): 403 `environment.forbidden`
|
|
12
|
+
* with `details: [{ reason: "machine_revoked" }]`, so the tools tell the model what to ask for.
|
|
13
|
+
*/
|
|
14
|
+
export declare const machineRevoked: () => ApiError;
|
|
15
|
+
/** The text a machine's `error` result reaches the model with (ruling R28). */
|
|
16
|
+
export declare const ON_MACHINE_PREFIX = "On the connected machine: ";
|
|
17
|
+
/** The longest one lease check of a waiting caller may take before it counts as "unknown". */
|
|
18
|
+
export declare const LEASE_CHECK_TIMEOUT_MS = 2000;
|
|
19
|
+
/** How often a waiting caller checks that a replica still holds the machine's connection. */
|
|
20
|
+
export declare const HOLDER_POLL_MS = 5000;
|
|
21
|
+
/**
|
|
22
|
+
* How much longer than the caller's wait a queued request lives: giving up must still find an
|
|
23
|
+
* untaken request on the list (an expired one would look taken and get a needless cancel).
|
|
24
|
+
*/
|
|
25
|
+
export declare const LIST_TTL_MARGIN_MS = 30000;
|
|
26
|
+
export interface DeviceCallOptions {
|
|
27
|
+
/** How long the machine may take for the operation (sent to it as `deadlineMs`). */
|
|
28
|
+
deadlineMs: number;
|
|
29
|
+
/** The caller's signal: aborting gives the request up and rejects. */
|
|
30
|
+
signal: AbortSignal;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The caller side of the device relay (environments spec §13.4). A request goes onto the
|
|
34
|
+
* environment's Redis list (`capk:device-req:<environmentId>`) and is announced on
|
|
35
|
+
* `device.req.<environmentId>`; whichever gateway replica holds the machine's lease drains the
|
|
36
|
+
* list and forwards the frames to the machine.
|
|
37
|
+
*
|
|
38
|
+
* **The holder's half of the wire** (Task 6 follows it): items on the list are `KernelReq` or
|
|
39
|
+
* `KernelCancel` frames as JSON text, to be parsed with `parseDeviceFrame(item, "kernel")`; the
|
|
40
|
+
* nudge's payload is `{ id }`. For each `res` frame the machine sends, the holder writes the frame
|
|
41
|
+
* (the JSON text as validated by `parseDeviceFrame(…, "device")`) under
|
|
42
|
+
* `capk:device-res:<requestId>` with a TTL and publishes the same frame object on
|
|
43
|
+
* `device.res.<requestId>`.
|
|
44
|
+
*
|
|
45
|
+
* The caller subscribes to its result topic before pushing and reads the result key once after,
|
|
46
|
+
* and once more before giving up (the run-abort pattern; a publish lost while the subscriber
|
|
47
|
+
* reconnects is still found). It waits within its own call for at most `deadlineMs` plus
|
|
48
|
+
* `environments.device.reconnectGraceSeconds`; when the lease disappears meanwhile (checked every
|
|
49
|
+
* {@link HOLDER_POLL_MS}) the wait ends at most one grace later. A result produced while the
|
|
50
|
+
* machine was disconnected arrives after it reconnects. Giving up (grace, abort, a bad result)
|
|
51
|
+
* removes the request from the list, or queues a `cancel` when the machine already took it
|
|
52
|
+
* (ruling R15). Nothing is kept in process memory beyond the call.
|
|
53
|
+
*/
|
|
54
|
+
export declare class DeviceRelay {
|
|
55
|
+
private readonly redis;
|
|
56
|
+
private readonly bus;
|
|
57
|
+
private readonly locks;
|
|
58
|
+
private readonly config;
|
|
59
|
+
private readonly log;
|
|
60
|
+
private readonly targets;
|
|
61
|
+
constructor(redis: Redis, bus: ExtensionContext["bus"], locks: Pick<LockService, "holderOf">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn">, targets: Pick<DeviceTargets, "state">);
|
|
62
|
+
/** Whether a gateway replica holds the machine's connection now. */
|
|
63
|
+
holderLive(environmentId: string): Promise<boolean>;
|
|
64
|
+
/**
|
|
65
|
+
* Queues `op` for the machine without waiting for an answer (ruling R14: `stop`). The caller
|
|
66
|
+
* checks {@link holderLive} first; the frame waits on the list for the grace like any request.
|
|
67
|
+
*/
|
|
68
|
+
send(environmentId: string, op: DeviceOp, args: unknown, deadlineMs: number): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Runs `op` on the environment's machine and returns its validated result. Throws
|
|
71
|
+
* `environment.offline` when no replica holds the machine at send time or when the wait ran
|
|
72
|
+
* out, but `environment.forbidden` ({@link machineRevoked}) when the machine was revoked and
|
|
73
|
+
* `environment.not_found` when the environment was deleted (checked whenever the connection is
|
|
74
|
+
* missing, ruling R27); the machine's failures map to `SandboxGoneError` (`gone`),
|
|
75
|
+
* `FileSystemGoneError` (`fs_gone`) or a `ToolError` (`policy`, and `error` prefixed
|
|
76
|
+
* {@link ON_MACHINE_PREFIX}); an invalid answer throws a `DeviceProtocolError`. On abort the
|
|
77
|
+
* abort reason is thrown.
|
|
78
|
+
*/
|
|
79
|
+
call<Op extends DeviceOp>(environmentId: string, op: Op, args: unknown, opts: DeviceCallOptions): Promise<DeviceOpResults[Op]>;
|
|
80
|
+
/** {@link holderLive}, or undefined when it takes longer than {@link LEASE_CHECK_TIMEOUT_MS}. */
|
|
81
|
+
private leaseCheck;
|
|
82
|
+
/**
|
|
83
|
+
* The environment's state ({@link DeviceTargets}), or undefined when it cannot be read within
|
|
84
|
+
* {@link LEASE_CHECK_TIMEOUT_MS} (a failure only logs: the caller keeps its other rules).
|
|
85
|
+
*/
|
|
86
|
+
private targetState;
|
|
87
|
+
/** The error of a state that never comes back; undefined for `active` or unknown. */
|
|
88
|
+
private goneError;
|
|
89
|
+
private graceMs;
|
|
90
|
+
private push;
|
|
91
|
+
/** Announces new frames to the holder; a lost nudge is picked up on the holder's next drain. */
|
|
92
|
+
private nudge;
|
|
93
|
+
/** Removes the request from the list, or queues a cancel when the machine took it (R15). */
|
|
94
|
+
private giveUp;
|
|
95
|
+
/** Runs a side step whose failure must not replace the call's outcome: logged, swallowed. */
|
|
96
|
+
private quietly;
|
|
97
|
+
/** A stored / published `res` frame for request `id`, or the protocol error it carries. */
|
|
98
|
+
private parseRes;
|
|
99
|
+
private resultOf;
|
|
100
|
+
}
|