ai-battery 0.1.17 → 0.1.18

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 CHANGED
@@ -173,11 +173,11 @@ ai-battery setup codex
173
173
 
174
174
  Codex setup은 `~/.codex/config.toml`의 `[tui]`에 `model-with-reasoning`, `current-dir`, `git-branch` status line을 설정합니다. 기존 값이 있으면 uninstall 복구용으로 백업합니다. Codex wrapper는 기존 `codex` 명령을 직접 덮어쓰지 않습니다. `~/.local/bin`이 이미 PATH에서 원본 `codex`보다 앞에 있고 `~/.local/bin/codex`가 비어 있거나 AI Battery 관리 파일이면 그 위치에 wrapper를 둬서 바로 잡히게 합니다. 그렇지 않으면 `~/.local/share/ai-battery/bin/codex`에 관리형 wrapper를 만들고, 필요한 경우 셸 설정에 이 디렉터리를 PATH 앞쪽으로 추가합니다. `~/.local/bin/codex` 같은 공용 위치에 이미 다른 파일이 있으면 덮어쓰지 않습니다. 새 터미널부터 `codex`가 자동으로 AI Battery 하단 행과 함께 실행됩니다. 같은 터미널에서 이미 `codex`를 실행한 적이 있으면 셸 캐시 때문에 `hash -r`이 한 번 필요할 수 있고, PATH 추가가 필요한 경우에는 `setup` 출력에 표시되는 `source ...` 명령을 실행하세요.
175
175
 
176
- Windows native `cmd`/PowerShell에서는 `codex.cmd` wrapper가 기본 `fullscreen` runner를 실행합니다. 이 경로에는 중간 ConPTY나 headless terminal이 없습니다. Codex가 실제 콘솔에 직접 연결되어 native alternate screen, 스크롤, 입력과 `[tui].status_line`을 그대로 소유합니다. AI Battery는 터미널 바로 아래에 Codex와 Claude 사용량을 Linux/macOS와 같은 텍스트 TUI 상태행으로 표시합니다. 최대화, 전체화면, Windows 스냅이 터미널 높이를 다시 채우면 상태행 공간을 자동으로 재확보합니다. dock 중에는 터미널 하단 코너를 직각으로 바꾸고 상태행을 경계에 겹쳐 붙인 뒤 상태행의 하단 코너만 둥글게 처리하므로 하나의 창처럼 이어집니다. 이 docked TUI와 작업표시줄 HUD는 별도 프로세스와 singleton을 사용하므로 동시에 실행할 수 있습니다. `AI_BATTERY_WIN_LAYOUT=fullscreen`이 명시 이름이고 `auto`는 같은 경로의 호환 alias입니다.
176
+ Windows native `cmd`/PowerShell에서는 `codex.cmd` wrapper가 기본 `fullscreen` runner를 실행합니다. 이 경로에는 중간 ConPTY나 headless terminal이 없습니다. Codex가 실제 콘솔에 직접 연결되어 native alternate screen, 스크롤, 입력과 `[tui].status_line`을 그대로 소유합니다. AI Battery는 터미널 바로 아래에 Codex와 Claude 사용량을 Linux/macOS와 같은 텍스트 TUI 상태행으로 표시합니다. 최대화, 전체화면, Windows 스냅이 터미널 높이를 다시 채우면 상태행 공간을 자동으로 재확보합니다. dock 중에는 터미널 하단 코너를 직각으로 바꾸고 상태행을 경계에 겹쳐 붙인 뒤 상태행의 하단 코너만 둥글게 처리하므로 하나의 창처럼 이어집니다. 활성 상태와 수명은 Windows 전체 프로세스가 아니라 터미널 HWND별 provider 세션으로 관리하며, 탭을 다른 Windows Terminal 창으로 옮기면 새 HWND로 등록을 이전합니다. 이 docked TUI와 작업표시줄 HUD는 별도 프로세스와 singleton을 사용하므로 동시에 실행할 수 있습니다. `AI_BATTERY_WIN_LAYOUT=fullscreen`이 명시 이름이고 `auto`는 같은 경로의 호환 alias입니다.
177
177
 
178
178
  Windows dock 위치는 `AI_BATTERY_WIN_DOCK_POSITION`으로 선택합니다. 기본값 `bottom`은 터미널 하단에 결합하고, `tabs`는 같은 compact 사용량 행을 상단 탭 바 오른쪽에 고정합니다. PowerShell에서는 `$env:AI_BATTERY_WIN_DOCK_POSITION="tabs"`, cmd에서는 `set AI_BATTERY_WIN_DOCK_POSITION=tabs`를 설정한 뒤 `codex`를 실행합니다. launcher를 직접 확인하려면 `ai-battery hud --dock-console --dock-position tabs`를 사용합니다.
179
179
 
