@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/dist/index.d.mts CHANGED
@@ -533,17 +533,78 @@ interface SessionHostEndpointOptions {
533
533
  platform?: NodeJS.Platform;
534
534
  }
535
535
  declare function getDefaultSessionHostEndpoint(appName?: string, options?: SessionHostEndpointOptions): SessionHostEndpoint;
536
- declare function createLineParser(onEnvelope: (envelope: SessionHostWireEnvelope) => void): (chunk: Buffer | string) => void;
536
+ /**
537
+ * UTF8-CHUNK-BOUNDARY: decode the socket stream, never the individual chunk.
538
+ *
539
+ * This used to call `chunk.toString()` on every Buffer independently. A socket
540
+ * hands us arbitrary byte slices — a multi-byte UTF-8 sequence straddling two
541
+ * chunks gets decoded as two truncated sequences, and each half becomes U+FFFD.
542
+ * The damage is silent by construction: the replacement character is valid JSON
543
+ * string content, so the envelope still parses and only the *value* is wrong.
544
+ * A pasted 11,994-char Korean prompt lost exactly one character that way — the
545
+ * `도` beginning at wire offset 8190, split across the 8192-byte chunk boundary,
546
+ * arrived as `�착`.
547
+ *
548
+ * StringDecoder holds an incomplete trailing sequence back until the bytes that
549
+ * finish it arrive, which is the only correct way to turn a byte stream into
550
+ * text. String chunks bypass it: they are already decoded, and feeding them
551
+ * through `Buffer.from` would re-encode text the caller never asked us to touch.
552
+ */
553
+ declare function createLineParser(onEnvelope: (envelope: SessionHostWireEnvelope) => void): {
554
+ (chunk: Buffer | string): void;
555
+ end(): string;
556
+ };
537
557
  interface SessionHostClientOptions {
538
558
  endpoint?: SessionHostEndpoint;
539
559
  appName?: string;
540
560
  }
