@mearl/daemon-core 2.21.0 → 3.0.0-beta.0

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Mearl 各 Node 包共享的守护进程生命周期原语:进程存活探测
4
4
 
5
5
  把 `cloud-server`、`cloud-connector`、`native-host` 里原本各写一份、容易彼此漂移的 daemon 逻辑(`isAlive`、原子读写注册表、日志滚动、按 key 派生路径)收敛到这一处,确保「写方」和「读方」对**记录位置与格式**始终一致。
6
6
 
7
- > 仅供 monorepo 内部使用(Node-only)。`cloud-server` / `cloud-connector` 以普通依赖引入(运行时从 npm 解析),`native-host` 在打包时直接内联。
7
+ 此包只在 Node 中运行,可以作为普通依赖使用,也可以由执行宿主打包内联。
8
8
 
9
9
  ## API
10
10
 
@@ -95,3 +95,6 @@ tailFile(logFile: string, lines: number): string
95
95
  - **cloud-server** —— `createDaemon`(单实例,`~/.mearl/cloud-server.json`)
96
96
  - **cloud-connector** —— `createDaemon`(多实例,按 `serverUrl` 区分,`~/.mearl/connectors/<hash>.json`)+ `readLiveRecords` 列举
97
97
  - **native-host** —— 仅用原语(`isAlive` / `keyedConfigFile` / `readRecord` / `readLiveRecords` 等)读取连接器共享注册表,以发现/接管/列举连接器
98
+
99
+
100
+ `@mearl/daemon-core/capabilities` 的 `NodeCapabilityRegistry` 可在第三个构造参数传入 `hooks`,只加载这些绑定引用的模块。选择本身仍完整校验,目标模块字节按摘要验证,提交仍核对当前选择;忽略的模块不执行。该局部实例适用于安装 CLI 等只需要少量本机服务的宿主,不替代完整 Native Host 的激活与就绪回执。省略 `hooks` 时保持完整加载。
package/dist/command.d.ts CHANGED
@@ -1,4 +1,16 @@
1
1
  import fs from 'node:fs';
