@adhdev/session-host-core 1.0.82-rc.5 → 1.0.82-rc.51

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
@@ -7,13 +7,23 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
7
7
 
8
8
  // src/types.ts
9
9
  var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
10
+ "get_upgrade_lease",
11
+ "acquire_upgrade_lease",
12
+ "release_upgrade_lease",
10
13
  "create_session",
11
14
  "attach_session",
15
+ // Distinct request kind: old hosts must refuse instead of ignoring a pin.
16
+ "attach_session_if_incarnation",
12
17
  "detach_session",
13
18
  "send_input",
19
+ "send_input_if_seq",
20
+ "get_input_state",
14
21
  "resize_session",
15
22
  "stop_session",
23
+ "stop_session_if_expected",
24
+ "stop_mesh_writer",
16
25
  "delete_session",
26
+ "delete_session_if_expected",
17
27
  "resume_session",
18
28
  "acquire_write",
19
29
  "release_write",
@@ -26,9 +36,76 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
26
36
  "send_signal",
27
37
  "restart_session",
28
38
  "prune_duplicate_sessions",
39
+ "get_session_census",
40
+ "get_session",
29
41
  "list_sessions"
30
42
  ];
31
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
+
32
109
  // src/termination.ts
33
110
  function classifyTermination(input) {
34
111
  const { exitCode, terminatedAt } = input;
@@ -62,6 +139,72 @@ function classifyTermination(input) {
62
139
  return termination;
63
140
  }
64
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
+
65
208
  // src/buffer.ts
66
209
  var DEFAULT_SESSION_RING_BUFFER_MAX_BYTES = 4 * 1024 * 1024;
67
210
  var SessionRingBuffer = class {
@@ -398,6 +541,13 @@ function formatRuntimeOwner(record) {
398
541
  // src/registry.ts
399
542
  var SessionHostRegistry = class {
400
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
+ }
401
551
  createSession(payload) {
402
552
  const sessionId = payload.sessionId || generateUUID();
403
553
  if (this.sessions.has(sessionId)) {
@@ -429,6 +579,8 @@ var SessionHostRegistry = class {
429
579
  lifecycle: "starting",
430
580
  writeOwner: null,
431
581
  attachedClients: initialClient,
582
+ inputSeq: 0,
583
+ inputEpoch: this.mintInputEpoch(),
432
584
  buffer: {
433
585
  scrollbackBytes: 0,
434
586
  snapshotSeq: 0
@@ -448,6 +600,10 @@ var SessionHostRegistry = class {
448
600
  }
449
601
  restoreSession(record, snapshot) {
450
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();
451
607
  this.sessions.set(cloned.sessionId, {
452
608
  record: cloned,
453
609
  buffer: (() => {
@@ -458,13 +614,50 @@ var SessionHostRegistry = class {
458
614
  });
459
615
  return this.cloneRecord(cloned);
460
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
+ }
461
626
  listSessions() {
462
627
  return Array.from(this.sessions.values()).map((state) => this.cloneRecord(state.record)).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
463
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
+ }
464
649
  getSession(sessionId) {
465
650
  const state = this.sessions.get(sessionId);
466
651
  return state ? this.cloneRecord(state.record) : null;
467
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
+ }
468
661
  attachClient(payload) {
469
662
  const state = this.requireSession(payload.sessionId);
470
663
  const now = Date.now();
@@ -509,6 +702,20 @@ var SessionHostRegistry = class {
509
702
  state.record.lastActivityAt = Date.now();
510
703
  return this.cloneRecord(state.record);
511
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
+ }
512
719
  acquireWrite(payload) {
513
720
  const state = this.requireSession(payload.sessionId);
514
721
  if (state.record.writeOwner && state.record.writeOwner.clientId !== payload.clientId && !payload.force) {
@@ -625,10 +832,19 @@ function cloneMeta(meta) {
625
832
  }
626
833
 
627
834
  // src/ipc.ts
628
- import * as os from "os";
835
+ import * as os2 from "os";
629
836
  import * as path2 from "path";
630
837
  import * as net from "net";
838
+ import { createHash } from "crypto";
631
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
+ }
632
848
  function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
633
849
  const rawKey = typeof options.ipcKey === "string" ? options.ipcKey.trim() : "";
634
850
  if (rawKey && !/^[0-9a-f]{12}$/.test(rawKey)) {
@@ -642,48 +858,102 @@ function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
642
858
  path: `\\\\.\\pipe\\${appName}-session-host${suffix}`
643
859
  };
644
860
  }
645
- return {
861
+ const endpoint = {
646
862
  kind: "unix",
647
- path: path2.join(os.tmpdir(), `${appName}-session-host${suffix}.sock`)
863
+ path: path2.join(options.tmpDir ?? os2.tmpdir(), `${appName}-session-host${suffix}.sock`)
648
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;
649
872
  }
650
873
  function serializeEnvelope(envelope) {
651
874
  return `${JSON.stringify(envelope)}
652
875
  `;
653
876
  }
654
877
  function createLineParser(onEnvelope) {
655
- let buffer = "";
878
+ let fragments = [];
656
879
  const decoder = new StringDecoder("utf8");
657
880
  const parser = (chunk) => {
658
- buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
659
- let newlineIndex = buffer.indexOf("\n");
660
- while (newlineIndex >= 0) {
661
- const rawLine = buffer.slice(0, newlineIndex).trim();
662
- buffer = buffer.slice(newlineIndex + 1);
663
- if (rawLine) {
664
- 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;
665
888
  }
666
- 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));
667
894
  }
668
895
  };
669
896
  parser.end = () => {
670
- const remainder = buffer + decoder.end();
671
- buffer = "";
897
+ const remainder = fragments.join("") + decoder.end();
898
+ fragments = [];
672
899
  return remainder;
673
900
  };
674
901
  return parser;
675
902
  }
676
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
+ }
677
930
  var SessionHostClient = class {
678
931
  endpoint;
679
932
  socket = null;
933
+ connectPromise = null;
934
+ requestTimeoutMs = 3e4;
680
935
  requestWaiters = /* @__PURE__ */ new Map();
681
936
  eventListeners = /* @__PURE__ */ new Set();
682
937
  disconnectListeners = /* @__PURE__ */ new Set();
683
938
  /** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
684
939
  disconnectedSockets = /* @__PURE__ */ new WeakSet();
940
+ /** Session subscriptions established via create_session/attach_session, replayed automatically on reconnect. */
941
+ attachedSessions = /* @__PURE__ */ new Map();
685
942
  constructor(options = {}) {
686
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));
687
957
  }
688
958
  /**
689
959
  * Fires when an established connection to the session host goes away.
@@ -726,6 +996,7 @@ var SessionHostClient = class {
726
996
  this.requestWaiters.clear();
727
997
  if (this.socket === socket) {
728
998
  this.socket = null;
999
+ this.connectPromise = null;
729
1000
  }
730
1001
  try {
731
1002
  socket.destroy();
@@ -745,8 +1016,53 @@ var SessionHostClient = class {
745
1016
  }
746
1017
  }
747
1018
  }
748
- async connect() {
749
- 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
+ }
750
1066
  if (this.socket) {
751
1067
  try {
752
1068
  this.socket.destroy();
@@ -754,6 +1070,7 @@ var SessionHostClient = class {
754
1070
  }
755
1071
  this.socket = null;
756
1072
  }
1073
+ this.connectPromise = null;
757
1074
  const socket = net.createConnection(this.endpoint.path);
758
1075
  this.socket = socket;
759
1076
  const parser = createLineParser((envelope) => {
@@ -766,7 +1083,12 @@ var SessionHostClient = class {
766
1083
  return;
767
1084
  }
768
1085
  if (envelope.kind === "event") {
769
- 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
+ }
770
1092
  }
771
1093
  });
772
1094
  socket.on("data", parser);
@@ -787,13 +1109,68 @@ var SessionHostClient = class {
787
1109
  socket.on("end", () => {
788
1110
  this.handleDisconnect(socket, "ended", void 0, flushParser().length);
789
1111
  });
790
- await new Promise((resolve3, reject) => {
791
- socket.once("connect", () => {
792
- establishedSockets.add(socket);
793
- 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);
794
1152
  });
795
- socket.once("error", reject);
796
- });
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
+ }
797
1174
  }
798
1175
  onEvent(listener) {
799
1176
  this.eventListeners.add(listener);
@@ -801,35 +1178,86 @@ var SessionHostClient = class {
801
1178
  this.eventListeners.delete(listener);
802
1179
  };
803
1180
  }
804
- async request(request) {
805
- await this.connect();
806
- if (!this.socket) throw new Error("Session host socket unavailable");
807
- const requestId = generateUUID();
808
- const envelope = {
809
- kind: "request",
810
- requestId,
811
- request
812
- };
813
- const response = await new Promise((resolve3, reject) => {
814
- const timeout = setTimeout(() => {
815
- this.requestWaiters.delete(requestId);
816
- reject(new Error(`Session host request timed out after 30s (${request.type})`));
817
- }, 3e4);
818
- this.requestWaiters.set(requestId, {
819
- resolve: (value) => {
820
- clearTimeout(timeout);
821
- resolve3(value);
822
- },
823
- reject: (error) => {
824
- clearTimeout(timeout);
825
- 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
+ });
826
1238
  }
827
- });
828
- this.socket?.write(serializeEnvelope(envelope));
829
- });
1239
+ } else if (request.type === "detach_session" || request.type === "delete_session") {
1240
+ this.attachedSessions.delete(request.payload.sessionId);
1241
+ }
1242
+ }
830
1243
  return response;
831
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
+ }
832
1258
  async close() {
1259
+ this.attachedSessions.clear();
1260
+ this.connectPromise = null;
833
1261
  if (!this.socket) return;
834
1262
  const socket = this.socket;
835
1263
  this.socket = null;
@@ -865,20 +1293,34 @@ function writeEnvelope(socket, envelope) {
865
1293
 
866
1294
  // src/instance-key.ts
867
1295
  import * as crypto2 from "crypto";
868
- import * as fs from "fs";
869
- import * as os2 from "os";
1296
+ import * as fs2 from "fs";
1297
+ import * as os3 from "os";
870
1298
  import * as path3 from "path";
871
1299
  var DEFAULT_CONFIG_DIR_NAME = ".adhdev";
872
- 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()) {
873
1313
  const override = typeof env.ADHDEV_CONFIG_DIR === "string" ? env.ADHDEV_CONFIG_DIR.trim() : "";
874
- 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;
875
1317
  }
876
1318
  function realpathLongestExistingPrefix(resolved) {
877
1319
  let current = resolved;
878
1320
  const remainder = [];
879
1321
  for (let depth = 0; depth < 256; depth++) {
880
1322
  try {
881
- const real = fs.realpathSync.native(current);
1323
+ const real = fs2.realpathSync.native(current);
882
1324
  return remainder.length === 0 ? real : path3.join(real, ...remainder);
883
1325
  } catch {
884
1326
  const parent = path3.dirname(current);
@@ -894,17 +1336,17 @@ function canonicalizeInstancePath(dir, platform2 = process.platform) {
894
1336
  const real = realpathLongestExistingPrefix(resolved).replace(/[\\/]+$/, "");
895
1337
  return platform2 === "win32" ? real.toLowerCase() : real;
896
1338
  }
897
- function isDefaultInstanceConfigDir(configDir, homeDir = os2.homedir(), platform2 = process.platform) {
1339
+ function isDefaultInstanceConfigDir(configDir, homeDir = os3.homedir(), platform2 = process.platform) {
898
1340
  return canonicalizeInstancePath(configDir, platform2) === canonicalizeInstancePath(path3.join(homeDir, DEFAULT_CONFIG_DIR_NAME), platform2);
899
1341
  }
900
- function resolveSessionHostIpcKey(configDir, homeDir = os2.homedir(), platform2 = process.platform) {
1342
+ function resolveSessionHostIpcKey(configDir, homeDir = os3.homedir(), platform2 = process.platform) {
901
1343
  if (isDefaultInstanceConfigDir(configDir, homeDir, platform2)) return "";
902
1344
  const canonical = canonicalizeInstancePath(configDir, platform2);
903
1345
  return crypto2.createHash("sha256").update(canonical, "utf8").digest("hex").slice(0, 12);
904
1346
  }
905
1347
 
906
1348
  // src/spawn-env.ts
907
- import * as os3 from "os";
1349
+ import * as os4 from "os";
908
1350
  import * as path4 from "path";
909
1351
  function sanitizeSpawnEnv(baseEnv, overrides) {
910
1352
  const env = {};
@@ -934,6 +1376,27 @@ function sanitizeSpawnEnv(baseEnv, overrides) {
934
1376
  applyTerminalColorEnv(env);
935
1377
  return env;
936
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
+ }
937
1400
  function applyTerminalColorEnv(env) {
938
1401
  if (env.NO_COLOR) return;
939
1402
  if (!env.TERM || env.TERM === "xterm-color") {
@@ -946,16 +1409,16 @@ function applyTerminalColorEnv(env) {
946
1409
  }
947
1410
  }
948
1411
  function ensureNodePtySpawnHelperPermissions(logFn) {
949
- if (os3.platform() === "win32") return;
1412
+ if (os4.platform() === "win32") return;
950
1413
  try {
951
- const fs2 = __require("fs");
1414
+ const fs3 = __require("fs");
952
1415
  const ptyDir = path4.resolve(path4.dirname(__require.resolve("node-pty")), "..");
953
- const platformArch = `${os3.platform()}-${os3.arch()}`;
1416
+ const platformArch = `${os4.platform()}-${os4.arch()}`;
954
1417
  const helper = path4.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
955
- if (fs2.existsSync(helper)) {
956
- const stat = fs2.statSync(helper);
1418
+ if (fs3.existsSync(helper)) {
1419
+ const stat = fs3.statSync(helper);
957
1420
  if (!(stat.mode & 73)) {
958
- fs2.chmodSync(helper, stat.mode | 493);
1421
+ fs3.chmodSync(helper, stat.mode | 493);
959
1422
  logFn?.(`Fixed spawn-helper permissions: ${helper}`);
960
1423
  }
961
1424
  }
@@ -969,15 +1432,48 @@ function createSessionHostControlPlane(transport) {
969
1432
  getDiagnostics(payload = {}) {
970
1433
  return transport.request("get_host_diagnostics", payload);
971
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
+ },
972
1459
  listSessions() {
973
1460
  return transport.request("list_sessions", {});
974
1461
  },
975
1462
  stopSession(sessionId) {
976
1463
  return transport.request("stop_session", { sessionId });
977
1464
  },
1465
+ stopSessionIfExpected(sessionId, expected) {
1466
+ return transport.request("stop_session_if_expected", { sessionId, expected });
1467
+ },
978
1468
  deleteSession(sessionId, opts = {}) {
979
1469
  return transport.request("delete_session", { sessionId, force: opts.force === true });
980
1470
  },
1471
+ deleteSessionIfExpected(sessionId, expected, opts = {}) {
1472
+ return transport.request(
1473
+ "delete_session_if_expected",
1474
+ { sessionId, expected, force: opts.force === true }
1475
+ );
1476
+ },
981
1477
  resumeSession(sessionId) {
982
1478
  return transport.request("resume_session", { sessionId });
983
1479
  },
@@ -1005,6 +1501,10 @@ function createSessionHostControlPlane(transport) {
1005
1501
  };
1006
1502
  }
1007
1503
  export {
1504
+ CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
1505
+ CLI_CHILD_NICE_ENV,
1506
+ CLI_CHILD_NICE_INCREMENT,
1507
+ CLI_CHILD_SCHEDULING_ENV,
1008
1508
  DEFAULT_CONFIG_DIR_NAME,
1009
1509
  DEFAULT_SESSION_HOST_COLS,
1010
1510
  DEFAULT_SESSION_HOST_ROWS,
@@ -1014,32 +1514,47 @@ export {
1014
1514
  SessionHostRegistry,
1015
1515
  SessionRingBuffer,
1016
1516
  applyTerminalColorEnv,
1517
+ assertTestStorageIsolated,
1017
1518
  buildRuntimeDisplayName,
1018
1519
  buildRuntimeKey,
1019
1520
  canonicalizeInstancePath,
1020
1521
  classifyTermination,
1522
+ createCliChildPriorityPolicy,
1021
1523
  createLineParser,
1022
1524
  createResponseEnvelope,
1023
1525
  createSessionHostControlPlane,
1526
+ disconnectSessionHostClients,
1024
1527
  ensureNodePtySpawnHelperPermissions,
1528
+ findConnectedSessionHostClient,
1025
1529
  formatRuntimeOwner,
1026
1530
  getDefaultSessionHostEndpoint,
1027
1531
  getSessionHostRecoveryLabel,
1028
1532
  getSessionHostSurfaceKind,
1029
1533
  getWorkspaceLabel,
1534
+ hiddenSpawn as hiddenSpawnProcess,
1535
+ hostBootIdFromStartedAt,
1030
1536
  isDefaultInstanceConfigDir,
1031
1537
  isSessionHostLiveRuntime,
1032
1538
  isSessionHostRecoverySnapshot,
1033
1539
  isTerminalRecord,
1540
+ niceLaunch,
1034
1541
  partitionSessionHostDiagnosticsSessions,
1035
1542
  partitionSessionHostRecords,
1543
+ refuseCleanupExpectedDelete,
1544
+ refuseCleanupExpectedStop,
1545
+ replayLaunchEnv,
1036
1546
  resolveAttachableRuntimeRecord,
1547
+ resolveHostBootId,
1037
1548
  resolveInstanceConfigDir,
1038
1549
  resolveRuntimeRecord,
1039
1550
  resolveSessionHostCols,
1040
1551
  resolveSessionHostIpcKey,
1041
1552
  resolveSessionHostRows,
1042
1553
  sanitizeSpawnEnv,
1554
+ spawnCliChild,
1555
+ stripCleanupAfterStopSideEffect,
1556
+ tagCleanupAfterStopSideEffect,
1557
+ validateSessionHostEndpoint,
1043
1558
  writeEnvelope
1044
1559
  };
1045
1560
  //# sourceMappingURL=index.mjs.map