@adhdev/session-host-core 1.0.82-rc.8 → 1.0.82-rc.81
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.d.mts +319 -4
- package/dist/index.d.ts +319 -4
- package/dist/index.js +596 -62
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +577 -62
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/cleanup-expected.ts +114 -0
- package/src/cli-child-priority.ts +117 -0
- package/src/control-plane.ts +58 -0
- package/src/index.ts +24 -0
- package/src/instance-key.ts +20 -1
- package/src/ipc.ts +289 -46
- package/src/process/hidden-spawn.ts +10 -0
- package/src/registry.ts +87 -0
- package/src/spawn-env.ts +11 -0
- package/src/types.ts +131 -1
package/dist/index.js
CHANGED
|
@@ -30,6 +30,10 @@ 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,
|
|
34
|
+
CLI_CHILD_NICE_ENV: () => CLI_CHILD_NICE_ENV,
|
|
35
|
+
CLI_CHILD_NICE_INCREMENT: () => CLI_CHILD_NICE_INCREMENT,
|
|
36
|
+
CLI_CHILD_SCHEDULING_ENV: () => CLI_CHILD_SCHEDULING_ENV,
|
|
33
37
|
DEFAULT_CONFIG_DIR_NAME: () => DEFAULT_CONFIG_DIR_NAME,
|
|
34
38
|
DEFAULT_SESSION_HOST_COLS: () => DEFAULT_SESSION_HOST_COLS,
|
|
35
39
|
DEFAULT_SESSION_HOST_ROWS: () => DEFAULT_SESSION_HOST_ROWS,
|
|
@@ -39,45 +43,70 @@ __export(index_exports, {
|
|
|
39
43
|
SessionHostRegistry: () => SessionHostRegistry,
|
|
40
44
|
SessionRingBuffer: () => SessionRingBuffer,
|
|
41
45
|
applyTerminalColorEnv: () => applyTerminalColorEnv,
|
|
46
|
+
assertTestStorageIsolated: () => assertTestStorageIsolated,
|
|
42
47
|
buildRuntimeDisplayName: () => buildRuntimeDisplayName,
|
|
43
48
|
buildRuntimeKey: () => buildRuntimeKey,
|
|
44
49
|
canonicalizeInstancePath: () => canonicalizeInstancePath,
|
|
45
50
|
classifyTermination: () => classifyTermination,
|
|
51
|
+
createCliChildPriorityPolicy: () => createCliChildPriorityPolicy,
|
|
46
52
|
createLineParser: () => createLineParser,
|
|
47
53
|
createResponseEnvelope: () => createResponseEnvelope,
|
|
48
54
|
createSessionHostControlPlane: () => createSessionHostControlPlane,
|
|
55
|
+
disconnectSessionHostClients: () => disconnectSessionHostClients,
|
|
49
56
|
ensureNodePtySpawnHelperPermissions: () => ensureNodePtySpawnHelperPermissions,
|
|
57
|
+
findConnectedSessionHostClient: () => findConnectedSessionHostClient,
|
|
50
58
|
formatRuntimeOwner: () => formatRuntimeOwner,
|
|
51
59
|
getDefaultSessionHostEndpoint: () => getDefaultSessionHostEndpoint,
|
|
52
60
|
getSessionHostRecoveryLabel: () => getSessionHostRecoveryLabel,
|
|
53
61
|
getSessionHostSurfaceKind: () => getSessionHostSurfaceKind,
|
|
54
62
|
getWorkspaceLabel: () => getWorkspaceLabel,
|
|
63
|
+
hiddenSpawnProcess: () => hiddenSpawn,
|
|
64
|
+
hostBootIdFromStartedAt: () => hostBootIdFromStartedAt,
|
|
55
65
|
isDefaultInstanceConfigDir: () => isDefaultInstanceConfigDir,
|
|
56
66
|
isSessionHostLiveRuntime: () => isSessionHostLiveRuntime,
|
|
57
67
|
isSessionHostRecoverySnapshot: () => isSessionHostRecoverySnapshot,
|
|
58
68
|
isTerminalRecord: () => isTerminalRecord,
|
|
69
|
+
niceLaunch: () => niceLaunch,
|
|
59
70
|
partitionSessionHostDiagnosticsSessions: () => partitionSessionHostDiagnosticsSessions,
|
|
60
71
|
partitionSessionHostRecords: () => partitionSessionHostRecords,
|
|
72
|
+
refuseCleanupExpectedDelete: () => refuseCleanupExpectedDelete,
|
|
73
|
+
refuseCleanupExpectedStop: () => refuseCleanupExpectedStop,
|
|
74
|
+
replayLaunchEnv: () => replayLaunchEnv,
|
|
61
75
|
resolveAttachableRuntimeRecord: () => resolveAttachableRuntimeRecord,
|
|
76
|
+
resolveHostBootId: () => resolveHostBootId,
|
|
62
77
|
resolveInstanceConfigDir: () => resolveInstanceConfigDir,
|
|
63
78
|
resolveRuntimeRecord: () => resolveRuntimeRecord,
|
|
64
79
|
resolveSessionHostCols: () => resolveSessionHostCols,
|
|
65
80
|
resolveSessionHostIpcKey: () => resolveSessionHostIpcKey,
|
|
66
81
|
resolveSessionHostRows: () => resolveSessionHostRows,
|
|
67
82
|
sanitizeSpawnEnv: () => sanitizeSpawnEnv,
|
|
83
|
+
spawnCliChild: () => spawnCliChild,
|
|
84
|
+
stripCleanupAfterStopSideEffect: () => stripCleanupAfterStopSideEffect,
|
|
85
|
+
tagCleanupAfterStopSideEffect: () => tagCleanupAfterStopSideEffect,
|
|
86
|
+
validateSessionHostEndpoint: () => validateSessionHostEndpoint,
|
|
68
87
|
writeEnvelope: () => writeEnvelope
|
|
69
88
|
});
|
|
70
89
|
module.exports = __toCommonJS(index_exports);
|
|
71
90
|
|
|
72
91
|
// src/types.ts
|
|
73
92
|
var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
|
|
93
|
+
"get_upgrade_lease",
|
|
94
|
+
"acquire_upgrade_lease",
|
|
95
|
+
"release_upgrade_lease",
|
|
74
96
|
"create_session",
|
|
75
97
|
"attach_session",
|
|
98
|
+
// Distinct request kind: old hosts must refuse instead of ignoring a pin.
|
|
99
|
+
"attach_session_if_incarnation",
|
|
76
100
|
"detach_session",
|
|
77
101
|
"send_input",
|
|
102
|
+
"send_input_if_seq",
|
|
103
|
+
"get_input_state",
|
|
78
104
|
"resize_session",
|
|
79
105
|
"stop_session",
|
|
106
|
+
"stop_session_if_expected",
|
|
107
|
+
"stop_mesh_writer",
|
|
80
108
|
"delete_session",
|
|
109
|
+
"delete_session_if_expected",
|
|
81
110
|
"resume_session",
|
|
82
111
|
"acquire_write",
|
|
83
112
|
"release_write",
|
|
@@ -90,9 +119,76 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
|
|
|
90
119
|
"send_signal",
|
|
91
120
|
"restart_session",
|
|
92
121
|
"prune_duplicate_sessions",
|
|
122
|
+
"get_session_census",
|
|
123
|
+
"get_session",
|
|
93
124
|
"list_sessions"
|
|
94
125
|
];
|
|
95
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
|
+
|
|
96
192
|
// src/termination.ts
|
|
97
193
|
function classifyTermination(input) {
|
|
98
194
|
const { exitCode, terminatedAt } = input;
|
|
@@ -126,6 +222,72 @@ function classifyTermination(input) {
|
|
|
126
222
|
return termination;
|
|
127
223
|
}
|
|
128
224
|
|
|
225
|
+
// src/cli-child-priority.ts
|
|
226
|
+
var fs = __toESM(require("fs"));
|
|
227
|
+
var os = __toESM(require("os"));
|
|
228
|
+
|
|
229
|
+
// src/process/hidden-spawn.ts
|
|
230
|
+
var import_node_child_process = require("child_process");
|
|
231
|
+
function hiddenSpawn(command, args = [], options = {}) {
|
|
232
|
+
return (0, import_node_child_process.spawn)(command, args, { windowsHide: true, ...options });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/cli-child-priority.ts
|
|
236
|
+
var CLI_CHILD_NICE_INCREMENT = 10;
|
|
237
|
+
var CLI_CHILD_NICE_ENV = "ADHDEV_CLI_CHILD_NICE";
|
|
238
|
+
var CLI_CHILD_SCHEDULING_ENV = "ADHDEV_CLI_CHILD_SCHEDULING";
|
|
239
|
+
function setDarwinBackground(pid, onFailure) {
|
|
240
|
+
const task = hiddenSpawn("/usr/sbin/taskpolicy", ["-b", "-p", String(pid)], { stdio: "ignore" });
|
|
241
|
+
task.once("error", onFailure);
|
|
242
|
+
task.once("exit", (code, signal) => {
|
|
243
|
+
if (code !== 0) onFailure(new Error(`taskpolicy exited with ${signal ?? code}`));
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
var POSIX_NICE_BINARY = "/usr/bin/nice";
|
|
247
|
+
function niceLaunch(command, args, env = process.env, platform2 = process.platform, niceAvailable = () => fs.existsSync(POSIX_NICE_BINARY)) {
|
|
248
|
+
if (env[CLI_CHILD_NICE_ENV] === "0" || platform2 !== "darwin" && platform2 !== "linux" || !command || !niceAvailable()) {
|
|
249
|
+
return { command, args: [...args], preApplied: false };
|
|
250
|
+
}
|
|
251
|
+
return { command: POSIX_NICE_BINARY, args: ["-n", String(CLI_CHILD_NICE_INCREMENT), command, ...args], preApplied: true };
|
|
252
|
+
}
|
|
253
|
+
function createCliChildPriorityPolicy(deps = {
|
|
254
|
+
platform: process.platform,
|
|
255
|
+
getPriority: os.getPriority,
|
|
256
|
+
setPriority: os.setPriority,
|
|
257
|
+
setDarwinBackground
|
|
258
|
+
}) {
|
|
259
|
+
let failureLogged = false;
|
|
260
|
+
return function spawnCliChild2(spawnChild, env = process.env, logInfo = console.info, opts = {}) {
|
|
261
|
+
const child = spawnChild();
|
|
262
|
+
const pid = child.pid;
|
|
263
|
+
if (env[CLI_CHILD_NICE_ENV] === "0" || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return child;
|
|
264
|
+
const onFailure = (error) => {
|
|
265
|
+
if (!failureLogged) {
|
|
266
|
+
failureLogged = true;
|
|
267
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
268
|
+
logInfo(`[cli-child-priority] Could not apply CLI child scheduling (pid ${pid}); continuing: ${detail}`);
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
if (!opts.preApplied) {
|
|
272
|
+
try {
|
|
273
|
+
const priority = deps.platform === "win32" ? os.constants.priority.PRIORITY_BELOW_NORMAL : Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
|
|
274
|
+
deps.setPriority(pid, priority);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
onFailure(error);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (deps.platform === "darwin" && env[CLI_CHILD_SCHEDULING_ENV] === "darwin-bg") {
|
|
280
|
+
try {
|
|
281
|
+
deps.setDarwinBackground?.(pid, onFailure);
|
|
282
|
+
} catch (error) {
|
|
283
|
+
onFailure(error);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return child;
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
var spawnCliChild = createCliChildPriorityPolicy();
|
|
290
|
+
|
|
129
291
|
// src/buffer.ts
|
|
130
292
|
var DEFAULT_SESSION_RING_BUFFER_MAX_BYTES = 4 * 1024 * 1024;
|
|
131
293
|
var SessionRingBuffer = class {
|
|
@@ -462,6 +624,13 @@ function formatRuntimeOwner(record) {
|
|
|
462
624
|
// src/registry.ts
|
|
463
625
|
var SessionHostRegistry = class {
|
|
464
626
|
sessions = /* @__PURE__ */ new Map();
|
|
627
|
+
/** This registry's lifetime; every inputEpoch it mints starts with it. */
|
|
628
|
+
lifetimeId = generateUUID();
|
|
629
|
+
epochCounter = 0;
|
|
630
|
+
mintInputEpoch() {
|
|
631
|
+
this.epochCounter += 1;
|
|
632
|
+
return `${this.lifetimeId}:${this.epochCounter}`;
|
|
633
|
+
}
|
|
465
634
|
createSession(payload) {
|
|
466
635
|
const sessionId = payload.sessionId || generateUUID();
|
|
467
636
|
if (this.sessions.has(sessionId)) {
|
|
@@ -493,6 +662,8 @@ var SessionHostRegistry = class {
|
|
|
493
662
|
lifecycle: "starting",
|
|
494
663
|
writeOwner: null,
|
|
495
664
|
attachedClients: initialClient,
|
|
665
|
+
inputSeq: 0,
|
|
666
|
+
inputEpoch: this.mintInputEpoch(),
|
|
496
667
|
buffer: {
|
|
497
668
|
scrollbackBytes: 0,
|
|
498
669
|
snapshotSeq: 0
|
|
@@ -512,6 +683,10 @@ var SessionHostRegistry = class {
|
|
|
512
683
|
}
|
|
513
684
|
restoreSession(record, snapshot) {
|
|
514
685
|
const cloned = this.cloneRecord(record);
|
|
686
|
+
if (typeof cloned.inputSeq !== "number") cloned.inputSeq = 0;
|
|
687
|
+
const live = this.sessions.get(cloned.sessionId)?.record;
|
|
688
|
+
const sameLifetime = !!live && typeof live.inputEpoch === "string" && cloned.inputEpoch === live.inputEpoch && cloned.inputSeq >= (live.inputSeq ?? 0);
|
|
689
|
+
if (!sameLifetime) cloned.inputEpoch = this.mintInputEpoch();
|
|
515
690
|
this.sessions.set(cloned.sessionId, {
|
|
516
691
|
record: cloned,
|
|
517
692
|
buffer: (() => {
|
|
@@ -522,13 +697,50 @@ var SessionHostRegistry = class {
|
|
|
522
697
|
});
|
|
523
698
|
return this.cloneRecord(cloned);
|
|
524
699
|
}
|
|
700
|
+
/** Census projection: omit launch arguments/environment and summarize stopped
|
|
701
|
+
* sessions. Full details remain available through getSession. */
|
|
702
|
+
listSessionSummaries(activeOnly = false) {
|
|
703
|
+
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({
|
|
704
|
+
...r,
|
|
705
|
+
launchCommand: { command: r.launchCommand.command, args: [] },
|
|
706
|
+
meta: r.termination || r.lifecycle === "stopped" || r.lifecycle === "failed" ? {} : { ...r.meta, cliArgs: [], cliArgsOmitted: true }
|
|
707
|
+
})).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
708
|
+
}
|
|
525
709
|
listSessions() {
|
|
526
710
|
return Array.from(this.sessions.values()).map((state) => this.cloneRecord(state.record)).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
527
711
|
}
|
|
712
|
+
/** No launch bodies are cloned. Unknown role evidence stays conservative. */
|
|
713
|
+
getSessionCensus(sessionIds) {
|
|
714
|
+
if (!Array.isArray(sessionIds) || sessionIds.length > 128 || sessionIds.some((id) => typeof id !== "string" || id.length === 0 || id.length > 256)) {
|
|
715
|
+
throw new Error("Invalid session census: at most 128 identities of 256 characters");
|
|
716
|
+
}
|
|
717
|
+
const requested = new Set(sessionIds);
|
|
718
|
+
const liveSessionIds = [];
|
|
719
|
+
let hasOtherAssistantCandidates = false;
|
|
720
|
+
for (const { record } of this.sessions.values()) {
|
|
721
|
+
if (record.category !== "cli" || record.termination || !["starting", "running", "stopping", "interrupted"].includes(record.lifecycle)) continue;
|
|
722
|
+
if (requested.has(record.sessionId)) liveSessionIds.push(record.sessionId);
|
|
723
|
+
else {
|
|
724
|
+
const launch = record.meta?.launchRecord;
|
|
725
|
+
if (record.meta?.assistant === true || launch?.launchedBy === "assistant" || launch?.roleLaunch?.role === "assistant") {
|
|
726
|
+
hasOtherAssistantCandidates = true;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return { liveSessionIds, hasOtherAssistantCandidates };
|
|
731
|
+
}
|
|
528
732
|
getSession(sessionId) {
|
|
529
733
|
const state = this.sessions.get(sessionId);
|
|
530
734
|
return state ? this.cloneRecord(state.record) : null;
|
|
531
735
|
}
|
|
736
|
+
attachClientIfIncarnation(payload) {
|
|
737
|
+
const record = this.requireSession(payload.sessionId).record;
|
|
738
|
+
const expected = payload.expectedIncarnation;
|
|
739
|
+
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) {
|
|
740
|
+
throw new Error(`Runtime not found for session: ${payload.sessionId} (incarnation changed)`);
|
|
741
|
+
}
|
|
742
|
+
return this.attachClient(payload);
|
|
743
|
+
}
|
|
532
744
|
attachClient(payload) {
|
|
533
745
|
const state = this.requireSession(payload.sessionId);
|
|
534
746
|
const now = Date.now();
|
|
@@ -573,6 +785,20 @@ var SessionHostRegistry = class {
|
|
|
573
785
|
state.record.lastActivityAt = Date.now();
|
|
574
786
|
return this.cloneRecord(state.record);
|
|
575
787
|
}
|
|
788
|
+
/** Count one accepted input (see SessionHostRecord.inputSeq); returns its number. */
|
|
789
|
+
recordInput(sessionId) {
|
|
790
|
+
const state = this.requireSession(sessionId);
|
|
791
|
+
state.record.inputSeq = (typeof state.record.inputSeq === "number" ? state.record.inputSeq : 0) + 1;
|
|
792
|
+
if (typeof state.record.inputEpoch !== "string") state.record.inputEpoch = this.mintInputEpoch();
|
|
793
|
+
return state.record.inputSeq;
|
|
794
|
+
}
|
|
795
|
+
/** The current input counter (see SessionHostInputState). */
|
|
796
|
+
getInputState(sessionId) {
|
|
797
|
+
const state = this.requireSession(sessionId);
|
|
798
|
+
if (typeof state.record.inputSeq !== "number") state.record.inputSeq = 0;
|
|
799
|
+
if (typeof state.record.inputEpoch !== "string") state.record.inputEpoch = this.mintInputEpoch();
|
|
800
|
+
return { inputSeq: state.record.inputSeq, inputEpoch: state.record.inputEpoch };
|
|
801
|
+
}
|
|
576
802
|
acquireWrite(payload) {
|
|
577
803
|
const state = this.requireSession(payload.sessionId);
|
|
578
804
|
if (state.record.writeOwner && state.record.writeOwner.clientId !== payload.clientId && !payload.force) {
|
|
@@ -689,10 +915,19 @@ function cloneMeta(meta) {
|
|
|
689
915
|
}
|
|
690
916
|
|
|
691
917
|
// src/ipc.ts
|
|
692
|
-
var
|
|
918
|
+
var os2 = __toESM(require("os"));
|
|
693
919
|
var path2 = __toESM(require("path"));
|
|
694
920
|
var net = __toESM(require("net"));
|
|
921
|
+
var import_crypto = require("crypto");
|
|
695
922
|
var import_string_decoder = require("string_decoder");
|
|
923
|
+
function validateSessionHostEndpoint(endpoint, platform2 = process.platform) {
|
|
924
|
+
if (endpoint.kind !== "unix") return;
|
|
925
|
+
const limit = platform2 === "linux" ? 108 : 104;
|
|
926
|
+
const pathBytes = Buffer.byteLength(endpoint.path, "utf8");
|
|
927
|
+
if (pathBytes + 1 > limit) {
|
|
928
|
+
throw new Error(`session_host_unix_socket_path_too_long: path_bytes=${pathBytes} required_bytes=${pathBytes + 1} limit_bytes=${limit} platform=${platform2}`);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
696
931
|
function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
|
|
697
932
|
const rawKey = typeof options.ipcKey === "string" ? options.ipcKey.trim() : "";
|
|
698
933
|
if (rawKey && !/^[0-9a-f]{12}$/.test(rawKey)) {
|
|
@@ -706,48 +941,102 @@ function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
|
|
|
706
941
|
path: `\\\\.\\pipe\\${appName}-session-host${suffix}`
|
|
707
942
|
};
|
|
708
943
|
}
|
|
709
|
-
|
|
944
|
+
const endpoint = {
|
|
710
945
|
kind: "unix",
|
|
711
|
-
path: path2.join(
|
|
946
|
+
path: path2.join(options.tmpDir ?? os2.tmpdir(), `${appName}-session-host${suffix}.sock`)
|
|
712
947
|
};
|
|
948
|
+
const limit = platform2 === "linux" ? 108 : 104;
|
|
949
|
+
if (Buffer.byteLength(endpoint.path, "utf8") + 1 <= limit) return endpoint;
|
|
950
|
+
const identity = JSON.stringify([endpoint.path, appName, rawKey, process.getuid?.() ?? null]);
|
|
951
|
+
const digest = (0, import_crypto.createHash)("sha256").update(identity, "utf8").digest("hex");
|
|
952
|
+
const shortened = { kind: "unix", path: `/tmp/adhdev-sh-${digest}.sock` };
|
|
953
|
+
validateSessionHostEndpoint(shortened, platform2);
|
|
954
|
+
return shortened;
|
|
713
955
|
}
|
|
714
956
|
function serializeEnvelope(envelope) {
|
|
715
957
|
return `${JSON.stringify(envelope)}
|
|
716
958
|
`;
|
|
717
959
|
}
|
|
718
960
|
function createLineParser(onEnvelope) {
|
|
719
|
-
let
|
|
961
|
+
let fragments = [];
|
|
720
962
|
const decoder = new import_string_decoder.StringDecoder("utf8");
|
|
721
963
|
const parser = (chunk) => {
|
|
722
|
-
|
|
723
|
-
let
|
|
724
|
-
|
|
725
|
-
const
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
964
|
+
const text = typeof chunk === "string" ? chunk : decoder.write(chunk);
|
|
965
|
+
let start = 0;
|
|
966
|
+
for (; ; ) {
|
|
967
|
+
const newline = text.indexOf("\n", start);
|
|
968
|
+
if (newline < 0) {
|
|
969
|
+
if (start < text.length) fragments.push(text.slice(start));
|
|
970
|
+
break;
|
|
729
971
|
}
|
|
730
|
-
|
|
972
|
+
fragments.push(text.slice(start, newline));
|
|
973
|
+
const rawLine = fragments.join("").trim();
|
|
974
|
+
fragments = [];
|
|
975
|
+
start = newline + 1;
|
|
976
|
+
if (rawLine) onEnvelope(JSON.parse(rawLine));
|
|
731
977
|
}
|
|
732
978
|
};
|
|
733
979
|
parser.end = () => {
|
|
734
|
-
const remainder =
|
|
735
|
-
|
|
980
|
+
const remainder = fragments.join("") + decoder.end();
|
|
981
|
+
fragments = [];
|
|
736
982
|
return remainder;
|
|
737
983
|
};
|
|
738
984
|
return parser;
|
|
739
985
|
}
|
|
740
986
|
var establishedSockets = /* @__PURE__ */ new WeakSet();
|
|
987
|
+
var activeClientRefs = /* @__PURE__ */ new Set();
|
|
988
|
+
function disconnectSessionHostClients(endpoint, error) {
|
|
989
|
+
for (const ref of activeClientRefs) {
|
|
990
|
+
const client = ref.deref();
|
|
991
|
+
if (!client) {
|
|
992
|
+
activeClientRefs.delete(ref);
|
|
993
|
+
continue;
|
|
994
|
+
}
|
|
995
|
+
if (!endpoint || client.endpoint.path === endpoint.path) {
|
|
996
|
+
client.disconnect(error);
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
function findConnectedSessionHostClient(endpoint) {
|
|
1001
|
+
for (const ref of activeClientRefs) {
|
|
1002
|
+
const client = ref.deref();
|
|
1003
|
+
if (!client) {
|
|
1004
|
+
activeClientRefs.delete(ref);
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
if ((!endpoint || client.endpoint.path === endpoint.path) && client.isConnected()) {
|
|
1008
|
+
return client;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
741
1013
|
var SessionHostClient = class {
|
|
742
1014
|
endpoint;
|
|
743
1015
|
socket = null;
|
|
1016
|
+
connectPromise = null;
|
|
1017
|
+
requestTimeoutMs = 3e4;
|
|
744
1018
|
requestWaiters = /* @__PURE__ */ new Map();
|
|
745
1019
|
eventListeners = /* @__PURE__ */ new Set();
|
|
746
1020
|
disconnectListeners = /* @__PURE__ */ new Set();
|
|
747
1021
|
/** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
|
|
748
1022
|
disconnectedSockets = /* @__PURE__ */ new WeakSet();
|
|
1023
|
+
/** Session subscriptions established via create_session/attach_session, replayed automatically on reconnect. */
|
|
1024
|
+
attachedSessions = /* @__PURE__ */ new Map();
|
|
749
1025
|
constructor(options = {}) {
|
|
750
1026
|
this.endpoint = options.endpoint || getDefaultSessionHostEndpoint(options.appName || "adhdev");
|
|
1027
|
+
if (typeof options.requestTimeoutMs === "number" && options.requestTimeoutMs > 0) {
|
|
1028
|
+
this.requestTimeoutMs = options.requestTimeoutMs;
|
|
1029
|
+
}
|
|
1030
|
+
if (options.registerAsShared !== false) activeClientRefs.add(new WeakRef(this));
|
|
1031
|
+
}
|
|
1032
|
+
static disconnectClients(endpoint, error) {
|
|
1033
|
+
disconnectSessionHostClients(endpoint, error);
|
|
1034
|
+
}
|
|
1035
|
+
static findConnectedClient(endpoint) {
|
|
1036
|
+
return findConnectedSessionHostClient(endpoint);
|
|
1037
|
+
}
|
|
1038
|
+
isConnected() {
|
|
1039
|
+
return Boolean(this.socket && !this.socket.destroyed && establishedSockets.has(this.socket));
|
|
751
1040
|
}
|
|
752
1041
|
/**
|
|
753
1042
|
* Fires when an established connection to the session host goes away.
|
|
@@ -790,6 +1079,7 @@ var SessionHostClient = class {
|
|
|
790
1079
|
this.requestWaiters.clear();
|
|
791
1080
|
if (this.socket === socket) {
|
|
792
1081
|
this.socket = null;
|
|
1082
|
+
this.connectPromise = null;
|
|
793
1083
|
}
|
|
794
1084
|
try {
|
|
795
1085
|
socket.destroy();
|
|
@@ -809,8 +1099,53 @@ var SessionHostClient = class {
|
|
|
809
1099
|
}
|
|
810
1100
|
}
|
|
811
1101
|
}
|
|
812
|
-
|
|
813
|
-
|
|
1102
|
+
sendRawRequestOnSocket(socket, request, timeoutMs = this.requestTimeoutMs) {
|
|
1103
|
+
const requestId = generateUUID();
|
|
1104
|
+
const envelope = {
|
|
1105
|
+
kind: "request",
|
|
1106
|
+
requestId,
|
|
1107
|
+
request
|
|
1108
|
+
};
|
|
1109
|
+
const timeoutLabel = timeoutMs % 1e3 === 0 ? `${timeoutMs / 1e3}s` : `${timeoutMs}ms`;
|
|
1110
|
+
const startedAt = Date.now();
|
|
1111
|
+
const startedMonotonicAt = performance.now();
|
|
1112
|
+
return new Promise((resolve3, reject) => {
|
|
1113
|
+
const timeout = setTimeout(() => {
|
|
1114
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - startedMonotonicAt));
|
|
1115
|
+
const wallElapsedMs = Math.max(0, Date.now() - startedAt);
|
|
1116
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
1117
|
+
const timeoutError = Object.assign(
|
|
1118
|
+
new Error(`Session host request timed out after ${timeoutLabel} (${request.type})`),
|
|
1119
|
+
{
|
|
1120
|
+
code: "SESSION_HOST_REQUEST_TIMEOUT",
|
|
1121
|
+
requestType: request.type,
|
|
1122
|
+
scheduledTimeoutMs: timeoutMs,
|
|
1123
|
+
actualElapsedMs,
|
|
1124
|
+
wallElapsedMs,
|
|
1125
|
+
observerLagMs
|
|
1126
|
+
}
|
|
1127
|
+
);
|
|
1128
|
+
this.requestWaiters.delete(requestId);
|
|
1129
|
+
reject(timeoutError);
|
|
1130
|
+
}, timeoutMs);
|
|
1131
|
+
this.requestWaiters.set(requestId, {
|
|
1132
|
+
resolve: (value) => {
|
|
1133
|
+
clearTimeout(timeout);
|
|
1134
|
+
resolve3(value);
|
|
1135
|
+
},
|
|
1136
|
+
reject: (error) => {
|
|
1137
|
+
clearTimeout(timeout);
|
|
1138
|
+
reject(error);
|
|
1139
|
+
}
|
|
1140
|
+
});
|
|
1141
|
+
socket.write(serializeEnvelope(envelope));
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
async connect(timeoutMs = this.requestTimeoutMs) {
|
|
1145
|
+
if (this.socket && !this.socket.destroyed) {
|
|
1146
|
+
if (this.connectPromise) await this.connectPromise;
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
814
1149
|
if (this.socket) {
|
|
815
1150
|
try {
|
|
816
1151
|
this.socket.destroy();
|
|
@@ -818,6 +1153,7 @@ var SessionHostClient = class {
|
|
|
818
1153
|
}
|
|
819
1154
|
this.socket = null;
|
|
820
1155
|
}
|
|
1156
|
+
this.connectPromise = null;
|
|
821
1157
|
const socket = net.createConnection(this.endpoint.path);
|
|
822
1158
|
this.socket = socket;
|
|
823
1159
|
const parser = createLineParser((envelope) => {
|
|
@@ -830,7 +1166,12 @@ var SessionHostClient = class {
|
|
|
830
1166
|
return;
|
|
831
1167
|
}
|
|
832
1168
|
if (envelope.kind === "event") {
|
|
833
|
-
for (const listener of this.eventListeners)
|
|
1169
|
+
for (const listener of this.eventListeners) {
|
|
1170
|
+
try {
|
|
1171
|
+
listener(envelope.event);
|
|
1172
|
+
} catch {
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
834
1175
|
}
|
|
835
1176
|
});
|
|
836
1177
|
socket.on("data", parser);
|
|
@@ -851,13 +1192,68 @@ var SessionHostClient = class {
|
|
|
851
1192
|
socket.on("end", () => {
|
|
852
1193
|
this.handleDisconnect(socket, "ended", void 0, flushParser().length);
|
|
853
1194
|
});
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
1195
|
+
const connectTask = (async () => {
|
|
1196
|
+
await new Promise((resolve3, reject) => {
|
|
1197
|
+
const cleanup = () => {
|
|
1198
|
+
clearTimeout(timer);
|
|
1199
|
+
socket.off("connect", connected);
|
|
1200
|
+
socket.off("error", failed);
|
|
1201
|
+
socket.off("close", closed);
|
|
1202
|
+
};
|
|
1203
|
+
const connected = () => {
|
|
1204
|
+
cleanup();
|
|
1205
|
+
establishedSockets.add(socket);
|
|
1206
|
+
resolve3();
|
|
1207
|
+
};
|
|
1208
|
+
const failed = (error) => {
|
|
1209
|
+
cleanup();
|
|
1210
|
+
reject(error);
|
|
1211
|
+
};
|
|
1212
|
+
const closed = () => failed(new Error("Session host connection closed before connect"));
|
|
1213
|
+
const connectStartedAt = Date.now();
|
|
1214
|
+
const connectStartedMonotonicAt = performance.now();
|
|
1215
|
+
const timer = setTimeout(() => {
|
|
1216
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - connectStartedMonotonicAt));
|
|
1217
|
+
const wallElapsedMs = Math.max(0, Date.now() - connectStartedAt);
|
|
1218
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
1219
|
+
const error = Object.assign(
|
|
1220
|
+
new Error(`Session host connect timed out after ${timeoutMs}ms`),
|
|
1221
|
+
{
|
|
1222
|
+
code: "SESSION_HOST_CONNECT_TIMEOUT",
|
|
1223
|
+
scheduledTimeoutMs: timeoutMs,
|
|
1224
|
+
actualElapsedMs,
|
|
1225
|
+
wallElapsedMs,
|
|
1226
|
+
observerLagMs
|
|
1227
|
+
}
|
|
1228
|
+
);
|
|
1229
|
+
failed(error);
|
|
1230
|
+
if (this.socket === socket) this.disconnect(error);
|
|
1231
|
+
}, timeoutMs);
|
|
1232
|
+
socket.once("connect", connected);
|
|
1233
|
+
socket.once("error", failed);
|
|
1234
|
+
socket.once("close", closed);
|
|
858
1235
|
});
|
|
859
|
-
socket.
|
|
860
|
-
|
|
1236
|
+
if (this.attachedSessions.size > 0 && this.socket === socket && !socket.destroyed) {
|
|
1237
|
+
for (const [sessionId, sub] of [...this.attachedSessions.entries()]) {
|
|
1238
|
+
if (this.socket !== socket || socket.destroyed) break;
|
|
1239
|
+
const replayResponse = await this.sendRawRequestOnSocket(socket, {
|
|
1240
|
+
type: "attach_session",
|
|
1241
|
+
payload: sub
|
|
1242
|
+
}).catch(() => null);
|
|
1243
|
+
if (replayResponse && !replayResponse.success) {
|
|
1244
|
+
this.attachedSessions.delete(sessionId);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
})();
|
|
1249
|
+
this.connectPromise = connectTask;
|
|
1250
|
+
try {
|
|
1251
|
+
await connectTask;
|
|
1252
|
+
} finally {
|
|
1253
|
+
if (this.connectPromise === connectTask) {
|
|
1254
|
+
this.connectPromise = null;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
861
1257
|
}
|
|
862
1258
|
onEvent(listener) {
|
|
863
1259
|
this.eventListeners.add(listener);
|
|
@@ -865,35 +1261,86 @@ var SessionHostClient = class {
|
|
|
865
1261
|
this.eventListeners.delete(listener);
|
|
866
1262
|
};
|
|
867
1263
|
}
|
|
868
|
-
async request(request) {
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
const
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
1264
|
+
async request(request, options = {}) {
|
|
1265
|
+
const timeoutMs = Math.max(1, options.timeoutMs ?? this.requestTimeoutMs);
|
|
1266
|
+
const deadline = Date.now() + timeoutMs;
|
|
1267
|
+
const alreadyConnected = this.isConnected() && !this.connectPromise;
|
|
1268
|
+
if (options.timeoutMs !== void 0) {
|
|
1269
|
+
let timer;
|
|
1270
|
+
const raceStartedAt = Date.now();
|
|
1271
|
+
const raceStartedMonotonicAt = performance.now();
|
|
1272
|
+
try {
|
|
1273
|
+
await Promise.race([
|
|
1274
|
+
this.connect(),
|
|
1275
|
+
new Promise((_resolve, reject) => {
|
|
1276
|
+
timer = setTimeout(() => {
|
|
1277
|
+
const actualElapsedMs = Math.max(0, Math.round(performance.now() - raceStartedMonotonicAt));
|
|
1278
|
+
const wallElapsedMs = Math.max(0, Date.now() - raceStartedAt);
|
|
1279
|
+
const observerLagMs = Math.max(0, actualElapsedMs - timeoutMs);
|
|
1280
|
+
const error = Object.assign(
|
|
1281
|
+
new Error(`Session host connect timed out after ${timeoutMs}ms`),
|
|
1282
|
+
{
|
|
1283
|
+
code: "SESSION_HOST_CONNECT_TIMEOUT",
|
|
1284
|
+
scheduledTimeoutMs: timeoutMs,
|
|
1285
|
+
actualElapsedMs,
|
|
1286
|
+
wallElapsedMs,
|
|
1287
|
+
observerLagMs
|
|
1288
|
+
}
|
|
1289
|
+
);
|
|
1290
|
+
reject(error);
|
|
1291
|
+
}, timeoutMs);
|
|
1292
|
+
})
|
|
1293
|
+
]);
|
|
1294
|
+
} finally {
|
|
1295
|
+
if (timer) clearTimeout(timer);
|
|
1296
|
+
}
|
|
1297
|
+
} else {
|
|
1298
|
+
await this.connect(timeoutMs);
|
|
1299
|
+
}
|
|
1300
|
+
const requestSocket = this.socket;
|
|
1301
|
+
if (!requestSocket) throw new Error("Session host socket unavailable");
|
|
1302
|
+
const response = await this.sendRawRequestOnSocket(requestSocket, request, options.timeoutMs === void 0 || alreadyConnected ? timeoutMs : Math.max(1, deadline - Date.now()));
|
|
1303
|
+
if (response.success) {
|
|
1304
|
+
if (request.type === "attach_session") {
|
|
1305
|
+
this.attachedSessions.set(request.payload.sessionId, {
|
|
1306
|
+
sessionId: request.payload.sessionId,
|
|
1307
|
+
clientId: request.payload.clientId,
|
|
1308
|
+
clientType: request.payload.clientType,
|
|
1309
|
+
readOnly: request.payload.readOnly === true
|
|
1310
|
+
});
|
|
1311
|
+
} else if (request.type === "create_session") {
|
|
1312
|
+
const createdId = response.result?.sessionId || request.payload.sessionId;
|
|
1313
|
+
const clientId = typeof request.payload.clientId === "string" ? request.payload.clientId.trim() : "";
|
|
1314
|
+
if (createdId && clientId) {
|
|
1315
|
+
this.attachedSessions.set(createdId, {
|
|
1316
|
+
sessionId: createdId,
|
|
1317
|
+
clientId,
|
|
1318
|
+
clientType: request.payload.clientType || "daemon",
|
|
1319
|
+
readOnly: false
|
|
1320
|
+
});
|
|
890
1321
|
}
|
|
891
|
-
})
|
|
892
|
-
|
|
893
|
-
|
|
1322
|
+
} else if (request.type === "detach_session" || request.type === "delete_session") {
|
|
1323
|
+
this.attachedSessions.delete(request.payload.sessionId);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
894
1326
|
return response;
|
|
895
1327
|
}
|
|
1328
|
+
disconnect(error) {
|
|
1329
|
+
const socket = this.socket;
|
|
1330
|
+
if (socket) {
|
|
1331
|
+
this.handleDisconnect(socket, error ? "error" : "closed", error, 0);
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
this.connectPromise = null;
|
|
1335
|
+
const failure = error || new Error(`Session host client disconnected (${this.endpoint.path})`);
|
|
1336
|
+
for (const waiter of this.requestWaiters.values()) {
|
|
1337
|
+
waiter.reject(failure);
|
|
1338
|
+
}
|
|
1339
|
+
this.requestWaiters.clear();
|
|
1340
|
+
}
|
|
896
1341
|
async close() {
|
|
1342
|
+
this.attachedSessions.clear();
|
|
1343
|
+
this.connectPromise = null;
|
|
897
1344
|
if (!this.socket) return;
|
|
898
1345
|
const socket = this.socket;
|
|
899
1346
|
this.socket = null;
|
|
@@ -929,20 +1376,34 @@ function writeEnvelope(socket, envelope) {
|
|
|
929
1376
|
|
|
930
1377
|
// src/instance-key.ts
|
|
931
1378
|
var crypto2 = __toESM(require("crypto"));
|
|
932
|
-
var
|
|
933
|
-
var
|
|
1379
|
+
var fs2 = __toESM(require("fs"));
|
|
1380
|
+
var os3 = __toESM(require("os"));
|
|
934
1381
|
var path3 = __toESM(require("path"));
|
|
935
1382
|
var DEFAULT_CONFIG_DIR_NAME = ".adhdev";
|
|
936
|
-
function
|
|
1383
|
+
function assertTestStorageIsolated(destination) {
|
|
1384
|
+
const env = process.env;
|
|
1385
|
+
if (!env.VITEST && env.NODE_ENV !== "test" && !env.NODE_TEST_CONTEXT && !process.execArgv.some((arg) => arg === "--test" || arg.startsWith("--test="))) return;
|
|
1386
|
+
const target = canonicalizeInstancePath(destination);
|
|
1387
|
+
const home = os3.userInfo().homedir;
|
|
1388
|
+
for (const track of [".adhdev", ".adhdev-preview"]) {
|
|
1389
|
+
const live = canonicalizeInstancePath(path3.join(home, track));
|
|
1390
|
+
if (target === live || target.startsWith(live + path3.sep)) {
|
|
1391
|
+
throw new Error("LIVE runtime storage is forbidden in a test process; pin ADHDEV_CONFIG_DIR or storageRootDir to a temporary directory");
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
function resolveInstanceConfigDir(env = process.env, homeDir = os3.homedir()) {
|
|
937
1396
|
const override = typeof env.ADHDEV_CONFIG_DIR === "string" ? env.ADHDEV_CONFIG_DIR.trim() : "";
|
|
938
|
-
|
|
1397
|
+
const resolved = override || path3.join(homeDir, DEFAULT_CONFIG_DIR_NAME);
|
|
1398
|
+
if (env === process.env) assertTestStorageIsolated(resolved);
|
|
1399
|
+
return resolved;
|
|
939
1400
|
}
|
|
940
1401
|
function realpathLongestExistingPrefix(resolved) {
|
|
941
1402
|
let current = resolved;
|
|
942
1403
|
const remainder = [];
|
|
943
1404
|
for (let depth = 0; depth < 256; depth++) {
|
|
944
1405
|
try {
|
|
945
|
-
const real =
|
|
1406
|
+
const real = fs2.realpathSync.native(current);
|
|
946
1407
|
return remainder.length === 0 ? real : path3.join(real, ...remainder);
|
|
947
1408
|
} catch {
|
|
948
1409
|
const parent = path3.dirname(current);
|
|
@@ -958,17 +1419,17 @@ function canonicalizeInstancePath(dir, platform2 = process.platform) {
|
|
|
958
1419
|
const real = realpathLongestExistingPrefix(resolved).replace(/[\\/]+$/, "");
|
|
959
1420
|
return platform2 === "win32" ? real.toLowerCase() : real;
|
|
960
1421
|
}
|
|
961
|
-
function isDefaultInstanceConfigDir(configDir, homeDir =
|
|
1422
|
+
function isDefaultInstanceConfigDir(configDir, homeDir = os3.homedir(), platform2 = process.platform) {
|
|
962
1423
|
return canonicalizeInstancePath(configDir, platform2) === canonicalizeInstancePath(path3.join(homeDir, DEFAULT_CONFIG_DIR_NAME), platform2);
|
|
963
1424
|
}
|
|
964
|
-
function resolveSessionHostIpcKey(configDir, homeDir =
|
|
1425
|
+
function resolveSessionHostIpcKey(configDir, homeDir = os3.homedir(), platform2 = process.platform) {
|
|
965
1426
|
if (isDefaultInstanceConfigDir(configDir, homeDir, platform2)) return "";
|
|
966
1427
|
const canonical = canonicalizeInstancePath(configDir, platform2);
|
|
967
1428
|
return crypto2.createHash("sha256").update(canonical, "utf8").digest("hex").slice(0, 12);
|
|
968
1429
|
}
|
|
969
1430
|
|
|
970
1431
|
// src/spawn-env.ts
|
|
971
|
-
var
|
|
1432
|
+
var os4 = __toESM(require("os"));
|
|
972
1433
|
var path4 = __toESM(require("path"));
|
|
973
1434
|
function sanitizeSpawnEnv(baseEnv, overrides) {
|
|
974
1435
|
const env = {};
|
|
@@ -998,6 +1459,27 @@ function sanitizeSpawnEnv(baseEnv, overrides) {
|
|
|
998
1459
|
applyTerminalColorEnv(env);
|
|
999
1460
|
return env;
|
|
1000
1461
|
}
|
|
1462
|
+
function replayLaunchEnv(command) {
|
|
1463
|
+
if (command.envMode === "launch_overrides") return { ...command.env };
|
|
1464
|
+
const roleKeys = /* @__PURE__ */ new Set([
|
|
1465
|
+
"HOME",
|
|
1466
|
+
"USERPROFILE",
|
|
1467
|
+
"XDG_CONFIG_HOME",
|
|
1468
|
+
"CLAUDE_CONFIG_DIR",
|
|
1469
|
+
"CODEX_HOME",
|
|
1470
|
+
"KIMI_CODE_HOME",
|
|
1471
|
+
"GEMINI_CLI_HOME",
|
|
1472
|
+
"OPENCODE_CONFIG",
|
|
1473
|
+
"OPENCODE_CONFIG_CONTENT",
|
|
1474
|
+
"CLAUDE_CODE_DISABLE_AUTO_MEMORY",
|
|
1475
|
+
"TERMINAL_CWD",
|
|
1476
|
+
"ADHDEV_INLINE_MESH",
|
|
1477
|
+
"ADHDEV_ASSISTANT_SESSION_ID",
|
|
1478
|
+
"ADHDEV_COORDINATOR_SESSION_ID",
|
|
1479
|
+
"ADHDEV_CONFIG_DIR"
|
|
1480
|
+
]);
|
|
1481
|
+
return Object.fromEntries(Object.entries(command.env ?? {}).filter(([key]) => roleKeys.has(key)));
|
|
1482
|
+
}
|
|
1001
1483
|
function applyTerminalColorEnv(env) {
|
|
1002
1484
|
if (env.NO_COLOR) return;
|
|
1003
1485
|
if (!env.TERM || env.TERM === "xterm-color") {
|
|
@@ -1010,16 +1492,16 @@ function applyTerminalColorEnv(env) {
|
|
|
1010
1492
|
}
|
|
1011
1493
|
}
|
|
1012
1494
|
function ensureNodePtySpawnHelperPermissions(logFn) {
|
|
1013
|
-
if (
|
|
1495
|
+
if (os4.platform() === "win32") return;
|
|
1014
1496
|
try {
|
|
1015
|
-
const
|
|
1497
|
+
const fs3 = require("fs");
|
|
1016
1498
|
const ptyDir = path4.resolve(path4.dirname(require.resolve("node-pty")), "..");
|
|
1017
|
-
const platformArch = `${
|
|
1499
|
+
const platformArch = `${os4.platform()}-${os4.arch()}`;
|
|
1018
1500
|
const helper = path4.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
|
|
1019
|
-
if (
|
|
1020
|
-
const stat =
|
|
1501
|
+
if (fs3.existsSync(helper)) {
|
|
1502
|
+
const stat = fs3.statSync(helper);
|
|
1021
1503
|
if (!(stat.mode & 73)) {
|
|
1022
|
-
|
|
1504
|
+
fs3.chmodSync(helper, stat.mode | 493);
|
|
1023
1505
|
logFn?.(`Fixed spawn-helper permissions: ${helper}`);
|
|
1024
1506
|
}
|
|
1025
1507
|
}
|
|
@@ -1033,15 +1515,48 @@ function createSessionHostControlPlane(transport) {
|
|
|
1033
1515
|
getDiagnostics(payload = {}) {
|
|
1034
1516
|
return transport.request("get_host_diagnostics", payload);
|
|
1035
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
|
+
},
|
|
1036
1542
|
listSessions() {
|
|
1037
1543
|
return transport.request("list_sessions", {});
|
|
1038
1544
|
},
|
|
1039
1545
|
stopSession(sessionId) {
|
|
1040
1546
|
return transport.request("stop_session", { sessionId });
|
|
1041
1547
|
},
|
|
1548
|
+
stopSessionIfExpected(sessionId, expected) {
|
|
1549
|
+
return transport.request("stop_session_if_expected", { sessionId, expected });
|
|
1550
|
+
},
|
|
1042
1551
|
deleteSession(sessionId, opts = {}) {
|
|
1043
1552
|
return transport.request("delete_session", { sessionId, force: opts.force === true });
|
|
1044
1553
|
},
|
|
1554
|
+
deleteSessionIfExpected(sessionId, expected, opts = {}) {
|
|
1555
|
+
return transport.request(
|
|
1556
|
+
"delete_session_if_expected",
|
|
1557
|
+
{ sessionId, expected, force: opts.force === true }
|
|
1558
|
+
);
|
|
1559
|
+
},
|
|
1045
1560
|
resumeSession(sessionId) {
|
|
1046
1561
|
return transport.request("resume_session", { sessionId });
|
|
1047
1562
|
},
|
|
@@ -1070,6 +1585,10 @@ function createSessionHostControlPlane(transport) {
|
|
|
1070
1585
|
}
|
|
1071
1586
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1072
1587
|
0 && (module.exports = {
|
|
1588
|
+
CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
|
|
1589
|
+
CLI_CHILD_NICE_ENV,
|
|
1590
|
+
CLI_CHILD_NICE_INCREMENT,
|
|
1591
|
+
CLI_CHILD_SCHEDULING_ENV,
|
|
1073
1592
|
DEFAULT_CONFIG_DIR_NAME,
|
|
1074
1593
|
DEFAULT_SESSION_HOST_COLS,
|
|
1075
1594
|
DEFAULT_SESSION_HOST_ROWS,
|
|
@@ -1079,32 +1598,47 @@ function createSessionHostControlPlane(transport) {
|
|
|
1079
1598
|
SessionHostRegistry,
|
|
1080
1599
|
SessionRingBuffer,
|
|
1081
1600
|
applyTerminalColorEnv,
|
|
1601
|
+
assertTestStorageIsolated,
|
|
1082
1602
|
buildRuntimeDisplayName,
|
|
1083
1603
|
buildRuntimeKey,
|
|
1084
1604
|
canonicalizeInstancePath,
|
|
1085
1605
|
classifyTermination,
|
|
1606
|
+
createCliChildPriorityPolicy,
|
|
1086
1607
|
createLineParser,
|
|
1087
1608
|
createResponseEnvelope,
|
|
1088
1609
|
createSessionHostControlPlane,
|
|
1610
|
+
disconnectSessionHostClients,
|
|
1089
1611
|
ensureNodePtySpawnHelperPermissions,
|
|
1612
|
+
findConnectedSessionHostClient,
|
|
1090
1613
|
formatRuntimeOwner,
|
|
1091
1614
|
getDefaultSessionHostEndpoint,
|
|
1092
1615
|
getSessionHostRecoveryLabel,
|
|
1093
1616
|
getSessionHostSurfaceKind,
|
|
1094
1617
|
getWorkspaceLabel,
|
|
1618
|
+
hiddenSpawnProcess,
|
|
1619
|
+
hostBootIdFromStartedAt,
|
|
1095
1620
|
isDefaultInstanceConfigDir,
|
|
1096
1621
|
isSessionHostLiveRuntime,
|
|
1097
1622
|
isSessionHostRecoverySnapshot,
|
|
1098
1623
|
isTerminalRecord,
|
|
1624
|
+
niceLaunch,
|
|
1099
1625
|
partitionSessionHostDiagnosticsSessions,
|
|
1100
1626
|
partitionSessionHostRecords,
|
|
1627
|
+
refuseCleanupExpectedDelete,
|
|
1628
|
+
refuseCleanupExpectedStop,
|
|
1629
|
+
replayLaunchEnv,
|
|
1101
1630
|
resolveAttachableRuntimeRecord,
|
|
1631
|
+
resolveHostBootId,
|
|
1102
1632
|
resolveInstanceConfigDir,
|
|
1103
1633
|
resolveRuntimeRecord,
|
|
1104
1634
|
resolveSessionHostCols,
|
|
1105
1635
|
resolveSessionHostIpcKey,
|
|
1106
1636
|
resolveSessionHostRows,
|
|
1107
1637
|
sanitizeSpawnEnv,
|
|
1638
|
+
spawnCliChild,
|
|
1639
|
+
stripCleanupAfterStopSideEffect,
|
|
1640
|
+
tagCleanupAfterStopSideEffect,
|
|
1641
|
+
validateSessionHostEndpoint,
|
|
1108
1642
|
writeEnvelope
|
|
1109
1643
|
});
|
|
1110
1644
|
//# sourceMappingURL=index.js.map
|