@adhdev/session-host-core 1.0.82-rc.36 → 1.0.82-rc.38

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
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX: () => CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
33
34
  CLI_CHILD_NICE_ENV: () => CLI_CHILD_NICE_ENV,
34
35
  CLI_CHILD_NICE_INCREMENT: () => CLI_CHILD_NICE_INCREMENT,
35
36
  CLI_CHILD_SCHEDULING_ENV: () => CLI_CHILD_SCHEDULING_ENV,
@@ -37,14 +38,11 @@ __export(index_exports, {
37
38
  DEFAULT_SESSION_HOST_COLS: () => DEFAULT_SESSION_HOST_COLS,
38
39
  DEFAULT_SESSION_HOST_ROWS: () => DEFAULT_SESSION_HOST_ROWS,
39
40
  DEFAULT_SESSION_RING_BUFFER_MAX_BYTES: () => DEFAULT_SESSION_RING_BUFFER_MAX_BYTES,
40
- OPERATOR_RECOVERY_TARGET: () => OPERATOR_RECOVERY_TARGET,
41
- RecoveryOwnerAdmission: () => RecoveryOwnerAdmission,
42
41
  SESSION_HOST_SUPPORTED_REQUEST_TYPES: () => SESSION_HOST_SUPPORTED_REQUEST_TYPES,
43
42
  SessionHostClient: () => SessionHostClient,
44
43
  SessionHostRegistry: () => SessionHostRegistry,
45
44
  SessionRingBuffer: () => SessionRingBuffer,
46
45
  applyTerminalColorEnv: () => applyTerminalColorEnv,
47
- assertRecoveryLaunchIdentity: () => assertRecoveryLaunchIdentity,
48
46
  assertTestStorageIsolated: () => assertTestStorageIsolated,
49
47
  buildRuntimeDisplayName: () => buildRuntimeDisplayName,
50
48
  buildRuntimeKey: () => buildRuntimeKey,
@@ -63,17 +61,19 @@ __export(index_exports, {
63
61
  getSessionHostSurfaceKind: () => getSessionHostSurfaceKind,
64
62
  getWorkspaceLabel: () => getWorkspaceLabel,
65
63
  hiddenSpawnProcess: () => hiddenSpawn,
64
+ hostBootIdFromStartedAt: () => hostBootIdFromStartedAt,
66
65
  isDefaultInstanceConfigDir: () => isDefaultInstanceConfigDir,
67
- isRecoveryEndpoint: () => isRecoveryEndpoint,
68
66
  isSessionHostLiveRuntime: () => isSessionHostLiveRuntime,
69
67
  isSessionHostRecoverySnapshot: () => isSessionHostRecoverySnapshot,
70
68
  isTerminalRecord: () => isTerminalRecord,
71
69
  niceLaunch: () => niceLaunch,
72
70
  partitionSessionHostDiagnosticsSessions: () => partitionSessionHostDiagnosticsSessions,
73
71
  partitionSessionHostRecords: () => partitionSessionHostRecords,
74
- recoveryTargetBytes: () => recoveryTargetBytes,
72
+ refuseCleanupExpectedDelete: () => refuseCleanupExpectedDelete,
73
+ refuseCleanupExpectedStop: () => refuseCleanupExpectedStop,
75
74
  replayLaunchEnv: () => replayLaunchEnv,
76
75
  resolveAttachableRuntimeRecord: () => resolveAttachableRuntimeRecord,
76
+ resolveHostBootId: () => resolveHostBootId,
77
77
  resolveInstanceConfigDir: () => resolveInstanceConfigDir,
78
78
  resolveRuntimeRecord: () => resolveRuntimeRecord,
79
79
  resolveSessionHostCols: () => resolveSessionHostCols,
@@ -81,134 +81,15 @@ __export(index_exports, {
81
81
  resolveSessionHostRows: () => resolveSessionHostRows,
82
82
  sanitizeSpawnEnv: () => sanitizeSpawnEnv,
83
83
  spawnCliChild: () => spawnCliChild,
84
+ stripCleanupAfterStopSideEffect: () => stripCleanupAfterStopSideEffect,
85
+ tagCleanupAfterStopSideEffect: () => tagCleanupAfterStopSideEffect,
84
86
  validateSessionHostEndpoint: () => validateSessionHostEndpoint,
85
87
  writeEnvelope: () => writeEnvelope
86
88
  });
87
89
  module.exports = __toCommonJS(index_exports);
88
90
 
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
-
206
91
  // src/types.ts
207
92
  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",
212
93
  "get_upgrade_lease",
213
94
  "acquire_upgrade_lease",
214
95
  "release_upgrade_lease",
@@ -222,8 +103,10 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
222
103
  "get_input_state",
223
104
  "resize_session",
224
105
  "stop_session",
106
+ "stop_session_if_expected",
225
107
  "stop_mesh_writer",
226
108
  "delete_session",
109
+ "delete_session_if_expected",
227
110
  "resume_session",
228
111
  "acquire_write",
229
112
  "release_write",
@@ -241,6 +124,71 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
241
124
  "list_sessions"
242
125
  ];
243
126
 
127
+ // src/cleanup-expected.ts
128
+ var CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX = "cleanup_after_stop_side_effect:";
129
+ function tagCleanupAfterStopSideEffect(code) {
130
+ return `${CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX}${code}`;
131
+ }
132
+ function stripCleanupAfterStopSideEffect(raw) {
133
+ if (raw.startsWith(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX)) {
134
+ return { afterStop: true, code: raw.slice(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX.length) };
135
+ }
136
+ return { afterStop: false, code: raw };
137
+ }
138
+ function hostBootIdFromStartedAt(hostStartedAt) {
139
+ return `hs:${hostStartedAt}`;
140
+ }
141
+ function resolveHostBootId(opts) {
142
+ if (typeof opts.upgradeBootId === "string" && opts.upgradeBootId) return opts.upgradeBootId;
143
+ if (!Number.isFinite(opts.hostStartedAt) || opts.hostStartedAt <= 0) return null;
144
+ return hostBootIdFromStartedAt(opts.hostStartedAt);
145
+ }
146
+ function refuseCleanupExpectedIdentity(record, expected, currentHostBootId) {
147
+ 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) {
148
+ return "cleanup_expected_malformed";
149
+ }
150
+ if (!currentHostBootId) return "cleanup_host_boot_unknown";
151
+ if (expected.hostBootId !== currentHostBootId) return "cleanup_host_boot_mismatch";
152
+ if (!record) return "cleanup_session_not_running";
153
+ if (record.runtimeKey !== expected.runtimeKey || record.startedAt !== expected.startedAt) {
154
+ return "cleanup_native_incarnation_mismatch";
155
+ }
156
+ return null;
157
+ }
158
+ function refuseCleanupExpectedAssignment(record, expected, opts = {}) {
159
+ const active = record.meta?.meshActiveAssignment;
160
+ if (expected.taskId === null) {
161
+ if (active && typeof active.taskId === "string" && active.taskId) return "cleanup_expected_unbound_now_bound";
162
+ return null;
163
+ }
164
+ if (!active || typeof active.taskId !== "string" || !active.taskId) {
165
+ return opts.allowClearedBound ? null : "cleanup_expected_bound_now_unbound";
166
+ }
167
+ if (active.taskId !== expected.taskId || active.attemptId !== expected.attemptId || active.generation !== expected.generation || active.dispatchNonce !== expected.dispatchNonce) {
168
+ return "cleanup_assignment_mismatch";
169
+ }
170
+ return null;
171
+ }
172
+ function refuseCleanupExpectedStop(record, expected, currentHostBootId, hasRuntime) {
173
+ const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
174
+ if (identity) return identity;
175
+ if (!record || record.termination || !hasRuntime || record.lifecycle !== "running") {
176
+ return "cleanup_session_not_running";
177
+ }
178
+ return refuseCleanupExpectedAssignment(record, expected);
179
+ }
180
+ function refuseCleanupExpectedDelete(record, expected, currentHostBootId, hasRuntime, force) {
181
+ if (!record) return "cleanup_session_not_running";
182
+ const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
183
+ if (identity) return identity;
184
+ if (hasRuntime) {
185
+ if (!force) return "cleanup_session_still_running";
186
+ if (record.termination || record.lifecycle !== "running") return "cleanup_session_not_running";
187
+ return refuseCleanupExpectedAssignment(record, expected);
188
+ }
189
+ return refuseCleanupExpectedAssignment(record, expected, { allowClearedBound: true });
190
+ }
191
+
244
192
  // src/termination.ts
245
193
  function classifyTermination(input) {
246
194
  const { exitCode, terminatedAt } = input;
@@ -1567,15 +1515,48 @@ function createSessionHostControlPlane(transport) {
1567
1515
  getDiagnostics(payload = {}) {
1568
1516
  return transport.request("get_host_diagnostics", payload);
1569
1517
  },
1518
+ async resolveHostBootId() {
1519
+ let diagnostics;
1520
+ try {
1521
+ diagnostics = await transport.request("get_host_diagnostics", {});
1522
+ } catch {
1523
+ return null;
1524
+ }
1525
+ if (typeof diagnostics.hostBootId === "string" && diagnostics.hostBootId) {
1526
+ return diagnostics.hostBootId;
1527
+ }
1528
+ try {
1529
+ const proof = await transport.request("get_upgrade_lease", {});
1530
+ return resolveHostBootId({
1531
+ upgradeBootId: typeof proof?.bootId === "string" ? proof.bootId : null,
1532
+ hostStartedAt: diagnostics.hostStartedAt
1533
+ });
1534
+ } catch (error) {
1535
+ const msg = error instanceof Error ? error.message : String(error);
1536
+ if (msg.includes("native_host_upgrade_binding_unavailable") || /unsupported|unknown request/i.test(msg)) {
1537
+ return resolveHostBootId({ hostStartedAt: diagnostics.hostStartedAt });
1538
+ }
1539
+ return null;
1540
+ }
1541
+ },
1570
1542
  listSessions() {
1571
1543
  return transport.request("list_sessions", {});
1572
1544
  },
1573
1545
  stopSession(sessionId) {
1574
1546
  return transport.request("stop_session", { sessionId });
1575
1547
  },
1548
+ stopSessionIfExpected(sessionId, expected) {
1549
+ return transport.request("stop_session_if_expected", { sessionId, expected });
1550
+ },
1576
1551
  deleteSession(sessionId, opts = {}) {
1577
1552
  return transport.request("delete_session", { sessionId, force: opts.force === true });
1578
1553
  },
1554
+ deleteSessionIfExpected(sessionId, expected, opts = {}) {
1555
+ return transport.request(
1556
+ "delete_session_if_expected",
1557
+ { sessionId, expected, force: opts.force === true }
1558
+ );
1559
+ },
1579
1560
  resumeSession(sessionId) {
1580
1561
  return transport.request("resume_session", { sessionId });
1581
1562
  },
@@ -1604,6 +1585,7 @@ function createSessionHostControlPlane(transport) {
1604
1585
  }
1605
1586
  // Annotate the CommonJS export names for ESM import in node:
1606
1587
  0 && (module.exports = {
1588
+ CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
1607
1589
  CLI_CHILD_NICE_ENV,
1608
1590
  CLI_CHILD_NICE_INCREMENT,
1609
1591
  CLI_CHILD_SCHEDULING_ENV,
@@ -1611,14 +1593,11 @@ function createSessionHostControlPlane(transport) {
1611
1593
  DEFAULT_SESSION_HOST_COLS,
1612
1594
  DEFAULT_SESSION_HOST_ROWS,
1613
1595
  DEFAULT_SESSION_RING_BUFFER_MAX_BYTES,
1614
- OPERATOR_RECOVERY_TARGET,
1615
- RecoveryOwnerAdmission,
1616
1596
  SESSION_HOST_SUPPORTED_REQUEST_TYPES,
1617
1597
  SessionHostClient,
1618
1598
  SessionHostRegistry,
1619
1599
  SessionRingBuffer,
1620
1600
  applyTerminalColorEnv,
1621
- assertRecoveryLaunchIdentity,
1622
1601
  assertTestStorageIsolated,
1623
1602
  buildRuntimeDisplayName,
1624
1603
  buildRuntimeKey,
@@ -1637,17 +1616,19 @@ function createSessionHostControlPlane(transport) {
1637
1616
  getSessionHostSurfaceKind,
1638
1617
  getWorkspaceLabel,
1639
1618
  hiddenSpawnProcess,
1619
+ hostBootIdFromStartedAt,
1640
1620
  isDefaultInstanceConfigDir,
1641
- isRecoveryEndpoint,
1642
1621
  isSessionHostLiveRuntime,
1643
1622
  isSessionHostRecoverySnapshot,
1644
1623
  isTerminalRecord,
1645
1624
  niceLaunch,
1646
1625
  partitionSessionHostDiagnosticsSessions,
1647
1626
  partitionSessionHostRecords,
1648
- recoveryTargetBytes,
1627
+ refuseCleanupExpectedDelete,
1628
+ refuseCleanupExpectedStop,
1649
1629
  replayLaunchEnv,
1650
1630
  resolveAttachableRuntimeRecord,
1631
+ resolveHostBootId,
1651
1632
  resolveInstanceConfigDir,
1652
1633
  resolveRuntimeRecord,
1653
1634
  resolveSessionHostCols,
@@ -1655,6 +1636,8 @@ function createSessionHostControlPlane(transport) {
1655
1636
  resolveSessionHostRows,
1656
1637
  sanitizeSpawnEnv,
1657
1638
  spawnCliChild,
1639
+ stripCleanupAfterStopSideEffect,
1640
+ tagCleanupAfterStopSideEffect,
1658
1641
  validateSessionHostEndpoint,
1659
1642
  writeEnvelope
1660
1643
  });