heimdall-agent 1.4.0 → 1.5.0

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
@@ -263,6 +263,11 @@ heimdall audit
263
263
  # Refresh dynamic model catalog from your active provider/proxy
264
264
  heimdall sync-models
265
265
 
266
+ # Enable, disable, or theme the 2-line Heimdall HUD statusline
267
+ heimdall hud
268
+ heimdall hud --on --theme night-blue
269
+ heimdall hud --off
270
+
266
271
  # Browse canonical skills catalog and upstream repositories
267
272
  heimdall skills
268
273
 
@@ -279,7 +284,9 @@ heimdall uninstall
279
284
  | Flag | Default | Description | Example |
280
285
  | :--- | :---: | :--- | :--- |
281
286
  | `--profile <name>` | `full` | Skill profile tier: `full`, `minimal`, `security`, or `design`. | `heimdall --profile minimal` |
282
- | `--agents <targets>` | `all` | Comma-separated list of harnesses: `claude`, `gemini`, `codex`, `desktop`, `all`. | `heimdall --agents claude,gemini` |
287
+ | `--agents <targets>` | `all` | Comma-separated list of harnesses: `claude`, `gemini`, `codex`, `hermes`, `openclaw`, `vscode`, `desktop`, `all`. | `heimdall --agents claude,vscode` |
288
+ | `--theme <name>` | `night-blue` | HUD color theme: `night-blue`, `heimdall`, `claude-warm`, or `titanium`. | `heimdall hud --theme claude-warm` |
289
+ | `--no-hud` | `false` | Skip configuring the Heimdall HUD statusline during install or sync. | `heimdall --no-hud` |
283
290
  | `--link` | `true` (rec.) | Deploy skills using live NTFS junctions (Windows) or POSIX symlinks (macOS/Linux). | `heimdall --link` |
284
291
  | `--clean` | `false` | Wipe legacy skills from target directory before deploying. | `heimdall --clean` |
285
292
  | `--dry-run` | `false` | Simulate execution and display actions without modifying the filesystem. | `heimdall --dry-run` |
