@adhdev/daemon-core 0.9.82-rc.447 → 0.9.82-rc.448

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.
@@ -0,0 +1,64 @@
1
+ import { type SessionHostEndpoint, type SessionHostRequestType } from '@adhdev/session-host-core';
2
+ /**
3
+ * Shared managed-session-host process helpers.
4
+ *
5
+ * The cloud (`packages/daemon-cloud`) and standalone (`oss/packages/daemon-standalone`)
6
+ * daemons carried byte-for-byte copies of `buildSessionHostEnv`, `resolveSessionHostEntry`,
7
+ * `getSessionHostPidFile`, `killPid`, a base `stopManagedSessionHostProcess`, and the
8
+ * `ensureSessionHostReady` retry-wrapper. Those live here now. The pieces that genuinely
9
+ * differ between the two daemons (kill windowsHide, quarantine preamble, spawn stdio,
10
+ * required request types, cloud's socket-owner sweep) are injected via options so the
11
+ * observable behavior of each daemon is preserved exactly.
12
+ */
13
+ export interface ManagedSessionHostOptions {
14
+ /** Session-host namespace (app name). Drives the socket endpoint and pidfile path. */
15
+ appName: string;
16
+ /** Capability probe: request types the host must advertise before it's considered ready. */
17
+ requiredRequestTypes: readonly SessionHostRequestType[];
18
+ /** Ready timeout for the spawn/poll loop. Defaults to the shared runtime default. */
19
+ timeoutMs?: number;
20
+ /**
21
+ * `killPid` on win32 uses `taskkill /T /F`. Cloud passes `windowsHide: true`; standalone
22
+ * historically did not. Kept as a flag to preserve each daemon's exact spawn options.
23
+ */
24
+ killWindowsHide?: boolean;
25
+ /**
26
+ * How the detached host child's stdio is wired. 'ignore' matches standalone; 'logfile'
27
+ * matches cloud (append to `~/.adhdev/logs/session-host.log`).
28
+ */
29
+ spawnStdio?: 'ignore' | 'logfile';
30
+ /**
31
+ * Optional preamble run at the start of `ensureReady` (before the first connect probe).
32
+ * Cloud uses this to quarantine legacy standalone runtime files.
33
+ */
34
+ beforeEnsureReady?: () => void;
35
+ /**
36
+ * Optional extra stop pass appended to `stopManagedSessionHostProcess`. Cloud sweeps
37
+ * managed session-host processes that own the default socket but predate pidfile tracking.
38
+ * Returns true if it stopped anything.
39
+ */
40
+ extraStop?: (endpoint: SessionHostEndpoint) => boolean;
41
+ /**
42
+ * Optional guard applied to a pidfile-tracked pid before killing it in
43
+ * `stopManagedSessionHostProcess`. Cloud verifies the command line is an ADHDev
44
+ * session-host daemon; standalone kills unconditionally (returns true here).
45
+ */
46
+ isManagedPid?: (pid: number) => boolean;
47
+ }
48
+ export interface ManagedSessionHost {
49
+ readonly appName: string;
50
+ readonly endpoint: SessionHostEndpoint;
51
+ getPidFile(): string;
52
+ getPid(): number | null;
53
+ buildEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
54
+ resolveEntry(): string;
55
+ killPid(pid: number): boolean;
56
+ spawnHost(): void;
57
+ stopManagedSessionHostProcess(): boolean;
58
+ ensureReady(): Promise<SessionHostEndpoint>;
59
+ getStatusPaths(): {
60
+ pidFile: string;
61
+ endpoint: SessionHostEndpoint;
62
+ };
63
+ }
64
+ export declare function createManagedSessionHost(options: ManagedSessionHostOptions): ManagedSessionHost;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adhdev/daemon-core",
3
- "version": "0.9.82-rc.447",
3
+ "version": "0.9.82-rc.448",
4
4
  "description": "ADHDev daemon core — CDP, IDE detection, providers, command execution",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -46,7 +46,7 @@
46
46
  "author": "vilmire",
47
47
  "license": "AGPL-3.0-or-later",
