@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,332 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KernelInstanceRegistry = exports.DEFAULT_INSTANCE_IDLE_TIMEOUT_MS = exports.KernelInstanceNotFoundError = exports.BootOptionNotAllowedError = exports.EXPOSED_API_SCOPE_RECORD_FIELD = exports.IDENTITY_REGISTRY_PATH_FIELD = void 0;
4
+ exports.loadKernelModule = loadKernelModule;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const node_fs_1 = require("node:fs");
7
+ const node_path_1 = require("node:path");
8
+ let kernelModulePromise;
9
+ /** Loads `@brud/kernel` once (ESM, cached). */
10
+ function loadKernelModule() {
11
+ kernelModulePromise ??= import('@brud/kernel');
12
+ return kernelModulePromise;
13
+ }
14
+ /** Kernel-owned startup fields the daemon fills from its own home. */
15
+ exports.IDENTITY_REGISTRY_PATH_FIELD = 'identity.registry.path';
16
+ exports.EXPOSED_API_SCOPE_RECORD_FIELD = 'exposedApi.scopeRecord.path';
17
+ /** A boot logger that records the kernel's pruning reports and forwards the rest. */
18
+ function pruneRecorder(forward) {
19
+ const pruned = [];
20
+ const logger = {
21
+ warn(message, meta) {
22
+ const detail = meta;
23
+ if (detail !== undefined && Array.isArray(detail.participants) && Array.isArray(detail.missingFields)) {
24
+ pruned.push({
25
+ participants: [...detail.participants],
26
+ path: String(detail.path ?? ''),
27
+ missingFields: [...detail.missingFields],
28
+ });
29
+ return;
30
+ }
31
+ forward?.warn(message, meta);
32
+ },
33
+ info: () => undefined,
34
+ debug: () => undefined,
35
+ error(message, meta) {
36
+ forward?.warn(message, meta);
37
+ },
38
+ };
39
+ return { logger, pruned };
40
+ }
41
+ /** Raised when a client sets a startup field the operator did not allow. */
42
+ class BootOptionNotAllowedError extends Error {
43
+ field;
44
+ code = 'BOOT_OPTION_NOT_ALLOWED';
45
+ constructor(field) {
46
+ super(`The operator does not allow clients to set startup field "${field}"`);
47
+ this.field = field;
48
+ this.name = 'BootOptionNotAllowedError';
49
+ }
50
+ }
51
+ exports.BootOptionNotAllowedError = BootOptionNotAllowedError;
52
+ /** Raised for an instance id that is unknown or not attached to the client. */
53
+ class KernelInstanceNotFoundError extends Error {
54
+ instanceId;
55
+ code = 'KERNEL_INSTANCE_NOT_FOUND';
56
+ constructor(instanceId) {
57
+ super(`No kernel instance "${instanceId}" is attached to this connection`);
58
+ this.instanceId = instanceId;
59
+ this.name = 'KernelInstanceNotFoundError';
60
+ }
61
+ }
62
+ exports.KernelInstanceNotFoundError = KernelInstanceNotFoundError;
63
+ /** Default idle window for a kernel with no clients. */
64
+ exports.DEFAULT_INSTANCE_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
65
+ function stableStringify(value) {
66
+ if (Array.isArray(value)) {
67
+ return `[${value.map(stableStringify).join(',')}]`;
68
+ }
69
+ if (typeof value === 'object' && value !== null) {
70
+ const entries = Object.keys(value).sort()
71
+ .map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
72
+ return `{${entries.join(',')}}`;
73
+ }
74
+ return JSON.stringify(value) ?? 'null';
75
+ }
76
+ /**
77
+ * The daemon's kernels. It knows no participant and no domain: startup options
78
+ * are the operator's fixed options plus the client's allowed ones, validated by
79
+ * the kernel's own context contract at boot.
80
+ */
81
+ class KernelInstanceRegistry {
82
+ instances = new Map();
83
+ pending = new Map();
84
+ /** State folder names held by live or booting kernels. */
85
+ reservedStates = new Set();
86
+ home;
87
+ operator;
88
+ idleTimeoutMs;
89
+ now;
90
+ logger;
91
+ sweepTimer;
92
+ disposed = false;
93
+ constructor(options) {
94
+ this.home = options.home;
95
+ this.operator = options.operator;
96
+ this.idleTimeoutMs = options.idleTimeoutMs ?? exports.DEFAULT_INSTANCE_IDLE_TIMEOUT_MS;
97
+ this.now = options.now ?? Date.now;
98
+ this.logger = options.logger;
99
+ if (this.idleTimeoutMs > 0) {
100
+ this.sweepTimer = setInterval(() => {
101
+ void this.sweepIdle();
102
+ }, Math.min(this.idleTimeoutMs, 60_000));
103
+ this.sweepTimer.unref();
104
+ }
105
+ }
106
+ /** Startup fields a client may set. */
107
+ get clientSettableFields() {
108
+ return this.operator.clientOptions;
109
+ }
110
+ /** Host-session capabilities for an authenticated principal. */
111
+ capabilitiesFor(principal) {
112
+ return this.operator.principals[principal];
113
+ }
114
+ /**
115
+ * The composition's declared startup fields. Boots a throwaway kernel with
116
+ * only the operator's options: the context contract refuses it before any
117
+ * participant is constructed when a required field is missing, and the
118
+ * collected declarations are read either way.
119
+ */
120
+ async requirements() {
121
+ const kernelModule = await loadKernelModule();
122
+ const scratch = (0, node_path_1.join)(this.home, 'requirements', (0, node_crypto_1.randomUUID)());
123
+ const recorder = pruneRecorder(undefined);
124
+ const kernel = kernelModule.createDeferredKernel(this.operator.composition, {});
125
+ let schema = { locked: false, fields: [] };
126
+ try {
127
+ await kernel.boot({ options: this.kernelOptions(scratch, {}, kernelModule), logger: recorder.logger });
128
+ schema = kernel.getContextSchema();
129
+ await kernel.shutdown().catch(() => undefined);
130
+ }
131
+ catch {
132
+ // A refusal still leaves the collected declarations readable.
133
+ schema = kernel.getContextSchema();
134
+ }
135
+ finally {
136
+ (0, node_fs_1.rmSync)(scratch, { recursive: true, force: true });
137
+ }
138
+ const fields = schema.fields.map((field) => ({
139
+ name: field.name,
140
+ type: String(field.type),
141
+ required: field.required === true,
142
+ ...(field.description === undefined ? {} : { description: field.description }),
143
+ service: field.service,
144
+ }));
145
+ // Fields of participants the kernel left out are withdrawn from the
146
+ // schema; the pruning report still names them.
147
+ for (const entry of recorder.pruned) {
148
+ for (const name of entry.missingFields) {
149
+ if (!fields.some((field) => field.name === name)) {
150
+ fields.push({ name, type: 'unknown', required: true, service: entry.path });
151
+ }
152
+ }
153
+ }
154
+ return fields;
155
+ }
156
+ /** Boots (or, if the operator allows, reuses) a kernel for one client. */
157
+ async boot(clientOptions, clientId) {
158
+ if (this.disposed) {
159
+ throw new Error('The kernel instance registry has been disposed');
160
+ }
161
+ for (const field of Object.keys(clientOptions)) {
162
+ if (!this.operator.clientOptions.includes(field)) {
163
+ throw new BootOptionNotAllowedError(field);
164
+ }
165
+ }
166
+ const key = (0, node_crypto_1.createHash)('sha256').update(stableStringify(clientOptions)).digest('hex').slice(0, 32);
167
+ if (this.operator.reuseIdenticalBoots) {
168
+ const existing = [...this.instances.values()].find((entry) => entry.key === key && entry.state === 'running');
169
+ if (existing !== undefined) {
170
+ this.attach(existing.id, clientId);
171
+ return { instance: existing, reused: true };
172
+ }
173
+ const inFlight = this.pending.get(key);
174
+ if (inFlight !== undefined) {
175
+ const instance = await inFlight;
176
+ this.attach(instance.id, clientId);
177
+ return { instance, reused: true };
178
+ }
179
+ }
180
+ const creation = this.create(key, clientOptions);
181
+ if (this.operator.reuseIdenticalBoots) {
182
+ this.pending.set(key, creation);
183
+ }
184
+ try {
185
+ const instance = await creation;
186
+ this.attach(instance.id, clientId);
187
+ return { instance, reused: false };
188
+ }
189
+ finally {
190
+ this.pending.delete(key);
191
+ }
192
+ }
193
+ /** Claims the lowest free state folder name for a key (synchronously, before any await). */
194
+ reserveState(key) {
195
+ let name = key;
196
+ for (let ordinal = 1; this.reservedStates.has(name); ordinal += 1) {
197
+ name = `${key}-${String(ordinal)}`;
198
+ }
199
+ this.reservedStates.add(name);
200
+ return name;
201
+ }
202
+ async create(key, clientOptions) {
203
+ const stateName = this.reserveState(key);
204
+ let kernel;
205
+ let recorder;
206
+ try {
207
+ const kernelModule = await loadKernelModule();
208
+ recorder = pruneRecorder(this.logger);
209
+ kernel = await kernelModule.bootKernel(this.operator.composition, {
210
+ options: this.kernelOptions((0, node_path_1.join)(this.home, 'kernels', stateName), clientOptions, kernelModule),
211
+ logger: recorder.logger,
212
+ });
213
+ }
214
+ catch (error) {
215
+ this.reservedStates.delete(stateName);
216
+ throw error;
217
+ }
218
+ const instance = {
219
+ id: `k_${(0, node_crypto_1.randomUUID)()}`,
220
+ key,
221
+ stateName,
222
+ kernel,
223
+ clients: new Set(),
224
+ state: 'running',
225
+ lastUsedAt: new Date(this.now()),
226
+ pruned: Object.freeze([...recorder.pruned]),
227
+ };
228
+ this.instances.set(instance.id, instance);
229
+ return instance;
230
+ }
231
+ /**
232
+ * Kernel-owned fields come from the daemon home; the operator's fixed
233
+ * options override them; the client's allowed options come last but can
234
+ * only name allowed fields.
235
+ */
236
+ kernelOptions(stateFolder, clientOptions, kernelModule) {
237
+ const options = {
238
+ [exports.IDENTITY_REGISTRY_PATH_FIELD]: (0, node_path_1.join)(stateFolder, 'identity.json'),
239
+ [exports.EXPOSED_API_SCOPE_RECORD_FIELD]: (0, node_path_1.join)(stateFolder, 'exposed-api.json'),
240
+ ...this.operator.fixedOptions,
241
+ ...clientOptions,
242
+ };
243
+ const registryPath = options[exports.IDENTITY_REGISTRY_PATH_FIELD];
244
+ if (typeof registryPath === 'string' && !(0, node_fs_1.existsSync)(registryPath)) {
245
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(registryPath), { recursive: true });
246
+ kernelModule.provisionIdentityRegistryStorage(registryPath);
247
+ }
248
+ return options;
249
+ }
250
+ /** Attaches a client to an existing instance. */
251
+ attach(instanceId, clientId) {
252
+ const instance = this.instances.get(instanceId);
253
+ if (instance === undefined || instance.state !== 'running') {
254
+ throw new KernelInstanceNotFoundError(instanceId);
255
+ }
256
+ instance.clients.add(clientId);
257
+ instance.lastUsedAt = new Date(this.now());
258
+ return instance;
259
+ }
260
+ /** An instance the client is attached to. */
261
+ forClient(instanceId, clientId) {
262
+ const instance = this.instances.get(instanceId);
263
+ if (instance === undefined || instance.state !== 'running' || !instance.clients.has(clientId)) {
264
+ throw new KernelInstanceNotFoundError(instanceId);
265
+ }
266
+ instance.lastUsedAt = new Date(this.now());
267
+ return instance;
268
+ }
269
+ /** Instances the client is attached to. */
270
+ listFor(clientId) {
271
+ return [...this.instances.values()].filter((entry) => entry.clients.has(clientId));
272
+ }
273
+ /** Detaches a closing client from every instance. */
274
+ detachClient(clientId) {
275
+ for (const instance of this.instances.values()) {
276
+ if (instance.clients.delete(clientId)) {
277
+ instance.lastUsedAt = new Date(this.now());
278
+ }
279
+ }
280
+ }
281
+ /** Shuts one instance down. */
282
+ async dispose(instanceId) {
283
+ const instance = this.instances.get(instanceId);
284
+ if (instance === undefined) {
285
+ return false;
286
+ }
287
+ this.instances.delete(instanceId);
288
+ instance.state = 'shutting-down';
289
+ try {
290
+ await instance.kernel.shutdown();
291
+ }
292
+ catch (error) {
293
+ this.logger?.warn('Kernel instance shutdown failed', {
294
+ instanceId,
295
+ error: error instanceof Error ? error.message : String(error),
296
+ });
297
+ }
298
+ finally {
299
+ instance.state = 'disposed';
300
+ instance.clients.clear();
301
+ this.reservedStates.delete(instance.stateName);
302
+ }
303
+ return true;
304
+ }
305
+ /** Disposes client-less instances idle past the timeout. */
306
+ async sweepIdle() {
307
+ if (this.idleTimeoutMs <= 0) {
308
+ return;
309
+ }
310
+ const cutoff = this.now() - this.idleTimeoutMs;
311
+ for (const instance of [...this.instances.values()]) {
312
+ if (instance.clients.size === 0 && instance.lastUsedAt.getTime() <= cutoff) {
313
+ await this.dispose(instance.id);
314
+ }
315
+ }
316
+ }
317
+ /** Every running instance (daemon-internal: shutdown, activity). */
318
+ get size() {
319
+ return this.instances.size;
320
+ }
321
+ /** Shuts every instance down. */
322
+ async disposeAll() {
323
+ this.disposed = true;
324
+ if (this.sweepTimer !== undefined) {
325
+ clearInterval(this.sweepTimer);
326
+ this.sweepTimer = undefined;
327
+ }
328
+ await Promise.all([...this.instances.keys()].map((id) => this.dispose(id)));
329
+ }
330
+ }
331
+ exports.KernelInstanceRegistry = KernelInstanceRegistry;
332
+ //# sourceMappingURL=instanceRegistry.js.map
@@ -0,0 +1,19 @@
1
+ export interface DaemonEndpoint {
2
+ readonly home: string;
3
+ readonly homeHash: string;
4
+ readonly runtimeDir: string;
5
+ readonly socketPath: string;
6
+ readonly lockPath: string;
7
+ /** UI-principal pre-shared key. */
8
+ readonly tokenPath: string;
9
+ /** AI-principal pre-shared key. */
10
+ readonly aiTokenPath: string;
11
+ readonly metaPath: string;
12
+ readonly isWindows: boolean;
13
+ }
14
+ export declare class EndpointResolutionError extends Error {
15
+ constructor(message: string, options?: ErrorOptions);
16
+ }
17
+ export declare function hashDaemonHome(canonicalRoot: string): string;
18
+ export declare function canonicalizeDaemonHome(home: string): Promise<string>;
19
+ export declare function resolveEndpoint(home: string): Promise<DaemonEndpoint>;
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EndpointResolutionError = void 0;
4
+ exports.hashDaemonHome = hashDaemonHome;
5
+ exports.canonicalizeDaemonHome = canonicalizeDaemonHome;
6
+ exports.resolveEndpoint = resolveEndpoint;
7
+ const node_crypto_1 = require("node:crypto");
8
+ const promises_1 = require("node:fs/promises");
9
+ const node_os_1 = require("node:os");
10
+ const node_path_1 = require("node:path");
11
+ const HASH_LENGTH = 24;
12
+ const MAX_SOCKET_PATH_BYTES = 100;
13
+ const RUNTIME_DIRECTORY_MODE = 0o700;
14
+ class EndpointResolutionError extends Error {
15
+ constructor(message, options) {
16
+ super(message, options);
17
+ this.name = 'EndpointResolutionError';
18
+ }
19
+ }
20
+ exports.EndpointResolutionError = EndpointResolutionError;
21
+ function readEnvironmentValue(name) {
22
+ const value = process.env[name]?.trim();
23
+ return value === undefined || value.length === 0 ? undefined : value;
24
+ }
25
+ function currentUid() {
26
+ return typeof process.getuid === 'function' ? process.getuid() : undefined;
27
+ }
28
+ function hashDaemonHome(canonicalRoot) {
29
+ return (0, node_crypto_1.createHash)('sha256').update(canonicalRoot).digest('hex').slice(0, HASH_LENGTH);
30
+ }
31
+ async function canonicalizeDaemonHome(home) {
32
+ const requested = (0, node_path_1.resolve)(home);
33
+ try {
34
+ // The daemon home is the operator's state folder; it is created on demand.
35
+ await (0, promises_1.mkdir)(requested, { recursive: true, mode: RUNTIME_DIRECTORY_MODE });
36
+ const canonical = await (0, promises_1.realpath)(requested);
37
+ return process.platform === 'win32' ? canonical.toLowerCase() : canonical;
38
+ }
39
+ catch (error) {
40
+ throw new EndpointResolutionError(`Cannot resolve daemon home "${home}"`, { cause: error });
41
+ }
42
+ }
43
+ async function ensurePosixRuntimeDirectory(directory) {
44
+ await (0, promises_1.mkdir)(directory, { recursive: true, mode: RUNTIME_DIRECTORY_MODE });
45
+ try {
46
+ await (0, promises_1.chmod)(directory, RUNTIME_DIRECTORY_MODE);
47
+ }
48
+ catch {
49
+ // Ownership validation below produces a precise error when this fails.
50
+ }
51
+ const info = await (0, promises_1.stat)(directory);
52
+ const uid = currentUid();
53
+ if (uid !== undefined && info.uid !== uid) {
54
+ throw new EndpointResolutionError(`Runtime directory "${directory}" is owned by uid ${info.uid}, expected ${uid}`);
55
+ }
56
+ if ((info.mode & 0o077) !== 0) {
57
+ throw new EndpointResolutionError(`Runtime directory "${directory}" has insecure mode ${(info.mode & 0o777).toString(8)}`);
58
+ }
59
+ }
60
+ async function ensureWindowsRuntimeDirectory(directory) {
61
+ await (0, promises_1.mkdir)(directory, { recursive: true });
62
+ }
63
+ function posixRuntimeDirectory() {
64
+ const configured = readEnvironmentValue('BRUD_DAEMON_RUNTIME_DIR');
65
+ if (configured !== undefined) {
66
+ return configured;
67
+ }
68
+ const xdgRuntimeDirectory = readEnvironmentValue('XDG_RUNTIME_DIR');
69
+ if (xdgRuntimeDirectory !== undefined) {
70
+ return (0, node_path_1.join)(xdgRuntimeDirectory, 'brud');
71
+ }
72
+ return (0, node_path_1.join)((0, node_os_1.tmpdir)(), `brud-${currentUid() ?? 'default'}`);
73
+ }
74
+ function windowsRuntimeDirectory() {
75
+ const localAppData = readEnvironmentValue('LOCALAPPDATA');
76
+ return localAppData === undefined
77
+ ? (0, node_path_1.join)((0, node_os_1.tmpdir)(), 'brud')
78
+ : (0, node_path_1.join)(localAppData, 'Brud', 'runtime');
79
+ }
80
+ function derivePosixSocketPath(runtimeDir, hash) {
81
+ const preferred = (0, node_path_1.join)(runtimeDir, `d-${hash}.sock`);
82
+ if (Buffer.byteLength(preferred) < MAX_SOCKET_PATH_BYTES) {
83
+ return preferred;
84
+ }
85
+ const fallback = (0, node_path_1.join)((0, node_os_1.tmpdir)(), `b-${hash}.sock`);
86
+ if (Buffer.byteLength(fallback) >= MAX_SOCKET_PATH_BYTES) {
87
+ throw new EndpointResolutionError(`Daemon socket path "${fallback}" exceeds ${MAX_SOCKET_PATH_BYTES} bytes`);
88
+ }
89
+ return fallback;
90
+ }
91
+ async function resolveEndpoint(home) {
92
+ const canonicalRoot = await canonicalizeDaemonHome(home);
93
+ const homeHash = hashDaemonHome(canonicalRoot);
94
+ const isWindows = process.platform === 'win32';
95
+ if (isWindows) {
96
+ const runtimeDir = windowsRuntimeDirectory();
97
+ await ensureWindowsRuntimeDirectory(runtimeDir);
98
+ return {
99
+ home: canonicalRoot,
100
+ homeHash,
101
+ runtimeDir,
102
+ socketPath: `\\\\.\\pipe\\brud-${homeHash}`,
103
+ lockPath: (0, node_path_1.join)(runtimeDir, `d-${homeHash}.lock`),
104
+ tokenPath: (0, node_path_1.join)(runtimeDir, `d-${homeHash}.token`),
105
+ aiTokenPath: (0, node_path_1.join)(runtimeDir, `d-${homeHash}.ai.token`),
106
+ metaPath: (0, node_path_1.join)(runtimeDir, `d-${homeHash}.json`),
107
+ isWindows,
108
+ };
109
+ }
110
+ const runtimeDir = posixRuntimeDirectory();
111
+ await ensurePosixRuntimeDirectory(runtimeDir);
112
+ return {
113
+ home: canonicalRoot,
114
+ homeHash,
115
+ runtimeDir,
116
+ socketPath: derivePosixSocketPath(runtimeDir, homeHash),
117
+ lockPath: (0, node_path_1.join)(runtimeDir, `d-${homeHash}.lock`),
118
+ tokenPath: (0, node_path_1.join)(runtimeDir, `d-${homeHash}.token`),
119
+ aiTokenPath: (0, node_path_1.join)(runtimeDir, `d-${homeHash}.ai.token`),
120
+ metaPath: (0, node_path_1.join)(runtimeDir, `d-${homeHash}.json`),
121
+ isWindows,
122
+ };
123
+ }
124
+ //# sourceMappingURL=endpoint.js.map
@@ -0,0 +1,28 @@
1
+ export declare const DEFAULT_IDLE_TIMEOUT_MS = 300000;
2
+ export declare const MINIMUM_IDLE_TIMEOUT_MS = 5000;
3
+ export interface IdleTimerHandle {
4
+ unref?: () => void;
5
+ }
6
+ export interface IdleTimerScheduler {
7
+ setTimeout(callback: () => void, delayMs: number): IdleTimerHandle;
8
+ clearTimeout(handle: IdleTimerHandle): void;
9
+ }
10
+ export interface IdleMonitorOptions {
11
+ readonly idleTimeoutMs?: number;
12
+ readonly onIdleShutdown: () => void | Promise<void>;
13
+ readonly scheduler?: IdleTimerScheduler;
14
+ readonly minimumIdleTimeoutMs?: number;
15
+ }
16
+ export declare class IdleMonitor {
17
+ readonly idleTimeoutMs: number;
18
+ private readonly onIdleShutdown;
19
+ private readonly scheduler;
20
+ private timer;
21
+ private disposed;
22
+ constructor(options: IdleMonitorOptions);
23
+ get isArmed(): boolean;
24
+ update(activeConnections: number, inFlightRequests: number): void;
25
+ dispose(): void;
26
+ private arm;
27
+ private disarm;
28
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IdleMonitor = exports.MINIMUM_IDLE_TIMEOUT_MS = exports.DEFAULT_IDLE_TIMEOUT_MS = void 0;
4
+ exports.DEFAULT_IDLE_TIMEOUT_MS = 300_000;
5
+ exports.MINIMUM_IDLE_TIMEOUT_MS = 5_000;
6
+ const defaultScheduler = {
7
+ setTimeout: (callback, delayMs) => setTimeout(callback, delayMs),
8
+ clearTimeout: (handle) => {
9
+ clearTimeout(handle);
10
+ },
11
+ };
12
+ function clampTimeout(requested, minimum) {
13
+ if (requested === undefined) {
14
+ return Math.max(exports.DEFAULT_IDLE_TIMEOUT_MS, minimum);
15
+ }
16
+ if (!Number.isFinite(requested) || requested <= 0) {
17
+ throw new RangeError('idleTimeoutMs must be a positive finite number');
18
+ }
19
+ return Math.max(Math.trunc(requested), minimum);
20
+ }
21
+ class IdleMonitor {
22
+ idleTimeoutMs;
23
+ onIdleShutdown;
24
+ scheduler;
25
+ timer;
26
+ disposed = false;
27
+ constructor(options) {
28
+ this.idleTimeoutMs = clampTimeout(options.idleTimeoutMs, options.minimumIdleTimeoutMs ?? exports.MINIMUM_IDLE_TIMEOUT_MS);
29
+ this.onIdleShutdown = options.onIdleShutdown;
30
+ this.scheduler = options.scheduler ?? defaultScheduler;
31
+ }
32
+ get isArmed() {
33
+ return this.timer !== undefined;
34
+ }
35
+ update(activeConnections, inFlightRequests) {
36
+ if (this.disposed) {
37
+ return;
38
+ }
39
+ if (activeConnections > 0 || inFlightRequests > 0) {
40
+ this.disarm();
41
+ return;
42
+ }
43
+ this.arm();
44
+ }
45
+ dispose() {
46
+ this.disposed = true;
47
+ this.disarm();
48
+ }
49
+ arm() {
50
+ if (this.timer !== undefined) {
51
+ return;
52
+ }
53
+ const timer = this.scheduler.setTimeout(() => {
54
+ this.timer = undefined;
55
+ void this.onIdleShutdown();
56
+ }, this.idleTimeoutMs);
57
+ timer.unref?.();
58
+ this.timer = timer;
59
+ }
60
+ disarm() {
61
+ if (this.timer === undefined) {
62
+ return;
63
+ }
64
+ this.scheduler.clearTimeout(this.timer);
65
+ this.timer = undefined;
66
+ }
67
+ }
68
+ exports.IdleMonitor = IdleMonitor;
69
+ //# sourceMappingURL=idle.js.map
@@ -0,0 +1,4 @@
1
+ export * from './endpoint.js';
2
+ export * from './lock.js';
3
+ export * from './idle.js';
4
+ export * from './shutdown.js';
@@ -0,0 +1,21 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./endpoint.js"), exports);
18
+ __exportStar(require("./lock.js"), exports);
19
+ __exportStar(require("./idle.js"), exports);
20
+ __exportStar(require("./shutdown.js"), exports);
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,28 @@
1
+ import type { DaemonEndpoint } from './endpoint.js';
2
+ export interface DaemonLockMetadata {
3
+ readonly pid: number;
4
+ readonly version: string;
5
+ }
6
+ export interface DaemonLockRecord {
7
+ readonly pid: number;
8
+ readonly startedAt: number;
9
+ readonly version: string;
10
+ readonly home: string;
11
+ }
12
+ export interface LockHandle {
13
+ readonly endpoint: DaemonEndpoint;
14
+ readonly lockPath: string;
15
+ readonly record: DaemonLockRecord;
16
+ release(): Promise<void>;
17
+ }
18
+ export declare class LockContentionError extends Error {
19
+ readonly existingPid: number | undefined;
20
+ readonly lockPath: string;
21
+ constructor(lockPath: string, existingPid: number | undefined, message?: string);
22
+ }
23
+ export declare class LockAcquisitionError extends Error {
24
+ constructor(message: string, options?: ErrorOptions);
25
+ }
26
+ export declare function isPidAlive(pid: number): boolean;
27
+ export declare function releaseDaemonLock(endpoint: DaemonEndpoint): Promise<void>;
28
+ export declare function acquireDaemonLock(endpoint: DaemonEndpoint, metadata: DaemonLockMetadata): Promise<LockHandle>;