@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.mjs CHANGED
@@ -5,13 +5,136 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
5
5
  throw Error('Dynamic require of "' + x + '" is not supported');
6
6
  });
7
7
 
8
+ // src/operator-recovery.ts
9
+ import { createPublicKey, randomBytes, verify } from "crypto";
10
+ import { isAbsolute, basename } from "path";
11
+ import { performance as performance2 } from "perf_hooks";
12
+ var OPERATOR_RECOVERY_TARGET = Object.freeze({
13
+ association: "operator_asserted",
14
+ taskId: "a1cdf3c0-f029-4d17-a8e9-db64e0a55501",
15
+ meshId: "mesh_271444af883843e9b36c67155b87b22f",
16
+ attemptId: "mesh_queue:mesh_271444af883843e9b36c67155b87b22f:a1cdf3c0-f029-4d17-a8e9-db64e0a55501:0",
17
+ generation: 0,
18
+ dispatchNonce: 1,
19
+ deliveryId: "dlv-7e259b34-b049-47ee-a466-2ca9c12bcff4",
20
+ ownerDaemonId: "daemon_mach_4462a75330c548be9c2e74dd9f7f6ffb",
21
+ nodeId: "node_d82de0cef9b042b6948986609e32142f",
22
+ workerDaemonId: "daemon_mach_6733c865d60f432dbeb119a6875ee303",
23
+ sessionId: "de321185-4ebc-40aa-8c6e-b4919e87fae3",
24
+ providerSessionId: "60806c79-7d77-4614-9fa6-e628533478ba",
25
+ namespace: "6a2ef3162182"
26
+ });
27
+ var recoveryTargetBytes = JSON.stringify(OPERATOR_RECOVERY_TARGET);
28
+ function assertRecoveryLaunchIdentity(value) {
29
+ if (!value || typeof value !== "object") return;
30
+ const identities = /* @__PURE__ */ new Set([
31
+ "sessionId",
32
+ "runtimeId",
33
+ "runtimeSessionId",
34
+ "providerSessionId",
35
+ "presetSessionKey",
36
+ "resumeSessionId",
37
+ "key"
38
+ ]);
39
+ const nested = /* @__PURE__ */ new Set(["options", "meta", "settings", "settingsOverride", "restartBinding", "sessionBinding", "launchCommand"]);
40
+ for (const [key, field] of Object.entries(value)) {
41
+ if (identities.has(key) || ["args", "cliArgs", "cliArgsWithBrain"].includes(key)) {
42
+ const bytes = JSON.stringify(field)?.toLowerCase();
43
+ if (bytes?.includes(OPERATOR_RECOVERY_TARGET.sessionId) || bytes?.includes(OPERATOR_RECOVERY_TARGET.providerSessionId)) {
44
+ throw new Error("operator_recovery_fenced");
45
+ }
46
+ } else if (nested.has(key)) assertRecoveryLaunchIdentity(field);
47
+ }
48
+ }
49
+ function isRecoveryEndpoint(endpoint) {
50
+ return isAbsolute(endpoint) && basename(endpoint) === `adhdev-preview-session-host-${OPERATOR_RECOVERY_TARGET.namespace}.sock`;
51
+ }
52
+ var RecoveryOwnerAdmission = class {
53
+ constructor(enrollment, clock = () => performance2.now()) {
54
+ this.clock = clock;
55
+ this.enrollment = Object.freeze({ ...enrollment });
56
+ if (!enrollment.enrollmentId || !enrollment.coordinatorBootId || !enrollment.authEpoch || typeof enrollment.verifyCurrent !== "function") throw new Error("recovery_owner_enrollment_required");
57
+ this.key = createPublicKey(enrollment.publicKey);
58
+ if (this.key.asymmetricKeyType !== "ed25519") throw new Error("recovery_owner_key_type");
59
+ }
60
+ key;
61
+ enrollment;
62
+ pending = /* @__PURE__ */ new Map();
63
+ grants = /* @__PURE__ */ new WeakMap();
64
+ lastNow = -Infinity;
65
+ now() {
66
+ const n = this.clock();
67
+ if (!Number.isFinite(n) || n < this.lastNow || this.enrollment.verifyCurrent() !== true) {
68
+ this.pending.clear();
69
+ this.lastNow = Infinity;
70
+ throw new Error("recovery_owner_revoked");
71
+ }
72
+ this.lastNow = n;
73
+ return n;
74
+ }
75
+ challenge(operation = "anchor_recover") {
76
+ if (!["anchor_recover", "fence_install", "witness_enroll"].includes(operation)) throw new Error("recovery_owner_operation_rejected");
77
+ const now = this.now();
78
+ for (const [message2, entry] of this.pending) if (entry.deadline <= now) this.pending.delete(message2);
79
+ if (this.pending.size >= 16) throw new Error("recovery_owner_challenge_limit");
80
+ const message = JSON.stringify([
81
+ "operator_recovery_v1",
82
+ operation,
83
+ recoveryTargetBytes,
84
+ this.enrollment.enrollmentId,
85
+ this.enrollment.coordinatorBootId,
86
+ this.enrollment.authEpoch,
87
+ randomBytes(32).toString("hex")
88
+ ]);
89
+ this.pending.set(message, { deadline: now + 3e4, operation });
90
+ return Object.freeze({ message });
91
+ }
92
+ authorize(message, signature) {
93
+ const now = this.now();
94
+ const entry = this.pending.get(message);
95
+ this.pending.delete(message);
96
+ if (!entry || now >= entry.deadline || !/^[a-f0-9]{128}$/.test(signature) || !verify(null, Buffer.from(message), this.key, Buffer.from(signature, "hex"))) {
97
+ throw new Error("recovery_owner_signature_rejected");
98
+ }
99
+ const grant = Object.freeze({ purpose: "operator_recovery_v1", operation: entry.operation });
100
+ this.grants.set(grant, entry);
101
+ return grant;
102
+ }
103
+ assertGrant(grant) {
104
+ const now = this.now();
105
+ const entry = typeof grant === "object" && grant !== null ? this.grants.get(grant) : void 0;
106
+ if (!entry || now >= entry.deadline) throw new Error("recovery_owner_grant_rejected");
107
+ }
108
+ /** Burn synchronously before any work or await. The private continuation
109
+ * rechecks the ORIGINAL deadline and revocation; it cannot mint a new grant. */
110
+ reserve(grant, operation) {
111
+ this.assertGrant(grant);
112
+ const entry = this.grants.get(grant);
113
+ this.grants.delete(grant);
114
+ if (entry.operation !== operation) throw new Error("recovery_owner_operation_rejected");
115
+ return () => {
116
+ if (this.now() >= entry.deadline) throw new Error("recovery_owner_grant_rejected");
117
+ };
118
+ }
119
+ consume(grant) {
120
+ this.assertGrant(grant);
121
+ this.grants.delete(grant);
122
+ }
123
+ };
124
+
8
125
  // src/types.ts
