ai-battery 0.2.0 → 0.2.1
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/README.md +30 -14
- package/bin/ai-battery-macos-status.applescript +5 -12
- package/bin/ai-battery-run +701 -31
- package/bin/ai-battery-tmux.js +17 -0
- package/bin/terminal-compositor.js +111 -0
- package/docs/REFERENCE.md +23 -3
- package/docs/RELEASING.md +24 -7
- package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
- package/docs/hud-preview.svg +43 -20
- package/docs/terminal-vertical-preview.svg +73 -0
- package/lib/cli.js +945 -219
- package/lib/core/atomic-rename.js +18 -0
- package/lib/core/cli-help.js +35 -7
- package/lib/core/cli-messages.js +45 -1
- package/lib/core/cli-output.js +277 -72
- package/lib/core/cli-wrappers.js +410 -0
- package/lib/core/config-editor.js +177 -29
- package/lib/core/display-config.js +45 -0
- package/lib/core/integration-files.js +32 -3
- package/lib/core/shared-bar.js +603 -0
- package/lib/core/statusline-git.js +179 -15
- package/lib/core/terminal.js +25 -7
- package/lib/core/tmux-status.js +172 -0
- package/lib/core/uninstall.js +20 -7
- package/lib/core/usage-store.js +85 -0
- package/lib/hud/launcher.js +29 -31
- package/lib/platforms/linux/hud.js +1 -1
- package/lib/platforms/linux/panel.js +1 -1
- package/lib/platforms/macos/hud.js +5 -5
- package/lib/platforms/process-scanner.js +77 -29
- package/lib/platforms/windows/autostart-cleanup.js +1 -1
- package/lib/platforms/windows/codex-runner.js +178 -21
- package/lib/platforms/windows/hud/controls.ps1 +44 -10
- package/lib/platforms/windows/hud/main.ps1 +350 -43
- package/lib/platforms/windows/hud/rendering.ps1 +1227 -1
- package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
- package/lib/platforms/windows/hud-launcher.js +153 -79
- package/lib/platforms/windows/shared-bar-platform.js +972 -0
- package/lib/platforms/windows/terminal-compositor.js +210 -25
- package/lib/platforms/windows/wt-bar.js +729 -0
- package/lib/platforms/windows/wt-fragment.js +665 -0
- package/lib/platforms/windows/wt-keybinding.js +300 -0
- package/lib/providers/antigravity.js +155 -8
- package/package.json +5 -2
- package/vendor/PaneContext.cs +875 -0
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import crypto from "node:crypto";
|
|
5
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { atomicRename } from "../../core/atomic-rename.js";
|
|
8
|
+
import { DEFAULT_SIDEBAR_WIDTH, isDisplayConfig, normalizeBarPosition, normalizeSidebarWidth, normalizeSplitBarMode } from "../../core/display-config.js";
|
|
9
|
+
import { claimAutoAttachTrigger, isAutoAttachPending, isSharedBarActive, listActiveAiSessions, registerAiSession, selectSharedBarEdgeGroup, unregisterAiSession } from "../../core/shared-bar.js";
|
|
10
|
+
import { isWsl } from "../runtime.js";
|
|
11
|
+
import { isWtFragmentValid, readWtTriggerKeybinding, resolveWindowsLocalAppData, updateWtFragmentPosition } from "./wt-fragment.js";
|
|
12
|
+
|
|
13
|
+
const source = fileURLToPath(new URL("../../../vendor/PaneContext.cs", import.meta.url));
|
|
14
|
+
const memory = new Map();
|
|
15
|
+
let sourceDigestCache = null;
|
|
16
|
+
let wslWinStateDirMemo;
|
|
17
|
+
const wslSessionAliveCache = new Map();
|
|
18
|
+
const winPidsAliveCache = new Map();
|
|
19
|
+
|
|
20
|
+
function alive(pid) {
|
|
21
|
+
try {
|
|
22
|
+
process.kill(Number(pid), 0);
|
|
23
|
+
return Number(pid) > 0;
|
|
24
|
+
} catch (error) {
|
|
25
|
+
return error?.code === "EPERM";
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isValidHelperExe(file) {
|
|
30
|
+
try {
|
|
31
|
+
const stat = fs.statSync(file);
|
|
32
|
+
return stat.isFile() && stat.size > 0;
|
|
33
|
+
} catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function paneContextSourceDigest() {
|
|
39
|
+
const stat = fs.statSync(source);
|
|
40
|
+
if (sourceDigestCache && sourceDigestCache.mtimeMs === stat.mtimeMs && sourceDigestCache.size === stat.size) {
|
|
41
|
+
return sourceDigestCache;
|
|
42
|
+
}
|
|
43
|
+
const bytes = fs.readFileSync(source);
|
|
44
|
+
const digest = crypto.createHash("sha256").update(bytes).digest("hex");
|
|
45
|
+
sourceDigestCache = { mtimeMs: stat.mtimeMs, size: stat.size, digest, bytes };
|
|
46
|
+
return sourceDigestCache;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function findDotNetCompiler(env = process.env, wsl = false) {
|
|
50
|
+
let windowsDir = env.WINDIR || "C:\\Windows";
|
|
51
|
+
if (wsl) {
|
|
52
|
+
const converted = spawnSync("wslpath", ["-u", windowsDir], { encoding: "utf8", timeout: 2000 });
|
|
53
|
+
windowsDir = converted.status === 0 ? converted.stdout.trim() : "/mnt/c/Windows";
|
|
54
|
+
}
|
|
55
|
+
const framework = path.join(windowsDir, "Microsoft.NET");
|
|
56
|
+
return ["Framework64", "Framework"]
|
|
57
|
+
.map(name => path.join(framework, name, "v4.0.30319", "csc.exe"))
|
|
58
|
+
.find(file => fs.existsSync(file)) || null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function wpfReferencePaths(compiler) {
|
|
62
|
+
const wpfDir = path.join(path.dirname(compiler), "WPF");
|
|
63
|
+
return ["UIAutomationClient.dll", "UIAutomationTypes.dll", "WindowsBase.dll"]
|
|
64
|
+
.map(name => path.join(wpfDir, name));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function hasCustomXdgStateHome(env = process.env) {
|
|
68
|
+
const xdg = String(env.XDG_STATE_HOME || "").trim();
|
|
69
|
+
if (!xdg) return false;
|
|
70
|
+
const home = String(env.HOME || "").trim() || os.homedir();
|
|
71
|
+
return path.resolve(xdg) !== path.resolve(home, ".local", "state");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function resolveWslWindowsStateDir(env = process.env) {
|
|
75
|
+
if (process.platform === "win32" || !isWsl()) return null;
|
|
76
|
+
const override = String(env.AI_BATTERY_WINDOWS_STATE_DIR || "").trim();
|
|
77
|
+
if (override) return override;
|
|
78
|
+
if (env.AI_BATTERY_STATE_DIR || env.CLAUDEX_BATTERY_STATE_DIR || hasCustomXdgStateHome(env)) return null;
|
|
79
|
+
const home = String(env.HOME || "").trim() || os.homedir();
|
|
80
|
+
if (wslWinStateDirMemo && wslWinStateDirMemo.home === home && fs.existsSync(wslWinStateDirMemo.dir)) {
|
|
81
|
+
return wslWinStateDirMemo.dir;
|
|
82
|
+
}
|
|
83
|
+
const cacheFile = path.join(home, ".local", "state", "ai-battery", "windows-state-dir");
|
|
84
|
+
try {
|
|
85
|
+
const cached = fs.readFileSync(cacheFile, "utf8").trim();
|
|
86
|
+
if (cached && fs.existsSync(cached)) {
|
|
87
|
+
wslWinStateDirMemo = { home, dir: cached };
|
|
88
|
+
return cached;
|
|
89
|
+
}
|
|
90
|
+
} catch { /* Fall through. */ }
|
|
91
|
+
const localAppData = resolveWindowsLocalAppData(env);
|
|
92
|
+
if (localAppData) {
|
|
93
|
+
const derived = path.join(path.dirname(path.dirname(localAppData)), ".local", "state", "ai-battery");
|
|
94
|
+
if (fs.existsSync(derived)) {
|
|
95
|
+
wslWinStateDirMemo = { home, dir: derived };
|
|
96
|
+
return derived;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function isWslWtContext(env = process.env, platform = process.platform) {
|
|
103
|
+
if (platform === "win32" || !isWsl()) return false;
|
|
104
|
+
if (env.TMUX || env.SSH_CONNECTION || env.SSH_TTY) return false;
|
|
105
|
+
if (String(env.WT_SESSION || "").trim()) return true;
|
|
106
|
+
// DefTerm-launched `wsl.exe` (e.g. Start Menu `wsl` or Win+R) routes into
|
|
107
|
+
// Windows Terminal without exporting WT_SESSION; allow PaneContext `self`
|
|
108
|
+
// probing whenever Windows LOCALAPPDATA interop is reachable.
|
|
109
|
+
return Boolean(resolveWindowsLocalAppData(env, { platform }));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function sharedBarRoot(env = process.env, { platform = process.platform } = {}) {
|
|
113
|
+
const explicit = env.AI_BATTERY_STATE_DIR || env.CLAUDEX_BATTERY_STATE_DIR;
|
|
114
|
+
if (explicit) return path.join(explicit, "shared-bars");
|
|
115
|
+
const localAppData = resolveWindowsLocalAppData(env, { platform });
|
|
116
|
+
return path.join(
|
|
117
|
+
path.join(localAppData || os.tmpdir(), "ai-battery"),
|
|
118
|
+
"shared-bars"
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function displayConfigCandidates(env = process.env) {
|
|
123
|
+
const dirs = [];
|
|
124
|
+
const push = (dir) => {
|
|
125
|
+
const value = String(dir || "").trim();
|
|
126
|
+
if (value && !dirs.includes(value)) dirs.push(value);
|
|
127
|
+
};
|
|
128
|
+
push(env.AI_BATTERY_SHARED_USAGE_STATE_DIR);
|
|
129
|
+
push(resolveWslWindowsStateDir(env));
|
|
130
|
+
if (env.AI_BATTERY_STATE_DIR) push(env.AI_BATTERY_STATE_DIR);
|
|
131
|
+
else if (env.CLAUDEX_BATTERY_STATE_DIR) push(env.CLAUDEX_BATTERY_STATE_DIR);
|
|
132
|
+
else if (env.XDG_STATE_HOME) push(path.join(env.XDG_STATE_HOME, "ai-battery"));
|
|
133
|
+
else {
|
|
134
|
+
const envHome = String(env.HOME || "").trim();
|
|
135
|
+
const looksWinHome = envHome && (/^[A-Za-z]:[\\/]/.test(envHome) || envHome.startsWith("\\\\"));
|
|
136
|
+
const home = process.platform === "win32"
|
|
137
|
+
? (looksWinHome ? envHome : String(env.USERPROFILE || "").trim() || os.homedir())
|
|
138
|
+
: (envHome || os.homedir());
|
|
139
|
+
if (home) push(path.join(home, ".local", "state", "ai-battery"));
|
|
140
|
+
}
|
|
141
|
+
return dirs.map(dir => path.join(dir, "display-config.json"));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function readFirstDisplayConfig(env = process.env) {
|
|
145
|
+
for (const file of displayConfigCandidates(env)) {
|
|
146
|
+
try {
|
|
147
|
+
const text = fs.readFileSync(file, "utf8").replace(/^\uFEFF/, "");
|
|
148
|
+
const parsed = JSON.parse(text);
|
|
149
|
+
if (isDisplayConfig(parsed)) return parsed;
|
|
150
|
+
} catch {
|
|
151
|
+
// Missing or invalid config -> fall through to next candidate or default.
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function readConfiguredSplitBarMode(env = process.env) {
|
|
158
|
+
const parsed = readFirstDisplayConfig(env);
|
|
159
|
+
return parsed ? normalizeSplitBarMode(parsed.splitBar, "auto") : "auto";
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function readConfiguredBarPosition(env = process.env) {
|
|
163
|
+
const override = String(env.AI_BATTERY_BAR_POSITION || "").trim();
|
|
164
|
+
if (override) return normalizeBarPosition(override, "bottom");
|
|
165
|
+
const parsed = readFirstDisplayConfig(env);
|
|
166
|
+
return parsed?.barPosition ? normalizeBarPosition(parsed.barPosition, "bottom") : "bottom";
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function readConfiguredSplitBarPosition(env = process.env) {
|
|
170
|
+
const override = String(env.AI_BATTERY_SPLIT_BAR_POSITION || env.AI_BATTERY_BAR_POSITION || "").trim();
|
|
171
|
+
if (override) return normalizeBarPosition(override, "bottom");
|
|
172
|
+
const parsed = readFirstDisplayConfig(env);
|
|
173
|
+
if (parsed?.splitBarPosition) return normalizeBarPosition(parsed.splitBarPosition, "bottom");
|
|
174
|
+
if (parsed?.barPosition) return normalizeBarPosition(parsed.barPosition, "bottom");
|
|
175
|
+
return "bottom";
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function readConfiguredSidebarWidth(env = process.env) {
|
|
179
|
+
const override = String(env.AI_BATTERY_SIDEBAR_WIDTH || "").trim();
|
|
180
|
+
if (override) return normalizeSidebarWidth(override, DEFAULT_SIDEBAR_WIDTH);
|
|
181
|
+
const parsed = readFirstDisplayConfig(env);
|
|
182
|
+
return parsed?.sidebarWidth !== undefined
|
|
183
|
+
? normalizeSidebarWidth(parsed.sidebarWidth, DEFAULT_SIDEBAR_WIDTH)
|
|
184
|
+
: DEFAULT_SIDEBAR_WIDTH;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function resolveSplitBarMode(env = process.env, { configuredMode } = {}) {
|
|
188
|
+
const configured = configuredMode !== undefined
|
|
189
|
+
? normalizeSplitBarMode(configuredMode, "auto")
|
|
190
|
+
: readConfiguredSplitBarMode(env);
|
|
191
|
+
if (/^(0|false|off)$/i.test(env.AI_BATTERY_WT_BAR || env.AI_BATTERY_PANE_SHARING || "")) {
|
|
192
|
+
const source = /^(0|false|off)$/i.test(env.AI_BATTERY_WT_BAR || "") ? "AI_BATTERY_WT_BAR" : "AI_BATTERY_PANE_SHARING";
|
|
193
|
+
return { mode: "off", configuredMode: configured, envOverride: source };
|
|
194
|
+
}
|
|
195
|
+
if (/^(0|false|off)$/i.test(env.AI_BATTERY_WT_AUTO_ATTACH || "")) {
|
|
196
|
+
if (configured === "off") return { mode: "off", configuredMode: configured, envOverride: null };
|
|
197
|
+
return {
|
|
198
|
+
mode: "manual",
|
|
199
|
+
configuredMode: configured,
|
|
200
|
+
envOverride: configured === "auto" ? "AI_BATTERY_WT_AUTO_ATTACH" : null
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
return { mode: configured, configuredMode: configured, envOverride: null };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function preparePaneContextHelper(env = process.env, { build = true, platform = process.platform, wslBridge: wslBridgeOverride = undefined } = {}) {
|
|
207
|
+
const wslBridge = platform !== "win32" && (wslBridgeOverride ?? isWslWtContext(env, platform));
|
|
208
|
+
if (platform !== "win32" && !wslBridge) {
|
|
209
|
+
return { ready: false, built: false, path: null, compiler: null, reason: "PaneContext helper is Windows-only." };
|
|
210
|
+
}
|
|
211
|
+
let srcInfo;
|
|
212
|
+
try {
|
|
213
|
+
srcInfo = paneContextSourceDigest();
|
|
214
|
+
} catch {
|
|
215
|
+
return { ready: false, built: false, path: null, compiler: null, reason: "PaneContext helper source not found." };
|
|
216
|
+
}
|
|
217
|
+
const localAppData = resolveWindowsLocalAppData(env, { platform });
|
|
218
|
+
const baseDir = env.AI_BATTERY_DATA_DIR || (localAppData ? path.join(localAppData, "ai-battery") : null);
|
|
219
|
+
if (!baseDir) {
|
|
220
|
+
return { ready: false, built: false, path: null, compiler: null, reason: "PaneContext helper is not built. Run: ai-battery setup split" };
|
|
221
|
+
}
|
|
222
|
+
const folder = path.join(baseDir, "bin");
|
|
223
|
+
const executable = path.join(folder, `pane-context-${srcInfo.digest.slice(0, 16)}.exe`);
|
|
224
|
+
if (isValidHelperExe(executable)) {
|
|
225
|
+
return { ready: true, built: false, path: executable, compiler: null, reason: null };
|
|
226
|
+
}
|
|
227
|
+
if (wslBridge && !build) {
|
|
228
|
+
return { ready: false, built: false, path: executable, compiler: null, reason: "PaneContext helper is not built. Run: ai-battery setup split" };
|
|
229
|
+
}
|
|
230
|
+
const compiler = findDotNetCompiler(env, wslBridge);
|
|
231
|
+
if (!compiler) {
|
|
232
|
+
return {
|
|
233
|
+
ready: false,
|
|
234
|
+
built: false,
|
|
235
|
+
path: executable,
|
|
236
|
+
compiler: null,
|
|
237
|
+
reason: ".NET Framework csc.exe not found under %WINDIR%\\Microsoft.NET"
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
const refPaths = wpfReferencePaths(compiler);
|
|
241
|
+
const missingRef = refPaths.find(file => !fs.existsSync(file));
|
|
242
|
+
if (missingRef) {
|
|
243
|
+
return {
|
|
244
|
+
ready: false,
|
|
245
|
+
built: false,
|
|
246
|
+
path: executable,
|
|
247
|
+
compiler,
|
|
248
|
+
reason: `WPF UI Automation assembly not found: ${path.basename(missingRef)}`
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
if (!build) {
|
|
252
|
+
return {
|
|
253
|
+
ready: false,
|
|
254
|
+
built: false,
|
|
255
|
+
path: executable,
|
|
256
|
+
compiler,
|
|
257
|
+
reason: "PaneContext helper is not built. Run: ai-battery setup split"
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
fs.mkdirSync(folder, { recursive: true });
|
|
262
|
+
// Copy source to local NTFS first so csc.exe works reliably even when
|
|
263
|
+
// ai-battery is executed from a WSL UNC path (\\wsl$\...).
|
|
264
|
+
const localSource = path.join(folder, `pane-context-src-${process.pid}.cs`);
|
|
265
|
+
const temporary = path.join(folder, `pane-context-build-${process.pid}.exe`);
|
|
266
|
+
try {
|
|
267
|
+
fs.writeFileSync(localSource, srcInfo.bytes);
|
|
268
|
+
const nativePath = file => wslBridge ? toWindowsPath(file) : file;
|
|
269
|
+
const references = refPaths.map(file => `/reference:${nativePath(file)}`);
|
|
270
|
+
const compiled = spawnSync(
|
|
271
|
+
compiler,
|
|
272
|
+
["/nologo", "/target:exe", ...references, `/out:${nativePath(temporary)}`, nativePath(localSource)],
|
|
273
|
+
{ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true, timeout: 15000 }
|
|
274
|
+
);
|
|
275
|
+
if (compiled.error || compiled.status !== 0) {
|
|
276
|
+
const detail = `${compiled.stderr || ""}\n${compiled.stdout || ""}\n${compiled.error?.message || ""}`
|
|
277
|
+
.split(/\r?\n/)
|
|
278
|
+
.map(line => line.trim())
|
|
279
|
+
.find(Boolean) || `exit ${compiled.status}`;
|
|
280
|
+
return {
|
|
281
|
+
ready: false,
|
|
282
|
+
built: false,
|
|
283
|
+
path: executable,
|
|
284
|
+
compiler,
|
|
285
|
+
reason: `csc.exe failed to compile PaneContext helper: ${detail}`
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
if (!isValidHelperExe(executable)) {
|
|
289
|
+
try {
|
|
290
|
+
atomicRename(temporary, executable);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (!isValidHelperExe(executable)) {
|
|
293
|
+
return {
|
|
294
|
+
ready: false,
|
|
295
|
+
built: false,
|
|
296
|
+
path: executable,
|
|
297
|
+
compiler,
|
|
298
|
+
reason: `Could not publish PaneContext helper: ${error.message}`
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
} finally {
|
|
304
|
+
fs.rmSync(localSource, { force: true });
|
|
305
|
+
fs.rmSync(temporary, { force: true });
|
|
306
|
+
}
|
|
307
|
+
if (!isValidHelperExe(executable)) {
|
|
308
|
+
return {
|
|
309
|
+
ready: false,
|
|
310
|
+
built: false,
|
|
311
|
+
path: executable,
|
|
312
|
+
compiler,
|
|
313
|
+
reason: "PaneContext helper binary is missing after build."
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
return { ready: true, built: true, path: executable, compiler, reason: null };
|
|
317
|
+
} catch (error) {
|
|
318
|
+
return {
|
|
319
|
+
ready: false,
|
|
320
|
+
built: false,
|
|
321
|
+
path: executable,
|
|
322
|
+
compiler,
|
|
323
|
+
reason: error?.message || "Failed to prepare PaneContext helper."
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export function diagnosePaneContextHelper(env = process.env, options = {}) {
|
|
329
|
+
return preparePaneContextHelper(env, { ...options, build: false });
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function ensurePaneContextHelper(env = process.env, { build = true, wslBridge = undefined } = {}) {
|
|
333
|
+
const result = preparePaneContextHelper(env, { build, wslBridge });
|
|
334
|
+
return result.ready ? result.path : null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function readLinuxProcStat(pid) {
|
|
338
|
+
try {
|
|
339
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
340
|
+
const closeParen = stat.lastIndexOf(")");
|
|
341
|
+
if (closeParen < 0) return null;
|
|
342
|
+
const comm = stat.slice(stat.indexOf("(") + 1, closeParen);
|
|
343
|
+
const rest = stat.slice(closeParen + 2).trim().split(/\s+/);
|
|
344
|
+
const ppid = Number(rest[1]);
|
|
345
|
+
const starttime = String(rest[19] || "");
|
|
346
|
+
let cmdline = "";
|
|
347
|
+
try {
|
|
348
|
+
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").replaceAll("\0", " ").trim();
|
|
349
|
+
} catch {}
|
|
350
|
+
return { pid: Number(pid), ppid, comm, starttime, cmdline };
|
|
351
|
+
} catch {
|
|
352
|
+
return null;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export function resolveWslLinuxOwner(startPid, provider) {
|
|
357
|
+
let current = Number(startPid) || process.pid;
|
|
358
|
+
const seen = new Set();
|
|
359
|
+
let namedMatch = null;
|
|
360
|
+
let nodeMatch = null;
|
|
361
|
+
for (let depth = 0; depth < 24 && current > 1 && !seen.has(current); depth += 1) {
|
|
362
|
+
seen.add(current);
|
|
363
|
+
const info = readLinuxProcStat(current);
|
|
364
|
+
if (!info) break;
|
|
365
|
+
const comm = info.comm.toLowerCase();
|
|
366
|
+
const cmd = info.cmdline.toLowerCase();
|
|
367
|
+
const tokens = info.cmdline.split(/\s+/).filter(Boolean);
|
|
368
|
+
const exeBase = path.basename(tokens[0] || comm).toLowerCase();
|
|
369
|
+
const argBases = tokens.slice(1, 4).map(t => path.basename(t).toLowerCase());
|
|
370
|
+
if (!namedMatch && (
|
|
371
|
+
(provider === "antigravity" && (comm === "agy" || exeBase === "agy" || exeBase === "gemini" || argBases.some(b => b === "agy" || b === "agy.js" || b === "gemini" || b === "gemini.js"))) ||
|
|
372
|
+
(provider === "claude" && (comm === "claude" || exeBase === "claude" || exeBase === "claude-code" || cmd.includes("@anthropic-ai/claude-code") || cmd.includes("/claude-code"))) ||
|
|
373
|
+
(provider === "codex" && (comm === "codex" || exeBase === "codex" || cmd.includes("ai-battery-run")))
|
|
374
|
+
)) {
|
|
375
|
+
namedMatch = info;
|
|
376
|
+
}
|
|
377
|
+
if (!nodeMatch && (provider === "claude" || provider === "antigravity") && depth > 0 && (comm === "node" || exeBase === "node")) {
|
|
378
|
+
nodeMatch = info;
|
|
379
|
+
}
|
|
380
|
+
if (info.ppid <= 1 || info.ppid === current) break;
|
|
381
|
+
current = info.ppid;
|
|
382
|
+
}
|
|
383
|
+
const chosen = namedMatch || nodeMatch;
|
|
384
|
+
if (chosen) {
|
|
385
|
+
return { ownerPid: chosen.pid, startedAt: chosen.starttime, persistentOwner: true };
|
|
386
|
+
}
|
|
387
|
+
const fallback = readLinuxProcStat(Number(startPid) || process.pid);
|
|
388
|
+
return {
|
|
389
|
+
ownerPid: fallback?.pid || Number(startPid) || process.pid,
|
|
390
|
+
startedAt: fallback?.starttime || "",
|
|
391
|
+
persistentOwner: Number(startPid) > 0 && /\bai-battery-run\b/.test(fallback?.cmdline || "")
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export function nativePaneContext(pid, provider = "direct", tabMode = false, env = process.env) {
|
|
396
|
+
const wsl = isWslWtContext(env);
|
|
397
|
+
if (process.platform !== "win32" && !wsl) return null;
|
|
398
|
+
const executable = ensurePaneContextHelper(env, { build: false, wslBridge: true });
|
|
399
|
+
if (!executable) return null;
|
|
400
|
+
const tabArg = tabMode === "tab-only" ? ["tab-only"] : tabMode ? ["tab"] : [];
|
|
401
|
+
const targetArg = wsl ? "self" : String(pid);
|
|
402
|
+
const result = spawnSync(
|
|
403
|
+
executable,
|
|
404
|
+
[targetArg, provider, ...tabArg],
|
|
405
|
+
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true, timeout: 2500 }
|
|
406
|
+
);
|
|
407
|
+
try {
|
|
408
|
+
return result.status === 0 ? JSON.parse(result.stdout) : null;
|
|
409
|
+
} catch {
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export function nativeTabState(windowHandle, env = process.env) {
|
|
415
|
+
if (!windowHandle) return null;
|
|
416
|
+
const wsl = isWslWtContext(env);
|
|
417
|
+
if (process.platform !== "win32" && !wsl) return null;
|
|
418
|
+
const executable = ensurePaneContextHelper(env, { build: false, wslBridge: true });
|
|
419
|
+
if (!executable) return null;
|
|
420
|
+
const result = spawnSync(
|
|
421
|
+
executable,
|
|
422
|
+
["--tab-state", String(windowHandle)],
|
|
423
|
+
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true, timeout: 2000 }
|
|
424
|
+
);
|
|
425
|
+
try {
|
|
426
|
+
return result.status === 0 ? JSON.parse(result.stdout) : null;
|
|
427
|
+
} catch {
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export function nativePidsAlive(pids, env = process.env) {
|
|
433
|
+
const unique = [...new Set((pids || []).map(Number).filter(n => Number.isInteger(n) && n > 0))];
|
|
434
|
+
if (!unique.length) return new Set();
|
|
435
|
+
if (process.platform === "win32") {
|
|
436
|
+
return new Set(unique.filter(alive));
|
|
437
|
+
}
|
|
438
|
+
if (!isWsl()) return new Set();
|
|
439
|
+
const key = unique.sort((a, b) => a - b).join(",");
|
|
440
|
+
const cached = winPidsAliveCache.get(key);
|
|
441
|
+
if (cached && Date.now() - cached.at < 2000) return cached.alive;
|
|
442
|
+
const executable = ensurePaneContextHelper(env, { build: false, wslBridge: true });
|
|
443
|
+
if (!executable) return new Set();
|
|
444
|
+
const result = spawnSync(
|
|
445
|
+
executable,
|
|
446
|
+
["--pids-alive", key],
|
|
447
|
+
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true, timeout: 2000 }
|
|
448
|
+
);
|
|
449
|
+
try {
|
|
450
|
+
const parsed = result.status === 0 ? JSON.parse(result.stdout) : null;
|
|
451
|
+
const set = new Set((parsed?.alive || []).map(Number));
|
|
452
|
+
winPidsAliveCache.set(key, { at: Date.now(), alive: set });
|
|
453
|
+
return set;
|
|
454
|
+
} catch {
|
|
455
|
+
return new Set();
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function isWslLinuxPidAliveLocal(pid, startedAt = "") {
|
|
460
|
+
if (!alive(pid)) return false;
|
|
461
|
+
if (!startedAt) return true;
|
|
462
|
+
const info = readLinuxProcStat(pid);
|
|
463
|
+
return Boolean(info && (!info.starttime || info.starttime === String(startedAt)));
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function batchCheckWslSessionsFromWindows(distro, sessions) {
|
|
467
|
+
const key = `${distro}:${sessions.map(s => `${s.ownerPid}:${s.startedAt || ""}`).sort().join(",")}`;
|
|
468
|
+
const cached = wslSessionAliveCache.get(key);
|
|
469
|
+
if (cached && Date.now() - cached.at < 2000) return cached.alive;
|
|
470
|
+
const checks = sessions.map(s => {
|
|
471
|
+
const pid = Number(s.ownerPid);
|
|
472
|
+
const start = String(s.startedAt || "").replace(/[^0-9]/g, "");
|
|
473
|
+
if (!Number.isInteger(pid) || pid <= 0) return "";
|
|
474
|
+
return `if [ -r /proc/${pid}/stat ]; then s=$(cat /proc/${pid}/stat 2>/dev/null) && r=\${s##*) } && set -- $r && shift 19 && { [ -z "${start}" ] || [ "$1" = "${start}" ]; } && echo ${pid}; fi`;
|
|
475
|
+
}).filter(Boolean).join("; ");
|
|
476
|
+
if (!checks) return new Set();
|
|
477
|
+
try {
|
|
478
|
+
const args = [...(distro ? ["-d", distro] : []), "--exec", "sh", "-c", `${checks}; true`];
|
|
479
|
+
const wslExe = process.platform === "win32" ? "wsl.exe" : "/mnt/c/Windows/System32/wsl.exe";
|
|
480
|
+
const result = spawnSync(wslExe, args, {
|
|
481
|
+
encoding: "utf8",
|
|
482
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
483
|
+
windowsHide: true,
|
|
484
|
+
timeout: 2000
|
|
485
|
+
});
|
|
486
|
+
if (result.error || result.status !== 0) {
|
|
487
|
+
// Transient wsl.exe failure: fall back to live Win32 host PIDs rather than
|
|
488
|
+
// falsely concluding all WSL sessions exited.
|
|
489
|
+
return new Set(sessions.map(s => Number(s.ownerPid)).filter(n => Number.isInteger(n) && n > 0));
|
|
490
|
+
}
|
|
491
|
+
const set = new Set(
|
|
492
|
+
String(result.stdout || "").split(/\r?\n/).map(line => Number(line.trim())).filter(n => Number.isInteger(n) && n > 0)
|
|
493
|
+
);
|
|
494
|
+
wslSessionAliveCache.set(key, { at: Date.now(), alive: set });
|
|
495
|
+
return set;
|
|
496
|
+
} catch {
|
|
497
|
+
return new Set(sessions.map(s => Number(s.ownerPid)).filter(n => Number.isInteger(n) && n > 0));
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export function createCrossOsLeaseAlive({ env = process.env, platform = process.platform } = {}) {
|
|
502
|
+
if (platform === "win32") {
|
|
503
|
+
return (pid) => alive(pid);
|
|
504
|
+
}
|
|
505
|
+
return (pid, lease) => {
|
|
506
|
+
const updatedAt = Number(lease?.updatedAt || lease?.claimedAt || 0);
|
|
507
|
+
// Trust fresh Win32 wt-bar heartbeats (every 2s) at 0ms steady-state cost.
|
|
508
|
+
if (Number.isFinite(updatedAt) && Date.now() - updatedAt <= 4500) return true;
|
|
509
|
+
return nativePidsAlive([pid], env).has(Number(pid));
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
export function createCrossOsSessionAlive({ root, context, env = process.env, platform = process.platform } = {}) {
|
|
514
|
+
let winBatch = null;
|
|
515
|
+
const wslBatches = new Map();
|
|
516
|
+
const currentDistro = String(env.WSL_DISTRO_NAME || "").trim();
|
|
517
|
+
|
|
518
|
+
const readTabSessions = () => {
|
|
519
|
+
if (!root || !context?.window || !context?.tab) return [];
|
|
520
|
+
try {
|
|
521
|
+
const dir = path.join(
|
|
522
|
+
root,
|
|
523
|
+
String(context.window),
|
|
524
|
+
`tab-${crypto.createHash("sha256").update(String(context.tab)).digest("hex").slice(0, 16)}`,
|
|
525
|
+
"sessions"
|
|
526
|
+
);
|
|
527
|
+
return fs.readdirSync(dir)
|
|
528
|
+
.filter(name => /^console-\d+\.json$/.test(name))
|
|
529
|
+
.map(name => { try { return JSON.parse(fs.readFileSync(path.join(dir, name), "utf8")); } catch { return null; } })
|
|
530
|
+
.filter(Boolean);
|
|
531
|
+
} catch {
|
|
532
|
+
return [];
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
return (pid, session) => {
|
|
537
|
+
const host = session?.ownerHost || "win32";
|
|
538
|
+
if (platform === "win32") {
|
|
539
|
+
if (host !== "wsl") return alive(pid);
|
|
540
|
+
if (Number(session?.winHostPid) > 0 && !alive(session.winHostPid)) return false;
|
|
541
|
+
const distro = String(session?.wslDistro || "").trim();
|
|
542
|
+
if (!wslBatches.has(distro)) {
|
|
543
|
+
const matching = readTabSessions().filter(s => s?.ownerHost === "wsl" && String(s?.wslDistro || "").trim() === distro && s.persistentOwner);
|
|
544
|
+
if (!matching.some(s => Number(s.ownerPid) === Number(pid))) matching.push(session);
|
|
545
|
+
wslBatches.set(distro, batchCheckWslSessionsFromWindows(distro, matching));
|
|
546
|
+
}
|
|
547
|
+
return wslBatches.get(distro).has(Number(pid));
|
|
548
|
+
}
|
|
549
|
+
if (host === "wsl" && (!session?.wslDistro || !currentDistro || session.wslDistro === currentDistro)) {
|
|
550
|
+
return isWslLinuxPidAliveLocal(pid, session?.startedAt || "");
|
|
551
|
+
}
|
|
552
|
+
if (host !== "wsl") {
|
|
553
|
+
if (!winBatch) {
|
|
554
|
+
const winPids = readTabSessions().filter(s => (s?.ownerHost || "win32") !== "wsl" && s.persistentOwner).map(s => Number(s.ownerPid));
|
|
555
|
+
winPids.push(Number(pid));
|
|
556
|
+
winBatch = nativePidsAlive(winPids, env);
|
|
557
|
+
}
|
|
558
|
+
return winBatch.has(Number(pid));
|
|
559
|
+
}
|
|
560
|
+
const distro = String(session?.wslDistro || "").trim();
|
|
561
|
+
if (!wslBatches.has(distro)) {
|
|
562
|
+
const matching = readTabSessions().filter(s => s?.ownerHost === "wsl" && s.wslDistro === distro && s.persistentOwner);
|
|
563
|
+
if (!matching.some(s => Number(s.ownerPid) === Number(pid))) matching.push(session);
|
|
564
|
+
wslBatches.set(distro, batchCheckWslSessionsFromWindows(distro, matching));
|
|
565
|
+
}
|
|
566
|
+
return wslBatches.get(distro).has(Number(pid));
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function toWindowsPath(filePath) {
|
|
571
|
+
const text = String(filePath || "");
|
|
572
|
+
if (!text) return "";
|
|
573
|
+
if (/^[A-Za-z]:[\\/]/.test(text) || text.startsWith("\\\\")) return text.replace(/\//g, "\\");
|
|
574
|
+
const mnt = text.match(/^\/mnt\/([a-zA-Z])\/(.*)$/);
|
|
575
|
+
if (mnt) return `${mnt[1].toUpperCase()}:\\${mnt[2].replace(/\//g, "\\")}`;
|
|
576
|
+
if (text.startsWith("/") && isWsl()) {
|
|
577
|
+
const converted = spawnSync("wslpath", ["-w", text], { encoding: "utf8", timeout: 2000 });
|
|
578
|
+
if (converted.status === 0 && converted.stdout.trim()) return converted.stdout.trim();
|
|
579
|
+
}
|
|
580
|
+
return text;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
export function scheduleNativeFocusRestore(windowHandle, tabId, barPid, env = process.env) {
|
|
584
|
+
if ((process.platform !== "win32" && !isWslWtContext(env)) || !windowHandle) return false;
|
|
585
|
+
const executable = ensurePaneContextHelper(env, { build: false, wslBridge: true });
|
|
586
|
+
if (!executable) return false;
|
|
587
|
+
try {
|
|
588
|
+
const child = spawn(
|
|
589
|
+
executable,
|
|
590
|
+
["--restore-focus", String(windowHandle), String(tabId || ""), String(Math.max(0, Number(barPid) || 0))],
|
|
591
|
+
{ cwd: os.tmpdir(), stdio: "ignore", detached: true, windowsHide: true }
|
|
592
|
+
);
|
|
593
|
+
child.on("error", () => {});
|
|
594
|
+
child.unref();
|
|
595
|
+
return true;
|
|
596
|
+
} catch {
|
|
597
|
+
return false;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
export function triggerNativeAttachBar(windowHandle, tabId, vk, env = process.env, { minPanes = 2, delayMs = 0 } = {}) {
|
|
602
|
+
if ((process.platform !== "win32" && !isWslWtContext(env)) || !windowHandle || !vk) return false;
|
|
603
|
+
const executable = ensurePaneContextHelper(env, { build: false, wslBridge: true });
|
|
604
|
+
if (!executable) return false;
|
|
605
|
+
try {
|
|
606
|
+
const triggerArgs = ["--trigger-attach", String(windowHandle), String(tabId || ""), String(vk), String(Math.max(1, Number(minPanes) || 2))];
|
|
607
|
+
if (Number(delayMs) > 0) triggerArgs.push(String(Math.min(1500, Math.trunc(Number(delayMs)))));
|
|
608
|
+
const child = spawn(
|
|
609
|
+
executable,
|
|
610
|
+
triggerArgs,
|
|
611
|
+
{ cwd: os.tmpdir(), stdio: "ignore", detached: true, windowsHide: true }
|
|
612
|
+
);
|
|
613
|
+
child.on("error", () => {});
|
|
614
|
+
child.unref();
|
|
615
|
+
return true;
|
|
616
|
+
} catch {
|
|
617
|
+
return false;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function resolveTriggerBinding(env) {
|
|
622
|
+
// A pre-existing user shortcut can survive reset; it must never trigger an
|
|
623
|
+
// action after our profile/fragment has been removed.
|
|
624
|
+
return isWtFragmentValid({ env }) ? readWtTriggerKeybinding(env) : null;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
export function resolveCurrentPaneContext(provider, { ownerPid = 0, env = process.env, forceTab = false, includePaneCount = false, columnsOnly = false, cols = 0, rows = 0 } = {}) {
|
|
628
|
+
const wsl = isWslWtContext(env);
|
|
629
|
+
const root = sharedBarRoot(env);
|
|
630
|
+
const mode = ownerPid || provider === "codex" || provider === "direct" ? "direct" : provider;
|
|
631
|
+
const start = ownerPid || process.pid;
|
|
632
|
+
const wslLinuxOwner = wsl ? resolveWslLinuxOwner(start, provider) : null;
|
|
633
|
+
const session = wsl
|
|
634
|
+
? `wsl:${env.WT_SESSION || ""}:owner:${wslLinuxOwner?.ownerPid || start}:${wslLinuxOwner?.startedAt || ""}`
|
|
635
|
+
: (ownerPid || provider === "codex" || provider === "direct" ? String(start) : env.WT_SESSION || String(start));
|
|
636
|
+
const key = crypto.createHash("sha256").update(`${provider}:${session}`).digest("hex").slice(0, 24);
|
|
637
|
+
const cacheFile = path.join(root, `context-${key}.json`);
|
|
638
|
+
|
|
639
|
+
let cached = memory.get(key);
|
|
640
|
+
if (!cached) {
|
|
641
|
+
try { cached = JSON.parse(fs.readFileSync(cacheFile, "utf8")); } catch { /* First lookup. */ }
|
|
642
|
+
}
|
|
643
|
+
if (!forceTab && !includePaneCount && cached && !cached.context?.window && Date.now() - cached.checkedAt < 5000) {
|
|
644
|
+
return cached.context || null;
|
|
645
|
+
}
|
|
646
|
+
const cacheAlive = cached?.context?.ownerPid
|
|
647
|
+
? (wsl ? isWslLinuxPidAliveLocal(cached.context.ownerPid, cached.context.startedAt) : alive(cached.context.ownerPid))
|
|
648
|
+
: false;
|
|
649
|
+
const sizeChanged = (Number(cols) > 0 && Number(cached?.lastCols) > 0 && Number(cols) !== Number(cached.lastCols))
|
|
650
|
+
|| (Number(rows) > 0 && Number(cached?.lastRows) > 0 && Number(rows) !== Number(cached.lastRows));
|
|
651
|
+
const persistContextCache = (entry) => {
|
|
652
|
+
memory.set(key, entry);
|
|
653
|
+
if (!entry?.context?.window || forceTab) return;
|
|
654
|
+
try {
|
|
655
|
+
fs.mkdirSync(root, { recursive: true });
|
|
656
|
+
const temporary = `${cacheFile}.${process.pid}.tmp`;
|
|
657
|
+
try {
|
|
658
|
+
fs.writeFileSync(temporary, JSON.stringify(entry));
|
|
659
|
+
atomicRename(temporary, cacheFile);
|
|
660
|
+
} finally {
|
|
661
|
+
fs.rmSync(temporary, { force: true });
|
|
662
|
+
}
|
|
663
|
+
} catch { /* Best-effort cache write. */ }
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
if (!forceTab && !includePaneCount && cached?.context?.window && (columnsOnly || cached?.context?.tab) && cacheAlive) {
|
|
667
|
+
const age = Date.now() - cached.checkedAt;
|
|
668
|
+
if (!sizeChanged && age < 5000) {
|
|
669
|
+
// Refresh lightweight UIA-only paneCount/foreground every 1.5s so split
|
|
670
|
+
// creation (Alt+Shift+D) or split closure is detected promptly without AttachConsole churn.
|
|
671
|
+
if (!columnsOnly && age >= 1500) {
|
|
672
|
+
const liveTab = nativeTabState(cached.context.window, env);
|
|
673
|
+
if (liveTab && liveTab.tab && liveTab.tab === cached.context.tab) {
|
|
674
|
+
cached = {
|
|
675
|
+
...cached,
|
|
676
|
+
checkedAt: Date.now(),
|
|
677
|
+
context: {
|
|
678
|
+
...cached.context,
|
|
679
|
+
paneCount: Number(liveTab.paneCount) || cached.context.paneCount || 0,
|
|
680
|
+
...(typeof liveTab.foreground === "boolean" ? { foreground: liveTab.foreground } : {}),
|
|
681
|
+
...(Number(liveTab.clientWidth) > 0 ? { clientWidth: Number(liveTab.clientWidth) } : {}),
|
|
682
|
+
...(Number(liveTab.dpi) >= 72 ? { dpi: Number(liveTab.dpi) } : {})
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
persistContextCache(cached);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return cached.context;
|
|
689
|
+
}
|
|
690
|
+
if (!columnsOnly && sizeChanged) {
|
|
691
|
+
const liveTab = nativeTabState(cached.context.window, env);
|
|
692
|
+
if (liveTab && liveTab.tab && liveTab.tab === cached.context.tab) {
|
|
693
|
+
cached = {
|
|
694
|
+
...cached,
|
|
695
|
+
checkedAt: Date.now(),
|
|
696
|
+
lastCols: Number(cols) || cached.lastCols || 0,
|
|
697
|
+
lastRows: Number(rows) || cached.lastRows || 0,
|
|
698
|
+
context: {
|
|
699
|
+
...cached.context,
|
|
700
|
+
paneCount: Number(liveTab.paneCount) || cached.context.paneCount || 0,
|
|
701
|
+
...(typeof liveTab.foreground === "boolean" ? { foreground: liveTab.foreground } : {}),
|
|
702
|
+
...(Number(liveTab.clientWidth) > 0 ? { clientWidth: Number(liveTab.clientWidth) } : {}),
|
|
703
|
+
...(Number(liveTab.dpi) >= 72 ? { dpi: Number(liveTab.dpi) } : {})
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
persistContextCache(cached);
|
|
707
|
+
return cached.context;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
const tabMode = columnsOnly ? false : ((forceTab || includePaneCount) ? "tab" : ((!cached?.context?.tab || !cached?.context?.paneRectKnown) ? "tab-only" : false));
|
|
713
|
+
let context = nativePaneContext(start, mode, tabMode, env);
|
|
714
|
+
const profileId = String(env.WT_PROFILE_ID || "").trim();
|
|
715
|
+
if (wsl && context?.window) {
|
|
716
|
+
const linuxOwner = wslLinuxOwner || resolveWslLinuxOwner(start, provider);
|
|
717
|
+
context = {
|
|
718
|
+
...context,
|
|
719
|
+
winHostPid: Number(context.winHostPid || context.ownerPid) || 0,
|
|
720
|
+
ownerPid: linuxOwner.ownerPid,
|
|
721
|
+
startedAt: linuxOwner.startedAt,
|
|
722
|
+
persistentOwner: linuxOwner.persistentOwner,
|
|
723
|
+
ownerHost: "wsl",
|
|
724
|
+
wslDistro: String(env.WSL_DISTRO_NAME || "").trim(),
|
|
725
|
+
...(profileId ? { profileId } : {})
|
|
726
|
+
};
|
|
727
|
+
} else if (context?.window && profileId) {
|
|
728
|
+
context = { ...context, profileId };
|
|
729
|
+
}
|
|
730
|
+
// Concurrent status hooks can briefly fail to attach to the provider console.
|
|
731
|
+
// Retain only a recent, live owner; an absent probe must not erase its tab.
|
|
732
|
+
if (!context?.window && !forceTab && cached?.context?.tab
|
|
733
|
+
&& Date.now() - cached.checkedAt < 8000 && cacheAlive) {
|
|
734
|
+
return cached.context;
|
|
735
|
+
}
|
|
736
|
+
if (context?.window && cached?.context?.window && context.window !== cached.context.window) {
|
|
737
|
+
const reProbed = nativePaneContext(start, mode, includePaneCount ? "tab" : "tab-only", env);
|
|
738
|
+
if (reProbed?.window) {
|
|
739
|
+
context = wsl
|
|
740
|
+
? { ...context, ...reProbed, ownerPid: context.ownerPid, startedAt: context.startedAt, persistentOwner: context.persistentOwner, ownerHost: "wsl", wslDistro: context.wslDistro, winHostPid: Number(reProbed.winHostPid || reProbed.ownerPid) || context.winHostPid, ...(profileId ? { profileId } : {}) }
|
|
741
|
+
: { ...reProbed, ...(profileId ? { profileId } : {}) };
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (
|
|
745
|
+
!forceTab
|
|
746
|
+
&& cached?.context?.tab
|
|
747
|
+
&& ((context?.ownerPid === cached.context.ownerPid && context?.startedAt === cached.context.startedAt)
|
|
748
|
+
|| (context?.console && context.console === cached.context.console))
|
|
749
|
+
&& context?.window === cached.context.window
|
|
750
|
+
) {
|
|
751
|
+
context.tab = cached.context.tab;
|
|
752
|
+
if (!context.paneRectKnown && cached.context.paneRectKnown) {
|
|
753
|
+
context.paneRectKnown = true;
|
|
754
|
+
context.paneLeft = cached.context.paneLeft;
|
|
755
|
+
context.paneTop = cached.context.paneTop;
|
|
756
|
+
context.paneRight = cached.context.paneRight;
|
|
757
|
+
context.paneBottom = cached.context.paneBottom;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
if (!forceTab && context?.console === cached?.context?.console && context?.window === cached?.context?.window
|
|
761
|
+
&& cached?.context?.persistentOwner && !context?.persistentOwner && cacheAlive) {
|
|
762
|
+
context = { ...context, ownerPid: cached.context.ownerPid, startedAt: cached.context.startedAt, persistentOwner: true };
|
|
763
|
+
}
|
|
764
|
+
if (
|
|
765
|
+
cached?.context?.window
|
|
766
|
+
&& cached?.context?.tab
|
|
767
|
+
&& cached?.context?.console
|
|
768
|
+
&& context?.window
|
|
769
|
+
&& (context.window !== cached.context.window || (context.tab && context.tab !== cached.context.tab))
|
|
770
|
+
) {
|
|
771
|
+
unregisterAiSession({ root, context: cached.context });
|
|
772
|
+
}
|
|
773
|
+
cached = {
|
|
774
|
+
checkedAt: Date.now(),
|
|
775
|
+
context,
|
|
776
|
+
lastCols: Number(cols) > 0 ? Math.trunc(Number(cols)) : (Number(context?.columns) || 0),
|
|
777
|
+
lastRows: Number(rows) > 0 ? Math.trunc(Number(rows)) : 0
|
|
778
|
+
};
|
|
779
|
+
memory.set(key, cached);
|
|
780
|
+
if (context?.window && !forceTab) {
|
|
781
|
+
try {
|
|
782
|
+
fs.mkdirSync(root, { recursive: true });
|
|
783
|
+
const temporary = `${cacheFile}.${process.pid}.tmp`;
|
|
784
|
+
try {
|
|
785
|
+
fs.writeFileSync(temporary, JSON.stringify(cached));
|
|
786
|
+
atomicRename(temporary, cacheFile);
|
|
787
|
+
} finally {
|
|
788
|
+
fs.rmSync(temporary, { force: true });
|
|
789
|
+
}
|
|
790
|
+
} catch { /* Best-effort cache write. */ }
|
|
791
|
+
}
|
|
792
|
+
return context;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
export function cleanupPaneAiSession(provider, { ownerPid = 0, env = process.env } = {}) {
|
|
796
|
+
if (process.platform !== "win32" && !isWslWtContext(env)) return false;
|
|
797
|
+
try {
|
|
798
|
+
const context = resolveCurrentPaneContext(provider, { ownerPid, env });
|
|
799
|
+
if (!context?.window || !context?.console) return false;
|
|
800
|
+
return unregisterAiSession({ root: sharedBarRoot(env), context });
|
|
801
|
+
} catch {
|
|
802
|
+
return false;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
export function isPaneSharedBarActive(decision, options = {}) {
|
|
807
|
+
if (!decision?.root || !decision?.context) return false;
|
|
808
|
+
const isAlive = options.isAlive || createCrossOsLeaseAlive({ env: decision.env || process.env });
|
|
809
|
+
if (isSharedBarActive({ root: decision.root, context: decision.context, isAlive, ...options }).active) {
|
|
810
|
+
return true;
|
|
811
|
+
}
|
|
812
|
+
if (options.includePendingAttach) {
|
|
813
|
+
return isAutoAttachPending({ root: decision.root, context: decision.context, windowMs: options.pendingWindowMs });
|
|
814
|
+
}
|
|
815
|
+
return false;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// Upper panes register their active AI presence in (window, tab). By default,
|
|
819
|
+
// when >= 2 AI panes share the same tab, the edge Leader pane renders the
|
|
820
|
+
// unified status bar inside its own terminal buffer (no extra tab/pane and no
|
|
821
|
+
// external HUD window), while sibling AI panes hide their duplicate bar.
|
|
822
|
+
export function paneUsageDecision(provider, {
|
|
823
|
+
ownerPid = 0,
|
|
824
|
+
cols = 0,
|
|
825
|
+
rows = 0,
|
|
826
|
+
participate = true,
|
|
827
|
+
env = process.env,
|
|
828
|
+
platform = process.platform,
|
|
829
|
+
resolveContext = null,
|
|
830
|
+
resolveTrigger = resolveTriggerBinding,
|
|
831
|
+
triggerAttach = triggerNativeAttachBar,
|
|
832
|
+
isAlive = undefined
|
|
833
|
+
} = {}) {
|
|
834
|
+
if (!participate) return { showUsage: false, coordinated: false, sharedBar: false, columns: null, root: null, context: null };
|
|
835
|
+
const wslWt = isWslWtContext(env, platform);
|
|
836
|
+
if (platform !== "win32" && !wslWt) {
|
|
837
|
+
return { showUsage: true, coordinated: false, sharedBar: false, columns: null, root: null, context: null };
|
|
838
|
+
}
|
|
839
|
+
const { mode } = resolveSplitBarMode(env);
|
|
840
|
+
if (mode === "off") {
|
|
841
|
+
try {
|
|
842
|
+
const context = resolveContext
|
|
843
|
+
? resolveContext(provider, { ownerPid, env, columnsOnly: true })
|
|
844
|
+
: resolveCurrentPaneContext(provider, { ownerPid, env, columnsOnly: true });
|
|
845
|
+
const columns = Number(context?.columns) > 0 ? Math.trunc(Number(context.columns)) : null;
|
|
846
|
+
return { showUsage: true, coordinated: false, sharedBar: false, columns, root: null, context: null };
|
|
847
|
+
} catch {
|
|
848
|
+
return { showUsage: true, coordinated: false, sharedBar: false, columns: null, root: null, context: null };
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
const autoAttachDisabled = mode !== "auto";
|
|
852
|
+
try {
|
|
853
|
+
const context = resolveContext
|
|
854
|
+
? resolveContext(provider, { ownerPid, env, cols, rows })
|
|
855
|
+
: resolveCurrentPaneContext(provider, { ownerPid, env, cols, rows });
|
|
856
|
+
const columns = Number(cols) > 0
|
|
857
|
+
? Math.trunc(Number(cols))
|
|
858
|
+
: (Number(context?.columns) > 0 ? Math.trunc(Number(context.columns)) : null);
|
|
859
|
+
if (!context?.window) {
|
|
860
|
+
return { showUsage: true, coordinated: false, sharedBar: false, columns, root: null, context: null };
|
|
861
|
+
}
|
|
862
|
+
const root = sharedBarRoot(env, { platform });
|
|
863
|
+
if (context.tab && context.console) {
|
|
864
|
+
registerAiSession({
|
|
865
|
+
root,
|
|
866
|
+
context,
|
|
867
|
+
provider,
|
|
868
|
+
persistentOwner: Boolean(context.persistentOwner),
|
|
869
|
+
cols: Number(cols) > 0 ? Math.trunc(Number(cols)) : (columns || 0),
|
|
870
|
+
rows: Number(rows) > 0 ? Math.trunc(Number(rows)) : 0
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
const leaseAlive = isAlive || createCrossOsLeaseAlive({ env, platform });
|
|
874
|
+
const status = isSharedBarActive({ root, context, isAlive: leaseAlive });
|
|
875
|
+
if (status.active) {
|
|
876
|
+
return {
|
|
877
|
+
showUsage: false,
|
|
878
|
+
coordinated: true,
|
|
879
|
+
sharedBar: true,
|
|
880
|
+
barSlice: null,
|
|
881
|
+
window: status.window,
|
|
882
|
+
ownerPid: status.ownerPid,
|
|
883
|
+
columns,
|
|
884
|
+
root,
|
|
885
|
+
context,
|
|
886
|
+
env
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
const backendOverride = String(env.AI_BATTERY_SPLIT_BACKEND || "").trim().toLowerCase();
|
|
890
|
+
if (!autoAttachDisabled && context.tab) {
|
|
891
|
+
const sessionAlive = isAlive || createCrossOsSessionAlive({ root, context, env, platform });
|
|
892
|
+
const activeSessions = listActiveAiSessions({ root, context, isAlive: sessionAlive });
|
|
893
|
+
const isSplitTab = activeSessions.length >= 2 || Number(context.paneCount || 0) >= 2;
|
|
894
|
+
if (activeSessions.length >= 1 && isSplitTab) {
|
|
895
|
+
const position = readConfiguredSplitBarPosition(env);
|
|
896
|
+
const prefersWtPane = triggerAttach !== triggerNativeAttachBar || backendOverride !== "in-terminal";
|
|
897
|
+
if (prefersWtPane) {
|
|
898
|
+
const binding = resolveTrigger(env);
|
|
899
|
+
if (binding?.vk) {
|
|
900
|
+
if (context.foreground === true) {
|
|
901
|
+
const minSessions = Number(context.paneCount || 0) >= 2 ? 1 : 2;
|
|
902
|
+
const decision = claimAutoAttachTrigger({ root, context, activeSessions, minSessions, isAlive: leaseAlive });
|
|
903
|
+
if (decision.shouldTrigger) {
|
|
904
|
+
let attachDelayMs = 0;
|
|
905
|
+
if (triggerAttach === triggerNativeAttachBar && (position === "left" || position === "right") && Number(context.clientWidth) >= 400) {
|
|
906
|
+
try {
|
|
907
|
+
const tuned = updateWtFragmentPosition({
|
|
908
|
+
env,
|
|
909
|
+
position,
|
|
910
|
+
sidebarWidth: readConfiguredSidebarWidth(env),
|
|
911
|
+
windowClientWidth: Number(context.clientWidth),
|
|
912
|
+
windowDpi: Number(context.dpi) || 96
|
|
913
|
+
});
|
|
914
|
+
if (tuned?.updated) attachDelayMs = 250;
|
|
915
|
+
} catch {}
|
|
916
|
+
}
|
|
917
|
+
triggerAttach(context.window, context.tab, binding.vk, env, {
|
|
918
|
+
minPanes: 2,
|
|
919
|
+
...(attachDelayMs > 0 ? { delayMs: attachDelayMs } : {})
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
const attaching = triggerAttach === triggerNativeAttachBar
|
|
924
|
+
&& isAutoAttachPending({ root, context });
|
|
925
|
+
return { showUsage: true, attaching, coordinated: false, sharedBar: false, columns, root, context, env };
|
|
926
|
+
}
|
|
927
|
+
// If WT fragment/trigger is explicitly expected (legacy override/test), stop here;
|
|
928
|
+
// otherwise fall back cleanly to in-terminal edge coordination.
|
|
929
|
+
if (triggerAttach !== triggerNativeAttachBar || backendOverride === "wt-pane") {
|
|
930
|
+
return { showUsage: true, coordinated: false, sharedBar: false, columns, root, context, env };
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
if (activeSessions.length < 2) {
|
|
934
|
+
return { showUsage: true, coordinated: false, sharedBar: false, barSlice: null, columns, root, context, env };
|
|
935
|
+
}
|
|
936
|
+
const edge = selectSharedBarEdgeGroup(activeSessions, position, {
|
|
937
|
+
currentConsole: context.console,
|
|
938
|
+
currentCols: columns || 0,
|
|
939
|
+
currentRows: Number(rows) > 0 ? Math.trunc(Number(rows)) : 0
|
|
940
|
+
});
|
|
941
|
+
const leader = edge.edgeSessions[0] || null;
|
|
942
|
+
const isEdgeMember = edge.isEdgeMember || !leader;
|
|
943
|
+
const isLeader = !leader || Number(leader.console) === Number(context.console);
|
|
944
|
+
const barSlice = isEdgeMember && edge.sliceCount > 1
|
|
945
|
+
? {
|
|
946
|
+
offset: edge.sliceOffset,
|
|
947
|
+
length: edge.sliceLength,
|
|
948
|
+
total: edge.totalSpan,
|
|
949
|
+
index: edge.sliceIndex,
|
|
950
|
+
count: edge.sliceCount
|
|
951
|
+
}
|
|
952
|
+
: null;
|
|
953
|
+
return {
|
|
954
|
+
showUsage: isEdgeMember,
|
|
955
|
+
coordinated: true,
|
|
956
|
+
sharedBar: !isEdgeMember,
|
|
957
|
+
isLeader,
|
|
958
|
+
leaderConsole: leader ? Number(leader.console) : Number(context.console),
|
|
959
|
+
sessionCount: activeSessions.length,
|
|
960
|
+
barSlice,
|
|
961
|
+
columns,
|
|
962
|
+
root,
|
|
963
|
+
context,
|
|
964
|
+
env
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return { showUsage: true, coordinated: false, sharedBar: false, barSlice: null, columns, root, context, env };
|
|
969
|
+
} catch {
|
|
970
|
+
return { showUsage: true, coordinated: false, sharedBar: false, barSlice: null, columns: null, root: null, context: null };
|
|
971
|
+
}
|
|
972
|
+
}
|