561
+ /**
562
+ * Why an established session-host connection went away.
563
+ * - `error` — socket emitted 'error' (includes ECONNRESET on abrupt host death)
564
+ * - `ended` — peer sent FIN ('end'): the host closed the connection cleanly
565
+ * - `closed` — socket fully closed ('close') without a preceding error/end
566
+ */
567
+ type SessionHostDisconnectReason = 'error' | 'ended' | 'closed';
568
+ interface SessionHostDisconnectInfo {
569
+ reason: SessionHostDisconnectReason;
570
+ endpointPath: string;
571
+ /** In-flight requests abandoned by this disconnect (they were rejected). */
572
+ pendingRequests: number;
573
+ error?: Error;
574
+ /**
575
+ * Bytes discarded from a newline-unterminated frame at EOF (0 when the peer
576
+ * hung up on a clean frame boundary, which is the normal case).
577
+ *
578
+ * Non-zero means the peer was cut off MID-WRITE — diagnostic context that
579
+ * distinguishes "the host exited" from "the host died with a frame in
580
+ * flight". Before the parser's `end()` was reachable this was unknowable:
581
+ * the bytes were dropped with the decoder and no counter existed.
582
+ */
583
+ droppedTailBytes: number;
584
+ }
541
585
  declare class SessionHostClient {
542
586
  readonly endpoint: SessionHostEndpoint;
543
587
  private socket;
544
588
  private requestWaiters;
545
589
  private eventListeners;
590
+ private disconnectListeners;
591
+ /** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
592
+ private disconnectedSockets;
546
593
  constructor(options?: SessionHostClientOptions);
594
+ /**
595
+ * Fires when an established connection to the session host goes away.
596
+ *
597
+ * Before this existed the client registered only 'data' and 'error' handlers,
598
+ * so a *clean* FIN — the host process exiting normally, or dying to an
599
+ * uncaught exception that took the socket down without an error event on our
600
+ * end — ran nothing at all: `this.socket` stayed non-null pointing at a dead
601
+ * socket, in-flight waiters hung to their 30s timeout, and no caller was told.
602
+ * That silence is what let a session-host death present downstream as an
603
+ * unrelated application-level fault (a missing completion marker) instead of
604
+ * "the host is gone".
605
+ */
606
+ onDisconnect(listener: (info: SessionHostDisconnectInfo) => void): () => void;
607
+ private handleDisconnect;
547
608
  connect(): Promise<void>;
548
609
  onEvent(listener: (event: SessionHostEvent) => void): () => void;
549
610
  request<T = unknown>(request: SessionHostRequest): Promise<SessionHostResponse<T>>;
@@ -683,4 +744,4 @@ interface SessionHostControlTransport {
683
744
  */
684
745
  declare function createSessionHostControlPlane(transport: SessionHostControlTransport): SessionHostControlPlane;
685
746
 
686
- export { type AcquireWritePayload, type AttachSessionPayload, type ClearSessionBufferPayload, type CreateSessionPayload, DEFAULT_CONFIG_DIR_NAME, DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, type DetachSessionPayload, type ForceDetachClientPayload, type GetHostDiagnosticsPayload, type GetSnapshotPayload, type GetTerminalSnapshotPayload, type PruneDuplicateSessionsPayload, type ReleaseWritePayload, type ResizeSessionPayload, type RestartSessionPayload, type ResumeSessionPayload, SESSION_HOST_SUPPORTED_REQUEST_TYPES, type SendInputPayload, type SendSignalPayload, type SessionAttachedClient, type SessionBufferSnapshot, type SessionClientType, type SessionHostCategory, SessionHostClient, type SessionHostClientOptions, type SessionHostControlPlane, type SessionHostControlTransport, type SessionHostDiagnostics, type SessionHostDuplicateSessionGroup, type SessionHostEndpoint, type SessionHostEndpointOptions, type SessionHostEvent, type SessionHostEventEnvelope, type SessionHostLogEntry, type SessionHostPruneDuplicatesResult, type SessionHostRecord, SessionHostRegistry, type SessionHostRequest, type SessionHostRequestEnvelope, type SessionHostRequestTrace, type SessionHostRequestType, type SessionHostResponse, type SessionHostResponseEnvelope, type SessionHostRuntimeTransition, type SessionHostSurfaceKind, type SessionHostSurfaceRecordLike, type SessionHostWireEnvelope, type SessionLaunchCommand, type SessionLifecycle, type SessionOwnerType, SessionRingBuffer, type SessionRingBufferOptions, type SessionTerminalSnapshot, type SessionTerminalState, type SessionTermination, type SessionTransport, type SessionWriteOwner, type StopSessionPayload, type UpdateSessionMetaPayload, applyTerminalColorEnv, buildRuntimeDisplayName, buildRuntimeKey, canonicalizeInstancePath, classifyTermination, createLineParser, createResponseEnvelope, createSessionHostControlPlane, ensureNodePtySpawnHelperPermissions, formatRuntimeOwner, getDefaultSessionHostEndpoint, getSessionHostRecoveryLabel, getSessionHostSurfaceKind, getWorkspaceLabel, isDefaultInstanceConfigDir, isSessionHostLiveRuntime, isSessionHostRecoverySnapshot, isTerminalRecord, partitionSessionHostDiagnosticsSessions, partitionSessionHostRecords, resolveAttachableRuntimeRecord, resolveInstanceConfigDir, resolveRuntimeRecord, resolveSessionHostIpcKey, sanitizeSpawnEnv, writeEnvelope };
747
+ export { type AcquireWritePayload, type AttachSessionPayload, type ClearSessionBufferPayload, type CreateSessionPayload, DEFAULT_CONFIG_DIR_NAME, DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, type DetachSessionPayload, type ForceDetachClientPayload, type GetHostDiagnosticsPayload, type GetSnapshotPayload, type GetTerminalSnapshotPayload, type PruneDuplicateSessionsPayload, type ReleaseWritePayload, type ResizeSessionPayload, type RestartSessionPayload, type ResumeSessionPayload, SESSION_HOST_SUPPORTED_REQUEST_TYPES, type SendInputPayload, type SendSignalPayload, type SessionAttachedClient, type SessionBufferSnapshot, type SessionClientType, type SessionHostCategory, SessionHostClient, type SessionHostClientOptions, type SessionHostControlPlane, type SessionHostControlTransport, type SessionHostDiagnostics, type SessionHostDisconnectInfo, type SessionHostDisconnectReason, type SessionHostDuplicateSessionGroup, type SessionHostEndpoint, type SessionHostEndpointOptions, type SessionHostEvent, type SessionHostEventEnvelope, type SessionHostLogEntry, type SessionHostPruneDuplicatesResult, type SessionHostRecord, SessionHostRegistry, type SessionHostRequest, type SessionHostRequestEnvelope, type SessionHostRequestTrace, type SessionHostRequestType, type SessionHostResponse, type SessionHostResponseEnvelope, type SessionHostRuntimeTransition, type SessionHostSurfaceKind, type SessionHostSurfaceRecordLike, type SessionHostWireEnvelope, type SessionLaunchCommand, type SessionLifecycle, type SessionOwnerType, SessionRingBuffer, type SessionRingBufferOptions, type SessionTerminalSnapshot, type SessionTerminalState, type SessionTermination, type SessionTransport, type SessionWriteOwner, type StopSessionPayload, type UpdateSessionMetaPayload, applyTerminalColorEnv, buildRuntimeDisplayName, buildRuntimeKey, canonicalizeInstancePath, classifyTermination, createLineParser, createResponseEnvelope, createSessionHostControlPlane, ensureNodePtySpawnHelperPermissions, formatRuntimeOwner, getDefaultSessionHostEndpoint, getSessionHostRecoveryLabel, getSessionHostSurfaceKind, getWorkspaceLabel, isDefaultInstanceConfigDir, isSessionHostLiveRuntime, isSessionHostRecoverySnapshot, isTerminalRecord, partitionSessionHostDiagnosticsSessions, partitionSessionHostRecords, resolveAttachableRuntimeRecord, resolveInstanceConfigDir, resolveRuntimeRecord, resolveSessionHostIpcKey, sanitizeSpawnEnv, writeEnvelope };
package/dist/index.d.ts CHANGED
@@ -533,17 +533,78 @@ interface SessionHostEndpointOptions {
533
533
  platform?: NodeJS.Platform;
534
534
  }
535
535
  declare function getDefaultSessionHostEndpoint(appName?: string, options?: SessionHostEndpointOptions): SessionHostEndpoint;
536
- declare function createLineParser(onEnvelope: (envelope: SessionHostWireEnvelope) => void): (chunk: Buffer | string) => void;
536
+ /**
537
+ * UTF8-CHUNK-BOUNDARY: decode the socket stream, never the individual chunk.
538
+ *
539
+ * This used to call `chunk.toString()` on every Buffer independently. A socket
540
+ * hands us arbitrary byte slices — a multi-byte UTF-8 sequence straddling two
541
+ * chunks gets decoded as two truncated sequences, and each half becomes U+FFFD.
542
+ * The damage is silent by construction: the replacement character is valid JSON
543
+ * string content, so the envelope still parses and only the *value* is wrong.
544
+ * A pasted 11,994-char Korean prompt lost exactly one character that way — the
545
+ * `도` beginning at wire offset 8190, split across the 8192-byte chunk boundary,
546
+ * arrived as `�착`.
547
+ *
548
+ * StringDecoder holds an incomplete trailing sequence back until the bytes that
549
+ * finish it arrive, which is the only correct way to turn a byte stream into
550
+ * text. String chunks bypass it: they are already decoded, and feeding them
551
+ * through `Buffer.from` would re-encode text the caller never asked us to touch.
552
+ */
553
+ declare function createLineParser(onEnvelope: (envelope: SessionHostWireEnvelope) => void): {
554
+ (chunk: Buffer | string): void;
555
+ end(): string;
556
+ };
537
557
  interface SessionHostClientOptions {
538
558
  endpoint?: SessionHostEndpoint;
539
559
  appName?: string;
540
560
  }
561
+ /**
562
+ * Why an established session-host connection went away.
563
+ * - `error` — socket emitted 'error' (includes ECONNRESET on abrupt host death)
564
+ * - `ended` — peer sent FIN ('end'): the host closed the connection cleanly
565
+ * - `closed` — socket fully closed ('close') without a preceding error/end
566
+ */
567
+ type SessionHostDisconnectReason = 'error' | 'ended' | 'closed';
568
+ interface SessionHostDisconnectInfo {
569
+ reason: SessionHostDisconnectReason;
570
+ endpointPath: string;
571
+ /** In-flight requests abandoned by this disconnect (they were rejected). */
572
+ pendingRequests: number;
573
+ error?: Error;
574
+ /**
575
+ * Bytes discarded from a newline-unterminated frame at EOF (0 when the peer
576
+ * hung up on a clean frame boundary, which is the normal case).
577
+ *
578
+ * Non-zero means the peer was cut off MID-WRITE — diagnostic context that
579
+ * distinguishes "the host exited" from "the host died with a frame in
580
+ * flight". Before the parser's `end()` was reachable this was unknowable:
581
+ * the bytes were dropped with the decoder and no counter existed.
582
+ */
583
+ droppedTailBytes: number;
584
+ }
541
585
  declare class SessionHostClient {
542
586
  readonly endpoint: SessionHostEndpoint;
543
587
  private socket;
544
588
  private requestWaiters;
545
589
  private eventListeners;
590
+ private disconnectListeners;
591
+ /** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
592
+ private disconnectedSockets;
546
593
  constructor(options?: SessionHostClientOptions);
594
+ /**
595
+ * Fires when an established connection to the session host goes away.
596
+ *
597
+ * Before this existed the client registered only 'data' and 'error' handlers,
598
+ * so a *clean* FIN — the host process exiting normally, or dying to an
599
+ * uncaught exception that took the socket down without an error event on our
600
+ * end — ran nothing at all: `this.socket` stayed non-null pointing at a dead
601
+ * socket, in-flight waiters hung to their 30s timeout, and no caller was told.
602
+ * That silence is what let a session-host death present downstream as an
603
+ * unrelated application-level fault (a missing completion marker) instead of
604
+ * "the host is gone".
605
+ */
606
+ onDisconnect(listener: (info: SessionHostDisconnectInfo) => void): () => void;
607
+ private handleDisconnect;
547
608
  connect(): Promise<void>;
548
609
  onEvent(listener: (event: SessionHostEvent) => void): () => void;
549
610
  request<T = unknown>(request: SessionHostRequest): Promise<SessionHostResponse<T>>;
@@ -683,4 +744,4 @@ interface SessionHostControlTransport {
683
744
  */
684
745
  declare function createSessionHostControlPlane(transport: SessionHostControlTransport): SessionHostControlPlane;
685
746
 
686
- export { type AcquireWritePayload, type AttachSessionPayload, type ClearSessionBufferPayload, type CreateSessionPayload, DEFAULT_CONFIG_DIR_NAME, DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, type DetachSessionPayload, type ForceDetachClientPayload, type GetHostDiagnosticsPayload, type GetSnapshotPayload, type GetTerminalSnapshotPayload, type PruneDuplicateSessionsPayload, type ReleaseWritePayload, type ResizeSessionPayload, type RestartSessionPayload, type ResumeSessionPayload, SESSION_HOST_SUPPORTED_REQUEST_TYPES, type SendInputPayload, type SendSignalPayload, type SessionAttachedClient, type SessionBufferSnapshot, type SessionClientType, type SessionHostCategory, SessionHostClient, type SessionHostClientOptions, type SessionHostControlPlane, type SessionHostControlTransport, type SessionHostDiagnostics, type SessionHostDuplicateSessionGroup, type SessionHostEndpoint, type SessionHostEndpointOptions, type SessionHostEvent, type SessionHostEventEnvelope, type SessionHostLogEntry, type SessionHostPruneDuplicatesResult, type SessionHostRecord, SessionHostRegistry, type SessionHostRequest, type SessionHostRequestEnvelope, type SessionHostRequestTrace, type SessionHostRequestType, type SessionHostResponse, type SessionHostResponseEnvelope, type SessionHostRuntimeTransition, type SessionHostSurfaceKind, type SessionHostSurfaceRecordLike, type SessionHostWireEnvelope, type SessionLaunchCommand, type SessionLifecycle, type SessionOwnerType, SessionRingBuffer, type SessionRingBufferOptions, type SessionTerminalSnapshot, type SessionTerminalState, type SessionTermination, type SessionTransport, type SessionWriteOwner, type StopSessionPayload, type UpdateSessionMetaPayload, applyTerminalColorEnv, buildRuntimeDisplayName, buildRuntimeKey, canonicalizeInstancePath, classifyTermination, createLineParser, createResponseEnvelope, createSessionHostControlPlane, ensureNodePtySpawnHelperPermissions, formatRuntimeOwner, getDefaultSessionHostEndpoint, getSessionHostRecoveryLabel, getSessionHostSurfaceKind, getWorkspaceLabel, isDefaultInstanceConfigDir, isSessionHostLiveRuntime, isSessionHostRecoverySnapshot, isTerminalRecord, partitionSessionHostDiagnosticsSessions, partitionSessionHostRecords, resolveAttachableRuntimeRecord, resolveInstanceConfigDir, resolveRuntimeRecord, resolveSessionHostIpcKey, sanitizeSpawnEnv, writeEnvelope };
747
+ export { type AcquireWritePayload, type AttachSessionPayload, type ClearSessionBufferPayload, type CreateSessionPayload, DEFAULT_CONFIG_DIR_NAME, DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, type DetachSessionPayload, type ForceDetachClientPayload, type GetHostDiagnosticsPayload, type GetSnapshotPayload, type GetTerminalSnapshotPayload, type PruneDuplicateSessionsPayload, type ReleaseWritePayload, type ResizeSessionPayload, type RestartSessionPayload, type ResumeSessionPayload, SESSION_HOST_SUPPORTED_REQUEST_TYPES, type SendInputPayload, type SendSignalPayload, type SessionAttachedClient, type SessionBufferSnapshot, type SessionClientType, type SessionHostCategory, SessionHostClient, type SessionHostClientOptions, type SessionHostControlPlane, type SessionHostControlTransport, type SessionHostDiagnostics, type SessionHostDisconnectInfo, type SessionHostDisconnectReason, type SessionHostDuplicateSessionGroup, type SessionHostEndpoint, type SessionHostEndpointOptions, type SessionHostEvent, type SessionHostEventEnvelope, type SessionHostLogEntry, type SessionHostPruneDuplicatesResult, type SessionHostRecord, SessionHostRegistry, type SessionHostRequest, type SessionHostRequestEnvelope, type SessionHostRequestTrace, type SessionHostRequestType, type SessionHostResponse, type SessionHostResponseEnvelope, type SessionHostRuntimeTransition, type SessionHostSurfaceKind, type SessionHostSurfaceRecordLike, type SessionHostWireEnvelope, type SessionLaunchCommand, type SessionLifecycle, type SessionOwnerType, SessionRingBuffer, type SessionRingBufferOptions, type SessionTerminalSnapshot, type SessionTerminalState, type SessionTermination, type SessionTransport, type SessionWriteOwner, type StopSessionPayload, type UpdateSessionMetaPayload, applyTerminalColorEnv, buildRuntimeDisplayName, buildRuntimeKey, canonicalizeInstancePath, classifyTermination, createLineParser, createResponseEnvelope, createSessionHostControlPlane, ensureNodePtySpawnHelperPermissions, formatRuntimeOwner, getDefaultSessionHostEndpoint, getSessionHostRecoveryLabel, getSessionHostSurfaceKind, getWorkspaceLabel, isDefaultInstanceConfigDir, isSessionHostLiveRuntime, isSessionHostRecoverySnapshot, isTerminalRecord, partitionSessionHostDiagnosticsSessions, partitionSessionHostRecords, resolveAttachableRuntimeRecord, resolveInstanceConfigDir, resolveRuntimeRecord, resolveSessionHostIpcKey, sanitizeSpawnEnv, writeEnvelope };
package/dist/index.js CHANGED
@@ -580,6 +580,7 @@ var SessionHostRegistry = class {
580
580
  var os = __toESM(require("os"));
581
581
  var path2 = __toESM(require("path"));
582
582
  var net = __toESM(require("net"));
583
+ var import_string_decoder = require("string_decoder");
583
584
  function generateUUID2() {
584
585
  if (typeof crypto !== "undefined" && crypto.randomUUID) {
585
586
  return crypto.randomUUID();
@@ -614,8 +615,9 @@ function serializeEnvelope(envelope) {
614
615
  }
615
616
  function createLineParser(onEnvelope) {
616
617
  let buffer = "";
617
- return (chunk) => {
618
- buffer += chunk.toString();
618
+ const decoder = new import_string_decoder.StringDecoder("utf8");
619
+ const parser = (chunk) => {
620
+ buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
619
621
  let newlineIndex = buffer.indexOf("\n");
620
622
  while (newlineIndex >= 0) {
621
623
  const rawLine = buffer.slice(0, newlineIndex).trim();
@@ -626,15 +628,85 @@ function createLineParser(onEnvelope) {
626
628
  newlineIndex = buffer.indexOf("\n");
627
629
  }
628
630
  };
631
+ parser.end = () => {
632
+ const remainder = buffer + decoder.end();
633
+ buffer = "";
634
+ return remainder;
635
+ };
636
+ return parser;
629
637
  }
638
+ var establishedSockets = /* @__PURE__ */ new WeakSet();
630
639
  var SessionHostClient = class {
631
640
  endpoint;
632
641
  socket = null;
633
642
  requestWaiters = /* @__PURE__ */ new Map();
634
643
  eventListeners = /* @__PURE__ */ new Set();
644
+ disconnectListeners = /* @__PURE__ */ new Set();
645
+ /** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
646
+ disconnectedSockets = /* @__PURE__ */ new WeakSet();
635
647
  constructor(options = {}) {
636
648
  this.endpoint = options.endpoint || getDefaultSessionHostEndpoint(options.appName || "adhdev");
637
649
  }
650
+ /**
651
+ * Fires when an established connection to the session host goes away.
652
+ *
653
+ * Before this existed the client registered only 'data' and 'error' handlers,
654
+ * so a *clean* FIN — the host process exiting normally, or dying to an
655
+ * uncaught exception that took the socket down without an error event on our
656
+ * end — ran nothing at all: `this.socket` stayed non-null pointing at a dead
657
+ * socket, in-flight waiters hung to their 30s timeout, and no caller was told.
658
+ * That silence is what let a session-host death present downstream as an
659
+ * unrelated application-level fault (a missing completion marker) instead of
660
+ * "the host is gone".
661
+ */
662
+ onDisconnect(listener) {
663
+ this.disconnectListeners.add(listener);
664
+ return () => {
665
+ this.disconnectListeners.delete(listener);
666
+ };
667
+ }
668
+ handleDisconnect(socket, reason, error, droppedTailBytes = 0) {
669
+ if (this.disconnectedSockets.has(socket)) return;
670
+ this.disconnectedSockets.add(socket);
671
+ const wasEstablished = establishedSockets.has(socket);
672
+ if (!wasEstablished) {
673
+ if (this.socket === socket) this.socket = null;
674
+ try {
675
+ socket.destroy();
676
+ } catch {
677
+ }
678
+ const failure2 = error || new Error(`Session host connect failed (${this.endpoint.path})`);
679
+ for (const waiter of this.requestWaiters.values()) waiter.reject(failure2);
680
+ this.requestWaiters.clear();
681
+ return;
682
+ }
683
+ const pendingRequests = this.requestWaiters.size;
684
+ const failure = error || new Error(`Session host connection ${reason} (${this.endpoint.path})`);
685
+ for (const waiter of this.requestWaiters.values()) {
686
+ waiter.reject(failure);
687
+ }
688
+ this.requestWaiters.clear();
689
+ if (this.socket === socket) {
690
+ this.socket = null;
691
+ }
692
+ try {
693
+ socket.destroy();
694
+ } catch {
695
+ }
696
+ const info = {
697
+ reason,
698
+ endpointPath: this.endpoint.path,
699
+ pendingRequests,
700
+ error,
701
+ droppedTailBytes
702
+ };
703
+ for (const listener of this.disconnectListeners) {
704
+ try {
705
+ listener(info);
706
+ } catch {
707
+ }
708
+ }
709
+ }
638
710
  async connect() {
639
711
  if (this.socket && !this.socket.destroyed) return;
640
712
  if (this.socket) {
@@ -646,7 +718,7 @@ var SessionHostClient = class {
646
718
  }
647
719
  const socket = net.createConnection(this.endpoint.path);
648
720
  this.socket = socket;
649
- socket.on("data", createLineParser((envelope) => {
721
+ const parser = createLineParser((envelope) => {
650
722
  if (envelope.kind === "response") {
651
723
  const waiter = this.requestWaiters.get(envelope.requestId);
652
724
  if (waiter) {
@@ -658,22 +730,30 @@ var SessionHostClient = class {
658
730
  if (envelope.kind === "event") {
659
731
  for (const listener of this.eventListeners) listener(envelope.event);
660
732
  }
661
- }));
662
- socket.on("error", (error) => {
663
- for (const waiter of this.requestWaiters.values()) {
664
- waiter.reject(error);
665
- }
666
- this.requestWaiters.clear();
667
- if (this.socket === socket) {
668
- this.socket = null;
669
- }
733
+ });
734
+ socket.on("data", parser);
735
+ const flushParser = () => {
670
736
  try {
671
- socket.destroy();
737
+ return parser.end();
672
738
  } catch {
739
+ return "";
673
740
  }
741
+ };
742
+ socket.on("error", (error) => {
743
+ const remainder = flushParser();
744
+ this.handleDisconnect(socket, "error", error, remainder.length);
745
+ });
746
+ socket.on("close", () => {
747
+ this.handleDisconnect(socket, "closed", void 0, flushParser().length);
748
+ });
749
+ socket.on("end", () => {
750
+ this.handleDisconnect(socket, "ended", void 0, flushParser().length);
674
751
  });
675
752
  await new Promise((resolve3, reject) => {
676
- socket.once("connect", () => resolve3());
753
+ socket.once("connect", () => {
754
+ establishedSockets.add(socket);
755
+ resolve3();
756
+ });
677
757
  socket.once("error", reject);
678
758
  });
679
759
  }
@@ -715,6 +795,7 @@ var SessionHostClient = class {
715
795
  if (!this.socket) return;
716
796
  const socket = this.socket;
717
797
  this.socket = null;
798
+ this.disconnectedSockets.add(socket);
718
799
  for (const waiter of this.requestWaiters.values()) {
719
800
  waiter.reject(new Error("Session host client closed"));
720
801
  }
@@ -804,6 +885,8 @@ function sanitizeSpawnEnv(baseEnv, overrides) {
804
885
  delete env.CODEX_SANDBOX_NETWORK_DISABLED;
805
886
  delete env.NO_COLOR;
806
887
  delete env.COLOR;
888
+ delete env.COLUMNS;
889
+ delete env.LINES;
807
890
  delete env.CLAUDECODE;
808
891
  delete env.CLAUDE_CODE_CHILD_SESSION;
809
892
  delete env.CLAUDE_CODE_ENTRYPOINT;