9
126
  var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
127
+ "prepare_operator_recovery_fence_v1",
128
+ "install_operator_recovery_fence_v1",
129
+ "attest_operator_recovery_v1",
130
+ "get_operator_recovery_coverage_v1",
10
131
  "get_upgrade_lease",
11
132
  "acquire_upgrade_lease",
12
133
  "release_upgrade_lease",
13
134
  "create_session",
14
135
  "attach_session",
136
+ // Distinct request kind: old hosts must refuse instead of ignoring a pin.
137
+ "attach_session_if_incarnation",
15
138
  "detach_session",
16
139
  "send_input",
17
140
  "send_input_if_seq",
@@ -32,6 +155,7 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
32
155
  "send_signal",
33
156
  "restart_session",
34
157
  "prune_duplicate_sessions",
158
+ "get_session_census",
35
159
  "get_session",
36
160
  "list_sessions"
37
161
  ];
@@ -70,6 +194,7 @@ function classifyTermination(input) {
70
194
  }
71
195
 
72
196
  // src/cli-child-priority.ts
197
+ import * as fs from "fs";
73
198
  import * as os from "os";
74
199
 
75
200
  // src/process/hidden-spawn.ts
@@ -89,6 +214,13 @@ function setDarwinBackground(pid, onFailure) {
89
214
  if (code !== 0) onFailure(new Error(`taskpolicy exited with ${signal ?? code}`));
90
215
  });