180
- `composite`는 `@xterm/headless`로 화면을 재해석하는 실험 모드입니다. `tui`, `reserve`, `overlay`, `inline`도 이전 구현을 확인하기 위한 호환 모드이며, `tui`에서만 로컬 빌드된 `rowpty.exe`와 bundled ConPTY를 사용합니다. 기본 docked HUD에는 rowpty가 필요하지 않으므로 일반 `setup`에서는 컴파일하지 않습니다. 레거시 경로가 필요하면 `AI_BATTERY_WIN_LAYOUT=tui` 또는 `AI_BATTERY_INSTALL_ROWPTY=1`을 설정한 뒤 `ai-battery setup codex`를 다시 실행하세요. `plain`은 HUD 없이 Codex를 직접 실행합니다. Windows의 Claude statusLine은 Claude Code 내부 header만 표시하고, 첫 statusLine payload에서 같은 terminal-docked 사용량 HUD를 연결합니다.
180
+ `composite`는 `@xterm/headless`로 화면을 재해석하는 실험 모드입니다. `tui`, `reserve`, `overlay`, `inline`도 이전 구현을 확인하기 위한 호환 모드이며, `tui`에서만 로컬 빌드된 `rowpty.exe`와 bundled ConPTY를 사용합니다. 기본 docked HUD도 Windows Claude setup이 설치한 작은 `rowpty.exe`를 Job Object 밖의 HUD 호스트 실행과 포그라운드 터미널 HWND 조회에 사용하지만, 이 경우 ConPTY나 터미널 렌더링은 사용하지 않습니다. `ai-battery setup` 또는 `ai-battery setup claude`가 이 헬퍼를 로컬에서 컴파일합니다. Codex만 설치하면서 레거시 TUI 경로가 필요하면 `AI_BATTERY_WIN_LAYOUT=tui` 또는 `AI_BATTERY_INSTALL_ROWPTY=1`을 설정한 뒤 `ai-battery setup codex`를 다시 실행하세요. `plain`은 HUD 없이 Codex를 직접 실행합니다. Windows의 Claude statusLine은 Claude Code 내부 header만 표시하고, 첫 statusLine payload에서 같은 terminal-docked 사용량 HUD를 연결합니다.
181
181
 
182
182
  Native fullscreen의 자동 smoke는 `npm run smoke:fullscreen`, 실험 compositor smoke는 `npm run smoke:composite`로 실행합니다. 두 테스트 모두 `cmd`와 PowerShell 자식을 각각 검증합니다.
183
183
 
@@ -342,7 +342,7 @@ Codex는 최근 세션 로그에서 `rate_limits` 이벤트를 찾습니다. Cla
342
342
 
343
343
  ## Source Environment
344
344
 
345
- 기본 CLI는 Node.js 18 이상이 있으면 Windows native, WSL, Linux, macOS에서 실행됩니다. Windows native의 기본 Codex 경로는 중간 PTY 없이 Codex를 직접 실행하고 PowerShell/WinForms docked HUD를 붙입니다. `rowpty.exe`와 same-console overlay는 명시적으로 선택한 레거시 `tui`/`reserve`/`overlay` 모드에서만 사용합니다. WSL/Linux/macOS의 `ai-battery-run`은 Python 3와 POSIX PTY를 사용하고, macOS HUD는 내장 `osascript`와 AppleScriptObjC를 사용합니다.
345
+ 기본 CLI는 Node.js 18 이상이 있으면 Windows native, WSL, Linux, macOS에서 실행됩니다. Windows native의 기본 Codex 경로는 중간 PTY 없이 Codex를 직접 실행하고 PowerShell/WinForms docked HUD를 붙입니다. 이 경로에서 `rowpty.exe`는 분리 프로세스 실행과 HWND 조회만 담당하고, same-console 렌더링과 ConPTY는 명시적으로 선택한 레거시 `tui`/`reserve`/`overlay` 모드에서만 사용합니다. WSL/Linux/macOS의 `ai-battery-run`은 Python 3와 POSIX PTY를 사용하고, macOS HUD는 내장 `osascript`와 AppleScriptObjC를 사용합니다.
346
346
 
347
347
  Codex 데이터는 Codex가 실제로 사용하는 `CODEX_HOME`(기본값 `~/.codex`)의 `sessions`를 읽습니다. AI Battery는 `HOME`, `USERPROFILE`, `CODEX_HOME`을 설정하거나 변경하지 않습니다. `CODEX_HOME`을 바꾸면 Codex 자체의 `/resume` 저장소도 바뀌므로 Windows와 WSL의 경로를 합치는 용도로 사용하지 마세요. 쉼표로 여러 경로를 지정하는 방식도 지원하지 않습니다.
348
348
 
package/lib/cli.js CHANGED
@@ -5,12 +5,12 @@ import fs from "node:fs";
5
5
  import https from "node:https";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
- import { execFileSync, spawn, spawnSync } from "node:child_process";
8
+ import { execFileSync, spawnSync } from "node:child_process";
9
9
  import { createRequire } from "node:module";
10
10
  import { fileURLToPath, pathToFileURL } from "node:url";
11
11
  import { isDeepStrictEqual } from "node:util";
12
12
 
13
- import { rowptyExePath } from "./platforms/windows/codex-runner.js";
13
+ import { quoteWindowsCommandLineArg, rowptyExePath } from "./platforms/windows/codex-runner.js";
14
14
  import { isWsl } from "./platforms/runtime.js";