2
+ export interface CommandProcessOwner {
3
+ pid: number;
4
+ processIdentity?: string;
5
+ group?: number;
6
+ }
7
+ export interface CommandLifecycle {
8
+ started(owner: CommandProcessOwner): void;
9
+ finished(owner: CommandProcessOwner): void;
10
+ }
11
+ /** Accepted installation commands retain process ownership until their complete process group exits. */
12
+ export declare function withOwnedCommands<T>(lifecycle: CommandLifecycle, operation: () => Promise<T>): Promise<T>;
13
+ export declare function isCommandProcessAlive(owner: CommandProcessOwner): boolean;
2
14
  export interface SpawnCommand {
3
15
  command: string;
4
16
  args: string[];
package/dist/command.js CHANGED
@@ -1,6 +1,54 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { spawn } from 'node:child_process';
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { isProcessGroupAlive, isProcessOwnerAlive, processIdentity } from './process.js';
6
+ const ownedCommands = new AsyncLocalStorage();
7
+ /** Accepted installation commands retain process ownership until their complete process group exits. */
8
+ export function withOwnedCommands(lifecycle, operation) {
9
+ return ownedCommands.run(lifecycle, operation);
10
+ }
11
+ export function isCommandProcessAlive(owner) {
12
+ if (!owner.group || process.platform === 'win32')
13
+ return isProcessOwnerAlive(owner);
14
+ const identity = processIdentity(owner.pid);
15
+ if (identity && owner.processIdentity && identity !== owner.processIdentity)
16
+ return false;
17
+ return isProcessGroupAlive(owner.group);
18
+ }
19
+ async function stopCommandProcess(owner) {
20
+ if (process.platform === 'win32') {
21
+ if (!isCommandProcessAlive(owner))
22
+ return;
23
+ await new Promise((resolve, reject) => {
24
+ const killer = spawn('taskkill', ['/pid', String(owner.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore' });
25
+ killer.once('error', reject);
26
+ killer.once('close', () => resolve());
27
+ });
28
+ }
29
+ else {
30
+ const signal = (value) => {
31
+ try {
32
+ process.kill(-(owner.group ?? owner.pid), value);
33
+ }
34
+ catch (error) {
35
+ if (error.code !== 'ESRCH')
36
+ throw error;
37
+ }
38
+ };
39
+ signal('SIGTERM');
40
+ const grace = Date.now() + 250;
41
+ while (isCommandProcessAlive(owner) && Date.now() < grace)
42
+ await new Promise(resolve => setTimeout(resolve, 20));
43
+ if (isCommandProcessAlive(owner))
44
+ signal('SIGKILL');
45
+ }
46
+ const deadline = Date.now() + 2000;
47
+ while (isCommandProcessAlive(owner) && Date.now() < deadline)
48
+ await new Promise(resolve => setTimeout(resolve, 20));
49
+ if (isCommandProcessAlive(owner))
50
+ throw new Error('Command process is still stopping');
51
+ }
4
52
  const MAX_CAPTURE_LENGTH = 1_000_000;
5
53
  export function isExecutable(filePath, platform = process.platform) {
6
54
  try {
@@ -90,16 +138,21 @@ export function findExecutable(name, options = {}) {
90
138
  }
91
139
  export const runCommand = (command, args, options = {}) => new Promise((resolve, reject) => {
92
140
  const capture = options.capture === true || options.tee === true;
141
+ const lifecycle = ownedCommands.getStore();
93
142
  const launch = resolveSpawnCommand(command, args);
94
143
  const child = spawn(launch.command, launch.args, {
95
144
  cwd: options.cwd,
96
145
  env: options.env,
97
146
  stdio: capture ? [options.tee ? 'inherit' : 'ignore', 'pipe', 'pipe'] : 'inherit',
98
147
  windowsHide: true,
148
+ ...(lifecycle && process.platform !== 'win32' ? { detached: true } : {}),
99
149
  });
100
150
  let stdout = '';
101
151
  let stderr = '';
102
152
  let settled = false;
153
+ let finalizing = false;
154
+ let timedOut;
155
+ const owner = lifecycle && child.pid ? { pid: child.pid, processIdentity: processIdentity(child.pid), ...(process.platform !== 'win32' ? { group: child.pid } : {}) } : undefined;
103
156
  const append = (current, chunk) => options.tee
104
157
  ? (current + chunk).slice(-MAX_CAPTURE_LENGTH)
105
158
  : current.length >= MAX_CAPTURE_LENGTH
@@ -116,11 +169,33 @@ export const runCommand = (command, args, options = {}) => new Promise((resolve,
116
169
  else
117
170
  resolve({ code, stdout, stderr });
118
171
  };
172
+ const finishOwned = async (error, code = 1) => {
173
+ if (finalizing || settled)
174
+ return;
175
+ finalizing = true;
176
+ if (timer)
177
+ clearTimeout(timer);
178
+ try {
179
+ if (owner && isCommandProcessAlive(owner))
180
+ await stopCommandProcess(owner);
181
+ if (owner)
182
+ lifecycle.finished(owner);
183
+ finish(error ?? timedOut, code);
184
+ }
185
+ catch (failure) {
186
+ finish(failure instanceof Error ? failure : new Error(String(failure)));
187
+ }
188
+ };
119
189
  const timer = options.timeoutMs === undefined
120
190
  ? undefined
121
191
  : setTimeout(() => {
122
- child.kill('SIGTERM');
123
- finish(new Error(`Command timed out after ${options.timeoutMs}ms`));
192
+ timedOut = new Error(`Command timed out after ${options.timeoutMs}ms`);
193
+ if (lifecycle)
194
+ void finishOwned(timedOut);
195
+ else {
196
+ child.kill('SIGTERM');
197
+ finish(timedOut);
198
+ }
124
199
  }, options.timeoutMs);
125
200
  if (capture) {
126
201
  child.stdout?.setEncoding('utf8').on('data', (chunk) => {
@@ -134,6 +209,14 @@ export const runCommand = (command, args, options = {}) => new Promise((resolve,
134
209
  process.stderr.write(chunk);
135
210
  });
136
211
  }
137
- child.once('error', error => finish(error));
138
- child.once('close', code => finish(undefined, code ?? 1));
212
+ child.once('error', error => lifecycle ? void finishOwned(error) : finish(error));
213
+ child.once('close', code => lifecycle ? void finishOwned(undefined, code ?? 1) : finish(undefined, code ?? 1));
214
+ if (lifecycle && owner) {
215
+ try {
216
+ lifecycle.started(owner);
217
+ }
218
+ catch (error) {
219
+ void finishOwned(error instanceof Error ? error : new Error(String(error)));
220
+ }
221
+ }
139
222
  });
@@ -0,0 +1,23 @@
1
+ export type NodeCapabilityHandler = (...args: any[]) => any;
2
+ export type NodeCapabilityHandlers = Record<string, NodeCapabilityHandler>;
3
+ export type NodeCapabilityFactory<Host extends object = object> = (host: Readonly<Host>, config: Record<string, unknown>) => NodeCapabilityHandlers | Promise<NodeCapabilityHandlers>;
4
+ /** Locally installed, verified module bytes execute only in the Node host. */
5
+ export declare class NodeCapabilityRegistry<Host extends object = object> {
6
+ readonly directory: string;
7
+ private active;
8
+ private queue;
9
+ private readonly host;
10
+ private readonly hooks?;
11
+ constructor(host: Host, directory?: string, options?: {
12
+ hooks?: readonly string[];
13
+ });
14
+ get revision(): string | undefined;
15
+ get installationRevision(): string | undefined;
16
+ get<T extends NodeCapabilityHandler>(name: string): T | undefined;
17
+ require<T extends NodeCapabilityHandler>(name: string): T;
18
+ refresh(): Promise<string | undefined>;
19
+ private readSelection;
20
+ private load;
21
+ private restorePrevious;
22
+ private prepareSelection;
23
+ }
@@ -0,0 +1,169 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createRequire } from 'node:module';
3
+ import { Script } from 'node:vm';
4
+ import { constants } from 'node:fs';
5
+ import { lstat, open } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ import { DAEMON_HOME } from './paths.js';
8
+ import { verifyNodeCapabilityActivation, MAX_NODE_SELECTION_BYTES } from '@mearl/preset';
9
+ const MAX_SELECTION_BYTES = MAX_NODE_SELECTION_BYTES + 128;
10
+ const handlerName = /^[a-z][a-zA-Z0-9_.-]{0,127}$/;
11
+ async function readBoundedFile(file, limit) {
12
+ const stat = await lstat(file);
13
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > limit)
14
+ throw new Error('Invalid Node capability resource file');
15
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
16
+ try {
17
+ const opened = await handle.stat();
18
+ if (!opened.isFile() || opened.size > limit)
19
+ throw new Error('Invalid Node capability resource file');
20
+ const bytes = Buffer.alloc(limit + 1);
21
+ let length = 0;
22
+ while (length < bytes.byteLength) {
23
+ const read = await handle.read(bytes, length, bytes.byteLength - length, null);
24
+ if (read.bytesRead === 0)
25
+ break;
26
+ length += read.bytesRead;
27
+ }
28
+ if (length > limit)
29
+ throw new Error('Node capability resource exceeds its declared size');
30
+ return bytes.subarray(0, length);
31
+ }
32
+ finally {
33
+ await handle.close();
34
+ }
35
+ }
36
+ /** Locally installed, verified module bytes execute only in the Node host. */
37
+ export class NodeCapabilityRegistry {
38
+ directory;
39
+ active;
40
+ queue = Promise.resolve();
41
+ host;
42
+ hooks;
43
+ constructor(host, directory = join(DAEMON_HOME, 'capabilities'), options = {}) {
44
+ if (options.hooks && (options.hooks.length > 256 || options.hooks.some(name => !handlerName.test(name))))
45
+ throw new Error('Invalid Node hook selection');
46
+ this.hooks = options.hooks ? new Set(options.hooks) : undefined;
47
+ this.directory = directory;
48
+ this.host = Object.freeze({ ...host });
49
+ }
50
+ get revision() { return this.active?.snapshot.revision; }
51
+ get installationRevision() { return this.active?.snapshot.installationRevision; }
52
+ get(name) { return this.active && Object.hasOwn(this.active.handlers, name) ? this.active.handlers[name] : undefined; }
53
+ require(name) {
54
+ const handler = this.get(name);
55
+ if (!handler)
56
+ throw new Error(`Required capability is not installed: ${name}. Enable the preset that provides it.`);
57
+ return handler;
58
+ }
59
+ refresh() {
60
+ const result = this.queue.catch(() => { }).then(async () => {
61
+ let selection;
62
+ try {
63
+ selection = await this.readSelection();
64
+ return await this.load(selection);
65
+ }
66
+ catch (error) {
67
+ // A cold host can keep the installer's previous verified selection usable.
68
+ if (!this.active)
69
+ await this.restorePrevious(selection).catch(() => { });
70
+ throw error;
71
+ }
72
+ });
73
+ this.queue = result;
74
+ return result;
75
+ }
76
+ async readSelection() {
77
+ const file = join(this.directory, 'active-node.json');
78
+ let bytes;
79
+ try {
80
+ bytes = await readBoundedFile(file, MAX_SELECTION_BYTES);
81
+ }
82
+ catch (error) {
83
+ if (error.code === 'ENOENT')
84
+ return undefined;
85
+ throw error;
86
+ }
87
+ return verifyNodeCapabilityActivation(JSON.parse(bytes.toString('utf8')));
88
+ }
89
+ async load(snapshot) {
90
+ if (!snapshot) {
91
+ this.active = undefined;
92
+ return undefined;
93
+ }
94
+ if (snapshot.revision === this.active?.snapshot.revision) {
95
+ this.active.snapshot = snapshot;
96
+ return snapshot.revision;
97
+ }
98
+ return this.prepareSelection(snapshot, async () => {
99
+ const current = await this.readSelection();
100
+ return current?.revision === snapshot.revision ? current : undefined;
101
+ });
102
+ }
103
+ async restorePrevious(failed) {
104
+ const pointer = join(this.directory, 'active-node.json');
105
+ const bytes = await readBoundedFile(pointer, MAX_SELECTION_BYTES);
106
+ const requested = JSON.parse(bytes.toString('utf8'));
107
+ const current = await verifyNodeCapabilityActivation(requested).catch(() => undefined);
108
+ if (current && (current.revision !== failed?.revision || current.installationRevision !== failed?.installationRevision)) {
109
+ try {
110
+ await this.load(current);
111
+ return;
112
+ }
113
+ catch { /* A newer candidate can also require its verified rollback selection. */ }
114
+ }
115
+ if (typeof requested.installationRevision !== 'string' || !/^[a-f0-9]{64}$/.test(requested.installationRevision))
116
+ return;
117
+ const record = JSON.parse((await readBoundedFile(join(this.directory, 'rollback.json'), MAX_SELECTION_BYTES + 256)).toString('utf8'));
118
+ if (record.candidate !== requested.installationRevision || !record.previous)
119
+ return;
120
+ const previous = await verifyNodeCapabilityActivation(record.previous);
121
+ const expected = createHash('sha256').update(bytes).digest('hex');
122
+ await this.prepareSelection(previous, async () => {
123
+ const current = await readBoundedFile(pointer, MAX_SELECTION_BYTES);
124
+ return createHash('sha256').update(current).digest('hex') === expected ? previous : undefined;
125
+ });
126
+ }
127
+ async prepareSelection(snapshot, guard) {
128
+ const bindings = Object.entries(snapshot.bindings).filter(([name]) => !this.hooks || this.hooks.has(name));
129
+ const selected = new Set(bindings.map(([, binding]) => binding.module));
130
+ const entries = Object.entries(snapshot.modules).filter(([id]) => !this.hooks || selected.has(id));
131
+ const resources = new Map();
132
+ for (const [id, resource] of entries) {
133
+ const file = join(this.directory, 'objects', `${resource.sha256}.cjs`);
134
+ const bytes = await readBoundedFile(file, resource.byteLength);
135
+ if (bytes.byteLength !== resource.byteLength || createHash('sha256').update(bytes).digest('hex') !== resource.sha256)
136
+ throw new Error(`Node capability integrity check failed: ${id}`);
137
+ resources.set(id, bytes);
138
+ }
139
+ const modules = new Map();
140
+ for (const [id, resource] of entries) {
141
+ const bytes = resources.get(id);
142
+ // CommonJS wrappers can be reclaimed after their active and in-flight handlers are released.
143
+ const module = { exports: {} };
144
+ const execute = new Script(`(function(module,exports,require){\n${bytes.toString('utf8')}\n})`, { filename: `mearl-capability-${resource.sha256}.cjs` }).runInThisContext();
145
+ execute(module, module.exports, createRequire(import.meta.url));
146
+ const factory = typeof module.exports === 'function' ? module.exports : module.exports?.default;
147
+ const loaded = { default: factory };
148
+ if (typeof loaded.default !== 'function')
149
+ throw new Error(`Node capability ${id} requires a default factory`);
150
+ const handlers = await loaded.default(this.host, structuredClone(resource.config ?? {}));
151
+ if (!handlers || typeof handlers !== 'object' || Array.isArray(handlers) || Object.keys(handlers).length > 256 || Object.entries(handlers).some(([name, handler]) => !handlerName.test(name) || typeof handler !== 'function'))
152
+ throw new Error(`Invalid Node capability handlers: ${id}`);
153
+ modules.set(id, handlers);
154
+ }
155
+ const handlers = {};
156
+ for (const [name, binding] of bindings) {
157
+ const module = modules.get(binding.module);
158
+ const handler = Object.hasOwn(module, binding.handler) ? module[binding.handler] : undefined;
159
+ if (typeof handler !== 'function')
160
+ throw new Error(`Node capability handler is missing: ${name}`);
161
+ handlers[name] = handler;
162
+ }
163
+ const current = await guard();
164
+ if (!current)
165
+ throw new Error('Node capability selection changed while preparing modules');
166
+ this.active = { snapshot: current, handlers: Object.freeze(handlers) };
167
+ return snapshot.revision;
168
+ }
169
+ }
@@ -5,6 +5,8 @@ export interface DaemonRecord {
5
5
  [key: string]: unknown;
6
6
  }
7
7
  export declare function ensureDir(dir: string): void;
8
+ /** Serialize record ownership changes across processes sharing the registry. */
9
+ export declare function withRecordLock<T>(file: string, operation: () => T): T;
8
10
  /**
9
11
  * Atomically write a record: serialise to a temp file then rename over the
10
12
  * target, so a concurrent reader never observes a half-written file. Temp file
package/dist/registry.js CHANGED
@@ -69,7 +69,7 @@ function removeStaleLock(lockDir) {
69
69
  }
70
70
  }
71
71
  /** Serialize record ownership changes across processes sharing the registry. */
72
- function withRecordLock(file, operation) {
72
+ export function withRecordLock(file, operation) {
73
73
  ensureDir(dirname(file));
74
74
  const lockDir = `${file}.registry.lock`;
75
75
  const ownerFile = join(lockDir, 'owner.json');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mearl/daemon-core",
3
- "version": "2.21.0",
3
+ "version": "3.0.0-beta.0",
4
4
  "description": "Shared Node daemon lifecycle primitives for Mearl — process liveness, JSON record registry, log rotation, and a detached daemon manager",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -9,6 +9,10 @@
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
+ },
13
+ "./capabilities": {
14
+ "types": "./dist/node-capabilities.d.ts",
15
+ "import": "./dist/node-capabilities.js"
12
16
  }
13
17
  },
14
18
  "files": [
@@ -19,7 +23,7 @@
19
23
  "mearl",
20
24
  "daemon"
21
25
  ],
22
- "license": "ISC",
26
+ "license": "Apache-2.0",
23
27
  "engines": {
24
28
  "node": ">=22.12.0"
25
29
  },
@@ -30,6 +34,9 @@
30
34
  "@types/node": "^24.9.1",
31
35
  "typescript": "^5.8.3"
32
36
  },
37
+ "dependencies": {
38
+ "@mearl/preset": "3.0.0-beta.0"
39
+ },
33
40
  "scripts": {
34
41
  "build": "rm -rf dist/ && tsc",
35
42
  "dev": "tsc --watch",