@brud/daemon 0.0.0-stage → 0.0.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.
Files changed (61) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +67 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.js +88 -0
  5. package/dist/client/DaemonClient.d.ts +55 -0
  6. package/dist/client/DaemonClient.js +383 -0
  7. package/dist/client/connectToDaemon.d.ts +19 -0
  8. package/dist/client/connectToDaemon.js +131 -0
  9. package/dist/client/errors.d.ts +74 -0
  10. package/dist/client/errors.js +104 -0
  11. package/dist/client/identity.d.ts +3 -0
  12. package/dist/client/identity.js +7 -0
  13. package/dist/client/index.d.ts +6 -0
  14. package/dist/client/index.js +23 -0
  15. package/dist/client/socket.d.ts +9 -0
  16. package/dist/client/socket.js +101 -0
  17. package/dist/client/spawn.d.ts +7 -0
  18. package/dist/client/spawn.js +171 -0
  19. package/dist/index.d.ts +12 -0
  20. package/dist/index.js +29 -0
  21. package/dist/instanceRegistry.d.ts +130 -0
  22. package/dist/instanceRegistry.js +332 -0
  23. package/dist/lifecycle/endpoint.d.ts +19 -0
  24. package/dist/lifecycle/endpoint.js +124 -0
  25. package/dist/lifecycle/idle.d.ts +28 -0
  26. package/dist/lifecycle/idle.js +69 -0
  27. package/dist/lifecycle/index.d.ts +4 -0
  28. package/dist/lifecycle/index.js +21 -0
  29. package/dist/lifecycle/lock.d.ts +28 -0
  30. package/dist/lifecycle/lock.js +155 -0
  31. package/dist/lifecycle/shutdown.d.ts +39 -0
  32. package/dist/lifecycle/shutdown.js +115 -0
  33. package/dist/operatorConfig.d.ts +36 -0
  34. package/dist/operatorConfig.js +92 -0
  35. package/dist/security/channel.d.ts +113 -0
  36. package/dist/security/channel.js +448 -0
  37. package/dist/security/noise.d.ts +64 -0
  38. package/dist/security/noise.js +313 -0
  39. package/dist/security/ownership.d.ts +36 -0
  40. package/dist/security/ownership.js +86 -0
  41. package/dist/security/peerCredentials.d.ts +104 -0
  42. package/dist/security/peerCredentials.js +244 -0
  43. package/dist/server/Connection.d.ts +70 -0
  44. package/dist/server/Connection.js +412 -0
  45. package/dist/server/DaemonServer.d.ts +77 -0
  46. package/dist/server/DaemonServer.js +396 -0
  47. package/dist/server/createDaemon.d.ts +52 -0
  48. package/dist/server/createDaemon.js +165 -0
  49. package/dist/server/dispatch.d.ts +52 -0
  50. package/dist/server/dispatch.js +291 -0
  51. package/dist/server/framing.d.ts +63 -0
  52. package/dist/server/framing.js +196 -0
  53. package/dist/server/handshake.d.ts +22 -0
  54. package/dist/server/handshake.js +94 -0
  55. package/dist/server/protocolValidation.d.ts +47 -0
  56. package/dist/server/protocolValidation.js +366 -0
  57. package/dist/server/wireErrors.d.ts +5 -0
  58. package/dist/server/wireErrors.js +190 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +6 -0
  61. package/package.json +55 -4
