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.
Files changed (45) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-status.applescript +5 -12
  3. package/bin/ai-battery-run +701 -31
  4. package/bin/ai-battery-tmux.js +17 -0
  5. package/bin/terminal-compositor.js +111 -0
  6. package/docs/REFERENCE.md +23 -3
  7. package/docs/RELEASING.md +24 -7
  8. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  9. package/docs/hud-preview.svg +43 -20
  10. package/docs/terminal-vertical-preview.svg +73 -0
  11. package/lib/cli.js +945 -219
  12. package/lib/core/atomic-rename.js +18 -0
  13. package/lib/core/cli-help.js +35 -7
  14. package/lib/core/cli-messages.js +45 -1
  15. package/lib/core/cli-output.js +277 -72
  16. package/lib/core/cli-wrappers.js +410 -0
  17. package/lib/core/config-editor.js +177 -29
  18. package/lib/core/display-config.js +45 -0
  19. package/lib/core/integration-files.js +32 -3
  20. package/lib/core/shared-bar.js +603 -0
  21. package/lib/core/statusline-git.js +179 -15
  22. package/lib/core/terminal.js +25 -7
  23. package/lib/core/tmux-status.js +172 -0
  24. package/lib/core/uninstall.js +20 -7
  25. package/lib/core/usage-store.js +85 -0
  26. package/lib/hud/launcher.js +29 -31
  27. package/lib/platforms/linux/hud.js +1 -1
  28. package/lib/platforms/linux/panel.js +1 -1
  29. package/lib/platforms/macos/hud.js +5 -5
  30. package/lib/platforms/process-scanner.js +77 -29
  31. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  32. package/lib/platforms/windows/codex-runner.js +178 -21
  33. package/lib/platforms/windows/hud/controls.ps1 +44 -10
  34. package/lib/platforms/windows/hud/main.ps1 +350 -43
  35. package/lib/platforms/windows/hud/rendering.ps1 +1227 -1
  36. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  37. package/lib/platforms/windows/hud-launcher.js +153 -79
  38. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  39. package/lib/platforms/windows/terminal-compositor.js +210 -25
  40. package/lib/platforms/windows/wt-bar.js +729 -0
  41. package/lib/platforms/windows/wt-fragment.js +665 -0
  42. package/lib/platforms/windows/wt-keybinding.js +300 -0
  43. package/lib/providers/antigravity.js +155 -8
  44. package/package.json +5 -2
  45. package/vendor/PaneContext.cs +875 -0
