ai-battery 0.2.0 → 0.2.2

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.
Files changed (48) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-rail.applescript +227 -0
  3. package/bin/ai-battery-macos-status.applescript +5 -12
  4. package/bin/ai-battery-run +701 -31
  5. package/bin/ai-battery-tmux.js +17 -0
  6. package/bin/terminal-compositor.js +111 -0
  7. package/docs/REFERENCE.md +23 -3
  8. package/docs/RELEASING.md +30 -7
  9. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  10. package/docs/hud-preview.svg +75 -20
  11. package/docs/terminal-vertical-preview.svg +73 -0
  12. package/lib/cli.js +1148 -240
  13. package/lib/core/atomic-rename.js +18 -0
  14. package/lib/core/cli-help.js +57 -12
  15. package/lib/core/cli-messages.js +45 -1
  16. package/lib/core/cli-output.js +277 -72
  17. package/lib/core/cli-wrappers.js +410 -0
  18. package/lib/core/config-editor.js +194 -29
  19. package/lib/core/display-config.js +45 -0
  20. package/lib/core/integration-files.js +32 -3
  21. package/lib/core/shared-bar.js +603 -0
  22. package/lib/core/statusline-git.js +179 -15
  23. package/lib/core/terminal.js +25 -7
  24. package/lib/core/tmux-status.js +172 -0
  25. package/lib/core/uninstall.js +20 -7
  26. package/lib/core/usage-store.js +85 -0
  27. package/lib/hud/launcher.js +32 -33
  28. package/lib/platforms/linux/gnome-extension/extension.js +7 -6
  29. package/lib/platforms/linux/hud.js +157 -42
  30. package/lib/platforms/linux/panel.js +16 -3
  31. package/lib/platforms/linux/rail.js +412 -0
  32. package/lib/platforms/macos/hud.js +152 -44
  33. package/lib/platforms/process-scanner.js +77 -29
  34. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  35. package/lib/platforms/windows/codex-runner.js +178 -21
  36. package/lib/platforms/windows/hud/controls.ps1 +65 -15
  37. package/lib/platforms/windows/hud/main.ps1 +715 -54
  38. package/lib/platforms/windows/hud/rendering.ps1 +1284 -2
  39. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  40. package/lib/platforms/windows/hud-launcher.js +234 -81
  41. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  42. package/lib/platforms/windows/terminal-compositor.js +210 -25
  43. package/lib/platforms/windows/wt-bar.js +729 -0
  44. package/lib/platforms/windows/wt-fragment.js +665 -0
  45. package/lib/platforms/windows/wt-keybinding.js +300 -0
  46. package/lib/providers/antigravity.js +155 -8
  47. package/package.json +6 -2
  48. package/vendor/PaneContext.cs +875 -0
