@adhdev/session-host-core 1.0.82-rc.13 → 1.0.82-rc.131
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 +304 -4
- package/dist/index.d.ts +304 -4
- package/dist/index.js +593 -62
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +574 -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 +23 -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 +118 -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,32 +43,47 @@ __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);
|
|
@@ -76,11 +95,18 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
|
|
|
76
95
|
"release_upgrade_lease",
|
|
77
96
|
"create_session",
|
|
78
97
|
"attach_session",
|
|
98
|
+
// Distinct request kind: old hosts must refuse instead of ignoring a pin.
|
|
99
|
+
"attach_session_if_incarnation",
|
|
79
100
|
"detach_session",
|
|
80
101
|
"send_input",
|
|
102
|
+
"send_input_if_seq",
|
|
103
|
+
"get_input_state",
|
|
81
104
|
"resize_session",
|
|
82
105
|
"stop_session",
|
|
106
|
+
"stop_session_if_expected",
|
|
107
|
+
"stop_mesh_writer",
|
|
83
108
|
"delete_session",
|
|
109
|
+
"delete_session_if_expected",
|
|
84
110
|
"resume_session",
|
|
85
111
|
"acquire_write",
|
|
86
112
|
"release_write",
|
|
@@ -93,9 +119,76 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
|
|
|
93
119
|
"send_signal",
|
|
94
120
|
"restart_session",
|
|
95
121
|
"prune_duplicate_sessions",
|
|
122
|
+
"get_session_census",
|
|
123
|
+
"get_session",
|
|
96
124
|
"list_sessions"
|
|
97
125
|
];
|
|
98
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
|
+
|
|
99
192
|
// src/termination.ts
|
|
100
193
|
function classifyTermination(input) {
|
|
101
194
|
const { exitCode, terminatedAt } = input;
|
|
@@ -129,6 +222,72 @@ function classifyTermination(input) {
|
|
|
129
222
|
return termination;
|
|
130
223
|
}
|
|
131
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
|
+
|
|
132
291
|
// src/buffer.ts
|
|
133
292
|
var DEFAULT_SESSION_RING_BUFFER_MAX_BYTES = 4 * 1024 * 1024;
|
|
134
293
|
var SessionRingBuffer = class {
|
|
@@ -465,6 +624,13 @@ function formatRuntimeOwner(record) {
|
|
|
465
624
|
// src/registry.ts
|
|
466
625
|
var SessionHostRegistry = class {
|
|
467
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
|
+
}
|
|
468
634
|
createSession(payload) {
|
|
469
635
|
const sessionId = payload.sessionId || generateUUID();
|
|
470
636
|
if (this.sessions.has(sessionId)) {
|
|
@@ -496,6 +662,8 @@ var SessionHostRegistry = class {
|
|
|
496
662
|
lifecycle: "starting",
|
|
497
663
|
writeOwner: null,
|
|
498
664
|
attachedClients: initialClient,
|
|
665
|
+
inputSeq: 0,
|
|
666
|
+
inputEpoch: this.mintInputEpoch(),
|
|
499
667
|
buffer: {
|
|
500
668
|
scrollbackBytes: 0,
|
|
501
669
|
snapshotSeq: 0
|
|
@@ -515,6 +683,10 @@ var SessionHostRegistry = class {
|
|
|
515
683
|
}
|
|
516
684
|
restoreSession(record, snapshot) {
|
|
517
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();
|
|
518
690
|
this.sessions.set(cloned.sessionId, {
|
|
519
691
|
record: cloned,
|
|
520
692
|
buffer: (() => {
|
|
@@ -525,13 +697,50 @@ var SessionHostRegistry = class {
|
|
|
525
697
|
});
|
|
526
698
|
return this.cloneRecord(cloned);
|
|
527
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
|
+
}
|
|
528
709
|
listSessions() {
|
|
529
710
|
return Array.from(this.sessions.values()).map((state) => this.cloneRecord(state.record)).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
530
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
|
+
}
|
|
531
732
|
getSession(sessionId) {
|
|
532
733
|
const state = this.sessions.get(sessionId);
|
|
533
734
|
return state ? this.cloneRecord(state.record) : null;
|
|
534
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
|
+
}
|
|
535
744
|
attachClient(payload) {
|
|
536
745
|
const state = this.requireSession(payload.sessionId);
|
|
537
746
|
const now = Date.now();
|
|
@@ -576,6 +785,20 @@ var SessionHostRegistry = class {
|
|
|
576
785
|
state.record.lastActivityAt = Date.now();
|
|
577
786
|
return this.cloneRecord(state.record);
|
|
578
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
|
+
}
|
|
579
802
|
acquireWrite(payload) {
|
|
580
803
|
const state = this.requireSession(payload.sessionId);
|
|
581
804
|
if (state.record.writeOwner && state.record.writeOwner.clientId !== payload.clientId && !payload.force) {
|
|
@@ -692,10 +915,19 @@ function cloneMeta(meta) {
|
|
|
692
915
|
}
|
|
693
916
|
|
|
694
917
|
// src/ipc.ts
|
|
695
|
-
var
|
|
918
|
+
var os2 = __toESM(require("os"));
|
|
696
919
|
var path2 = __toESM(require("path"));
|
|
697
920
|
var net = __toESM(require("net"));
|
|
921
|
+
var import_crypto = require("crypto");
|
|
698
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
|
+
}
|
|
699
931
|
function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
|
|
700
932
|
const rawKey = typeof options.ipcKey === "string" ? options.ipcKey.trim() : "";
|
|
701
933
|
if (rawKey && !/^[0-9a-f]{12}$/.test(rawKey)) {
|
|
@@ -709,48 +941,102 @@ function getDefaultSessionHostEndpoint(appName = "adhdev", options = {}) {
|
|
|
709
941
|
path: `\\\\.\\pipe\\${appName}-session-host${suffix}`
|
|
710
942
|
};
|
|
711
943
|
}
|
|
712
|
-
|
|
944
|
+
const endpoint = {
|
|
713
945
|
kind: "unix",
|
|
714
|
-
path: path2.join(
|
|
946
|
+
path: path2.join(options.tmpDir ?? os2.tmpdir(), `${appName}-session-host${suffix}.sock`)
|
|
715
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;
|
|
716
955
|
}
|
|
717
956
|
function serializeEnvelope(envelope) {
|
|
718
957
|
return `${JSON.stringify(envelope)}
|
|
719
958
|
`;
|
|
720
959
|
}
|
|
721
960
|
function createLineParser(onEnvelope) {
|
|
722
|
-
let
|
|
961
|
+
let fragments = [];
|
|
723
962
|
const decoder = new import_string_decoder.StringDecoder("utf8");
|
|
724
963
|
const parser = (chunk) => {
|
|
725
|
-
|
|
726
|
-
let
|
|
727
|
-
|
|
728
|
-
const
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
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;
|
|
732
971
|
}
|
|
733
|
-
|
|
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));
|
|
734
977
|
}
|
|
735
978
|
};
|
|
736
979
|
parser.end = () => {
|
|
737
|
-
const remainder =
|
|
738
|
-
|
|
980
|
+
const remainder = fragments.join("") + decoder.end();
|
|
981
|
+
fragments = [];
|
|
739
982
|
return remainder;
|
|
740
983
|
};
|
|
741
984
|
return parser;
|
|
742
985
|
}
|
|
743
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
|
+
}
|
|
744
1013
|
var SessionHostClient = class {
|
|
745
1014
|
endpoint;
|
|
746
1015
|
socket = null;
|
|
1016
|
+
connectPromise = null;
|
|
1017
|
+
requestTimeoutMs = 3e4;
|
|
747
1018
|
requestWaiters = /* @__PURE__ */ new Map();
|
|
748
1019
|
eventListeners = /* @__PURE__ */ new Set();
|
|
749
1020
|
disconnectListeners = /* @__PURE__ */ new Set();
|
|
750
1021
|
/** Guards against emitting both an 'error'-path and a 'close'-path disconnect for one socket. */
|
|
751
1022
|
disconnectedSockets = /* @__PURE__ */ new WeakSet();
|
|
1023
|
+
/** Session subscriptions established via create_session/attach_session, replayed automatically on reconnect. */
|
|
1024
|
+
attachedSessions = /* @__PURE__ */ new Map();
|
|
752
1025
|
constructor(options = {}) {
|
|
753
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));
|
|
754
1040
|
}
|
|
755
1041
|
/**
|
|
756
1042
|
* Fires when an established connection to the session host goes away.
|
|
@@ -793,6 +1079,7 @@ var SessionHostClient = class {
|
|
|
793
1079
|
this.requestWaiters.clear();
|
|
794
1080
|
if (this.socket === socket) {
|
|
795
1081
|
this.socket = null;
|
|
1082
|
+
this.connectPromise = null;
|
|
796
1083
|
}
|
|
797
1084
|
try {
|
|
798
1085
|
socket.destroy();
|
|
@@ -812,8 +1099,53 @@ var SessionHostClient = class {
|
|
|
812
1099
|
}
|
|
813
1100
|
}
|
|
814
1101
|
}
|
|
815
|
-
|
|
816
|
-
|
|
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
|
+
}
|
|
817
1149
|
if (this.socket) {
|
|
818
1150
|
try {
|
|
819
1151
|
this.socket.destroy();
|
|
@@ -821,6 +1153,7 @@ var SessionHostClient = class {
|
|
|
821
1153
|
}
|
|
822
1154
|
this.socket = null;
|
|
823
1155
|
}
|
|
1156
|
+
this.connectPromise = null;
|
|
824
1157
|
const socket = net.createConnection(this.endpoint.path);
|
|
825
1158
|
this.socket = socket;
|
|
826
1159
|
const parser = createLineParser((envelope) => {
|
|
@@ -833,7 +1166,12 @@ var SessionHostClient = class {
|
|
|
833
1166
|
return;
|
|
834
1167
|
}
|
|
835
1168
|
if (envelope.kind === "event") {
|
|
836
|
-
for (const listener of this.eventListeners)
|
|
1169
|
+
for (const listener of this.eventListeners) {
|
|
1170
|
+
try {
|
|
1171
|
+
listener(envelope.event);
|
|
1172
|
+
} catch {
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
837
1175
|
}
|
|
838
1176
|
});
|
|
839
1177
|
socket.on("data", parser);
|
|
@@ -854,13 +1192,68 @@ var SessionHostClient = class {
|
|
|
854
1192
|
socket.on("end", () => {
|
|
855
1193
|
this.handleDisconnect(socket, "ended", void 0, flushParser().length);
|
|
856
1194
|
});
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
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);
|
|
861
1235
|
});
|
|
862
|
-
socket.
|
|
863
|
-
|
|
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
|
+
}
|
|
864
1257
|
}
|
|
865
1258
|
onEvent(listener) {
|
|
866
1259
|
this.eventListeners.add(listener);
|
|
@@ -868,35 +1261,86 @@ var SessionHostClient = class {
|
|
|
868
1261
|
this.eventListeners.delete(listener);
|
|
869
1262
|
};
|
|
870
1263
|
}
|
|
871
|
-
async request(request) {
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
const
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
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
|
+
});
|
|
893
1321
|
}
|
|
894
|
-
})
|
|
895
|
-
|
|
896
|
-
|
|
1322
|
+
} else if (request.type === "detach_session" || request.type === "delete_session") {
|
|
1323
|
+
this.attachedSessions.delete(request.payload.sessionId);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
897
1326
|
return response;
|
|
898
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
|
+
}
|
|
899
1341
|
async close() {
|
|
1342
|
+
this.attachedSessions.clear();
|
|
1343
|
+
this.connectPromise = null;
|
|
900
1344
|
if (!this.socket) return;
|
|
901
1345
|
const socket = this.socket;
|
|
902
1346
|
this.socket = null;
|
|
@@ -932,20 +1376,34 @@ function writeEnvelope(socket, envelope) {
|
|
|
932
1376
|
|
|
933
1377
|
// src/instance-key.ts
|
|
934
1378
|
var crypto2 = __toESM(require("crypto"));
|
|
935
|
-
var
|
|
936
|
-
var
|
|
1379
|
+
var fs2 = __toESM(require("fs"));
|
|
1380
|
+
var os3 = __toESM(require("os"));
|
|
937
1381
|
var path3 = __toESM(require("path"));
|
|
938
1382
|
var DEFAULT_CONFIG_DIR_NAME = ".adhdev";
|
|
939
|
-
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()) {
|
|
940
1396
|
const override = typeof env.ADHDEV_CONFIG_DIR === "string" ? env.ADHDEV_CONFIG_DIR.trim() : "";
|
|
941
|
-
|
|
1397
|
+
const resolved = override || path3.join(homeDir, DEFAULT_CONFIG_DIR_NAME);
|
|
1398
|
+
if (env === process.env) assertTestStorageIsolated(resolved);
|
|
1399
|
+
return resolved;
|
|
942
1400
|
}
|
|
943
1401
|
function realpathLongestExistingPrefix(resolved) {
|
|
944
1402
|
let current = resolved;
|
|
945
1403
|
const remainder = [];
|
|
946
1404
|
for (let depth = 0; depth < 256; depth++) {
|
|
947
1405
|
try {
|
|
948
|
-
const real =
|
|
1406
|
+
const real = fs2.realpathSync.native(current);
|
|
949
1407
|
return remainder.length === 0 ? real : path3.join(real, ...remainder);
|
|
950
1408
|
} catch {
|
|
951
1409
|
const parent = path3.dirname(current);
|
|
@@ -961,17 +1419,17 @@ function canonicalizeInstancePath(dir, platform2 = process.platform) {
|
|
|
961
1419
|
const real = realpathLongestExistingPrefix(resolved).replace(/[\\/]+$/, "");
|
|
962
1420
|
return platform2 === "win32" ? real.toLowerCase() : real;
|
|
963
1421
|
}
|
|
964
|
-
function isDefaultInstanceConfigDir(configDir, homeDir =
|
|
1422
|
+
function isDefaultInstanceConfigDir(configDir, homeDir = os3.homedir(), platform2 = process.platform) {
|
|
965
1423
|
return canonicalizeInstancePath(configDir, platform2) === canonicalizeInstancePath(path3.join(homeDir, DEFAULT_CONFIG_DIR_NAME), platform2);
|
|
966
1424
|
}
|
|
967
|
-
function resolveSessionHostIpcKey(configDir, homeDir =
|
|
1425
|
+
function resolveSessionHostIpcKey(configDir, homeDir = os3.homedir(), platform2 = process.platform) {
|
|
968
1426
|
if (isDefaultInstanceConfigDir(configDir, homeDir, platform2)) return "";
|
|
969
1427
|
const canonical = canonicalizeInstancePath(configDir, platform2);
|
|
970
1428
|
return crypto2.createHash("sha256").update(canonical, "utf8").digest("hex").slice(0, 12);
|
|
971
1429
|
}
|
|
972
1430
|
|
|
973
1431
|
// src/spawn-env.ts
|
|
974
|
-
var
|
|
1432
|
+
var os4 = __toESM(require("os"));
|
|
975
1433
|
var path4 = __toESM(require("path"));
|
|
976
1434
|
function sanitizeSpawnEnv(baseEnv, overrides) {
|
|
977
1435
|
const env = {};
|
|
@@ -1001,6 +1459,27 @@ function sanitizeSpawnEnv(baseEnv, overrides) {
|
|
|
1001
1459
|
applyTerminalColorEnv(env);
|
|
1002
1460
|
return env;
|
|
1003
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
|
+
}
|
|
1004
1483
|
function applyTerminalColorEnv(env) {
|
|
1005
1484
|
if (env.NO_COLOR) return;
|
|
1006
1485
|
if (!env.TERM || env.TERM === "xterm-color") {
|
|
@@ -1013,16 +1492,16 @@ function applyTerminalColorEnv(env) {
|
|
|
1013
1492
|
}
|
|
1014
1493
|
}
|
|
1015
1494
|
function ensureNodePtySpawnHelperPermissions(logFn) {
|
|
1016
|
-
if (
|
|
1495
|
+
if (os4.platform() === "win32") return;
|
|
1017
1496
|
try {
|
|
1018
|
-
const
|
|
1497
|
+
const fs3 = require("fs");
|
|
1019
1498
|
const ptyDir = path4.resolve(path4.dirname(require.resolve("node-pty")), "..");
|
|
1020
|
-
const platformArch = `${
|
|
1499
|
+
const platformArch = `${os4.platform()}-${os4.arch()}`;
|
|
1021
1500
|
const helper = path4.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
|
|
1022
|
-
if (
|
|
1023
|
-
const stat =
|
|
1501
|
+
if (fs3.existsSync(helper)) {
|
|
1502
|
+
const stat = fs3.statSync(helper);
|
|
1024
1503
|
if (!(stat.mode & 73)) {
|
|
1025
|
-
|
|
1504
|
+
fs3.chmodSync(helper, stat.mode | 493);
|
|
1026
1505
|
logFn?.(`Fixed spawn-helper permissions: ${helper}`);
|
|
1027
1506
|
}
|
|
1028
1507
|
}
|
|
@@ -1036,15 +1515,48 @@ function createSessionHostControlPlane(transport) {
|
|
|
1036
1515
|
getDiagnostics(payload = {}) {
|
|
1037
1516
|
return transport.request("get_host_diagnostics", payload);
|
|
1038
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
|
+
},
|
|
1039
1542
|
listSessions() {
|
|
1040
1543
|
return transport.request("list_sessions", {});
|
|
1041
1544
|
},
|
|
1042
1545
|
stopSession(sessionId) {
|
|
1043
1546
|
return transport.request("stop_session", { sessionId });
|
|
1044
1547
|
},
|
|
1548
|
+
stopSessionIfExpected(sessionId, expected) {
|
|
1549
|
+
return transport.request("stop_session_if_expected", { sessionId, expected });
|
|
1550
|
+
},
|
|
1045
1551
|
deleteSession(sessionId, opts = {}) {
|
|
1046
1552
|
return transport.request("delete_session", { sessionId, force: opts.force === true });
|
|
1047
1553
|
},
|
|
1554
|
+
deleteSessionIfExpected(sessionId, expected, opts = {}) {
|
|
1555
|
+
return transport.request(
|
|
1556
|
+
"delete_session_if_expected",
|
|
1557
|
+
{ sessionId, expected, force: opts.force === true }
|
|
1558
|
+
);
|
|
1559
|
+
},
|
|
1048
1560
|
resumeSession(sessionId) {
|
|
1049
1561
|
return transport.request("resume_session", { sessionId });
|
|
1050
1562
|
},
|
|
@@ -1073,6 +1585,10 @@ function createSessionHostControlPlane(transport) {
|
|
|
1073
1585
|
}
|
|
1074
1586
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1075
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,
|
|
1076
1592
|
DEFAULT_CONFIG_DIR_NAME,
|
|
1077
1593
|
DEFAULT_SESSION_HOST_COLS,
|
|
1078
1594
|
DEFAULT_SESSION_HOST_ROWS,
|
|
@@ -1082,32 +1598,47 @@ function createSessionHostControlPlane(transport) {
|
|
|
1082
1598
|
SessionHostRegistry,
|
|
1083
1599
|
SessionRingBuffer,
|
|
1084
1600
|
applyTerminalColorEnv,
|
|
1601
|
+
assertTestStorageIsolated,
|
|
1085
1602
|
buildRuntimeDisplayName,
|
|
1086
1603
|
buildRuntimeKey,
|
|
1087
1604
|
canonicalizeInstancePath,
|
|
1088
1605
|
classifyTermination,
|
|
1606
|
+
createCliChildPriorityPolicy,
|
|
1089
1607
|
createLineParser,
|
|
1090
1608
|
createResponseEnvelope,
|
|
1091
1609
|
createSessionHostControlPlane,
|
|
1610
|
+
disconnectSessionHostClients,
|
|
1092
1611
|
ensureNodePtySpawnHelperPermissions,
|
|
1612
|
+
findConnectedSessionHostClient,
|
|
1093
1613
|
formatRuntimeOwner,
|
|
1094
1614
|
getDefaultSessionHostEndpoint,
|
|
1095
1615
|
getSessionHostRecoveryLabel,
|
|
1096
1616
|
getSessionHostSurfaceKind,
|
|
1097
1617
|
getWorkspaceLabel,
|
|
1618
|
+
hiddenSpawnProcess,
|
|
1619
|
+
hostBootIdFromStartedAt,
|
|
1098
1620
|
isDefaultInstanceConfigDir,
|
|
1099
1621
|
isSessionHostLiveRuntime,
|
|
1100
1622
|
isSessionHostRecoverySnapshot,
|
|
1101
1623
|
isTerminalRecord,
|
|
1624
|
+
niceLaunch,
|
|
1102
1625
|
partitionSessionHostDiagnosticsSessions,
|
|
1103
1626
|
partitionSessionHostRecords,
|
|
1627
|
+
refuseCleanupExpectedDelete,
|
|
1628
|
+
refuseCleanupExpectedStop,
|
|
1629
|
+
replayLaunchEnv,
|
|
1104
1630
|
resolveAttachableRuntimeRecord,
|
|
1631
|
+
resolveHostBootId,
|
|
1105
1632
|
resolveInstanceConfigDir,
|
|
1106
1633
|
resolveRuntimeRecord,
|
|
1107
1634
|
resolveSessionHostCols,
|
|
1108
1635
|
resolveSessionHostIpcKey,
|
|
1109
1636
|
resolveSessionHostRows,
|
|
1110
1637
|
sanitizeSpawnEnv,
|
|
1638
|
+
spawnCliChild,
|
|
1639
|
+
stripCleanupAfterStopSideEffect,
|
|
1640
|
+
tagCleanupAfterStopSideEffect,
|
|
1641
|
+
validateSessionHostEndpoint,
|
|
1111
1642
|
writeEnvelope
|
|
1112
1643
|
});
|
|
1113
1644
|
//# sourceMappingURL=index.js.map
|