@@ -0,0 +1,410 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ export const CLI_WRAPPER_MARKER = "AI_BATTERY_MANAGED_CLI_WRAPPER";
7
+ export const WRAPPED_CLI_NAMES = ["claude", "agy"];
8
+ const positionReader = fileURLToPath(new URL("../../bin/terminal-compositor.js", import.meta.url));
9
+
10
+ function shQuote(value) {
11
+ return `'${String(value).replace(/'/g, "'\\''")}'`;
12
+ }
13
+
14
+ export function isManagedCliWrapper(filePath) {
15
+ let fd;
16
+ try {
17
+ fd = fs.openSync(filePath, "r");
18
+ const buf = Buffer.alloc(512);
19
+ const len = fs.readSync(fd, buf, 0, buf.length, 0);
20
+ return buf.toString("utf8", 0, len).includes(CLI_WRAPPER_MARKER);
21
+ } catch {
22
+ return false;
23
+ } finally {
24
+ if (fd !== undefined) fs.closeSync(fd);
25
+ }
26
+ }
27
+
28
+ export function posixCliWrapperDir(homeDir = os.homedir()) {
29
+ return path.join(homeDir, ".local", "share", "ai-battery", "bin");
30
+ }
31
+
32
+ export function windowsCliWrapperDir(homeDir = os.homedir(), env = process.env) {
33
+ if (env.AI_BATTERY_DATA_DIR) return path.join(env.AI_BATTERY_DATA_DIR, "bin");
34
+ if (env.CLAUDEX_BATTERY_DATA_DIR) return path.join(env.CLAUDEX_BATTERY_DATA_DIR, "bin");
35
+ if (env.LOCALAPPDATA) return path.join(env.LOCALAPPDATA, "ai-battery", "bin");
36
+ return path.join(homeDir, ".local", "bin");
37
+ }
38
+
39
+ function buildPosixCliWrapperScript(commandName, runnerPath) {
40
+ return `#!/bin/sh
41
+ # ${CLI_WRAPPER_MARKER}=1
42
+ ai_battery_cmd_name=${shQuote(commandName)}
43
+ ai_battery_configured_runner=${shQuote(runnerPath)}
44
+ ai_battery_position_reader=${shQuote(positionReader)}
45
+ ai_battery_head=$(command -v head) || ai_battery_head=/usr/bin/head
46
+
47
+ ai_battery_is_cli_wrapper() {
48
+ ai_battery_hdr=$("$ai_battery_head" -c 256 "$1" 2>/dev/null) || return 1
49
+ case "$ai_battery_hdr" in
50
+ *${CLI_WRAPPER_MARKER}*) return 0 ;;
51
+ esac
52
+ return 1
53
+ }
54
+
55
+ ai_battery_find_real() {
56
+ ai_battery_rem=$PATH
57
+ while :; do
58
+ case "$ai_battery_rem" in
59
+ *:*)
60
+ ai_battery_dir=\${ai_battery_rem%%:*}
61
+ ai_battery_rem=\${ai_battery_rem#*:}
62
+ ai_battery_more=1 ;;
63
+ *) ai_battery_dir=$ai_battery_rem; ai_battery_more=0 ;;
64
+ esac
65
+ ai_battery_cand=\${ai_battery_dir:-.}/$1
66
+ if [ -f "$ai_battery_cand" ] && [ -x "$ai_battery_cand" ]; then
67
+ if ! ai_battery_is_cli_wrapper "$ai_battery_cand"; then
68
+ printf '%s\\n' "$ai_battery_cand"
69
+ return 0
70
+ fi
71
+ fi
72
+ [ "$ai_battery_more" = 1 ] || break
73
+ done
74
+ return 1
75
+ }
76
+
77
+ ai_battery_read_pos() {
78
+ ai_battery_node=$(command -v node 2>/dev/null) || ai_battery_node=
79
+ if [ -n "$ai_battery_node" ] && [ -f "$ai_battery_position_reader" ]; then
80
+ ai_battery_node_pos=$("$ai_battery_node" "$ai_battery_position_reader" --bar-position 2>/dev/null) || ai_battery_node_pos=
81
+ if [ -n "$ai_battery_node_pos" ]; then
82
+ printf '%s\\n' "$ai_battery_node_pos"
83
+ return 0
84
+ fi
85
+ fi
86
+ if [ -n "\${AI_BATTERY_BAR_POSITION:-}" ]; then
87
+ printf '%s\\n' "$AI_BATTERY_BAR_POSITION"
88
+ return 0
89
+ fi
90
+ ai_battery_win_dir=
91
+ if [ -f "$HOME/.local/state/ai-battery/windows-state-dir" ]; then
92
+ ai_battery_win_dir=$(cat "$HOME/.local/state/ai-battery/windows-state-dir" 2>/dev/null | tr -d '\\r\\n')
93
+ fi
94
+ for ai_battery_cfg in \\
95
+ "\${AI_BATTERY_SHARED_USAGE_STATE_DIR:+$AI_BATTERY_SHARED_USAGE_STATE_DIR/display-config.json}" \\
96
+ "\${AI_BATTERY_WINDOWS_STATE_DIR:+$AI_BATTERY_WINDOWS_STATE_DIR/display-config.json}" \\
97
+ "\${AI_BATTERY_STATE_DIR:+$AI_BATTERY_STATE_DIR/display-config.json}" \\
98
+ "\${CLAUDEX_BATTERY_STATE_DIR:+$CLAUDEX_BATTERY_STATE_DIR/display-config.json}" \\
99
+ "\${XDG_STATE_HOME:+$XDG_STATE_HOME/ai-battery/display-config.json}" \\
100
+ "\${ai_battery_win_dir:+$ai_battery_win_dir/display-config.json}" \\
101
+ "$HOME/.local/state/ai-battery/display-config.json"; do
102
+ if [ -n "$ai_battery_cfg" ] && [ -f "$ai_battery_cfg" ]; then
103
+ ai_battery_found=$(sed -n 's/.*"barPosition"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p' "$ai_battery_cfg" 2>/dev/null | "$ai_battery_head" -n 1)
104
+ if [ -n "$ai_battery_found" ]; then
105
+ printf '%s\\n' "$ai_battery_found"
106
+ return 0
107
+ fi
108
+ fi
109
+ done
110
+ printf 'bottom\\n'
111
+ }
112
+
113
+ ai_battery_real=$(ai_battery_find_real "$ai_battery_cmd_name") || ai_battery_real=
114
+ if [ -z "$ai_battery_real" ]; then
115
+ printf '%s: command not found on PATH\\n' "$ai_battery_cmd_name" >&2
116
+ exit 127
117
+ fi
118
+
119
+ ai_battery_pos=$(ai_battery_read_pos | tr '[:upper:]' '[:lower:]')
120
+ ai_battery_runner=$ai_battery_configured_runner
121
+ if [ ! -x "$ai_battery_runner" ]; then
122
+ ai_battery_runner=$(command -v ai-battery-run 2>/dev/null) || ai_battery_runner=
123
+ fi
124
+ ai_battery_python=$(command -v python3 2>/dev/null) || ai_battery_python=
125
+
126
+ ai_battery_noninteractive=0
127
+ for ai_battery_arg in "$@"; do
128
+ case "$ai_battery_arg" in
129
+ -h|--help|-v|-V|--version|-p|--print) ai_battery_noninteractive=1; break ;;
130
+ esac
131
+ done
132
+
133
+ case "$ai_battery_pos" in
134
+ top|up|t|left|l|right|r)
135
+ if [ "$ai_battery_noninteractive" = 0 ] && [ -t 0 ] && [ -t 1 ] && [ "\${AI_BATTERY_WRAPPED_CLI:-}" != 1 ] && [ -x "$ai_battery_runner" ] && [ -n "$ai_battery_python" ]; then
136
+ ai_battery_node_bin=$(command -v node 2>/dev/null) || ai_battery_node_bin=
137
+ if [ -n "$ai_battery_node_bin" ] && [ -z "\${AI_BATTERY_NODE:-}" ]; then
138
+ export AI_BATTERY_NODE="$ai_battery_node_bin"
139
+ fi
140
+ export AI_BATTERY_WRAPPED_CLI=1
141
+ exec "$ai_battery_runner" --provider all -- "$ai_battery_real" "$@"
142
+ fi
143
+ ;;
144
+ esac
145
+
146
+ exec "$ai_battery_real" "$@"
147
+ `;
148
+ }
149
+
150
+ function buildWindowsCliCmd(nodePath) {
151
+ return [
152
+ "@echo off",
153
+ `rem ${CLI_WRAPPER_MARKER}=1`,
154
+ "setlocal EnableExtensions DisableDelayedExpansion",
155
+ `set "_ai_battery_node=${nodePath}"`,
156
+ 'if not exist "%_ai_battery_node%" set "_ai_battery_node=node"',
157
+ '"%_ai_battery_node%" "%~f0.ai-battery.cjs" %*',
158
+ "exit /b %ERRORLEVEL%"
159
+ ].join("\r\n") + "\r\n";
160
+ }
161
+
162
+ function buildWindowsCliBridge(commandName, runnerPath) {
163
+ return `// ${CLI_WRAPPER_MARKER}=1
164
+ const fs = require("node:fs");
165
+ const os = require("node:os");
166
+ const path = require("node:path");
167
+ const { spawn } = require("node:child_process");
168
+ const { spawnSync } = require("node:child_process");
169
+
170
+ const CMD_NAME = ${JSON.stringify(commandName)};
171
+ const RUNNER = ${JSON.stringify(runnerPath)};
172
+ const POSITION_READER = ${JSON.stringify(positionReader)};
173
+ const MARKER = ${JSON.stringify(CLI_WRAPPER_MARKER)};
174
+
175
+ function windowsCommandNames(command, env = process.env) {
176
+ const extensions = (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
177
+ return [...extensions.map((ext) => command + ext.toLowerCase()), command];
178
+ }
179
+
180
+ function isManaged(file) {
181
+ let fd;
182
+ try {
183
+ fd = fs.openSync(file, "r");
184
+ const header = Buffer.alloc(512);
185
+ const count = fs.readSync(fd, header, 0, header.length, 0);
186
+ return header.toString("utf8", 0, count).includes(MARKER);
187
+ } catch {
188
+ return false;
189
+ } finally {
190
+ if (fd !== undefined) fs.closeSync(fd);
191
+ }
192
+ }
193
+
194
+ function findRealCommand(command, env = process.env) {
195
+ for (const entry of (env.PATH || "").split(path.delimiter)) {
196
+ const dir = entry.replace(/^"(.*)"$/, "$1");
197
+ if (!dir) continue;
198
+ for (const name of windowsCommandNames(command, env)) {
199
+ const candidate = path.resolve(dir, name);
200
+ try {
201
+ if (!fs.statSync(candidate).isFile()) continue;
202
+ if (isManaged(candidate)) continue;
203
+ return candidate;
204
+ } catch {}
205
+ }
206
+ }
207
+ return null;
208
+ }
209
+
210
+ function readBarPosition(env = process.env) {
211
+ if (fs.existsSync(POSITION_READER)) {
212
+ const result = spawnSync(process.execPath, [POSITION_READER, "--bar-position"], {
213
+ env, encoding: "utf8", windowsHide: true, timeout: 5000
214
+ });
215
+ if (result.status === 0 && result.stdout.trim()) return result.stdout.trim();
216
+ }
217
+ const override = String(env.AI_BATTERY_BAR_POSITION || "").trim().toLowerCase();
218
+ if (override) return override;
219
+ const dirs = [
220
+ env.AI_BATTERY_SHARED_USAGE_STATE_DIR,
221
+ env.AI_BATTERY_STATE_DIR,
222
+ env.CLAUDEX_BATTERY_STATE_DIR,
223
+ env.XDG_STATE_HOME ? path.join(env.XDG_STATE_HOME, "ai-battery") : "",
224
+ path.join(os.homedir(), ".local", "state", "ai-battery")
225
+ ].filter(Boolean);
226
+ for (const dir of dirs) {
227
+ try {
228
+ const text = fs.readFileSync(path.join(dir, "display-config.json"), "utf8").replace(/^\\uFEFF/, "");
229
+ const parsed = JSON.parse(text);
230
+ const pos = String(parsed?.barPosition || "").trim().toLowerCase();
231
+ if (pos) return pos;
232
+ } catch {}
233
+ }
234
+ return "bottom";
235
+ }
236
+
237
+ function resolveNpmCmdShim(commandPath) {
238
+ if (!/\\.cmd$/i.test(commandPath)) return null;
239
+ let source;
240
+ try { source = fs.readFileSync(commandPath, "utf8"); } catch { return null; }
241
+ if (!source.includes("%dp0%") || !source.includes("%*")) return null;
242
+ const match = source.match(/%dp0%[\\\\/]([^"\\r\\n]+?\\.(?:cjs|mjs|js))"?\\s+%\\*/i);
243
+ if (!match) return null;
244
+ const scriptPath = path.resolve(path.dirname(commandPath), match[1].replace(/[\\\\/]+/g, path.sep));
245
+ if (!fs.existsSync(scriptPath)) return null;
246
+ const localNode = path.join(path.dirname(commandPath), "node.exe");
247
+ return { file: fs.existsSync(localNode) ? localNode : process.execPath, scriptPath };
248
+ }
249
+
250
+ const UNSAFE_CMD_ARGUMENT_RE = /[\\r\\n&|<>^%!()]/;
251
+ const UNSAFE_CMD_PATH_RE = /[\\r\\n&|<>^%!]/;
252
+
253
+ function directLaunch(exe, rest) {
254
+ if (/\\.(cmd|bat)$/i.test(exe)) {
255
+ const shim = resolveNpmCmdShim(exe);
256
+ if (shim) return { file: shim.file, args: [shim.scriptPath, ...rest] };
257
+ if (UNSAFE_CMD_PATH_RE.test(String(exe)) || rest.some((arg) => UNSAFE_CMD_ARGUMENT_RE.test(String(arg)))) {
258
+ throw new Error("Cannot safely pass shell metacharacters through batch command " + exe);
259
+ }
260
+ return { file: "cmd.exe", args: ["/d", "/s", "/c", "call", exe, ...rest] };
261
+ }
262
+ if (/\\.ps1$/i.test(exe)) {
263
+ return { file: "powershell.exe", args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", exe, ...rest] };
264
+ }
265
+ if (/\\.(js|mjs|cjs)$/i.test(exe)) {
266
+ return { file: process.execPath, args: [exe, ...rest] };
267
+ }
268
+ return { file: exe, args: rest };
269
+ }
270
+
271
+ const real = findRealCommand(CMD_NAME);
272
+ if (!real) {
273
+ console.error(CMD_NAME + ": command not found on PATH");
274
+ process.exit(127);
275
+ }
276
+
277
+ const pos = readBarPosition();
278
+ const wantsSideOrTop = ["top", "up", "t", "left", "l", "right", "r"].includes(pos);
279
+ const cliArgs = process.argv.slice(2);
280
+ const nonInteractive = cliArgs.some((arg) => ["-h", "--help", "-v", "-V", "--version", "-p", "--print"].includes(arg));
281
+ const env = { ...process.env };
282
+ let launch;
283
+ if (wantsSideOrTop && !nonInteractive && process.stdin.isTTY && process.stdout.isTTY && env.AI_BATTERY_WRAPPED_CLI !== "1" && fs.existsSync(RUNNER)) {
284
+ env.AI_BATTERY_WRAPPED_CLI = "1";
285
+ launch = { file: process.execPath, args: [RUNNER, "--provider", "all", "--left-padding", "2", "--", real, ...cliArgs] };
286
+ } else {
287
+ launch = directLaunch(real, cliArgs);
288
+ }
289
+
290
+ const child = spawn(launch.file, launch.args, { stdio: "inherit", env });
291
+ child.on("error", (error) => {
292
+ console.error(CMD_NAME + ": " + error.message);
293
+ process.exit(1);
294
+ });
295
+ child.on("exit", (code, signal) => {
296
+ if (signal) process.kill(process.pid, signal);
297
+ process.exit(code ?? 0);
298
+ });
299
+ `;
300
+ }
301
+
302
+ function writeManagedFile(filePath, content, executable = false) {
303
+ if (fs.existsSync(filePath) && !isManagedCliWrapper(filePath)) {
304
+ return { skipped: true, path: filePath };
305
+ }
306
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
307
+ const tmp = `${filePath}.${process.pid}.tmp`;
308
+ fs.writeFileSync(tmp, content, "utf8");
309
+ if (executable && process.platform !== "win32") {
310
+ fs.chmodSync(tmp, 0o755);
311
+ }
312
+ fs.renameSync(tmp, filePath);
313
+ return { installed: true, path: filePath };
314
+ }
315
+
316
+ export function installCliPositionWrappers({
317
+ names = WRAPPED_CLI_NAMES,
318
+ runnerPath,
319
+ homeDir = os.homedir(),
320
+ platform = process.platform,
321
+ nodePath = process.execPath,
322
+ windowsDir = null,
323
+ env = process.env
324
+ } = {}) {
325
+ if (!runnerPath) return { installed: [], skipped: [] };
326
+ const installed = [];
327
+ const skipped = [];
328
+
329
+ if (platform === "win32") {
330
+ const dir = windowsDir || windowsCliWrapperDir(homeDir, env);
331
+ const legacyDir = path.join(homeDir, ".local", "bin");
332
+ const sameAsLegacy = path.resolve(dir).toLowerCase() === path.resolve(legacyDir).toLowerCase();
333
+ for (const name of names) {
334
+ const cmdPath = path.join(dir, `${name}.cmd`);
335
+ const bridgePath = `${cmdPath}.ai-battery.cjs`;
336
+ const cmdRes = writeManagedFile(cmdPath, buildWindowsCliCmd(nodePath), false);
337
+ if (cmdRes.skipped) {
338
+ skipped.push(cmdPath);
339
+ continue;
340
+ }
341
+ writeManagedFile(bridgePath, buildWindowsCliBridge(name, runnerPath), false);
342
+ installed.push(cmdPath);
343
+ // Clean up legacy managed wrappers in ~/.local/bin after migrating to dedicated bin dir
344
+ // so old shims cannot shadow or conflict with native ~/.local/bin/claude.exe.
345
+ if (!sameAsLegacy) {
346
+ for (const oldFile of [path.join(legacyDir, `${name}.cmd`), path.join(legacyDir, `${name}.cmd.ai-battery.cjs`)]) {
347
+ if (fs.existsSync(oldFile) && isManagedCliWrapper(oldFile)) {
348
+ try { fs.unlinkSync(oldFile); } catch {}
349
+ }
350
+ }
351
+ }
352
+ }
353
+ return { dir, installed, skipped };
354
+ }
355
+
356
+ const dedicatedDir = posixCliWrapperDir(homeDir);
357
+ const localBinDir = path.join(homeDir, ".local", "bin");
358
+ for (const name of names) {
359
+ const content = buildPosixCliWrapperScript(name, runnerPath);
360
+ const primary = writeManagedFile(path.join(dedicatedDir, name), content, true);
361
+ if (primary.installed) installed.push(primary.path);
362
+ else skipped.push(primary.path);
363
+ // Also place in ~/.local/bin if unoccupied (e.g. claude) so already-open shells pick it up immediately.
364
+ const secondaryPath = path.join(localBinDir, name);
365
+ if (!fs.existsSync(secondaryPath) || isManagedCliWrapper(secondaryPath)) {
366
+ const secondary = writeManagedFile(secondaryPath, content, true);
367
+ if (secondary.installed) installed.push(secondary.path);
368
+ }
369
+ }
370
+ return { dir: dedicatedDir, installed, skipped };
371
+ }
372
+
373
+ export function uninstallCliPositionWrappers({
374
+ names = WRAPPED_CLI_NAMES,
375
+ homeDir = os.homedir(),
376
+ platform = process.platform,
377
+ windowsDir = null,
378
+ env = process.env
379
+ } = {}) {
380
+ const removed = [];
381
+ const removeIfManaged = (filePath) => {
382
+ if (fs.existsSync(filePath) && isManagedCliWrapper(filePath)) {
383
+ try {
384
+ fs.unlinkSync(filePath);
385
+ removed.push(filePath);
386
+ } catch {}
387
+ }
388
+ };
389
+ if (platform === "win32") {
390
+ const dirs = [...new Set([
391
+ windowsDir,
392
+ windowsCliWrapperDir(homeDir, env),
393
+ path.join(homeDir, ".local", "bin")
394
+ ].filter(Boolean).map(d => path.resolve(d)))];
395
+ for (const dir of dirs) {
396
+ for (const name of names) {
397
+ const cmdPath = path.join(dir, `${name}.cmd`);
398
+ removeIfManaged(cmdPath);
399
+ removeIfManaged(`${cmdPath}.ai-battery.cjs`);
400
+ }
401
+ }
402
+ return { removed };
403
+ }
404
+ for (const dir of [posixCliWrapperDir(homeDir), path.join(homeDir, ".local", "bin")]) {
405
+ for (const name of names) {
406
+ removeIfManaged(path.join(dir, name));
407
+ }
408
+ }
409
+ return { removed };
410
+ }
@@ -1,5 +1,6 @@
1
1
  import { clearScreenDown, cursorTo, emitKeypressEvents, moveCursor } from "node:readline";
