@adhdev/session-host-core 1.0.82-rc.13 → 1.0.82-rc.131

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.mjs CHANGED
@@ -12,11 +12,18 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
12
12
  "release_upgrade_lease",
13
13
  "create_session",
14
14
  "attach_session",
15
+ // Distinct request kind: old hosts must refuse instead of ignoring a pin.
16
+ "attach_session_if_incarnation",
15
17
  "detach_session",
16
18
  "send_input",
19
+ "send_input_if_seq",
20
+ "get_input_state",
17
21
  "resize_session",
18
22
  "stop_session",
23
+ "stop_session_if_expected",
24
+ "stop_mesh_writer",
19
25
  "delete_session",
26
+ "delete_session_if_expected",
20
27
  "resume_session",
21
28
  "acquire_write",
22
29
  "release_write",
@@ -29,9 +36,76 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
29
36
  "send_signal",
30
37
  "restart_session",
31
38
  "prune_duplicate_sessions",
39
+ "get_session_census",
40
+ "get_session",
32
41
  "list_sessions"
33
42
  ];
34
43
 
44
+ // src/cleanup-expected.ts
45
+ var CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX = "cleanup_after_stop_side_effect:";
46
+ function tagCleanupAfterStopSideEffect(code) {
47
+ return `${CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX}${code}`;
48
+ }
49
+ function stripCleanupAfterStopSideEffect(raw) {
50
+ if (raw.startsWith(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX)) {
51
+ return { afterStop: true, code: raw.slice(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX.length) };
52
+ }
53
+ return { afterStop: false, code: raw };
54
+ }
55
+ function hostBootIdFromStartedAt(hostStartedAt) {
56
+ return `hs:${hostStartedAt}`;
57
+ }
58
+ function resolveHostBootId(opts) {
59
+ if (typeof opts.upgradeBootId === "string" && opts.upgradeBootId) return opts.upgradeBootId;
60
+ if (!Number.isFinite(opts.hostStartedAt) || opts.hostStartedAt <= 0) return null;
61
+ return hostBootIdFromStartedAt(opts.hostStartedAt);
62
+ }
63
+ function refuseCleanupExpectedIdentity(record, expected, currentHostBootId) {
64
+ if (!expected || expected.sessionId !== (record?.sessionId ?? "") || typeof expected.hostBootId !== "string" || !expected.hostBootId || typeof expected.runtimeKey !== "string" || !expected.runtimeKey || !Number.isSafeInteger(expected.startedAt) || expected.startedAt <= 0) {
65
+ return "cleanup_expected_malformed";
66
+ }
67
+ if (!currentHostBootId) return "cleanup_host_boot_unknown";
68
+ if (expected.hostBootId !== currentHostBootId) return "cleanup_host_boot_mismatch";
69
+ if (!record) return "cleanup_session_not_running";
70
+ if (record.runtimeKey !== expected.runtimeKey || record.startedAt !== expected.startedAt) {
71
+ return "cleanup_native_incarnation_mismatch";
72
+ }
73
+ return null;
74
+ }
75
+ function refuseCleanupExpectedAssignment(record, expected, opts = {}) {
76
+ const active = record.meta?.meshActiveAssignment;
77
+ if (expected.taskId === null) {
78
+ if (active && typeof active.taskId === "string" && active.taskId) return "cleanup_expected_unbound_now_bound";
79
+ return null;
80
+ }
81
+ if (!active || typeof active.taskId !== "string" || !active.taskId) {
82
+ return opts.allowClearedBound ? null : "cleanup_expected_bound_now_unbound";
83
+ }
84
+ if (active.taskId !== expected.taskId || active.attemptId !== expected.attemptId || active.generation !== expected.generation || active.dispatchNonce !== expected.dispatchNonce) {
85
+ return "cleanup_assignment_mismatch";
86
+ }
87
+ return null;
88
+ }
89
+ function refuseCleanupExpectedStop(record, expected, currentHostBootId, hasRuntime) {
90
+ const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
91
+ if (identity) return identity;
92
+ if (!record || record.termination || !hasRuntime || record.lifecycle !== "running") {
93
+ return "cleanup_session_not_running";
94
+ }
95
+ return refuseCleanupExpectedAssignment(record, expected);
96
+ }
97
+ function refuseCleanupExpectedDelete(record, expected, currentHostBootId, hasRuntime, force) {
98
+ if (!record) return "cleanup_session_not_running";
99
+ const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
100
+ if (identity) return identity;
101
+ if (hasRuntime) {
102
+ if (!force) return "cleanup_session_still_running";
103
+ if (record.termination || record.lifecycle !== "running") return "cleanup_session_not_running";
104
+ return refuseCleanupExpectedAssignment(record, expected);
105
+ }
106
+ return refuseCleanupExpectedAssignment(record, expected, { allowClearedBound: true });
107
+ }
108
+
35
109
  // src/termination.ts
