@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.
- package/LICENSE +201 -0
- package/README.md +67 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +88 -0
- package/dist/client/DaemonClient.d.ts +55 -0
- package/dist/client/DaemonClient.js +383 -0
- package/dist/client/connectToDaemon.d.ts +19 -0
- package/dist/client/connectToDaemon.js +131 -0
- package/dist/client/errors.d.ts +74 -0
- package/dist/client/errors.js +104 -0
- package/dist/client/identity.d.ts +3 -0
- package/dist/client/identity.js +7 -0
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.js +23 -0
- package/dist/client/socket.d.ts +9 -0
- package/dist/client/socket.js +101 -0
- package/dist/client/spawn.d.ts +7 -0
- package/dist/client/spawn.js +171 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +29 -0
- package/dist/instanceRegistry.d.ts +130 -0
- package/dist/instanceRegistry.js +332 -0
- package/dist/lifecycle/endpoint.d.ts +19 -0
- package/dist/lifecycle/endpoint.js +124 -0
- package/dist/lifecycle/idle.d.ts +28 -0
- package/dist/lifecycle/idle.js +69 -0
- package/dist/lifecycle/index.d.ts +4 -0
- package/dist/lifecycle/index.js +21 -0
- package/dist/lifecycle/lock.d.ts +28 -0
- package/dist/lifecycle/lock.js +155 -0
- package/dist/lifecycle/shutdown.d.ts +39 -0
- package/dist/lifecycle/shutdown.js +115 -0
- package/dist/operatorConfig.d.ts +36 -0
- package/dist/operatorConfig.js +92 -0
- package/dist/security/channel.d.ts +113 -0
- package/dist/security/channel.js +448 -0
- package/dist/security/noise.d.ts +64 -0
- package/dist/security/noise.js +313 -0
- package/dist/security/ownership.d.ts +36 -0
- package/dist/security/ownership.js +86 -0
- package/dist/security/peerCredentials.d.ts +104 -0
- package/dist/security/peerCredentials.js +244 -0
- package/dist/server/Connection.d.ts +70 -0
- package/dist/server/Connection.js +412 -0
- package/dist/server/DaemonServer.d.ts +77 -0
- package/dist/server/DaemonServer.js +396 -0
- package/dist/server/createDaemon.d.ts +52 -0
- package/dist/server/createDaemon.js +165 -0
- package/dist/server/dispatch.d.ts +52 -0
- package/dist/server/dispatch.js +291 -0
- package/dist/server/framing.d.ts +63 -0
- package/dist/server/framing.js +196 -0
- package/dist/server/handshake.d.ts +22 -0
- package/dist/server/handshake.js +94 -0
- package/dist/server/protocolValidation.d.ts +47 -0
- package/dist/server/protocolValidation.js +366 -0
- package/dist/server/wireErrors.d.ts +5 -0
- package/dist/server/wireErrors.js +190 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +6 -0
- package/package.json +55 -4
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DaemonStartupTimeoutError = exports.DaemonNotRunningError = exports.DaemonSpawnError = exports.DaemonAuthError = exports.DaemonConnectionError = exports.DaemonRequestCancelledError = exports.DaemonRequestTimeoutError = exports.DaemonDisconnectedError = exports.DaemonRpcError = exports.DaemonClientError = void 0;
|
|
4
|
+
class DaemonClientError extends Error {
|
|
5
|
+
constructor(message, options) {
|
|
6
|
+
super(message, options);
|
|
7
|
+
this.name = 'DaemonClientError';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
exports.DaemonClientError = DaemonClientError;
|
|
11
|
+
class DaemonRpcError extends DaemonClientError {
|
|
12
|
+
code;
|
|
13
|
+
method;
|
|
14
|
+
requestId;
|
|
15
|
+
details;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
super(options.message);
|
|
18
|
+
this.name = 'DaemonRpcError';
|
|
19
|
+
this.code = options.code;
|
|
20
|
+
this.method = options.method;
|
|
21
|
+
this.requestId = options.requestId;
|
|
22
|
+
this.details = options.details;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.DaemonRpcError = DaemonRpcError;
|
|
26
|
+
class DaemonDisconnectedError extends DaemonClientError {
|
|
27
|
+
constructor(message = 'Daemon connection is closed', options) {
|
|
28
|
+
super(message, options);
|
|
29
|
+
this.name = 'DaemonDisconnectedError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
exports.DaemonDisconnectedError = DaemonDisconnectedError;
|
|
33
|
+
class DaemonRequestTimeoutError extends DaemonClientError {
|
|
34
|
+
requestId;
|
|
35
|
+
method;
|
|
36
|
+
timeoutMs;
|
|
37
|
+
constructor(options) {
|
|
38
|
+
super(`Request "${options.method}" timed out after ${options.timeoutMs} ms`);
|
|
39
|
+
this.name = 'DaemonRequestTimeoutError';
|
|
40
|
+
this.requestId = options.requestId;
|
|
41
|
+
this.method = options.method;
|
|
42
|
+
this.timeoutMs = options.timeoutMs;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
exports.DaemonRequestTimeoutError = DaemonRequestTimeoutError;
|
|
46
|
+
class DaemonRequestCancelledError extends DaemonClientError {
|
|
47
|
+
requestId;
|
|
48
|
+
method;
|
|
49
|
+
constructor(options) {
|
|
50
|
+
super(`Request "${options.method}" was cancelled`);
|
|
51
|
+
this.name = 'DaemonRequestCancelledError';
|
|
52
|
+
this.requestId = options.requestId;
|
|
53
|
+
this.method = options.method;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
exports.DaemonRequestCancelledError = DaemonRequestCancelledError;
|
|
57
|
+
class DaemonConnectionError extends DaemonClientError {
|
|
58
|
+
constructor(message, options) {
|
|
59
|
+
super(message, options);
|
|
60
|
+
this.name = 'DaemonConnectionError';
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
exports.DaemonConnectionError = DaemonConnectionError;
|
|
64
|
+
/**
|
|
65
|
+
* The authenticated channel could not be established: wrong principal key,
|
|
66
|
+
* invalid handshake payload, tampered record, or a rejected workspace scope.
|
|
67
|
+
*/
|
|
68
|
+
class DaemonAuthError extends DaemonClientError {
|
|
69
|
+
constructor(message, options) {
|
|
70
|
+
super(message, options);
|
|
71
|
+
this.name = 'DaemonAuthError';
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
exports.DaemonAuthError = DaemonAuthError;
|
|
75
|
+
class DaemonSpawnError extends DaemonClientError {
|
|
76
|
+
constructor(message, options) {
|
|
77
|
+
super(message, options);
|
|
78
|
+
this.name = 'DaemonSpawnError';
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
exports.DaemonSpawnError = DaemonSpawnError;
|
|
82
|
+
class DaemonNotRunningError extends DaemonClientError {
|
|
83
|
+
home;
|
|
84
|
+
socketPath;
|
|
85
|
+
constructor(options) {
|
|
86
|
+
super(`No daemon is running for workspace "${options.home}" at "${options.socketPath}"`, options.cause === undefined ? undefined : { cause: options.cause });
|
|
87
|
+
this.name = 'DaemonNotRunningError';
|
|
88
|
+
this.home = options.home;
|
|
89
|
+
this.socketPath = options.socketPath;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
exports.DaemonNotRunningError = DaemonNotRunningError;
|
|
93
|
+
class DaemonStartupTimeoutError extends DaemonClientError {
|
|
94
|
+
home;
|
|
95
|
+
timeoutMs;
|
|
96
|
+
constructor(options) {
|
|
97
|
+
super(`Daemon for workspace "${options.home}" did not become ready within ${options.timeoutMs} ms`, options.cause === undefined ? undefined : { cause: options.cause });
|
|
98
|
+
this.name = 'DaemonStartupTimeoutError';
|
|
99
|
+
this.home = options.home;
|
|
100
|
+
this.timeoutMs = options.timeoutMs;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
exports.DaemonStartupTimeoutError = DaemonStartupTimeoutError;
|
|
104
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DAEMON_CLIENT_CAPABILITIES = exports.DAEMON_CLIENT_VERSION = exports.DAEMON_CLIENT_NAME = void 0;
|
|
4
|
+
exports.DAEMON_CLIENT_NAME = 'brud-daemon-client';
|
|
5
|
+
exports.DAEMON_CLIENT_VERSION = '0.0.1';
|
|
6
|
+
exports.DAEMON_CLIENT_CAPABILITIES = ['fs'];
|
|
7
|
+
//# sourceMappingURL=identity.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
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("./errors.js"), exports);
|
|
18
|
+
__exportStar(require("./identity.js"), exports);
|
|
19
|
+
__exportStar(require("./socket.js"), exports);
|
|
20
|
+
__exportStar(require("./DaemonClient.js"), exports);
|
|
21
|
+
__exportStar(require("./spawn.js"), exports);
|
|
22
|
+
__exportStar(require("./connectToDaemon.js"), exports);
|
|
23
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Socket } from 'node:net';
|
|
2
|
+
import type { DaemonCallerTier } from '@brud/protocol';
|
|
3
|
+
import type { DaemonEndpoint } from '../lifecycle/endpoint.js';
|
|
4
|
+
export declare const DEFAULT_CONNECT_TIMEOUT_MS = 5000;
|
|
5
|
+
export declare function normalizeTimeout(value: number | undefined, fallback: number): number;
|
|
6
|
+
/** Path of the pre-shared key that authenticates one caller principal. */
|
|
7
|
+
export declare function principalTokenPath(endpoint: DaemonEndpoint, principal: DaemonCallerTier): string;
|
|
8
|
+
export declare function readDaemonToken(endpoint: DaemonEndpoint, principal?: DaemonCallerTier): Promise<string>;
|
|
9
|
+
export declare function connectSocket(socketPath: string, timeoutMs?: number): Promise<Socket>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_CONNECT_TIMEOUT_MS = void 0;
|
|
4
|
+
exports.normalizeTimeout = normalizeTimeout;
|
|
5
|
+
exports.principalTokenPath = principalTokenPath;
|
|
6
|
+
exports.readDaemonToken = readDaemonToken;
|
|
7
|
+
exports.connectSocket = connectSocket;
|
|
8
|
+
const promises_1 = require("node:fs/promises");
|
|
9
|
+
const node_net_1 = require("node:net");
|
|
10
|
+
const ownership_js_1 = require("../security/ownership.js");
|
|
11
|
+
const errors_js_1 = require("./errors.js");
|
|
12
|
+
exports.DEFAULT_CONNECT_TIMEOUT_MS = 5_000;
|
|
13
|
+
function normalizeTimeout(value, fallback) {
|
|
14
|
+
if (value === undefined) {
|
|
15
|
+
return fallback;
|
|
16
|
+
}
|
|
17
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
18
|
+
throw new RangeError('Timeout must be a positive finite number');
|
|
19
|
+
}
|
|
20
|
+
return Math.max(1, Math.trunc(value));
|
|
21
|
+
}
|
|
22
|
+
/** Path of the pre-shared key that authenticates one caller principal. */
|
|
23
|
+
function principalTokenPath(endpoint, principal) {
|
|
24
|
+
return principal === 'ai' ? endpoint.aiTokenPath : endpoint.tokenPath;
|
|
25
|
+
}
|
|
26
|
+
async function readDaemonToken(endpoint, principal = 'ui') {
|
|
27
|
+
const tokenPath = principalTokenPath(endpoint, principal);
|
|
28
|
+
let token;
|
|
29
|
+
try {
|
|
30
|
+
token = (await (0, promises_1.readFile)(tokenPath, 'utf8')).trim();
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
throw new errors_js_1.DaemonConnectionError(`Unable to read daemon token at "${tokenPath}"`, { cause: error });
|
|
34
|
+
}
|
|
35
|
+
if (token.length === 0) {
|
|
36
|
+
throw new errors_js_1.DaemonConnectionError(`Daemon token at "${tokenPath}" is empty`);
|
|
37
|
+
}
|
|
38
|
+
return token;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Verifies the endpoint's on-disk ownership before opening a connection.
|
|
42
|
+
*
|
|
43
|
+
* On POSIX this refuses a socket owned by another user or reachable by group
|
|
44
|
+
* or world. Windows named pipes report `unsupported`; the caller proceeds on
|
|
45
|
+
* the platform's pipe ACL, which Node cannot inspect.
|
|
46
|
+
*/
|
|
47
|
+
async function assertEndpointOwnership(socketPath) {
|
|
48
|
+
try {
|
|
49
|
+
await (0, ownership_js_1.verifyEndpointOwnership)(socketPath);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (error instanceof ownership_js_1.EndpointOwnershipError) {
|
|
53
|
+
throw new errors_js_1.DaemonConnectionError(error.message, { cause: error });
|
|
54
|
+
}
|
|
55
|
+
throw new errors_js_1.DaemonConnectionError(`Cannot verify daemon endpoint ownership at "${socketPath}"`, { cause: error });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function connectSocket(socketPath, timeoutMs = exports.DEFAULT_CONNECT_TIMEOUT_MS) {
|
|
59
|
+
const timeout = normalizeTimeout(timeoutMs, exports.DEFAULT_CONNECT_TIMEOUT_MS);
|
|
60
|
+
await assertEndpointOwnership(socketPath);
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
const socket = (0, node_net_1.createConnection)(socketPath);
|
|
63
|
+
let settled = false;
|
|
64
|
+
const finish = () => {
|
|
65
|
+
if (settled) {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
settled = true;
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
socket.off('connect', onConnect);
|
|
71
|
+
socket.off('error', onError);
|
|
72
|
+
return true;
|
|
73
|
+
};
|
|
74
|
+
const onConnect = () => {
|
|
75
|
+
if (!finish()) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
resolve(socket);
|
|
79
|
+
};
|
|
80
|
+
const onError = (error) => {
|
|
81
|
+
if (!finish()) {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
socket.destroy();
|
|
85
|
+
reject(new errors_js_1.DaemonConnectionError(`Cannot connect to daemon socket at "${socketPath}"`, {
|
|
86
|
+
cause: error,
|
|
87
|
+
}));
|
|
88
|
+
};
|
|
89
|
+
const timer = setTimeout(() => {
|
|
90
|
+
if (!finish()) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
socket.destroy();
|
|
94
|
+
reject(new errors_js_1.DaemonConnectionError(`Timed out connecting to daemon socket at "${socketPath}" after ${timeout} ms`));
|
|
95
|
+
}, timeout);
|
|
96
|
+
timer.unref?.();
|
|
97
|
+
socket.once('connect', onConnect);
|
|
98
|
+
socket.once('error', onError);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=socket.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const DEFAULT_SPAWN_TIMEOUT_MS = 5000;
|
|
2
|
+
export declare const READINESS_POLL_INTERVAL_MS = 50;
|
|
3
|
+
export interface SpawnDaemonOptions {
|
|
4
|
+
readonly timeoutMs?: number;
|
|
5
|
+
}
|
|
6
|
+
export declare function resolveDaemonCliPath(): Promise<string>;
|
|
7
|
+
export declare function spawnDaemon(home: string, options?: SpawnDaemonOptions): Promise<void>;
|
|
@@ -0,0 +1,171 @@
|
|
|
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.READINESS_POLL_INTERVAL_MS = exports.DEFAULT_SPAWN_TIMEOUT_MS = void 0;
|
|
37
|
+
exports.resolveDaemonCliPath = resolveDaemonCliPath;
|
|
38
|
+
exports.spawnDaemon = spawnDaemon;
|
|
39
|
+
const node_child_process_1 = require("node:child_process");
|
|
40
|
+
const promises_1 = require("node:fs/promises");
|
|
41
|
+
const node_fs_1 = require("node:fs");
|
|
42
|
+
const node_path_1 = require("node:path");
|
|
43
|
+
const Protocol = __importStar(require("@brud/protocol"));
|
|
44
|
+
const endpoint_js_1 = require("../lifecycle/endpoint.js");
|
|
45
|
+
const DaemonClient_js_1 = require("./DaemonClient.js");
|
|
46
|
+
const errors_js_1 = require("./errors.js");
|
|
47
|
+
const identity_js_1 = require("./identity.js");
|
|
48
|
+
const socket_js_1 = require("./socket.js");
|
|
49
|
+
const channel_js_1 = require("../security/channel.js");
|
|
50
|
+
exports.DEFAULT_SPAWN_TIMEOUT_MS = 5_000;
|
|
51
|
+
exports.READINESS_POLL_INTERVAL_MS = 50;
|
|
52
|
+
const PROBE_ATTEMPT_TIMEOUT_MS = 1_000;
|
|
53
|
+
function delay(durationMs) {
|
|
54
|
+
return new Promise((resolveDelay) => {
|
|
55
|
+
setTimeout(resolveDelay, durationMs);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
async function fileExists(path) {
|
|
59
|
+
try {
|
|
60
|
+
await (0, promises_1.access)(path, node_fs_1.constants.F_OK);
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function resolveDaemonCliPath() {
|
|
68
|
+
const candidates = [
|
|
69
|
+
(0, node_path_1.resolve)(__dirname, '..', 'cli.js'),
|
|
70
|
+
(0, node_path_1.resolve)(__dirname, '..', 'cli.ts'),
|
|
71
|
+
(0, node_path_1.resolve)(__dirname, 'daemon', 'cli.js'),
|
|
72
|
+
(0, node_path_1.resolve)(__dirname, '..', '..', 'dist', 'cli.js'),
|
|
73
|
+
];
|
|
74
|
+
for (const candidate of candidates) {
|
|
75
|
+
if (await fileExists(candidate)) {
|
|
76
|
+
return candidate;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
throw new errors_js_1.DaemonSpawnError(`Cannot locate daemon CLI. Looked in: ${candidates.join(', ')}`);
|
|
80
|
+
}
|
|
81
|
+
async function readReadyMetadata(endpoint) {
|
|
82
|
+
let content;
|
|
83
|
+
try {
|
|
84
|
+
content = await (0, promises_1.readFile)(endpoint.metaPath, 'utf8');
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
throw new errors_js_1.DaemonConnectionError(`Daemon metadata at "${endpoint.metaPath}" is not available`, { cause: error });
|
|
88
|
+
}
|
|
89
|
+
let parsed;
|
|
90
|
+
try {
|
|
91
|
+
parsed = JSON.parse(content);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
throw new errors_js_1.DaemonConnectionError(`Daemon metadata at "${endpoint.metaPath}" is not valid JSON`, { cause: error });
|
|
95
|
+
}
|
|
96
|
+
if (typeof parsed !== 'object' || parsed === null || !('socketPath' in parsed)) {
|
|
97
|
+
throw new errors_js_1.DaemonConnectionError(`Daemon metadata at "${endpoint.metaPath}" is malformed`);
|
|
98
|
+
}
|
|
99
|
+
const socketPath = parsed.socketPath;
|
|
100
|
+
if (socketPath !== endpoint.socketPath) {
|
|
101
|
+
throw new errors_js_1.DaemonConnectionError(`Daemon metadata socket path does not match "${endpoint.socketPath}"`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function probeDaemonReadiness(endpoint, timeoutMs) {
|
|
105
|
+
await readReadyMetadata(endpoint);
|
|
106
|
+
const token = await (0, socket_js_1.readDaemonToken)(endpoint, 'ui');
|
|
107
|
+
const socket = await (0, socket_js_1.connectSocket)(endpoint.socketPath, timeoutMs);
|
|
108
|
+
const client = new DaemonClient_js_1.DaemonClient(socket, {
|
|
109
|
+
psk: token,
|
|
110
|
+
principal: 'ui',
|
|
111
|
+
home: endpoint.home,
|
|
112
|
+
prologue: (0, channel_js_1.channelPrologue)(endpoint.socketPath),
|
|
113
|
+
handshakeTimeoutMs: timeoutMs,
|
|
114
|
+
});
|
|
115
|
+
try {
|
|
116
|
+
await client.connect({
|
|
117
|
+
protocolVersion: Protocol.DAEMON_PROTOCOL_VERSION,
|
|
118
|
+
client: { name: identity_js_1.DAEMON_CLIENT_NAME, version: identity_js_1.DAEMON_CLIENT_VERSION },
|
|
119
|
+
capabilities: [...identity_js_1.DAEMON_CLIENT_CAPABILITIES],
|
|
120
|
+
}, { timeoutMs });
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
await client.close();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
async function spawnDaemon(home, options) {
|
|
127
|
+
const timeoutMs = (0, socket_js_1.normalizeTimeout)(options?.timeoutMs, exports.DEFAULT_SPAWN_TIMEOUT_MS);
|
|
128
|
+
const endpoint = await (0, endpoint_js_1.resolveEndpoint)(home);
|
|
129
|
+
const cliPath = await resolveDaemonCliPath();
|
|
130
|
+
const invocation = cliPath.endsWith('.ts')
|
|
131
|
+
? ['--import', 'tsx', cliPath]
|
|
132
|
+
: [cliPath];
|
|
133
|
+
const child = (0, node_child_process_1.spawn)(process.execPath, [...invocation, '--home', endpoint.home], {
|
|
134
|
+
detached: true,
|
|
135
|
+
stdio: 'ignore',
|
|
136
|
+
windowsHide: true,
|
|
137
|
+
env: { ...process.env, BRUD_DAEMON_HOME: endpoint.home },
|
|
138
|
+
});
|
|
139
|
+
let spawnError;
|
|
140
|
+
child.once('error', (error) => {
|
|
141
|
+
spawnError = error;
|
|
142
|
+
});
|
|
143
|
+
child.unref();
|
|
144
|
+
const deadline = Date.now() + timeoutMs;
|
|
145
|
+
let lastError;
|
|
146
|
+
for (;;) {
|
|
147
|
+
if (spawnError !== undefined) {
|
|
148
|
+
throw new errors_js_1.DaemonSpawnError(`Failed to spawn daemon for home "${endpoint.home}"`, { cause: spawnError });
|
|
149
|
+
}
|
|
150
|
+
const remaining = deadline - Date.now();
|
|
151
|
+
const attemptTimeout = Math.max(1, Math.min(PROBE_ATTEMPT_TIMEOUT_MS, remaining));
|
|
152
|
+
try {
|
|
153
|
+
await probeDaemonReadiness(endpoint, attemptTimeout);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
lastError = error;
|
|
158
|
+
}
|
|
159
|
+
const remainingAfterProbe = deadline - Date.now();
|
|
160
|
+
if (remainingAfterProbe <= 0) {
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
await delay(Math.min(exports.READINESS_POLL_INTERVAL_MS, remainingAfterProbe));
|
|
164
|
+
}
|
|
165
|
+
throw new errors_js_1.DaemonStartupTimeoutError({
|
|
166
|
+
home: endpoint.home,
|
|
167
|
+
timeoutMs,
|
|
168
|
+
cause: lastError,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
//# sourceMappingURL=spawn.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './version.js';
|
|
2
|
+
export * from './operatorConfig.js';
|
|
3
|
+
export * from './instanceRegistry.js';
|
|
4
|
+
export * from './lifecycle/index.js';
|
|
5
|
+
export * from './server/framing.js';
|
|
6
|
+
export * from './server/wireErrors.js';
|
|
7
|
+
export * from './server/handshake.js';
|
|
8
|
+
export * from './server/dispatch.js';
|
|
9
|
+
export * from './server/Connection.js';
|
|
10
|
+
export * from './server/DaemonServer.js';
|
|
11
|
+
export * from './server/createDaemon.js';
|
|
12
|
+
export * from './client/index.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
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("./version.js"), exports);
|
|
18
|
+
__exportStar(require("./operatorConfig.js"), exports);
|
|
19
|
+
__exportStar(require("./instanceRegistry.js"), exports);
|
|
20
|
+
__exportStar(require("./lifecycle/index.js"), exports);
|
|
21
|
+
__exportStar(require("./server/framing.js"), exports);
|
|
22
|
+
__exportStar(require("./server/wireErrors.js"), exports);
|
|
23
|
+
__exportStar(require("./server/handshake.js"), exports);
|
|
24
|
+
__exportStar(require("./server/dispatch.js"), exports);
|
|
25
|
+
__exportStar(require("./server/Connection.js"), exports);
|
|
26
|
+
__exportStar(require("./server/DaemonServer.js"), exports);
|
|
27
|
+
__exportStar(require("./server/createDaemon.js"), exports);
|
|
28
|
+
__exportStar(require("./client/index.js"), exports);
|
|
29
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type * as KernelApi from '@brud/kernel' with { 'resolution-mode': 'import' };
|
|
2
|
+
import type { BrudKernel } from '@brud/kernel' with { 'resolution-mode': 'import' };
|
|
3
|
+
import type { DaemonOperatorConfig } from './operatorConfig.js';
|
|
4
|
+
type KernelModule = typeof KernelApi;
|
|
5
|
+
/** Loads `@brud/kernel` once (ESM, cached). */
|
|
6
|
+
export declare function loadKernelModule(): Promise<KernelModule>;
|
|
7
|
+
/** Kernel-owned startup fields the daemon fills from its own home. */
|
|
8
|
+
export declare const IDENTITY_REGISTRY_PATH_FIELD = "identity.registry.path";
|
|
9
|
+
export declare const EXPOSED_API_SCOPE_RECORD_FIELD = "exposedApi.scopeRecord.path";
|
|
10
|
+
/** Lifecycle of one hosted kernel. */
|
|
11
|
+
export type KernelInstanceState = 'booting' | 'running' | 'shutting-down' | 'disposed';
|
|
12
|
+
/** A participant the kernel left out because required startup fields were missing. */
|
|
13
|
+
export interface PrunedParticipants {
|
|
14
|
+
readonly participants: readonly string[];
|
|
15
|
+
readonly path: string;
|
|
16
|
+
readonly missingFields: readonly string[];
|
|
17
|
+
}
|
|
18
|
+
/** One kernel the daemon hosts. */
|
|
19
|
+
export interface KernelInstance {
|
|
20
|
+
readonly id: string;
|
|
21
|
+
/** Hash of the client-supplied options (identical boots share a key). */
|
|
22
|
+
readonly key: string;
|
|
23
|
+
/**
|
|
24
|
+
* Name of the instance's state folder under `<home>/kernels/`. The first
|
|
25
|
+
* live kernel for a key uses the key itself, so its identity registry
|
|
26
|
+
* persists across restarts; a concurrent kernel with the same key gets a
|
|
27
|
+
* numbered sibling, because two live kernels must never share state.
|
|
28
|
+
*/
|
|
29
|
+
readonly stateName: string;
|
|
30
|
+
readonly kernel: BrudKernel;
|
|
31
|
+
readonly clients: Set<string>;
|
|
32
|
+
state: KernelInstanceState;
|
|
33
|
+
lastUsedAt: Date;
|
|
34
|
+
/** Participants the kernel left out at boot (missing required fields). */
|
|
35
|
+
readonly pruned: readonly PrunedParticipants[];
|
|
36
|
+
}
|
|
37
|
+
/** A required startup field, as collected from the composition. */
|
|
38
|
+
export interface RequirementField {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly type: string;
|
|
41
|
+
readonly required: boolean;
|
|
42
|
+
readonly description?: string;
|
|
43
|
+
readonly service: string;
|
|
44
|
+
}
|
|
45
|
+
/** Raised when a client sets a startup field the operator did not allow. */
|
|
46
|
+
export declare class BootOptionNotAllowedError extends Error {
|
|
47
|
+
readonly field: string;
|
|
48
|
+
readonly code = "BOOT_OPTION_NOT_ALLOWED";
|
|
49
|
+
constructor(field: string);
|
|
50
|
+
}
|
|
51
|
+
/** Raised for an instance id that is unknown or not attached to the client. */
|
|
52
|
+
export declare class KernelInstanceNotFoundError extends Error {
|
|
53
|
+
readonly instanceId: string;
|
|
54
|
+
readonly code = "KERNEL_INSTANCE_NOT_FOUND";
|
|
55
|
+
constructor(instanceId: string);
|
|
56
|
+
}
|
|
57
|
+
export interface KernelInstanceRegistryOptions {
|
|
58
|
+
/** Daemon home: the operator's state folder. */
|
|
59
|
+
readonly home: string;
|
|
60
|
+
readonly operator: DaemonOperatorConfig;
|
|
61
|
+
/** Dispose a kernel with no attached clients after this long; 0 disables. */
|
|
62
|
+
readonly idleTimeoutMs?: number;
|
|
63
|
+
readonly now?: () => number;
|
|
64
|
+
readonly logger?: {
|
|
65
|
+
warn(message: string, meta?: Record<string, unknown>): void;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Default idle window for a kernel with no clients. */
|
|
69
|
+
export declare const DEFAULT_INSTANCE_IDLE_TIMEOUT_MS: number;
|
|
70
|
+
/**
|
|
71
|
+
* The daemon's kernels. It knows no participant and no domain: startup options
|
|
72
|
+
* are the operator's fixed options plus the client's allowed ones, validated by
|
|
73
|
+
* the kernel's own context contract at boot.
|
|
74
|
+
*/
|
|
75
|
+
export declare class KernelInstanceRegistry {
|
|
76
|
+
private readonly instances;
|
|
77
|
+
private readonly pending;
|
|
78
|
+
/** State folder names held by live or booting kernels. */
|
|
79
|
+
private readonly reservedStates;
|
|
80
|
+
private readonly home;
|
|
81
|
+
private readonly operator;
|
|
82
|
+
private readonly idleTimeoutMs;
|
|
83
|
+
private readonly now;
|
|
84
|
+
private readonly logger;
|
|
85
|
+
private sweepTimer;
|
|
86
|
+
private disposed;
|
|
87
|
+
constructor(options: KernelInstanceRegistryOptions);
|
|
88
|
+
/** Startup fields a client may set. */
|
|
89
|
+
get clientSettableFields(): readonly string[];
|
|
90
|
+
/** Host-session capabilities for an authenticated principal. */
|
|
91
|
+
capabilitiesFor(principal: 'ui' | 'ai'): readonly string[];
|
|
92
|
+
/**
|
|
93
|
+
* The composition's declared startup fields. Boots a throwaway kernel with
|
|
94
|
+
* only the operator's options: the context contract refuses it before any
|
|
95
|
+
* participant is constructed when a required field is missing, and the
|
|
96
|
+
* collected declarations are read either way.
|
|
97
|
+
*/
|
|
98
|
+
requirements(): Promise<readonly RequirementField[]>;
|
|
99
|
+
/** Boots (or, if the operator allows, reuses) a kernel for one client. */
|
|
100
|
+
boot(clientOptions: Readonly<Record<string, unknown>>, clientId: string): Promise<{
|
|
101
|
+
readonly instance: KernelInstance;
|
|
102
|
+
readonly reused: boolean;
|
|
103
|
+
}>;
|
|
104
|
+
/** Claims the lowest free state folder name for a key (synchronously, before any await). */
|
|
105
|
+
private reserveState;
|
|
106
|
+
private create;
|
|
107
|
+
/**
|
|
108
|
+
* Kernel-owned fields come from the daemon home; the operator's fixed
|
|
109
|
+
* options override them; the client's allowed options come last but can
|
|
110
|
+
* only name allowed fields.
|
|
111
|
+
*/
|
|
112
|
+
private kernelOptions;
|
|
113
|
+
/** Attaches a client to an existing instance. */
|
|
114
|
+
attach(instanceId: string, clientId: string): KernelInstance;
|
|
115
|
+
/** An instance the client is attached to. */
|
|
116
|
+
forClient(instanceId: string, clientId: string): KernelInstance;
|
|
117
|
+
/** Instances the client is attached to. */
|
|
118
|
+
listFor(clientId: string): readonly KernelInstance[];
|
|
119
|
+
/** Detaches a closing client from every instance. */
|
|
120
|
+
detachClient(clientId: string): void;
|
|
121
|
+
/** Shuts one instance down. */
|
|
122
|
+
dispose(instanceId: string): Promise<boolean>;
|
|
123
|
+
/** Disposes client-less instances idle past the timeout. */
|
|
124
|
+
sweepIdle(): Promise<void>;
|
|
125
|
+
/** Every running instance (daemon-internal: shutdown, activity). */
|
|
126
|
+
get size(): number;
|
|
127
|
+
/** Shuts every instance down. */
|
|
128
|
+
disposeAll(): Promise<void>;
|
|
129
|
+
}
|
|
130
|
+
export {};
|