@@ -487,6 +494,7 @@ For multi-device pair programming, mobile monitoring, and project memory, Heimda
487
494
  * **[Moshi (`getmoshi.app`)](https://getmoshi.app/)**: Mobile client (iOS/Android) pairing with your terminal session. Delivers push notifications when an agent hits an interactive planning gate and enables remote approval.
488
495
  * **[Graphify (`github.com/Graphify-Labs/graphify`)](https://github.com/Graphify-Labs/graphify)**: Local-first code knowledge graph builder. Uses Tree-sitter AST parsing across 40+ programming languages to build deterministic dependency maps with zero LLM API costs, exporting directly to Obsidian vaults.
489
496
  * **[Obsidian (`obsidian.md`)](https://obsidian.md/)**: Local-first Markdown knowledge base. Paired with Graphify-generated vaults (`[[wikilinks]]`), it serves as persistent external memory for AI coding agents, loading immediate architectural context on startup without token-heavy scanning.
497
+ * **Heimdall HUD ([`tools/heimdall-hud.mjs`](tools/heimdall-hud.mjs))**: Built-in 2-line terminal statusline for **Claude Code** and **Google Antigravity (`agy`)** displaying model, color-coded context bar, git branch/dirty count, token usage, session cost, and duration across 4 themes (`night-blue` default, `heimdall`, `claude-warm`, `titanium`). For **Codex CLI** (which does not execute external `statusLine` scripts), `heimdall hud` configures Codex's native `[tui] status_line` items in `~/.codex/config.toml`.
490
498
 
491
499
  [↑ Back to top](#table-of-contents)
492
500
 
package/README.pt-BR.md CHANGED
@@ -263,6 +263,11 @@ heimdall audit
263
263
  # Atualizar o catálogo dinâmico de modelos a partir do seu provedor/proxy ativo
264
264
  heimdall sync-models
265
265
 
266
+ # Ativar, desativar ou escolher o tema da statusline Heimdall HUD (2 linhas)
267
+ heimdall hud
268
+ heimdall hud --on --theme night-blue
269
+ heimdall hud --off
270
+
266
271
  # Navegar pelo catálogo canônico de skills e repositórios upstream
267
272
  heimdall skills
268
273
 
@@ -279,7 +284,9 @@ heimdall uninstall
279
284
  | Flag | Padrão | Descrição | Exemplo |
280
285
  | :--- | :---: | :--- | :--- |
281
286
  | `--profile <nome>` | `full` | Perfil de skills: `full`, `minimal`, `security` ou `design`. | `heimdall --profile minimal` |
282
- | `--agents <alvos>` | `all` | Lista de ferramentas separadas por vírgula: `claude`, `gemini`, `codex`, `desktop`, `all`. | `heimdall --agents claude,gemini` |
287
+ | `--agents <alvos>` | `all` | Lista de ferramentas separadas por vírgula: `claude`, `gemini`, `codex`, `hermes`, `openclaw`, `vscode`, `desktop`, `all`. | `heimdall --agents claude,vscode` |
288
+ | `--theme <nome>` | `night-blue` | Tema de cores do HUD: `night-blue`, `heimdall`, `claude-warm` ou `titanium`. | `heimdall hud --theme claude-warm` |
289
+ | `--no-hud` | `false` | Pula a configuração da statusline Heimdall HUD durante a instalação ou sincronização. | `heimdall --no-hud` |
283
290
  | `--link` | `true` (rec.) | Implanta skills usando junctions NTFS (Windows) ou symlinks POSIX (macOS/Linux). | `heimdall --link` |
284
291
  | `--clean` | `false` | Limpa skills antigas do diretório de destino antes de implantar. | `heimdall --clean` |
285
292
  | `--dry-run` | `false` | Simula a execução e exibe as ações sem modificar o sistema de arquivos. | `heimdall --dry-run` |
@@ -500,6 +507,7 @@ Para programação em par entre múltiplos dispositivos, monitoramento mobile e
500
507
  * **[Moshi (`getmoshi.app`)](https://getmoshi.app/)**: Cliente mobile (iOS/Android) pareado com sua sessão de terminal. Envia notificações push quando um agente atinge um portão interativo de planejamento e permite aprovação remota.
501
508
  * **[Graphify (`github.com/Graphify-Labs/graphify`)](https://github.com/Graphify-Labs/graphify)**: Construtor local de grafos de conhecimento de código. Usa análise AST via Tree-sitter em mais de 40 linguagens para gerar mapas determinísticos de dependência sem custo de API de LLM, exportando diretamente para cofres do Obsidian.
502
509
  * **[Obsidian (`obsidian.md`)](https://obsidian.md/)**: Base de conhecimento local em Markdown. Combinado com cofres gerados pelo Graphify (`[[wikilinks]]`), funciona como memória externa persistente para agentes de IA, carregando contexto arquitetural imediato na inicialização sem varreduras pesadas em tokens.
510
+ * **Heimdall HUD ([`tools/heimdall-hud.mjs`](tools/heimdall-hud.mjs))**: Statusline nativa de 2 linhas para terminal no **Claude Code** e **Google Antigravity (`agy`)**, exibindo modelo, barra de contexto colorida, branch Git e arquivos modificados, consumo de tokens, custo e duração da sessão em 4 temas (`night-blue` padrão, `heimdall`, `claude-warm`, `titanium`). No **Codex CLI** (que não executa scripts externos de `statusLine`), o `heimdall hud` configura os itens nativos `[tui] status_line` em `~/.codex/config.toml`.
503
511
 
504
512
  [↑ Voltar ao topo](#indice)
505
513
 
@@ -14,7 +14,7 @@
14
14
  "mcp"
15
15
  ],
16
16
  "env": {
17
- "OD_DATA_DIR": "C:\\Users\\Bernardo\\AppData\\Roaming\\Open Design\\en\\27c3746c33b16995\\resources\\open-design\\data\\namespaces\\release-stable-win\\data",
17
+ "OD_DATA_DIR": "C:\\Users\\Bernardo\\AppData\\Roaming\\Open Design\\launcher\\channels\\stable\\namespaces\\release-stable-win\\versions\\0.27.0\\payload\\resources\\open-design\\data",
18
18
  "OD_SIDECAR_CLIENT_ENDPOINT": "\\\\.\\pipe\\open-design-sidecar-714ebde02da67fea98a7ed27125062c8",
19
19
  "OD_MCP_BOOTSTRAP_COMMAND": "C:\\Users\\Bernardo\\AppData\\Local\\Programs\\Open Design\\Open Design.exe",
20
20
  "OD_MCP_BOOTSTRAP_ARGS": "[\"--headless\"]",
@@ -0,0 +1,187 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const os = require('node:os');
4
+
5
+ const CODEX_STATUS_LINE_ITEMS = [
6
+ 'model-with-reasoning',
7
+ 'current-dir',
8
+ 'git-branch',
9
+ 'context-used',
10
+ 'context-window-size',
11
+ 'five-hour-limit',
12
+ 'weekly-limit'
13
+ ];
14
+
15
+ function formatHudCommand(hudScriptPath) {
16
+ const normalized = String(hudScriptPath).replace(/\\/g, '/');
17
+ return `node "${normalized}"`;
18
+ }
19
+
20
+ /**
21
+ * Configures Claude Code's ~/.claude/settings.json statusLine command.
22
+ */
23
+ function configureClaudeStatusLine(hudScriptPath, dryRun = false, homeDir = os.homedir()) {
24
+ const settingsPath = path.join(homeDir, '.claude', 'settings.json');
25
+ if (!fs.existsSync(settingsPath)) return false;
26
+ try {
27
+ const cfg = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
28
+ const desiredCmd = formatHudCommand(hudScriptPath);
29
+ if (cfg.statusLine?.command === desiredCmd && cfg.statusLine?.type === 'command') {
30
+ return false;
31
+ }
32
+ cfg.statusLine = { type: 'command', command: desiredCmd };
33
+ if (!dryRun) {
34
+ fs.writeFileSync(settingsPath, JSON.stringify(cfg, null, 2) + '\n');
35
+ }
36
+ return true;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Configures Antigravity CLI's ~/.gemini/antigravity-cli/settings.json statusLine command.
44
+ */
45
+ function configureAntigravityStatusLine(hudScriptPath, dryRun = false, homeDir = os.homedir()) {
46
+ const settingsPath = path.join(homeDir, '.gemini', 'antigravity-cli', 'settings.json');
47
+ if (!fs.existsSync(settingsPath)) return false;
48
+ try {
49
+ const cfg = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
50
+ const desiredCmd = formatHudCommand(hudScriptPath);
51
+ if (cfg.statusLine?.command === desiredCmd && cfg.statusLine?.enabled === true) {
52
+ return false;
53
+ }
54
+ cfg.statusLine = {
55
+ type: 'command',
56
+ command: desiredCmd,
57
+ enabled: true,
58
+ padding: 0,
59
+ stack_with_default: false
60
+ };
61
+ if (!dryRun) {
62
+ fs.writeFileSync(settingsPath, JSON.stringify(cfg, null, 2) + '\n');
63
+ }
64
+ return true;
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Ensures Codex CLI's ~/.codex/config.toml [tui] table includes status_line items.
72
+ */
73
+ function configureCodexStatusLine(dryRun = false, homeDir = os.homedir()) {
74
+ const configPath = path.join(homeDir, '.codex', 'config.toml');
75
+ if (!fs.existsSync(configPath)) return false;
76
+ try {
77
+ let content = fs.readFileSync(configPath, 'utf8');
78
+ if (/^\s*status_line\s*=/m.test(content)) {
79
+ return false;
80
+ }
81
+ const itemsLiteral = CODEX_STATUS_LINE_ITEMS.map(item => `"${item}"`).join(', ');
82
+ const snippet = `status_line = [${itemsLiteral}]`;
83
+
84
+ if (/^\[tui\]/m.test(content)) {
85
+ content = content.replace(/^(\[tui\]\s*\r?\n)/m, `$1${snippet}\n`);
86
+ } else {
87
+ content = content.trimEnd() + `\n\n[tui]\n${snippet}\n`;
88
+ }
89
+
90
+ if (!dryRun) {
91
+ fs.writeFileSync(configPath, content);
92
+ }
93
+ return true;
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Removes statusLine from Claude Code's ~/.claude/settings.json.
101
+ */
102
+ function disableClaudeStatusLine(dryRun = false, homeDir = os.homedir()) {
103
+ const settingsPath = path.join(homeDir, '.claude', 'settings.json');
104
+ if (!fs.existsSync(settingsPath)) return false;
105
+ try {
106
+ const cfg = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
107
+ if (!cfg.statusLine) return false;
108
+ delete cfg.statusLine;
109
+ if (!dryRun) {
110
+ fs.writeFileSync(settingsPath, JSON.stringify(cfg, null, 2) + '\n');
111
+ }
112
+ return true;
113
+ } catch {
114
+ return false;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Removes statusLine from Antigravity CLI's ~/.gemini/antigravity-cli/settings.json.
120
+ */
121
+ function disableAntigravityStatusLine(dryRun = false, homeDir = os.homedir()) {
122
+ const settingsPath = path.join(homeDir, '.gemini', 'antigravity-cli', 'settings.json');
123
+ if (!fs.existsSync(settingsPath)) return false;
124
+ try {
125
+ const cfg = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
126
+ if (!cfg.statusLine) return false;
127
+ delete cfg.statusLine;
128
+ if (!dryRun) {
129
+ fs.writeFileSync(settingsPath, JSON.stringify(cfg, null, 2) + '\n');
130
+ }
131
+ return true;
132
+ } catch {
133
+ return false;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Removes status_line and status_line_use_colors from Codex CLI's ~/.codex/config.toml.
139
+ */
140
+ function disableCodexStatusLine(dryRun = false, homeDir = os.homedir()) {
141
+ const configPath = path.join(homeDir, '.codex', 'config.toml');
142
+ if (!fs.existsSync(configPath)) return false;
143
+ try {
144
+ const original = fs.readFileSync(configPath, 'utf8');
145
+ const updated = original
146
+ .replace(/^\s*status_line\s*=.*\r?\n?/gm, '')
147
+ .replace(/^\s*status_line_use_colors\s*=.*\r?\n?/gm, '');
148
+ if (updated === original) return false;
149
+ if (!dryRun) {
150
+ fs.writeFileSync(configPath, updated);
151
+ }
152
+ return true;
153
+ } catch {
154
+ return false;
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Persists user HUD theme and line-count preferences to ~/.heimdall-hud.json.
160
+ */
161
+ function writeHudConfig({ theme, lines }, dryRun = false, homeDir = os.homedir()) {
162
+ const cfgPath = path.join(homeDir, '.heimdall-hud.json');
163
+ let existing = {};
164
+ if (fs.existsSync(cfgPath)) {
165
+ try { existing = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch {}
166
+ }
167
+ const next = {
168
+ ...existing,
169
+ ...(theme ? { theme } : {}),
170
+ ...(lines ? { lines: Number(lines) === 1 ? 1 : 2 } : {})
171
+ };
172
+ if (!dryRun) {
173
+ fs.writeFileSync(cfgPath, JSON.stringify(next, null, 2) + '\n');
174
+ }
175
+ return next;
176
+ }
177
+
178
+ module.exports = {
179
+ CODEX_STATUS_LINE_ITEMS,
180
+ configureClaudeStatusLine,
181
+ configureAntigravityStatusLine,
182
+ configureCodexStatusLine,
183
+ disableClaudeStatusLine,
184
+ disableAntigravityStatusLine,
185
+ disableCodexStatusLine,
186
+ writeHudConfig
187
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heimdall-agent",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Autonomous multi-agent engineering sentinel & bootstrapper. Synchronizes specialized agent personas, curated skills, and universal doctrine across Google Antigravity, Claude Code, OpenAI Codex CLI, Hermes Agent, OpenClaw, and Claude Desktop.",
5
5
  "type": "module",
6
6
  "bin": {
package/setup.mjs CHANGED
@@ -23,6 +23,15 @@ import { syncAgentsWithModels, syncModelRegistryPlaybook } from './lib/model-rou
23
23
  import { updateHermesConfigContext } from './lib/hermes-context.cjs';
24
24
  import { detectPathCandidates } from './lib/path-discovery.cjs';
25
25
  import { syncCatalogCounts } from './lib/catalog-sync.cjs';
26
+ import {
27
+ configureClaudeStatusLine,
28
+ configureAntigravityStatusLine,
29
+ configureCodexStatusLine,
30
+ disableClaudeStatusLine,
31
+ disableAntigravityStatusLine,
32
+ disableCodexStatusLine,
33
+ writeHudConfig
34
+ } from './lib/hud-sync.cjs';
26
35
 
27
36
  const __filename = fileURLToPath(import.meta.url);
28
37
  const __dirname = path.dirname(__filename);
@@ -87,13 +96,36 @@ function getOpenClawDir() {
87
96
  return homePath;
88
97
  }
89
98
 
99
+ /**
100
+ * Resolves the GitHub Copilot / VS Code user skills & agents directory (~/.copilot).
101
+ */
102
+ function getCopilotDir() {
103
+ return path.join(userHome, '.copilot');
104
+ }
105
+
106
+ /**
107
+ * Resolves the VS Code User configuration directory across Windows, macOS, and Linux.
108
+ */
109
+ function getVSCodeUserDir() {
110
+ const platform = os.platform();
111
+ if (platform === 'win32') {
112
+ const appData = process.env.APPDATA || path.join(userHome, 'AppData', 'Roaming');
113
+ return path.join(appData, 'Code', 'User');
114
+ }
115
+ if (platform === 'darwin') {
116
+ return path.join(userHome, 'Library', 'Application Support', 'Code', 'User');
117
+ }
118
+ return path.join(userHome, '.config', 'Code', 'User');
119
+ }
120
+
90
121
  const targetPaths = {
91
122
  claude: path.join(userHome, '.claude', 'skills'),
92
123
  gemini: path.join(userHome, '.gemini', 'skills'),
93
124
  codex: path.join(userHome, '.codex', 'skills'),
94
125
  agents: path.join(userHome, '.agents', 'skills'),
95
126
  hermes: path.join(getHermesDir(), 'skills'),
96
- openclaw: path.join(getOpenClawDir(), 'skills')
127
+ openclaw: path.join(getOpenClawDir(), 'skills'),
128
+ vscode: path.join(getCopilotDir(), 'skills')
97
129
  };
98
130
 
99
131
  const targetAgentPaths = {
@@ -102,7 +134,8 @@ const targetAgentPaths = {
102
134
  codex: path.join(userHome, '.codex', 'agents'),
103
135
  agents: path.join(userHome, '.agents', 'agents'),
104
136
  hermes: path.join(getHermesDir(), 'agents'),
105
- openclaw: path.join(getOpenClawDir(), 'agents')
137
+ openclaw: path.join(getOpenClawDir(), 'agents'),
138
+ vscode: path.join(getCopilotDir(), 'agents')
106
139
  };
107
140
 
108
141
  const targetDoctrinePaths = {
@@ -111,7 +144,8 @@ const targetDoctrinePaths = {
111
144
  codex: path.join(userHome, '.codex', 'AGENTS.md'),
112
145
  agents: path.join(userHome, '.agents', 'AGENTS.md'),
113
146
  hermes: path.join(getHermesDir(), 'AGENTS.md'),
114
- openclaw: path.join(getOpenClawDir(), 'AGENTS.md')
147
+ openclaw: path.join(getOpenClawDir(), 'AGENTS.md'),
148
+ vscode: path.join(getCopilotDir(), 'copilot-instructions.md')
115
149
  };
116
150
 
117
151
  const targetPlaybookPaths = {
@@ -119,7 +153,8 @@ const targetPlaybookPaths = {
119
153
  gemini: path.join(userHome, '.gemini', 'playbooks'),
120
154
  agents: path.join(userHome, '.agents', 'playbooks'),
121
155
  hermes: path.join(getHermesDir(), 'playbooks'),
122
- openclaw: path.join(getOpenClawDir(), 'playbooks')
156
+ openclaw: path.join(getOpenClawDir(), 'playbooks'),
157
+ vscode: path.join(getCopilotDir(), 'playbooks')
123
158
  };
124
159
 
125
160
  const targetCommandPaths = {
@@ -140,6 +175,7 @@ function getAgentRootDir(agent) {
140
175
  if (agent === 'agents') return path.join(userHome, '.agents');
141
176
  if (agent === 'hermes') return getHermesDir();
142
177
  if (agent === 'openclaw') return getOpenClawDir();
178
+ if (agent === 'vscode') return getCopilotDir();
143
179
  if (agent === 'desktop') return getClaudeDesktopDir();
144
180
  return null;
145
181
  }
@@ -153,6 +189,9 @@ function isAgentConfigurable(agent) {
153
189
  const status = detectClaudeDesktop();
154
190
  return Boolean(status.configExists);
155
191
  }
192
+ if (agent === 'vscode') {
193
+ return Boolean(fs.existsSync(getCopilotDir()) || fs.existsSync(getVSCodeUserDir()) || detectVSCodeBinary());
194
+ }
156
195
  const rootDir = getAgentRootDir(agent);
157
196
  return Boolean(rootDir && fs.existsSync(rootDir));
158
197
  }
@@ -523,6 +562,17 @@ function auditMcpServers() {
523
562
  } catch {}
524
563
  }
525
564
 
565
+ // VS Code (User/mcp.json)
566
+ const vscodeMcpFile = path.join(getVSCodeUserDir(), 'mcp.json');
567
+ if (fs.existsSync(vscodeMcpFile)) {
568
+ try {
569
+ const cfg = JSON.parse(fs.readFileSync(vscodeMcpFile, 'utf8'));
570
+ for (const s of serverNames) {
571
+ results.push({ harness: 'VS Code', server: s, configured: Boolean(cfg.servers?.[s]) });
572
+ }
573
+ } catch {}
574
+ }
575
+
526
576
  return results;
527
577
  }
528
578
 
@@ -617,6 +667,31 @@ function detectOpenClawBinary() {
617
667
  return null;
618
668
  }
619
669
 
670
+ /**
671
+ * Resiliently discovers the VS Code CLI binary on PATH and standard Windows/POSIX install paths.
672
+ */
673
+ function detectVSCodeBinary() {
674
+ const onPath = checkCommand('code');
675
+ if (onPath) return onPath;
676
+
677
+ if (os.platform() === 'win32') {
678
+ const candidates = [
679
+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'Microsoft VS Code', 'bin', 'code.cmd'),
680
+ path.join(process.env['ProgramFiles'] || 'C:\\Program Files', 'Microsoft VS Code', 'bin', 'code.cmd')
681
+ ];
682
+ for (const cand of candidates) {
683
+ if (cand && fs.existsSync(cand)) return cand;
684
+ }
685
+ } else if (os.platform() === 'darwin') {
686
+ const macCand = '/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code';
687
+ if (fs.existsSync(macCand)) return macCand;
688
+ } else {
689
+ const linuxCand = '/usr/bin/code';
690
+ if (fs.existsSync(linuxCand)) return linuxCand;
691
+ }
692
+ return null;
693
+ }
694
+
620
695
  /**
621
696
  * Ensures ~/.agents/skills is registered under external_dirs in Hermes's config.yaml.
622
697
  */
@@ -727,6 +802,7 @@ function detectEnvironment() {
727
802
  detected.tools.codex = detectCodexBinary();
728
803
  detected.tools.hermes = detectHermesBinary();
729
804
  detected.tools.openclaw = detectOpenClawBinary();
805
+ detected.tools.vscode = detectVSCodeBinary();
730
806
  detected.tools.cursor = checkCommand('cursor');
731
807
  detected.tools.windsurf = checkCommand('windsurf');
732
808
 
@@ -816,9 +892,106 @@ function detectEnvironment() {
816
892
  detected.endpoints.openclaw = 'Not Installed / Unconfigured';
817
893
  }
818
894
 
895
+ // 8. Check VS Code / Copilot endpoint
896
+ const vscodeSettingsPath = path.join(getVSCodeUserDir(), 'settings.json');
897
+ if (fs.existsSync(vscodeSettingsPath)) {
898
+ try {
899
+ const raw = fs.readFileSync(vscodeSettingsPath, 'utf8');
900
+ const envMatch = raw.match(/"ANTHROPIC_BASE_URL"\s*:\s*"([^"]+)"/) || raw.match(/"OPENAI_BASE_URL"\s*:\s*"([^"]+)"/);
901
+ if (envMatch) detected.endpoints.vscode = envMatch[1];
902
+ } catch {}
903
+ }
904
+ if (!detected.endpoints.vscode && (detected.tools.vscode || fs.existsSync(getVSCodeUserDir()) || fs.existsSync(getCopilotDir()))) {
905
+ detected.endpoints.vscode = 'GitHub Copilot / Local User Config';
906
+ } else if (!detected.endpoints.vscode) {
907
+ detected.endpoints.vscode = 'Not Installed / Unconfigured';
908
+ }
909
+
819
910
  return detected;
820
911
  }
821
912
 
913
+ function syncHud(dryRun = false, hudOptions = {}) {
914
+ const hudScript = path.join(toolsDir, 'heimdall-hud.mjs');
915
+ if (!fs.existsSync(hudScript)) return false;
916
+ let updated = false;
917
+
918
+ if (hudOptions.off) {
919
+ if (disableClaudeStatusLine(dryRun)) {
920
+ console.log(` ${colors.yellow}✔ Disabled Heimdall HUD statusLine in Claude Code (~/.claude/settings.json)${colors.reset}`);
921
+ updated = true;
922
+ }
923
+ if (disableAntigravityStatusLine(dryRun)) {
924
+ console.log(` ${colors.yellow}✔ Disabled Heimdall HUD statusLine in Antigravity (~/.gemini/antigravity-cli/settings.json)${colors.reset}`);
925
+ updated = true;
926
+ }
927
+ if (disableCodexStatusLine(dryRun)) {
928
+ console.log(` ${colors.yellow}✔ Disabled [tui] status_line in Codex CLI (~/.codex/config.toml)${colors.reset}`);
929
+ updated = true;
930
+ }
931
+ return updated;
932
+ }
933
+
934
+ if (hudOptions.theme || hudOptions.lines) {
935
+ writeHudConfig({ theme: hudOptions.theme, lines: hudOptions.lines }, dryRun);
936
+ console.log(` ${colors.green}✔ Saved HUD preferences (~/.heimdall-hud.json): theme=${hudOptions.theme || 'night-blue'}, lines=${hudOptions.lines || 2}${colors.reset}`);
937
+ updated = true;
938
+ }
939
+
940
+ if (configureClaudeStatusLine(hudScript, dryRun)) {
941
+ console.log(` ${colors.green}✔ Configured Heimdall HUD statusLine in Claude Code (~/.claude/settings.json)${colors.reset}`);
942
+ updated = true;
943
+ }
944
+ if (configureAntigravityStatusLine(hudScript, dryRun)) {
945
+ console.log(` ${colors.green}✔ Configured Heimdall HUD statusLine in Antigravity (~/.gemini/antigravity-cli/settings.json)${colors.reset}`);
946
+ updated = true;
947
+ }
948
+ if (configureCodexStatusLine(dryRun)) {
949
+ console.log(` ${colors.green}✔ Configured native [tui] status_line in Codex CLI (~/.codex/config.toml)${colors.reset}`);
950
+ updated = true;
951
+ }
952
+ return updated;
953
+ }
954
+
955
+ const HUD_THEMES = ['night-blue', 'heimdall', 'claude-warm', 'titanium'];
956
+
957
+ async function runHudInteractive(options, existingRl = null) {
958
+ const rl = existingRl || readline.createInterface({ input: process.stdin, output: process.stdout });
959
+ try {
960
+ console.log(`${colors.bold}${colors.cyan}=== Heimdall HUD Statusline Configuration ===${colors.reset}\n`);
961
+ console.log(` 1. Enable / Update HUD (Claude Code, Antigravity, Codex)`);
962
+ console.log(` 2. Disable HUD across all harnesses`);
963
+ console.log(` 3. Choose HUD Theme only (night-blue, heimdall, claude-warm, titanium)`);
964
+ const action = (await rl.question(`Choose an option [1-3, default: 1]: `)).trim();
965
+
966
+ if (action === '2') {
967
+ const updated = syncHud(options.dryRun, { off: true });
968
+ if (!updated) console.log(` ${colors.dim}HUD was not active in any harness.${colors.reset}`);
969
+ return;
970
+ }
971
+
972
+ console.log(`\n${colors.yellow}Select HUD Color Theme:${colors.reset}`);
973
+ console.log(` 1. night-blue [Default]`);
974
+ console.log(` 2. heimdall`);
975
+ console.log(` 3. claude-warm`);
976
+ console.log(` 4. titanium`);
977
+ const tChoice = (await rl.question(`Choose theme [1-4, default: 1]: `)).trim();
978
+ const themeIdx = parseInt(tChoice, 10);
979
+ const chosenTheme = (themeIdx >= 1 && themeIdx <= HUD_THEMES.length) ? HUD_THEMES[themeIdx - 1] : 'night-blue';
980
+
981
+ const lChoice = (await rl.question(`Layout lines? [1 or 2, default: 2]: `)).trim();
982
+ const chosenLines = lChoice === '1' ? 1 : 2;
983
+
984
+ if (action === '3') {
985
+ writeHudConfig({ theme: chosenTheme, lines: chosenLines }, options.dryRun);
986
+ console.log(` ${colors.green}✔ Updated ~/.heimdall-hud.json (theme=${chosenTheme}, lines=${chosenLines})${colors.reset}`);
987
+ } else {
988
+ syncHud(options.dryRun, { theme: chosenTheme, lines: chosenLines });
989
+ }
990
+ } finally {
991
+ if (!existingRl) rl.close();
992
+ }
993
+ }
994
+
822
995
  function printHelp() {
823
996
  console.log(`
824
997
  ${colors.bold}${colors.cyan}Heimdall Agent CLI${colors.reset} — Intelligent Multi-Agent Sentinel & Quality Bootstrapper
@@ -835,13 +1008,14 @@ ${colors.bold}PRIMARY SUBCOMMANDS:${colors.reset}
835
1008
  ${colors.green}audit${colors.reset} (or ${colors.dim}--audit${colors.reset}) Audit installed harnesses, active API endpoints, and skill counts
836
1009
  ${colors.green}uninstall${colors.reset} (or ${colors.dim}--uninstall${colors.reset}) Safely remove Heimdall skills and agent personas from all harnesses
837
1010
  ${colors.green}sync-models${colors.reset} (or ${colors.dim}--sync-models${colors.reset}) Probe active proxy/endpoint (e.g. Custom Proxies / API or Custom Vendors) and refresh models.json
1011
+ ${colors.green}hud${colors.reset} (or ${colors.dim}--hud${colors.reset}) Enable, disable, or theme Heimdall HUD (--on | --off | --theme <name> | --lines <1|2>)
838
1012
  ${colors.green}skills${colors.reset} (or ${colors.dim}--skills${colors.reset}) List all canonical skills, categories, and upstream provenance
839
1013
  ${colors.green}update-skill <name|all>${colors.reset} Inspect upstream repository, updates, and bounded review protocol
840
1014
  ${colors.green}help${colors.reset} (or ${colors.dim}--help, -h${colors.reset}) Display this parameter and command reference
841
1015
 
842
1016
  ${colors.bold}SETUP & BOOTSTRAP OPTIONS:${colors.reset}
843
1017
  ${colors.yellow}--profile <name>${colors.reset} Skill profile tier: full (69), minimal (16), security (12), design (14) [default: full]
844
- ${colors.yellow}--agents <targets>${colors.reset} Comma-separated harnesses: claude, gemini, codex, hermes, openclaw, desktop, all [default: all]
1018
+ ${colors.yellow}--agents <targets>${colors.reset} Comma-separated harnesses: claude, gemini, codex, hermes, openclaw, vscode, desktop, all [default: all]
845
1019
  ${colors.yellow}--link / --no-link${colors.reset} Use live NTFS junctions / symlinks vs static copies [default: false in wizard, true recommended]
846
1020
  ${colors.yellow}--clean${colors.reset} Wipe legacy skills from target directory before deploying
847
1021
  ${colors.yellow}-y, --yes${colors.reset} Non-interactive mode (use defaults or provided CLI arguments)
@@ -850,6 +1024,8 @@ ${colors.bold}SETUP & BOOTSTRAP OPTIONS:${colors.reset}
850
1024
  ${colors.yellow}--doctrine-path <file>${colors.reset} Custom file destination for AGENTS.md universal doctrine
851
1025
  ${colors.yellow}--no-tools${colors.reset} Skip deploying bridge tools and CLI shims
852
1026
  ${colors.yellow}--no-doctrine${colors.reset} Skip deploying AGENTS.md universal doctrine
1027
+ ${colors.yellow}--no-hud${colors.reset} Skip configuring Heimdall HUD statusline during install/sync
1028
+ ${colors.yellow}--theme <name>${colors.reset} HUD color theme: night-blue [default], heimdall, claude-warm, titanium
853
1029
 
854
1030
  ${colors.bold}EXAMPLES:${colors.reset}
855
1031
  heimdall # Interactive management hub (audit, sync, uninstall)
@@ -882,6 +1058,11 @@ function parseArgs() {
882
1058
  dryRun: false,
883
1059
  audit: false,
884
1060
  syncModels: false,
1061
+ hud: false,
1062
+ hudEnabled: true,
1063
+ hudOff: false,
1064
+ hudTheme: null,
1065
+ hudLines: null,
885
1066
  listSkills: false,
886
1067
  updateSkill: null,
887
1068
  help: false,
@@ -899,6 +1080,15 @@ function parseArgs() {
899
1080
  else if (arg === 'sync-docs' || arg === '--sync-docs' || arg === 'syncdocs') options.syncDocs = true;
900
1081
  else if (arg === 'uninstall' || arg === '--uninstall') options.uninstall = true;
901
1082
  else if (arg === 'sync-models' || arg === '--sync-models' || arg === 'syncmodels') options.syncModels = true;
1083
+ else if (arg === 'hud' || arg === '--hud') options.hud = true;
1084
+ else if (arg === '--on') options.hudOff = false;
1085
+ else if (arg === '--off') options.hudOff = true;
1086
+ else if (arg === '--no-hud') options.hudEnabled = false;
1087
+ else if ((arg === '--theme' || arg === '--hud-theme') && args[i + 1]) {
1088
+ options.hudTheme = args[++i].toLowerCase();
1089
+ } else if (arg === '--lines' && args[i + 1]) {
1090
+ options.hudLines = parseInt(args[++i], 10);
1091
+ }
902
1092
  else if (arg === 'skills' || arg === '--skills') options.listSkills = true;
903
1093
  else if (arg === 'update-skill' || arg === '--update-skill' || arg === 'updateskill') {
904
1094
  options.updateSkill = args[i + 1] && !args[i + 1].startsWith('-') ? args[++i] : 'all';
@@ -1394,6 +1584,11 @@ async function runSync(options, detected) {
1394
1584
  const mcpSynced = syncMcpServers(detected, options);
1395
1585
  if (mcpSynced) syncedAny = true;
1396
1586
 
1587
+ // Synchronize Heimdall HUD statusline across Claude Code, Antigravity (agy), and Codex CLI
1588
+ if (options.hudEnabled !== false) {
1589
+ if (syncHud(options.dryRun, { theme: options.hudTheme, lines: options.hudLines })) syncedAny = true;
1590
+ }
1591
+
1397
1592
  // Refresh bridge tools & shims
1398
1593
  const activeToolsDir = options.toolsDir || detected.pathCandidates[0];
1399
1594
  if (activeToolsDir && fs.existsSync(activeToolsDir)) {
@@ -1436,6 +1631,10 @@ function runAudit(options) {
1436
1631
  console.log(` OpenClaw Agent: ${detected.tools.openclaw ? colors.green + detected.tools.openclaw + colors.reset : colors.dim + getOpenClawDir() + colors.reset}`);
1437
1632
  console.log(` Endpoint: ${colors.cyan}${detected.endpoints.openclaw}${colors.reset}`);
1438
1633
  }
1634
+ if (detected.tools.vscode || fs.existsSync(getVSCodeUserDir()) || fs.existsSync(getCopilotDir())) {
1635
+ console.log(` VS Code (Copilot): ${detected.tools.vscode ? colors.green + detected.tools.vscode + colors.reset : colors.dim + getVSCodeUserDir() + colors.reset}`);
1636
+ console.log(` Endpoint: ${colors.cyan}${detected.endpoints.vscode}${colors.reset}`);
1637
+ }
1439
1638
  console.log(` Claude Desktop: ${detected.tools.claudeDesktop ? colors.green + detected.tools.claudeDesktop + colors.reset : colors.dim + 'Not found' + colors.reset}`);
1440
1639
  console.log('');
1441
1640
 
@@ -1701,6 +1900,11 @@ async function runUninstall(options, detected, existingRl = null) {
1701
1900
  } catch {}
1702
1901
  }
1703
1902
 
1903
+ // Unregister HUD statuslines if present
1904
+ disableClaudeStatusLine(options.dryRun);
1905
+ disableAntigravityStatusLine(options.dryRun);
1906
+ disableCodexStatusLine(options.dryRun);
1907
+
1704
1908
  console.log(`\n${colors.bold}${colors.green}Uninstallation Complete:${colors.reset} Removed ${totalRemovedSkills} skill bindings and ${totalRemovedAgents} agent personas across harnesses.\n`);
1705
1909
  }
1706
1910
 
@@ -1718,6 +1922,7 @@ async function runPostInstallMenu(options, detected) {
1718
1922
  { label: 'Audit Environment & Health Check', action: 'audit' },
1719
1923
  { label: 'Fast Sync Skills & Agents (1-sec zero-drift)', action: 'sync' },
1720
1924
  ...(hasCustomApi ? [{ label: 'Refresh Dynamic Models (sync-models)', action: 'sync-models' }] : []),
1925
+ { label: 'Configure / Toggle Heimdall HUD Statusline', action: 'hud' },
1721
1926
  { label: 'Uninstall Heimdall', action: 'uninstall' },
1722
1927
  { label: 'Reinstall / Reconfigure Profile & Targets', action: 'reinstall' },
1723
1928
  { label: 'Exit', action: 'exit' }
@@ -1745,6 +1950,8 @@ async function runPostInstallMenu(options, detected) {
1745
1950
  await runSync(options, currentDetected);
1746
1951
  } else if (selected === 'sync-models') {
1747
1952
  await syncModelsFromEndpoint();
1953
+ } else if (selected === 'hud') {
1954
+ await runHudInteractive(options, rl);
1748
1955
  } else if (selected === 'uninstall') {
1749
1956
  await runUninstall(options, currentDetected, rl);
1750
1957
  } else if (selected === 'reinstall') {
@@ -1783,6 +1990,8 @@ async function runInteractive(options, detected) {
1783
1990
  console.log(` ${colors.dim}Endpoint: ${detected.endpoints.hermes}${colors.reset}`);
1784
1991
  console.log(` [${detected.tools.openclaw ? colors.green + '✔' : colors.dim + ' '}${colors.reset}] OpenClaw ${detected.tools.openclaw ? '(' + detected.tools.openclaw + ')' : '(Not found)'}`);
1785
1992
  console.log(` ${colors.dim}Endpoint: ${detected.endpoints.openclaw}${colors.reset}`);
1993
+ console.log(` [${detected.tools.vscode ? colors.green + '✔' : colors.dim + ' '}${colors.reset}] VS Code (Copilot) ${detected.tools.vscode ? '(' + detected.tools.vscode + ')' : '(Not found)'}`);
1994
+ console.log(` ${colors.dim}Endpoint: ${detected.endpoints.vscode}${colors.reset}`);
1786
1995
  console.log(` [${detected.tools.claudeDesktop ? colors.green + '✔' : colors.dim + ' '}${colors.reset}] Claude Desktop ${detected.tools.claudeDesktop ? '(' + detected.tools.claudeDesktop + ')' : '(Not found)'}`);
1787
1996
  console.log('');
1788
1997
 
@@ -1793,18 +2002,20 @@ async function runInteractive(options, detected) {
1793
2002
  console.log(` 4. OpenAI Codex CLI only`);
1794
2003
  console.log(` 5. Hermes Agent only`);
1795
2004
  console.log(` 6. OpenClaw only`);
1796
- console.log(` 7. Claude Desktop only (MCP & Playbooks)`);
1797
- console.log(` 8. Custom Multi-Selection (e.g. Claude + Hermes)`);
2005
+ console.log(` 7. VS Code (Copilot) only`);
2006
+ console.log(` 8. Claude Desktop only (MCP & Playbooks)`);
2007
+ console.log(` 9. Custom Multi-Selection (e.g. Claude + VS Code)`);
1798
2008
 
1799
- const tChoice = await rl.question(`Choose installation targets [1-8, default: 1]: `);
2009
+ const tChoice = await rl.question(`Choose installation targets [1-9, default: 1]: `);
1800
2010
  if (tChoice === '2') options.agents = ['claude'];
1801
2011
  else if (tChoice === '3') options.agents = ['gemini'];
1802
2012
  else if (tChoice === '4') options.agents = ['codex'];
1803
2013
  else if (tChoice === '5') options.agents = ['hermes'];
1804
2014
  else if (tChoice === '6') options.agents = ['openclaw'];
1805
- else if (tChoice === '7') options.agents = ['desktop'];
1806
- else if (tChoice === '8') {
1807
- const custom = await rl.question(`Enter comma-separated targets (claude, gemini, codex, hermes, openclaw, desktop): `);
2015
+ else if (tChoice === '7') options.agents = ['vscode'];
2016
+ else if (tChoice === '8') options.agents = ['desktop'];
2017
+ else if (tChoice === '9') {
2018
+ const custom = await rl.question(`Enter comma-separated targets (claude, gemini, codex, hermes, openclaw, vscode, desktop): `);
1808
2019
  options.agents = custom.split(',').map(s => s.trim().toLowerCase());
1809
2020
  } else {
1810
2021
  options.agents = ['all'];
@@ -1879,6 +2090,17 @@ async function runInteractive(options, detected) {
1879
2090
  options.doctrinePath = detected.doctrineCandidates[0];
1880
2091
  options.doctrine = true;
1881
2092
  }
2093
+
2094
+ // Optional Heimdall HUD statusline prompt
2095
+ console.log(`\n${colors.yellow}Heimdall HUD Statusline (Claude Code, Antigravity, Codex):${colors.reset}`);
2096
+ const hudChoice = (await rl.question(`Enable Heimdall HUD statusline? (y/n, default: y): `)).trim().toLowerCase();
2097
+ options.hudEnabled = hudChoice !== 'n' && hudChoice !== 'no';
2098
+ if (options.hudEnabled) {
2099
+ console.log(` 1. night-blue [Default] 2. heimdall 3. claude-warm 4. titanium`);
2100
+ const htChoice = (await rl.question(`Choose HUD theme [1-4, default: 1]: `)).trim();
2101
+ const htIdx = parseInt(htChoice, 10);
2102
+ options.hudTheme = (htIdx >= 1 && htIdx <= HUD_THEMES.length) ? HUD_THEMES[htIdx - 1] : 'night-blue';
2103
+ }
1882
2104
  } finally {
1883
2105
  rl.close();
1884
2106
  }
@@ -2029,6 +2251,23 @@ async function main() {
2029
2251
  process.exit(0);
2030
2252
  }
2031
2253
 
2254
+ if (options.hud) {
2255
+ if (!options.hudOff && !options.hudTheme && !options.hudLines && !options.yes && process.stdin.isTTY && !process.argv.includes('--on')) {
2256
+ await runHudInteractive(options);
2257
+ } else {
2258
+ console.log(`${colors.bold}${colors.cyan}=== Heimdall HUD Statusline Sync ===${colors.reset}\n`);
2259
+ const updated = syncHud(options.dryRun, {
2260
+ off: options.hudOff,
2261
+ theme: options.hudTheme,
2262
+ lines: options.hudLines
2263
+ });
2264
+ if (!updated) {
2265
+ console.log(` ${colors.green}✔${colors.reset} HUD statusline already up to date across detected harnesses.`);
2266
+ }
2267
+ }
2268
+ process.exit(0);
2269
+ }
2270
+
2032
2271
  if (options.syncDocs) {
2033
2272
  const res = syncCatalogCounts(__dirname, options.dryRun);
2034
2273
  if (res) {
@@ -2118,7 +2357,14 @@ async function main() {
2118
2357
  // 3. Clean and deploy skills
2119
2358
  for (const [agent, targetDir] of activeDestinations) {
2120
2359
  const rootDir = getAgentRootDir(agent);
2121
- if (!rootDir || !fs.existsSync(rootDir)) continue;
2360
+ if (!rootDir) continue;
2361
+ if (!fs.existsSync(rootDir)) {
2362
+ if (agent === 'vscode' && !options.dryRun) {
2363
+ fs.mkdirSync(rootDir, { recursive: true });
2364
+ } else if (agent !== 'vscode') {
2365
+ continue;
2366
+ }
2367
+ }
2122
2368
 
2123
2369
  console.log(`\n-> Deploying to ${colors.bold}${agent.toUpperCase()}${colors.reset} (${targetDir})...`);
2124
2370
  if (!options.dryRun && !fs.existsSync(targetDir)) {
@@ -2286,6 +2532,12 @@ async function main() {
2286
2532
  }
2287
2533
  }
2288
2534
 
2535
+ // 7. Configure Heimdall HUD Statusline if enabled
2536
+ if (options.hudEnabled !== false) {
2537
+ console.log(`\n-> Configuring Heimdall HUD Statusline...`);
2538
+ syncHud(options.dryRun, { theme: options.hudTheme, lines: options.hudLines });
2539
+ }
2540
+
2289
2541
  console.log(`\n${colors.bold}${colors.green}=== Heimdall Installation Complete! ===${colors.reset}\n`);
2290
2542
  }
2291
2543
 
@@ -0,0 +1,283 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Heimdall HUD — Cross-Harness Terminal Statusline Renderer
4
+ *
5
+ * Normalizes session telemetry JSON piped to stdin by:
6
+ * - Google Antigravity CLI (agy)
7
+ * - Claude Code CLI
8
+ *
9
+ * Supports 2-line telemetry + truecolor theme presets:
10
+ * heimdall (default), claude-warm, night-blue, titanium
11
+ *
12
+ * Zero external dependencies; always exits 0 to avoid CLI circuit breakers.
13
+ */
14
+
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import { execFileSync } from 'node:child_process';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ const RESET = '\x1b[0m';
22
+ const BOLD = '\x1b[1m';
23
+ const DIM = '\x1b[2m';
24
+
25
+ function fg(r, g, b) {
26
+ return `\x1b[38;2;${r};${g};${b}m`;
27
+ }
28
+
29
+ export const THEMES = {
30
+ heimdall: {
31
+ model: fg(56, 189, 248), // sky cyan
32
+ dir: fg(226, 232, 240), // slate 200
33
+ branch: fg(96, 165, 250), // blue 400
34
+ dirty: fg(251, 191, 36), // amber 400
35
+ cost: fg(74, 222, 128), // green 400
36
+ state: fg(192, 132, 252), // purple 400
37
+ sep: fg(100, 116, 139), // slate 500
38
+ ok: fg(74, 222, 128),
39
+ warn: fg(250, 204, 21),
40
+ crit: fg(248, 113, 113)
41
+ },
42
+ 'claude-warm': {
43
+ model: fg(224, 122, 95), // terracotta
44
+ dir: fg(244, 241, 222), // warm cream
45
+ branch: fg(242, 204, 143), // sand gold
46
+ dirty: fg(245, 158, 11), // warm amber
47
+ cost: fg(129, 178, 154), // sage green
48
+ state: fg(224, 122, 95),
49
+ sep: fg(140, 122, 107), // mutedtaupe
50
+ ok: fg(129, 178, 154),
51
+ warn: fg(242, 204, 143),
52
+ crit: fg(231, 111, 81)
53
+ },
54
+ 'night-blue': {
55
+ model: fg(96, 165, 250), // electric blue
56
+ dir: fg(219, 234, 254), // ice blue
57
+ branch: fg(167, 139, 250), // soft indigo
58
+ dirty: fg(251, 191, 36),
59
+ cost: fg(52, 211, 153), // mint
60
+ state: fg(125, 211, 252), // sky 300
61
+ sep: fg(71, 85, 105),
62
+ ok: fg(52, 211, 153),
63
+ warn: fg(251, 191, 36),
64
+ crit: fg(248, 113, 113)
65
+ },
66
+ titanium: {
67
+ model: fg(248, 250, 252), // bright silver
68
+ dir: fg(203, 213, 225), // slate 300
69
+ branch: fg(148, 163, 184), // slate 400
70
+ dirty: fg(251, 191, 36),
71
+ cost: fg(56, 189, 248), // steel cyan
72
+ state: fg(148, 163, 184),
73
+ sep: fg(71, 85, 105),
74
+ ok: fg(148, 163, 184),
75
+ warn: fg(251, 191, 36),
76
+ crit: fg(239, 68, 68)
77
+ }
78
+ };
79
+
80
+ /**
81
+ * Formats a token count into a compact human-readable string (e.g. 1M, 200K).
82
+ */
83
+ export function formatTokens(n) {
84
+ if (!Number.isFinite(n) || n <= 0) return '';
85
+ if (n >= 1_000_000) {
86
+ const m = n / 1_000_000;
87
+ return `${m.toFixed(1).replace(/\.0$/, '')}M`;
88
+ }
89
+ if (n >= 1_000) return `${Math.round(n / 1_000)}K`;
90
+ return String(Math.round(n));
91
+ }
92
+
93
+ /**
94
+ * Formats milliseconds into a compact duration string (e.g. 2m 27s).
95
+ */
96
+ export function formatDuration(ms) {
97
+ if (!Number.isFinite(ms) || ms <= 0) return '';
98
+ const totalSec = Math.floor(ms / 1000);
99
+ if (totalSec < 60) return `${totalSec}s`;
100
+ const mins = Math.floor(totalSec / 60);
101
+ const secs = totalSec % 60;
102
+ if (mins < 60) return `${mins}m ${secs}s`;
103
+ const hrs = Math.floor(mins / 60);
104
+ return `${hrs}h ${mins % 60}m`;
105
+ }
106
+
107
+ /**
108
+ * Resolves HUD theme & line-count config from options, env, or ~/.heimdall-hud.json.
109
+ */
110
+ export function resolveHudConfig(options = {}, homeDir = os.homedir()) {
111
+ let fileCfg = {};
112
+ const cfgPath = path.join(homeDir, '.heimdall-hud.json');
113
+ if (fs.existsSync(cfgPath)) {
114
+ try {
115
+ fileCfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
116
+ } catch { /* ignore invalid JSON */ }
117
+ }
118
+ const themeName = options.theme || process.env.HEIMDALL_HUD_THEME || fileCfg.theme || 'night-blue';
119
+ const lines = Number(options.lines || process.env.HEIMDALL_HUD_LINES || fileCfg.lines || 2);
120
+ return {
121
+ themeName: THEMES[themeName] ? themeName : 'night-blue',
122
+ theme: THEMES[themeName] || THEMES['night-blue'],
123
+ lines: lines === 1 ? 1 : 2
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Builds an 8-block context saturation bar color-coded to Heimdall's 75% sentinel threshold.
129
+ */
130
+ export function renderContextBar(pct, width = 8, theme = THEMES['night-blue']) {
131
+ const clamped = Math.max(0, Math.min(100, Number(pct) || 0));
132
+ const filled = Math.round((clamped / 100) * width);
133
+ const empty = Math.max(0, width - filled);
134
+ const color = clamped >= 75 ? theme.crit : clamped >= 50 ? theme.warn : theme.ok;
135
+ return `${color}[${'█'.repeat(filled)}${'░'.repeat(empty)}] ${Math.round(clamped)}%${RESET}`;
136
+ }
137
+
138
+ function resolveGitInfo(cwd) {
139
+ if (!cwd) return { branch: null, dirtyCount: 0 };
140
+ try {
141
+ const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
142
+ cwd,
143
+ encoding: 'utf8',
144
+ timeout: 400,
145
+ stdio: ['ignore', 'pipe', 'ignore']
146
+ }).trim() || null;
147
+
148
+ let dirtyCount = 0;
149
+ if (branch) {
150
+ const status = execFileSync('git', ['status', '--porcelain'], {
151
+ cwd,
152
+ encoding: 'utf8',
153
+ timeout: 400,
154
+ stdio: ['ignore', 'pipe', 'ignore']
155
+ });
156
+ dirtyCount = status ? status.split(/\r?\n/).filter(Boolean).length : 0;
157
+ }
158
+ return { branch, dirtyCount };
159
+ } catch {
160
+ return { branch: null, dirtyCount: 0 };
161
+ }
162
+ }
163
+
164
+ function formatStateBadge(state, theme) {
165
+ if (!state) return '';
166
+ const map = {
167
+ idle: `${DIM}● idle${RESET}`,
168
+ thinking: `${theme.state}◐ thinking${RESET}`,
169
+ working: `${theme.model}⟳ working${RESET}`,
170
+ tool_use: `${theme.warn}⚙ tool${RESET}`,
171
+ error: `${theme.crit}✖ error${RESET}`
172
+ };
173
+ return map[state] || `${DIM}${state}${RESET}`;
174
+ }
175
+
176
+ /**
177
+ * Normalizes Claude Code / Antigravity telemetry payloads and renders the 1- or 2-line HUD.
178
+ */
179
+ export function renderHud(payload = {}, options = {}) {
180
+ const { theme, lines } = resolveHudConfig(options);
181
+ const sep = ` ${theme.sep}│${RESET} `;
182
+
183
+ const modelName =
184
+ (typeof payload.model === 'object' ? payload.model?.display_name || payload.model?.id : payload.model) ||
185
+ 'Agent';
186
+
187
+ const currentDir = payload.workspace?.current_dir || payload.cwd || process.cwd();
188
+ const dirName = path.basename(currentDir) || currentDir;
189
+
190
+ const gitInfo = options.skipGit ? { branch: null, dirtyCount: 0 } : resolveGitInfo(currentDir);
191
+ const branch = payload.workspace?.branch || gitInfo.branch;
192
+ const dirtyCount = typeof payload.workspace?.dirty_count === 'number'
193
+ ? payload.workspace.dirty_count
194
+ : gitInfo.dirtyCount;
195
+
196
+ const pct = payload.context_window?.used_percentage ?? 0;
197
+ const ctxSize = payload.context_window?.context_window_size || payload.context_window?.size || 0;
198
+ const ctxSizeLabel = formatTokens(ctxSize);
199
+ const inTok = formatTokens(payload.context_window?.total_input_tokens);
200
+ const outTok = formatTokens(payload.context_window?.total_output_tokens);
201
+ const duration = formatDuration(payload.cost?.total_duration_ms);
202
+
203
+ const columns = payload.terminal?.columns || process.stdout.columns || 120;
204
+ const compact = columns < 80;
205
+
206
+ const bar = renderContextBar(pct, compact ? 6 : 8, theme);
207
+ const ctxSegment = ctxSizeLabel && !compact ? `${bar} ${DIM}(${ctxSizeLabel})${RESET}` : bar;
208
+
209
+ const locParts = [`${theme.dir}${dirName}${RESET}`];
210
+ if (branch) {
211
+ const dirtySuffix = dirtyCount > 0 ? ` ${theme.dirty}*${dirtyCount}${RESET}` : '';
212
+ locParts.push(`${theme.branch}(${branch}${dirtySuffix}${theme.branch})${RESET}`);
213
+ }
214
+ const locSegment = locParts.join(' ');
215
+
216
+ if (lines === 1) {
217
+ const single = [`${BOLD}${theme.model}${modelName}${RESET}`, locSegment, ctxSegment];
218
+ if (payload.agent_state) single.push(formatStateBadge(payload.agent_state, theme));
219
+ if (typeof payload.cost?.total_cost_usd === 'number' && !compact) {
220
+ single.push(`${theme.cost}$${payload.cost.total_cost_usd.toFixed(2)}${RESET}`);
221
+ }
222
+ if (payload.vim?.mode && !compact) single.push(`${theme.state}[${payload.vim.mode}]${RESET}`);
223
+ return single.join(sep);
224
+ }
225
+
226
+ // Line 1: Model │ Context Bar │ State │ Cost │ Vim
227
+ const line1 = [`${BOLD}${theme.model}${modelName}${RESET}`, ctxSegment];
228
+ if (payload.agent_state) line1.push(formatStateBadge(payload.agent_state, theme));
229
+ if (typeof payload.cost?.total_cost_usd === 'number') {
230
+ line1.push(`${theme.cost}$${payload.cost.total_cost_usd.toFixed(2)}${RESET}`);
231
+ }
232
+ if (payload.vim?.mode && !compact) {
233
+ line1.push(`${theme.state}[${payload.vim.mode}]${RESET}`);
234
+ }
235
+
236
+ // Line 2: Workspace (branch *dirty) │ Tokens │ Duration
237
+ const line2 = [locSegment];
238
+ if (inTok || outTok) {
239
+ line2.push(`${DIM}↑${inTok || '0'} ↓${outTok || '0'}${RESET}`);
240
+ }
241
+ if (duration && !compact) {
242
+ line2.push(`${DIM}⏱ ${duration}${RESET}`);
243
+ }
244
+
245
+ return `${line1.join(sep)}\n${line2.join(sep)}`;
246
+ }
247
+
248
+ function readStdinSafe() {
249
+ try {
250
+ if (process.stdin.isTTY) return '';
251
+ return fs.readFileSync(0, 'utf8');
252
+ } catch {
253
+ return '';
254
+ }
255
+ }
256
+
257
+ const isMain = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
258
+ if (isMain) {
259
+ const args = process.argv.slice(2);
260
+ if (args.includes('--preview')) {
261
+ const sample = {
262
+ agent_state: 'working',
263
+ model: 'Gemini 4 Hydrogen (Medium)',
264
+ workspace: { current_dir: process.cwd(), branch: 'main', dirty_count: 2 },
265
+ context_window: { used_percentage: 42, context_window_size: 1048576, total_input_tokens: 45200, total_output_tokens: 3100 },
266
+ cost: { total_cost_usd: 0.14, total_duration_ms: 147000 },
267
+ terminal: { columns: 120 }
268
+ };
269
+ for (const name of Object.keys(THEMES)) {
270
+ process.stdout.write(`${BOLD}Theme: ${name}${RESET}\n${renderHud(sample, { theme: name, skipGit: true })}\n\n`);
271
+ }
272
+ process.exit(0);
273
+ }
274
+
275
+ try {
276
+ const raw = readStdinSafe().trim();
277
+ const payload = raw ? JSON.parse(raw) : {};
278
+ process.stdout.write(renderHud(payload) + '\n');
279
+ } catch {
280
+ process.stdout.write(`${THEMES['night-blue'].model}Heimdall HUD${RESET}\n`);
281
+ }
282
+ process.exit(0);
283
+ }