2
- import { PROVIDERS, normalizeOrder, providerLabel } from "./display-config.js";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { BAR_POSITIONS, DEFAULT_SIDEBAR_WIDTH, MAX_SIDEBAR_WIDTH, MIN_SIDEBAR_WIDTH, PROVIDERS, normalizeBarPosition, normalizeOrder, normalizeSidebarWidth, providerLabel } from "./display-config.js";
3
4
  import { cliLanguage } from "./cli-help.js";
4
5
  import { truncateMiddleVisible, visibleWidth } from "./terminal.js";
5
6
 
@@ -9,9 +10,23 @@ export function canEditConfig(input = process.stdin, output = process.stdout) {
9
10
 
10
11
  export function editDisplayConfig(initialConfig, { input = process.stdin, output = process.stdout, language = cliLanguage(), color = !Object.hasOwn(process.env, "NO_COLOR") } = {}) {
11
12
  const order = normalizeOrder(initialConfig.providerOrder, PROVIDERS);
13
+ const initialOrder = [...order];
12
14
  const providers = Object.fromEntries(PROVIDERS.map(provider => [provider, initialConfig.providers?.[provider] !== false]));
13
15
  const changedProviders = new Set();
16
+ const initialBarPosition = normalizeBarPosition(initialConfig.barPosition, "bottom");
17
+ let barPosition = initialBarPosition;
18
+ const initialSidebarWidth = normalizeSidebarWidth(initialConfig.sidebarWidth, DEFAULT_SIDEBAR_WIDTH);
19
+ let sidebarWidth = initialSidebarWidth;
20
+ let positionSelected = Math.max(0, BAR_POSITIONS.indexOf(barPosition));
21
+ let activeTab = "providers";
22
+ let positionTabVisited = false;
14
23
  const t = (english, korean) => language === "ko" ? korean : english;
24
+ const positionLabel = pos => ({
25
+ bottom: t("Bottom", "하단 (bottom)"),
26
+ top: t("Top", "상단 (top)"),
27
+ left: t("Left", "좌측 (left)"),
28
+ right: t("Right", "우측 (right)")
29
+ })[pos] || pos;
15
30
  const wasRaw = Boolean(input.isRaw);
16
31
  const wasFlowing = input.readableFlowing;
17
32
  let selected = 0;
@@ -37,35 +52,143 @@ export function editDisplayConfig(initialConfig, { input = process.stdin, output
37
52
  const width = Math.min(64, availableWidth);
38
53
  const height = Number(output.rows) || 24;
39
54
  const fit = text => truncateMiddleVisible(text, width);
40
- const arrows = t("↑↓ select · ←→ move", "↑↓ 선택 · ←→ 순서 이동");
41
- const toggle = t("Space show/hide", "Space 표시/숨김");
42
- const confirm = t("Enter save · Esc cancel", "Enter 저장 · Esc 취소");
43
- const fullHelp = `${arrows} · ${toggle} · ${confirm}`;
44
- const compactHelp = t("↑↓ select · ←→ move · Space toggle · Enter save · Esc cancel", "↑↓ 선택 · ←→ 순서 · Space 표시 · Enter 저장 · Esc 취소");
45
- const help = [fullHelp, compactHelp, "↑↓ · ←→ · Space · Enter · Esc"].find(text => visibleWidth(text) <= availableWidth)
46
- || truncateMiddleVisible("↑↓ ←→ Space Enter Esc", availableWidth);
47
- const items = order.map((provider, index) => {
48
- const text = `${index === selected ? "›" : " "} ${index + 1}. [${providers[provider] ? "x" : " "}] ${providerLabel(provider)}`;
49
- const inside = truncateMiddleVisible(text, Math.max(1, width - 4));
50
- const padded = inside + " ".repeat(Math.max(0, width - 4 - visibleWidth(inside)));
51
- const line = width >= 24 && height >= 10 ? `│ ${padded} │` : text;
52
- return index === selected && color ? `\x1b[36m${line}\x1b[0m` : line;
53
- });
55
+ const toolsTitle = t("Tools & display order", "표시 도구·순서");
56
+ const posTitle = t("Bar position", "상태바 위치");
57
+ const formatTabHeader = () => {
58
+ const activeFirst = activeTab === "providers";
59
+ const activeText = activeFirst ? toolsTitle : posTitle;
60
+ const inactiveText = activeFirst ? posTitle : toolsTitle;
61
+ const activeBadge = color ? `\x1b[1;7m ▸ ${activeText} \x1b[0m` : `▸ ${activeText}`;
62
+ const inactiveLabel = color ? `\x1b[2m${inactiveText}\x1b[0m` : inactiveText;
63
+ const sep = color ? "\x1b[2m │ \x1b[0m" : " │ ";
64
+ const tabbedTitle = activeFirst
65
+ ? ` ${activeBadge}${sep}${inactiveLabel} `
66
+ : ` ${inactiveLabel}${sep}${activeBadge} `;
67
+ if (visibleWidth(tabbedTitle) <= width - 3) return tabbedTitle;
68
+ const compactActive = truncateMiddleVisible(` ▸ ${activeText} `, width - 3);
69
+ return color ? `\x1b[1;7m${compactActive}\x1b[0m` : compactActive;
70
+ };
54
71
  let lines;
55
- const preview = order.filter(provider => providers[provider]).map(providerLabel).join(" → ") || t("All hidden", "모두 숨김");
56
- if (width >= 24 && height >= 10) {
57
- const title = truncateMiddleVisible(` ${t("Tools & display order", "표시 도구·순서")} `, width - 3);
58
- lines = [
59
- `╭─${title}${"─".repeat(Math.max(0, width - 3 - visibleWidth(title)))}╮`,
60
- ...items,
61
- `╰${"─".repeat(width - 2)}╯`,
62
- fit(`${t("Preview", "미리보기")}: ${preview}`),
63
- help
64
- ];
65
- } else if (height >= 8) {
66
- lines = [fit(t("Tools & display order", "표시 도구·순서")), ...items.map(fit), help];
72
+
73
+ if (activeTab === "providers") {
74
+ const arrows = t("↑↓ select · ←→ move", "↑↓ 선택 · ←→ 순서 이동");
75
+ const toggle = t("Space show/hide", "Space 표시/숨김");
76
+ const confirm = t("Enter save · Esc cancel", "Enter 저장 · Esc 취소");
77
+ const tabHint = t("Tab switch", "Tab 전환");
78
+ const fullHelp = `${arrows} · ${toggle} · ${confirm} · ${tabHint}`;
79
+ const baseHelp = `${arrows} · ${toggle} · ${confirm}`;
80
+ const compactHelp = t("↑↓ select · ←→ move · Space toggle · Enter save · Esc cancel · Tab", "↑↓ 선택 · ←→ 순서 · Space 표시 · Enter 저장 · Esc 취소 · Tab");
81
+ const help = [fullHelp, baseHelp, compactHelp, "↑↓ · ←→ · Space · Enter · Esc · Tab"].find(text => visibleWidth(text) <= availableWidth)
82
+ || truncateMiddleVisible("↑↓ ←→ Space Enter Esc Tab", availableWidth);
83
+ const items = order.map((provider, index) => {
84
+ const enabled = providers[provider];
85
+ const text = `${index === selected ? "›" : " "} ${index + 1}. [${enabled ? "x" : " "}] ${providerLabel(provider)}`;
86
+ const inside = truncateMiddleVisible(text, Math.max(1, width - 4));
87
+ const padded = inside + " ".repeat(Math.max(0, width - 4 - visibleWidth(inside)));
88
+ const boxed = width >= 24 && height >= 10;
89
+ if (!color) return boxed ? `│ ${padded} │` : text;
90
+ if (boxed) {
91
+ if (index === selected) {
92
+ return enabled ? `\x1b[36m│ ${padded} │\x1b[0m` : `\x1b[36m│ \x1b[2m${padded}\x1b[0;36m │\x1b[0m`;
93
+ }
94
+ return enabled ? `│ ${padded} │` : `│ \x1b[2m${padded}\x1b[0m │`;
95
+ }
96
+ if (index === selected) return enabled ? `\x1b[36m${text}\x1b[0m` : `\x1b[2;36m${text}\x1b[0m`;
97
+ return enabled ? text : `\x1b[2m${text}\x1b[0m`;
98
+ });
99
+ const preview = order.filter(provider => providers[provider]).map(providerLabel).join(" → ") || t("All hidden", "모두 숨김");
100
+ if (width >= 24 && height >= 10) {
101
+ const title = formatTabHeader();
102
+ lines = [
103
+ `╭─${title}${"─".repeat(Math.max(0, width - 3 - visibleWidth(title)))}╮`,
104
+ ...items,
105
+ `╰${"─".repeat(width - 2)}╯`,
106
+ fit(`${t("Preview", "미리보기")}: ${preview}`),
107
+ help
108
+ ];
109
+ } else if (height >= 8) {
110
+ lines = [fit(toolsTitle), ...items.map(fit), help];
111
+ } else {
112
+ lines = [fit(`${selected + 1}/${order.length} [${providers[order[selected]] ? "x" : " "}] ${providerLabel(order[selected])}`), help].slice(0, Math.max(1, height));
113
+ }
67
114
  } else {
68
- lines = [fit(`${selected + 1}/${order.length} [${providers[order[selected]] ? "x" : " "}] ${providerLabel(order[selected])}`), help].slice(0, Math.max(1, height));
115
+ const isSidePosition = barPosition === "left" || barPosition === "right";
116
+ const fullHelp = t("↑↓ select · Enter save · Esc cancel · Tab switch", "↑↓ 선택 · Enter 저장 · Esc 취소 · Tab 전환");
117
+ const compactHelp = t("↑↓ select · Enter save · Esc cancel · Tab", "↑↓ 선택 · Enter 저장 · Esc 취소 · Tab");
118
+ const help = [fullHelp, compactHelp, "↑↓ · Enter · Esc · Tab"].find(text => visibleWidth(text) <= availableWidth)
119
+ || truncateMiddleVisible("↑↓ Enter Esc Tab", availableWidth);
120
+ const items = BAR_POSITIONS.map((pos, index) => {
121
+ const text = `${index === positionSelected ? "›" : " "} [${pos === barPosition ? "x" : " "}] ${positionLabel(pos)}`;
122
+ const inside = truncateMiddleVisible(text, Math.max(1, width - 4));
123
+ const padded = inside + " ".repeat(Math.max(0, width - 4 - visibleWidth(inside)));
124
+ const line = width >= 24 && height >= 10 ? `│ ${padded} │` : text;
125
+ return index === positionSelected && color ? `\x1b[36m${line}\x1b[0m` : line;
126
+ });
127
+ const buildSideMockup = () => {
128
+ if (!isSidePosition || width < 28 || height < 16) return [];
129
+ const frameW = Math.min(availableWidth, width);
130
+ const sideW = 5;
131
+ const workW = Math.max(8, frameW - sideW - 3);
132
+ const padCell = (raw, w) => {
133
+ const clipped = truncateMiddleVisible(raw, w);
134
+ return clipped + " ".repeat(Math.max(0, w - visibleWidth(clipped)));
135
+ };
136
+ const centerCell = (raw, w) => {
137
+ const clipped = truncateMiddleVisible(raw, w);
138
+ const len = visibleWidth(clipped);
139
+ const l = Math.floor(Math.max(0, w - len) / 2);
140
+ const r = Math.max(0, w - len - l);
141
+ return `${" ".repeat(l)}${clipped}${" ".repeat(r)}`;
142
+ };
143
+ const gRail = color ? "\x1b[90m│\x1b[0m" : "│";
144
+ const gPart = color ? "\x1b[32m▄\x1b[0m" : "▄";
145
+ const gFull = color ? "\x1b[32m█\x1b[0m" : "█";
146
+ const mockSideRows = [
147
+ centerCell(color ? "\x1b[1;38;2;96;165;250mAGY\x1b[0m" : "AGY", sideW),
148
+ centerCell(gRail, sideW),
149
+ centerCell(gPart, sideW),
150
+ centerCell(gFull, sideW),
151
+ centerCell(color ? "\x1b[1;32m50%\x1b[0m" : "50%", sideW),
152
+ centerCell(color ? "\x1b[90m5h\x1b[0m" : "5h", sideW),
153
+ centerCell(color ? "\x1b[37m18:34\x1b[0m" : "18:34", sideW),
154
+ centerCell(color ? "\x1b[90m7d\x1b[0m" : "7d", sideW),
155
+ centerCell(color ? "\x1b[37m74%\x1b[0m" : "74%", sideW)
156
+ ];
157
+ const mockWorkRows = mockSideRows.map((_, idx) => (
158
+ idx === 0
159
+ ? padCell(color ? "\x1b[2m $ codex\x1b[0m" : " $ codex", workW)
160
+ : " ".repeat(workW)
161
+ ));
162
+ const isLeft = barPosition === "left";
163
+ const border = s => color ? `\x1b[2m${s}\x1b[0m` : s;
164
+ const top = isLeft
165
+ ? border(`┌${"─".repeat(sideW)}┬${"─".repeat(workW)}┐`)
166
+ : border(`┌${"─".repeat(workW)}┬${"─".repeat(sideW)}┐`);
167
+ const bottom = isLeft
168
+ ? border(`└${"─".repeat(sideW)}┴${"─".repeat(workW)}┘`)
169
+ : border(`└${"─".repeat(workW)}┴${"─".repeat(sideW)}┘`);
170
+ const v = border("│");
171
+ const body = mockSideRows.map((sideCell, idx) => (
172
+ isLeft
173
+ ? `${v}${sideCell}${v}${mockWorkRows[idx]}${v}`
174
+ : `${v}${mockWorkRows[idx]}${v}${sideCell}${v}`
175
+ ));
176
+ return [top, ...body, bottom];
177
+ };
178
+ if (width >= 24 && height >= 10) {
179
+ const title = formatTabHeader();
180
+ lines = [
181
+ `╭─${title}${"─".repeat(Math.max(0, width - 3 - visibleWidth(title)))}╮`,
182
+ ...items,
183
+ `╰${"─".repeat(width - 2)}╯`,
184
+ ...buildSideMockup(),
185
+ help
186
+ ];
187
+ } else if (height >= 8) {
188
+ lines = [fit(posTitle), ...items.map(fit), help];
189
+ } else {
190
+ lines = [fit(`${positionSelected + 1}/${BAR_POSITIONS.length} [${barPosition}] ${positionLabel(barPosition)}`), help].slice(0, Math.max(1, height));
191
+ }
69
192
  }
70
193
  erase();
71
194
  output.write(`${lines.join("\r\n")}\r`);
@@ -99,8 +222,33 @@ export function editDisplayConfig(initialConfig, { input = process.stdin, output
99
222
  if (key.ctrl && key.name === "c") return onInterrupt();
100
223
  if (key.name === "return" || key.name === "enter") return finish({
101
224
  providerOrder: [...order],
102
- providerChanges: Object.fromEntries([...changedProviders].map(provider => [provider, providers[provider]]))
225
+ orderChanged: !isDeepStrictEqual(order, initialOrder),
226
+ providerChanges: Object.fromEntries([...changedProviders].map(provider => [provider, providers[provider]])),
227
+ barPosition,
228
+ barPositionChanged: barPosition !== initialBarPosition,
229
+ positionTabVisited,
230
+ sidebarWidth,
231
+ sidebarWidthChanged: sidebarWidth !== initialSidebarWidth
103
232
  });
233
+ if (key.name === "tab" || _text === "\t") {
234
+ activeTab = activeTab === "providers" ? "position" : "providers";
235
+ if (activeTab === "position") positionTabVisited = true;
236
+ onResize();
237
+ return;
238
+ }
239
+ if (activeTab === "position") {
240
+ if (key.name === "up" || key.name === "left") {
241
+ positionSelected = (positionSelected - 1 + BAR_POSITIONS.length) % BAR_POSITIONS.length;
242
+ barPosition = BAR_POSITIONS[positionSelected];
243
+ } else if (key.name === "down" || key.name === "right") {
244
+ positionSelected = (positionSelected + 1) % BAR_POSITIONS.length;
245
+ barPosition = BAR_POSITIONS[positionSelected];
246
+ } else if ((key.name === "space" || _text === " ") && !key.ctrl && !key.meta) {
247
+ barPosition = BAR_POSITIONS[positionSelected];
248
+ } else return;
249
+ onResize();
250
+ return;
251
+ }
104
252
  if ((key.name === "space" || _text === " ") && !key.ctrl && !key.meta) {
105
253
  const provider = order[selected];
106
254
  providers[provider] = !providers[provider];