@eloxiv/daemon 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +6 -2
- package/dist/Acp.d.ts +8 -0
- package/dist/Acp.d.ts.map +1 -0
- package/dist/Acp.js +268 -0
- package/dist/Acp.js.map +1 -0
- package/dist/Canonical.d.ts +3 -0
- package/dist/Canonical.d.ts.map +1 -0
- package/dist/Canonical.js +12 -0
- package/dist/Canonical.js.map +1 -0
- package/dist/Client.d.ts +102 -0
- package/dist/Client.d.ts.map +1 -0
- package/dist/Client.js +482 -0
- package/dist/Client.js.map +1 -0
- package/dist/Commands.d.ts +85 -0
- package/dist/Commands.d.ts.map +1 -0
- package/dist/Commands.js +370 -0
- package/dist/Commands.js.map +1 -0
- package/dist/Config.d.ts +74 -0
- package/dist/Config.d.ts.map +1 -0
- package/dist/Config.js +126 -0
- package/dist/Config.js.map +1 -0
- package/dist/Daemon.d.ts +243 -0
- package/dist/Daemon.d.ts.map +1 -0
- package/dist/Daemon.js +965 -0
- package/dist/Daemon.js.map +1 -0
- package/dist/Harness.d.ts +133 -0
- package/dist/Harness.d.ts.map +1 -0
- package/dist/Harness.js +734 -0
- package/dist/Harness.js.map +1 -0
- package/dist/Http.d.ts +15 -0
- package/dist/Http.d.ts.map +1 -0
- package/dist/Http.js +548 -0
- package/dist/Http.js.map +1 -0
- package/dist/KernelLink.d.ts +145 -0
- package/dist/KernelLink.d.ts.map +1 -0
- package/dist/KernelLink.js +109 -0
- package/dist/KernelLink.js.map +1 -0
- package/dist/LocalAuth.d.ts +99 -0
- package/dist/LocalAuth.d.ts.map +1 -0
- package/dist/LocalAuth.js +225 -0
- package/dist/LocalAuth.js.map +1 -0
- package/dist/Main.d.ts +51 -0
- package/dist/Main.d.ts.map +1 -0
- package/dist/Main.js +219 -0
- package/dist/Main.js.map +1 -0
- package/dist/PersonSession.d.ts +49 -0
- package/dist/PersonSession.d.ts.map +1 -0
- package/dist/PersonSession.js +173 -0
- package/dist/PersonSession.js.map +1 -0
- package/dist/Secrets.d.ts +21 -0
- package/dist/Secrets.d.ts.map +1 -0
- package/dist/Secrets.js +204 -0
- package/dist/Secrets.js.map +1 -0
- package/dist/SecureUrl.d.ts +11 -0
- package/dist/SecureUrl.d.ts.map +1 -0
- package/dist/SecureUrl.js +23 -0
- package/dist/SecureUrl.js.map +1 -0
- package/dist/State.d.ts +77 -0
- package/dist/State.d.ts.map +1 -0
- package/dist/State.js +38 -0
- package/dist/State.js.map +1 -0
- package/dist/Terminals.d.ts +49 -0
- package/dist/Terminals.d.ts.map +1 -0
- package/dist/Terminals.js +203 -0
- package/dist/Terminals.js.map +1 -0
- package/dist/bin-node.d.ts +2 -0
- package/dist/bin-node.d.ts.map +1 -0
- package/dist/bin-node.js +4 -0
- package/dist/bin-node.js.map +1 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +4 -0
- package/dist/bin.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -0
- package/dist/runtime/bun.d.ts +11 -0
- package/dist/runtime/bun.d.ts.map +1 -0
- package/dist/runtime/bun.js +20 -0
- package/dist/runtime/bun.js.map +1 -0
- package/dist/runtime/node.d.ts +11 -0
- package/dist/runtime/node.d.ts.map +1 -0
- package/dist/runtime/node.js +21 -0
- package/dist/runtime/node.js.map +1 -0
- package/dist/testing.d.ts +25 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +27 -0
- package/dist/testing.js.map +1 -0
- package/fixtures/claude-code-env-vars.txt +409 -0
- package/fixtures/fake-acp-agent.mjs +222 -0
- package/fixtures/fake-harness.mjs +299 -0
- package/fixtures/recorded/claude-code.jsonl +7 -0
- package/fixtures/recorded/codex.jsonl +6 -0
- package/package.json +64 -3
- package/scripts/build-sidecar.ts +86 -0
- package/src/Acp.ts +292 -0
- package/src/Canonical.ts +9 -0
- package/src/Client.ts +590 -0
- package/src/Commands.ts +427 -0
- package/src/Config.ts +179 -0
- package/src/Daemon.ts +1092 -0
- package/src/Harness.ts +839 -0
- package/src/Http.ts +563 -0
- package/src/KernelLink.ts +197 -0
- package/src/LocalAuth.ts +301 -0
- package/src/Main.ts +281 -0
- package/src/PersonSession.ts +203 -0
- package/src/Secrets.ts +226 -0
- package/src/SecureUrl.ts +21 -0
- package/src/State.ts +109 -0
- package/src/Terminals.ts +227 -0
- package/src/bin-node.ts +4 -0
- package/src/bin.ts +4 -0
- package/src/index.ts +17 -0
- package/src/runtime/bun.ts +29 -0
- package/src/runtime/node.ts +30 -0
- package/src/testing.ts +43 -0
package/dist/Daemon.js
ADDED
|
@@ -0,0 +1,965 @@
|
|
|
1
|
+
import { commandKindOf } from "@eloxiv/contracts";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { chmodSync, mkdirSync, mkdtempSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { hostname, platform, tmpdir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { canonicalize } from "./Canonical.js";
|
|
7
|
+
import { LocalClientService } from "./Client.js";
|
|
8
|
+
import { CompanionQueue, confine, isLocalKind, runLocalCommand } from "./Commands.js";
|
|
9
|
+
import { ptyAvailable, TerminalError, Terminals } from "./Terminals.js";
|
|
10
|
+
import { runAcpHarness } from "./Acp.js";
|
|
11
|
+
import { detectHarness, harnessConfigs, runHarness } from "./Harness.js";
|
|
12
|
+
import { DeviceRevoked, KernelError, KernelLink, pollPairing, startPairing } from "./KernelLink.js";
|
|
13
|
+
import { LocalAuth } from "./LocalAuth.js";
|
|
14
|
+
import { credentialKey } from "./Secrets.js";
|
|
15
|
+
import { secureUrl } from "./SecureUrl.js";
|
|
16
|
+
import { sha256Hex, StateFile } from "./State.js";
|
|
17
|
+
const KINDS = ["claude-code", "codex", "opencode", "acp"];
|
|
18
|
+
/** How often a command the daemon took asks the kernel whether it was cancelled (ms). */
|
|
19
|
+
export const COMMAND_CHECK_MS = 1_000;
|
|
20
|
+
/** The device commands one daemon runs at once. */
|
|
21
|
+
export const MAX_COMMANDS_AT_ONCE = 4;
|
|
22
|
+
/** Events per `appendTurnEvents` call: a larger backlog goes in several calls, in order. */
|
|
23
|
+
export const EVENT_PAGE = 200;
|
|
24
|
+
/** The daemon refused a kernel pairing it was asked for. */
|
|
25
|
+
export class PairingRefused extends Error {
|
|
26
|
+
name = "PairingRefused";
|
|
27
|
+
tag;
|
|
28
|
+
constructor(tag, message) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.tag = tag;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A kernel the daemon may pair with: `https`, or `http` only on loopback (a local kernel). A plain-http kernel
|
|
35
|
+
* elsewhere would see the device credential in clear.
|
|
36
|
+
*/
|
|
37
|
+
export const checkKernelUrl = (raw) => {
|
|
38
|
+
try {
|
|
39
|
+
return secureUrl(raw);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
throw new PairingRefused("InvalidInput", error.message);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Where turns that name no directory work: one fresh directory each, under a root per state directory, outside
|
|
47
|
+
* it; the root is emptied when a daemon starts, so a killed process leaves nothing behind for long.
|
|
48
|
+
*/
|
|
49
|
+
export const turnRootFor = (stateDir) => join(tmpdir(), `eloxiv-turns-${sha256Hex(resolve(stateDir)).slice(0, 16)}`);
|
|
50
|
+
/**
|
|
51
|
+
* Where resumable turns that name no directory keep theirs: one per kept harness session, outside the state
|
|
52
|
+
* directory, removed when the session is forgotten (never emptied at start-up: a follow-up needs it).
|
|
53
|
+
*/
|
|
54
|
+
export const sessionRootFor = (stateDir) => join(tmpdir(), `eloxiv-sessions-${sha256Hex(resolve(stateDir)).slice(0, 16)}`);
|
|
55
|
+
/** How many harness sessions the daemon keeps for follow-ups; the least recently used beyond it are forgotten. */
|
|
56
|
+
export const MAX_HARNESS_SESSIONS = 50;
|
|
57
|
+
/** The file `eloxiv-daemon approve-client` reads the daemon's control secret from (0600). */
|
|
58
|
+
export const controlSecretPath = (stateDir) => join(stateDir, "control.secret");
|
|
59
|
+
export class Daemon {
|
|
60
|
+
state;
|
|
61
|
+
auth;
|
|
62
|
+
log;
|
|
63
|
+
harnesses;
|
|
64
|
+
#port = 0;
|
|
65
|
+
#pairing;
|
|
66
|
+
#pairingError;
|
|
67
|
+
#harnessStatus;
|
|
68
|
+
#runner;
|
|
69
|
+
/** Relay sessions for local clients' MCP use (agent-originated), by client id. */
|
|
70
|
+
#relaySessions = new Map();
|
|
71
|
+
/** Per-turn occurrence counters for runner tool calls (idempotency keys). */
|
|
72
|
+
#occurrences = new Map();
|
|
73
|
+
/** The runner turn being served, by id: asks the kernel (a heartbeat) whether it was cancelled, stopping it if so. */
|
|
74
|
+
#turnChecks = new Map();
|
|
75
|
+
#sessions = new Map();
|
|
76
|
+
/** The session report in flight, if any: the next waits for it (`reportSessions`). */
|
|
77
|
+
#reportingSessions = Promise.resolve();
|
|
78
|
+
#commandLoop;
|
|
79
|
+
#commandsRunning = 0;
|
|
80
|
+
/** The capabilities last reported to the kernel (JSON), so only a change is reported again. */
|
|
81
|
+
#reportedCapabilities;
|
|
82
|
+
/** Browser and computer commands waiting for their companion. */
|
|
83
|
+
companions;
|
|
84
|
+
/** Terminal sessions of local clients (`POST /terminals`). */
|
|
85
|
+
terminals;
|
|
86
|
+
/** LocalClient (`/client/v1`), when the sidecar was composed with a `clientApp`. */
|
|
87
|
+
client;
|
|
88
|
+
options;
|
|
89
|
+
constructor(options) {
|
|
90
|
+
this.options = options;
|
|
91
|
+
// The terminal and files act in the workspace, which they need; the tools-only profile allows neither.
|
|
92
|
+
const local = (options.commands ?? []).filter(isLocalKind);
|
|
93
|
+
if (local.length > 0 && options.toolsOnly === true) {
|
|
94
|
+
throw new Error(`The tools-only profile cannot serve ${local.join(" or ")} commands`);
|
|
95
|
+
}
|
|
96
|
+
if (local.length > 0 && options.workspace === undefined) {
|
|
97
|
+
throw new Error(`${local.join(" and ")} commands need a workspace (--workspace)`);
|
|
98
|
+
}
|
|
99
|
+
this.companions = new CompanionQueue(() => this.capabilitiesChanged());
|
|
100
|
+
this.terminals = new Terminals((terminal) => {
|
|
101
|
+
this.#sessions.set(`terminal:${terminal.id}`, {
|
|
102
|
+
id: `terminal:${terminal.id}`,
|
|
103
|
+
kind: "terminal",
|
|
104
|
+
label: `terminal ${terminal.id}`,
|
|
105
|
+
startedAt: terminal.startedAt,
|
|
106
|
+
endedAt: terminal.endedAt,
|
|
107
|
+
detail: terminal.pty ? "pty" : "pipes",
|
|
108
|
+
});
|
|
109
|
+
void this.reportSessions();
|
|
110
|
+
});
|
|
111
|
+
this.log = options.log ?? ((line) => process.stderr.write(`[eloxiv-daemon] ${line}\n`));
|
|
112
|
+
this.state = new StateFile(options.stateDir);
|
|
113
|
+
// A per-start secret for `eloxiv-daemon approve-client` (the person at this machine, acting as the host).
|
|
114
|
+
const controlSecret = randomBytes(32).toString("base64url");
|
|
115
|
+
writeFileSync(controlSecretPath(options.stateDir), `${controlSecret}\n`, { mode: 0o600 });
|
|
116
|
+
chmodSync(controlSecretPath(options.stateDir), 0o600);
|
|
117
|
+
this.auth = new LocalAuth(this.state, {
|
|
118
|
+
...options.localPairing,
|
|
119
|
+
hostSecret: options.hostSecret,
|
|
120
|
+
controlSecret,
|
|
121
|
+
trustedOrigins: options.trustedOrigins,
|
|
122
|
+
log: this.log,
|
|
123
|
+
});
|
|
124
|
+
this.harnesses = { ...harnessConfigs(), ...options.harnesses };
|
|
125
|
+
this.client = this.#clientService(options);
|
|
126
|
+
// A runner that died mid-turn: the kernel takes the turn back when this process says it is fresh.
|
|
127
|
+
if (this.state.current.inflight !== undefined)
|
|
128
|
+
this.state.update((s) => ({ ...s, inflight: undefined }));
|
|
129
|
+
// Private files of turns a killed process left behind.
|
|
130
|
+
rmSync(join(options.stateDir, "turns"), { recursive: true, force: true });
|
|
131
|
+
// Working directories of turns a killed process left behind (outside the state directory).
|
|
132
|
+
rmSync(turnRootFor(options.stateDir), { recursive: true, force: true });
|
|
133
|
+
for (const client of this.state.current.localClients) {
|
|
134
|
+
this.#sessions.set(`client:${client.id}`, {
|
|
135
|
+
id: `client:${client.id}`,
|
|
136
|
+
kind: client.kind,
|
|
137
|
+
label: client.name,
|
|
138
|
+
startedAt: client.pairedAt,
|
|
139
|
+
endedAt: null,
|
|
140
|
+
detail: null,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** LocalClient's service, for a sidecar composed with a `clientApp`. */
|
|
145
|
+
#clientService(options) {
|
|
146
|
+
if (options.clientApp === undefined)
|
|
147
|
+
return undefined;
|
|
148
|
+
return new LocalClientService({
|
|
149
|
+
app: options.clientApp,
|
|
150
|
+
stateDir: options.stateDir,
|
|
151
|
+
secrets: options.secrets,
|
|
152
|
+
sqlite: options.sqlite,
|
|
153
|
+
port: () => this.#port,
|
|
154
|
+
credentials: async () => [await this.credential()],
|
|
155
|
+
env: options.env,
|
|
156
|
+
log: this.log,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
get port() {
|
|
160
|
+
return this.#port;
|
|
161
|
+
}
|
|
162
|
+
set port(port) {
|
|
163
|
+
this.#port = port;
|
|
164
|
+
this.auth.port = port;
|
|
165
|
+
}
|
|
166
|
+
// --- kernel pairing and custody ------------------------------------------------------------------------------
|
|
167
|
+
credential = () => this.options.secrets.get(credentialKey(this.options.stateDir));
|
|
168
|
+
/** Is the daemon paired with a kernel that (as far as it knows) still accepts it? */
|
|
169
|
+
get paired() {
|
|
170
|
+
const kernel = this.state.current.kernel;
|
|
171
|
+
return kernel !== undefined && kernel.revokedAt === undefined;
|
|
172
|
+
}
|
|
173
|
+
/** The kernel as this device, or undefined when unpaired or revoked. */
|
|
174
|
+
kernel() {
|
|
175
|
+
const kernel = this.state.current.kernel;
|
|
176
|
+
if (kernel === undefined || kernel.revokedAt !== undefined)
|
|
177
|
+
return undefined;
|
|
178
|
+
return new KernelLink(kernel.url, this.credential);
|
|
179
|
+
}
|
|
180
|
+
/** The kernel refused the credential: forget it, and say so. */
|
|
181
|
+
async markRevoked(reason) {
|
|
182
|
+
if (this.state.current.kernel === undefined || this.state.current.kernel.revokedAt !== undefined)
|
|
183
|
+
return;
|
|
184
|
+
this.log(`the kernel refused this device (${reason}); it is no longer paired`);
|
|
185
|
+
this.state.update((s) => ({ ...s, kernel: s.kernel && { ...s.kernel, revokedAt: new Date().toISOString() } }));
|
|
186
|
+
await this.options.secrets.delete(credentialKey(this.options.stateDir));
|
|
187
|
+
this.#relaySessions.clear();
|
|
188
|
+
this.#runner?.stop();
|
|
189
|
+
this.#commandLoop?.stop();
|
|
190
|
+
this.forgetSessions(() => true);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Run `body` against the kernel. A refused credential is checked once more (`GET /kernel/device/me`): only
|
|
194
|
+
* when the kernel refuses the device itself is it marked revoked and the credential deleted.
|
|
195
|
+
*/
|
|
196
|
+
async withKernel(body) {
|
|
197
|
+
const kernel = this.kernel();
|
|
198
|
+
if (kernel === undefined)
|
|
199
|
+
throw new DeviceRevoked("This daemon is not paired with a kernel");
|
|
200
|
+
try {
|
|
201
|
+
return await body(kernel);
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
if (error instanceof DeviceRevoked)
|
|
205
|
+
await this.confirmRevocation(kernel, error.message);
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async confirmRevocation(kernel, reason) {
|
|
210
|
+
try {
|
|
211
|
+
await kernel.me();
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (error instanceof DeviceRevoked)
|
|
215
|
+
await this.markRevoked(reason);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** Is the daemon started with this command kind (`--allow-commands`)? */
|
|
219
|
+
commandEnabled(kind) {
|
|
220
|
+
return (this.options.commands ?? []).includes(kind);
|
|
221
|
+
}
|
|
222
|
+
/** Each command kind's availability now: enabled, and for a browser or the computer, a companion connected. */
|
|
223
|
+
availability() {
|
|
224
|
+
const local = (kind) => ({
|
|
225
|
+
enabled: this.commandEnabled(kind),
|
|
226
|
+
available: this.commandEnabled(kind),
|
|
227
|
+
reason: this.commandEnabled(kind)
|
|
228
|
+
? null
|
|
229
|
+
: this.options.toolsOnly === true
|
|
230
|
+
? "This daemon runs the tools-only profile"
|
|
231
|
+
: `Not enabled on this daemon (start it with --allow-commands ${kind} and a --workspace)`,
|
|
232
|
+
});
|
|
233
|
+
const companion = (kind, client) => {
|
|
234
|
+
const enabled = this.commandEnabled(kind);
|
|
235
|
+
const connected = this.companions.connected(kind);
|
|
236
|
+
return {
|
|
237
|
+
enabled,
|
|
238
|
+
available: enabled && connected,
|
|
239
|
+
reason: !enabled
|
|
240
|
+
? `Not enabled on this daemon (start it with --allow-commands ${kind})`
|
|
241
|
+
: connected
|
|
242
|
+
? null
|
|
243
|
+
: `No ${client} companion is connected to this daemon`,
|
|
244
|
+
};
|
|
245
|
+
};
|
|
246
|
+
return {
|
|
247
|
+
terminal: local("terminal"),
|
|
248
|
+
files: local("files"),
|
|
249
|
+
browser: companion("browser", "browser-extension"),
|
|
250
|
+
computer: companion("computer", "computer-use"),
|
|
251
|
+
pty: ptyAvailable(),
|
|
252
|
+
toolsOnly: this.options.toolsOnly === true,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/** The command kinds the daemon can serve now. */
|
|
256
|
+
availableKinds() {
|
|
257
|
+
const availability = this.availability();
|
|
258
|
+
return ["terminal", "files", "browser", "computer"].filter((kind) => availability[kind].available);
|
|
259
|
+
}
|
|
260
|
+
async capabilities() {
|
|
261
|
+
const statuses = await this.harnessStatus();
|
|
262
|
+
const kinds = this.availableKinds();
|
|
263
|
+
return {
|
|
264
|
+
harnesses: statuses.filter((status) => status.available).map((status) => status.kind),
|
|
265
|
+
computerUse: kinds.includes("computer"),
|
|
266
|
+
browserExtension: kinds.includes("browser"),
|
|
267
|
+
commands: kinds,
|
|
268
|
+
toolsOnly: this.options.toolsOnly === true,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/** Tell the kernel what the device offers now, if that changed since the last report. */
|
|
272
|
+
async reportCapabilities() {
|
|
273
|
+
if (!this.paired)
|
|
274
|
+
return;
|
|
275
|
+
const capabilities = await this.capabilities();
|
|
276
|
+
const json = JSON.stringify(capabilities);
|
|
277
|
+
if (json === this.#reportedCapabilities)
|
|
278
|
+
return;
|
|
279
|
+
try {
|
|
280
|
+
await this.withKernel((kernel) => kernel.reportCapabilities(capabilities));
|
|
281
|
+
this.#reportedCapabilities = json;
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
// Best effort: the next change (or the command loop) reports again.
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/** A companion connected or went away: report what the device offers, and its sessions. */
|
|
288
|
+
capabilitiesChanged() {
|
|
289
|
+
void this.reportCapabilities();
|
|
290
|
+
void this.reportSessions();
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Start pairing with the kernel at `url`: the kernel's user code is in the returned status (and the log). The
|
|
294
|
+
* daemon polls in the background and stores the credential once a signed-in person confirms the code.
|
|
295
|
+
*/
|
|
296
|
+
async startKernelPairing(raw, request) {
|
|
297
|
+
if (this.#pairing !== undefined)
|
|
298
|
+
return this.#pairing;
|
|
299
|
+
const url = checkKernelUrl(raw);
|
|
300
|
+
// One kernel at a time: pairing elsewhere first needs this pairing revoked (or `eloxiv-daemon unpair`).
|
|
301
|
+
if (this.paired) {
|
|
302
|
+
throw new PairingRefused("AlreadyPaired", `This daemon is paired with ${this.state.current.kernel.url}; revoke it there or run \`eloxiv-daemon unpair\` first`);
|
|
303
|
+
}
|
|
304
|
+
const started = await startPairing(url, {
|
|
305
|
+
name: (request.name ?? `${hostname()} (${request.kind})`).slice(0, 100),
|
|
306
|
+
kind: request.kind,
|
|
307
|
+
platform: `${platform()}-${process.arch}`,
|
|
308
|
+
capabilities: await this.capabilities(),
|
|
309
|
+
});
|
|
310
|
+
this.#pairingError = undefined;
|
|
311
|
+
// Never the code: logs are collected, and whoever reads the code first can confirm it under their own account.
|
|
312
|
+
// It is shown only to the authenticated host or control channel (`/status`, `eloxiv-daemon pairing-code`) and
|
|
313
|
+
// in interactive output (`eloxiv-daemon pair`, a headless start on a terminal).
|
|
314
|
+
this.log(`pairing with ${url}: confirm the code at ${started.verificationUri}; it is shown in the desktop app, by \`eloxiv-daemon pairing-code\` or \`eloxiv-daemon pair\``);
|
|
315
|
+
const done = this.pollUntilPaired(url, started, request.kind).finally(() => {
|
|
316
|
+
this.#pairing = undefined;
|
|
317
|
+
});
|
|
318
|
+
this.#pairing = { started, url, done };
|
|
319
|
+
return this.#pairing;
|
|
320
|
+
}
|
|
321
|
+
async pollUntilPaired(url, started, kind) {
|
|
322
|
+
while (true) {
|
|
323
|
+
await new Promise((resolve) => setTimeout(resolve, started.interval * 1000));
|
|
324
|
+
let result;
|
|
325
|
+
try {
|
|
326
|
+
result = await pollPairing(url, started.pairingId, started.pollSecret);
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
if (error instanceof KernelError) {
|
|
330
|
+
this.#pairingError = error.message;
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (result.status === "pending")
|
|
336
|
+
continue;
|
|
337
|
+
if (result.status !== "paired") {
|
|
338
|
+
this.#pairingError = `The pairing was ${result.status}`;
|
|
339
|
+
throw new Error(this.#pairingError);
|
|
340
|
+
}
|
|
341
|
+
await this.options.secrets.set(credentialKey(this.options.stateDir), result.credential);
|
|
342
|
+
this.state.update((s) => ({
|
|
343
|
+
...s,
|
|
344
|
+
kernel: {
|
|
345
|
+
url,
|
|
346
|
+
deviceId: result.deviceId,
|
|
347
|
+
orgId: result.orgId,
|
|
348
|
+
subject: result.subject,
|
|
349
|
+
name: `${hostname()} (${kind})`,
|
|
350
|
+
kind,
|
|
351
|
+
pairedAt: new Date().toISOString(),
|
|
352
|
+
},
|
|
353
|
+
}));
|
|
354
|
+
this.log(`paired as device ${result.deviceId} in ${result.orgId}`);
|
|
355
|
+
void this.reportSessions();
|
|
356
|
+
this.startCommands();
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/** Forget the kernel pairing (the device stays listed on the kernel until someone revokes it there). */
|
|
361
|
+
async unpair() {
|
|
362
|
+
this.#runner?.stop();
|
|
363
|
+
this.#commandLoop?.stop();
|
|
364
|
+
await this.options.secrets.delete(credentialKey(this.options.stateDir));
|
|
365
|
+
this.state.update((s) => ({ ...s, kernel: undefined }));
|
|
366
|
+
this.forgetSessions(() => true);
|
|
367
|
+
}
|
|
368
|
+
// --- harness sessions (follow-ups) ---------------------------------------------------------------------------
|
|
369
|
+
/** The harness sessions resumable turns kept, newest last. */
|
|
370
|
+
get harnessSessions() {
|
|
371
|
+
return this.state.current.harnessSessions ?? [];
|
|
372
|
+
}
|
|
373
|
+
/** Forget the kept sessions `which` selects, removing the directories the daemon created for them. */
|
|
374
|
+
forgetSessions(which) {
|
|
375
|
+
const forgotten = this.harnessSessions.filter(which);
|
|
376
|
+
if (forgotten.length === 0)
|
|
377
|
+
return;
|
|
378
|
+
const kept = this.harnessSessions.filter((record) => !which(record));
|
|
379
|
+
this.state.update((s) => ({ ...s, harnessSessions: kept }));
|
|
380
|
+
for (const record of forgotten) {
|
|
381
|
+
if (record.owned && !kept.some((other) => other.cwd === record.cwd)) {
|
|
382
|
+
rmSync(record.cwd, { recursive: true, force: true });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
/** Keep `record` (replacing the session it continues), and forget the least recently used beyond the limit. */
|
|
387
|
+
keepSession(record, replaces) {
|
|
388
|
+
const others = this.harnessSessions.filter((r) => r.id !== record.id && r.id !== replaces);
|
|
389
|
+
this.state.update((s) => ({ ...s, harnessSessions: [...others, record] }));
|
|
390
|
+
const excess = this.harnessSessions.length - MAX_HARNESS_SESSIONS;
|
|
391
|
+
if (excess > 0) {
|
|
392
|
+
const oldest = new Set(this.harnessSessions.slice(0, excess).map((r) => r.id));
|
|
393
|
+
this.forgetSessions((r) => oldest.has(r.id));
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
async harnessStatus(refresh = false) {
|
|
397
|
+
if (this.#harnessStatus === undefined || refresh) {
|
|
398
|
+
this.#harnessStatus = await Promise.all(KINDS.map((kind) => detectHarness(this.harnesses[kind])));
|
|
399
|
+
}
|
|
400
|
+
return this.#harnessStatus;
|
|
401
|
+
}
|
|
402
|
+
async status() {
|
|
403
|
+
const kernel = this.state.current.kernel;
|
|
404
|
+
const pairing = this.#pairing;
|
|
405
|
+
return {
|
|
406
|
+
mode: this.options.mode,
|
|
407
|
+
kernel: {
|
|
408
|
+
state: pairing !== undefined
|
|
409
|
+
? "pairing"
|
|
410
|
+
: kernel === undefined
|
|
411
|
+
? "unpaired"
|
|
412
|
+
: kernel.revokedAt !== undefined
|
|
413
|
+
? "revoked"
|
|
414
|
+
: "paired",
|
|
415
|
+
url: pairing?.url ?? kernel?.url ?? null,
|
|
416
|
+
deviceId: kernel?.deviceId ?? null,
|
|
417
|
+
orgId: kernel?.orgId ?? null,
|
|
418
|
+
userCode: pairing?.started.userCode ?? null,
|
|
419
|
+
verificationUri: pairing?.started.verificationUriComplete ?? null,
|
|
420
|
+
},
|
|
421
|
+
secretStore: this.options.secrets.kind,
|
|
422
|
+
harnesses: await this.harnessStatus(),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
get pairingError() {
|
|
426
|
+
return this.#pairingError;
|
|
427
|
+
}
|
|
428
|
+
// --- relay ---------------------------------------------------------------------------------------------------
|
|
429
|
+
/**
|
|
430
|
+
* The kernel credential a relayed call uses: a harness's turn session (agent-originated), a short-lived agent
|
|
431
|
+
* session for a local client's MCP use, or the device credential (the person) for a local client's action
|
|
432
|
+
* calls. Never returned to the client.
|
|
433
|
+
*/
|
|
434
|
+
async relayToken(client, purpose) {
|
|
435
|
+
if (client.turn !== undefined)
|
|
436
|
+
return client.turn.agentToken;
|
|
437
|
+
if (purpose === "action")
|
|
438
|
+
return undefined; // the device credential, read by KernelLink
|
|
439
|
+
const cached = this.#relaySessions.get(client.id);
|
|
440
|
+
if (cached !== undefined && cached.expiresAt > Date.now() + 60_000)
|
|
441
|
+
return cached.token;
|
|
442
|
+
const session = await this.withKernel((kernel) => kernel.relaySession(`mcp for ${client.kind} ${client.name}`, 3600));
|
|
443
|
+
this.#relaySessions.set(client.id, { token: session.token, expiresAt: Date.parse(session.expiresAt) });
|
|
444
|
+
return session.token;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* The idempotency key a runner turn's tool call gets: the turn, the tool, its input and how many identical
|
|
448
|
+
* calls came before it in this attempt. A re-run attempt making the same calls replays them instead of acting
|
|
449
|
+
* again; a different call is a new key.
|
|
450
|
+
*/
|
|
451
|
+
idempotencyKey(client, tool, input) {
|
|
452
|
+
const scope = client.turn?.idempotencyScope;
|
|
453
|
+
if (scope === undefined)
|
|
454
|
+
return undefined;
|
|
455
|
+
const hash = sha256Hex(`${tool}\u0000${canonicalize(input)}`).slice(0, 24);
|
|
456
|
+
const counters = this.#occurrences.get(scope) ?? new Map();
|
|
457
|
+
this.#occurrences.set(scope, counters);
|
|
458
|
+
const occurrence = counters.get(hash) ?? 0;
|
|
459
|
+
counters.set(hash, occurrence + 1);
|
|
460
|
+
return `${scope}:${hash}:${occurrence}`;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Before the relay forwards a call of a runner turn's harness: whether the turn was cancelled (or its lease
|
|
464
|
+
* lost). The runner otherwise hears of a cancellation only at its next heartbeat, and the harness could act in
|
|
465
|
+
* between; this asks the kernel now (a heartbeat), and a cancelled turn's harness is stopped before the call is
|
|
466
|
+
* refused. Not a runner turn (a local client's): false.
|
|
467
|
+
*/
|
|
468
|
+
async turnStopped(client) {
|
|
469
|
+
const turnId = client.turn?.turnId;
|
|
470
|
+
const check = turnId === undefined ? undefined : this.#turnChecks.get(turnId);
|
|
471
|
+
return check === undefined ? false : await check();
|
|
472
|
+
}
|
|
473
|
+
// --- turns ---------------------------------------------------------------------------------------------------
|
|
474
|
+
/**
|
|
475
|
+
* Run one harness turn on this machine with the Eloxiv tools through the relay, as the device's subject's
|
|
476
|
+
* agent (an agent session bound to this device). `scope` makes tool calls idempotent per turn (runner turns).
|
|
477
|
+
*/
|
|
478
|
+
async runTurn(input) {
|
|
479
|
+
// A follow-up resumes only a session this daemon kept, with its harness, in its working directory.
|
|
480
|
+
const resume = input.resume ?? undefined;
|
|
481
|
+
const resumed = resume === undefined
|
|
482
|
+
? undefined
|
|
483
|
+
: this.harnessSessions.find((r) => r.id === resume && r.harness === input.harness);
|
|
484
|
+
if (resume !== undefined && resumed === undefined) {
|
|
485
|
+
return {
|
|
486
|
+
outcome: "failed",
|
|
487
|
+
result: null,
|
|
488
|
+
usage: null,
|
|
489
|
+
error: `This device keeps no ${input.harness} session ${resume} to follow up`,
|
|
490
|
+
events: [],
|
|
491
|
+
sessionId: null,
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
// The tools-only profile never gives a harness its built-in file and shell tools.
|
|
495
|
+
if (input.workspaceTools === true && this.options.toolsOnly === true) {
|
|
496
|
+
return {
|
|
497
|
+
outcome: "failed",
|
|
498
|
+
result: null,
|
|
499
|
+
usage: null,
|
|
500
|
+
error: "This device runs the tools-only profile: turns cannot have workspace tools",
|
|
501
|
+
events: [],
|
|
502
|
+
sessionId: null,
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
const keep = input.resumable === true || resumed !== undefined;
|
|
506
|
+
const session = await this.withKernel((kernel) => kernel.relaySession(`turn ${input.turnId}`, input.timeoutMs / 1000 + 300, input.kernelTurn === true ? input.turnId : undefined));
|
|
507
|
+
const grant = this.auth.grantHarness({
|
|
508
|
+
turnId: input.turnId,
|
|
509
|
+
agentToken: session.token,
|
|
510
|
+
idempotencyScope: input.idempotencyScope,
|
|
511
|
+
actions: input.actions === undefined || input.actions === null ? undefined : new Set(input.actions),
|
|
512
|
+
});
|
|
513
|
+
// No named directory: a fresh, empty one, outside the state directory, removed with the turn.
|
|
514
|
+
const turnRoot = turnRootFor(this.options.stateDir);
|
|
515
|
+
let scratchCwd;
|
|
516
|
+
let sessionCwd;
|
|
517
|
+
if (resumed === undefined && input.cwd === null && this.options.workspace === undefined) {
|
|
518
|
+
if (keep) {
|
|
519
|
+
// A resumable turn's directory outlives the turn: the follow-up resumes the session in it.
|
|
520
|
+
const root = sessionRootFor(this.options.stateDir);
|
|
521
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
522
|
+
sessionCwd = mkdtempSync(join(root, "session-"));
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
mkdirSync(turnRoot, { recursive: true, mode: 0o700 });
|
|
526
|
+
scratchCwd = mkdtempSync(join(turnRoot, "turn-"));
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
const cwd = resumed?.cwd ?? input.cwd ?? this.options.workspace ?? sessionCwd ?? scratchCwd;
|
|
530
|
+
const sessionId = `turn:${input.turnId}`;
|
|
531
|
+
this.#sessions.set(sessionId, {
|
|
532
|
+
id: sessionId,
|
|
533
|
+
kind: "harness",
|
|
534
|
+
label: `${input.harness} turn ${input.turnId}`,
|
|
535
|
+
startedAt: new Date().toISOString(),
|
|
536
|
+
endedAt: null,
|
|
537
|
+
detail: input.harness,
|
|
538
|
+
});
|
|
539
|
+
void this.reportSessions();
|
|
540
|
+
let kept = false;
|
|
541
|
+
try {
|
|
542
|
+
const config = this.harnesses[input.harness];
|
|
543
|
+
const result = await (config.protocol === "acp" ? runAcpHarness : runHarness)(config, {
|
|
544
|
+
prompt: input.prompt,
|
|
545
|
+
cwd,
|
|
546
|
+
resumable: keep,
|
|
547
|
+
resume,
|
|
548
|
+
workspaceTools: input.workspaceTools,
|
|
549
|
+
model: input.model,
|
|
550
|
+
timeoutMs: input.timeoutMs,
|
|
551
|
+
mcp: { url: `http://127.0.0.1:${this.#port}/mcp`, token: grant.token },
|
|
552
|
+
scratchRoot: join(this.options.stateDir, "turns"),
|
|
553
|
+
signal: input.signal,
|
|
554
|
+
onEvent: input.onEvent,
|
|
555
|
+
onRawLine: input.onRawLine,
|
|
556
|
+
});
|
|
557
|
+
if (keep && result.sessionId !== null) {
|
|
558
|
+
this.keepSession({
|
|
559
|
+
id: result.sessionId,
|
|
560
|
+
harness: input.harness,
|
|
561
|
+
cwd,
|
|
562
|
+
owned: resumed?.owned ?? sessionCwd !== undefined,
|
|
563
|
+
turnId: input.turnId,
|
|
564
|
+
lastUsedAt: new Date().toISOString(),
|
|
565
|
+
}, resumed?.id);
|
|
566
|
+
kept = true;
|
|
567
|
+
}
|
|
568
|
+
return result;
|
|
569
|
+
}
|
|
570
|
+
finally {
|
|
571
|
+
grant.revoke();
|
|
572
|
+
// A resumable turn that left no session to resume: its directory goes with it.
|
|
573
|
+
if (sessionCwd !== undefined && !kept)
|
|
574
|
+
rmSync(sessionCwd, { recursive: true, force: true });
|
|
575
|
+
if (scratchCwd !== undefined) {
|
|
576
|
+
rmSync(scratchCwd, { recursive: true, force: true });
|
|
577
|
+
// The root too, once no other turn uses it.
|
|
578
|
+
try {
|
|
579
|
+
rmdirSync(turnRoot);
|
|
580
|
+
}
|
|
581
|
+
catch {
|
|
582
|
+
// Another turn is still working in it.
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
if (input.idempotencyScope !== undefined)
|
|
586
|
+
this.#occurrences.delete(input.idempotencyScope);
|
|
587
|
+
const session = this.#sessions.get(sessionId);
|
|
588
|
+
if (session !== undefined)
|
|
589
|
+
this.#sessions.set(sessionId, { ...session, endedAt: new Date().toISOString() });
|
|
590
|
+
void this.reportSessions();
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
// --- the headless runner -------------------------------------------------------------------------------------
|
|
594
|
+
/** Serve turns addressed to this device until stopped or revoked. */
|
|
595
|
+
startRunner() {
|
|
596
|
+
if (this.#runner !== undefined)
|
|
597
|
+
return this.#runner;
|
|
598
|
+
const controller = new AbortController();
|
|
599
|
+
const done = this.runnerLoop(controller.signal).finally(() => {
|
|
600
|
+
this.#runner = undefined;
|
|
601
|
+
});
|
|
602
|
+
this.#runner = { stop: () => controller.abort(), done };
|
|
603
|
+
return this.#runner;
|
|
604
|
+
}
|
|
605
|
+
async runnerLoop(signal) {
|
|
606
|
+
// A result a previous process could not report goes first: asking for work as a fresh runner would put
|
|
607
|
+
// its turn back in the queue and run it again.
|
|
608
|
+
const pending = this.state.current.pendingCompletion;
|
|
609
|
+
if (pending !== undefined)
|
|
610
|
+
await this.complete(pending, signal);
|
|
611
|
+
if (signal.aborted)
|
|
612
|
+
return;
|
|
613
|
+
let fresh = true;
|
|
614
|
+
let backoff = 500;
|
|
615
|
+
while (!signal.aborted && this.paired) {
|
|
616
|
+
let claimed;
|
|
617
|
+
try {
|
|
618
|
+
claimed = await this.withKernel((kernel) => kernel.nextTurn(this.options.pollWaitMs ?? 25_000, fresh, signal));
|
|
619
|
+
fresh = false;
|
|
620
|
+
backoff = 500;
|
|
621
|
+
}
|
|
622
|
+
catch (error) {
|
|
623
|
+
if (signal.aborted || error instanceof DeviceRevoked)
|
|
624
|
+
return;
|
|
625
|
+
this.log(`runner: could not reach the kernel (${String(error)}); retrying`);
|
|
626
|
+
await new Promise((resolve) => setTimeout(resolve, backoff));
|
|
627
|
+
backoff = Math.min(backoff * 2, 10_000);
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
if (claimed.turn === null)
|
|
631
|
+
continue;
|
|
632
|
+
await this.serveTurn(claimed.turn, signal);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
async serveTurn(turn, stopSignal) {
|
|
636
|
+
this.log(`runner: turn ${turn.id} attempt ${turn.attempt} (${turn.harness})`);
|
|
637
|
+
this.state.update((s) => ({
|
|
638
|
+
...s,
|
|
639
|
+
inflight: { turnId: turn.id, attempt: turn.attempt, since: new Date().toISOString() },
|
|
640
|
+
}));
|
|
641
|
+
const controller = new AbortController();
|
|
642
|
+
const onStop = () => controller.abort();
|
|
643
|
+
stopSignal.addEventListener("abort", onStop, { once: true });
|
|
644
|
+
const pending = [];
|
|
645
|
+
let seq = 0;
|
|
646
|
+
let flushing = Promise.resolve();
|
|
647
|
+
let lost = false;
|
|
648
|
+
/**
|
|
649
|
+
* Send what is pending in pages (or an empty heartbeat); stop the harness when the kernel says so. A page the
|
|
650
|
+
* kernel did not take stays pending, in order, for the next call: nothing is dropped.
|
|
651
|
+
*/
|
|
652
|
+
const send = async () => {
|
|
653
|
+
do {
|
|
654
|
+
if (lost)
|
|
655
|
+
return;
|
|
656
|
+
const batch = pending.slice(0, EVENT_PAGE);
|
|
657
|
+
try {
|
|
658
|
+
const answer = await this.withKernel((kernel) => kernel.appendEvents(turn.id, turn.lease, batch));
|
|
659
|
+
pending.splice(0, batch.length);
|
|
660
|
+
if (answer.stop)
|
|
661
|
+
controller.abort();
|
|
662
|
+
}
|
|
663
|
+
catch (error) {
|
|
664
|
+
if ((error instanceof KernelError && error.status === 409) || error instanceof DeviceRevoked) {
|
|
665
|
+
lost = true;
|
|
666
|
+
controller.abort();
|
|
667
|
+
}
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
} while (pending.length > 0);
|
|
671
|
+
};
|
|
672
|
+
const flush = () => {
|
|
673
|
+
flushing = flushing.then(send);
|
|
674
|
+
return flushing;
|
|
675
|
+
};
|
|
676
|
+
// A relayed call asks first (`turnStopped`): pending events and a heartbeat go out, and a stop is acted on.
|
|
677
|
+
this.#turnChecks.set(turn.id, async () => {
|
|
678
|
+
await flush();
|
|
679
|
+
return controller.signal.aborted;
|
|
680
|
+
});
|
|
681
|
+
// Heartbeat and batching: events go out every 300 ms, and an empty batch renews the lease.
|
|
682
|
+
let lastFlush = Date.now();
|
|
683
|
+
const ticker = setInterval(() => {
|
|
684
|
+
if (pending.length > 0 || Date.now() - lastFlush > turn.leaseMs / 3) {
|
|
685
|
+
lastFlush = Date.now();
|
|
686
|
+
void flush();
|
|
687
|
+
}
|
|
688
|
+
}, Math.min(300, turn.leaseMs / 4));
|
|
689
|
+
let result;
|
|
690
|
+
try {
|
|
691
|
+
result = await this.runTurn({
|
|
692
|
+
turnId: turn.id,
|
|
693
|
+
harness: turn.harness,
|
|
694
|
+
prompt: turn.prompt,
|
|
695
|
+
cwd: turn.cwd,
|
|
696
|
+
model: turn.model,
|
|
697
|
+
timeoutMs: turn.timeoutMs,
|
|
698
|
+
idempotencyScope: `device-turn:${turn.id}`,
|
|
699
|
+
kernelTurn: true,
|
|
700
|
+
actions: turn.actions,
|
|
701
|
+
workspaceTools: turn.workspaceTools,
|
|
702
|
+
resumable: turn.resumable,
|
|
703
|
+
resume: turn.resume,
|
|
704
|
+
signal: controller.signal,
|
|
705
|
+
onEvent: (event) => {
|
|
706
|
+
pending.push({ ...event, seq: seq++ });
|
|
707
|
+
},
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
catch (error) {
|
|
711
|
+
result = {
|
|
712
|
+
outcome: "failed",
|
|
713
|
+
result: null,
|
|
714
|
+
usage: null,
|
|
715
|
+
error: String(error),
|
|
716
|
+
events: [],
|
|
717
|
+
sessionId: null,
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
finally {
|
|
721
|
+
clearInterval(ticker);
|
|
722
|
+
stopSignal.removeEventListener("abort", onStop);
|
|
723
|
+
this.#turnChecks.delete(turn.id);
|
|
724
|
+
}
|
|
725
|
+
// The events still pending go out (in pages) while the lease holds; give up on them only once it is lost.
|
|
726
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
727
|
+
if (pending.length === 0 || lost || stopSignal.aborted)
|
|
728
|
+
break;
|
|
729
|
+
await flush();
|
|
730
|
+
if (pending.length > 0)
|
|
731
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(250 * 2 ** attempt, 5_000)));
|
|
732
|
+
}
|
|
733
|
+
await flush();
|
|
734
|
+
if (stopSignal.aborted && result.outcome === "cancelled")
|
|
735
|
+
return; // the daemon is stopping: leave the turn leased
|
|
736
|
+
if (!lost) {
|
|
737
|
+
await this.complete({
|
|
738
|
+
turnId: turn.id,
|
|
739
|
+
lease: turn.lease,
|
|
740
|
+
outcome: result.outcome === "succeeded" ? "succeeded" : "failed",
|
|
741
|
+
result: result.result,
|
|
742
|
+
usage: result.usage,
|
|
743
|
+
error: result.error,
|
|
744
|
+
sessionId: turn.resumable === true || (turn.resume ?? null) !== null ? result.sessionId : null,
|
|
745
|
+
}, stopSignal);
|
|
746
|
+
}
|
|
747
|
+
this.state.update((s) => ({ ...s, inflight: undefined }));
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Report a turn's outcome until the kernel takes it: the result is kept in the state file first, so a restart
|
|
751
|
+
* reports it too, and it is retried (with backoff, without a cap on attempts) until the kernel settles the
|
|
752
|
+
* turn, says this attempt lost its lease, or refuses the device. Only those clear it.
|
|
753
|
+
*/
|
|
754
|
+
async complete(completion, signal) {
|
|
755
|
+
this.state.update((s) => ({ ...s, pendingCompletion: completion }));
|
|
756
|
+
const max = this.options.retryBackoffMaxMs ?? 30_000;
|
|
757
|
+
let backoff = Math.min(250, max);
|
|
758
|
+
while (!signal.aborted) {
|
|
759
|
+
try {
|
|
760
|
+
const settled = await this.withKernel((kernel) => kernel.completeTurn(completion));
|
|
761
|
+
this.log(`runner: turn ${completion.turnId} ${settled.duplicate ? "was already settled" : `settled ${completion.outcome}`}`);
|
|
762
|
+
break;
|
|
763
|
+
}
|
|
764
|
+
catch (error) {
|
|
765
|
+
if (error instanceof KernelError && error.status === 409) {
|
|
766
|
+
this.log(`runner: turn ${completion.turnId} is no longer this attempt's; its result is dropped`);
|
|
767
|
+
break;
|
|
768
|
+
}
|
|
769
|
+
if (error instanceof DeviceRevoked && !this.paired)
|
|
770
|
+
break;
|
|
771
|
+
await new Promise((resolve) => setTimeout(resolve, backoff));
|
|
772
|
+
backoff = Math.min(backoff * 2, max);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
if (!signal.aborted)
|
|
776
|
+
this.state.update((s) => ({ ...s, pendingCompletion: undefined }));
|
|
777
|
+
}
|
|
778
|
+
async stopRunner() {
|
|
779
|
+
const runner = this.#runner;
|
|
780
|
+
runner?.stop();
|
|
781
|
+
await runner?.done;
|
|
782
|
+
}
|
|
783
|
+
// --- device commands (DeviceControl) -------------------------------------------------------------------------
|
|
784
|
+
/** Serve device commands (when the daemon is paired and enabled for some kind) until stopped or revoked. */
|
|
785
|
+
startCommands() {
|
|
786
|
+
if (this.#commandLoop !== undefined || (this.options.commands ?? []).length === 0 || !this.paired)
|
|
787
|
+
return;
|
|
788
|
+
const controller = new AbortController();
|
|
789
|
+
const done = this.commandLoop(controller.signal).finally(() => {
|
|
790
|
+
this.#commandLoop = undefined;
|
|
791
|
+
});
|
|
792
|
+
this.#commandLoop = { stop: () => controller.abort(), done };
|
|
793
|
+
}
|
|
794
|
+
async stopCommands() {
|
|
795
|
+
const loop = this.#commandLoop;
|
|
796
|
+
loop?.stop();
|
|
797
|
+
await loop?.done;
|
|
798
|
+
}
|
|
799
|
+
/** Stop everything that serves the kernel (the runner and the command loop). */
|
|
800
|
+
async stop() {
|
|
801
|
+
this.terminals.closeAll();
|
|
802
|
+
await Promise.all([this.stopRunner(), this.stopCommands(), this.client?.close()]);
|
|
803
|
+
}
|
|
804
|
+
/** Open a terminal for a local client, in the workspace (or a directory in it). Only with the terminal enabled. */
|
|
805
|
+
openTerminal(owner, input) {
|
|
806
|
+
if (!this.commandEnabled("terminal")) {
|
|
807
|
+
throw new TerminalError(403, "The terminal is not enabled on this daemon (--allow-commands terminal)");
|
|
808
|
+
}
|
|
809
|
+
let cwd;
|
|
810
|
+
try {
|
|
811
|
+
cwd = confine(this.options.workspace, this.options.stateDir, input.cwd);
|
|
812
|
+
}
|
|
813
|
+
catch (error) {
|
|
814
|
+
throw new TerminalError(403, error.message);
|
|
815
|
+
}
|
|
816
|
+
return this.terminals.open(owner, { cwd, cols: input.cols, rows: input.rows });
|
|
817
|
+
}
|
|
818
|
+
async commandLoop(signal) {
|
|
819
|
+
let backoff = 500;
|
|
820
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
821
|
+
while (!signal.aborted && this.paired) {
|
|
822
|
+
// Companions that stopped asking no longer count as connected.
|
|
823
|
+
this.companions.prune();
|
|
824
|
+
await this.reportCapabilities();
|
|
825
|
+
const kinds = this.availableKinds();
|
|
826
|
+
if (kinds.length === 0 || this.#commandsRunning >= MAX_COMMANDS_AT_ONCE) {
|
|
827
|
+
await wait(250);
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
let claimed;
|
|
831
|
+
try {
|
|
832
|
+
// A short poll: a companion that connects meanwhile is asked for at the next one.
|
|
833
|
+
const waitMs = Math.min(this.options.pollWaitMs ?? 25_000, 10_000);
|
|
834
|
+
claimed = await this.withKernel((kernel) => kernel.nextCommand(kinds, waitMs, signal));
|
|
835
|
+
backoff = 500;
|
|
836
|
+
}
|
|
837
|
+
catch (error) {
|
|
838
|
+
if (signal.aborted || error instanceof DeviceRevoked)
|
|
839
|
+
return;
|
|
840
|
+
this.log(`commands: could not reach the kernel (${String(error)}); retrying`);
|
|
841
|
+
await wait(backoff);
|
|
842
|
+
backoff = Math.min(backoff * 2, 10_000);
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
if (claimed.command !== null)
|
|
846
|
+
void this.serveCommand(claimed.command, signal);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
/** Run one command (here, or through its companion) and report it once, before its deadline. */
|
|
850
|
+
async serveCommand(command, signal) {
|
|
851
|
+
this.#commandsRunning += 1;
|
|
852
|
+
try {
|
|
853
|
+
const kind = commandKindOf(command.operation);
|
|
854
|
+
/** Whether the kernel says the command should stop (cancelled, or no longer this device's). */
|
|
855
|
+
const stopped = () => this.withKernel((kernel) => kernel.checkCommand({ commandId: command.id, lease: command.lease })).then((answer) => answer.stop, () => false);
|
|
856
|
+
let outcome;
|
|
857
|
+
if (!this.commandEnabled(kind)) {
|
|
858
|
+
// Fails closed: a kind the daemon was not started with never runs, whatever the kernel handed out.
|
|
859
|
+
outcome = { outcome: "failed", result: null, error: `${kind} commands are not enabled on this device` };
|
|
860
|
+
}
|
|
861
|
+
else if (await stopped()) {
|
|
862
|
+
// Asked once more just before acting: a command cancelled after it was taken never runs.
|
|
863
|
+
outcome = { outcome: "cancelled", result: null, error: "Cancelled before the device ran it; it never ran" };
|
|
864
|
+
}
|
|
865
|
+
else {
|
|
866
|
+
// While it waits or runs, the kernel is asked again: a cancellation stops what can still be stopped.
|
|
867
|
+
const cancel = new AbortController();
|
|
868
|
+
const check = async () => {
|
|
869
|
+
if (await stopped())
|
|
870
|
+
cancel.abort();
|
|
871
|
+
};
|
|
872
|
+
const watcher = setInterval(() => void check(), COMMAND_CHECK_MS);
|
|
873
|
+
try {
|
|
874
|
+
if (isLocalKind(kind)) {
|
|
875
|
+
const controller = new AbortController();
|
|
876
|
+
const onAbort = () => controller.abort();
|
|
877
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
878
|
+
outcome = await runLocalCommand(command, {
|
|
879
|
+
workspace: this.options.workspace,
|
|
880
|
+
stateDir: this.options.stateDir,
|
|
881
|
+
signal: controller.signal,
|
|
882
|
+
cancel: cancel.signal,
|
|
883
|
+
});
|
|
884
|
+
signal.removeEventListener("abort", onAbort);
|
|
885
|
+
}
|
|
886
|
+
else {
|
|
887
|
+
outcome = await this.companions.run(kind, command, signal, cancel.signal);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
finally {
|
|
891
|
+
clearInterval(watcher);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
this.log(`commands: ${command.operation} ${command.id} ${outcome.outcome}`);
|
|
895
|
+
// Reported until the kernel takes it, refuses it, or its deadline (and the network's grace) has passed.
|
|
896
|
+
const until = Date.parse(command.deadline) + 10_000;
|
|
897
|
+
let backoff = 250;
|
|
898
|
+
while (!signal.aborted && Date.now() < until) {
|
|
899
|
+
try {
|
|
900
|
+
await this.withKernel((kernel) => kernel.completeCommand({ commandId: command.id, lease: command.lease, ...outcome }));
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
catch (error) {
|
|
904
|
+
if (error instanceof KernelError || error instanceof DeviceRevoked)
|
|
905
|
+
return;
|
|
906
|
+
await new Promise((resolve) => setTimeout(resolve, backoff));
|
|
907
|
+
backoff = Math.min(backoff * 2, 5_000);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
finally {
|
|
912
|
+
this.#commandsRunning -= 1;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
/** Register (or with null remove) the push subscription of the host beside this daemon. */
|
|
916
|
+
registerPush(subscription) {
|
|
917
|
+
return this.withKernel((kernel) => kernel.registerPush(subscription));
|
|
918
|
+
}
|
|
919
|
+
// --- sessions (DeviceControl) --------------------------------------------------------------------------------
|
|
920
|
+
sessions() {
|
|
921
|
+
// A companion's session says where it runs (a browser extension's origin) while it is connected.
|
|
922
|
+
for (const companion of this.companions.companions()) {
|
|
923
|
+
const session = this.#sessions.get(`client:${companion.client}`);
|
|
924
|
+
if (session !== undefined && companion.origin !== null && session.detail !== companion.origin) {
|
|
925
|
+
this.#sessions.set(session.id, { ...session, detail: companion.origin });
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
const open = [...this.#sessions.values()].filter((s) => s.endedAt === null);
|
|
929
|
+
const ended = [...this.#sessions.values()].filter((s) => s.endedAt !== null).slice(-20);
|
|
930
|
+
return [...open, ...ended];
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Report the sessions, one report at a time, each read when it is sent: two reports in flight at once (a client
|
|
934
|
+
* paired, then its companion connected) could commit at the kernel in the other order and leave the older state
|
|
935
|
+
* standing, with nothing to report again.
|
|
936
|
+
*/
|
|
937
|
+
reportSessions() {
|
|
938
|
+
if (!this.paired)
|
|
939
|
+
return Promise.resolve();
|
|
940
|
+
const previous = this.#reportingSessions;
|
|
941
|
+
const report = (async () => {
|
|
942
|
+
await previous;
|
|
943
|
+
try {
|
|
944
|
+
await this.withKernel((kernel) => kernel.reportSessions(this.sessions()));
|
|
945
|
+
}
|
|
946
|
+
catch {
|
|
947
|
+
// Best effort: the next change reports again.
|
|
948
|
+
}
|
|
949
|
+
})();
|
|
950
|
+
this.#reportingSessions = report;
|
|
951
|
+
return report;
|
|
952
|
+
}
|
|
953
|
+
onLocalClientPaired(client) {
|
|
954
|
+
this.#sessions.set(`client:${client.clientId}`, {
|
|
955
|
+
id: `client:${client.clientId}`,
|
|
956
|
+
kind: client.kind,
|
|
957
|
+
label: client.name,
|
|
958
|
+
startedAt: new Date().toISOString(),
|
|
959
|
+
endedAt: null,
|
|
960
|
+
detail: null,
|
|
961
|
+
});
|
|
962
|
+
void this.reportSessions();
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
//# sourceMappingURL=Daemon.js.map
|