91
216
  }
217
+ var POSIX_NICE_BINARY = "/usr/bin/nice";
218
+ function niceLaunch(command, args, env = process.env, platform2 = process.platform, niceAvailable = () => fs.existsSync(POSIX_NICE_BINARY)) {
219
+ if (env[CLI_CHILD_NICE_ENV] === "0" || platform2 !== "darwin" && platform2 !== "linux" || !command || !niceAvailable()) {
220
+ return { command, args: [...args], preApplied: false };
221
+ }
222
+ return { command: POSIX_NICE_BINARY, args: ["-n", String(CLI_CHILD_NICE_INCREMENT), command, ...args], preApplied: true };
223
+ }
92
224
  function createCliChildPriorityPolicy(deps = {
93
225
  platform: process.platform,
94
226
  getPriority: os.getPriority,
@@ -96,7 +228,7 @@ function createCliChildPriorityPolicy(deps = {
96
228
  setDarwinBackground
97
229
  }) {
98
230
  let failureLogged = false;
99
- return function spawnCliChild2(spawnChild, env = process.env, logInfo = console.info) {
231
+ return function spawnCliChild2(spawnChild, env = process.env, logInfo = console.info, opts = {}) {
100
232
  const child = spawnChild();
101
233
  const pid = child.pid;
102
234
  if (env[CLI_CHILD_NICE_ENV] === "0" || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return child;
@@ -107,11 +239,13 @@ function createCliChildPriorityPolicy(deps = {
107
239
  logInfo(`[cli-child-priority] Could not apply CLI child scheduling (pid ${pid}); continuing: ${detail}`);
108
240
  }
109
241
  };
110
- try {
111
- const priority = deps.platform === "win32" ? os.constants.priority.PRIORITY_BELOW_NORMAL : Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
112
- deps.setPriority(pid, priority);
113
- } catch (error) {
114
- onFailure(error);
242
+ if (!opts.preApplied) {
243
+ try {
244
+ const priority = deps.platform === "win32" ? os.constants.priority.PRIORITY_BELOW_NORMAL : Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
245
+ deps.setPriority(pid, priority);
246
+ } catch (error) {
247
+ onFailure(error);
248
+ }
115
249
  }
116
250
  if (deps.platform === "darwin" && env[CLI_CHILD_SCHEDULING_ENV] === "darwin-bg") {
117
251
  try {
@@ -546,10 +680,38 @@ var SessionHostRegistry = class {
546
680
  listSessions() {
547
681
  return Array.from(this.sessions.values()).map((state) => this.cloneRecord(state.record)).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
548
682
  }
683
+ /** No launch bodies are cloned. Unknown role evidence stays conservative. */
684
+ getSessionCensus(sessionIds) {
685
+ if (!Array.isArray(sessionIds) || sessionIds.length > 128 || sessionIds.some((id) => typeof id !== "string" || id.length === 0 || id.length > 256)) {
686
+ throw new Error("Invalid session census: at most 128 identities of 256 characters");
687
+ }
688
+ const requested = new Set(sessionIds);
689
+ const liveSessionIds = [];
690
+ let hasOtherAssistantCandidates = false;
691
+ for (const { record } of this.sessions.values()) {
692
+ if (record.category !== "cli" || record.termination || !["starting", "running", "stopping", "interrupted"].includes(record.lifecycle)) continue;
693
+ if (requested.has(record.sessionId)) liveSessionIds.push(record.sessionId);
694
+ else {
695
+ const launch = record.meta?.launchRecord;
696
+ if (record.meta?.assistant === true || launch?.launchedBy === "assistant" || launch?.roleLaunch?.role === "assistant") {
697
+ hasOtherAssistantCandidates = true;
698
+ }
699
+ }
700
+ }
701
+ return { liveSessionIds, hasOtherAssistantCandidates };
702
+ }
549
703
  getSession(sessionId) {
550
704
  const state = this.sessions.get(sessionId);
551
705
  return state ? this.cloneRecord(state.record) : null;
552
706
  }
707
+ attachClientIfIncarnation(payload) {
708
+ const record = this.requireSession(payload.sessionId).record;
709
+ const expected = payload.expectedIncarnation;
710
+ 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) {
711
+ throw new Error(`Runtime not found for session: ${payload.sessionId} (incarnation changed)`);
712
+ }
713
+ return this.attachClient(payload);
714
+ }
553
715
  attachClient(payload) {
554
716
  const state = this.requireSession(payload.sessionId);
555
717
  const now = Date.now();
@@ -727,6 +889,7 @@ function cloneMeta(meta) {
727
889
  import * as os2 from "os";
728
890
  import * as path2 from "path";
729
891
  import * as net from "net";
892
+ import { createHash } from "crypto";
730
893
  import { StringDecoder } from "string_decoder";
731
894
  function validateSessionHostEndpoint(endpoint, platform2 = process.platform) {
732
895
  if (endpoint.kind !== "unix") return;
@@ -749,10 +912,17 @@ function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
749
912
  path: `\\\\.\\pipe\\${appName}-session-host${suffix}`
750
913
  };
751
914
  }
752
- return {
915
+ const endpoint = {
753
916
  kind: "unix",
754
- path: path2.join(os2.tmpdir(), `${appName}-session-host${suffix}.sock`)
917
+ path: path2.join(options.tmpDir ?? os2.tmpdir(), `${appName}-session-host${suffix}.sock`)
755
918
  };
919
+ const limit = platform2 === "linux" ? 108 : 104;
920
+ if (Buffer.byteLength(endpoint.path, "utf8") + 1 <= limit) return endpoint;
921
+ const identity = JSON.stringify([endpoint.path, appName, rawKey, process.getuid?.() ?? null]);
922
+ const digest = createHash("sha256").update(identity, "utf8").digest("hex");
923
+ const shortened = { kind: "unix", path: `/tmp/adhdev-sh-${digest}.sock` };
924
+ validateSessionHostEndpoint(shortened, platform2);
925
+ return shortened;
756
926
  }
757
927
  function serializeEnvelope(envelope) {
758
928
  return `${JSON.stringify(envelope)}
@@ -926,17 +1096,8 @@ var SessionHostClient = class {
926
1096
  observerLagMs
927
1097
  }
928
1098
  );
929
- if (this.socket === socket) {
930
- this.disconnect(timeoutError);
931
- } else {
932
- this.requestWaiters.delete(requestId);
933
- this.disconnectedSockets.add(socket);
934
- try {
935
- socket.destroy();
936
- } catch {
937
- }
938
- reject(timeoutError);
939
- }
1099
+ this.requestWaiters.delete(requestId);
1100
+ reject(timeoutError);
940
1101
  }, timeoutMs);
941
1102
  this.requestWaiters.set(requestId, {
942
1103
  resolve: (value) => {
@@ -1081,7 +1242,7 @@ var SessionHostClient = class {
1081
1242
  const raceStartedMonotonicAt = performance.now();
1082
1243
  try {
1083
1244
  await Promise.race([
1084
- this.connect(timeoutMs),
1245
+ this.connect(),
1085
1246
  new Promise((_resolve, reject) => {
1086
1247
  timer = setTimeout(() => {
1087
1248
  const actualElapsedMs = Math.max(0, Math.round(performance.now() - raceStartedMonotonicAt));
@@ -1098,7 +1259,6 @@ var SessionHostClient = class {
1098
1259
  }
1099
1260
  );
1100
1261
  reject(error);
1101
- this.disconnect(error);
1102
1262
  }, timeoutMs);
1103
1263
  })
1104
1264
  ]);
@@ -1187,7 +1347,7 @@ function writeEnvelope(socket, envelope) {
1187
1347
 
1188
1348
  // src/instance-key.ts
1189
1349
  import * as crypto2 from "crypto";
1190
- import * as fs from "fs";
1350
+ import * as fs2 from "fs";
1191
1351
  import * as os3 from "os";
1192
1352
  import * as path3 from "path";
1193
1353
  var DEFAULT_CONFIG_DIR_NAME = ".adhdev";
@@ -1214,7 +1374,7 @@ function realpathLongestExistingPrefix(resolved) {
1214
1374
  const remainder = [];
1215
1375
  for (let depth = 0; depth < 256; depth++) {
1216
1376
  try {
1217
- const real = fs.realpathSync.native(current);
1377
+ const real = fs2.realpathSync.native(current);
1218
1378
  return remainder.length === 0 ? real : path3.join(real, ...remainder);
1219
1379
  } catch {
1220
1380
  const parent = path3.dirname(current);
@@ -1305,14 +1465,14 @@ function applyTerminalColorEnv(env) {
1305
1465
  function ensureNodePtySpawnHelperPermissions(logFn) {
1306
1466
  if (os4.platform() === "win32") return;
1307
1467
  try {
1308
- const fs2 = __require("fs");
1468
+ const fs3 = __require("fs");
1309
1469
  const ptyDir = path4.resolve(path4.dirname(__require.resolve("node-pty")), "..");
1310
1470
  const platformArch = `${os4.platform()}-${os4.arch()}`;
1311
1471
  const helper = path4.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
1312
- if (fs2.existsSync(helper)) {
1313
- const stat = fs2.statSync(helper);
1472
+ if (fs3.existsSync(helper)) {
1473
+ const stat = fs3.statSync(helper);
1314
1474
  if (!(stat.mode & 73)) {
1315
- fs2.chmodSync(helper, stat.mode | 493);
1475
+ fs3.chmodSync(helper, stat.mode | 493);
1316
1476
  logFn?.(`Fixed spawn-helper permissions: ${helper}`);
1317
1477
  }
1318
1478
  }
@@ -1369,11 +1529,14 @@ export {
1369
1529
  DEFAULT_SESSION_HOST_COLS,
1370
1530
  DEFAULT_SESSION_HOST_ROWS,
1371
1531
  DEFAULT_SESSION_RING_BUFFER_MAX_BYTES,
1532
+ OPERATOR_RECOVERY_TARGET,
1533
+ RecoveryOwnerAdmission,
1372
1534
  SESSION_HOST_SUPPORTED_REQUEST_TYPES,
1373
1535
  SessionHostClient,
1374
1536
  SessionHostRegistry,
1375
1537
  SessionRingBuffer,
1376
1538
  applyTerminalColorEnv,
1539
+ assertRecoveryLaunchIdentity,
1377
1540
  assertTestStorageIsolated,
1378
1541
  buildRuntimeDisplayName,
1379
1542
  buildRuntimeKey,
@@ -1393,11 +1556,14 @@ export {
1393
1556
  getWorkspaceLabel,
1394
1557
  hiddenSpawn as hiddenSpawnProcess,
1395
1558
  isDefaultInstanceConfigDir,
1559
+ isRecoveryEndpoint,
1396
1560
  isSessionHostLiveRuntime,
1397
1561
  isSessionHostRecoverySnapshot,
1398
1562
  isTerminalRecord,
1563
+ niceLaunch,
1399
1564
  partitionSessionHostDiagnosticsSessions,
1400
1565
  partitionSessionHostRecords,
1566
+ recoveryTargetBytes,
1401
1567
  replayLaunchEnv,
1402
1568
  resolveAttachableRuntimeRecord,
1403
1569
  resolveInstanceConfigDir,