@adhdev/session-host-core 1.0.82-rc.3 → 1.0.82-rc.30
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/dist/index.d.mts +104 -3
- package/dist/index.d.ts +104 -3
- package/dist/index.js +347 -42
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +338 -42
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/cli-child-priority.ts +81 -0
- package/src/index.ts +9 -0
- package/src/ipc.ts +241 -31
- package/src/process/hidden-spawn.ts +10 -0
- package/src/spawn-env.ts +11 -0
- package/src/types.ts +26 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import * as os from 'node:os';
|
|
2
|
+
import { hiddenSpawn } from './process/hidden-spawn.js';
|
|
3
|
+
|
|
4
|
+
/** Relative POSIX niceness adjustment for newly spawned agent workloads. */
|
|
5
|
+
export const CLI_CHILD_NICE_INCREMENT = 10;
|
|
6
|
+
/** Set to "0" in the daemon environment (or launch env) to disable lowering. */
|
|
7
|
+
export const CLI_CHILD_NICE_ENV = 'ADHDEV_CLI_CHILD_NICE';
|
|
8
|
+
/** Optional Darwin CPU + I/O background policy, in addition to baseline nice. */
|
|
9
|
+
export const CLI_CHILD_SCHEDULING_ENV = 'ADHDEV_CLI_CHILD_SCHEDULING';
|
|
10
|
+
|
|
11
|
+
function setDarwinBackground(pid: number, onFailure: (error: unknown) => void): void {
|
|
12
|
+
// A short control helper stays normal priority. Do not block the IPC owner.
|
|
13
|
+
const task = hiddenSpawn('/usr/sbin/taskpolicy', ['-b', '-p', String(pid)], { stdio: 'ignore' });
|
|
14
|
+
task.once('error', onFailure);
|
|
15
|
+
task.once('exit', (code, signal) => {
|
|
16
|
+
if (code !== 0) onFailure(new Error(`taskpolicy exited with ${signal ?? code}`));
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface PriorityDependencies {
|
|
21
|
+
platform: NodeJS.Platform;
|
|
22
|
+
getPriority: typeof os.getPriority;
|
|
23
|
+
setPriority: typeof os.setPriority;
|
|
24
|
+
setDarwinBackground?: typeof setDarwinBackground;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Separate policy instances are useful for platform/error tests. */
|
|
28
|
+
export function createCliChildPriorityPolicy(deps: PriorityDependencies = {
|
|
29
|
+
platform: process.platform,
|
|
30
|
+
getPriority: os.getPriority,
|
|
31
|
+
setPriority: os.setPriority,
|
|
32
|
+
setDarwinBackground,
|
|
33
|
+
}) {
|
|
34
|
+
let failureLogged = false;
|
|
35
|
+
return function spawnCliChild<T extends { readonly pid?: number }>(
|
|
36
|
+
spawnChild: () => T,
|
|
37
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
38
|
+
logInfo: (message: string) => void = console.info,
|
|
39
|
+
): T {
|
|
40
|
+
const child = spawnChild();
|
|
41
|
+
const pid = child.pid;
|
|
42
|
+
// Never pass 0/undefined to setPriority: that would lower the IPC owner!
|
|
43
|
+
if (env[CLI_CHILD_NICE_ENV] === '0' || typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return child;
|
|
44
|
+
const onFailure = (error: unknown) => {
|
|
45
|
+
if (!failureLogged) {
|
|
46
|
+
failureLogged = true;
|
|
47
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
48
|
+
logInfo(`[cli-child-priority] Could not apply CLI child scheduling (pid ${pid}); continuing: ${detail}`);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
try {
|
|
52
|
+
const priority = deps.platform === 'win32'
|
|
53
|
+
? os.constants.priority.PRIORITY_BELOW_NORMAL
|
|
54
|
+
: Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
|
|
55
|
+
deps.setPriority(pid, priority);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
// EACCES/EPERM (policy/permissions) and ESRCH (already exited), as well
|
|
58
|
+
// as unexpected OS errors, are best effort. Never fail a CLI launch.
|
|
59
|
+
onFailure(error);
|
|
60
|
+
}
|
|
61
|
+
if (deps.platform === 'darwin' && env[CLI_CHILD_SCHEDULING_ENV] === 'darwin-bg') {
|
|
62
|
+
try { deps.setDarwinBackground?.(pid, onFailure); } catch (error) { onFailure(error); }
|
|
63
|
+
}
|
|
64
|
+
return child;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Only wrap agent workload spawns. Keep daemon, session-host IPC, P2P signal
|
|
70
|
+
* workers, version probes and git helpers at their existing priority.
|
|
71
|
+
*
|
|
72
|
+
* node-pty has no pre-spawn priority hook. Apply immediately on return, before
|
|
73
|
+
* registering listeners/doing other work. There is a spawn-to-setPriority race:
|
|
74
|
+
* a child can run (and fork) before this call. Later descendants inherit nice
|
|
75
|
+
* on POSIX; early descendants are not retroactively changed. Windows creation
|
|
76
|
+
* and ConPTY inheritance require verification on the DesktopA.
|
|
77
|
+
* Optional darwin-bg is applied asynchronously by taskpolicy after nice; the
|
|
78
|
+
* extra helper startup adds a further race before the background class takes
|
|
79
|
+
* effect. It also throttles I/O, so nice alone remains the default.
|
|
80
|
+
*/
|
|
81
|
+
export const spawnCliChild = createCliChildPriorityPolicy();
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
export type {
|
|
2
|
+
MeshWriterAssignment,
|
|
3
|
+
MeshWriterStopTarget,
|
|
4
|
+
StopMeshWriterPayload,
|
|
5
|
+
HostUpgradeLeasePayload,
|
|
2
6
|
AcquireWritePayload,
|
|
3
7
|
AttachSessionPayload,
|
|
4
8
|
ClearSessionBufferPayload,
|
|
@@ -49,6 +53,8 @@ export type {
|
|
|
49
53
|
|
|
50
54
|
export { SESSION_HOST_SUPPORTED_REQUEST_TYPES } from './types.js';
|
|
51
55
|
export { classifyTermination } from './termination.js';
|
|
56
|
+
export { CLI_CHILD_NICE_INCREMENT, CLI_CHILD_NICE_ENV, CLI_CHILD_SCHEDULING_ENV, createCliChildPriorityPolicy, spawnCliChild } from './cli-child-priority.js';
|
|
57
|
+
export { hiddenSpawn as hiddenSpawnProcess } from './process/hidden-spawn.js';
|
|
52
58
|
|
|
53
59
|
export { DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, SessionRingBuffer } from './buffer.js';
|
|
54
60
|
export type { SessionRingBufferOptions } from './buffer.js';
|
|
@@ -73,6 +79,8 @@ export {
|
|
|
73
79
|
SessionHostClient,
|
|
74
80
|
createLineParser,
|
|
75
81
|
createResponseEnvelope,
|
|
82
|
+
disconnectSessionHostClients,
|
|
83
|
+
findConnectedSessionHostClient,
|
|
76
84
|
getDefaultSessionHostEndpoint,
|
|
77
85
|
writeEnvelope,
|
|
78
86
|
} from './ipc.js';
|
|
@@ -98,6 +106,7 @@ export {
|
|
|
98
106
|
} from './defaults.js';
|
|
99
107
|
export {
|
|
100
108
|
sanitizeSpawnEnv,
|
|
109
|
+
replayLaunchEnv,
|
|
101
110
|
applyTerminalColorEnv,
|
|
102
111
|
ensureNodePtySpawnHelperPermissions,
|
|
103
112
|
} from './spawn-env.js';
|
package/src/ipc.ts
CHANGED
|
@@ -4,6 +4,7 @@ import * as net from 'net';
|
|
|
4
4
|
import { generateUUID } from './uuid.js';
|
|
5
5
|
import { StringDecoder } from 'string_decoder';
|
|
6
6
|
import type {
|
|
7
|
+
AttachSessionPayload,
|
|
7
8
|
SessionHostEvent,
|
|
8
9
|
SessionHostRequest,
|
|
9
10
|
SessionHostRequestEnvelope,
|
|
@@ -122,6 +123,9 @@ function createLineParser<TEnvelope = SessionHostWireEnvelope>(
|
|
|
122
123
|
export interface SessionHostClientOptions {
|
|
123
124
|
endpoint?: SessionHostEndpoint;
|
|
124
125
|
appName?: string;
|
|
126
|
+
requestTimeoutMs?: number;
|
|
127
|
+
/** Join the shared client registry (default true). Disable for short-lived probes. */
|
|
128
|
+
registerAsShared?: boolean;
|
|
125
129
|
}
|
|
126
130
|
|
|
127
131
|
/**
|
|
@@ -138,6 +142,34 @@ export type SessionHostDisconnectReason = 'error' | 'ended' | 'closed';
|
|
|
138
142
|
* (host not up yet) — only the former is a session-host death signal.
|
|
139
143
|
*/
|
|
140
144
|
const establishedSockets = new WeakSet<net.Socket>();
|
|
145
|
+
const activeClientRefs = new Set<WeakRef<SessionHostClient>>();
|
|
146
|
+
|
|
147
|
+
export function disconnectSessionHostClients(endpoint?: SessionHostEndpoint, error?: Error): void {
|
|
148
|
+
for (const ref of activeClientRefs) {
|
|
149
|
+
const client = ref.deref();
|
|
150
|
+
if (!client) {
|
|
151
|
+
activeClientRefs.delete(ref);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (!endpoint || client.endpoint.path === endpoint.path) {
|
|
155
|
+
client.disconnect(error);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function findConnectedSessionHostClient(endpoint?: SessionHostEndpoint): SessionHostClient | null {
|
|
161
|
+
for (const ref of activeClientRefs) {
|
|
162
|
+
const client = ref.deref();
|
|
163
|
+
if (!client) {
|
|
164
|
+
activeClientRefs.delete(ref);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
if ((!endpoint || client.endpoint.path === endpoint.path) && client.isConnected()) {
|
|
168
|
+
return client;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
141
173
|
|
|
142
174
|
export interface SessionHostDisconnectInfo {
|
|
143
175
|
reason: SessionHostDisconnectReason;
|
|
@@ -161,14 +193,34 @@ export class SessionHostClient {
|
|
|
161
193
|
readonly endpoint: SessionHostEndpoint;
|
|
162
194
|
|
|
163
195
|
private socket: net.Socket | null = null;
|
|
196
|
+
private connectPromise: Promise<void> | null = null;
|
|
197
|
+
private requestTimeoutMs = 30_000;
|
|
164
198
|
private requestWaiters = new Map<string, { resolve: (value: SessionHostResponse) => void; reject: (error: Error) => void }>();
|
|
165
199
|
private eventListeners = new Set<(event: SessionHostEvent) => void>();
|
|
166
200
|
private disconnectListeners = new Set<(info: SessionHostDisconnectInfo) => void>();
|
|
167
201
|
/** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
|
|
168
202
|
private disconnectedSockets = new WeakSet<net.Socket>();
|
|
203
|
+
/** Session subscriptions established via create_session/attach_session, replayed automatically on reconnect. */
|
|
204
|
+
private attachedSessions = new Map<string, AttachSessionPayload>();
|
|
169
205
|
|
|
170
206
|
constructor(options: SessionHostClientOptions = {}) {
|
|
171
207
|
this.endpoint = options.endpoint || getDefaultSessionHostEndpoint(options.appName || 'adhdev');
|
|
208
|
+
if (typeof options.requestTimeoutMs === 'number' && options.requestTimeoutMs > 0) {
|
|
209
|
+
this.requestTimeoutMs = options.requestTimeoutMs;
|
|
210
|
+
}
|
|
211
|
+
if (options.registerAsShared !== false) activeClientRefs.add(new WeakRef(this));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
static disconnectClients(endpoint?: SessionHostEndpoint, error?: Error): void {
|
|
215
|
+
disconnectSessionHostClients(endpoint, error);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
static findConnectedClient(endpoint?: SessionHostEndpoint): SessionHostClient | null {
|
|
219
|
+
return findConnectedSessionHostClient(endpoint);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
isConnected(): boolean {
|
|
223
|
+
return Boolean(this.socket && !this.socket.destroyed && establishedSockets.has(this.socket));
|
|
172
224
|
}
|
|
173
225
|
|
|
174
226
|
/**
|
|
@@ -228,6 +280,7 @@ export class SessionHostClient {
|
|
|
228
280
|
// guard at the top of connect().
|
|
229
281
|
if (this.socket === socket) {
|
|
230
282
|
this.socket = null;
|
|
283
|
+
this.connectPromise = null;
|
|
231
284
|
}
|
|
232
285
|
try { socket.destroy(); } catch { /* noop */ }
|
|
233
286
|
|
|
@@ -246,13 +299,64 @@ export class SessionHostClient {
|
|
|
246
299
|
}
|
|
247
300
|
}
|
|
248
301
|
|
|
249
|
-
|
|
250
|
-
|
|
302
|
+
private sendRawRequestOnSocket<T = unknown>(
|
|
303
|
+
socket: net.Socket,
|
|
304
|
+
request: SessionHostRequest,
|
|
305
|
+
timeoutMs = this.requestTimeoutMs,
|
|
306
|
+
): Promise<SessionHostResponse<T>> {
|
|
307
|
+
const requestId = generateUUID();
|
|
308
|
+
const envelope: SessionHostRequestEnvelope = {
|
|
309
|
+
kind: 'request',
|
|
310
|
+
requestId,
|
|
311
|
+
request,
|
|
312
|
+
};
|
|
313
|
+
const timeoutLabel = timeoutMs % 1000 === 0 ? `${timeoutMs / 1000}s` : `${timeoutMs}ms`;
|
|
314
|
+
const startedAt = Date.now();
|
|
315
|
+
const startedMonotonicAt = performance.now();
|
|
316
|
+
return new Promise<SessionHostResponse<T>>((resolve, reject) => {
|
|
317
|
+
const timeout = setTimeout(() => {
|
|
318
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - startedMonotonicAt));
|
|
319
|
+
const wallElapsedMs = Math.max(0, Date.now() - startedAt);
|
|
320
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
321
|
+
const timeoutError = Object.assign(
|
|
322
|
+
new Error(`Session host request timed out after ${timeoutLabel} (${request.type})`),
|
|
323
|
+
{
|
|
324
|
+
code: 'SESSION_HOST_REQUEST_TIMEOUT',
|
|
325
|
+
requestType: request.type,
|
|
326
|
+
scheduledTimeoutMs: timeoutMs,
|
|
327
|
+
actualElapsedMs,
|
|
328
|
+
wallElapsedMs,
|
|
329
|
+
observerLagMs,
|
|
330
|
+
},
|
|
331
|
+
);
|
|
332
|
+
if (this.socket === socket) {
|
|
333
|
+
this.disconnect(timeoutError);
|
|
334
|
+
} else {
|
|
335
|
+
this.requestWaiters.delete(requestId);
|
|
336
|
+
this.disconnectedSockets.add(socket);
|
|
337
|
+
try { socket.destroy(); } catch { /* noop */ }
|
|
338
|
+
reject(timeoutError);
|
|
339
|
+
}
|
|
340
|
+
}, timeoutMs);
|
|
341
|
+
this.requestWaiters.set(requestId, {
|
|
342
|
+
resolve: (value) => { clearTimeout(timeout); resolve(value as SessionHostResponse<T>); },
|
|
343
|
+
reject: (error) => { clearTimeout(timeout); reject(error); },
|
|
344
|
+
});
|
|
345
|
+
socket.write(serializeEnvelope(envelope));
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async connect(timeoutMs = this.requestTimeoutMs): Promise<void> {
|
|
350
|
+
if (this.socket && !this.socket.destroyed) {
|
|
351
|
+
if (this.connectPromise) await this.connectPromise;
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
251
354
|
// Cleanup stale socket reference left after error/disconnect
|
|
252
355
|
if (this.socket) {
|
|
253
356
|
try { this.socket.destroy(); } catch { /* noop */ }
|
|
254
357
|
this.socket = null;
|
|
255
358
|
}
|
|
359
|
+
this.connectPromise = null;
|
|
256
360
|
|
|
257
361
|
const socket = net.createConnection(this.endpoint.path);
|
|
258
362
|
this.socket = socket;
|
|
@@ -314,13 +418,62 @@ export class SessionHostClient {
|
|
|
314
418
|
this.handleDisconnect(socket, 'ended', undefined, flushParser().length);
|
|
315
419
|
});
|
|
316
420
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
421
|
+
const connectTask = (async () => {
|
|
422
|
+
await new Promise<void>((resolve, reject) => {
|
|
423
|
+
const cleanup = () => {
|
|
424
|
+
clearTimeout(timer);
|
|
425
|
+
socket.off('connect', connected);
|
|
426
|
+
socket.off('error', failed);
|
|
427
|
+
socket.off('close', closed);
|
|
428
|
+
};
|
|
429
|
+
const connected = () => { cleanup(); establishedSockets.add(socket); resolve(); };
|
|
430
|
+
const failed = (error: Error) => { cleanup(); reject(error); };
|
|
431
|
+
const closed = () => failed(new Error('Session host connection closed before connect'));
|
|
432
|
+
const connectStartedAt = Date.now();
|
|
433
|
+
const connectStartedMonotonicAt = performance.now();
|
|
434
|
+
const timer = setTimeout(() => {
|
|
435
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - connectStartedMonotonicAt));
|
|
436
|
+
const wallElapsedMs = Math.max(0, Date.now() - connectStartedAt);
|
|
437
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
438
|
+
const error = Object.assign(
|
|
439
|
+
new Error(`Session host connect timed out after ${timeoutMs}ms`),
|
|
440
|
+
{
|
|
441
|
+
code: 'SESSION_HOST_CONNECT_TIMEOUT',
|
|
442
|
+
scheduledTimeoutMs: timeoutMs,
|
|
443
|
+
actualElapsedMs,
|
|
444
|
+
wallElapsedMs,
|
|
445
|
+
observerLagMs,
|
|
446
|
+
},
|
|
447
|
+
);
|
|
448
|
+
failed(error);
|
|
449
|
+
if (this.socket === socket) this.disconnect(error);
|
|
450
|
+
}, timeoutMs);
|
|
451
|
+
socket.once('connect', connected);
|
|
452
|
+
socket.once('error', failed);
|
|
453
|
+
socket.once('close', closed);
|
|
321
454
|
});
|
|
322
|
-
socket.
|
|
323
|
-
|
|
455
|
+
if (this.attachedSessions.size > 0 && this.socket === socket && !socket.destroyed) {
|
|
456
|
+
for (const [sessionId, sub] of [...this.attachedSessions.entries()]) {
|
|
457
|
+
if (this.socket !== socket || socket.destroyed) break;
|
|
458
|
+
const replayResponse = await this.sendRawRequestOnSocket(socket, {
|
|
459
|
+
type: 'attach_session',
|
|
460
|
+
payload: sub,
|
|
461
|
+
}).catch(() => null);
|
|
462
|
+
if (replayResponse && !replayResponse.success) {
|
|
463
|
+
this.attachedSessions.delete(sessionId);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
})();
|
|
468
|
+
|
|
469
|
+
this.connectPromise = connectTask;
|
|
470
|
+
try {
|
|
471
|
+
await connectTask;
|
|
472
|
+
} finally {
|
|
473
|
+
if (this.connectPromise === connectTask) {
|
|
474
|
+
this.connectPromise = null;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
324
477
|
}
|
|
325
478
|
|
|
326
479
|
onEvent(listener: (event: SessionHostEvent) => void): () => void {
|
|
@@ -330,33 +483,90 @@ export class SessionHostClient {
|
|
|
330
483
|
};
|
|
331
484
|
}
|
|
332
485
|
|
|
333
|
-
async request<T = unknown>(request: SessionHostRequest): Promise<SessionHostResponse<T>> {
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
486
|
+
async request<T = unknown>(request: SessionHostRequest, options: { timeoutMs?: number } = {}): Promise<SessionHostResponse<T>> {
|
|
487
|
+
const timeoutMs = Math.max(1, options.timeoutMs ?? this.requestTimeoutMs);
|
|
488
|
+
const deadline = Date.now() + timeoutMs;
|
|
489
|
+
const alreadyConnected = this.isConnected() && !this.connectPromise;
|
|
490
|
+
// A probe must also bound a connect/re-attach already in flight on this
|
|
491
|
+
// client; that task may have started with the normal 30s timeout.
|
|
492
|
+
if (options.timeoutMs !== undefined) {
|
|
493
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
494
|
+
const raceStartedAt = Date.now();
|
|
495
|
+
const raceStartedMonotonicAt = performance.now();
|
|
496
|
+
try {
|
|
497
|
+
await Promise.race([
|
|
498
|
+
this.connect(timeoutMs),
|
|
499
|
+
new Promise<never>((_resolve, reject) => {
|
|
500
|
+
timer = setTimeout(() => {
|
|
501
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - raceStartedMonotonicAt));
|
|
502
|
+
const wallElapsedMs = Math.max(0, Date.now() - raceStartedAt);
|
|
503
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
504
|
+
const error = Object.assign(
|
|
505
|
+
new Error(`Session host connect timed out after ${timeoutMs}ms`),
|
|
506
|
+
{
|
|
507
|
+
code: 'SESSION_HOST_CONNECT_TIMEOUT',
|
|
508
|
+
scheduledTimeoutMs: timeoutMs,
|
|
509
|
+
actualElapsedMs,
|
|
510
|
+
wallElapsedMs,
|
|
511
|
+
observerLagMs,
|
|
512
|
+
},
|
|
513
|
+
);
|
|
514
|
+
reject(error);
|
|
515
|
+
this.disconnect(error);
|
|
516
|
+
}, timeoutMs);
|
|
517
|
+
}),
|
|
518
|
+
]);
|
|
519
|
+
} finally { if (timer) clearTimeout(timer); }
|
|
520
|
+
} else {
|
|
521
|
+
await this.connect(timeoutMs);
|
|
522
|
+
}
|
|
523
|
+
const requestSocket = this.socket;
|
|
524
|
+
if (!requestSocket) throw new Error('Session host socket unavailable');
|
|
525
|
+
|
|
526
|
+
const response = await this.sendRawRequestOnSocket<T>(requestSocket, request, options.timeoutMs === undefined || alreadyConnected ? timeoutMs : Math.max(1, deadline - Date.now()));
|
|
527
|
+
if (response.success) {
|
|
528
|
+
if (request.type === 'attach_session') {
|
|
529
|
+
this.attachedSessions.set(request.payload.sessionId, {
|
|
530
|
+
sessionId: request.payload.sessionId,
|
|
531
|
+
clientId: request.payload.clientId,
|
|
532
|
+
clientType: request.payload.clientType,
|
|
533
|
+
readOnly: request.payload.readOnly === true,
|
|
534
|
+
});
|
|
535
|
+
} else if (request.type === 'create_session') {
|
|
536
|
+
const createdId = (response.result as { sessionId?: string } | undefined)?.sessionId || request.payload.sessionId;
|
|
537
|
+
const clientId = typeof request.payload.clientId === 'string' ? request.payload.clientId.trim() : '';
|
|
538
|
+
if (createdId && clientId) {
|
|
539
|
+
this.attachedSessions.set(createdId, {
|
|
540
|
+
sessionId: createdId,
|
|
541
|
+
clientId,
|
|
542
|
+
clientType: request.payload.clientType || 'daemon',
|
|
543
|
+
readOnly: false,
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
} else if (request.type === 'detach_session' || request.type === 'delete_session') {
|
|
547
|
+
this.attachedSessions.delete(request.payload.sessionId);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return response;
|
|
551
|
+
}
|
|
355
552
|
|
|
356
|
-
|
|
553
|
+
disconnect(error?: Error): void {
|
|
554
|
+
const socket = this.socket;
|
|
555
|
+
if (socket) {
|
|
556
|
+
this.handleDisconnect(socket, error ? 'error' : 'closed', error, 0);
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
this.connectPromise = null;
|
|
560
|
+
const failure = error || new Error(`Session host client disconnected (${this.endpoint.path})`);
|
|
561
|
+
for (const waiter of this.requestWaiters.values()) {
|
|
562
|
+
waiter.reject(failure);
|
|
563
|
+
}
|
|
564
|
+
this.requestWaiters.clear();
|
|
357
565
|
}
|
|
358
566
|
|
|
359
567
|
async close(): Promise<void> {
|
|
568
|
+
this.attachedSessions.clear();
|
|
569
|
+
this.connectPromise = null;
|
|
360
570
|
if (!this.socket) return;
|
|
361
571
|
const socket = this.socket;
|
|
362
572
|
this.socket = null;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { spawn, type SpawnOptions, type ChildProcess } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/** Shared hidden-window primitive for daemon and session-host process helpers. */
|
|
4
|
+
export function hiddenSpawn(
|
|
5
|
+
command: string,
|
|
6
|
+
args: readonly string[] = [],
|
|
7
|
+
options: SpawnOptions = {},
|
|
8
|
+
): ChildProcess {
|
|
9
|
+
return spawn(command, args as string[], { windowsHide: true, ...options });
|
|
10
|
+
}
|
package/src/spawn-env.ts
CHANGED
|
@@ -117,6 +117,17 @@ export function sanitizeSpawnEnv(
|
|
|
117
117
|
return env;
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
/** Recover only role bindings from legacy full-environment snapshots.
|
|
121
|
+
* New records distinguish explicit overrides, including intentional custom keys. */
|
|
122
|
+
export function replayLaunchEnv(command: { env?: Record<string, string>; envMode?: 'launch_overrides' }): Record<string, string> {
|
|
123
|
+
if (command.envMode === 'launch_overrides') return { ...command.env };
|
|
124
|
+
const roleKeys = new Set(['HOME', 'USERPROFILE', 'XDG_CONFIG_HOME', 'CLAUDE_CONFIG_DIR',
|
|
125
|
+
'CODEX_HOME', 'KIMI_CODE_HOME', 'GEMINI_CLI_HOME', 'OPENCODE_CONFIG', 'OPENCODE_CONFIG_CONTENT',
|
|
126
|
+
'CLAUDE_CODE_DISABLE_AUTO_MEMORY', 'TERMINAL_CWD', 'ADHDEV_INLINE_MESH',
|
|
127
|
+
'ADHDEV_ASSISTANT_SESSION_ID', 'ADHDEV_COORDINATOR_SESSION_ID', 'ADHDEV_CONFIG_DIR']);
|
|
128
|
+
return Object.fromEntries(Object.entries(command.env ?? {}).filter(([key]) => roleKeys.has(key)));
|
|
129
|
+
}
|
|
130
|
+
|
|
120
131
|
/**
|
|
121
132
|
* Apply preferred terminal colour environment variables.
|
|
122
133
|
* Ensures TERM is set to xterm-256color and enables colour on Windows.
|
package/src/types.ts
CHANGED
|
@@ -12,6 +12,8 @@ export interface SessionLaunchCommand {
|
|
|
12
12
|
command: string;
|
|
13
13
|
args: string[];
|
|
14
14
|
env?: Record<string, string>;
|
|
15
|
+
/** Unmarked older daemon records contained the full inherited environment. */
|
|
16
|
+
envMode?: 'launch_overrides';
|
|
15
17
|
}
|
|
16
18
|
|
|
17
19
|
export interface SessionWriteOwner {
|
|
@@ -155,6 +157,15 @@ export interface ResizeSessionPayload {
|
|
|
155
157
|
export interface StopSessionPayload {
|
|
156
158
|
sessionId: string;
|
|
157
159
|
}
|
|
160
|
+
export interface MeshWriterAssignment {
|
|
161
|
+
meshId: string; nodeId: string; taskId: string; attemptId: string;
|
|
162
|
+
generation: number; dispatchNonce: number; ownerDaemonId: string;
|
|
163
|
+
}
|
|
164
|
+
export interface MeshWriterStopTarget {
|
|
165
|
+
runtimeKey: string; startedAt: number; osPid: number; providerType: string;
|
|
166
|
+
assignment: MeshWriterAssignment;
|
|
167
|
+
}
|
|
168
|
+
export interface StopMeshWriterPayload extends MeshWriterStopTarget { sessionId: string; clientId: string }
|
|
158
169
|
|
|
159
170
|
export interface DeleteSessionPayload {
|
|
160
171
|
sessionId: string;
|
|
@@ -298,13 +309,24 @@ export interface SessionHostDiagnostics {
|
|
|
298
309
|
recentTransitions: SessionHostRuntimeTransition[];
|
|
299
310
|
}
|
|
300
311
|
|
|
312
|
+
export interface HostUpgradeLeasePayload {
|
|
313
|
+
bootId: string;
|
|
314
|
+
epoch: number;
|
|
315
|
+
owner: string;
|
|
316
|
+
token: string;
|
|
317
|
+
}
|
|
318
|
+
|
|
301
319
|
export type SessionHostRequest =
|
|
320
|
+
| { type: 'get_upgrade_lease'; payload?: {} }
|
|
321
|
+
| { type: 'acquire_upgrade_lease'; payload: HostUpgradeLeasePayload }
|
|
322
|
+
| { type: 'release_upgrade_lease'; payload: HostUpgradeLeasePayload }
|
|
302
323
|
| { type: 'create_session'; payload: CreateSessionPayload }
|
|
303
324
|
| { type: 'attach_session'; payload: AttachSessionPayload }
|
|
304
325
|
| { type: 'detach_session'; payload: DetachSessionPayload }
|
|
305
326
|
| { type: 'send_input'; payload: SendInputPayload }
|
|
306
327
|
| { type: 'resize_session'; payload: ResizeSessionPayload }
|
|
307
328
|
| { type: 'stop_session'; payload: StopSessionPayload }
|
|
329
|
+
| { type: 'stop_mesh_writer'; payload: StopMeshWriterPayload }
|
|
308
330
|
| { type: 'delete_session'; payload: DeleteSessionPayload }
|
|
309
331
|
| { type: 'resume_session'; payload: ResumeSessionPayload }
|
|
310
332
|
| { type: 'acquire_write'; payload: AcquireWritePayload }
|
|
@@ -323,12 +345,16 @@ export type SessionHostRequest =
|
|
|
323
345
|
export type SessionHostRequestType = SessionHostRequest['type'];
|
|
324
346
|
|
|
325
347
|
export const SESSION_HOST_SUPPORTED_REQUEST_TYPES: readonly SessionHostRequestType[] = [
|
|
348
|
+
'get_upgrade_lease',
|
|
349
|
+
'acquire_upgrade_lease',
|
|
350
|
+
'release_upgrade_lease',
|
|
326
351
|
'create_session',
|
|
327
352
|
'attach_session',
|
|
328
353
|
'detach_session',
|
|
329
354
|
'send_input',
|
|
330
355
|
'resize_session',
|
|
331
356
|
'stop_session',
|
|
357
|
+
'stop_mesh_writer',
|
|
332
358
|
'delete_session',
|
|
333
359
|
'resume_session',
|
|
334
360
|
'acquire_write',
|