@adhdev/session-host-core 1.0.82-rc.8 → 1.0.82-rc.80
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 +319 -4
- package/dist/index.d.ts +319 -4
- package/dist/index.js +596 -62
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +577 -62
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/cleanup-expected.ts +114 -0
- package/src/cli-child-priority.ts +117 -0
- package/src/control-plane.ts +58 -0
- package/src/index.ts +24 -0
- package/src/instance-key.ts +20 -1
- package/src/ipc.ts +289 -46
- package/src/process/hidden-spawn.ts +10 -0
- package/src/registry.ts +87 -0
- package/src/spawn-env.ts +11 -0
- package/src/types.ts +131 -1
package/src/ipc.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import * as os from 'os';
|
|
2
2
|
import * as path from 'path';
|
|
3
3
|
import * as net from 'net';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
4
5
|
import { generateUUID } from './uuid.js';
|
|
5
6
|
import { StringDecoder } from 'string_decoder';
|
|
6
7
|
import type {
|
|
8
|
+
AttachSessionPayload,
|
|
7
9
|
SessionHostEvent,
|
|
8
10
|
SessionHostRequest,
|
|
9
11
|
SessionHostRequestEnvelope,
|
|
@@ -17,6 +19,20 @@ export interface SessionHostEndpoint {
|
|
|
17
19
|
path: string;
|
|
18
20
|
}
|
|
19
21
|
|
|
22
|
+
/** Reserve the trailing NUL in sockaddr_un; named pipes have a separate namespace. */
|
|
23
|
+
export function validateSessionHostEndpoint(
|
|
24
|
+
endpoint: SessionHostEndpoint,
|
|
25
|
+
platform: NodeJS.Platform = process.platform,
|
|
26
|
+
): void {
|
|
27
|
+
if (endpoint.kind !== 'unix') return;
|
|
28
|
+
// Darwin/BSD use 104 bytes; Linux provides 108. Default conservatively elsewhere.
|
|
29
|
+
const limit = platform === 'linux' ? 108 : 104;
|
|
30
|
+
const pathBytes = Buffer.byteLength(endpoint.path, 'utf8');
|
|
31
|
+
if (pathBytes + 1 > limit) {
|
|
32
|
+
throw new Error(`session_host_unix_socket_path_too_long: path_bytes=${pathBytes} required_bytes=${pathBytes + 1} limit_bytes=${limit} platform=${platform}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
20
36
|
export interface SessionHostEndpointOptions {
|
|
21
37
|
/**
|
|
22
38
|
* Instance IPC namespace key (see instance-key.ts). '' / omitted yields the
|
|
@@ -26,6 +42,8 @@ export interface SessionHostEndpointOptions {
|
|
|
26
42
|
ipcKey?: string;
|
|
27
43
|
/** Test seam: override the platform the endpoint shape is derived for. */
|
|
28
44
|
platform?: NodeJS.Platform;
|
|
45
|
+
/** Test seam: override the temporary directory used for endpoint derivation. */
|
|
46
|
+
tmpDir?: string;
|
|
29
47
|
}
|
|
30
48
|
|
|
31
49
|
export function getDefaultSessionHostEndpoint(
|
|
@@ -47,10 +65,25 @@ export function getDefaultSessionHostEndpoint(
|
|
|
47
65
|
};
|
|
48
66
|
}
|
|
49
67
|
|
|
50
|
-
|
|
68
|
+
const endpoint: SessionHostEndpoint = {
|
|
51
69
|
kind: 'unix',
|
|
52
|
-
path: path.join(os.tmpdir(), `${appName}-session-host${suffix}.sock`),
|
|
70
|
+
path: path.join(options.tmpDir ?? os.tmpdir(), `${appName}-session-host${suffix}.sock`),
|
|
53
71
|
};
|
|
72
|
+
const limit = platform === 'linux' ? 108 : 104;
|
|
73
|
+
if (Buffer.byteLength(endpoint.path, 'utf8') + 1 <= limit) return endpoint;
|
|
74
|
+
|
|
75
|
+
// Only an endpoint that cannot fit sockaddr_un changes. In particular, do not
|
|
76
|
+
// probe, relocate or unlink a legacy socket: every valid short path stays
|
|
77
|
+
// identical, including discovery by already-running hosts. Parent, host and
|
|
78
|
+
// CLI share this pure derivation. Hash the complete legacy namespace (tmpdir,
|
|
79
|
+
// app name and config-derived ipcKey), plus uid for the shared /tmp directory.
|
|
80
|
+
// A full SHA-256 avoids truncating long/multibyte names into aliases. Keep the
|
|
81
|
+
// literal /tmp spelling: Darwin's /private/tmp realpath needlessly adds bytes.
|
|
82
|
+
const identity = JSON.stringify([endpoint.path, appName, rawKey, process.getuid?.() ?? null]);
|
|
83
|
+
const digest = createHash('sha256').update(identity, 'utf8').digest('hex');
|
|
84
|
+
const shortened: SessionHostEndpoint = { kind: 'unix', path: `/tmp/adhdev-sh-${digest}.sock` };
|
|
85
|
+
validateSessionHostEndpoint(shortened, platform);
|
|
86
|
+
return shortened;
|
|
54
87
|
}
|
|
55
88
|
|
|
56
89
|
function serializeEnvelope(envelope: SessionHostWireEnvelope): string {
|
|
@@ -85,18 +118,19 @@ function serializeEnvelope(envelope: SessionHostWireEnvelope): string {
|
|
|
85
118
|
function createLineParser<TEnvelope = SessionHostWireEnvelope>(
|
|
86
119
|
onEnvelope: (envelope: TEnvelope) => void,
|
|
87
120
|
) {
|
|
88
|
-
let
|
|
121
|
+
let fragments: string[] = [];
|
|
89
122
|
const decoder = new StringDecoder('utf8');
|
|
90
123
|
const parser = (chunk: Buffer | string) => {
|
|
91
|
-
|
|
92
|
-
let
|
|
93
|
-
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
124
|
+
const text = typeof chunk === 'string' ? chunk : decoder.write(chunk);
|
|
125
|
+
let start = 0;
|
|
126
|
+
for (;;) {
|
|
127
|
+
const newline = text.indexOf('\n', start);
|
|
128
|
+
if (newline < 0) { if (start < text.length) fragments.push(text.slice(start)); break; }
|
|
129
|
+
fragments.push(text.slice(start, newline));
|
|
130
|
+
const rawLine = fragments.join('').trim();
|
|
131
|
+
fragments = [];
|
|
132
|
+
start = newline + 1;
|
|
133
|
+
if (rawLine) onEnvelope(JSON.parse(rawLine) as TEnvelope);
|
|
100
134
|
}
|
|
101
135
|
};
|
|
102
136
|
/**
|
|
@@ -112,8 +146,8 @@ function createLineParser<TEnvelope = SessionHostWireEnvelope>(
|
|
|
112
146
|
* mid-write into a crash of the process observing it.
|
|
113
147
|
*/
|
|
114
148
|
parser.end = (): string => {
|
|
115
|
-
const remainder =
|
|
116
|
-
|
|
149
|
+
const remainder = fragments.join('') + decoder.end();
|
|
150
|
+
fragments = [];
|
|
117
151
|
return remainder;
|
|
118
152
|
};
|
|
119
153
|
return parser;
|
|
@@ -122,6 +156,9 @@ function createLineParser<TEnvelope = SessionHostWireEnvelope>(
|
|
|
122
156
|
export interface SessionHostClientOptions {
|
|
123
157
|
endpoint?: SessionHostEndpoint;
|
|
124
158
|
appName?: string;
|
|
159
|
+
requestTimeoutMs?: number;
|
|
160
|
+
/** Join the shared client registry (default true). Disable for short-lived probes. */
|
|
161
|
+
registerAsShared?: boolean;
|
|
125
162
|
}
|
|
126
163
|
|
|
127
164
|
/**
|
|
@@ -138,6 +175,34 @@ export type SessionHostDisconnectReason = 'error' | 'ended' | 'closed';
|
|
|
138
175
|
* (host not up yet) — only the former is a session-host death signal.
|
|
139
176
|
*/
|
|
140
177
|
const establishedSockets = new WeakSet<net.Socket>();
|
|
178
|
+
const activeClientRefs = new Set<WeakRef<SessionHostClient>>();
|
|
179
|
+
|
|
180
|
+
export function disconnectSessionHostClients(endpoint?: SessionHostEndpoint, error?: Error): void {
|
|
181
|
+
for (const ref of activeClientRefs) {
|
|
182
|
+
const client = ref.deref();
|
|
183
|
+
if (!client) {
|
|
184
|
+
activeClientRefs.delete(ref);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (!endpoint || client.endpoint.path === endpoint.path) {
|
|
188
|
+
client.disconnect(error);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function findConnectedSessionHostClient(endpoint?: SessionHostEndpoint): SessionHostClient | null {
|
|
194
|
+
for (const ref of activeClientRefs) {
|
|
195
|
+
const client = ref.deref();
|
|
196
|
+
if (!client) {
|
|
197
|
+
activeClientRefs.delete(ref);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if ((!endpoint || client.endpoint.path === endpoint.path) && client.isConnected()) {
|
|
201
|
+
return client;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
141
206
|
|
|
142
207
|
export interface SessionHostDisconnectInfo {
|
|
143
208
|
reason: SessionHostDisconnectReason;
|
|
@@ -161,14 +226,34 @@ export class SessionHostClient {
|
|
|
161
226
|
readonly endpoint: SessionHostEndpoint;
|
|
162
227
|
|
|
163
228
|
private socket: net.Socket | null = null;
|
|
229
|
+
private connectPromise: Promise<void> | null = null;
|
|
230
|
+
private requestTimeoutMs = 30_000;
|
|
164
231
|
private requestWaiters = new Map<string, { resolve: (value: SessionHostResponse) => void; reject: (error: Error) => void }>();
|
|
165
232
|
private eventListeners = new Set<(event: SessionHostEvent) => void>();
|
|
166
233
|
private disconnectListeners = new Set<(info: SessionHostDisconnectInfo) => void>();
|
|
167
234
|
/** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
|
|
168
235
|
private disconnectedSockets = new WeakSet<net.Socket>();
|
|
236
|
+
/** Session subscriptions established via create_session/attach_session, replayed automatically on reconnect. */
|
|
237
|
+
private attachedSessions = new Map<string, AttachSessionPayload>();
|
|
169
238
|
|
|
170
239
|
constructor(options: SessionHostClientOptions = {}) {
|
|
171
240
|
this.endpoint = options.endpoint || getDefaultSessionHostEndpoint(options.appName || 'adhdev');
|
|
241
|
+
if (typeof options.requestTimeoutMs === 'number' && options.requestTimeoutMs > 0) {
|
|
242
|
+
this.requestTimeoutMs = options.requestTimeoutMs;
|
|
243
|
+
}
|
|
244
|
+
if (options.registerAsShared !== false) activeClientRefs.add(new WeakRef(this));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
static disconnectClients(endpoint?: SessionHostEndpoint, error?: Error): void {
|
|
248
|
+
disconnectSessionHostClients(endpoint, error);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
static findConnectedClient(endpoint?: SessionHostEndpoint): SessionHostClient | null {
|
|
252
|
+
return findConnectedSessionHostClient(endpoint);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
isConnected(): boolean {
|
|
256
|
+
return Boolean(this.socket && !this.socket.destroyed && establishedSockets.has(this.socket));
|
|
172
257
|
}
|
|
173
258
|
|
|
174
259
|
/**
|
|
@@ -228,6 +313,7 @@ export class SessionHostClient {
|
|
|
228
313
|
// guard at the top of connect().
|
|
229
314
|
if (this.socket === socket) {
|
|
230
315
|
this.socket = null;
|
|
316
|
+
this.connectPromise = null;
|
|
231
317
|
}
|
|
232
318
|
try { socket.destroy(); } catch { /* noop */ }
|
|
233
319
|
|
|
@@ -246,13 +332,60 @@ export class SessionHostClient {
|
|
|
246
332
|
}
|
|
247
333
|
}
|
|
248
334
|
|
|
249
|
-
|
|
250
|
-
|
|
335
|
+
private sendRawRequestOnSocket<T = unknown>(
|
|
336
|
+
socket: net.Socket,
|
|
337
|
+
request: SessionHostRequest,
|
|
338
|
+
timeoutMs = this.requestTimeoutMs,
|
|
339
|
+
): Promise<SessionHostResponse<T>> {
|
|
340
|
+
const requestId = generateUUID();
|
|
341
|
+
const envelope: SessionHostRequestEnvelope = {
|
|
342
|
+
kind: 'request',
|
|
343
|
+
requestId,
|
|
344
|
+
request,
|
|
345
|
+
};
|
|
346
|
+
const timeoutLabel = timeoutMs % 1000 === 0 ? `${timeoutMs / 1000}s` : `${timeoutMs}ms`;
|
|
347
|
+
const startedAt = Date.now();
|
|
348
|
+
const startedMonotonicAt = performance.now();
|
|
349
|
+
return new Promise<SessionHostResponse<T>>((resolve, reject) => {
|
|
350
|
+
const timeout = setTimeout(() => {
|
|
351
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - startedMonotonicAt));
|
|
352
|
+
const wallElapsedMs = Math.max(0, Date.now() - startedAt);
|
|
353
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
354
|
+
const timeoutError = Object.assign(
|
|
355
|
+
new Error(`Session host request timed out after ${timeoutLabel} (${request.type})`),
|
|
356
|
+
{
|
|
357
|
+
code: 'SESSION_HOST_REQUEST_TIMEOUT',
|
|
358
|
+
requestType: request.type,
|
|
359
|
+
scheduledTimeoutMs: timeoutMs,
|
|
360
|
+
actualElapsedMs,
|
|
361
|
+
wallElapsedMs,
|
|
362
|
+
observerLagMs,
|
|
363
|
+
},
|
|
364
|
+
);
|
|
365
|
+
// A deadline says nothing about socket or process liveness. Remove only
|
|
366
|
+
// this waiter; the parser safely discards its eventual late response.
|
|
367
|
+
this.requestWaiters.delete(requestId);
|
|
368
|
+
reject(timeoutError);
|
|
369
|
+
}, timeoutMs);
|
|
370
|
+
this.requestWaiters.set(requestId, {
|
|
371
|
+
resolve: (value) => { clearTimeout(timeout); resolve(value as SessionHostResponse<T>); },
|
|
372
|
+
reject: (error) => { clearTimeout(timeout); reject(error); },
|
|
373
|
+
});
|
|
374
|
+
socket.write(serializeEnvelope(envelope));
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async connect(timeoutMs = this.requestTimeoutMs): Promise<void> {
|
|
379
|
+
if (this.socket && !this.socket.destroyed) {
|
|
380
|
+
if (this.connectPromise) await this.connectPromise;
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
251
383
|
// Cleanup stale socket reference left after error/disconnect
|
|
252
384
|
if (this.socket) {
|
|
253
385
|
try { this.socket.destroy(); } catch { /* noop */ }
|
|
254
386
|
this.socket = null;
|
|
255
387
|
}
|
|
388
|
+
this.connectPromise = null;
|
|
256
389
|
|
|
257
390
|
const socket = net.createConnection(this.endpoint.path);
|
|
258
391
|
this.socket = socket;
|
|
@@ -273,7 +406,11 @@ export class SessionHostClient {
|
|
|
273
406
|
}
|
|
274
407
|
|
|
275
408
|
if (envelope.kind === 'event') {
|
|
276
|
-
for (const listener of this.eventListeners)
|
|
409
|
+
for (const listener of this.eventListeners) {
|
|
410
|
+
// An observer must never abort frame draining and strand a response
|
|
411
|
+
// behind an event in the same socket chunk.
|
|
412
|
+
try { listener(envelope.event); } catch { /* observer owns its error */ }
|
|
413
|
+
}
|
|
277
414
|
}
|
|
278
415
|
});
|
|
279
416
|
socket.on('data', parser);
|
|
@@ -314,13 +451,62 @@ export class SessionHostClient {
|
|
|
314
451
|
this.handleDisconnect(socket, 'ended', undefined, flushParser().length);
|
|
315
452
|
});
|
|
316
453
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
454
|
+
const connectTask = (async () => {
|
|
455
|
+
await new Promise<void>((resolve, reject) => {
|
|
456
|
+
const cleanup = () => {
|
|
457
|
+
clearTimeout(timer);
|
|
458
|
+
socket.off('connect', connected);
|
|
459
|
+
socket.off('error', failed);
|
|
460
|
+
socket.off('close', closed);
|
|
461
|
+
};
|
|
462
|
+
const connected = () => { cleanup(); establishedSockets.add(socket); resolve(); };
|
|
463
|
+
const failed = (error: Error) => { cleanup(); reject(error); };
|
|
464
|
+
const closed = () => failed(new Error('Session host connection closed before connect'));
|
|
465
|
+
const connectStartedAt = Date.now();
|
|
466
|
+
const connectStartedMonotonicAt = performance.now();
|
|
467
|
+
const timer = setTimeout(() => {
|
|
468
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - connectStartedMonotonicAt));
|
|
469
|
+
const wallElapsedMs = Math.max(0, Date.now() - connectStartedAt);
|
|
470
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
471
|
+
const error = Object.assign(
|
|
472
|
+
new Error(`Session host connect timed out after ${timeoutMs}ms`),
|
|
473
|
+
{
|
|
474
|
+
code: 'SESSION_HOST_CONNECT_TIMEOUT',
|
|
475
|
+
scheduledTimeoutMs: timeoutMs,
|
|
476
|
+
actualElapsedMs,
|
|
477
|
+
wallElapsedMs,
|
|
478
|
+
observerLagMs,
|
|
479
|
+
},
|
|
480
|
+
);
|
|
481
|
+
failed(error);
|
|
482
|
+
if (this.socket === socket) this.disconnect(error);
|
|
483
|
+
}, timeoutMs);
|
|
484
|
+
socket.once('connect', connected);
|
|
485
|
+
socket.once('error', failed);
|
|
486
|
+
socket.once('close', closed);
|
|
321
487
|
});
|
|
322
|
-
socket.
|
|
323
|
-
|
|
488
|
+
if (this.attachedSessions.size > 0 && this.socket === socket && !socket.destroyed) {
|
|
489
|
+
for (const [sessionId, sub] of [...this.attachedSessions.entries()]) {
|
|
490
|
+
if (this.socket !== socket || socket.destroyed) break;
|
|
491
|
+
const replayResponse = await this.sendRawRequestOnSocket(socket, {
|
|
492
|
+
type: 'attach_session',
|
|
493
|
+
payload: sub,
|
|
494
|
+
}).catch(() => null);
|
|
495
|
+
if (replayResponse && !replayResponse.success) {
|
|
496
|
+
this.attachedSessions.delete(sessionId);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
})();
|
|
501
|
+
|
|
502
|
+
this.connectPromise = connectTask;
|
|
503
|
+
try {
|
|
504
|
+
await connectTask;
|
|
505
|
+
} finally {
|
|
506
|
+
if (this.connectPromise === connectTask) {
|
|
507
|
+
this.connectPromise = null;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
324
510
|
}
|
|
325
511
|
|
|
326
512
|
onEvent(listener: (event: SessionHostEvent) => void): () => void {
|
|
@@ -330,33 +516,90 @@ export class SessionHostClient {
|
|
|
330
516
|
};
|
|
331
517
|
}
|
|
332
518
|
|
|
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
|
-
|
|
519
|
+
async request<T = unknown>(request: SessionHostRequest, options: { timeoutMs?: number } = {}): Promise<SessionHostResponse<T>> {
|
|
520
|
+
const timeoutMs = Math.max(1, options.timeoutMs ?? this.requestTimeoutMs);
|
|
521
|
+
const deadline = Date.now() + timeoutMs;
|
|
522
|
+
const alreadyConnected = this.isConnected() && !this.connectPromise;
|
|
523
|
+
// A probe must also bound a connect/re-attach already in flight on this
|
|
524
|
+
// client; that task may have started with the normal 30s timeout. The
|
|
525
|
+
// request budget must not shorten or cancel that shared connection task.
|
|
526
|
+
if (options.timeoutMs !== undefined) {
|
|
527
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
528
|
+
const raceStartedAt = Date.now();
|
|
529
|
+
const raceStartedMonotonicAt = performance.now();
|
|
530
|
+
try {
|
|
531
|
+
await Promise.race([
|
|
532
|
+
this.connect(),
|
|
533
|
+
new Promise<never>((_resolve, reject) => {
|
|
534
|
+
timer = setTimeout(() => {
|
|
535
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - raceStartedMonotonicAt));
|
|
536
|
+
const wallElapsedMs = Math.max(0, Date.now() - raceStartedAt);
|
|
537
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
538
|
+
const error = Object.assign(
|
|
539
|
+
new Error(`Session host connect timed out after ${timeoutMs}ms`),
|
|
540
|
+
{
|
|
541
|
+
code: 'SESSION_HOST_CONNECT_TIMEOUT',
|
|
542
|
+
scheduledTimeoutMs: timeoutMs,
|
|
543
|
+
actualElapsedMs,
|
|
544
|
+
wallElapsedMs,
|
|
545
|
+
observerLagMs,
|
|
546
|
+
},
|
|
547
|
+
);
|
|
548
|
+
reject(error);
|
|
549
|
+
}, timeoutMs);
|
|
550
|
+
}),
|
|
551
|
+
]);
|
|
552
|
+
} finally { if (timer) clearTimeout(timer); }
|
|
553
|
+
} else {
|
|
554
|
+
await this.connect(timeoutMs);
|
|
555
|
+
}
|
|
556
|
+
const requestSocket = this.socket;
|
|
557
|
+
if (!requestSocket) throw new Error('Session host socket unavailable');
|
|
558
|
+
|
|
559
|
+
const response = await this.sendRawRequestOnSocket<T>(requestSocket, request, options.timeoutMs === undefined || alreadyConnected ? timeoutMs : Math.max(1, deadline - Date.now()));
|
|
560
|
+
if (response.success) {
|
|
561
|
+
if (request.type === 'attach_session') {
|
|
562
|
+
this.attachedSessions.set(request.payload.sessionId, {
|
|
563
|
+
sessionId: request.payload.sessionId,
|
|
564
|
+
clientId: request.payload.clientId,
|
|
565
|
+
clientType: request.payload.clientType,
|
|
566
|
+
readOnly: request.payload.readOnly === true,
|
|
567
|
+
});
|
|
568
|
+
} else if (request.type === 'create_session') {
|
|
569
|
+
const createdId = (response.result as { sessionId?: string } | undefined)?.sessionId || request.payload.sessionId;
|
|
570
|
+
const clientId = typeof request.payload.clientId === 'string' ? request.payload.clientId.trim() : '';
|
|
571
|
+
if (createdId && clientId) {
|
|
572
|
+
this.attachedSessions.set(createdId, {
|
|
573
|
+
sessionId: createdId,
|
|
574
|
+
clientId,
|
|
575
|
+
clientType: request.payload.clientType || 'daemon',
|
|
576
|
+
readOnly: false,
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
} else if (request.type === 'detach_session' || request.type === 'delete_session') {
|
|
580
|
+
this.attachedSessions.delete(request.payload.sessionId);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return response;
|
|
584
|
+
}
|
|
355
585
|
|
|
356
|
-
|
|
586
|
+
disconnect(error?: Error): void {
|
|
587
|
+
const socket = this.socket;
|
|
588
|
+
if (socket) {
|
|
589
|
+
this.handleDisconnect(socket, error ? 'error' : 'closed', error, 0);
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
this.connectPromise = null;
|
|
593
|
+
const failure = error || new Error(`Session host client disconnected (${this.endpoint.path})`);
|
|
594
|
+
for (const waiter of this.requestWaiters.values()) {
|
|
595
|
+
waiter.reject(failure);
|
|
596
|
+
}
|
|
597
|
+
this.requestWaiters.clear();
|
|
357
598
|
}
|
|
358
599
|
|
|
359
600
|
async close(): Promise<void> {
|
|
601
|
+
this.attachedSessions.clear();
|
|
602
|
+
this.connectPromise = null;
|
|
360
603
|
if (!this.socket) return;
|
|
361
604
|
const socket = this.socket;
|
|
362
605
|
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/registry.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type {
|
|
|
7
7
|
ReleaseWritePayload,
|
|
8
8
|
SessionAttachedClient,
|
|
9
9
|
SessionHostRecord,
|
|
10
|
+
SessionHostRequest,
|
|
10
11
|
SessionTermination,
|
|
11
12
|
} from './types.js';
|
|
12
13
|
import { SessionRingBuffer } from './buffer.js';
|
|
@@ -20,6 +21,14 @@ interface SessionRuntimeState {
|
|
|
20
21
|
|
|
21
22
|
export class SessionHostRegistry {
|
|
22
23
|
private sessions = new Map<string, SessionRuntimeState>();
|
|
24
|
+
/** This registry's lifetime; every inputEpoch it mints starts with it. */
|
|
25
|
+
private readonly lifetimeId = generateUUID();
|
|
26
|
+
private epochCounter = 0;
|
|
27
|
+
|
|
28
|
+
private mintInputEpoch(): string {
|
|
29
|
+
this.epochCounter += 1;
|
|
30
|
+
return `${this.lifetimeId}:${this.epochCounter}`;
|
|
31
|
+
}
|
|
23
32
|
|
|
24
33
|
createSession(payload: CreateSessionPayload): SessionHostRecord {
|
|
25
34
|
const sessionId = payload.sessionId || generateUUID();
|
|
@@ -55,6 +64,8 @@ export class SessionHostRegistry {
|
|
|
55
64
|
lifecycle: 'starting',
|
|
56
65
|
writeOwner: null,
|
|
57
66
|
attachedClients: initialClient,
|
|
67
|
+
inputSeq: 0,
|
|
68
|
+
inputEpoch: this.mintInputEpoch(),
|
|
58
69
|
buffer: {
|
|
59
70
|
scrollbackBytes: 0,
|
|
60
71
|
snapshotSeq: 0,
|
|
@@ -78,6 +89,16 @@ export class SessionHostRegistry {
|
|
|
78
89
|
|
|
79
90
|
restoreSession(record: SessionHostRecord, snapshot?: { seq: number; text: string } | null): SessionHostRecord {
|
|
80
91
|
const cloned = this.cloneRecord(record);
|
|
92
|
+
// A record persisted by a host that predates inputSeq: this host counts from here.
|
|
93
|
+
if (typeof cloned.inputSeq !== 'number') cloned.inputSeq = 0;
|
|
94
|
+
// A new counter lifetime unless this is the SAME live record restored in
|
|
95
|
+
// place with its count intact (resize does that): a record loaded into
|
|
96
|
+
// this process for the first time, or one whose count went backwards,
|
|
97
|
+
// cannot be compared with anything announced before (review R8-2).
|
|
98
|
+
const live = this.sessions.get(cloned.sessionId)?.record;
|
|
99
|
+
const sameLifetime = !!live && typeof live.inputEpoch === 'string' && cloned.inputEpoch === live.inputEpoch
|
|
100
|
+
&& cloned.inputSeq >= (live.inputSeq ?? 0);
|
|
101
|
+
if (!sameLifetime) cloned.inputEpoch = this.mintInputEpoch();
|
|
81
102
|
this.sessions.set(cloned.sessionId, {
|
|
82
103
|
record: cloned,
|
|
83
104
|
buffer: (() => {
|
|
@@ -89,17 +110,67 @@ export class SessionHostRegistry {
|
|
|
89
110
|
return this.cloneRecord(cloned);
|
|
90
111
|
}
|
|
91
112
|
|
|
113
|
+
/** Census projection: omit launch arguments/environment and summarize stopped
|
|
114
|
+
* sessions. Full details remain available through getSession. */
|
|
115
|
+
listSessionSummaries(activeOnly = false): SessionHostRecord[] {
|
|
116
|
+
return Array.from(this.sessions.values()).map(s => s.record)
|
|
117
|
+
.filter(r => !activeOnly || (!r.termination && r.lifecycle !== 'stopped' && r.lifecycle !== 'failed'))
|
|
118
|
+
.map(r => this.cloneRecord({ ...r, launchCommand: { command: r.launchCommand.command, args: [] },
|
|
119
|
+
meta: r.termination || r.lifecycle === 'stopped' || r.lifecycle === 'failed' ? {} : { ...r.meta, cliArgs: [], cliArgsOmitted: true } }))
|
|
120
|
+
.sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
121
|
+
}
|
|
122
|
+
|
|
92
123
|
listSessions(): SessionHostRecord[] {
|
|
93
124
|
return Array.from(this.sessions.values())
|
|
94
125
|
.map(state => this.cloneRecord(state.record))
|
|
95
126
|
.sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
96
127
|
}
|
|
97
128
|
|
|
129
|
+
/** No launch bodies are cloned. Unknown role evidence stays conservative. */
|
|
130
|
+
getSessionCensus(sessionIds: string[]): { liveSessionIds: string[]; hasOtherAssistantCandidates: boolean } {
|
|
131
|
+
if (!Array.isArray(sessionIds) || sessionIds.length > 128
|
|
132
|
+
|| sessionIds.some(id => typeof id !== 'string' || id.length === 0 || id.length > 256)) {
|
|
133
|
+
throw new Error('Invalid session census: at most 128 identities of 256 characters');
|
|
134
|
+
}
|
|
135
|
+
const requested = new Set(sessionIds);
|
|
136
|
+
const liveSessionIds: string[] = [];
|
|
137
|
+
let hasOtherAssistantCandidates = false;
|
|
138
|
+
for (const { record } of this.sessions.values()) {
|
|
139
|
+
if (record.category !== 'cli' || record.termination
|
|
140
|
+
|| !['starting', 'running', 'stopping', 'interrupted'].includes(record.lifecycle)) continue;
|
|
141
|
+
if (requested.has(record.sessionId)) liveSessionIds.push(record.sessionId);
|
|
142
|
+
else {
|
|
143
|
+
const launch = record.meta?.launchRecord as { launchedBy?: unknown; roleLaunch?: { role?: unknown } } | undefined;
|
|
144
|
+
// This is uncertainty, never positive provenance or permission to attach.
|
|
145
|
+
// A role-marked writer created since the caller's disk scan must still
|
|
146
|
+
// prevent a duplicate, without returning any of its user-authored data.
|
|
147
|
+
if (record.meta?.assistant === true || launch?.launchedBy === 'assistant' || launch?.roleLaunch?.role === 'assistant') {
|
|
148
|
+
hasOtherAssistantCandidates = true;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { liveSessionIds, hasOtherAssistantCandidates };
|
|
153
|
+
}
|
|
154
|
+
|
|
98
155
|
getSession(sessionId: string): SessionHostRecord | null {
|
|
99
156
|
const state = this.sessions.get(sessionId);
|
|
100
157
|
return state ? this.cloneRecord(state.record) : null;
|
|
101
158
|
}
|
|
102
159
|
|
|
160
|
+
attachClientIfIncarnation(payload: Extract<SessionHostRequest, { type: 'attach_session_if_incarnation' }>['payload']): SessionHostRecord {
|
|
161
|
+
const record = this.requireSession(payload.sessionId).record;
|
|
162
|
+
const expected = payload.expectedIncarnation;
|
|
163
|
+
if (!expected || expected.sessionId !== record.sessionId
|
|
164
|
+
|| typeof expected.runtimeKey !== 'string' || !expected.runtimeKey
|
|
165
|
+
|| !Number.isFinite(expected.startedAt) || expected.startedAt <= 0
|
|
166
|
+
|| expected.runtimeKey !== record.runtimeKey || expected.startedAt !== record.startedAt) {
|
|
167
|
+
throw new Error(`Runtime not found for session: ${payload.sessionId} (incarnation changed)`);
|
|
168
|
+
}
|
|
169
|
+
// No await between comparison and mutation; a failed pin cannot evict an
|
|
170
|
+
// existing daemon, clear its owner, or grant this client an attachment.
|
|
171
|
+
return this.attachClient(payload);
|
|
172
|
+
}
|
|
173
|
+
|
|
103
174
|
attachClient(payload: AttachSessionPayload): SessionHostRecord {
|
|
104
175
|
const state = this.requireSession(payload.sessionId);
|
|
105
176
|
const now = Date.now();
|
|
@@ -153,6 +224,22 @@ export class SessionHostRegistry {
|
|
|
153
224
|
return this.cloneRecord(state.record);
|
|
154
225
|
}
|
|
155
226
|
|
|
227
|
+
/** Count one accepted input (see SessionHostRecord.inputSeq); returns its number. */
|
|
228
|
+
recordInput(sessionId: string): number {
|
|
229
|
+
const state = this.requireSession(sessionId);
|
|
230
|
+
state.record.inputSeq = (typeof state.record.inputSeq === 'number' ? state.record.inputSeq : 0) + 1;
|
|
231
|
+
if (typeof state.record.inputEpoch !== 'string') state.record.inputEpoch = this.mintInputEpoch();
|
|
232
|
+
return state.record.inputSeq;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The current input counter (see SessionHostInputState). */
|
|
236
|
+
getInputState(sessionId: string): { inputSeq: number; inputEpoch: string } {
|
|
237
|
+
const state = this.requireSession(sessionId);
|
|
238
|
+
if (typeof state.record.inputSeq !== 'number') state.record.inputSeq = 0;
|
|
239
|
+
if (typeof state.record.inputEpoch !== 'string') state.record.inputEpoch = this.mintInputEpoch();
|
|
240
|
+
return { inputSeq: state.record.inputSeq, inputEpoch: state.record.inputEpoch };
|
|
241
|
+
}
|
|
242
|
+
|
|
156
243
|
acquireWrite(payload: AcquireWritePayload): SessionHostRecord {
|
|
157
244
|
const state = this.requireSession(payload.sessionId);
|
|
158
245
|
if (state.record.writeOwner && state.record.writeOwner.clientId !== payload.clientId && !payload.force) {
|
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.
|