@@ -0,0 +1,603 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+ import { atomicRename } from "./atomic-rename.js";
5
+
6
+ const DEFAULT_STALE_MS = 15000;
7
+ const DEFAULT_SESSION_IDLE_MS = 15000;
8
+ const DEFAULT_TRIGGER_COOLDOWN_MS = 4000;
9
+
10
+ function readJson(file) {
11
+ try {
12
+ return JSON.parse(fs.readFileSync(file, "utf8"));
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+
18
+ function writeJsonAtomic(file, value) {
19
+ fs.mkdirSync(path.dirname(file), { recursive: true });
20
+ const temporary = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
21
+ try {
22
+ fs.writeFileSync(temporary, JSON.stringify(value), { mode: 0o600 });
23
+ atomicRename(temporary, file);
24
+ } finally {
25
+ try { fs.unlinkSync(temporary); } catch { /* Already renamed or cleaned up. */ }
26
+ }
27
+ }
28
+
29
+ function defaultIsAlive(pid) {
30
+ const numeric = Number(pid);
31
+ if (!Number.isInteger(numeric) || numeric <= 0) return false;
32
+ try {
33
+ process.kill(numeric, 0);
34
+ return true;
35
+ } catch (error) {
36
+ return error?.code === "EPERM";
37
+ }
38
+ }
39
+
40
+ export function validBarContext(context) {
41
+ return Number(context?.window) > 0 && Boolean(context?.tab);
42
+ }
43
+
44
+ export function sharedBarTabDir(root, context) {
45
+ const windowId = String(context.window);
46
+ const tabSegment = context?.tab
47
+ ? `tab-${crypto.createHash("sha256").update(String(context.tab)).digest("hex").slice(0, 16)}`
48
+ : "window";
49
+ return path.join(root, windowId, tabSegment);
50
+ }
51
+
52
+ export function sharedBarLeasePath(root, context) {
53
+ return path.join(sharedBarTabDir(root, context), "bar.json");
54
+ }
55
+
56
+ function sessionsDirPath(root, context) {
57
+ return path.join(sharedBarTabDir(root, context), "sessions");
58
+ }
59
+
60
+ function triggerStatePath(root, context) {
61
+ return path.join(sharedBarTabDir(root, context), "trigger.json");
62
+ }
63
+
64
+ function dismissedStatePath(root, context) {
65
+ return path.join(sharedBarTabDir(root, context), "dismissed.json");
66
+ }
67
+
68
+ function leaseIsFresh(lease, { now = Date.now(), staleMs = DEFAULT_STALE_MS, isAlive = defaultIsAlive } = {}) {
69
+ if (!lease || !Number.isInteger(lease.pid) || lease.pid <= 0) return false;
70
+ const updatedAt = Number(lease.updatedAt || lease.claimedAt || 0);
71
+ if (!Number.isFinite(updatedAt) || now - updatedAt > staleMs) return false;
72
+ return Boolean(isAlive(lease.pid, lease));
73
+ }
74
+
75
+ function sessionIsActive(session, {
76
+ now = Date.now(),
77
+ idleMs = DEFAULT_SESSION_IDLE_MS,
78
+ isAlive = defaultIsAlive
79
+ } = {}) {
80
+ if (!session || !Number(session.console)) return false;
81
+ const updatedAt = Number(session.updatedAt || 0);
82
+ // Persistent CLI owner PID (codex runner, agy.exe, claude node.exe): stays active
83
+ // as long as the CLI process is alive, even while idle between prompts.
84
+ if (session.persistentOwner && Number.isInteger(session.ownerPid) && session.ownerPid > 0) {
85
+ return Boolean(isAlive(session.ownerPid, session));
86
+ }
87
+ // Ephemeral hook process (no persistent parent identified): rely on recent heartbeat.
88
+ return Number.isFinite(updatedAt) && now - updatedAt <= idleMs;
89
+ }
90
+
91
+ export function registerAiSession({
92
+ root,
93
+ context,
94
+ provider = "unknown",
95
+ now = Date.now(),
96
+ persistentOwner = false,
97
+ cols = 0,
98
+ rows = 0
99
+ }) {
100
+ if (!validBarContext(context) || !Number(context?.console)) return null;
101
+ const dir = sessionsDirPath(root, context);
102
+ const consoleId = String(context.console);
103
+ const file = path.join(dir, `console-${consoleId}.json`);
104
+ const existing = readJson(file);
105
+ const ownerPid = Number(context.ownerPid) || 0;
106
+ const startedAt = String(context.startedAt || "");
107
+ const sameOwner = Boolean(
108
+ existing
109
+ && Number(existing.ownerPid) === ownerPid
110
+ && String(existing.startedAt || "") === startedAt
111
+ );
112
+ const hasRect = Boolean(context.paneRectKnown)
113
+ && Number.isFinite(Number(context.paneLeft))
114
+ && Number.isFinite(Number(context.paneTop));
115
+ const keepExistingRect = !hasRect && sameOwner && Boolean(existing?.paneRectKnown);
116
+ const liveCols = Number(cols) > 0 ? Math.trunc(Number(cols))
117
+ : (Number(context.columns) > 0 ? Math.trunc(Number(context.columns))
118
+ : (sameOwner && Number(existing?.cols) > 0 ? Math.trunc(Number(existing.cols)) : 0));
119
+ const liveRows = Number(rows) > 0 ? Math.trunc(Number(rows))
120
+ : (Number(context.rows) > 0 ? Math.trunc(Number(context.rows))
121
+ : (sameOwner && Number(existing?.rows) > 0 ? Math.trunc(Number(existing.rows)) : 0));
122
+ const sameRectAsExisting = hasRect && sameOwner && existing?.paneRectKnown
123
+ && Number(existing.paneLeft) === Number(context.paneLeft)
124
+ && Number(existing.paneTop) === Number(context.paneTop)
125
+ && Number(existing.paneRight) === Number(context.paneRight)
126
+ && Number(existing.paneBottom) === Number(context.paneBottom);
127
+ const initCols = (sameRectAsExisting || keepExistingRect) && Number(existing?.initCols) > 0
128
+ ? Math.trunc(Number(existing.initCols))
129
+ : liveCols;
130
+ const initRows = (sameRectAsExisting || keepExistingRect) && Number(existing?.initRows) > 0
131
+ ? Math.trunc(Number(existing.initRows))
132
+ : liveRows;
133
+ const record = {
134
+ version: 1,
135
+ provider: String(provider || "unknown"),
136
+ console: Number(context.console),
137
+ ownerPid,
138
+ startedAt,
139
+ persistentOwner: Boolean(persistentOwner && ownerPid > 0),
140
+ ...(context.ownerHost ? { ownerHost: String(context.ownerHost) } : {}),
141
+ ...(context.wslDistro ? { wslDistro: String(context.wslDistro) } : {}),
142
+ ...(Number(context.winHostPid) > 0 ? { winHostPid: Number(context.winHostPid) } : {}),
143
+ ...(context.profileId ? { profileId: String(context.profileId) } : {}),
144
+ ...(liveCols > 0 ? { cols: liveCols } : {}),
145
+ ...(liveRows > 0 ? { rows: liveRows } : {}),
146
+ ...(initCols > 0 ? { initCols } : {}),
147
+ ...(initRows > 0 ? { initRows } : {}),
148
+ ...(hasRect ? {
149
+ paneRectKnown: true,
150
+ paneLeft: Number(context.paneLeft),
151
+ paneTop: Number(context.paneTop),
152
+ ...(Number.isFinite(Number(context.paneRight)) ? { paneRight: Number(context.paneRight) } : {}),
153
+ ...(Number.isFinite(Number(context.paneBottom)) ? { paneBottom: Number(context.paneBottom) } : {})
154
+ } : keepExistingRect ? {
155
+ paneRectKnown: true,
156
+ paneLeft: Number(existing.paneLeft),
157
+ paneTop: Number(existing.paneTop),
158
+ ...(Number.isFinite(Number(existing.paneRight)) ? { paneRight: Number(existing.paneRight) } : {}),
159
+ ...(Number.isFinite(Number(existing.paneBottom)) ? { paneBottom: Number(existing.paneBottom) } : {})
160
+ } : {}),
161
+ window: Number(context.window),
162
+ tab: String(context.tab || ""),
163
+ registeredAt: sameOwner && Number.isFinite(Number(existing?.registeredAt)) ? Number(existing.registeredAt) : now,
164
+ updatedAt: now
165
+ };
166
+ writeJsonAtomic(file, record);
167
+ return { file, record };
168
+ }
169
+
170
+ // Deterministically pick the single in-terminal edge pane that owns the unified
171
+ // status bar for a split tab (leftmost for left, rightmost for right, topmost
172
+ // for top, bottommost for bottom) without creating extra tabs, panes, or HUDs.
173
+ export function selectSharedBarLeader(sessions = [], position = "bottom") {
174
+ if (!Array.isArray(sessions) || !sessions.length) return null;
175
+ if (sessions.length === 1) return sessions[0];
176
+ const pos = String(position || "bottom").trim().toLowerCase();
177
+ const num = (value, fallback = 0) => (typeof value === "number" && Number.isFinite(value) ? value : fallback);
178
+ const sorted = [...sessions].sort((a, b) => {
179
+ const aKnown = Boolean(a?.paneRectKnown) && Number.isFinite(Number(a?.paneLeft)) && Number.isFinite(Number(a?.paneTop));
180
+ const bKnown = Boolean(b?.paneRectKnown) && Number.isFinite(Number(b?.paneLeft)) && Number.isFinite(Number(b?.paneTop));
181
+ if (aKnown && bKnown) {
182
+ if (pos === "left") {
183
+ const dx = num(a.paneLeft) - num(b.paneLeft);
184
+ if (Math.abs(dx) > 4) return dx;
185
+ const dy = num(a.paneTop) - num(b.paneTop);
186
+ if (Math.abs(dy) > 4) return dy;
187
+ } else if (pos === "right") {
188
+ const dx = num(b.paneLeft) - num(a.paneLeft);
189
+ if (Math.abs(dx) > 4) return dx;
190
+ const dy = num(a.paneTop) - num(b.paneTop);
191
+ if (Math.abs(dy) > 4) return dy;
192
+ } else if (pos === "top") {
193
+ const dy = num(a.paneTop) - num(b.paneTop);
194
+ if (Math.abs(dy) > 4) return dy;
195
+ const dx = num(a.paneLeft) - num(b.paneLeft);
196
+ if (Math.abs(dx) > 4) return dx;
197
+ } else {
198
+ const dy = num(b.paneTop) - num(a.paneTop);
199
+ if (Math.abs(dy) > 4) return dy;
200
+ const dx = num(a.paneLeft) - num(b.paneLeft);
201
+ if (Math.abs(dx) > 4) return dx;
202
+ }
203
+ }
204
+ const aReg = num(a?.registeredAt, num(a?.updatedAt, 0));
205
+ const bReg = num(b?.registeredAt, num(b?.updatedAt, 0));
206
+ if (aReg !== bReg) {
207
+ return (pos === "right" || pos === "bottom") ? (bReg - aReg) : (aReg - bReg);
208
+ }
209
+ return num(a?.console, 0) - num(b?.console, 0);
210
+ });
211
+ return sorted[0];
212
+ }
213
+
214
+ function normalizedPaneRects(sessions) {
215
+ const entries = sessions.map((session) => {
216
+ const left = Number(session.paneLeft);
217
+ const top = Number(session.paneTop);
218
+ const rawRight = Number.isFinite(Number(session.paneRight)) ? Number(session.paneRight) : (left + 100);
219
+ const rawBottom = Number.isFinite(Number(session.paneBottom)) ? Number(session.paneBottom) : (top + 100);
220
+ let right = rawRight;
221
+ let bottom = rawBottom;
222
+ if (Number(session.initCols) > 0 && Number(session.cols) > 0 && rawRight > left) {
223
+ const scaled = Math.round(left + ((rawRight - left) / Number(session.initCols)) * Number(session.cols));
224
+ if (scaled > left + 16) right = Math.min(rawRight, scaled);
225
+ }
226
+ if (Number(session.initRows) > 0 && Number(session.rows) > 0 && rawBottom > top) {
227
+ const scaled = Math.round(top + ((rawBottom - top) / Number(session.initRows)) * Number(session.rows));
228
+ if (scaled > top + 16) bottom = Math.min(rawBottom, scaled);
229
+ }
230
+ return { session, left, top, right, bottom };
231
+ });
232
+
233
+ // Clamp stale pre-split right/bottom bounds against younger sibling panes so
234
+ // panes that were split without regaining focus never falsely claim an edge.
235
+ for (let pass = 0; pass < 2; pass += 1) {
236
+ for (const a of entries) {
237
+ for (const b of entries) {
238
+ if (a === b) continue;
239
+ if (b.left > a.left + 32 && b.top < a.bottom - 16 && b.bottom > a.top + 16) {
240
+ a.right = Math.min(a.right, b.left);
241
+ }
242
+ if (b.top > a.top + 24 && b.left < a.right - 16 && b.right > a.left + 16) {
243
+ a.bottom = Math.min(a.bottom, b.top);
244
+ }
245
+ }
246
+ }
247
+ }
248
+ return entries;
249
+ }
250
+
251
+ // Select all active AI panes touching the target window edge so a split tab
252
+ // can render one continuous full-window unified status bar across stacked
253
+ // (left/right) or side-by-side (top/bottom) panes without extra WT panes or HUDs.
254
+ export function selectSharedBarEdgeGroup(sessions = [], position = "bottom", { currentConsole = 0, currentCols = 0, currentRows = 0 } = {}) {
255
+ if (!Array.isArray(sessions) || !sessions.length) {
256
+ return { edgeSessions: [], isEdgeMember: false, sliceIndex: -1, sliceCount: 0, sliceOffset: 0, sliceLength: 0, totalSpan: 0 };
257
+ }
258
+ const pos = String(position || "bottom").trim().toLowerCase();
259
+ const isVertical = pos === "left" || pos === "right";
260
+ const allHaveRect = sessions.length > 1 && sessions.every(
261
+ s => Boolean(s?.paneRectKnown) && Number.isFinite(Number(s?.paneLeft)) && Number.isFinite(Number(s?.paneTop))
262
+ );
263
+
264
+ let edgeEntries;
265
+ if (!allHaveRect) {
266
+ const leader = selectSharedBarLeader(sessions, pos);
267
+ edgeEntries = leader ? [{ session: leader, left: 0, top: 0, right: 100, bottom: 100 }] : [];
268
+ } else {
269
+ const rects = normalizedPaneRects(sessions);
270
+ const minLeft = Math.min(...rects.map(r => r.left));
271
+ const maxRight = Math.max(...rects.map(r => r.right));
272
+ const minTop = Math.min(...rects.map(r => r.top));
273
+ const maxBottom = Math.max(...rects.map(r => r.bottom));
274
+ const xTol = 48;
275
+ const yTol = 36;
276
+
277
+ if (pos === "left") {
278
+ edgeEntries = rects.filter(r => (r.left - minLeft) <= xTol).sort((a, b) => (a.top - b.top) || (a.session.console - b.session.console));
279
+ } else if (pos === "right") {
280
+ edgeEntries = rects.filter(r => (maxRight - r.right) <= xTol).sort((a, b) => (a.top - b.top) || (a.session.console - b.session.console));
281
+ } else if (pos === "top") {
282
+ edgeEntries = rects.filter(r => (r.top - minTop) <= yTol).sort((a, b) => (a.left - b.left) || (a.session.console - b.session.console));
283
+ } else {
284
+ edgeEntries = rects.filter(r => (maxBottom - r.bottom) <= yTol).sort((a, b) => (a.left - b.left) || (a.session.console - b.session.console));
285
+ }
286
+ if (!edgeEntries.length) {
287
+ const leader = selectSharedBarLeader(sessions, pos);
288
+ edgeEntries = leader ? [{ session: leader, left: 0, top: 0, right: 100, bottom: 100 }] : [];
289
+ }
290
+ }
291
+
292
+ const edgeSessions = edgeEntries.map(e => e.session);
293
+ const targetConsole = Number(currentConsole);
294
+ const sliceIndex = edgeSessions.findIndex(s => Number(s.console) === targetConsole);
295
+ const isEdgeMember = sliceIndex >= 0;
296
+
297
+ const myEntry = isEdgeMember ? edgeEntries[sliceIndex] : null;
298
+ const mySpan = isVertical
299
+ ? (Number(currentRows) > 0 ? Math.trunc(Number(currentRows)) : (Number(myEntry?.session?.rows) || 0))
300
+ : (Number(currentCols) > 0 ? Math.trunc(Number(currentCols)) : (Number(myEntry?.session?.cols) || 0));
301
+ const myPx = myEntry ? Math.max(1, isVertical ? (myEntry.bottom - myEntry.top) : (myEntry.right - myEntry.left)) : 0;
302
+
303
+ const spans = edgeEntries.map((entry) => {
304
+ const isMe = Number(entry.session.console) === targetConsole;
305
+ const direct = isVertical
306
+ ? (isMe && Number(currentRows) > 0 ? Math.trunc(Number(currentRows)) : Number(entry.session.rows))
307
+ : (isMe && Number(currentCols) > 0 ? Math.trunc(Number(currentCols)) : Number(entry.session.cols));
308
+ if (Number.isFinite(direct) && direct > 0) return Math.trunc(direct);
309
+ const px = Math.max(1, isVertical ? (entry.bottom - entry.top) : (entry.right - entry.left));
310
+ if (mySpan > 0 && myPx > 0) return Math.max(1, Math.round(mySpan * (px / myPx)));
311
+ return isVertical ? 24 : 80;
312
+ });
313
+
314
+ const totalSpan = spans.reduce((sum, n) => sum + n, 0);
315
+ const sliceOffset = isEdgeMember ? spans.slice(0, sliceIndex).reduce((sum, n) => sum + n, 0) : 0;
316
+ const sliceLength = isEdgeMember ? spans[sliceIndex] : 0;
317
+
318
+ return {
319
+ edgeSessions,
320
+ isEdgeMember,
321
+ sliceIndex,
322
+ sliceCount: edgeSessions.length,
323
+ sliceOffset,
324
+ sliceLength,
325
+ totalSpan
326
+ };
327
+ }
328
+
329
+ export function unregisterAiSession({ root, context }) {
330
+ if (!validBarContext(context) || !Number(context?.console)) return false;
331
+ const file = path.join(sessionsDirPath(root, context), `console-${context.console}.json`);
332
+ try {
333
+ fs.rmSync(file, { force: true });
334
+ return true;
335
+ } catch {
336
+ return false;
337
+ }
338
+ }
339
+
340
+ export function clearTabAiSessions({ root, context }) {
341
+ if (!validBarContext(context)) return false;
342
+ try {
343
+ fs.rmSync(sessionsDirPath(root, context), { recursive: true, force: true });
344
+ return true;
345
+ } catch {
346
+ return false;
347
+ }
348
+ }
349
+
350
+ export function listActiveAiSessions({
351
+ root,
352
+ context,
353
+ now = Date.now(),
354
+ idleMs = DEFAULT_SESSION_IDLE_MS,
355
+ isAlive = defaultIsAlive,
356
+ pruneStale = true
357
+ }) {
358
+ if (!validBarContext(context)) return [];
359
+ const dir = sessionsDirPath(root, context);
360
+ let entries;
361
+ try {
362
+ entries = fs.readdirSync(dir, { withFileTypes: true });
363
+ } catch {
364
+ return [];
365
+ }
366
+ const active = [];
367
+ for (const entry of entries) {
368
+ if (!entry.isFile() || !/^console-\d+\.json$/.test(entry.name)) continue;
369
+ const file = path.join(dir, entry.name);
370
+ const record = readJson(file);
371
+ if (sessionIsActive(record, { now, idleMs, isAlive })) {
372
+ active.push(record);
373
+ } else if (pruneStale) {
374
+ try { fs.rmSync(file, { force: true }); } catch { /* Best-effort prune. */ }
375
+ }
376
+ }
377
+ return active.sort((a, b) => a.console - b.console);
378
+ }
379
+
380
+ function sessionSetKey(sessions) {
381
+ return sessions.map(s => `${s.console}:${s.ownerPid || 0}`).sort().join(",");
382
+ }
383
+
384
+ export function markSharedBarDismissed({ root, context, sessions = [], now = Date.now() }) {
385
+ if (!validBarContext(context)) return false;
386
+ writeJsonAtomic(dismissedStatePath(root, context), {
387
+ version: 1,
388
+ sessionKey: sessionSetKey(sessions),
389
+ dismissedAt: now
390
+ });
391
+ return true;
392
+ }
393
+
394
+ export function clearSharedBarDismissed({ root, context }) {
395
+ if (!validBarContext(context)) return false;
396
+ try {
397
+ fs.rmSync(dismissedStatePath(root, context), { force: true });
398
+ return true;
399
+ } catch {
400
+ return false;
401
+ }
402
+ }
403
+
404
+ // Decide whether an upper AI pane should automatically trigger AiBattery.AttachBar.
405
+ // Requires >= 2 distinct active AI panes in the same (window, tab), no active bar,
406
+ // not dismissed for this exact set of AI panes, and outside the trigger cooldown.
407
+ export function claimAutoAttachTrigger({
408
+ root,
409
+ context,
410
+ activeSessions = [],
411
+ minSessions = 2,
412
+ now = Date.now(),
413
+ cooldownMs = DEFAULT_TRIGGER_COOLDOWN_MS,
414
+ staleMs = DEFAULT_STALE_MS,
415
+ isAlive = defaultIsAlive
416
+ }) {
417
+ if (!validBarContext(context) || !context.tab) return { shouldTrigger: false, reason: "missing-tab" };
418
+ if (activeSessions.length < Math.max(1, Number(minSessions) || 2)) return { shouldTrigger: false, reason: "single-session" };
419
+ if (isSharedBarActive({ root, context, now, staleMs, isAlive }).active) {
420
+ return { shouldTrigger: false, reason: "already-active" };
421
+ }
422
+ const currentKey = sessionSetKey(activeSessions);
423
+ const dismissed = readJson(dismissedStatePath(root, context));
424
+ if (dismissed && dismissed.sessionKey === currentKey) {
425
+ return { shouldTrigger: false, reason: "dismissed" };
426
+ }
427
+ if (dismissed && dismissed.sessionKey !== currentKey) {
428
+ clearSharedBarDismissed({ root, context });
429
+ }
430
+ const triggerFile = triggerStatePath(root, context);
431
+ const previous = readJson(triggerFile);
432
+ if (previous && Number.isFinite(previous.triggeredAt) && now - previous.triggeredAt < cooldownMs) {
433
+ return { shouldTrigger: false, reason: "cooldown" };
434
+ }
435
+ // Use an atomic mkdir lock so two concurrent hooks don't double-fire VK_F24.
436
+ const lockDir = path.join(sharedBarTabDir(root, context), "trigger.lock");
437
+ fs.mkdirSync(sharedBarTabDir(root, context), { recursive: true });
438
+ try {
439
+ fs.mkdirSync(lockDir);
440
+ } catch (error) {
441
+ if (error?.code === "EEXIST") {
442
+ try {
443
+ if (now - fs.statSync(lockDir).mtimeMs > cooldownMs) {
444
+ fs.rmdirSync(lockDir);
445
+ fs.mkdirSync(lockDir);
446
+ } else {
447
+ return { shouldTrigger: false, reason: "locked" };
448
+ }
449
+ } catch {
450
+ return { shouldTrigger: false, reason: "locked" };
451
+ }
452
+ } else {
453
+ return { shouldTrigger: false, reason: "lock-error" };
454
+ }
455
+ }
456
+ try {
457
+ const recheck = readJson(triggerFile);
458
+ if (recheck && Number.isFinite(recheck.triggeredAt) && now - recheck.triggeredAt < cooldownMs) {
459
+ return { shouldTrigger: false, reason: "cooldown" };
460
+ }
461
+ writeJsonAtomic(triggerFile, {
462
+ version: 1,
463
+ triggeredAt: now,
464
+ pid: process.pid,
465
+ sessionKey: currentKey
466
+ });
467
+ return { shouldTrigger: true, reason: "auto-attach", sessionKey: currentKey };
468
+ } finally {
469
+ try { fs.rmdirSync(lockDir); } catch { /* Already cleaned. */ }
470
+ }
471
+ }
472
+
473
+ // Clear the auto-attach cooldown trigger (e.g. after a live position change
474
+ // closed the old bar) so the new bar attaches immediately at the new edge.
475
+ export function clearAutoAttachTrigger({ root, context }) {
476
+ if (!validBarContext(context) || !context.tab) return false;
477
+ try {
478
+ fs.rmSync(triggerStatePath(root, context), { force: true });
479
+ return true;
480
+ } catch {
481
+ return false;
482
+ }
483
+ }
484
+
485
+ // Check whether an auto-attach trigger was just fired for this tab (within the
486
+ // short boot window while Windows Terminal opens the root-split bar pane), so
487
+ // sibling AI panes can fold their internal bars smoothly in one synchronized step.
488
+ export function isAutoAttachPending({
489
+ root,
490
+ context,
491
+ now = Date.now(),
492
+ windowMs = 1800
493
+ }) {
494
+ if (!validBarContext(context) || !context.tab) return false;
495
+ const trigger = readJson(triggerStatePath(root, context));
496
+ if (!trigger || !Number.isFinite(trigger.triggeredAt)) return false;
497
+ const age = now - trigger.triggeredAt;
498
+ return age >= 0 && age <= windowMs;
499
+ }
500
+
501
+ // Check whether a dedicated native shared bar pane is actively running in the
502
+ // same Windows Terminal window + tab. Read-only and lock-free (atomic writes).
503
+ export function isSharedBarActive({
504
+ root,
505
+ context,
506
+ now = Date.now(),
507
+ staleMs = DEFAULT_STALE_MS,
508
+ isAlive = defaultIsAlive
509
+ }) {
510
+ if (!validBarContext(context)) return { active: false };
511
+ const leaseFile = sharedBarLeasePath(root, context);
512
+ const lease = readJson(leaseFile);
513
+ if (leaseIsFresh(lease, { now, staleMs, isAlive })) {
514
+ return {
515
+ active: true,
516
+ leaseFile,
517
+ ownerPid: lease.pid,
518
+ startedAt: lease.startedAt || "",
519
+ window: lease.window,
520
+ tab: lease.tab || ""
521
+ };
522
+ }
523
+ return { active: false, leaseFile };
524
+ }
525
+
526
+ // Claim the shared bar lease for (window, tab). If another live bar already
527
+ // owns this tab, returns { claimed: false, existing } so duplicate bars exit.
528
+ export function claimSharedBar({
529
+ root,
530
+ context,
531
+ pid = process.pid,
532
+ startedAt = "",
533
+ now = Date.now(),
534
+ staleMs = DEFAULT_STALE_MS,
535
+ isAlive = defaultIsAlive
536
+ }) {
537
+ if (!validBarContext(context)) return { claimed: false, reason: "invalid-context" };
538
+ const leaseFile = sharedBarLeasePath(root, context);
539
+ fs.mkdirSync(path.dirname(leaseFile), { recursive: true });
540
+ const lock = leaseFile + ".lock";
541
+ // Claiming is exclusive across concurrently launched native panes.
542
+ let held = false;
543
+ try {
544
+ for (let attempt = 0; attempt < 40; attempt += 1) {
545
+ try { fs.writeFileSync(lock, String(pid), { flag: "wx" }); held = true; break; }
546
+ catch (error) {
547
+ if (error.code !== "EEXIST") throw error;
548
+ try { if (Date.now() - fs.statSync(lock).mtimeMs > 5000) fs.unlinkSync(lock); } catch {}
549
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
550
+ }
551
+ }
552
+ if (!held) return { claimed: false, reason: "claim-busy" };
553
+ const existing = readJson(leaseFile);
554
+ if (
555
+ existing
556
+ && (existing.pid !== pid || (startedAt && existing.startedAt && existing.startedAt !== startedAt))
557
+ && leaseIsFresh(existing, { now, staleMs, isAlive })
558
+ ) {
559
+ return { claimed: false, reason: "already-active", leaseFile, existing };
560
+ }
561
+ clearSharedBarDismissed({ root, context });
562
+ const record = {
563
+ version: 1,
564
+ pid,
565
+ startedAt: String(startedAt || ""),
566
+ window: Number(context.window),
567
+ tab: String(context.tab || ""),
568
+ claimedAt: now,
569
+ updatedAt: now
570
+ };
571
+ writeJsonAtomic(leaseFile, record);
572
+ return { claimed: true, leaseFile, record };
573
+ } catch {
574
+ // A transient Windows file-sharing failure must not leave an error pane.
575
+ return { claimed: false, reason: "lease-unavailable", leaseFile };
576
+ } finally {
577
+ if (held) { try { fs.unlinkSync(lock); } catch {} }
578
+ }
579
+ }
580
+
581
+ export function heartbeatSharedBar({ leaseFile, pid = process.pid, startedAt = "", now = Date.now() }) {
582
+ if (!leaseFile) return false;
583
+ const current = readJson(leaseFile);
584
+ if (!current || current.pid !== pid) return false;
585
+ if (startedAt && current.startedAt && current.startedAt !== startedAt) return false;
586
+ writeJsonAtomic(leaseFile, { ...current, updatedAt: now });
587
+ return true;
588
+ }
589
+
590
+ export function releaseSharedBar({ leaseFile, pid = process.pid, startedAt = "" }) {
591
+ if (!leaseFile) return false;
592
+ const current = readJson(leaseFile);
593
+ if (!current || current.pid !== pid) return false;
594
+ if (startedAt && current.startedAt && current.startedAt !== startedAt) return false;
595
+ try {
596
+ fs.rmSync(leaseFile, { force: true });
597
+ return true;
598
+ } catch {
599
+ return false;
600
+ }
601
+ }
602
+
603
+ export { DEFAULT_STALE_MS, DEFAULT_SESSION_IDLE_MS, DEFAULT_TRIGGER_COOLDOWN_MS };