48
48
  "dependencies": {
49
- "@adhdev/mesh-shared": "0.9.82-rc.447",
49
+ "@adhdev/mesh-shared": "0.9.82-rc.448",
50
50
  "@adhdev/session-host-core": "*",
51
51
  "@agentclientprotocol/sdk": "^0.16.1",
52
52
  "ajv": "^8.20.0",
package/src/index.ts CHANGED
@@ -534,6 +534,8 @@ export {
534
534
  } from './session-host/app-name.js';
535
535
  export type { SessionHostAppNameResolution } from './session-host/app-name.js';
536
536
  export { ensureSessionHostReady, listHostedCliRuntimes } from './session-host/runtime-support.js';
537
+ export { createManagedSessionHost } from './session-host/managed-host.js';
538
+ export type { ManagedSessionHost, ManagedSessionHostOptions } from './session-host/managed-host.js';
537
539
  export {
538
540
  getSessionHostRecoveryLabel,
539
541
  getSessionHostSurfaceKind,
@@ -0,0 +1,218 @@
1
+ import { execFileSync, spawn, type StdioOptions } from 'child_process';
2
+ import * as fs from 'fs';
3
+ import * as os from 'os';
4
+ import * as path from 'path';
5
+ import {
6
+ getDefaultSessionHostEndpoint,
7
+ sanitizeSpawnEnv,
8
+ type SessionHostEndpoint,
9
+ type SessionHostRequestType,
10
+ } from '@adhdev/session-host-core';
11
+ import { ensureSessionHostReady as ensureSharedSessionHostReady } from './runtime-support.js';
12
+ import { DEFAULT_SESSION_HOST_READY_TIMEOUT_MS } from '../runtime-defaults.js';
13
+
14
+ /**
15
+ * Shared managed-session-host process helpers.
16
+ *
17
+ * The cloud (`packages/daemon-cloud`) and standalone (`oss/packages/daemon-standalone`)
18
+ * daemons carried byte-for-byte copies of `buildSessionHostEnv`, `resolveSessionHostEntry`,
19
+ * `getSessionHostPidFile`, `killPid`, a base `stopManagedSessionHostProcess`, and the
20
+ * `ensureSessionHostReady` retry-wrapper. Those live here now. The pieces that genuinely
21
+ * differ between the two daemons (kill windowsHide, quarantine preamble, spawn stdio,
22
+ * required request types, cloud's socket-owner sweep) are injected via options so the
23
+ * observable behavior of each daemon is preserved exactly.
24
+ */
25
+ export interface ManagedSessionHostOptions {
26
+ /** Session-host namespace (app name). Drives the socket endpoint and pidfile path. */
27
+ appName: string;
28
+ /** Capability probe: request types the host must advertise before it's considered ready. */
29
+ requiredRequestTypes: readonly SessionHostRequestType[];
30
+ /** Ready timeout for the spawn/poll loop. Defaults to the shared runtime default. */
31
+ timeoutMs?: number;
32
+ /**
33
+ * `killPid` on win32 uses `taskkill /T /F`. Cloud passes `windowsHide: true`; standalone
34
+ * historically did not. Kept as a flag to preserve each daemon's exact spawn options.
35
+ */
36
+ killWindowsHide?: boolean;
37
+ /**
38
+ * How the detached host child's stdio is wired. 'ignore' matches standalone; 'logfile'
39
+ * matches cloud (append to `~/.adhdev/logs/session-host.log`).
40
+ */
41
+ spawnStdio?: 'ignore' | 'logfile';
42
+ /**
43
+ * Optional preamble run at the start of `ensureReady` (before the first connect probe).
44
+ * Cloud uses this to quarantine legacy standalone runtime files.
45
+ */
46
+ beforeEnsureReady?: () => void;
47
+ /**
48
+ * Optional extra stop pass appended to `stopManagedSessionHostProcess`. Cloud sweeps
49
+ * managed session-host processes that own the default socket but predate pidfile tracking.
50
+ * Returns true if it stopped anything.
51
+ */
52
+ extraStop?: (endpoint: SessionHostEndpoint) => boolean;
53
+ /**
54
+ * Optional guard applied to a pidfile-tracked pid before killing it in
55
+ * `stopManagedSessionHostProcess`. Cloud verifies the command line is an ADHDev
56
+ * session-host daemon; standalone kills unconditionally (returns true here).
57
+ */
58
+ isManagedPid?: (pid: number) => boolean;
59
+ }
60
+
61
+ export interface ManagedSessionHost {
62
+ readonly appName: string;
63
+ readonly endpoint: SessionHostEndpoint;
64
+ getPidFile(): string;
65
+ getPid(): number | null;
66
+ buildEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
67
+ resolveEntry(): string;
68
+ killPid(pid: number): boolean;
69
+ spawnHost(): void;
70
+ stopManagedSessionHostProcess(): boolean;
71
+ ensureReady(): Promise<SessionHostEndpoint>;
72
+ getStatusPaths(): { pidFile: string; endpoint: SessionHostEndpoint };
73
+ }
74
+
75
+ export function createManagedSessionHost(options: ManagedSessionHostOptions): ManagedSessionHost {
76
+ const appName = options.appName;
77
+ const timeoutMs = options.timeoutMs ?? DEFAULT_SESSION_HOST_READY_TIMEOUT_MS;
78
+ const endpoint = getDefaultSessionHostEndpoint(appName);
79
+ const isManagedPid = options.isManagedPid ?? (() => true);
80
+
81
+ function buildEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
82
+ const env = sanitizeSpawnEnv(baseEnv) as NodeJS.ProcessEnv;
83
+ env.ADHDEV_SESSION_HOST_NAME = appName;
84
+ return env;
85
+ }
86
+
87
+ function resolveEntry(): string {
88
+ const packagedCandidates = [
89
+ path.resolve(__dirname, '../vendor/session-host-daemon/index.js'),
90
+ path.resolve(__dirname, '../../vendor/session-host-daemon/index.js'),
91
+ ];
92
+ for (const candidate of packagedCandidates) {
93
+ if (fs.existsSync(candidate)) {
94
+ return candidate;
95
+ }
96
+ }
97
+ return require.resolve('@adhdev/session-host-daemon');
98
+ }
99
+
100
+ function getPidFile(): string {
101
+ return path.join(os.homedir(), '.adhdev', `${appName}-session-host.pid`);
102
+ }
103
+
104
+ function getPid(): number | null {
105
+ try {
106
+ const pidFile = getPidFile();
107
+ if (!fs.existsSync(pidFile)) return null;
108
+ const pid = Number.parseInt(fs.readFileSync(pidFile, 'utf8').trim(), 10);
109
+ return Number.isFinite(pid) ? pid : null;
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ function killPid(pid: number): boolean {
116
+ try {
117
+ if (process.platform === 'win32') {
118
+ const spawnOpts: { stdio: 'ignore'; windowsHide?: boolean } = { stdio: 'ignore' };
119
+ if (options.killWindowsHide) spawnOpts.windowsHide = true;
120
+ execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], spawnOpts);
121
+ } else {
122
+ process.kill(pid, 'SIGTERM');
123
+ }
124
+ return true;
125
+ } catch {
126
+ return false;
127
+ }
128
+ }
129
+
130
+ function spawnHost(): void {
131
+ const entry = resolveEntry();
132
+ let stdio: StdioOptions = 'ignore';
133
+ let logFd: number | null = null;
134
+ if (options.spawnStdio === 'logfile') {
135
+ const logDir = path.join(os.homedir(), '.adhdev', 'logs');
136
+ fs.mkdirSync(logDir, { recursive: true });
137
+ logFd = fs.openSync(path.join(logDir, 'session-host.log'), 'a');
138
+ stdio = ['ignore', logFd, logFd];
139
+ }
140
+ const child = spawn(process.execPath, [entry], {
141
+ detached: true,
142
+ stdio,
143
+ windowsHide: true,
144
+ env: buildEnv(process.env),
145
+ });
146
+ child.unref();
147
+ if (logFd !== null) {
148
+ try { fs.closeSync(logFd); } catch { /* noop */ }
149
+ }
150
+ }
151
+
152
+ function stopManagedSessionHostProcess(): boolean {
153
+ let stopped = false;
154
+ const pidFile = getPidFile();
155
+ try {
156
+ if (fs.existsSync(pidFile)) {
157
+ const pid = Number.parseInt(fs.readFileSync(pidFile, 'utf8').trim(), 10);
158
+ if (Number.isFinite(pid) && pid !== process.pid && isManagedPid(pid)) {
159
+ stopped = killPid(pid) || stopped;
160
+ }
161
+ }
162
+ } catch {
163
+ // noop
164
+ } finally {
165
+ try {
166
+ fs.unlinkSync(pidFile);
167
+ } catch {
168
+ // noop
169
+ }
170
+ }
171
+
172
+ if (options.extraStop) {
173
+ stopped = options.extraStop(endpoint) || stopped;
174
+ }
175
+
176
+ return stopped;
177
+ }
178
+
179
+ async function ensureReady(): Promise<SessionHostEndpoint> {
180
+ options.beforeEnsureReady?.();
181
+ try {
182
+ return await ensureSharedSessionHostReady({
183
+ appName,
184
+ spawnHost,
185
+ timeoutMs,
186
+ requiredRequestTypes: options.requiredRequestTypes,
187
+ });
188
+ } catch (error) {
189
+ stopManagedSessionHostProcess();
190
+ return ensureSharedSessionHostReady({
191
+ appName,
192
+ spawnHost,
193
+ timeoutMs,
194
+ requiredRequestTypes: options.requiredRequestTypes,
195
+ }).catch((retryError) => {
196
+ const initialMessage = error instanceof Error ? error.message : String(error);
197
+ const retryMessage = retryError instanceof Error ? retryError.message : String(retryError);
198
+ throw new Error(`Session host failed to start after retry (${initialMessage}; retry: ${retryMessage})`);
199
+ });
200
+ }
201
+ }
202
+
203
+ return {
204
+ appName,
205
+ endpoint,
206
+ getPidFile,
207
+ getPid,
208
+ buildEnv,
209
+ resolveEntry,
210
+ killPid,
211
+ spawnHost,
212
+ stopManagedSessionHostProcess,
213
+ ensureReady,
214
+ getStatusPaths() {
215
+ return { pidFile: getPidFile(), endpoint };
216
+ },
217
+ };
218
+ }