@capybara-hq/device 0.1.0-rc.14 → 0.1.0-rc.16
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/README.md +101 -157
- package/dist/api.d.ts +2 -2
- package/dist/args.d.ts +2 -8
- package/dist/args.js +2 -25
- package/dist/cli.d.ts +2 -11
- package/dist/cli.js +6 -61
- package/dist/client.d.ts +8 -45
- package/dist/client.js +25 -424
- package/dist/command-log.d.ts +14 -4
- package/dist/command-log.js +37 -1
- package/dist/commands/ceiling.d.ts +0 -2
- package/dist/commands/ceiling.js +3 -4
- package/dist/commands/login.d.ts +25 -1
- package/dist/commands/login.js +75 -61
- package/dist/commands/policy.d.ts +6 -8
- package/dist/commands/policy.js +30 -49
- package/dist/commands/start.d.ts +2 -17
- package/dist/commands/start.js +13 -53
- package/dist/exec/docker-operations.d.ts +2 -2
- package/dist/exec/docker-operations.js +4 -2
- package/dist/exec/docker.d.ts +37 -122
- package/dist/exec/docker.js +72 -717
- package/dist/exec/instance-binding.d.ts +4 -4
- package/dist/exec/linux-agent.js +30 -0
- package/dist/exec/linux-operation-backend.d.ts +5 -0
- package/dist/exec/linux-operation-backend.js +3 -1
- package/dist/exec/linux-operation-worker.d.ts +9 -0
- package/dist/exec/linux-operation-worker.js +11 -2
- package/dist/exec/mac-read-policy.d.ts +58 -0
- package/dist/exec/mac-read-policy.js +104 -0
- package/dist/exec/mac-self-check.d.ts +6 -3
- package/dist/exec/mac-self-check.js +28 -5
- package/dist/exec/operation-worker.d.ts +21 -2
- package/dist/exec/operation-worker.js +164 -43
- package/dist/exec/sandbox-check.d.ts +10 -0
- package/dist/exec/sandbox-check.js +18 -0
- package/dist/exec/sandbox-messages.d.ts +3 -11
- package/dist/exec/sandbox-messages.js +3 -18
- package/dist/exec/shared.d.ts +24 -47
- package/dist/exec/shared.js +53 -165
- package/dist/exec/types.d.ts +2 -66
- package/dist/exec/types.js +1 -1
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/CAPYBARA-MODIFICATIONS.patch +71 -12
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/macos-sandbox-utils.js +18 -4
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js +6 -0
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js +4 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/concepts.md +9 -4
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/extension-points/channel.md +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/extension-points/file-preview.md +2 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/extension-points/sandbox.md +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/plugin-format.md +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/cards.d.ts +11 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/cards.js +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/channel.d.ts +37 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ctx.d.ts +47 -3
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-denied-paths.d.ts +14 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-denied-paths.js +41 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.d.ts +140 -20
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.js +419 -14
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/file-preview.d.ts +22 -5
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/hooks.d.ts +77 -13
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/http-access.d.ts +10 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.d.ts +2 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.js +2 -3
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/model.d.ts +89 -5
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/model.js +103 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/permissions.d.ts +3 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/permissions.js +2 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-operation.d.ts +4 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui-parts.d.ts +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui-parts.js +11 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui.d.ts +25 -6
- package/dist/node_modules/@capybara-hq/plugin-sdk/package.json +1 -1
- package/dist/owner-report.d.ts +2 -2
- package/dist/owner-report.js +2 -2
- package/dist/policy-store.d.ts +6 -10
- package/dist/policy-store.js +9 -23
- package/dist/policy.d.ts +3 -32
- package/dist/policy.js +4 -74
- package/dist/runtime-manifest.json +1 -1
- package/dist/server-ops.d.ts +18 -46
- package/dist/server-ops.js +134 -269
- package/dist/staged-connect.js +44 -7
- package/dist/staged-device.d.ts +4 -4
- package/dist/staged-device.js +3 -0
- package/dist/staged-session.d.ts +5 -5
- package/dist/staged-session.js +4 -4
- package/dist/state.js +3 -2
- package/package.json +2 -2
- package/dist/commands/mode.d.ts +0 -69
- package/dist/commands/mode.js +0 -133
- package/dist/exec/fs-helper.d.ts +0 -21
- package/dist/exec/fs-helper.js +0 -171
- package/dist/exec/host.d.ts +0 -61
- package/dist/exec/host.js +0 -203
- package/dist/exec/listing.d.ts +0 -35
- package/dist/exec/listing.js +0 -157
- package/dist/exec/os.d.ts +0 -162
- package/dist/exec/os.js +0 -616
- package/dist/exec/procs.d.ts +0 -11
- package/dist/exec/procs.js +0 -67
- package/dist/exec/reap.d.ts +0 -41
- package/dist/exec/reap.js +0 -89
- package/dist/exec/switch.d.ts +0 -107
- package/dist/exec/switch.js +0 -204
- package/dist/network.d.ts +0 -45
- package/dist/network.js +0 -154
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol-v3.d.ts +0 -117
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol-v3.js +0 -409
package/dist/client.d.ts
CHANGED
|
@@ -1,50 +1,15 @@
|
|
|
1
|
-
import type { CommandLog } from "./command-log.js";
|
|
2
|
-
import type { Executor } from "./exec/types.js";
|
|
3
|
-
import type { PolicyStore } from "./policy-store.js";
|
|
4
|
-
import type { Credential } from "./state.js";
|
|
5
1
|
export declare const OUTDATED_MESSAGE = "This capybara-device is too old for the deployment. Upgrade it: npm install -g @capybara-hq/device@next";
|
|
2
|
+
/** A 426 from a kernel on an older device protocol than this program's: upgrade the deployment. */
|
|
3
|
+
export declare const deploymentOutdatedMessage: (kernelProtocol: number) => string;
|
|
4
|
+
/**
|
|
5
|
+
* The message a 426 refusal ends the program with, from the refusal's body (the kernel's
|
|
6
|
+
* `device.program_outdated` names its protocol): an older kernel is to be upgraded first, else
|
|
7
|
+
* this program is outdated. An unreadable body keeps the outdated-program message.
|
|
8
|
+
*/
|
|
9
|
+
export declare function outdatedMessage(body: string): string;
|
|
6
10
|
export declare const DISCONNECTED_MESSAGE = "This machine was disconnected from the deployment. Run capybara-device logout, then capybara-device login.";
|
|
7
11
|
export declare const REPLACED_MESSAGE = "This machine connected elsewhere: a newer connection to this device replaced this one.";
|
|
8
12
|
export declare const DELETED_MESSAGE = "The device was deleted on the deployment. The files on this machine stay where they are.";
|
|
9
|
-
/** The answer sent instead of a result whose frame would exceed the connection's frame limit. */
|
|
10
|
-
export declare const TOO_LARGE_MESSAGE = "result larger than the connection's frame limit";
|
|
11
|
-
export interface ConnectOptions {
|
|
12
|
-
/** Staged backend lifecycle only; never announces protocol 3 or changes v2 dispatch. */
|
|
13
|
-
operations?: import("./exec/mac-operation-backend.js").MacOperationBackend;
|
|
14
|
-
log?: CommandLog;
|
|
15
|
-
/**
|
|
16
|
-
* The local policy the executor reads: its summary goes in each hello, and the `policy` op
|
|
17
|
-
* edits it. Without it the device does not offer the `policy` op.
|
|
18
|
-
*/
|
|
19
|
-
policy?: PolicyStore;
|
|
20
|
-
err?: (line: string) => void;
|
|
21
|
-
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
22
|
-
random?: () => number;
|
|
23
|
-
now?: () => number;
|
|
24
|
-
programVersion?: string;
|
|
25
|
-
/**
|
|
26
|
-
* The owner's home directory, reported in the hello (the base of an auto-mode project path).
|
|
27
|
-
* Defaults to the user's home; left out of the hello when it is not a clean absolute path, and
|
|
28
|
-
* by a docker-mode device (it offers its container's workspace only).
|
|
29
|
-
*/
|
|
30
|
-
home?: string;
|
|
31
|
-
/**
|
|
32
|
-
* The host's OS boot identity reported in each hello (`bootId`; default: read once from the
|
|
33
|
-
* OS); null leaves it out.
|
|
34
|
-
*/
|
|
35
|
-
bootId?: string | null;
|
|
36
|
-
/** A connection must stay up this long before the backoff resets (default 10 s). */
|
|
37
|
-
stableMs?: number;
|
|
38
|
-
/** Terminate a socket that heard nothing from the server for this long (default 60 s). */
|
|
39
|
-
livenessMs?: number;
|
|
40
|
-
/** Terminate a socket still closing this long after we asked it to close (default 2 s). */
|
|
41
|
-
closeTimeoutMs?: number;
|
|
42
|
-
/**
|
|
43
|
-
* How often a connected program checks its policy summary for a change made on the machine
|
|
44
|
-
* (default 2 s); a change is pushed to the deployment as a `policy` frame.
|
|
45
|
-
*/
|
|
46
|
-
policyCheckMs?: number;
|
|
47
|
-
}
|
|
48
13
|
/**
|
|
49
14
|
* A running connection. `done` resolves with the exit code once the program should end: 0 for a
|
|
50
15
|
* deliberate stop (revoked, replaced by a newer connection of this device, deleted, stopped,
|
|
@@ -61,6 +26,4 @@ export interface Connection {
|
|
|
61
26
|
}
|
|
62
27
|
/** Backoff before reconnect attempt `attempt` (0-based): 1 s doubling to 60 s, with jitter. */
|
|
63
28
|
export declare function backoffMs(attempt: number, random: () => number): number;
|
|
64
|
-
/** Connects this machine to the deployment and serves operations until told to stop. */
|
|
65
|
-
export declare function connect(cred: Credential, executor: Executor, opts?: ConnectOptions): Connection;
|
|
66
29
|
export { createStagedSessionState, drainStagedSession, type StagedDrainReport, serveStagedSession, } from "./staged-session.js";
|
package/dist/client.js
CHANGED
|
@@ -1,17 +1,32 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
import {
|
|
1
|
+
/**
|
|
2
|
+
* What the device program's connection shares: the messages it ends with, the reconnect backoff
|
|
3
|
+
* and the running connection's interface. The connection itself is the protocol 3 one
|
|
4
|
+
* (`staged-connect.ts`).
|
|
5
|
+
*/
|
|
6
|
+
import { DEVICE_PROTOCOL_VERSION } from "@capybara-hq/plugin-sdk";
|
|
7
7
|
export const OUTDATED_MESSAGE = "This capybara-device is too old for the deployment. Upgrade it: npm install -g @capybara-hq/device@next";
|
|
8
|
+
/** A 426 from a kernel on an older device protocol than this program's: upgrade the deployment. */
|
|
9
|
+
export const deploymentOutdatedMessage = (kernelProtocol) => `The deployment is older than this capybara-device: it speaks device protocol ${kernelProtocol}, this program protocol ${DEVICE_PROTOCOL_VERSION}. Ask its super admin to upgrade the deployment first, or install a capybara-device release that speaks protocol ${kernelProtocol}.`;
|
|
10
|
+
/**
|
|
11
|
+
* The message a 426 refusal ends the program with, from the refusal's body (the kernel's
|
|
12
|
+
* `device.program_outdated` names its protocol): an older kernel is to be upgraded first, else
|
|
13
|
+
* this program is outdated. An unreadable body keeps the outdated-program message.
|
|
14
|
+
*/
|
|
15
|
+
export function outdatedMessage(body) {
|
|
16
|
+
let message = "";
|
|
17
|
+
try {
|
|
18
|
+
message = String(JSON.parse(body).error?.message ?? "");
|
|
19
|
+
}
|
|
20
|
+
catch { }
|
|
21
|
+
const protocol = /device protocol (\d+)/.exec(message)?.[1];
|
|
22
|
+
const kernel = protocol === undefined ? Number.NaN : Number(protocol);
|
|
23
|
+
return Number.isSafeInteger(kernel) && kernel < DEVICE_PROTOCOL_VERSION
|
|
24
|
+
? deploymentOutdatedMessage(kernel)
|
|
25
|
+
: OUTDATED_MESSAGE;
|
|
26
|
+
}
|
|
8
27
|
export const DISCONNECTED_MESSAGE = "This machine was disconnected from the deployment. Run capybara-device logout, then capybara-device login.";
|
|
9
28
|
export const REPLACED_MESSAGE = "This machine connected elsewhere: a newer connection to this device replaced this one.";
|
|
10
29
|
export const DELETED_MESSAGE = "The device was deleted on the deployment. The files on this machine stay where they are.";
|
|
11
|
-
/** The answer sent instead of a result whose frame would exceed the connection's frame limit. */
|
|
12
|
-
export const TOO_LARGE_MESSAGE = "result larger than the connection's frame limit";
|
|
13
|
-
/** A failing connection is reported at most this often. */
|
|
14
|
-
const FAILURE_REPORT_INTERVAL_MS = 60_000;
|
|
15
30
|
const BACKOFF_BASE_MS = 1000;
|
|
16
31
|
const BACKOFF_MAX_MS = 60_000;
|
|
17
32
|
/** Backoff before reconnect attempt `attempt` (0-based): 1 s doubling to 60 s, with jitter. */
|
|
@@ -19,418 +34,4 @@ export function backoffMs(attempt, random) {
|
|
|
19
34
|
const ceiling = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** attempt);
|
|
20
35
|
return Math.round(ceiling * (0.5 + random() * 0.5));
|
|
21
36
|
}
|
|
22
|
-
function defaultSleep(ms, signal) {
|
|
23
|
-
return new Promise((resolve) => {
|
|
24
|
-
if (signal.aborted)
|
|
25
|
-
return resolve();
|
|
26
|
-
const t = setTimeout(resolve, ms);
|
|
27
|
-
signal.addEventListener("abort", () => {
|
|
28
|
-
clearTimeout(t);
|
|
29
|
-
resolve();
|
|
30
|
-
}, { once: true });
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
/** Connects this machine to the deployment and serves operations until told to stop. */
|
|
34
|
-
export function connect(cred, executor, opts = {}) {
|
|
35
|
-
const err = opts.err ?? ((l) => console.error(l));
|
|
36
|
-
const sleep = opts.sleep ?? defaultSleep;
|
|
37
|
-
const random = opts.random ?? Math.random;
|
|
38
|
-
const now = opts.now ?? Date.now;
|
|
39
|
-
const graceMs = cred.reconnectGraceSeconds * 1000;
|
|
40
|
-
const stableMs = opts.stableMs ?? 10_000;
|
|
41
|
-
const livenessMs = opts.livenessMs ?? 60_000;
|
|
42
|
-
const closeTimeoutMs = opts.closeTimeoutMs ?? 2000;
|
|
43
|
-
const policyCheckMs = opts.policyCheckMs ?? 2000;
|
|
44
|
-
const lifetime = new AbortController();
|
|
45
|
-
let ws;
|
|
46
|
-
let draining = false;
|
|
47
|
-
let stopping = false;
|
|
48
|
-
let exitAfterStop;
|
|
49
|
-
let session;
|
|
50
|
-
let drainTimer;
|
|
51
|
-
/** What the requests of this run have seen (the latest exec's mode), over reconnects. */
|
|
52
|
-
const seen = {};
|
|
53
|
-
const ctx = {
|
|
54
|
-
seen,
|
|
55
|
-
...(opts.policy !== undefined && { policy: opts.policy }),
|
|
56
|
-
};
|
|
57
|
-
const running = new Map();
|
|
58
|
-
/** Requests the kernel gave up on: never started, or their result is dropped. */
|
|
59
|
-
const cancelled = new Map();
|
|
60
|
-
/** Requests already seen (running, answered): a repeated req is ignored. */
|
|
61
|
-
const known = new Map();
|
|
62
|
-
/** Answers produced while no socket was open, with their expiry. */
|
|
63
|
-
const pending = new Map();
|
|
64
|
-
const prune = () => {
|
|
65
|
-
const t = now();
|
|
66
|
-
for (const m of [cancelled, known])
|
|
67
|
-
for (const [k, exp] of m)
|
|
68
|
-
if (exp <= t)
|
|
69
|
-
m.delete(k);
|
|
70
|
-
for (const [k, v] of pending)
|
|
71
|
-
if (v.expires <= t)
|
|
72
|
-
pending.delete(k);
|
|
73
|
-
};
|
|
74
|
-
const isOpen = () => ws !== undefined && ws.readyState === WebSocket.OPEN;
|
|
75
|
-
/** The policy summary now: the store's policy (re-read when its file changed) and the facts. */
|
|
76
|
-
const summaryNow = () => opts.policy === undefined
|
|
77
|
-
? undefined
|
|
78
|
-
: policySummary(opts.policy.current(), summaryFacts(executor, ctx));
|
|
79
|
-
/** The summary the deployment last got on this connection (hello, `policy` op, `policy` frame). */
|
|
80
|
-
let sentPolicy;
|
|
81
|
-
/**
|
|
82
|
-
* Pushes the policy summary when it differs from the one the deployment last got: the owner
|
|
83
|
-
* changed the mode or the policy on the machine (`capybara-device mode` / `policy ...`). Without
|
|
84
|
-
* it the deployment would learn the change only at the next connect. An exec's ceiling changes
|
|
85
|
-
* nothing here: the summary reports the owner's mode, which the kernel cuts itself.
|
|
86
|
-
*/
|
|
87
|
-
const pushPolicy = async () => {
|
|
88
|
-
// Reconcile every file-generation check, even when the visible summary is unchanged.
|
|
89
|
-
await opts.operations?.reconcileOwnerCeiling(AbortSignal.timeout(30_000));
|
|
90
|
-
if (!isOpen())
|
|
91
|
-
return;
|
|
92
|
-
const summary = summaryNow();
|
|
93
|
-
if (summary === undefined)
|
|
94
|
-
return;
|
|
95
|
-
const json = JSON.stringify(summary);
|
|
96
|
-
if (json === sentPolicy)
|
|
97
|
-
return;
|
|
98
|
-
sentPolicy = json;
|
|
99
|
-
ws?.send(JSON.stringify({ type: "policy", policy: summary }));
|
|
100
|
-
};
|
|
101
|
-
/** `res`, or an error answer when its frame would exceed the deployment's frame limit. */
|
|
102
|
-
const fit = (res) => Buffer.byteLength(JSON.stringify(res)) <= cred.maxFrameBytes
|
|
103
|
-
? res
|
|
104
|
-
: {
|
|
105
|
-
type: "res",
|
|
106
|
-
id: res.id,
|
|
107
|
-
ok: false,
|
|
108
|
-
error: { kind: "error", message: TOO_LARGE_MESSAGE },
|
|
109
|
-
};
|
|
110
|
-
const deliver = (answer) => {
|
|
111
|
-
const res = fit(answer);
|
|
112
|
-
if (isOpen()) {
|
|
113
|
-
ws?.send(JSON.stringify(res), (e) => {
|
|
114
|
-
if (e)
|
|
115
|
-
pending.set(res.id, { res, expires: now() + graceMs });
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
else {
|
|
119
|
-
pending.set(res.id, { res, expires: now() + graceMs });
|
|
120
|
-
}
|
|
121
|
-
};
|
|
122
|
-
const endSession = (end) => {
|
|
123
|
-
const s = session;
|
|
124
|
-
session = undefined;
|
|
125
|
-
s?.(end);
|
|
126
|
-
};
|
|
127
|
-
/** Ends the loop: no more reconnects, and a backoff sleep in progress wakes up. */
|
|
128
|
-
const halt = () => {
|
|
129
|
-
stopping = true;
|
|
130
|
-
lifetime.abort();
|
|
131
|
-
};
|
|
132
|
-
/** Asks the socket to close; terminates it if the close handshake does not finish. */
|
|
133
|
-
const closeSocket = (sock) => {
|
|
134
|
-
if (!sock)
|
|
135
|
-
return;
|
|
136
|
-
sock.close(1000);
|
|
137
|
-
setTimeout(() => sock.terminate(), closeTimeoutMs).unref();
|
|
138
|
-
};
|
|
139
|
-
const finishDrain = () => {
|
|
140
|
-
clearTimeout(drainTimer);
|
|
141
|
-
exitAfterStop = { exit: 0 };
|
|
142
|
-
halt();
|
|
143
|
-
closeSocket(ws);
|
|
144
|
-
if (!isOpen())
|
|
145
|
-
endSession({ exit: 0 });
|
|
146
|
-
};
|
|
147
|
-
const maybeFinishDrain = () => {
|
|
148
|
-
if (!draining || running.size > 0 || stopping)
|
|
149
|
-
return;
|
|
150
|
-
prune();
|
|
151
|
-
if (pending.size > 0 && !isOpen()) {
|
|
152
|
-
// Results wait for a reconnect, at most the grace.
|
|
153
|
-
drainTimer ??= setTimeout(finishDrain, graceMs);
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
finishDrain();
|
|
157
|
-
};
|
|
158
|
-
const handleReq = (req) => {
|
|
159
|
-
prune();
|
|
160
|
-
if (cancelled.has(req.id))
|
|
161
|
-
return; // the kernel gave up before it started: never start it
|
|
162
|
-
if (running.has(req.id) || known.has(req.id))
|
|
163
|
-
return;
|
|
164
|
-
known.set(req.id, now() + graceMs + req.deadlineMs);
|
|
165
|
-
if (draining && req.op !== "stop") {
|
|
166
|
-
deliver({
|
|
167
|
-
type: "res",
|
|
168
|
-
id: req.id,
|
|
169
|
-
ok: false,
|
|
170
|
-
error: { kind: "error", message: "draining" },
|
|
171
|
-
});
|
|
172
|
-
return;
|
|
173
|
-
}
|
|
174
|
-
const ctl = new AbortController();
|
|
175
|
-
running.set(req.id, ctl);
|
|
176
|
-
void serveOp(executor, req, ctl.signal, ctx).then(async ({ res, detail, run }) => {
|
|
177
|
-
if (req.op === "policy")
|
|
178
|
-
await opts.operations?.reconcileOwnerCeiling(AbortSignal.timeout(30_000));
|
|
179
|
-
running.delete(req.id);
|
|
180
|
-
opts.log?.append(logEntryFor(req, res, new Date(now()), detail, run));
|
|
181
|
-
if (cancelled.has(req.id)) {
|
|
182
|
-
// The kernel is no longer waiting for this one.
|
|
183
|
-
}
|
|
184
|
-
else if (req.op === "stop") {
|
|
185
|
-
const reason = req.args.reason;
|
|
186
|
-
exitAfterStop =
|
|
187
|
-
reason === "revoked"
|
|
188
|
-
? { exit: 0, message: DISCONNECTED_MESSAGE }
|
|
189
|
-
: { exit: 0, message: DELETED_MESSAGE };
|
|
190
|
-
halt();
|
|
191
|
-
const sock = ws;
|
|
192
|
-
if (isOpen() && sock) {
|
|
193
|
-
sock.send(JSON.stringify(res), () => closeSocket(sock));
|
|
194
|
-
}
|
|
195
|
-
else {
|
|
196
|
-
endSession(exitAfterStop);
|
|
197
|
-
}
|
|
198
|
-
return;
|
|
199
|
-
}
|
|
200
|
-
else {
|
|
201
|
-
// a policy op's answer carries the summary the deployment stores
|
|
202
|
-
if (req.op === "policy" && res.ok) {
|
|
203
|
-
sentPolicy = JSON.stringify(res.result.policy);
|
|
204
|
-
}
|
|
205
|
-
deliver(res);
|
|
206
|
-
}
|
|
207
|
-
maybeFinishDrain();
|
|
208
|
-
});
|
|
209
|
-
};
|
|
210
|
-
const handleCancel = (id) => {
|
|
211
|
-
prune();
|
|
212
|
-
cancelled.set(id, now() + graceMs);
|
|
213
|
-
pending.delete(id);
|
|
214
|
-
running.get(id)?.abort();
|
|
215
|
-
};
|
|
216
|
-
const onMessage = (raw) => {
|
|
217
|
-
let frame;
|
|
218
|
-
try {
|
|
219
|
-
frame = parseDeviceFrame(raw, "kernel");
|
|
220
|
-
}
|
|
221
|
-
catch (e) {
|
|
222
|
-
// Best effort: tell the kernel a request it sent was unusable.
|
|
223
|
-
try {
|
|
224
|
-
const o = JSON.parse(raw);
|
|
225
|
-
if (o.type === "req" && typeof o.id === "string" && o.id !== "") {
|
|
226
|
-
deliver({
|
|
227
|
-
type: "res",
|
|
228
|
-
id: o.id,
|
|
229
|
-
ok: false,
|
|
230
|
-
error: { kind: "error", message: `invalid request: ${e.message}` },
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
catch {
|
|
235
|
-
// not JSON: ignore
|
|
236
|
-
}
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
if (frame.type === "req")
|
|
240
|
-
handleReq(frame);
|
|
241
|
-
else if (frame.type === "cancel")
|
|
242
|
-
handleCancel(frame.id);
|
|
243
|
-
};
|
|
244
|
-
/**
|
|
245
|
-
* The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
|
|
246
|
-
* mode has no per-host view); the device applies `limits.mode` / `limits.network` (`mode`); the
|
|
247
|
-
* policy summary is the store's policy now (the owner's mode, not cut by any ceiling);
|
|
248
|
-
* then the outcomes of the latest policy ops by op id.
|
|
249
|
-
*/
|
|
250
|
-
// A container device offers only its container's workspace: the host's home is not its base.
|
|
251
|
-
const ownerHome = opts.home ?? homedir();
|
|
252
|
-
const home = executor.mode === "os" && validateSandboxPathShape(ownerHome).length === 0
|
|
253
|
-
? ownerHome
|
|
254
|
-
: undefined;
|
|
255
|
-
// the deployment's evidence that the host restarted (legacy retirement, cutover 8.5)
|
|
256
|
-
const bootId = opts.bootId === undefined ? currentBootId() : (opts.bootId ?? undefined);
|
|
257
|
-
const hello = () => {
|
|
258
|
-
const summary = summaryNow();
|
|
259
|
-
sentPolicy = summary === undefined ? undefined : JSON.stringify(summary);
|
|
260
|
-
const features = [];
|
|
261
|
-
if (executor.mode === "os")
|
|
262
|
-
features.push("networkReport");
|
|
263
|
-
// the policy op, logged by its op id (policy-ops.json next to the policy)
|
|
264
|
-
if (opts.policy !== undefined)
|
|
265
|
-
features.push("policyOp", "policyOpId");
|
|
266
|
-
features.push("mode");
|
|
267
|
-
// `list` and `scan`, read in each request's own mode (they need the owner's policy)
|
|
268
|
-
if (opts.policy !== undefined)
|
|
269
|
-
features.push("projects");
|
|
270
|
-
return {
|
|
271
|
-
type: "hello",
|
|
272
|
-
protocol: DEVICE_PROTOCOL_VERSION,
|
|
273
|
-
programVersion: opts.programVersion ?? PROGRAM_VERSION,
|
|
274
|
-
os: process.platform === "darwin" ? "darwin" : "linux",
|
|
275
|
-
arch: process.arch,
|
|
276
|
-
mode: executor.mode,
|
|
277
|
-
roots: executor.roots,
|
|
278
|
-
sessionIsolation: false,
|
|
279
|
-
features,
|
|
280
|
-
...(home !== undefined && { home }),
|
|
281
|
-
...(bootId !== undefined && { bootId }),
|
|
282
|
-
...(summary !== undefined && { policy: summary }),
|
|
283
|
-
// what became of the latest policy ops, so an answer lost with a connection is not lost
|
|
284
|
-
...(opts.policy !== undefined && { recentOps: opts.policy.ops.recent() }),
|
|
285
|
-
};
|
|
286
|
-
};
|
|
287
|
-
let attempt = 0;
|
|
288
|
-
/** When a failing connection was last reported; reset once a connection stays up. */
|
|
289
|
-
let lastReport;
|
|
290
|
-
/** The failure last reported: a different failure is reported at once, not after the interval. */
|
|
291
|
-
let lastReportText;
|
|
292
|
-
/**
|
|
293
|
-
* Reports why connecting keeps failing: a failure different from the last one is reported at
|
|
294
|
-
* once, the same one at most once a minute. A long outage therefore does not flood the log.
|
|
295
|
-
*/
|
|
296
|
-
const reportFailure = (why) => {
|
|
297
|
-
const t = now();
|
|
298
|
-
if (why === lastReportText &&
|
|
299
|
-
lastReport !== undefined &&
|
|
300
|
-
t - lastReport < FAILURE_REPORT_INTERVAL_MS) {
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
lastReport = t;
|
|
304
|
-
lastReportText = why;
|
|
305
|
-
err(`${why} Retrying.`);
|
|
306
|
-
};
|
|
307
|
-
const runSession = () => new Promise((resolve) => {
|
|
308
|
-
session = resolve;
|
|
309
|
-
const sock = new WebSocket(cred.connectUrl, {
|
|
310
|
-
headers: {
|
|
311
|
-
Authorization: `Bearer ${cred.credential}`,
|
|
312
|
-
"X-Capybara-Device-Protocol": String(DEVICE_PROTOCOL_VERSION),
|
|
313
|
-
},
|
|
314
|
-
});
|
|
315
|
-
ws = sock;
|
|
316
|
-
let liveness;
|
|
317
|
-
let stable;
|
|
318
|
-
let policyCheck;
|
|
319
|
-
let opened = false;
|
|
320
|
-
/** The deployment answered the upgrade with an HTTP status (already handled). */
|
|
321
|
-
let answered = false;
|
|
322
|
-
const heard = () => {
|
|
323
|
-
clearTimeout(liveness);
|
|
324
|
-
liveness = setTimeout(() => sock.terminate(), livenessMs);
|
|
325
|
-
};
|
|
326
|
-
sock.on("ping", heard);
|
|
327
|
-
sock.on("open", () => {
|
|
328
|
-
opened = true;
|
|
329
|
-
heard();
|
|
330
|
-
stable = setTimeout(() => {
|
|
331
|
-
// A connection that stayed up enough is a success: the next failure starts at the
|
|
332
|
-
// base delay, and is reported again even if it is the same message as before.
|
|
333
|
-
attempt = 0;
|
|
334
|
-
lastReport = undefined;
|
|
335
|
-
lastReportText = undefined;
|
|
336
|
-
}, stableMs);
|
|
337
|
-
sock.send(JSON.stringify(hello()));
|
|
338
|
-
if (opts.policy !== undefined)
|
|
339
|
-
policyCheck = setInterval(() => {
|
|
340
|
-
void pushPolicy().catch((error) => err(`Owner ceiling reconciliation failed: ${String(error)}`));
|
|
341
|
-
}, policyCheckMs);
|
|
342
|
-
prune();
|
|
343
|
-
for (const [id, p] of pending) {
|
|
344
|
-
pending.delete(id);
|
|
345
|
-
deliver(p.res);
|
|
346
|
-
}
|
|
347
|
-
maybeFinishDrain();
|
|
348
|
-
});
|
|
349
|
-
sock.on("message", (data, isBinary) => {
|
|
350
|
-
heard();
|
|
351
|
-
if (isBinary)
|
|
352
|
-
return;
|
|
353
|
-
onMessage(data.toString("utf8"));
|
|
354
|
-
});
|
|
355
|
-
sock.on("unexpected-response", (_req, res) => {
|
|
356
|
-
answered = true;
|
|
357
|
-
const status = res.statusCode ?? 0;
|
|
358
|
-
res.resume();
|
|
359
|
-
sock.terminate();
|
|
360
|
-
if (status === 401)
|
|
361
|
-
return endSession({ exit: 0, message: DISCONNECTED_MESSAGE });
|
|
362
|
-
// Not a deliberate stop: upgrading the package in place recovers it, so the exit is
|
|
363
|
-
// non-zero and the service manager starts the (new) program again.
|
|
364
|
-
if (status === 426)
|
|
365
|
-
return endSession({ exit: 1, message: OUTDATED_MESSAGE });
|
|
366
|
-
reportFailure(status === 404
|
|
367
|
-
? `Connecting to ${cred.connectUrl} failed: HTTP 404. The deployment must route ` +
|
|
368
|
-
"/device/connect to its gateway (see the deployment docs)."
|
|
369
|
-
: `Connecting to ${cred.connectUrl} failed: HTTP ${status}.`);
|
|
370
|
-
endSession({ reconnect: true });
|
|
371
|
-
});
|
|
372
|
-
sock.on("error", (e) => {
|
|
373
|
-
// 'close' follows; the reason is decided there. A failure before the socket opened is a
|
|
374
|
-
// connection attempt that did not reach the deployment.
|
|
375
|
-
if (!opened && !answered && !stopping) {
|
|
376
|
-
reportFailure(`Cannot reach ${cred.connectUrl}: ${e.message}.`);
|
|
377
|
-
}
|
|
378
|
-
});
|
|
379
|
-
sock.on("close", (code, reason) => {
|
|
380
|
-
clearTimeout(liveness);
|
|
381
|
-
clearTimeout(stable);
|
|
382
|
-
clearInterval(policyCheck);
|
|
383
|
-
if (ws === sock)
|
|
384
|
-
ws = undefined;
|
|
385
|
-
if (exitAfterStop)
|
|
386
|
-
return endSession(exitAfterStop);
|
|
387
|
-
if (code === 4002)
|
|
388
|
-
return endSession({ exit: 0, message: REPLACED_MESSAGE });
|
|
389
|
-
if (code === 4003)
|
|
390
|
-
return endSession({ exit: 0, message: DISCONNECTED_MESSAGE });
|
|
391
|
-
if (code === 4400) {
|
|
392
|
-
const why = reason.toString("utf8");
|
|
393
|
-
reportFailure(`The deployment closed the connection: 4400${why ? ` ${why}` : ""}.`);
|
|
394
|
-
}
|
|
395
|
-
endSession({ reconnect: true });
|
|
396
|
-
});
|
|
397
|
-
});
|
|
398
|
-
const loop = async () => {
|
|
399
|
-
while (!stopping) {
|
|
400
|
-
const end = await runSession();
|
|
401
|
-
if ("exit" in end) {
|
|
402
|
-
if (end.message)
|
|
403
|
-
err(end.message);
|
|
404
|
-
return end.exit;
|
|
405
|
-
}
|
|
406
|
-
if (stopping)
|
|
407
|
-
break;
|
|
408
|
-
await sleep(backoffMs(attempt++, random), lifetime.signal);
|
|
409
|
-
}
|
|
410
|
-
if (exitAfterStop?.message)
|
|
411
|
-
err(exitAfterStop.message);
|
|
412
|
-
return exitAfterStop?.exit ?? 0;
|
|
413
|
-
};
|
|
414
|
-
const done = loop().finally(() => {
|
|
415
|
-
clearTimeout(drainTimer);
|
|
416
|
-
lifetime.abort();
|
|
417
|
-
for (const ctl of running.values())
|
|
418
|
-
ctl.abort();
|
|
419
|
-
});
|
|
420
|
-
return {
|
|
421
|
-
done,
|
|
422
|
-
drain() {
|
|
423
|
-
draining = true;
|
|
424
|
-
maybeFinishDrain();
|
|
425
|
-
},
|
|
426
|
-
stop() {
|
|
427
|
-
halt();
|
|
428
|
-
if (ws)
|
|
429
|
-
closeSocket(ws);
|
|
430
|
-
else
|
|
431
|
-
endSession({ exit: 0 });
|
|
432
|
-
},
|
|
433
|
-
};
|
|
434
|
-
}
|
|
435
|
-
// Explicit dormant seam only; connect() never selects it or advertises v3.
|
|
436
37
|
export { createStagedSessionState, drainStagedSession, serveStagedSession, } from "./staged-session.js";
|
package/dist/command-log.d.ts
CHANGED
|
@@ -1,18 +1,26 @@
|
|
|
1
|
-
import type { SandboxMode } from "./state.js";
|
|
2
1
|
export declare const COMMAND_LOG_MAX_BYTES: number;
|
|
3
2
|
export interface CommandLogEntry {
|
|
4
3
|
time: string;
|
|
5
4
|
op: string;
|
|
6
5
|
tag: string | null;
|
|
6
|
+
/** Who asked: the account, and for an operation the conversation it ran for. */
|
|
7
7
|
actor: {
|
|
8
8
|
accountId: string;
|
|
9
|
+
conversationId?: string;
|
|
9
10
|
} | null;
|
|
10
11
|
exitCode: number | null;
|
|
11
|
-
/**
|
|
12
|
-
|
|
12
|
+
/** How an operation ran: restricted (the permission sandbox) or full (Full access). */
|
|
13
|
+
isolation?: "restricted" | "full";
|
|
14
|
+
/**
|
|
15
|
+
* Why a full operation ran without the sandbox when its conversation's profile is restricted:
|
|
16
|
+
* a per-call sandbox escalation the person or the review model approved for that one call.
|
|
17
|
+
* Absent for Full access and restricted operations.
|
|
18
|
+
*/
|
|
19
|
+
grantSource?: "call approval";
|
|
13
20
|
/**
|
|
14
21
|
* An audit line: a policy change from the deployment (`policy add a.com by <name> (<id>) via
|
|
15
|
-
* web, approval <id>`) or the
|
|
22
|
+
* web, approval <id>`) or the machine (`policy add allowedDomains a.com by <user> via cli`), the
|
|
23
|
+
* grants an exec was given (`grants run <id> by <id>: a.com`) or a failure's kind.
|
|
16
24
|
*/
|
|
17
25
|
detail?: string;
|
|
18
26
|
}
|
|
@@ -23,3 +31,5 @@ export declare class CommandLog {
|
|
|
23
31
|
constructor(stateDir: string, maxBytes?: number);
|
|
24
32
|
append(entry: CommandLogEntry): void;
|
|
25
33
|
}
|
|
34
|
+
/** Records a policy change made on the machine with the CLI: best effort, never fails it. */
|
|
35
|
+
export declare function noteCliPolicyChange(stateDir: string, what: string): void;
|
package/dist/command-log.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
1
|
+
import { appendFileSync, chmodSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
2
|
+
import { userInfo } from "node:os";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
export const COMMAND_LOG_MAX_BYTES = 10 * 1024 * 1024;
|
|
4
5
|
/** One JSON line per operation in `<stateDir>/commands.log`; rotated to `commands.log.1` at 10 MiB. */
|
|
@@ -8,6 +9,15 @@ export class CommandLog {
|
|
|
8
9
|
constructor(stateDir, maxBytes = COMMAND_LOG_MAX_BYTES) {
|
|
9
10
|
this.maxBytes = maxBytes;
|
|
10
11
|
this.file = join(stateDir, "commands.log");
|
|
12
|
+
// a log written by an older program, or by hand, is the owner's only: tighten it at open
|
|
13
|
+
for (const file of [this.file, `${this.file}.1`]) {
|
|
14
|
+
try {
|
|
15
|
+
chmodSync(file, 0o600);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
// absent, or not ours to change: appending still never fails an operation
|
|
19
|
+
}
|
|
20
|
+
}
|
|
11
21
|
}
|
|
12
22
|
append(entry) {
|
|
13
23
|
try {
|
|
@@ -26,3 +36,29 @@ export class CommandLog {
|
|
|
26
36
|
}
|
|
27
37
|
}
|
|
28
38
|
}
|
|
39
|
+
/** The local user who ran a CLI command, for the audit line (empty when unknown). */
|
|
40
|
+
function localUser() {
|
|
41
|
+
try {
|
|
42
|
+
return userInfo().username;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Records a policy change made on the machine with the CLI: best effort, never fails it. */
|
|
49
|
+
export function noteCliPolicyChange(stateDir, what) {
|
|
50
|
+
const user = localUser();
|
|
51
|
+
try {
|
|
52
|
+
new CommandLog(stateDir).append({
|
|
53
|
+
time: new Date().toISOString(),
|
|
54
|
+
op: "policy",
|
|
55
|
+
tag: null,
|
|
56
|
+
actor: null,
|
|
57
|
+
exitCode: null,
|
|
58
|
+
detail: `${what}${user === "" ? "" : ` by ${user}`} via cli`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// the local log never fails a change
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -13,8 +13,6 @@ export interface CeilingDeps {
|
|
|
13
13
|
/** Test seam: runs after the unlocked read, before the locked write. */
|
|
14
14
|
beforeWrite?: () => void;
|
|
15
15
|
}
|
|
16
|
-
/** Printed by `show` while the deployment still speaks protocol 2 (M2). */
|
|
17
|
-
export declare const CEILING_PROTOCOL2_NOTE: string;
|
|
18
16
|
/** True when `next` allows anything `cur` does not. */
|
|
19
17
|
export declare function widens(cur: OwnerCeilingPolicy, next: OwnerCeilingPolicy): boolean;
|
|
20
18
|
/**
|
package/dist/commands/ceiling.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { noteCliPolicyChange } from "../command-log.js";
|
|
1
2
|
import { readStrictOwnerCeilingSync } from "../exec/operation-types.js";
|
|
2
3
|
import { PolicyStore } from "../policy-store.js";
|
|
3
4
|
import { policyPath, readCredential } from "../state.js";
|
|
@@ -8,9 +9,6 @@ export const CEILING_WIDENING_TEXT = "Widening this machine's owner ceiling lets
|
|
|
8
9
|
"projects outside the device's workspace. Conversations need fresh Full consent either way.";
|
|
9
10
|
export const CEILING_NEEDS_YES = "Nothing changed. To widen the owner ceiling, add --yes (or answer y at the prompt).";
|
|
10
11
|
export const CEILING_PROMPT = "Widen this machine's owner ceiling? [y/N] ";
|
|
11
|
-
/** Printed by `show` while the deployment still speaks protocol 2 (M2). */
|
|
12
|
-
export const CEILING_PROTOCOL2_NOTE = "Note: the project reach takes effect only once this program and the deployment use the new " +
|
|
13
|
-
"device protocol; until then Full access allowed also lets restricted work reach as this OS user.";
|
|
14
12
|
/** Thrown inside the locked update when the policy now on disk makes the target a widening. */
|
|
15
13
|
class WideningNeedsConfirmation extends Error {
|
|
16
14
|
}
|
|
@@ -68,7 +66,6 @@ export async function ceilingCommand(cmd, deps) {
|
|
|
68
66
|
}
|
|
69
67
|
out("The platform and organization Full access settings and this machine's runtime support " +
|
|
70
68
|
"apply separately; the deployment's device page shows the effective permissions.");
|
|
71
|
-
out(CEILING_PROTOCOL2_NOTE);
|
|
72
69
|
return 0;
|
|
73
70
|
}
|
|
74
71
|
const next = {
|
|
@@ -111,6 +108,8 @@ export async function ceilingCommand(cmd, deps) {
|
|
|
111
108
|
err(`Cannot change ${policyPath(stateDir)}: ${e.message}`);
|
|
112
109
|
return 1;
|
|
113
110
|
}
|
|
111
|
+
noteCliPolicyChange(stateDir, `ceiling set fullAccess ${written.fullAccess ? "allow" : "deny"}, projectReach ` +
|
|
112
|
+
written.restrictedProjectReach);
|
|
114
113
|
out("This machine's owner ceiling is now:");
|
|
115
114
|
for (const line of describe(written))
|
|
116
115
|
out(line);
|