@adhdev/session-host-core 1.0.58-rc.1 → 1.0.58-rc.100

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/src/ipc.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as os from 'os';
2
2
  import * as path from 'path';
3
3
  import * as net from 'net';
4
+ import { StringDecoder } from 'string_decoder';
4
5
  import type {
5
6
  SessionHostEvent,
6
7
  SessionHostRequest,
@@ -66,10 +67,28 @@ function serializeEnvelope(envelope: SessionHostWireEnvelope): string {
66
67
  return `${JSON.stringify(envelope)}\n`;
67
68
  }
68
69
 
70
+ /**
71
+ * UTF8-CHUNK-BOUNDARY: decode the socket stream, never the individual chunk.
72
+ *
73
+ * This used to call `chunk.toString()` on every Buffer independently. A socket
74
+ * hands us arbitrary byte slices — a multi-byte UTF-8 sequence straddling two
75
+ * chunks gets decoded as two truncated sequences, and each half becomes U+FFFD.
76
+ * The damage is silent by construction: the replacement character is valid JSON
77
+ * string content, so the envelope still parses and only the *value* is wrong.
78
+ * A pasted 11,994-char Korean prompt lost exactly one character that way — the
79
+ * `도` beginning at wire offset 8190, split across the 8192-byte chunk boundary,
80
+ * arrived as `�착`.
81
+ *
82
+ * StringDecoder holds an incomplete trailing sequence back until the bytes that
83
+ * finish it arrive, which is the only correct way to turn a byte stream into
84
+ * text. String chunks bypass it: they are already decoded, and feeding them
85
+ * through `Buffer.from` would re-encode text the caller never asked us to touch.
86
+ */
69
87
  function createLineParser(onEnvelope: (envelope: SessionHostWireEnvelope) => void) {
70
88
  let buffer = '';
71
- return (chunk: Buffer | string) => {
72
- buffer += chunk.toString();
89
+ const decoder = new StringDecoder('utf8');
90
+ const parser = (chunk: Buffer | string) => {
91
+ buffer += typeof chunk === 'string' ? chunk : decoder.write(chunk);
73
92
  let newlineIndex = buffer.indexOf('\n');
74
93
  while (newlineIndex >= 0) {
75
94
  const rawLine = buffer.slice(0, newlineIndex).trim();
@@ -80,6 +99,24 @@ function createLineParser(onEnvelope: (envelope: SessionHostWireEnvelope) => voi
80
99
  newlineIndex = buffer.indexOf('\n');
81
100
  }
82
101
  };
102
+ /**
103
+ * Flush at EOF, returning whatever text never formed a complete line.
104
+ *
105
+ * `decoder.end()` releases any bytes still held back as an incomplete UTF-8
106
+ * sequence; without it those bytes vanish with the decoder. What is left in
107
+ * the buffer is by definition a partial line — envelopes are newline-framed,
108
+ * so an unterminated tail is a truncated transmission, not a message. It is
109
+ * therefore RETURNED for the caller to log rather than parsed: calling
110
+ * JSON.parse on a half-written envelope inside a socket EOF handler would
111
+ * raise an uncaught exception in the daemon, turning a peer that died
112
+ * mid-write into a crash of the process observing it.
113
+ */
114
+ parser.end = (): string => {
115
+ const remainder = buffer + decoder.end();
116
+ buffer = '';
117
+ return remainder;
118
+ };
119
+ return parser;
83
120
  }
84
121
 
85
122
  export interface SessionHostClientOptions {
@@ -87,17 +124,128 @@ export interface SessionHostClientOptions {
87
124
  appName?: string;
88
125
  }
89
126
 
127
+ /**
128
+ * Why an established session-host connection went away.
129
+ * - `error` — socket emitted 'error' (includes ECONNRESET on abrupt host death)
130
+ * - `ended` — peer sent FIN ('end'): the host closed the connection cleanly
131
+ * - `closed` — socket fully closed ('close') without a preceding error/end
132
+ */
133
+ export type SessionHostDisconnectReason = 'error' | 'ended' | 'closed';
134
+
135
+ /**
136
+ * Sockets that reached 'connect' at least once. Used to distinguish a genuine
137
+ * disconnect (host died under us) from a connect attempt that never landed
138
+ * (host not up yet) — only the former is a session-host death signal.
139
+ */
140
+ const establishedSockets = new WeakSet<net.Socket>();
141
+
142
+ export interface SessionHostDisconnectInfo {
143
+ reason: SessionHostDisconnectReason;
144
+ endpointPath: string;
145
+ /** In-flight requests abandoned by this disconnect (they were rejected). */
146
+ pendingRequests: number;
147
+ error?: Error;
148
+ /**
149
+ * Bytes discarded from a newline-unterminated frame at EOF (0 when the peer
150
+ * hung up on a clean frame boundary, which is the normal case).
151
+ *
152
+ * Non-zero means the peer was cut off MID-WRITE — diagnostic context that
153
+ * distinguishes "the host exited" from "the host died with a frame in
154
+ * flight". Before the parser's `end()` was reachable this was unknowable:
155
+ * the bytes were dropped with the decoder and no counter existed.
156
+ */
157
+ droppedTailBytes: number;
158
+ }
159
+
90
160
  export class SessionHostClient {
91
161
  readonly endpoint: SessionHostEndpoint;
92
162
 
93
163
  private socket: net.Socket | null = null;
94
164
  private requestWaiters = new Map<string, { resolve: (value: SessionHostResponse) => void; reject: (error: Error) => void }>();
95
165
  private eventListeners = new Set<(event: SessionHostEvent) => void>();
166
+ private disconnectListeners = new Set<(info: SessionHostDisconnectInfo) => void>();
167
+ /** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
168
+ private disconnectedSockets = new WeakSet<net.Socket>();
96
169
 
97
170
  constructor(options: SessionHostClientOptions = {}) {
98
171
  this.endpoint = options.endpoint || getDefaultSessionHostEndpoint(options.appName || 'adhdev');
99
172
  }
100
173
 
174
+ /**
175
+ * Fires when an established connection to the session host goes away.
176
+ *
177
+ * Before this existed the client registered only 'data' and 'error' handlers,
178
+ * so a *clean* FIN — the host process exiting normally, or dying to an
179
+ * uncaught exception that took the socket down without an error event on our
180
+ * end — ran nothing at all: `this.socket` stayed non-null pointing at a dead
181
+ * socket, in-flight waiters hung to their 30s timeout, and no caller was told.
182
+ * That silence is what let a session-host death present downstream as an
183
+ * unrelated application-level fault (a missing completion marker) instead of
184
+ * "the host is gone".
185
+ */
186
+ onDisconnect(listener: (info: SessionHostDisconnectInfo) => void): () => void {
187
+ this.disconnectListeners.add(listener);
188
+ return () => {
189
+ this.disconnectListeners.delete(listener);
190
+ };
191
+ }
192
+
193
+ private handleDisconnect(
194
+ socket: net.Socket,
195
+ reason: SessionHostDisconnectReason,
196
+ error?: Error,
197
+ droppedTailBytes = 0,
198
+ ): void {
199
+ if (this.disconnectedSockets.has(socket)) return;
200
+ this.disconnectedSockets.add(socket);
201
+
202
+ // A connect that never succeeded is a *failed connect*, not a disconnect —
203
+ // reporting it as a host death would make every poll against a not-yet-started
204
+ // host look like a crash. connect() already surfaces that failure to its caller
205
+ // via the awaited 'error'. Still clear socket state below? No: connect()'s own
206
+ // error path handles a never-established socket, and `this.socket` is
207
+ // overwritten on the next connect() attempt regardless.
208
+ const wasEstablished = establishedSockets.has(socket);
209
+ if (!wasEstablished) {
210
+ if (this.socket === socket) this.socket = null;
211
+ try { socket.destroy(); } catch { /* noop */ }
212
+ // Reject waiters anyway — a request() that raced a dying socket must not hang.
213
+ const failure = error || new Error(`Session host connect failed (${this.endpoint.path})`);
214
+ for (const waiter of this.requestWaiters.values()) waiter.reject(failure);
215
+ this.requestWaiters.clear();
216
+ return;
217
+ }
218
+
219
+ const pendingRequests = this.requestWaiters.size;
220
+ const failure = error || new Error(`Session host connection ${reason} (${this.endpoint.path})`);
221
+ for (const waiter of this.requestWaiters.values()) {
222
+ waiter.reject(failure);
223
+ }
224
+ this.requestWaiters.clear();
225
+
226
+ // Clear the dead socket reference so the next connect() creates a fresh
227
+ // connection instead of short-circuiting on the `!this.socket.destroyed`
228
+ // guard at the top of connect().
229
+ if (this.socket === socket) {
230
+ this.socket = null;
231
+ }
232
+ try { socket.destroy(); } catch { /* noop */ }
233
+
234
+ const info: SessionHostDisconnectInfo = {
235
+ reason,
236
+ endpointPath: this.endpoint.path,
237
+ pendingRequests,
238
+ error,
239
+ droppedTailBytes,
240
+ };
241
+ for (const listener of this.disconnectListeners) {
242
+ // A throwing observer must not suppress the remaining ones, and must not
243
+ // propagate out of a socket event handler (that would be an uncaught
244
+ // exception in the daemon).
245
+ try { listener(info); } catch { /* noop */ }
246
+ }
247
+ }
248
+
101
249
  async connect(): Promise<void> {
102
250
  if (this.socket && !this.socket.destroyed) return;
103
251
  // Cleanup stale socket reference left after error/disconnect
@@ -109,7 +257,12 @@ export class SessionHostClient {
109
257
  const socket = net.createConnection(this.endpoint.path);
110
258
  this.socket = socket;
111
259
 
112
- socket.on('data', createLineParser((envelope) => {
260
+ // PARSER-EOF-FLUSH: keep the parser handle so its EOF flush is reachable.
261
+ // Inlining `createLineParser(...)` into the 'data' registration discarded
262
+ // the only reference to `end()`, so bytes held back by the StringDecoder as
263
+ // an incomplete UTF-8 sequence were lost with the decoder when the host
264
+ // disconnected.
265
+ const parser = createLineParser((envelope) => {
113
266
  if (envelope.kind === 'response') {
114
267
  const waiter = this.requestWaiters.get(envelope.requestId);
115
268
  if (waiter) {
@@ -122,23 +275,50 @@ export class SessionHostClient {
122
275
  if (envelope.kind === 'event') {
123
276
  for (const listener of this.eventListeners) listener(envelope.event);
124
277
  }
125
- }));
278
+ });
279
+ socket.on('data', parser);
126
280
 
127
- socket.on('error', (error) => {
128
- for (const waiter of this.requestWaiters.values()) {
129
- waiter.reject(error);
281
+ /**
282
+ * Drain the parser at EOF. The remainder is a partial, newline-unterminated
283
+ * frame — a truncated transmission rather than a message — so it is NOT
284
+ * parsed. Feeding a half-written envelope to JSON.parse here would throw
285
+ * inside a socket event handler with no catch above it, converting a host
286
+ * that died mid-write into an uncaught exception in this process. That is
287
+ * exactly the failure the parser's contract set out to avoid.
288
+ *
289
+ * Reported through the existing disconnect surface rather than a new one:
290
+ * a non-empty tail means the peer was cut off mid-frame, which is
291
+ * diagnostic context for the disconnect that is about to be emitted.
292
+ */
293
+ const flushParser = (): string => {
294
+ try {
295
+ return parser.end();
296
+ } catch {
297
+ return '';
130
298
  }
131
- this.requestWaiters.clear();
132
- // Clear the dead socket reference so the next connect() creates a fresh connection
133
- // instead of skipping reconnection on the `!this.socket.destroyed` guard.
134
- if (this.socket === socket) {
135
- this.socket = null;
136
- }
137
- try { socket.destroy(); } catch { /* noop */ }
299
+ };
300
+
301
+ socket.on('error', (error) => {
302
+ const remainder = flushParser();
303
+ this.handleDisconnect(socket, 'error', error, remainder.length);
304
+ });
305
+
306
+ // 'close'/'end' are the clean-FIN counterparts of 'error'. The host server
307
+ // has always handled both directions (server.ts registers close+end); this
308
+ // side handled neither, so host death was observable only if it happened to
309
+ // surface as a socket error.
310
+ socket.on('close', () => {
311
+ this.handleDisconnect(socket, 'closed', undefined, flushParser().length);
312
+ });
313
+ socket.on('end', () => {
314
+ this.handleDisconnect(socket, 'ended', undefined, flushParser().length);
138
315
  });
139
316
 
140
317
  await new Promise<void>((resolve, reject) => {
141
- socket.once('connect', () => resolve());
318
+ socket.once('connect', () => {
319
+ establishedSockets.add(socket);
320
+ resolve();
321
+ });
142
322
  socket.once('error', reject);
143
323
  });
144
324
  }
@@ -180,6 +360,9 @@ export class SessionHostClient {
180
360
  if (!this.socket) return;
181
361
  const socket = this.socket;
182
362
  this.socket = null;
363
+ // Deliberate teardown: suppress the 'close' handler's disconnect signal so
364
+ // callers don't see an intentional close reported as a session-host death.
365
+ this.disconnectedSockets.add(socket);
183
366
  for (const waiter of this.requestWaiters.values()) {
184
367
  waiter.reject(new Error('Session host client closed'));
185
368
  }
package/src/spawn-env.ts CHANGED
@@ -57,6 +57,29 @@ export function sanitizeSpawnEnv(
57
57
  delete env.NO_COLOR;
58
58
  delete env.COLOR;
59
59
 
60
+ // Never forward an inherited terminal geometry. COLUMNS/LINES are advisory
61
+ // overrides that a TUI trusts *in preference to* the real TTY size
62
+ // (measured: with COLUMNS=17 exported, a child on a genuine 80-column PTY
63
+ // reports `tput cols` = 17). The PTY here is sized independently from the
64
+ // adapter's own geometry, so any inherited value is by definition unrelated
65
+ // to the terminal the child was actually given.
66
+ //
67
+ // When the two disagree the child lays out for the phantom width and the
68
+ // VT renders at the real one, so in-place repaints (`\r`, absolute cursor
69
+ // moves) land on the wrong row: content fragments across the buffer with a
70
+ // blank gap between the stale head and the live tail. Observed on
71
+ // antigravity-cli as a "Running command" spinner split into two rows 28
72
+ // blank lines apart, which the spec's from_top/from_bottom sections then
73
+ // sliced into separate body/footer values.
74
+ //
75
+ // Deleting them makes the child measure the TTY via ioctl(TIOCGWINSZ) —
76
+ // the PTY's real size, which is exactly what the VT is sized to. node-pty
77
+ // does not set these itself, so a clean parent env is already the normal
78
+ // case; this only removes a value that leaked in from whatever launched
79
+ // the daemon (interactive shell, tmux, CI runner, nested CLI).
80
+ delete env.COLUMNS;
81
+ delete env.LINES;
82
+
60
83
  // Do not leak a parent Claude Code session identity into spawned claude-cli
61
84
  // children. CLAUDE_CODE_CHILD_SESSION makes a spawned claude run as a nested
62
85
  // child that does NOT persist its ~/.claude/projects transcript, so the