36
110
  function classifyTermination(input) {
37
111
  const { exitCode, terminatedAt } = input;
@@ -65,6 +139,72 @@ function classifyTermination(input) {
65
139
  return termination;
66
140
  }
67
141
 
142
+ // src/cli-child-priority.ts
143
+ import * as fs from "fs";
144
+ import * as os from "os";
145
+
146
+ // src/process/hidden-spawn.ts
147
+ import { spawn } from "child_process";
148
+ function hiddenSpawn(command, args = [], options = {}) {
149
+ return spawn(command, args, { windowsHide: true, ...options });
150
+ }
151
+
152
+ // src/cli-child-priority.ts
153
+ var CLI_CHILD_NICE_INCREMENT = 10;
154
+ var CLI_CHILD_NICE_ENV = "ADHDEV_CLI_CHILD_NICE";
155
+ var CLI_CHILD_SCHEDULING_ENV = "ADHDEV_CLI_CHILD_SCHEDULING";
156
+ function setDarwinBackground(pid, onFailure) {
157
+ const task = hiddenSpawn("/usr/sbin/taskpolicy", ["-b", "-p", String(pid)], { stdio: "ignore" });
158
+ task.once("error", onFailure);
159
+ task.once("exit", (code, signal) => {
160
+ if (code !== 0) onFailure(new Error(`taskpolicy exited with ${signal ?? code}`));
161
+ });
162
+ }
163
+ var POSIX_NICE_BINARY = "/usr/bin/nice";
164
+ function niceLaunch(command, args, env = process.env, platform2 = process.platform, niceAvailable = () => fs.existsSync(POSIX_NICE_BINARY)) {
165
+ if (env[CLI_CHILD_NICE_ENV] === "0" || platform2 !== "darwin" && platform2 !== "linux" || !command || !niceAvailable()) {
166
+ return { command, args: [...args], preApplied: false };
167
+ }
168
+ return { command: POSIX_NICE_BINARY, args: ["-n", String(CLI_CHILD_NICE_INCREMENT), command, ...args], preApplied: true };
169
+ }
170
+ function createCliChildPriorityPolicy(deps = {
171
+ platform: process.platform,
172
+ getPriority: os.getPriority,
173
+ setPriority: os.setPriority,
174
+ setDarwinBackground
175
+ }) {
176
+ let failureLogged = false;
177
+ return function spawnCliChild2(spawnChild, env = process.env, logInfo = console.info, opts = {}) {
178
+ const child = spawnChild();
179
+ const pid = child.pid;
180
+ if (env[CLI_CHILD_NICE_ENV] === "0" || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return child;
181
+ const onFailure = (error) => {
182
+ if (!failureLogged) {
183
+ failureLogged = true;
184
+ const detail = error instanceof Error ? error.message : String(error);
185
+ logInfo(`[cli-child-priority] Could not apply CLI child scheduling (pid ${pid}); continuing: ${detail}`);
186
+ }
187
+ };
188
+ if (!opts.preApplied) {
189
+ try {
190
+ const priority = deps.platform === "win32" ? os.constants.priority.PRIORITY_BELOW_NORMAL : Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
191
+ deps.setPriority(pid, priority);
192
+ } catch (error) {
193
+ onFailure(error);
194
+ }
195
+ }
196
+ if (deps.platform === "darwin" && env[CLI_CHILD_SCHEDULING_ENV] === "darwin-bg") {
197
+ try {
198
+ deps.setDarwinBackground?.(pid, onFailure);
199
+ } catch (error) {
200
+ onFailure(error);
201
+ }
202
+ }
203
+ return child;
204
+ };
205
+ }
206
+ var spawnCliChild = createCliChildPriorityPolicy();
207
+
68
208
  // src/buffer.ts
69
209
  var DEFAULT_SESSION_RING_BUFFER_MAX_BYTES = 4 * 1024 * 1024;
70
210
  var SessionRingBuffer = class {
@@ -401,6 +541,13 @@ function formatRuntimeOwner(record) {
401
541
  // src/registry.ts
402
542
  var SessionHostRegistry = class {
403
543
  sessions = /* @__PURE__ */ new Map();
544
+ /** This registry's lifetime; every inputEpoch it mints starts with it. */
545
+ lifetimeId = generateUUID();
546
+ epochCounter = 0;
547
+ mintInputEpoch() {
548
+ this.epochCounter += 1;
549
+ return `${this.lifetimeId}:${this.epochCounter}`;
550
+ }
404
551
  createSession(payload) {
405
552
  const sessionId = payload.sessionId || generateUUID();
406
553
  if (this.sessions.has(sessionId)) {
@@ -432,6 +579,8 @@ var SessionHostRegistry = class {
432
579
  lifecycle: "starting",
433
580
  writeOwner: null,
434
581
  attachedClients: initialClient,
582
+ inputSeq: 0,
583
+ inputEpoch: this.mintInputEpoch(),
435
584
  buffer: {
436
585
  scrollbackBytes: 0,
437
586
  snapshotSeq: 0
@@ -451,6 +600,10 @@ var SessionHostRegistry = class {
451
600
  }
452
601
  restoreSession(record, snapshot) {
453
602
  const cloned = this.cloneRecord(record);
603
+ if (typeof cloned.inputSeq !== "number") cloned.inputSeq = 0;
604
+ const live = this.sessions.get(cloned.sessionId)?.record;
605
+ const sameLifetime = !!live && typeof live.inputEpoch === "string" && cloned.inputEpoch === live.inputEpoch && cloned.inputSeq >= (live.inputSeq ?? 0);
606
+ if (!sameLifetime) cloned.inputEpoch = this.mintInputEpoch();
454
607
  this.sessions.set(cloned.sessionId, {
455
608
  record: cloned,
456
609
  buffer: (() => {
@@ -461,13 +614,50 @@ var SessionHostRegistry = class {
461
614
  });
462
615
  return this.cloneRecord(cloned);
463
616
  }
617
+ /** Census projection: omit launch arguments/environment and summarize stopped
618
+ * sessions. Full details remain available through getSession. */
619
+ listSessionSummaries(activeOnly = false) {
620
+ return Array.from(this.sessions.values()).map((s) => s.record).filter((r) => !activeOnly || !r.termination && r.lifecycle !== "stopped" && r.lifecycle !== "failed").map((r) => this.cloneRecord({
621
+ ...r,
622
+ launchCommand: { command: r.launchCommand.command, args: [] },
623
+ meta: r.termination || r.lifecycle === "stopped" || r.lifecycle === "failed" ? {} : { ...r.meta, cliArgs: [], cliArgsOmitted: true }
624
+ })).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
625
+ }
464
626
  listSessions() {
465
627
  return Array.from(this.sessions.values()).map((state) => this.cloneRecord(state.record)).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
466
628
  }
629
+ /** No launch bodies are cloned. Unknown role evidence stays conservative. */
630
+ getSessionCensus(sessionIds) {
631
+ if (!Array.isArray(sessionIds) || sessionIds.length > 128 || sessionIds.some((id) => typeof id !== "string" || id.length === 0 || id.length > 256)) {
632
+ throw new Error("Invalid session census: at most 128 identities of 256 characters");
633
+ }
634
+ const requested = new Set(sessionIds);
635
+ const liveSessionIds = [];
636
+ let hasOtherAssistantCandidates = false;
637
+ for (const { record } of this.sessions.values()) {
638
+ if (record.category !== "cli" || record.termination || !["starting", "running", "stopping", "interrupted"].includes(record.lifecycle)) continue;
639
+ if (requested.has(record.sessionId)) liveSessionIds.push(record.sessionId);
640
+ else {
641
+ const launch = record.meta?.launchRecord;
642
+ if (record.meta?.assistant === true || launch?.launchedBy === "assistant" || launch?.roleLaunch?.role === "assistant") {
643
+ hasOtherAssistantCandidates = true;
644
+ }
645
+ }
646
+ }
647
+ return { liveSessionIds, hasOtherAssistantCandidates };
648
+ }
467
649
  getSession(sessionId) {
468
650
  const state = this.sessions.get(sessionId);
469
651
  return state ? this.cloneRecord(state.record) : null;
470
652
  }
653
+ attachClientIfIncarnation(payload) {
654
+ const record = this.requireSession(payload.sessionId).record;
655
+ const expected = payload.expectedIncarnation;
656
+ if (!expected || expected.sessionId !== record.sessionId || typeof expected.runtimeKey !== "string" || !expected.runtimeKey || !Number.isFinite(expected.startedAt) || expected.startedAt <= 0 || expected.runtimeKey !== record.runtimeKey || expected.startedAt !== record.startedAt) {
657
+ throw new Error(`Runtime not found for session: ${payload.sessionId} (incarnation changed)`);
658
+ }
659
+ return this.attachClient(payload);
660
+ }
471
661
  attachClient(payload) {
472
662
  const state = this.requireSession(payload.sessionId);
473
663
  const now = Date.now();
@@ -512,6 +702,20 @@ var SessionHostRegistry = class {
512
702
  state.record.lastActivityAt = Date.now();
513
703
  return this.cloneRecord(state.record);
514
704
  }
705
+ /** Count one accepted input (see SessionHostRecord.inputSeq); returns its number. */
706
+ recordInput(sessionId) {
707
+ const state = this.requireSession(sessionId);
708
+ state.record.inputSeq = (typeof state.record.inputSeq === "number" ? state.record.inputSeq : 0) + 1;
709
+ if (typeof state.record.inputEpoch !== "string") state.record.inputEpoch = this.mintInputEpoch();
710
+ return state.record.inputSeq;
711
+ }
712
+ /** The current input counter (see SessionHostInputState). */
713
+ getInputState(sessionId) {
714
+ const state = this.requireSession(sessionId);
715
+ if (typeof state.record.inputSeq !== "number") state.record.inputSeq = 0;
716
+ if (typeof state.record.inputEpoch !== "string") state.record.inputEpoch = this.mintInputEpoch();
717
+ return { inputSeq: state.record.inputSeq, inputEpoch: state.record.inputEpoch };
718
+ }
515
719
  acquireWrite(payload) {
516
720
  const state = this.requireSession(payload.sessionId);
517
721
  if (state.record.writeOwner && state.record.writeOwner.clientId !== payload.clientId && !payload.force) {
@@ -628,10 +832,19 @@ function cloneMeta(meta) {
628
832
  }
629
833
 
630
834
  // src/ipc.ts
631
- import * as os from "os";
835
+ import * as os2 from "os";
632
836
  import * as path2 from "path";
633
837
  import * as net from "net";
838
+ import { createHash } from "crypto";
634
839
  import { StringDecoder } from "string_decoder";
840
+ function validateSessionHostEndpoint(endpoint, platform2 = process.platform) {
841
+ if (endpoint.kind !== "unix") return;
842
+ const limit = platform2 === "linux" ? 108 : 104;
843
+ const pathBytes = Buffer.byteLength(endpoint.path, "utf8");
844
+ if (pathBytes + 1 > limit) {
845
+ throw new Error(`session_host_unix_socket_path_too_long: path_bytes=${pathBytes} required_bytes=${pathBytes + 1} limit_bytes=${limit} platform=${platform2}`);
846
+ }
847
+ }
635
848
  function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
636
849
  const rawKey = typeof options.ipcKey === "string" ? options.ipcKey.trim() : "";
637
850
  if (rawKey && !/^[0-9a-f]{12}$/.test(rawKey)) {
@@ -645,48 +858,102 @@ function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
645
858
  path: `\\\\.\\pipe\\${appName}-session-host${suffix}`
646
859
  };
647
860
  }
648
- return {
861
+ const endpoint = {
649
862
  kind: "unix",
650
- path: path2.join(os.tmpdir(), `${appName}-session-host${suffix}.sock`)
863
+ path: path2.join(options.tmpDir ?? os2.tmpdir(), `${appName}-session-host${suffix}.sock`)
651
864
  };
865
+ const limit = platform2 === "linux" ? 108 : 104;
866
+ if (Buffer.byteLength(endpoint.path, "utf8") + 1 <= limit) return endpoint;
867
+ const identity = JSON.stringify([endpoint.path, appName, rawKey, process.getuid?.() ?? null]);
868
+ const digest = createHash("sha256").update(identity, "utf8").digest("hex");
869
+ const shortened = { kind: "unix", path: `/tmp/adhdev-sh-${digest}.sock` };
870
+ validateSessionHostEndpoint(shortened, platform2);
871
+ return shortened;
652
872
  }
653
873
  function serializeEnvelope(envelope) {
654
874
  return `${JSON.stringify(envelope)}
655
875
  `;
656
876
  }
657
877
  function createLineParser(onEnvelope) {
658
- let buffer = "";
878
+ let fragments = [];
659
879
  const decoder = new StringDecoder("utf8");
660
880
  const parser = (chunk) => {
661
- buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
662
- let newlineIndex = buffer.indexOf("\n");
663
- while (newlineIndex >= 0) {
664
- const rawLine = buffer.slice(0, newlineIndex).trim();
665
- buffer = buffer.slice(newlineIndex + 1);
666
- if (rawLine) {
667
- onEnvelope(JSON.parse(rawLine));
881
+ const text = typeof chunk === "string" ? chunk : decoder.write(chunk);
882
+ let start = 0;
883
+ for (; ; ) {
884
+ const newline = text.indexOf("\n", start);
885
+ if (newline < 0) {
886
+ if (start < text.length) fragments.push(text.slice(start));
887
+ break;
668
888
  }
669
- newlineIndex = buffer.indexOf("\n");
889
+ fragments.push(text.slice(start, newline));
890
+ const rawLine = fragments.join("").trim();
891
+ fragments = [];
892
+ start = newline + 1;
893
+ if (rawLine) onEnvelope(JSON.parse(rawLine));
670
894
  }
671
895
  };
672
896
  parser.end = () => {
673
- const remainder = buffer + decoder.end();
674
- buffer = "";
897
+ const remainder = fragments.join("") + decoder.end();
898
+ fragments = [];
675
899
  return remainder;
676
900
  };
677
901
  return parser;
678
902
  }
679
903
  var establishedSockets = /* @__PURE__ */ new WeakSet();
904
+ var activeClientRefs = /* @__PURE__ */ new Set();
905
+ function disconnectSessionHostClients(endpoint, error) {
906
+ for (const ref of activeClientRefs) {
907
+ const client = ref.deref();
908
+ if (!client) {
909
+ activeClientRefs.delete(ref);
910
+ continue;
911
+ }
912
+ if (!endpoint || client.endpoint.path === endpoint.path) {
913
+ client.disconnect(error);
914
+ }
915
+ }
916
+ }
917
+ function findConnectedSessionHostClient(endpoint) {
918
+ for (const ref of activeClientRefs) {
919
+ const client = ref.deref();
920
+ if (!client) {
921
+ activeClientRefs.delete(ref);
922
+ continue;
923
+ }
924
+ if ((!endpoint || client.endpoint.path === endpoint.path) && client.isConnected()) {
925
+ return client;
926
+ }
927
+ }
928
+ return null;
929
+ }
680
930
  var SessionHostClient = class {
681
931
  endpoint;
682
932
  socket = null;
933
+ connectPromise = null;
934
+ requestTimeoutMs = 3e4;
683
935
  requestWaiters = /* @__PURE__ */ new Map();
684
936
  eventListeners = /* @__PURE__ */ new Set();
685
937
  disconnectListeners = /* @__PURE__ */ new Set();
686
938
  /** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
687
939
  disconnectedSockets = /* @__PURE__ */ new WeakSet();
940
+ /** Session subscriptions established via create_session/attach_session, replayed automatically on reconnect. */
941
+ attachedSessions = /* @__PURE__ */ new Map();
688
942
  constructor(options = {}) {
689
943
  this.endpoint = options.endpoint || getDefaultSessionHostEndpoint(options.appName || "adhdev");
944
+ if (typeof options.requestTimeoutMs === "number" && options.requestTimeoutMs > 0) {
945
+ this.requestTimeoutMs = options.requestTimeoutMs;
946
+ }
947
+ if (options.registerAsShared !== false) activeClientRefs.add(new WeakRef(this));
948
+ }
949
+ static disconnectClients(endpoint, error) {
950
+ disconnectSessionHostClients(endpoint, error);
951
+ }
952
+ static findConnectedClient(endpoint) {
953
+ return findConnectedSessionHostClient(endpoint);
954
+ }
955
+ isConnected() {
956
+ return Boolean(this.socket && !this.socket.destroyed && establishedSockets.has(this.socket));
690
957
  }
691
958
  /**
692
959
  * Fires when an established connection to the session host goes away.
@@ -729,6 +996,7 @@ var SessionHostClient = class {
729
996
  this.requestWaiters.clear();
730
997
  if (this.socket === socket) {
731
998
  this.socket = null;
999
+ this.connectPromise = null;
732
1000
  }
733
1001
  try {
734
1002
  socket.destroy();
@@ -748,8 +1016,53 @@ var SessionHostClient = class {
748
1016
  }
749
1017
  }
750
1018
  }
751
- async connect() {
752
- if (this.socket && !this.socket.destroyed) return;
1019
+ sendRawRequestOnSocket(socket, request, timeoutMs = this.requestTimeoutMs) {
1020
+ const requestId = generateUUID();
1021
+ const envelope = {
1022
+ kind: "request",
1023
+ requestId,
1024
+ request
1025
+ };
1026
+ const timeoutLabel = timeoutMs % 1e3 === 0 ? `${timeoutMs / 1e3}s` : `${timeoutMs}ms`;
1027
+ const startedAt = Date.now();
1028
+ const startedMonotonicAt = performance.now();
1029
+ return new Promise((resolve3, reject) => {
1030
+ const timeout = setTimeout(() => {
1031
+ const actualElapsedMs = Math.max(0, Math.round(performance.now() - startedMonotonicAt));
1032
+ const wallElapsedMs = Math.max(0, Date.now() - startedAt);
1033
+ const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
1034
+ const timeoutError = Object.assign(
1035
+ new Error(`Session host request timed out after ${timeoutLabel} (${request.type})`),
1036
+ {
1037
+ code: "SESSION_HOST_REQUEST_TIMEOUT",
1038
+ requestType: request.type,
1039
+ scheduledTimeoutMs: timeoutMs,
1040
+ actualElapsedMs,
1041
+ wallElapsedMs,
1042
+ observerLagMs
1043
+ }
1044
+ );
1045
+ this.requestWaiters.delete(requestId);
1046
+ reject(timeoutError);
1047
+ }, timeoutMs);
1048
+ this.requestWaiters.set(requestId, {
1049
+ resolve: (value) => {
1050
+ clearTimeout(timeout);
1051
+ resolve3(value);
1052
+ },
1053
+ reject: (error) => {
1054
+ clearTimeout(timeout);
1055
+ reject(error);
1056
+ }
1057
+ });
1058
+ socket.write(serializeEnvelope(envelope));
1059
+ });
1060
+ }
1061
+ async connect(timeoutMs = this.requestTimeoutMs) {
1062
+ if (this.socket && !this.socket.destroyed) {
1063
+ if (this.connectPromise) await this.connectPromise;
1064
+ return;
1065
+ }
753
1066
  if (this.socket) {
754
1067
  try {
755
1068
  this.socket.destroy();
@@ -757,6 +1070,7 @@ var SessionHostClient = class {
757
1070
  }
758
1071
  this.socket = null;
759
1072
  }
1073
+ this.connectPromise = null;
760
1074
  const socket = net.createConnection(this.endpoint.path);
761
1075
  this.socket = socket;
762
1076
  const parser = createLineParser((envelope) => {
@@ -769,7 +1083,12 @@ var SessionHostClient = class {
769
1083
  return;
770
1084
  }
771
1085
  if (envelope.kind === "event") {
772
- for (const listener of this.eventListeners) listener(envelope.event);
1086
+ for (const listener of this.eventListeners) {
1087
+ try {
1088
+ listener(envelope.event);
1089
+ } catch {
1090
+ }
1091
+ }
773
1092
  }
774
1093
  });
775
1094
  socket.on("data", parser);
@@ -790,13 +1109,68 @@ var SessionHostClient = class {
790
1109
  socket.on("end", () => {
791
1110
  this.handleDisconnect(socket, "ended", void 0, flushParser().length);
792
1111
  });
793
- await new Promise((resolve3, reject) => {
794
- socket.once("connect", () => {
795
- establishedSockets.add(socket);
796
- resolve3();
1112
+ const connectTask = (async () => {
1113
+ await new Promise((resolve3, reject) => {
1114
+ const cleanup = () => {
1115
+ clearTimeout(timer);
1116
+ socket.off("connect", connected);
1117
+ socket.off("error", failed);
1118
+ socket.off("close", closed);
1119
+ };
1120
+ const connected = () => {
1121
+ cleanup();
1122
+ establishedSockets.add(socket);
1123
+ resolve3();
1124
+ };
1125
+ const failed = (error) => {
1126
+ cleanup();
1127
+ reject(error);
1128
+ };
1129
+ const closed = () => failed(new Error("Session host connection closed before connect"));
1130
+ const connectStartedAt = Date.now();
1131
+ const connectStartedMonotonicAt = performance.now();
1132
+ const timer = setTimeout(() => {
1133
+ const actualElapsedMs = Math.max(0, Math.round(performance.now() - connectStartedMonotonicAt));
1134
+ const wallElapsedMs = Math.max(0, Date.now() - connectStartedAt);
1135
+ const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
1136
+ const error = Object.assign(
1137
+ new Error(`Session host connect timed out after ${timeoutMs}ms`),
1138
+ {
1139
+ code: "SESSION_HOST_CONNECT_TIMEOUT",
1140
+ scheduledTimeoutMs: timeoutMs,
1141
+ actualElapsedMs,
1142
+ wallElapsedMs,
1143
+ observerLagMs
1144
+ }
1145
+ );
1146
+ failed(error);
1147
+ if (this.socket === socket) this.disconnect(error);
1148
+ }, timeoutMs);
1149
+ socket.once("connect", connected);
1150
+ socket.once("error", failed);
1151
+ socket.once("close", closed);
797
1152
  });
798
- socket.once("error", reject);
799
- });
1153
+ if (this.attachedSessions.size > 0 && this.socket === socket && !socket.destroyed) {
1154
+ for (const [sessionId, sub] of [...this.attachedSessions.entries()]) {
1155
+ if (this.socket !== socket || socket.destroyed) break;
1156
+ const replayResponse = await this.sendRawRequestOnSocket(socket, {
1157
+ type: "attach_session",
1158
+ payload: sub
1159
+ }).catch(() => null);
1160
+ if (replayResponse && !replayResponse.success) {
1161
+ this.attachedSessions.delete(sessionId);
1162
+ }
1163
+ }
1164
+ }
1165
+ })();
1166
+ this.connectPromise = connectTask;
1167
+ try {
1168
+ await connectTask;
1169
+ } finally {
1170
+ if (this.connectPromise === connectTask) {
1171
+ this.connectPromise = null;
1172
+ }
1173
+ }
800
1174
  }
801
1175
  onEvent(listener) {
802
1176
  this.eventListeners.add(listener);
@@ -804,35 +1178,86 @@ var SessionHostClient = class {
804
1178
  this.eventListeners.delete(listener);
805
1179
  };
806
1180
  }
807
- async request(request) {
808
- await this.connect();
809
- if (!this.socket) throw new Error("Session host socket unavailable");
810
- const requestId = generateUUID();
811
- const envelope = {
812
- kind: "request",
813
- requestId,
814
- request
815
- };
816
- const response = await new Promise((resolve3, reject) => {
817
- const timeout = setTimeout(() => {
818
- this.requestWaiters.delete(requestId);
819
- reject(new Error(`Session host request timed out after 30s (${request.type})`));
820
- }, 3e4);
821
- this.requestWaiters.set(requestId, {
822
- resolve: (value) => {
823
- clearTimeout(timeout);
824
- resolve3(value);
825
- },
826
- reject: (error) => {
827
- clearTimeout(timeout);
828
- reject(error);
1181
+ async request(request, options = {}) {
1182
+ const timeoutMs = Math.max(1, options.timeoutMs ?? this.requestTimeoutMs);
1183
+ const deadline = Date.now() + timeoutMs;
1184
+ const alreadyConnected = this.isConnected() && !this.connectPromise;
1185
+ if (options.timeoutMs !== void 0) {
1186
+ let timer;
1187
+ const raceStartedAt = Date.now();
1188
+ const raceStartedMonotonicAt = performance.now();
1189
+ try {
1190
+ await Promise.race([
1191
+ this.connect(),
1192
+ new Promise((_resolve, reject) => {
1193
+ timer = setTimeout(() => {
1194
+ const actualElapsedMs = Math.max(0, Math.round(performance.now() - raceStartedMonotonicAt));
1195
+ const wallElapsedMs = Math.max(0, Date.now() - raceStartedAt);
1196
+ const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
1197
+ const error = Object.assign(
1198
+ new Error(`Session host connect timed out after ${timeoutMs}ms`),
1199
+ {
1200
+ code: "SESSION_HOST_CONNECT_TIMEOUT",
1201
+ scheduledTimeoutMs: timeoutMs,
1202
+ actualElapsedMs,
1203
+ wallElapsedMs,
1204
+ observerLagMs
1205
+ }
1206
+ );
1207
+ reject(error);
1208
+ }, timeoutMs);
1209
+ })
1210
+ ]);
1211
+ } finally {
1212
+ if (timer) clearTimeout(timer);
1213
+ }
1214
+ } else {
1215
+ await this.connect(timeoutMs);
1216
+ }
1217
+ const requestSocket = this.socket;
1218
+ if (!requestSocket) throw new Error("Session host socket unavailable");
1219
+ const response = await this.sendRawRequestOnSocket(requestSocket, request, options.timeoutMs === void 0 || alreadyConnected ? timeoutMs : Math.max(1, deadline - Date.now()));
1220
+ if (response.success) {
1221
+ if (request.type === "attach_session") {
1222
+ this.attachedSessions.set(request.payload.sessionId, {
1223
+ sessionId: request.payload.sessionId,
1224
+ clientId: request.payload.clientId,
1225
+ clientType: request.payload.clientType,
1226
+ readOnly: request.payload.readOnly === true
1227
+ });
1228
+ } else if (request.type === "create_session") {
1229
+ const createdId = response.result?.sessionId || request.payload.sessionId;
1230
+ const clientId = typeof request.payload.clientId === "string" ? request.payload.clientId.trim() : "";
1231
+ if (createdId && clientId) {
1232
+ this.attachedSessions.set(createdId, {
1233
+ sessionId: createdId,
1234
+ clientId,
1235
+ clientType: request.payload.clientType || "daemon",
1236
+ readOnly: false
1237
+ });
829
1238
  }
830
- });
831
- this.socket?.write(serializeEnvelope(envelope));
832
- });
1239
+ } else if (request.type === "detach_session" || request.type === "delete_session") {
1240
+ this.attachedSessions.delete(request.payload.sessionId);
1241
+ }
1242
+ }
833
1243
  return response;
834
1244
  }
1245
+ disconnect(error) {
1246
+ const socket = this.socket;
1247
+ if (socket) {
1248
+ this.handleDisconnect(socket, error ? "error" : "closed", error, 0);
1249
+ return;
1250
+ }
1251
+ this.connectPromise = null;
1252
+ const failure = error || new Error(`Session host client disconnected (${this.endpoint.path})`);
1253
+ for (const waiter of this.requestWaiters.values()) {
1254
+ waiter.reject(failure);
1255
+ }
1256
+ this.requestWaiters.clear();
1257
+ }
835
1258
  async close() {
1259
+ this.attachedSessions.clear();
1260
+ this.connectPromise = null;
836
1261
  if (!this.socket) return;
837
1262
  const socket = this.socket;
838
1263
  this.socket = null;
@@ -868,20 +1293,34 @@ function writeEnvelope(socket, envelope) {
868
1293
 
869
1294
  // src/instance-key.ts
870
1295
  import * as crypto2 from "crypto";
871
- import * as fs from "fs";
872
- import * as os2 from "os";
1296
+ import * as fs2 from "fs";
1297
+ import * as os3 from "os";
873
1298
  import * as path3 from "path";
874
1299
  var DEFAULT_CONFIG_DIR_NAME = ".adhdev";
875
- function resolveInstanceConfigDir(env = process.env, homeDir = os2.homedir()) {
1300
+ function assertTestStorageIsolated(destination) {
1301
+ const env = process.env;
1302
+ if (!env.VITEST && env.NODE_ENV !== "test" && !env.NODE_TEST_CONTEXT && !process.execArgv.some((arg) => arg === "--test" || arg.startsWith("--test="))) return;
1303
+ const target = canonicalizeInstancePath(destination);
1304
+ const home = os3.userInfo().homedir;
1305
+ for (const track of [".adhdev", ".adhdev-preview"]) {
1306
+ const live = canonicalizeInstancePath(path3.join(home, track));
1307
+ if (target === live || target.startsWith(live + path3.sep)) {
1308
+ throw new Error("LIVE runtime storage is forbidden in a test process; pin ADHDEV_CONFIG_DIR or storageRootDir to a temporary directory");
1309
+ }
1310
+ }
1311
+ }
1312
+ function resolveInstanceConfigDir(env = process.env, homeDir = os3.homedir()) {
876
1313
  const override = typeof env.ADHDEV_CONFIG_DIR === "string" ? env.ADHDEV_CONFIG_DIR.trim() : "";
877
- return override || path3.join(homeDir, DEFAULT_CONFIG_DIR_NAME);
1314
+ const resolved = override || path3.join(homeDir, DEFAULT_CONFIG_DIR_NAME);
1315
+ if (env === process.env) assertTestStorageIsolated(resolved);
1316
+ return resolved;
878
1317
  }
879
1318
  function realpathLongestExistingPrefix(resolved) {
880
1319
  let current = resolved;
881
1320
  const remainder = [];
882
1321
  for (let depth = 0; depth < 256; depth++) {
883
1322
  try {
884
- const real = fs.realpathSync.native(current);
1323
+ const real = fs2.realpathSync.native(current);
885
1324
  return remainder.length === 0 ? real : path3.join(real, ...remainder);
886
1325
  } catch {
887
1326
  const parent = path3.dirname(current);
@@ -897,17 +1336,17 @@ function canonicalizeInstancePath(dir, platform2 = process.platform) {
897
1336
  const real = realpathLongestExistingPrefix(resolved).replace(/[\\/]+$/, "");
898
1337
  return platform2 === "win32" ? real.toLowerCase() : real;
899
1338
  }
900
- function isDefaultInstanceConfigDir(configDir, homeDir = os2.homedir(), platform2 = process.platform) {
1339
+ function isDefaultInstanceConfigDir(configDir, homeDir = os3.homedir(), platform2 = process.platform) {
901
1340
  return canonicalizeInstancePath(configDir, platform2) === canonicalizeInstancePath(path3.join(homeDir, DEFAULT_CONFIG_DIR_NAME), platform2);
902
1341
  }
903
- function resolveSessionHostIpcKey(configDir, homeDir = os2.homedir(), platform2 = process.platform) {
1342
+ function resolveSessionHostIpcKey(configDir, homeDir = os3.homedir(), platform2 = process.platform) {
904
1343
  if (isDefaultInstanceConfigDir(configDir, homeDir, platform2)) return "";
905
1344
  const canonical = canonicalizeInstancePath(configDir, platform2);
906
1345
  return crypto2.createHash("sha256").update(canonical, "utf8").digest("hex").slice(0, 12);
907
1346
  }
908
1347
 
909
1348
  // src/spawn-env.ts
910
- import * as os3 from "os";
1349
+ import * as os4 from "os";
911
1350
  import * as path4 from "path";
912
1351
  function sanitizeSpawnEnv(baseEnv, overrides) {
913
1352
  const env = {};
@@ -937,6 +1376,27 @@ function sanitizeSpawnEnv(baseEnv, overrides) {
937
1376
  applyTerminalColorEnv(env);
938
1377
  return env;
939
1378
  }
1379
+ function replayLaunchEnv(command) {
1380
+ if (command.envMode === "launch_overrides") return { ...command.env };
1381
+ const roleKeys = /* @__PURE__ */ new Set([
1382
+ "HOME",
1383
+ "USERPROFILE",
1384
+ "XDG_CONFIG_HOME",
1385
+ "CLAUDE_CONFIG_DIR",
1386
+ "CODEX_HOME",
1387
+ "KIMI_CODE_HOME",
1388
+ "GEMINI_CLI_HOME",
1389
+ "OPENCODE_CONFIG",
1390
+ "OPENCODE_CONFIG_CONTENT",
1391
+ "CLAUDE_CODE_DISABLE_AUTO_MEMORY",
1392
+ "TERMINAL_CWD",
1393
+ "ADHDEV_INLINE_MESH",
1394
+ "ADHDEV_ASSISTANT_SESSION_ID",
1395
+ "ADHDEV_COORDINATOR_SESSION_ID",
1396
+ "ADHDEV_CONFIG_DIR"
1397
+ ]);
1398
+ return Object.fromEntries(Object.entries(command.env ?? {}).filter(([key]) => roleKeys.has(key)));
1399
+ }
940
1400
  function applyTerminalColorEnv(env) {
941
1401
  if (env.NO_COLOR) return;
942
1402
  if (!env.TERM || env.TERM === "xterm-color") {
@@ -949,16 +1409,16 @@ function applyTerminalColorEnv(env) {
949
1409
  }
950
1410
  }
951
1411
  function ensureNodePtySpawnHelperPermissions(logFn) {
952
- if (os3.platform() === "win32") return;
1412
+ if (os4.platform() === "win32") return;
953
1413
  try {
954
- const fs2 = __require("fs");
1414
+ const fs3 = __require("fs");
955
1415
  const ptyDir = path4.resolve(path4.dirname(__require.resolve("node-pty")), "..");
956
- const platformArch = `${os3.platform()}-${os3.arch()}`;
1416
+ const platformArch = `${os4.platform()}-${os4.arch()}`;
957
1417
  const helper = path4.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
958
- if (fs2.existsSync(helper)) {
959
- const stat = fs2.statSync(helper);
1418
+ if (fs3.existsSync(helper)) {
1419
+ const stat = fs3.statSync(helper);
960
1420
  if (!(stat.mode & 73)) {
961
- fs2.chmodSync(helper, stat.mode | 493);
1421
+ fs3.chmodSync(helper, stat.mode | 493);
962
1422
  logFn?.(`Fixed spawn-helper permissions: ${helper}`);
963
1423
  }
964
1424
  }
@@ -972,15 +1432,48 @@ function createSessionHostControlPlane(transport) {
972
1432
  getDiagnostics(payload = {}) {
973
1433
  return transport.request("get_host_diagnostics", payload);
974
1434
  },
1435
+ async resolveHostBootId() {
1436
+ let diagnostics;
1437
+ try {
1438
+ diagnostics = await transport.request("get_host_diagnostics", {});
1439
+ } catch {
1440
+ return null;
1441
+ }
1442
+ if (typeof diagnostics.hostBootId === "string" && diagnostics.hostBootId) {
1443
+ return diagnostics.hostBootId;
1444
+ }
1445
+ try {
1446
+ const proof = await transport.request("get_upgrade_lease", {});
1447
+ return resolveHostBootId({
1448
+ upgradeBootId: typeof proof?.bootId === "string" ? proof.bootId : null,
1449
+ hostStartedAt: diagnostics.hostStartedAt
1450
+ });
1451
+ } catch (error) {
1452
+ const msg = error instanceof Error ? error.message : String(error);
1453
+ if (msg.includes("native_host_upgrade_binding_unavailable") || /unsupported|unknown request/i.test(msg)) {
1454
+ return resolveHostBootId({ hostStartedAt: diagnostics.hostStartedAt });
1455
+ }
1456
+ return null;
1457
+ }
1458
+ },
975
1459
  listSessions() {
976
1460
  return transport.request("list_sessions", {});
977
1461
  },
978
1462
  stopSession(sessionId) {
979
1463
  return transport.request("stop_session", { sessionId });
980
1464
  },
1465
+ stopSessionIfExpected(sessionId, expected) {
1466
+ return transport.request("stop_session_if_expected", { sessionId, expected });
1467
+ },
981
1468
  deleteSession(sessionId, opts = {}) {
982
1469
  return transport.request("delete_session", { sessionId, force: opts.force === true });
983
1470
  },
1471
+ deleteSessionIfExpected(sessionId, expected, opts = {}) {
1472
+ return transport.request(
1473
+ "delete_session_if_expected",
1474
+ { sessionId, expected, force: opts.force === true }
1475
+ );
1476
+ },
984
1477
  resumeSession(sessionId) {
985
1478
  return transport.request("resume_session", { sessionId });
986
1479
  },
@@ -1008,6 +1501,10 @@ function createSessionHostControlPlane(transport) {
1008
1501
  };
1009
1502
  }
1010
1503
  export {
1504
+ CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
1505
+ CLI_CHILD_NICE_ENV,
1506
+ CLI_CHILD_NICE_INCREMENT,
1507
+ CLI_CHILD_SCHEDULING_ENV,
1011
1508
  DEFAULT_CONFIG_DIR_NAME,
1012
1509
  DEFAULT_SESSION_HOST_COLS,
1013
1510
  DEFAULT_SESSION_HOST_ROWS,
@@ -1017,32 +1514,47 @@ export {
1017
1514
  SessionHostRegistry,
1018
1515
  SessionRingBuffer,
1019
1516
  applyTerminalColorEnv,
1517
+ assertTestStorageIsolated,
1020
1518
  buildRuntimeDisplayName,
1021
1519
  buildRuntimeKey,
1022
1520
  canonicalizeInstancePath,
1023
1521
  classifyTermination,
1522
+ createCliChildPriorityPolicy,
1024
1523
  createLineParser,
1025
1524
  createResponseEnvelope,
1026
1525
  createSessionHostControlPlane,
1526
+ disconnectSessionHostClients,
1027
1527
  ensureNodePtySpawnHelperPermissions,
1528
+ findConnectedSessionHostClient,
1028
1529
  formatRuntimeOwner,
1029
1530
  getDefaultSessionHostEndpoint,
1030
1531
  getSessionHostRecoveryLabel,
1031
1532
  getSessionHostSurfaceKind,
1032
1533
  getWorkspaceLabel,
1534
+ hiddenSpawn as hiddenSpawnProcess,
1535
+ hostBootIdFromStartedAt,
1033
1536
  isDefaultInstanceConfigDir,
1034
1537
  isSessionHostLiveRuntime,
1035
1538
  isSessionHostRecoverySnapshot,
1036
1539
  isTerminalRecord,
1540
+ niceLaunch,
1037
1541
  partitionSessionHostDiagnosticsSessions,
1038
1542
  partitionSessionHostRecords,
1543
+ refuseCleanupExpectedDelete,
1544
+ refuseCleanupExpectedStop,
1545
+ replayLaunchEnv,
1039
1546
  resolveAttachableRuntimeRecord,
1547
+ resolveHostBootId,
1040
1548
  resolveInstanceConfigDir,
1041
1549
  resolveRuntimeRecord,
1042
1550
  resolveSessionHostCols,
1043
1551
  resolveSessionHostIpcKey,
1044
1552
  resolveSessionHostRows,
1045
1553
  sanitizeSpawnEnv,
1554
+ spawnCliChild,
1555
+ stripCleanupAfterStopSideEffect,
1556
+ tagCleanupAfterStopSideEffect,
1557
+ validateSessionHostEndpoint,
1046
1558
  writeEnvelope
1047
1559
  };
1048
1560
  //# sourceMappingURL=index.mjs.map