15
15
  import { createProcessScanner } from "./platforms/process-scanner.js";
16
16
  import { createWindowsPathIntegration } from "./platforms/windows/path-integration.js";
@@ -2220,8 +2220,15 @@ function setupTargets(targets) {
2220
2220
  function runSetup(args) {
2221
2221
  const targets = setupTargets(args.targets);
2222
2222
  const results = {};
2223
+ let windowsClaudeLauncher = null;
2223
2224
  if (targets.includes("claude")) {
2224
- results.claude = installClaudeStatusline(args);
2225
+ const statusLine = installClaudeStatusline(args);
2226
+ if (process.platform === "win32") {
2227
+ windowsClaudeLauncher = installRowPtyHost();
2228
+ results.claude = { ...statusLine, launcher: windowsClaudeLauncher };
2229
+ } else {
2230
+ results.claude = statusLine;
2231
+ }
2225
2232
  }
2226
2233
  if (targets.includes("tmux")) {
2227
2234
  results.tmux = installTmuxStatus();
@@ -2234,11 +2241,13 @@ function runSetup(args) {
2234
2241
  };
2235
2242
  if (process.platform === "win32") {
2236
2243
  results.codex.rowpty = windowsSetupNeedsRowPty()
2237
- ? installRowPtyHost()
2244
+ ? (windowsClaudeLauncher || installRowPtyHost())
2238
2245
  : {
2239
2246
  ok: true,
2240
2247
  skipped: true,
2241
- reason: "Not required by the default docked HUD; set AI_BATTERY_WIN_LAYOUT=tui and run setup codex to install it"
2248
+ reason: windowsClaudeLauncher?.ok
2249
+ ? "Installed with the Windows Claude HUD launcher; not required by the current Codex layout"
2250
+ : "Not required by the default docked HUD; set AI_BATTERY_WIN_LAYOUT=tui and run setup codex to install it"
2242
2251
  };
2243
2252
  }
2244
2253
  }
@@ -2248,8 +2257,11 @@ function runSetup(args) {
2248
2257
  function setupResultFailed(result) {
2249
2258
  return Boolean(
2250
2259
  result.claude?.error
2260
+ || result.claude?.launcher?.error
2261
+ || (result.claude?.launcher && result.claude.launcher.ok === false)
2251
2262
  || (result.codex && result.codex.ok === false)
2252
2263
  || result.codex?.statusLine?.error
2264
+ || result.codex?.rowpty?.error
2253
2265
  || (result.codex?.rowpty && result.codex.rowpty.ok === false)
2254
2266
  || (result.tmux && result.tmux.ok === false && !result.tmux.skipped)
2255
2267
  );
@@ -2979,6 +2991,10 @@ function captureClaudeStatusline(input) {
2979
2991
  transcriptPath: input.transcript_path ?? input.transcriptPath ?? null,
2980
2992
  sessionKind,
2981
2993
  claudeVersion: input.version ?? null,
2994
+ workspace: {
2995
+ currentDir: input.workspace?.current_dir ?? input.workspace?.currentDir ?? null,
2996
+ projectDir: input.workspace?.project_dir ?? input.workspace?.projectDir ?? null
2997
+ },
2982
2998
  model: {
2983
2999
  id: typeof input.model === "string" ? input.model : input.model?.id ?? null,
2984
3000
  displayName: typeof input.model === "string" ? input.model : input.model?.display_name ?? input.model?.displayName ?? null
@@ -3563,18 +3579,312 @@ function windowsHudEnabled() {
3563
3579
  return !["0", "false", "no", "off"].includes(String(value).trim().toLowerCase());
3564
3580
  }
3565
3581
 
3566
- function attachWindowsClaudeHud(sessionId) {
3582
+ function windowsProviderOwnerPidFromAncestors(provider, ancestors) {
3583
+ const executable = provider === "claude"
3584
+ ? /^(?:claude|claude-code)(?:\.exe)?$/i
3585
+ : /^codex(?:\.exe)?$/i;
3586
+ const packageMarkers = provider === "claude"
3587
+ ? ["@anthropic-ai/claude-code", "@anthropic-ai\\claude-code", "claude-code/cli.js", "claude-code\\cli.js"]
3588
+ : ["@openai/codex"];
3589
+ for (const ancestor of ancestors || []) {
3590
+ const processId = Number(ancestor.processId ?? ancestor.ProcessId);
3591
+ if (!Number.isInteger(processId) || processId <= 0) continue;
3592
+ const name = String(ancestor.name ?? ancestor.Name ?? "").trim();
3593
+ const commandLine = String(ancestor.commandLine ?? ancestor.CommandLine ?? "").toLowerCase();
3594
+ if (executable.test(name) || packageMarkers.some((marker) => commandLine.includes(marker))) {
3595
+ return processId;
3596
+ }
3597
+ }
3598
+ return 0;
3599
+ }
3600
+
3601
+ function windowsProcessAncestors(startPid = process.ppid) {
3602
+ if (process.platform !== "win32" || !Number.isInteger(Number(startPid)) || Number(startPid) <= 0) return [];
3603
+ const script = [
3604
+ `$currentId = ${Math.trunc(Number(startPid))}`,
3605
+ "$items = @()",
3606
+ "for ($depth = 0; $depth -lt 16 -and $currentId -gt 0; $depth++) {",
3607
+ " $item = Get-CimInstance Win32_Process -Filter (\"ProcessId = $currentId\") -ErrorAction SilentlyContinue",
3608
+ " if (-not $item) { break }",
3609
+ " $items += [PSCustomObject]@{ processId = [int]$item.ProcessId; parentProcessId = [int]$item.ParentProcessId; name = [string]$item.Name; commandLine = [string]$item.CommandLine }",
3610
+ " if ([string]$item.Name -match '^(?:claude|claude-code)(?:\\.exe)?$' -or [string]$item.CommandLine -match '@anthropic-ai[\\\\/]claude-code') { break }",
3611
+ " $currentId = [int]$item.ParentProcessId",
3612
+ "}",
3613
+ "ConvertTo-Json -InputObject @($items) -Compress"
3614
+ ].join("; ");
3615
+ try {
3616
+ const result = spawnSync("powershell.exe", [
3617
+ "-NoLogo",
3618
+ "-NoProfile",
3619
+ "-NonInteractive",
3620
+ "-ExecutionPolicy",
3621
+ "Bypass",
3622
+ "-Command",
3623
+ script
3624
+ ], {
3625
+ encoding: "utf8",
3626
+ stdio: ["ignore", "pipe", "ignore"],
3627
+ timeout: 5000,
3628
+ windowsHide: true,
3629
+ maxBuffer: 512 * 1024
3630
+ });
3631
+ if (result.status !== 0 || !String(result.stdout || "").trim()) return [];
3632
+ const parsed = JSON.parse(result.stdout);
3633
+ return Array.isArray(parsed) ? parsed : [parsed];
3634
+ } catch {
3635
+ return [];
3636
+ }
3637
+ }
3638
+
3639
+ function windowsProcessIdAlive(processId) {
3640
+ const pid = Number(processId);
3641
+ if (!Number.isInteger(pid) || pid <= 0) return false;
3642
+ try {
3643
+ process.kill(pid, 0);
3644
+ return true;
3645
+ } catch {
3646
+ return false;
3647
+ }
3648
+ }
3649
+
3650
+ function claudeNativeSessionOwnerPid(sessionId = "", workspaceHint = "", options = {}) {
3651
+ const sessionsRoot = options.sessionsRoot || homePath(".claude", "sessions");
3652
+ const processAlive = options.processAlive || windowsProcessIdAlive;
3653
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
3654
+ const normalizedWorkspace = workspaceHint
3655
+ ? path.resolve(String(workspaceHint)).toLowerCase()
3656
+ : "";
3657
+ let entries;
3658
+ try {
3659
+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });
3660
+ } catch {
3661
+ return 0;
3662
+ }
3663
+
3664
+ const candidates = entries
3665
+ .filter((entry) => entry.isFile() && /^\d+\.json$/i.test(entry.name))
3666
+ .map((entry) => {
3667
+ const filePath = path.join(sessionsRoot, entry.name);
3668
+ const stat = safeStat(filePath);
3669
+ if (!stat) return null;
3670
+ const metadata = readJson(filePath);
3671
+ const pid = Number(metadata?.pid || path.basename(entry.name, ".json"));
3672
+ if (!Number.isInteger(pid) || pid <= 0 || !processAlive(pid)) return null;
3673
+ if (metadata?.kind && metadata.kind !== "interactive") return null;
3674
+ const sessionMatch = Boolean(sessionId && metadata?.sessionId === sessionId);
3675
+ if (!sessionMatch && now - stat.mtimeMs > 5 * 60 * 1000) return null;
3676
+ if (normalizedWorkspace && metadata?.cwd) {
3677
+ const candidateWorkspace = path.resolve(String(metadata.cwd)).toLowerCase();
3678
+ if (candidateWorkspace !== normalizedWorkspace) return null;
3679
+ }
3680
+ return {
3681
+ pid,
3682
+ sessionMatch,
3683
+ mtimeMs: stat.mtimeMs
3684
+ };
3685
+ })
3686
+ .filter(Boolean)
3687
+ .sort((left, right) => Number(right.sessionMatch) - Number(left.sessionMatch) || right.mtimeMs - left.mtimeMs);
3688
+
3689
+ if (sessionId) return candidates.find((candidate) => candidate.sessionMatch)?.pid || 0;
3690
+ return candidates[0]?.pid || 0;
3691
+ }
3692
+
3693
+ function windowsTuiDockHostPid(hwnd = 0) {
3694
+ const root = process.env.LOCALAPPDATA
3695
+ ? path.join(process.env.LOCALAPPDATA, "ai-battery")
3696
+ : path.join(os.tmpdir(), "ai-battery");
3697
+ const windowId = Math.trunc(Number(hwnd) || 0);
3698
+ const host = readJson(path.join(root, windowId > 0
3699
+ ? `tui-dock-host-${windowId}.json`
3700
+ : "tui-dock-host.json"));
3701
+ return windowsProcessIdAlive(host?.pid) ? Number(host.pid) : 0;
3702
+ }
3703
+
3704
+ function windowsForegroundTerminalInfo() {
3705
+ const nativeLauncher = rowptyExePath();
3706
+ if (!nativeLauncher) return { hwnd: 0, title: "" };
3707
+ try {
3708
+ const result = spawnSync(nativeLauncher, ["--foreground-terminal"], {
3709
+ encoding: "utf8",
3710
+ stdio: ["ignore", "pipe", "ignore"],
3711
+ timeout: 750,
3712
+ windowsHide: true
3713
+ });
3714
+ if (result.status !== 0) return { hwnd: 0, title: "" };
3715
+ const [rawHwnd = "0", rawTitle = ""] = String(result.stdout || "").trimEnd().split("\t", 2);
3716
+ const hwnd = Number.parseInt(rawHwnd, 10) || 0;
3717
+ let title = "";
3718
+ try { title = Buffer.from(rawTitle, "base64").toString("utf8"); } catch { /* Empty title. */ }
3719
+ return { hwnd, title };
3720
+ } catch {
3721
+ return { hwnd: 0, title: "" };
3722
+ }
3723
+ }
3724
+
3725
+ function windowsTerminalTitleMatchesProvider(title, provider, workspaceHint = "") {
3726
+ const normalizedTitle = String(title || "").trim().toLowerCase();
3727
+ if (!normalizedTitle) return false;
3728
+ if (provider && normalizedTitle.includes(String(provider).toLowerCase())) return true;
3729
+ const workspaceName = path.basename(path.resolve(workspaceHint || ".")).trim().toLowerCase();
3730
+ return workspaceName.length >= 2 && normalizedTitle.includes(workspaceName);
3731
+ }
3732
+
3733
+ function launchWindowsProviderDetached(commandArgs, startPid, provider, cwd = process.cwd(), knownOwnerPid = 0) {
3734
+ const ownerPlaceholder = "__AI_BATTERY_PROVIDER_OWNER_PID__";
3735
+ const dockWindowPlaceholder = "__AI_BATTERY_DOCK_WINDOW__";
3736
+ const commandLine = commandArgs.map(quoteWindowsCommandLineArg).join(" ");
3737
+ const commandBase64 = Buffer.from(commandLine, "utf8").toString("base64");
3738
+ const cwdBase64 = Buffer.from(cwd, "utf8").toString("base64");
3739
+ const debugPathBase64 = Buffer.from(process.env.AI_BATTERY_HUD_DEBUG_LOG || "", "utf8").toString("base64");
3740
+ const providerPattern = provider === "claude"
3741
+ ? "^(?:claude|claude-code)(?:\\.exe)?$"
3742
+ : "^codex(?:\\.exe)?$";
3743
+ const packagePattern = provider === "claude"
3744
+ ? "@anthropic-ai[\\\\/]claude-code"
3745
+ : "@openai[\\\\/]codex";
3746
+ const nativeLauncher = rowptyExePath();
3747
+ if (nativeLauncher && Number(knownOwnerPid) > 0) {
3748
+ const nativeCommandLine = commandLine.replace(ownerPlaceholder, String(Math.trunc(Number(knownOwnerPid))));
3749
+ const nativeResult = spawnSync(nativeLauncher, [
3750
+ "--launch-detached",
3751
+ Buffer.from(nativeCommandLine, "utf8").toString("base64"),
3752
+ cwdBase64,
3753
+ dockWindowPlaceholder
3754
+ ], {
3755
+ encoding: "utf8",
3756
+ stdio: "ignore",
3757
+ timeout: 1500,
3758
+ windowsHide: true
3759
+ });
3760
+ if (nativeResult.status === 0) {
3761
+ return {
3762
+ ok: true,
3763
+ ownerPid: Math.trunc(Number(knownOwnerPid)),
3764
+ launcherPid: 0,
3765
+ ownerPlaceholder,
3766
+ dockWindowPlaceholder
3767
+ };
3768
+ }
3769
+ }
3770
+
3771
+ const script = [
3772
+ `$debugPath = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${debugPathBase64}'))`,
3773
+ "function Write-LaunchDebug($message) { if ($debugPath) { try { Add-Content -LiteralPath $debugPath -Value ((Get-Date -Format o) + ' provider-launch ' + $message) } catch { } } }",
3774
+ "Write-LaunchDebug 'helper started'",
3775
+ "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class AiBatteryLaunchWindow { [DllImport(\"user32.dll\")] public static extern IntPtr GetForegroundWindow(); [DllImport(\"user32.dll\")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId); }'",
3776
+ "$launchForeground = [AiBatteryLaunchWindow]::GetForegroundWindow()",
3777
+ "$launchForegroundPid = [uint32]0",
3778
+ "if ($launchForeground -ne [IntPtr]::Zero) { [AiBatteryLaunchWindow]::GetWindowThreadProcessId($launchForeground, [ref]$launchForegroundPid) | Out-Null }",
3779
+ `$currentId = ${Math.trunc(Number(startPid) || 0)}`,
3780
+ `$ownerPid = ${Math.trunc(Number(knownOwnerPid) || 0)}`,
3781
+ "if ($ownerPid -le 0) {",
3782
+ " for ($depth = 0; $depth -lt 16 -and $currentId -gt 0; $depth++) {",
3783
+ " $item = Get-CimInstance Win32_Process -Filter (\"ProcessId = $currentId\") -ErrorAction SilentlyContinue",
3784
+ " if (-not $item) { break }",
3785
+ ` if ([string]$item.Name -match '${providerPattern}' -or [string]$item.CommandLine -match '${packagePattern}') { $ownerPid = [int]$item.ProcessId; break }`,
3786
+ " $currentId = [int]$item.ParentProcessId",
3787
+ " }",
3788
+ "}",
3789
+ "if ($ownerPid -le 0) { exit 2 }",
3790
+ "Write-LaunchDebug (\"owner=$ownerPid foreground=$([Int64]$launchForeground) foregroundPid=$launchForegroundPid\")",
3791
+ "$terminalPid = 0",
3792
+ "$terminalName = ''",
3793
+ "$currentId = $ownerPid",
3794
+ "for ($depth = 0; $depth -lt 16 -and $currentId -gt 0; $depth++) {",
3795
+ " $item = Get-CimInstance Win32_Process -Filter (\"ProcessId = $currentId\") -ErrorAction SilentlyContinue",
3796
+ " if (-not $item) { break }",
3797
+ " $itemName = [System.IO.Path]::GetFileNameWithoutExtension([string]$item.Name).ToLowerInvariant()",
3798
+ " if (@('windowsterminal','wezterm-gui','alacritty','code','hyper','tabby','conemu64','conemu') -contains $itemName) { $terminalPid = [int]$item.ProcessId; $terminalName = $itemName; break }",
3799
+ " $currentId = [int]$item.ParentProcessId",
3800
+ "}",
3801
+ "$dockWindow = 0",
3802
+ "if ($terminalPid -gt 0 -and $launchForegroundPid -eq $terminalPid) { $dockWindow = [Int64]$launchForeground }",
3803
+ "Write-LaunchDebug (\"terminalPid=$terminalPid terminalName=$terminalName dockWindow=$dockWindow\")",
3804
+ `$commandLine = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${commandBase64}')).Replace('${ownerPlaceholder}', [string]$ownerPid).Replace('${dockWindowPlaceholder}', [string]$dockWindow)`,
3805
+ `$workingDirectory = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${cwdBase64}'))`,
3806
+ "$startup = ([wmiclass]'Win32_ProcessStartup').CreateInstance()",
3807
+ "$startup.ShowWindow = 0",
3808
+ "Write-LaunchDebug (\"dispatching $commandLine\")",
3809
+ "$result = ([wmiclass]'Win32_Process').Create($commandLine, $workingDirectory, $startup)",
3810
+ "Write-LaunchDebug (\"wmiResult=$([int]$result.ReturnValue) processId=$([int]$result.ProcessId)\")",
3811
+ "if ([int]$result.ReturnValue -ne 0) { exit [int]$result.ReturnValue }",
3812
+ "$ownerPid"
3813
+ ].join("; ");
3814
+ const result = spawnSync("powershell.exe", [
3815
+ "-NoLogo",
3816
+ "-NoProfile",
3817
+ "-NonInteractive",
3818
+ "-ExecutionPolicy",
3819
+ "Bypass",
3820
+ "-Command",
3821
+ script
3822
+ ], {
3823
+ encoding: "utf8",
3824
+ stdio: ["ignore", "pipe", "ignore"],
3825
+ timeout: 5000,
3826
+ windowsHide: true
3827
+ });
3828
+ return {
3829
+ ok: result.status === 0,
3830
+ ownerPid: result.status === 0 ? Number.parseInt(String(result.stdout || "").trim(), 10) || 0 : 0,
3831
+ launcherPid: 0,
3832
+ ownerPlaceholder,
3833
+ dockWindowPlaceholder
3834
+ };
3835
+ }
3836
+
3837
+ function attachWindowsClaudeHud(sessionId, workspaceHint = "", terminalColumns = 0) {
3567
3838
  if (process.platform !== "win32" || !windowsHudEnabled()) return false;
3568
3839
  const hudPath = path.join(scriptDir(), "ai-battery-hud.js");
3569
3840
  if (!fs.existsSync(hudPath)) return false;
3570
3841
 
3571
3842
  const sessionKey = safeCacheName(sessionId || "unknown");
3572
3843
  const markerPath = path.join(stateDir(), "claude-hud-sessions", `${sessionKey}.json`);
3844
+ const normalizedColumns = Math.max(0, Math.trunc(Number(terminalColumns) || 0));
3845
+ let previousMarker = null;
3846
+ let migrationTargetHwnd = 0;
3573
3847
  try {
3574
3848
  const previous = readJson(markerPath);
3575
- const previousAt = Date.parse(previous?.attemptedAt || "");
3576
- if (Number.isFinite(previousAt) && Date.now() - previousAt < 5 * 60 * 1000) return false;
3577
- writeJsonAtomic(markerPath, { attemptedAt: new Date().toISOString() });
3849
+ previousMarker = previous;
3850
+ const attemptedAt = Date.parse(previous?.attemptedAt || "");
3851
+ const ownerResolutionPending = ["resolving-owner", "owner-not-found"].includes(previous?.stage);
3852
+ const launcherPending = ["launching-hud", "resolving-window", "launching-host"].includes(previous?.stage)
3853
+ && windowsProcessIdAlive(previous?.launcherPid);
3854
+ const pendingWindowMs = ownerResolutionPending ? 500 : (launcherPending ? 10 * 1000 : 1000);
3855
+ const attemptPending = Number.isFinite(attemptedAt) && Date.now() - attemptedAt < pendingWindowMs;
3856
+ const hostPid = windowsTuiDockHostPid(previous?.hwnd);
3857
+ const attachmentAlive = (
3858
+ hostPid > 0
3859
+ && Number(previous?.hostPid) === hostPid
3860
+ && Number(previous?.hwnd) > 0
3861
+ && windowsProcessIdAlive(previous?.ownerPid)
3862
+ );
3863
+ if (attachmentAlive) {
3864
+ const checkedAt = Date.parse(previous?.windowCheckedAt || "");
3865
+ const widthChanged = normalizedColumns > 0
3866
+ && Number(previous?.columns) > 0
3867
+ && normalizedColumns !== Number(previous.columns);
3868
+ const checkDue = widthChanged
3869
+ || !Number.isFinite(checkedAt)
3870
+ || Date.now() - checkedAt >= 5000;
3871
+ if (!checkDue) return false;
3872
+
3873
+ const foreground = windowsForegroundTerminalInfo();
3874
+ const movedToAnotherTerminal = foreground.hwnd > 0
3875
+ && foreground.hwnd !== Number(previous.hwnd)
3876
+ && windowsTerminalTitleMatchesProvider(foreground.title, "claude", workspaceHint);
3877
+ if (!movedToAnotherTerminal) {
3878
+ writeJsonAtomic(markerPath, {
3879
+ ...previous,
3880
+ ...(normalizedColumns ? { columns: normalizedColumns } : {}),
3881
+ windowCheckedAt: new Date().toISOString()
3882
+ });
3883
+ return false;
3884
+ }
3885
+ migrationTargetHwnd = foreground.hwnd;
3886
+ }
3887
+ if (attemptPending) return false;
3578
3888
  } catch {
3579
3889
  // HUD attachment is best-effort and must never break Claude's statusLine.
3580
3890
  }
@@ -3587,26 +3897,80 @@ function attachWindowsClaudeHud(sessionId) {
3587
3897
  crypto.createHash("sha1").update(String(sessionId || process.ppid)).digest("hex").slice(0, 12),
3588
3898
  16
3589
3899
  );
3900
+ const nativeOwnerPid = claudeNativeSessionOwnerPid(sessionId, workspaceHint);
3590
3901
  try {
3591
- const child = spawn(process.execPath, [
3902
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
3903
+ const currentMarker = readJson(markerPath);
3904
+ const currentHostPid = windowsTuiDockHostPid(currentMarker?.hwnd);
3905
+ const currentAttachmentAlive = currentHostPid > 0
3906
+ && Number(currentMarker?.hostPid) === currentHostPid
3907
+ && Number(currentMarker?.hwnd) > 0
3908
+ && windowsProcessIdAlive(currentMarker?.ownerPid);
3909
+ if (currentAttachmentAlive && (
3910
+ !migrationTargetHwnd || Number(currentMarker.hwnd) === migrationTargetHwnd
3911
+ )) return false;
3912
+ if (currentAttachmentAlive) previousMarker = currentMarker;
3913
+ writeJsonAtomic(markerPath, {
3914
+ ...(previousMarker?.hwnd ? { previousHwnd: Number(previousMarker.hwnd) } : {}),
3915
+ ...(previousMarker?.hostPid ? { previousHostPid: Number(previousMarker.hostPid) } : {}),
3916
+ ...(normalizedColumns ? { columns: normalizedColumns } : {}),
3917
+ windowCheckedAt: new Date().toISOString(),
3918
+ attemptedAt: new Date().toISOString(),
3919
+ ownerPid: nativeOwnerPid,
3920
+ stage: nativeOwnerPid ? "launching-hud" : "resolving-owner",
3921
+ parentPid: process.ppid
3922
+ });
3923
+ const ownerPlaceholder = "__AI_BATTERY_PROVIDER_OWNER_PID__";
3924
+ const dockWindowPlaceholder = "__AI_BATTERY_DOCK_WINDOW__";
3925
+ const hudArgs = [process.execPath,
3592
3926
  hudPath,
3593
3927
  "--dock-console",
3928
+ "--dock-window",
3929
+ dockWindowPlaceholder,
3594
3930
  "--dock-position",
3595
3931
  placement,
3596
3932
  "--dock-session",
3597
- String(sessionNumber)
3598
- ], {
3599
- stdio: "ignore",
3600
- cwd: process.cwd(),
3601
- env: {
3602
- ...process.env,
3603
- AI_BATTERY_HUD_NO_PREFETCH: "1"
3604
- },
3605
- windowsHide: false
3606
- });
3607
- child.on("error", () => {});
3608
- child.unref();
3609
- return true;
3933
+ String(sessionNumber),
3934
+ "--dock-owner-pid",
3935
+ ownerPlaceholder,
3936
+ "--dock-provider",
3937
+ "claude",
3938
+ "--dock-marker",
3939
+ markerPath
3940
+ ];
3941
+ if (workspaceHint) hudArgs.push("--dock-title-hint", workspaceHint);
3942
+ const launched = launchWindowsProviderDetached(
3943
+ hudArgs,
3944
+ process.ppid,
3945
+ "claude",
3946
+ process.cwd(),
3947
+ nativeOwnerPid
3948
+ );
3949
+ if (launched.ok) {
3950
+ const current = readJson(markerPath);
3951
+ if (!current?.attachedAt) {
3952
+ writeJsonAtomic(markerPath, {
3953
+ ...current,
3954
+ attemptedAt: new Date().toISOString(),
3955
+ ownerPid: launched.ownerPid || nativeOwnerPid,
3956
+ launcherPid: launched.launcherPid,
3957
+ stage: "launching-hud",
3958
+ parentPid: process.ppid
3959
+ });
3960
+ }
3961
+ }
3962
+ if (!launched.ok) {
3963
+ const current = readJson(markerPath);
3964
+ if (!current?.attachedAt) {
3965
+ writeJsonAtomic(markerPath, {
3966
+ attemptedAt: new Date().toISOString(),
3967
+ ownerPid: launched.ownerPid,
3968
+ stage: launched.ownerPid ? "launch-failed" : "owner-not-found",
3969
+ parentPid: process.ppid
3970
+ });
3971
+ }
3972
+ }
3973
+ return launched.ok;
3610
3974
  } catch {
3611
3975
  return false;
3612
3976
  }
@@ -4785,8 +5149,21 @@ async function main() {
4785
5149
  if (!inputText.trim()) throw new Error("capture-claude expected Claude statusline JSON on stdin");
4786
5150
  const input = JSON.parse(inputText);
4787
5151
  const capturedClaude = captureClaudeStatusline(input);
4788
- if (args.attachHud) attachWindowsClaudeHud(capturedClaude.sessionId);
5152
+ if (args.attachHud) {
5153
+ attachWindowsClaudeHud(
5154
+ capturedClaude.sessionId,
5155
+ capturedClaude.workspace?.currentDir || capturedClaude.workspace?.projectDir || process.cwd(),
5156
+ statusLineColumns(input)
5157
+ );
5158
+ }
4789
5159
  if (!args.silent) {
5160
+ const contentWidth = Math.max(20, statusLineUsableColumns(input) - (Number(args.leftPadding) || 0));
5161
+ const header = args.header ? claudeHeader(input, args, capturedClaude) : "";
5162
+ const usageRowVisible = claudeUsageRowVisible(args);
5163
+ if (!usageRowVisible && header) {
5164
+ console.log(applyLeftPadding(header, args));
5165
+ return;
5166
+ }
4790
5167
  const results = [];
4791
5168
  if ((args.provider === "all" || args.provider === "codex") && providerVisible("codex")) {
4792
5169
  const codexData = readCodexForClaudeCapture();
@@ -4799,15 +5176,13 @@ async function main() {
4799
5176
  const claudeData = claudeStatuslineResultFromCache(capturedClaude, capturedSource, { includeBackground: true }) ?? readClaude();
4800
5177
  results.push({ ...claudeData, running: true });
4801
5178
  }
4802
- const contentWidth = Math.max(20, statusLineUsableColumns(input) - (Number(args.leftPadding) || 0));
4803
- const header = args.header ? claudeHeader(input, args, capturedClaude) : "";
4804
5179
  const usage = render({
4805
5180
  generatedAt: new Date().toISOString(),
4806
5181
  results
4807
5182
  }, { ...args, activeProvider: "claude", leftPadding: 0, maxWidth: contentWidth });
4808
5183
  // Inside tmux with the status-bar integration, the battery already shows
4809
5184
  // in tmux's own bar; keep the statusline to the one line tmux can't show.
4810
- const text = !claudeUsageRowVisible(args)
5185
+ const text = !usageRowVisible
4811
5186
  ? (header || usage)
4812
5187
  : (header && usage ? `${header}\n${usage}` : (usage || header));
4813
5188
  console.log(applyLeftPadding(text, args));
@@ -4852,6 +5227,7 @@ async function main() {
4852
5227
  export {
4853
5228
  bar,
4854
5229
  claudeHeader,
5230
+ claudeNativeSessionOwnerPid,
4855
5231
  claudeStateDir,
4856
5232
  commandMatchesProvider,
4857
5233
  codexBackgroundReadyInProcesses,
@@ -4891,6 +5267,7 @@ export {
4891
5267
  uninstallRowPtyHost,
4892
5268
  uninstallTmuxStatus,
4893
5269
  windowsOwnedShimDirsForUninstall,
5270
+ windowsProviderOwnerPidFromAncestors,
4894
5271
  windowsSetupNeedsRowPty,
4895
5272
  windowsUserPathWithShim,
4896
5273
  windowsCscPath