@@ -0,0 +1,396 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DaemonServer = exports.DEFAULT_MAX_CONNECTIONS = void 0;
37
+ const node_crypto_1 = require("node:crypto");
38
+ const promises_1 = require("node:fs/promises");
39
+ const node_net_1 = require("node:net");
40
+ const Connection_js_1 = require("./Connection.js");
41
+ const dispatch_js_1 = require("./dispatch.js");
42
+ const channel_js_1 = require("../security/channel.js");
43
+ const ownership_js_1 = require("../security/ownership.js");
44
+ const peerCredentials_js_1 = require("../security/peerCredentials.js");
45
+ const noise_js_1 = require("../security/noise.js");
46
+ const DaemonVersion = __importStar(require("../version.js"));
47
+ /** Default ceiling on simultaneously open local connections. */
48
+ exports.DEFAULT_MAX_CONNECTIONS = 64;
49
+ function isAbortedAccept(error) {
50
+ return typeof error === 'object'
51
+ && error !== null
52
+ && 'code' in error
53
+ && error.code === 'ECANCELED';
54
+ }
55
+ class DaemonServer {
56
+ socketPath;
57
+ server;
58
+ dispatcher;
59
+ connections = new Map();
60
+ /** Sockets that have been accepted but have not finished the handshake. */
61
+ handshaking = new Set();
62
+ activityListeners = new Set();
63
+ principals;
64
+ home;
65
+ maxConnections;
66
+ maxInFlightPerConnection;
67
+ requestTimeoutMs;
68
+ expectedPeerPid;
69
+ peerCredentialHost;
70
+ expectedPeer;
71
+ pipeListener;
72
+ inFlightRequests = 0;
73
+ listening = false;
74
+ stopping = false;
75
+ closedPromise;
76
+ static async create(config) {
77
+ return new DaemonServer(config);
78
+ }
79
+ constructor(config) {
80
+ this.socketPath = config.socketPath;
81
+ this.principals = config.principals;
82
+ this.home = config.home;
83
+ this.maxConnections = Math.max(1, Math.trunc(config.maxConnections ?? exports.DEFAULT_MAX_CONNECTIONS));
84
+ this.maxInFlightPerConnection = config.maxInFlightPerConnection;
85
+ this.requestTimeoutMs = config.requestTimeoutMs;
86
+ this.expectedPeerPid = config.expectedPeerPid ?? process.pid;
87
+ this.dispatcher = new dispatch_js_1.RequestDispatcher({
88
+ registry: config.registry,
89
+ serverName: config.serverName ?? DaemonVersion.DAEMON_SERVER_NAME,
90
+ serverVersion: config.serverVersion ?? DaemonVersion.DAEMON_SERVER_VERSION,
91
+ });
92
+ this.server = (0, node_net_1.createServer)((socket) => {
93
+ this.accept(socket);
94
+ });
95
+ }
96
+ get connectionCount() {
97
+ return this.connections.size + this.handshaking.size;
98
+ }
99
+ get inFlightCount() {
100
+ return this.inFlightRequests;
101
+ }
102
+ get activity() {
103
+ return {
104
+ activeConnections: this.connectionCount,
105
+ inFlightRequests: this.inFlightRequests,
106
+ };
107
+ }
108
+ onActivity(listener) {
109
+ this.activityListeners.add(listener);
110
+ return () => {
111
+ this.activityListeners.delete(listener);
112
+ };
113
+ }
114
+ async listen() {
115
+ if (this.listening) {
116
+ throw new Error('Daemon server is already listening');
117
+ }
118
+ if (process.platform === 'win32') {
119
+ await this.listenWindows();
120
+ }
121
+ else {
122
+ await this.listenPosix();
123
+ }
124
+ this.listening = true;
125
+ }
126
+ async listenPosix() {
127
+ // Capture the expected peer before the socket can accept anything. The
128
+ // credential helper is prebuilt; it is never compiled at install time.
129
+ const host = await (0, peerCredentials_js_1.loadPeerCredentialHost)();
130
+ this.peerCredentialHost = host;
131
+ this.expectedPeer = (0, peerCredentials_js_1.captureExpectedPeer)(host, this.expectedPeerPid);
132
+ const previousUmask = process.umask(0o177);
133
+ try {
134
+ await new Promise((resolve, reject) => {
135
+ const onError = (error) => {
136
+ this.server.off('listening', onListening);
137
+ reject(error);
138
+ };
139
+ const onListening = () => {
140
+ this.server.off('error', onError);
141
+ resolve();
142
+ };
143
+ this.server.once('error', onError);
144
+ this.server.once('listening', onListening);
145
+ this.server.listen(this.socketPath);
146
+ });
147
+ }
148
+ finally {
149
+ process.umask(previousUmask);
150
+ }
151
+ const ownership = await (0, ownership_js_1.enforceEndpointOwnership)(this.socketPath);
152
+ if (ownership.status === 'unsupported') {
153
+ process.stderr.write(`brud-daemon: peer endpoint ownership is not verifiable on ${ownership.platform}: ${ownership.reason}\n`);
154
+ }
155
+ }
156
+ async listenWindows() {
157
+ // The Windows helper owns the named pipe: it creates every instance with a
158
+ // protected DACL for this user, rejects remote clients, and reads the
159
+ // connecting process's PID, token user SID, and creation time before
160
+ // handing the connection to Node. Capture the expected host first so no
161
+ // connection can arrive before the baseline exists.
162
+ const host = await (0, peerCredentials_js_1.loadPeerCredentialHost)();
163
+ this.peerCredentialHost = host;
164
+ this.expectedPeer = (0, peerCredentials_js_1.captureExpectedPeer)(host, this.expectedPeerPid);
165
+ if (typeof host.listenPipe !== 'function') {
166
+ throw new peerCredentials_js_1.PeerCredentialError('the installed peer-credential helper does not expose the Windows named-pipe listener');
167
+ }
168
+ let listener;
169
+ try {
170
+ listener = host.listenPipe(this.socketPath);
171
+ }
172
+ catch (error) {
173
+ throw new peerCredentials_js_1.PeerCredentialError(`cannot serve the Windows named pipe "${this.socketPath}": ${error instanceof Error ? error.message : String(error)}`);
174
+ }
175
+ this.pipeListener = listener;
176
+ // Windows named pipes do not expose ownership or mode through node:fs, so
177
+ // the existing file-ownership check keeps reporting `unsupported`. It stays
178
+ // in the path as a visible layer; the helper's DACL and the client process
179
+ // identity below are the Windows defenses.
180
+ const ownership = await (0, ownership_js_1.enforceEndpointOwnership)(this.socketPath);
181
+ if (ownership.status === 'unsupported') {
182
+ process.stderr.write(`brud-daemon: peer endpoint ownership is not verifiable on ${ownership.platform}: ${ownership.reason}\n`);
183
+ }
184
+ this.acceptPipeConnections(listener, this.expectedPeer);
185
+ }
186
+ acceptPipeConnections(listener, expected) {
187
+ const loop = async () => {
188
+ for (;;) {
189
+ let result;
190
+ try {
191
+ result = await listener.accept();
192
+ }
193
+ catch (error) {
194
+ if (this.stopping || isAbortedAccept(error)) {
195
+ return;
196
+ }
197
+ process.stderr.write(`brud-daemon: named-pipe accept failed: ${error instanceof Error ? error.message : String(error)}\n`);
198
+ return;
199
+ }
200
+ if (this.stopping) {
201
+ if ((0, peerCredentials_js_1.isPipePeer)(result)) {
202
+ this.discardPipePeer(result);
203
+ }
204
+ return;
205
+ }
206
+ if (!(0, peerCredentials_js_1.isPipePeer)(result)) {
207
+ // The helper already closed this connection unread because it could
208
+ // not read the client's identity. Fail closed and keep serving.
209
+ process.stderr.write(`brud-daemon: refused connection: ${result.refused}\n`);
210
+ continue;
211
+ }
212
+ let socket;
213
+ try {
214
+ (0, peerCredentials_js_1.verifyWindowsPeer)(result, expected);
215
+ socket = new node_net_1.Socket({ fd: result.fd });
216
+ }
217
+ catch (error) {
218
+ const refusal = error instanceof Error
219
+ ? error
220
+ : new peerCredentials_js_1.PeerCredentialError(String(error));
221
+ try {
222
+ socket = new node_net_1.Socket({ fd: result.fd });
223
+ }
224
+ catch {
225
+ continue;
226
+ }
227
+ this.refuseConnection(socket, refusal);
228
+ continue;
229
+ }
230
+ this.admit(socket);
231
+ }
232
+ };
233
+ void loop();
234
+ }
235
+ discardPipePeer(peer) {
236
+ try {
237
+ new node_net_1.Socket({ fd: peer.fd }).destroy();
238
+ }
239
+ catch {
240
+ // The descriptor is already unusable; nothing else can release it here.
241
+ }
242
+ }
243
+ stopAccepting() {
244
+ if (!this.listening) {
245
+ return;
246
+ }
247
+ this.listening = false;
248
+ this.stopping = true;
249
+ if (process.platform === 'win32') {
250
+ const listener = this.pipeListener;
251
+ this.pipeListener = undefined;
252
+ listener?.close();
253
+ this.closedPromise = Promise.resolve();
254
+ return;
255
+ }
256
+ this.closedPromise = new Promise((resolve, reject) => {
257
+ this.server.close((error) => {
258
+ if (error === undefined) {
259
+ resolve();
260
+ return;
261
+ }
262
+ reject(error);
263
+ });
264
+ });
265
+ this.closedPromise.catch(() => undefined);
266
+ }
267
+ closeConnections() {
268
+ for (const connection of this.connections.values()) {
269
+ connection.end();
270
+ }
271
+ for (const socket of this.handshaking) {
272
+ socket.destroy();
273
+ }
274
+ this.handshaking.clear();
275
+ this.connections.clear();
276
+ this.notifyActivity();
277
+ }
278
+ async close() {
279
+ this.stopAccepting();
280
+ this.closeConnections();
281
+ if (this.closedPromise !== undefined) {
282
+ await this.closedPromise;
283
+ }
284
+ if (process.platform !== 'win32') {
285
+ await (0, promises_1.rm)(this.socketPath, { force: true });
286
+ }
287
+ }
288
+ accept(socket) {
289
+ if (process.platform !== 'win32') {
290
+ const host = this.peerCredentialHost;
291
+ const expectedPeer = this.expectedPeer;
292
+ if (host === undefined || expectedPeer === undefined) {
293
+ this.refuseConnection(socket, new peerCredentials_js_1.PeerCredentialError('peer-credential verification is not initialized'));
294
+ return;
295
+ }
296
+ try {
297
+ (0, peerCredentials_js_1.verifyPeerCredentials)(socket, expectedPeer, host);
298
+ }
299
+ catch (error) {
300
+ this.refuseConnection(socket, error instanceof Error ? error : new peerCredentials_js_1.PeerCredentialError(String(error)));
301
+ return;
302
+ }
303
+ }
304
+ this.admit(socket);
305
+ }
306
+ admit(socket) {
307
+ if (this.connectionCount >= this.maxConnections) {
308
+ // The limit is applied before the handshake or any dispatch work.
309
+ socket.destroy();
310
+ return;
311
+ }
312
+ this.handshaking.add(socket);
313
+ this.notifyActivity();
314
+ const prologue = (0, channel_js_1.channelPrologue)(this.socketPath);
315
+ const serverInfo = {
316
+ name: DaemonVersion.DAEMON_SERVER_NAME,
317
+ version: DaemonVersion.DAEMON_SERVER_VERSION,
318
+ pid: process.pid,
319
+ };
320
+ void channel_js_1.SecureChannel.accept(socket, {
321
+ prologue,
322
+ psks: [
323
+ { principal: 'ui', psk: (0, noise_js_1.derivePsk)(this.principals.ui) },
324
+ { principal: 'ai', psk: (0, noise_js_1.derivePsk)(this.principals.ai) },
325
+ ],
326
+ server: serverInfo,
327
+ validateHome: (home) => {
328
+ if (home !== this.home) {
329
+ throw new Error('Daemon home does not match this daemon');
330
+ }
331
+ },
332
+ }).then(({ channel, context }) => {
333
+ this.handshaking.delete(socket);
334
+ if (channel.isClosed) {
335
+ this.notifyActivity();
336
+ return;
337
+ }
338
+ this.attachConnection(channel, context);
339
+ }).catch(() => {
340
+ this.handshaking.delete(socket);
341
+ if (!socket.destroyed) {
342
+ socket.destroy();
343
+ }
344
+ this.notifyActivity();
345
+ });
346
+ }
347
+ refuseConnection(socket, error) {
348
+ const message = `brud-daemon: refused connection: ${error.message}\n`;
349
+ process.stderr.write(message);
350
+ if (socket.destroyed) {
351
+ return;
352
+ }
353
+ socket.once('error', () => undefined);
354
+ socket.end(message, () => {
355
+ socket.destroy();
356
+ });
357
+ }
358
+ attachConnection(channel, context) {
359
+ const connectionId = `c_${(0, node_crypto_1.randomUUID)()}`;
360
+ const connection = new Connection_js_1.Connection(connectionId, channel, context, this.dispatcher, {
361
+ onRequestStart: () => {
362
+ this.inFlightRequests += 1;
363
+ this.notifyActivity();
364
+ },
365
+ onRequestEnd: () => {
366
+ this.inFlightRequests = Math.max(0, this.inFlightRequests - 1);
367
+ this.notifyActivity();
368
+ },
369
+ }, {
370
+ ...(this.maxInFlightPerConnection === undefined
371
+ ? {}
372
+ : { maxInFlight: this.maxInFlightPerConnection }),
373
+ ...(this.requestTimeoutMs === undefined
374
+ ? {}
375
+ : { requestTimeoutMs: this.requestTimeoutMs }),
376
+ });
377
+ this.connections.set(connectionId, connection);
378
+ connection.onClose(() => {
379
+ this.connections.delete(connectionId);
380
+ this.dispatcher.connectionClosed(connectionId);
381
+ this.notifyActivity();
382
+ });
383
+ this.notifyActivity();
384
+ }
385
+ notifyActivity() {
386
+ if (this.activityListeners.size === 0) {
387
+ return;
388
+ }
389
+ const snapshot = this.activity;
390
+ for (const listener of this.activityListeners) {
391
+ listener(snapshot);
392
+ }
393
+ }
394
+ }
395
+ exports.DaemonServer = DaemonServer;
396
+ //# sourceMappingURL=DaemonServer.js.map
@@ -0,0 +1,52 @@
1
+ import { IdleMonitor } from '../lifecycle/idle.js';
2
+ import type { LockHandle } from '../lifecycle/lock.js';
3
+ import type { DaemonEndpoint } from '../lifecycle/endpoint.js';
4
+ import { KernelInstanceRegistry } from '../instanceRegistry.js';
5
+ import type { DaemonOperatorConfig } from '../operatorConfig.js';
6
+ import { DaemonServer } from './DaemonServer.js';
7
+ export interface CreateDaemonOptions {
8
+ /**
9
+ * Daemon home: the operator's state folder. It names the endpoint, holds
10
+ * kernel state, and by default holds the operator config (`daemon.json`).
11
+ */
12
+ readonly home: string;
13
+ /** Operator config; defaults to `<home>/daemon.json`. */
14
+ readonly operator?: DaemonOperatorConfig;
15
+ /** Explicit operator config path (ignored when `operator` is given). */
16
+ readonly operatorConfigPath?: string;
17
+ /** Daemon idle shutdown window. */
18
+ readonly idleTimeoutMs?: number;
19
+ /** Idle window for a kernel instance with no clients; 0 disables. */
20
+ readonly instanceIdleTimeoutMs?: number;
21
+ readonly maxConnections?: number;
22
+ readonly maxInFlightPerConnection?: number;
23
+ readonly requestTimeoutMs?: number;
24
+ readonly expectedPeerPid?: number;
25
+ }
26
+ export interface DaemonMetadataRecord {
27
+ readonly pid: number;
28
+ readonly version: string;
29
+ readonly protocolVersion: string;
30
+ readonly home: string;
31
+ readonly socketPath: string;
32
+ readonly lockPath: string;
33
+ readonly tokenPath: string;
34
+ readonly aiTokenPath: string;
35
+ readonly startedAt: number;
36
+ }
37
+ export interface RunningDaemon {
38
+ readonly endpoint: DaemonEndpoint;
39
+ readonly token: string;
40
+ readonly tokens: Readonly<Record<'ui' | 'ai', string>>;
41
+ readonly lock: LockHandle;
42
+ readonly registry: KernelInstanceRegistry;
43
+ readonly server: DaemonServer;
44
+ readonly idleMonitor: IdleMonitor;
45
+ readonly isShuttingDown: () => boolean;
46
+ readonly shutdown: () => Promise<void>;
47
+ }
48
+ /**
49
+ * Starts the daemon: a neutral host that boots kernels from the operator's
50
+ * composition on request. No kernel is booted at start.
51
+ */
52
+ export declare function createDaemon(options: CreateDaemonOptions): Promise<RunningDaemon>;
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.createDaemon = createDaemon;
37
+ const node_crypto_1 = require("node:crypto");
38
+ const promises_1 = require("node:fs/promises");
39
+ const Protocol = __importStar(require("@brud/protocol"));
40
+ const idle_js_1 = require("../lifecycle/idle.js");
41
+ const lock_js_1 = require("../lifecycle/lock.js");
42
+ const endpoint_js_1 = require("../lifecycle/endpoint.js");
43
+ const shutdown_js_1 = require("../lifecycle/shutdown.js");
44
+ const instanceRegistry_js_1 = require("../instanceRegistry.js");
45
+ const operatorConfig_js_1 = require("../operatorConfig.js");
46
+ const DaemonServer_js_1 = require("./DaemonServer.js");
47
+ const DaemonVersion = __importStar(require("../version.js"));
48
+ function writeDaemonWarning(message, meta) {
49
+ process.stderr.write(`${message}${meta === undefined ? '' : ` ${JSON.stringify(meta)}`}\n`);
50
+ }
51
+ function readErrorCode(error) {
52
+ if (typeof error !== 'object' || error === null || !('code' in error)) {
53
+ return undefined;
54
+ }
55
+ const code = error.code;
56
+ return typeof code === 'string' ? code : undefined;
57
+ }
58
+ async function unlinkIfPresent(path) {
59
+ try {
60
+ await (0, promises_1.unlink)(path);
61
+ }
62
+ catch (error) {
63
+ if (readErrorCode(error) !== 'ENOENT') {
64
+ throw error;
65
+ }
66
+ }
67
+ }
68
+ async function rollbackStartup(endpoint, lock, registry, server) {
69
+ if (server !== undefined) {
70
+ await server.close().catch(() => undefined);
71
+ }
72
+ if (registry !== undefined) {
73
+ await registry.disposeAll().catch(() => undefined);
74
+ }
75
+ await unlinkIfPresent(endpoint.tokenPath).catch(() => undefined);
76
+ await unlinkIfPresent(endpoint.aiTokenPath).catch(() => undefined);
77
+ await unlinkIfPresent(endpoint.metaPath).catch(() => undefined);
78
+ await lock.release().catch(() => undefined);
79
+ }
80
+ /**
81
+ * Starts the daemon: a neutral host that boots kernels from the operator's
82
+ * composition on request. No kernel is booted at start.
83
+ */
84
+ async function createDaemon(options) {
85
+ const endpoint = await (0, endpoint_js_1.resolveEndpoint)(options.home);
86
+ const operator = options.operator ?? (0, operatorConfig_js_1.loadOperatorConfig)(endpoint.home, options.operatorConfigPath);
87
+ const lock = await (0, lock_js_1.acquireDaemonLock)(endpoint, {
88
+ pid: process.pid,
89
+ version: DaemonVersion.DAEMON_SERVER_VERSION,
90
+ });
91
+ const tokens = {
92
+ ui: (0, node_crypto_1.randomBytes)(32).toString('hex'),
93
+ ai: (0, node_crypto_1.randomBytes)(32).toString('hex'),
94
+ };
95
+ let registry;
96
+ let server;
97
+ try {
98
+ await (0, promises_1.writeFile)(endpoint.tokenPath, tokens.ui, { encoding: 'utf8', mode: 0o600 });
99
+ await (0, promises_1.writeFile)(endpoint.aiTokenPath, tokens.ai, { encoding: 'utf8', mode: 0o600 });
100
+ registry = new instanceRegistry_js_1.KernelInstanceRegistry({
101
+ home: endpoint.home,
102
+ operator,
103
+ ...(options.instanceIdleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.instanceIdleTimeoutMs }),
104
+ logger: { warn: writeDaemonWarning },
105
+ });
106
+ server = await DaemonServer_js_1.DaemonServer.create({
107
+ registry,
108
+ socketPath: endpoint.socketPath,
109
+ principals: tokens,
110
+ home: endpoint.home,
111
+ ...(options.maxConnections === undefined ? {} : { maxConnections: options.maxConnections }),
112
+ ...(options.maxInFlightPerConnection === undefined ? {} : { maxInFlightPerConnection: options.maxInFlightPerConnection }),
113
+ ...(options.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: options.requestTimeoutMs }),
114
+ ...(options.expectedPeerPid === undefined ? {} : { expectedPeerPid: options.expectedPeerPid }),
115
+ });
116
+ await server.listen();
117
+ const metadata = {
118
+ pid: process.pid,
119
+ version: DaemonVersion.DAEMON_SERVER_VERSION,
120
+ protocolVersion: Protocol.DAEMON_PROTOCOL_VERSION,
121
+ home: endpoint.home,
122
+ socketPath: endpoint.socketPath,
123
+ lockPath: endpoint.lockPath,
124
+ tokenPath: endpoint.tokenPath,
125
+ aiTokenPath: endpoint.aiTokenPath,
126
+ startedAt: lock.record.startedAt,
127
+ };
128
+ await (0, promises_1.writeFile)(endpoint.metaPath, JSON.stringify(metadata), { encoding: 'utf8', mode: 0o600 });
129
+ }
130
+ catch (error) {
131
+ await rollbackStartup(endpoint, lock, registry, server);
132
+ throw error;
133
+ }
134
+ const runningRegistry = registry;
135
+ const runningServer = server;
136
+ const idleMonitor = new idle_js_1.IdleMonitor({
137
+ ...(options.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.idleTimeoutMs }),
138
+ onIdleShutdown: () => shutdownCoordinator.shutdown(),
139
+ });
140
+ const unsubscribeActivity = runningServer.onActivity((snapshot) => {
141
+ idleMonitor.update(snapshot.activeConnections, snapshot.inFlightRequests);
142
+ });
143
+ const shutdownCoordinator = new shutdown_js_1.GracefulShutdownCoordinator({
144
+ server: runningServer,
145
+ disposeKernels: () => runningRegistry.disposeAll(),
146
+ endpoint,
147
+ beforeTeardown: () => {
148
+ unsubscribeActivity();
149
+ idleMonitor.dispose();
150
+ },
151
+ });
152
+ idleMonitor.update(runningServer.connectionCount, runningServer.inFlightCount);
153
+ return {
154
+ endpoint,
155
+ token: tokens.ui,
156
+ tokens,
157
+ lock,
158
+ registry: runningRegistry,
159
+ server: runningServer,
160
+ idleMonitor,
161
+ isShuttingDown: () => shutdownCoordinator.isShuttingDown,
162
+ shutdown: () => shutdownCoordinator.shutdown(),
163
+ };
164
+ }
165
+ //# sourceMappingURL=createDaemon.js.map
@@ -0,0 +1,52 @@
1
+ import type { DaemonCallerTier, RpcRequest, RpcResponse } from '@brud/protocol';
2
+ import type { KernelInstanceRegistry } from '../instanceRegistry.js';
3
+ export interface DispatchSession {
4
+ readonly connectionId: string;
5
+ readonly handshaken: boolean;
6
+ /**
7
+ * Caller principal fixed by the authenticated handshake. Undefined only
8
+ * before the secure channel has established a session.
9
+ */
10
+ tier: DaemonCallerTier | undefined;
11
+ markHandshaken(): void;
12
+ }
13
+ export interface DispatchOptions {
14
+ /** Cancellation signal owned by the transport connection. */
15
+ readonly signal?: AbortSignal;
16
+ }
17
+ export interface RequestDispatcherOptions {
18
+ /** The daemon's kernels. */
19
+ readonly registry: KernelInstanceRegistry;
20
+ readonly serverName?: string;
21
+ readonly serverVersion?: string;
22
+ }
23
+ /**
24
+ * Routes daemon RPC. The dispatcher knows the kernel and nothing above it:
25
+ * remote work is Brud syntax handed to the Router inside a host session whose
26
+ * capabilities the operator assigned to the authenticated principal.
27
+ */
28
+ export declare class RequestDispatcher {
29
+ private readonly registry;
30
+ private readonly connectValidator;
31
+ private readonly serverName;
32
+ private readonly serverVersion;
33
+ private readonly startedAt;
34
+ constructor(options: RequestDispatcherOptions);
35
+ /** Detaches a closed connection from every kernel it used. */
36
+ connectionClosed(connectionId: string): void;
37
+ dispatch(request: RpcRequest, session: DispatchSession, options?: DispatchOptions): Promise<RpcResponse>;
38
+ private route;
39
+ private connect;
40
+ private ping;
41
+ private info;
42
+ private requirements;
43
+ private boot;
44
+ private attach;
45
+ private list;
46
+ private status;
47
+ private dispose;
48
+ /** Runs `operation` against the Router inside the session's host call. */
49
+ private inHostSession;
50
+ private kinds;
51
+ private routeText;
52
+ }