@adhdev/session-host-core 1.0.82-rc.32 → 1.0.82-rc.34

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.js CHANGED
@@ -37,11 +37,14 @@ __export(index_exports, {
37
37
  DEFAULT_SESSION_HOST_COLS: () => DEFAULT_SESSION_HOST_COLS,
38
38
  DEFAULT_SESSION_HOST_ROWS: () => DEFAULT_SESSION_HOST_ROWS,
39
39
  DEFAULT_SESSION_RING_BUFFER_MAX_BYTES: () => DEFAULT_SESSION_RING_BUFFER_MAX_BYTES,
40
+ OPERATOR_RECOVERY_TARGET: () => OPERATOR_RECOVERY_TARGET,
41
+ RecoveryOwnerAdmission: () => RecoveryOwnerAdmission,
40
42
  SESSION_HOST_SUPPORTED_REQUEST_TYPES: () => SESSION_HOST_SUPPORTED_REQUEST_TYPES,
41
43
  SessionHostClient: () => SessionHostClient,
42
44
  SessionHostRegistry: () => SessionHostRegistry,
43
45
  SessionRingBuffer: () => SessionRingBuffer,
44
46
  applyTerminalColorEnv: () => applyTerminalColorEnv,
47
+ assertRecoveryLaunchIdentity: () => assertRecoveryLaunchIdentity,
45
48
  assertTestStorageIsolated: () => assertTestStorageIsolated,
46
49
  buildRuntimeDisplayName: () => buildRuntimeDisplayName,
47
50
  buildRuntimeKey: () => buildRuntimeKey,
@@ -61,11 +64,14 @@ __export(index_exports, {
61
64
  getWorkspaceLabel: () => getWorkspaceLabel,
62
65
  hiddenSpawnProcess: () => hiddenSpawn,
63
66
  isDefaultInstanceConfigDir: () => isDefaultInstanceConfigDir,
67
+ isRecoveryEndpoint: () => isRecoveryEndpoint,
64
68
  isSessionHostLiveRuntime: () => isSessionHostLiveRuntime,
65
69
  isSessionHostRecoverySnapshot: () => isSessionHostRecoverySnapshot,
66
70
  isTerminalRecord: () => isTerminalRecord,
71
+ niceLaunch: () => niceLaunch,
67
72
  partitionSessionHostDiagnosticsSessions: () => partitionSessionHostDiagnosticsSessions,
68
73
  partitionSessionHostRecords: () => partitionSessionHostRecords,
74
+ recoveryTargetBytes: () => recoveryTargetBytes,
69
75
  replayLaunchEnv: () => replayLaunchEnv,
70
76
  resolveAttachableRuntimeRecord: () => resolveAttachableRuntimeRecord,
71
77
  resolveInstanceConfigDir: () => resolveInstanceConfigDir,
@@ -80,13 +86,136 @@ __export(index_exports, {
80
86
  });
81
87
  module.exports = __toCommonJS(index_exports);
82
88
 
89
+ // src/operator-recovery.ts
90
+ var import_node_crypto = require("crypto");
91
+ var import_node_path = require("path");
92
+ var import_node_perf_hooks = require("perf_hooks");
93
+ var OPERATOR_RECOVERY_TARGET = Object.freeze({
94
+ association: "operator_asserted",
95
+ taskId: "a1cdf3c0-f029-4d17-a8e9-db64e0a55501",
96
+ meshId: "mesh_271444af883843e9b36c67155b87b22f",
97
+ attemptId: "mesh_queue:mesh_271444af883843e9b36c67155b87b22f:a1cdf3c0-f029-4d17-a8e9-db64e0a55501:0",
98
+ generation: 0,
99
+ dispatchNonce: 1,
100
+ deliveryId: "dlv-7e259b34-b049-47ee-a466-2ca9c12bcff4",
101
+ ownerDaemonId: "daemon_mach_4462a75330c548be9c2e74dd9f7f6ffb",
102
+ nodeId: "node_d82de0cef9b042b6948986609e32142f",
103
+ workerDaemonId: "daemon_mach_6733c865d60f432dbeb119a6875ee303",
104
+ sessionId: "de321185-4ebc-40aa-8c6e-b4919e87fae3",
105
+ providerSessionId: "60806c79-7d77-4614-9fa6-e628533478ba",
106
+ namespace: "6a2ef3162182"
107
+ });
108
+ var recoveryTargetBytes = JSON.stringify(OPERATOR_RECOVERY_TARGET);
109
+ function assertRecoveryLaunchIdentity(value) {
110
+ if (!value || typeof value !== "object") return;
111
+ const identities = /* @__PURE__ */ new Set([
112
+ "sessionId",
113
+ "runtimeId",
114
+ "runtimeSessionId",
115
+ "providerSessionId",
116
+ "presetSessionKey",
117
+ "resumeSessionId",
118
+ "key"
119
+ ]);
120
+ const nested = /* @__PURE__ */ new Set(["options", "meta", "settings", "settingsOverride", "restartBinding", "sessionBinding", "launchCommand"]);
121
+ for (const [key, field] of Object.entries(value)) {
122
+ if (identities.has(key) || ["args", "cliArgs", "cliArgsWithBrain"].includes(key)) {
123
+ const bytes = JSON.stringify(field)?.toLowerCase();
124
+ if (bytes?.includes(OPERATOR_RECOVERY_TARGET.sessionId) || bytes?.includes(OPERATOR_RECOVERY_TARGET.providerSessionId)) {
125
+ throw new Error("operator_recovery_fenced");
126
+ }
127
+ } else if (nested.has(key)) assertRecoveryLaunchIdentity(field);
128
+ }
129
+ }
130
+ function isRecoveryEndpoint(endpoint) {
131
+ return (0, import_node_path.isAbsolute)(endpoint) && (0, import_node_path.basename)(endpoint) === `adhdev-preview-session-host-${OPERATOR_RECOVERY_TARGET.namespace}.sock`;
132
+ }
133
+ var RecoveryOwnerAdmission = class {
134
+ constructor(enrollment, clock = () => import_node_perf_hooks.performance.now()) {
135
+ this.clock = clock;
136
+ this.enrollment = Object.freeze({ ...enrollment });
137
+ if (!enrollment.enrollmentId || !enrollment.coordinatorBootId || !enrollment.authEpoch || typeof enrollment.verifyCurrent !== "function") throw new Error("recovery_owner_enrollment_required");
138
+ this.key = (0, import_node_crypto.createPublicKey)(enrollment.publicKey);
139
+ if (this.key.asymmetricKeyType !== "ed25519") throw new Error("recovery_owner_key_type");
140
+ }
141
+ key;
142
+ enrollment;
143
+ pending = /* @__PURE__ */ new Map();
144
+ grants = /* @__PURE__ */ new WeakMap();
145
+ lastNow = -Infinity;
146
+ now() {
147
+ const n = this.clock();
148
+ if (!Number.isFinite(n) || n < this.lastNow || this.enrollment.verifyCurrent() !== true) {
149
+ this.pending.clear();
150
+ this.lastNow = Infinity;
151
+ throw new Error("recovery_owner_revoked");
152
+ }
153
+ this.lastNow = n;
154
+ return n;
155
+ }
156
+ challenge(operation = "anchor_recover") {
157
+ if (!["anchor_recover", "fence_install", "witness_enroll"].includes(operation)) throw new Error("recovery_owner_operation_rejected");
158
+ const now = this.now();
159
+ for (const [message2, entry] of this.pending) if (entry.deadline <= now) this.pending.delete(message2);
160
+ if (this.pending.size >= 16) throw new Error("recovery_owner_challenge_limit");
161
+ const message = JSON.stringify([
162
+ "operator_recovery_v1",
163
+ operation,
164
+ recoveryTargetBytes,
165
+ this.enrollment.enrollmentId,
166
+ this.enrollment.coordinatorBootId,
167
+ this.enrollment.authEpoch,
168
+ (0, import_node_crypto.randomBytes)(32).toString("hex")
169
+ ]);
170
+ this.pending.set(message, { deadline: now + 3e4, operation });
171
+ return Object.freeze({ message });
172
+ }
173
+ authorize(message, signature) {
174
+ const now = this.now();
175
+ const entry = this.pending.get(message);
176
+ this.pending.delete(message);
177
+ if (!entry || now >= entry.deadline || !/^[a-f0-9]{128}$/.test(signature) || !(0, import_node_crypto.verify)(null, Buffer.from(message), this.key, Buffer.from(signature, "hex"))) {
178
+ throw new Error("recovery_owner_signature_rejected");
179
+ }
180
+ const grant = Object.freeze({ purpose: "operator_recovery_v1", operation: entry.operation });
181
+ this.grants.set(grant, entry);
182
+ return grant;
183
+ }
184
+ assertGrant(grant) {
185
+ const now = this.now();
186
+ const entry = typeof grant === "object" && grant !== null ? this.grants.get(grant) : void 0;
187
+ if (!entry || now >= entry.deadline) throw new Error("recovery_owner_grant_rejected");
188
+ }
189
+ /** Burn synchronously before any work or await. The private continuation
190
+ * rechecks the ORIGINAL deadline and revocation; it cannot mint a new grant. */
191
+ reserve(grant, operation) {
192
+ this.assertGrant(grant);
193
+ const entry = this.grants.get(grant);
194
+ this.grants.delete(grant);
195
+ if (entry.operation !== operation) throw new Error("recovery_owner_operation_rejected");
196
+ return () => {
197
+ if (this.now() >= entry.deadline) throw new Error("recovery_owner_grant_rejected");
198
+ };
199
+ }
200
+ consume(grant) {
201
+ this.assertGrant(grant);
202
+ this.grants.delete(grant);
203
+ }
204
+ };
205
+
83
206
  // src/types.ts
84
207
  var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
208
+ "prepare_operator_recovery_fence_v1",
209
+ "install_operator_recovery_fence_v1",
210
+ "attest_operator_recovery_v1",
211
+ "get_operator_recovery_coverage_v1",
85
212
  "get_upgrade_lease",
86
213
  "acquire_upgrade_lease",
87
214
  "release_upgrade_lease",
88
215
  "create_session",
89
216
  "attach_session",
217
+ // Distinct request kind: old hosts must refuse instead of ignoring a pin.
218
+ "attach_session_if_incarnation",
90
219
  "detach_session",
91
220
  "send_input",
92
221
  "send_input_if_seq",
@@ -107,6 +236,7 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
107
236
  "send_signal",
108
237
  "restart_session",
109
238
  "prune_duplicate_sessions",
239
+ "get_session_census",
110
240
  "get_session",
111
241
  "list_sessions"
112
242
  ];
@@ -145,6 +275,7 @@ function classifyTermination(input) {
145
275
  }
146
276
 
147
277
  // src/cli-child-priority.ts
278
+ var fs = __toESM(require("fs"));
148
279
  var os = __toESM(require("os"));
149
280
 
150
281
  // src/process/hidden-spawn.ts
@@ -164,6 +295,13 @@ function setDarwinBackground(pid, onFailure) {
164
295
  if (code !== 0) onFailure(new Error(`taskpolicy exited with ${signal ?? code}`));
165
296
  });
166
297
  }
298
+ var POSIX_NICE_BINARY = "/usr/bin/nice";
299
+ function niceLaunch(command, args, env = process.env, platform2 = process.platform, niceAvailable = () => fs.existsSync(POSIX_NICE_BINARY)) {
300
+ if (env[CLI_CHILD_NICE_ENV] === "0" || platform2 !== "darwin" && platform2 !== "linux" || !command || !niceAvailable()) {
301
+ return { command, args: [...args], preApplied: false };
302
+ }
303
+ return { command: POSIX_NICE_BINARY, args: ["-n", String(CLI_CHILD_NICE_INCREMENT), command, ...args], preApplied: true };
304
+ }
167
305
  function createCliChildPriorityPolicy(deps = {
168
306
  platform: process.platform,
169
307
  getPriority: os.getPriority,
@@ -171,7 +309,7 @@ function createCliChildPriorityPolicy(deps = {
171
309
  setDarwinBackground
172
310
  }) {
173
311
  let failureLogged = false;
174
- return function spawnCliChild2(spawnChild, env = process.env, logInfo = console.info) {
312
+ return function spawnCliChild2(spawnChild, env = process.env, logInfo = console.info, opts = {}) {
175
313
  const child = spawnChild();
176
314
  const pid = child.pid;
177
315
  if (env[CLI_CHILD_NICE_ENV] === "0" || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return child;
@@ -182,11 +320,13 @@ function createCliChildPriorityPolicy(deps = {
182
320
  logInfo(`[cli-child-priority] Could not apply CLI child scheduling (pid ${pid}); continuing: ${detail}`);
183
321
  }
184
322
  };
185
- try {
186
- const priority = deps.platform === "win32" ? os.constants.priority.PRIORITY_BELOW_NORMAL : Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
187
- deps.setPriority(pid, priority);
188
- } catch (error) {
189
- onFailure(error);
323
+ if (!opts.preApplied) {
324
+ try {
325
+ const priority = deps.platform === "win32" ? os.constants.priority.PRIORITY_BELOW_NORMAL : Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
326
+ deps.setPriority(pid, priority);
327
+ } catch (error) {
328
+ onFailure(error);
329
+ }
190
330
  }
191
331
  if (deps.platform === "darwin" && env[CLI_CHILD_SCHEDULING_ENV] === "darwin-bg") {
192
332
  try {
@@ -621,10 +761,38 @@ var SessionHostRegistry = class {
621
761
  listSessions() {
622
762
  return Array.from(this.sessions.values()).map((state) => this.cloneRecord(state.record)).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
623
763
  }
764
+ /** No launch bodies are cloned. Unknown role evidence stays conservative. */
765
+ getSessionCensus(sessionIds) {
766
+ if (!Array.isArray(sessionIds) || sessionIds.length > 128 || sessionIds.some((id) => typeof id !== "string" || id.length === 0 || id.length > 256)) {
767
+ throw new Error("Invalid session census: at most 128 identities of 256 characters");
768
+ }
769
+ const requested = new Set(sessionIds);
770
+ const liveSessionIds = [];
771
+ let hasOtherAssistantCandidates = false;
772
+ for (const { record } of this.sessions.values()) {
773
+ if (record.category !== "cli" || record.termination || !["starting", "running", "stopping", "interrupted"].includes(record.lifecycle)) continue;
774
+ if (requested.has(record.sessionId)) liveSessionIds.push(record.sessionId);
775
+ else {
776
+ const launch = record.meta?.launchRecord;
777
+ if (record.meta?.assistant === true || launch?.launchedBy === "assistant" || launch?.roleLaunch?.role === "assistant") {
778
+ hasOtherAssistantCandidates = true;
779
+ }
780
+ }
781
+ }
782
+ return { liveSessionIds, hasOtherAssistantCandidates };
783
+ }
624
784
  getSession(sessionId) {
625
785
  const state = this.sessions.get(sessionId);
626
786
  return state ? this.cloneRecord(state.record) : null;
627
787
  }
788
+ attachClientIfIncarnation(payload) {
789
+ const record = this.requireSession(payload.sessionId).record;
790
+ const expected = payload.expectedIncarnation;
791
+ 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) {
792
+ throw new Error(`Runtime not found for session: ${payload.sessionId} (incarnation changed)`);
793
+ }
794
+ return this.attachClient(payload);
795
+ }
628
796
  attachClient(payload) {
629
797
  const state = this.requireSession(payload.sessionId);
630
798
  const now = Date.now();
@@ -802,6 +970,7 @@ function cloneMeta(meta) {
802
970
  var os2 = __toESM(require("os"));
803
971
  var path2 = __toESM(require("path"));
804
972
  var net = __toESM(require("net"));
973
+ var import_crypto = require("crypto");
805
974
  var import_string_decoder = require("string_decoder");
806
975
  function validateSessionHostEndpoint(endpoint, platform2 = process.platform) {
807
976
  if (endpoint.kind !== "unix") return;
@@ -824,10 +993,17 @@ function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
824
993
  path: `\\\\.\\pipe\\${appName}-session-host${suffix}`
825
994
  };
826
995
  }
827
- return {
996
+ const endpoint = {
828
997
  kind: "unix",
829
- path: path2.join(os2.tmpdir(), `${appName}-session-host${suffix}.sock`)
998
+ path: path2.join(options.tmpDir ?? os2.tmpdir(), `${appName}-session-host${suffix}.sock`)
830
999
  };
1000
+ const limit = platform2 === "linux" ? 108 : 104;
1001
+ if (Buffer.byteLength(endpoint.path, "utf8") + 1 <= limit) return endpoint;
1002
+ const identity = JSON.stringify([endpoint.path, appName, rawKey, process.getuid?.() ?? null]);
1003
+ const digest = (0, import_crypto.createHash)("sha256").update(identity, "utf8").digest("hex");
1004
+ const shortened = { kind: "unix", path: `/tmp/adhdev-sh-${digest}.sock` };
1005
+ validateSessionHostEndpoint(shortened, platform2);
1006
+ return shortened;
831
1007
  }
832
1008
  function serializeEnvelope(envelope) {
833
1009
  return `${JSON.stringify(envelope)}
@@ -1001,17 +1177,8 @@ var SessionHostClient = class {
1001
1177
  observerLagMs
1002
1178
  }
1003
1179
  );
1004
- if (this.socket === socket) {
1005
- this.disconnect(timeoutError);
1006
- } else {
1007
- this.requestWaiters.delete(requestId);
1008
- this.disconnectedSockets.add(socket);
1009
- try {
1010
- socket.destroy();
1011
- } catch {
1012
- }
1013
- reject(timeoutError);
1014
- }
1180
+ this.requestWaiters.delete(requestId);
1181
+ reject(timeoutError);
1015
1182
  }, timeoutMs);
1016
1183
  this.requestWaiters.set(requestId, {
1017
1184
  resolve: (value) => {
@@ -1156,7 +1323,7 @@ var SessionHostClient = class {
1156
1323
  const raceStartedMonotonicAt = performance.now();
1157
1324
  try {
1158
1325
  await Promise.race([
1159
- this.connect(timeoutMs),
1326
+ this.connect(),
1160
1327
  new Promise((_resolve, reject) => {
1161
1328
  timer = setTimeout(() => {
1162
1329
  const actualElapsedMs = Math.max(0, Math.round(performance.now() - raceStartedMonotonicAt));
@@ -1173,7 +1340,6 @@ var SessionHostClient = class {
1173
1340
  }
1174
1341
  );
1175
1342
  reject(error);
1176
- this.disconnect(error);
1177
1343
  }, timeoutMs);
1178
1344
  })
1179
1345
  ]);
@@ -1262,7 +1428,7 @@ function writeEnvelope(socket, envelope) {
1262
1428
 
1263
1429
  // src/instance-key.ts
1264
1430
  var crypto2 = __toESM(require("crypto"));
1265
- var fs = __toESM(require("fs"));
1431
+ var fs2 = __toESM(require("fs"));
1266
1432
  var os3 = __toESM(require("os"));
1267
1433
  var path3 = __toESM(require("path"));
1268
1434
  var DEFAULT_CONFIG_DIR_NAME = ".adhdev";
@@ -1289,7 +1455,7 @@ function realpathLongestExistingPrefix(resolved) {
1289
1455
  const remainder = [];
1290
1456
  for (let depth = 0; depth < 256; depth++) {
1291
1457
  try {
1292
- const real = fs.realpathSync.native(current);
1458
+ const real = fs2.realpathSync.native(current);
1293
1459
  return remainder.length === 0 ? real : path3.join(real, ...remainder);
1294
1460
  } catch {
1295
1461
  const parent = path3.dirname(current);
@@ -1380,14 +1546,14 @@ function applyTerminalColorEnv(env) {
1380
1546
  function ensureNodePtySpawnHelperPermissions(logFn) {
1381
1547
  if (os4.platform() === "win32") return;
1382
1548
  try {
1383
- const fs2 = require("fs");
1549
+ const fs3 = require("fs");
1384
1550
  const ptyDir = path4.resolve(path4.dirname(require.resolve("node-pty")), "..");
1385
1551
  const platformArch = `${os4.platform()}-${os4.arch()}`;
1386
1552
  const helper = path4.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
1387
- if (fs2.existsSync(helper)) {
1388
- const stat = fs2.statSync(helper);
1553
+ if (fs3.existsSync(helper)) {
1554
+ const stat = fs3.statSync(helper);
1389
1555
  if (!(stat.mode & 73)) {
1390
- fs2.chmodSync(helper, stat.mode | 493);
1556
+ fs3.chmodSync(helper, stat.mode | 493);
1391
1557
  logFn?.(`Fixed spawn-helper permissions: ${helper}`);
1392
1558
  }
1393
1559
  }
@@ -1445,11 +1611,14 @@ function createSessionHostControlPlane(transport) {
1445
1611
  DEFAULT_SESSION_HOST_COLS,
1446
1612
  DEFAULT_SESSION_HOST_ROWS,
1447
1613
  DEFAULT_SESSION_RING_BUFFER_MAX_BYTES,
1614
+ OPERATOR_RECOVERY_TARGET,
1615
+ RecoveryOwnerAdmission,
1448
1616
  SESSION_HOST_SUPPORTED_REQUEST_TYPES,
1449
1617
  SessionHostClient,
1450
1618
  SessionHostRegistry,
1451
1619
  SessionRingBuffer,
1452
1620
  applyTerminalColorEnv,
1621
+ assertRecoveryLaunchIdentity,
1453
1622
  assertTestStorageIsolated,
1454
1623
  buildRuntimeDisplayName,
1455
1624
  buildRuntimeKey,
@@ -1469,11 +1638,14 @@ function createSessionHostControlPlane(transport) {
1469
1638
  getWorkspaceLabel,
1470
1639
  hiddenSpawnProcess,
1471
1640
  isDefaultInstanceConfigDir,
1641
+ isRecoveryEndpoint,
1472
1642
  isSessionHostLiveRuntime,
1473
1643
  isSessionHostRecoverySnapshot,
1474
1644
  isTerminalRecord,
1645
+ niceLaunch,
1475
1646
  partitionSessionHostDiagnosticsSessions,
1476
1647
  partitionSessionHostRecords,
1648
+ recoveryTargetBytes,
1477
1649
  replayLaunchEnv,
1478
1650
  resolveAttachableRuntimeRecord,
1479
1651
  resolveInstanceConfigDir,