nexakit 0.8.3 → 0.10.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
@@ -40,6 +40,10 @@ npx nexakit setup --reponer <skill> --apply # Devolver una skill global que qui
40
40
  ~/.nexakit/nexakit revision --disponibles --principal <ia> # Ver IA revisoras certificadas
41
41
  ~/.nexakit/nexakit modelo # Ver catálogo real de modelos y esfuerzos
42
42
  ~/.nexakit/nexakit ahorro # Cuánta salida de comandos recortó nexakit-ahorro
43
+ ~/.nexakit/nexakit codex auditar # Revisar contexto y recomendaciones de Codex
44
+ ~/.nexakit/nexakit codex agentes # Ver los cuatro niveles y seis especialistas de Codex
45
+ ~/.nexakit/nexakit codex consumo # Contadores registrados por los hooks de Codex
46
+ ~/.nexakit/nexakit codex recomendar --tarea "Escribe pruebas para el parser" # Modelo y esfuerzo sugeridos
43
47
  ~/.nexakit/nexakit lecciones # Correcciones, lecciones guardadas y pendientes
44
48
  npx nexakit memoria allow-dir <bóveda> --apply # Permitir a Claude Code abrir la memoria desde el proyecto
45
49
  ```
@@ -65,6 +69,18 @@ El catálogo incluido contiene **10 skills** con revisión de origen y hashes SH
65
69
 
66
70
  ## Más herramientas
67
71
 
72
+ **Codex:** `nexakit codex` audita contexto, prepara la barra nativa y los hooks de
73
+ medición y recomendaciones visibles, recorta salidas con un ejecutor explícito
74
+ y compara muestras de consumo. La preparación
75
+ muestra una vista previa; la activación se revisa por separado y respeta tu
76
+ configuración. [Guía de ahorro y consumo](docs/guias/codex-ahorro.md).
77
+
78
+ `nexakit codex agentes` prepara el equipo nativo: cuatro niveles y seis
79
+ especialistas con modelos del catálogo local, vista previa y actualización
80
+ con respaldos. [Equipo y delegación en Codex](docs/guias/codex-agentes.md).
81
+
82
+ **Antigravity CLI (`agy`):** `nexakit antigravity preparar` genera un plugin válido (`plugin.json`, `hooks.json`, los 10 `agents/*.md` de `niveles`, `settings.statusline.json` y `README.md`) con activación manual para la barra `statusLine` (`nexakit antigravity barra`), recomendación al enviar (`PreInvocation`), `guardarrailes`, `ahorro` (`nexakit antigravity ejecutar`), `lecciones` y avisos de `sesión` (60 % / 80 % de contexto y 70 % / 90 % de cuota); `nexakit antigravity agentes` instala o actualiza los 10 perfiles directamente en `~/.gemini/config/agents/` o `.agents/agents/`.
83
+
68
84
  Los mods de Claude Code se instalan *dentro* de Claude Code: `/plugin marketplace add Jcabr3ra1/nexakit` y luego `/plugin install <nombre>@agent-toolkit` para `niveles`, `nexakit-modelo`, `nexakit-sesion`, `nexakit-ahorro`, `nexakit-lecciones` y `nexakit-guardarrailes` ([paso 7 de la guía](docs/guias/guia-de-comandos.md#7-instala-los-plugins-y-mods-solo-claude-code)).
69
85
 
70
86
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "nexakit",
3
- "version": "0.8.3",
3
+ "version": "0.10.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "nexakit",
9
- "version": "0.8.3",
9
+ "version": "0.10.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/client": "^2.4.0",
package/bin/nexakit.js CHANGED
@@ -1,13 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import { loadWithDependencyCheck } from '../src/missing-dependencies.js';
3
- const cli = await loadWithDependencyCheck(() => import('../src/toolkit-cli.js'));
4
- if (cli) {
5
- process.stdout.on('error', () => {});
6
- process.stderr.on('error', () => {});
7
- process.exitCode = await cli.runToolkitCli(process.argv.slice(2), {
8
- out: t => process.stdout.write(t),
9
- err: t => process.stderr.write(t),
10
- input: process.stdin,
11
- output: process.stdout
12
- });
3
+ const args = process.argv.slice(2);
4
+ const io = {
5
+ out: t => process.stdout.write(t),
6
+ err: t => process.stderr.write(t),
7
+ input: process.stdin,
8
+ output: process.stdout
9
+ };
10
+ process.stdout.on('error', () => {});
11
+ process.stderr.on('error', () => {});
12
+
13
+ if (args[0] === 'antigravity' && ['barra', 'hook', 'ejecutar'].includes(args[1])) {
14
+ const cli = await loadWithDependencyCheck(() => import('../src/antigravity-command.js'));
15
+ if (cli) process.exitCode = await cli.runAntigravityCommand(args.slice(1), io);
16
+ } else {
17
+ const cli = await loadWithDependencyCheck(() => import('../src/toolkit-cli.js'));
18
+ if (cli) process.exitCode = await cli.runToolkitCli(args, io);
13
19
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexakit",
3
- "version": "0.8.3",
3
+ "version": "0.10.0",
4
4
  "description": "Asistente por pasos de skills verificadas por SHA-256, coordinación entre agentes y memoria por proyecto para Claude Code y Codex.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,8 +1,52 @@
1
1
  import fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
4
5
 
5
6
  const DIA_MS = 24 * 60 * 60 * 1000;
7
+ const MAX_REGISTRO_BYTES = 1024 * 1024;
8
+
9
+ async function directorioSeguro(target) {
10
+ const absolute = path.resolve(target);
11
+ let current = path.parse(absolute).root;
12
+ for (const part of absolute.slice(current.length).split(path.sep).filter(Boolean)) {
13
+ current = path.join(current, part);
14
+ const stat = await fs.lstat(current);
15
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Directorio inseguro');
16
+ }
17
+ }
18
+
19
+ async function leerFuente(target) {
20
+ let handle;
21
+ try {
22
+ await directorioSeguro(path.dirname(target));
23
+ const before = await fs.lstat(target);
24
+ if (!before.isFile() || before.nlink !== 1 || before.size > MAX_REGISTRO_BYTES) return [];
25
+ handle = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
26
+ const opened = await handle.stat();
27
+ if (!opened.isFile() || opened.nlink !== 1 || opened.size > MAX_REGISTRO_BYTES ||
28
+ opened.dev !== before.dev || opened.ino !== before.ino) return [];
29
+ // Un byte adicional detecta crecimiento sin una lectura sin límite.
30
+ const buffer = Buffer.alloc(MAX_REGISTRO_BYTES + 1);
31
+ let size = 0;
32
+ while (size < buffer.length) {
33
+ const { bytesRead } = await handle.read(buffer, size, buffer.length - size, size);
34
+ if (!bytesRead) break;
35
+ size += bytesRead;
36
+ }
37
+ const after = await handle.stat();
38
+ await directorioSeguro(path.dirname(target));
39
+ const final = await fs.lstat(target);
40
+ if (size > MAX_REGISTRO_BYTES || after.nlink !== 1 || !final.isFile() || final.nlink !== 1 ||
41
+ final.dev !== opened.dev || final.ino !== opened.ino) return [];
42
+ return leerRegistros(buffer.subarray(0, size).toString('utf8'));
43
+ } catch {
44
+ // Una fuente ausente o insegura no impide consultar la otra.
45
+ return [];
46
+ } finally {
47
+ await handle?.close();
48
+ }
49
+ }
6
50
 
7
51
  function resumir(registros) {
8
52
  const caracteres = registros.reduce((suma, r) => suma + (r.antes - r.despues), 0);
@@ -35,13 +79,18 @@ export async function runAhorroCommand(argv, { out, err }, options = {}) {
35
79
  }
36
80
  const home = options.homeDirectory ?? os.homedir();
37
81
  const ahora = options.now ?? Date.now();
38
- let texto = null;
82
+ const fuentes = new Set([path.resolve(home, '.nexakit', 'ahorro.jsonl')]);
39
83
  try {
40
- texto = await fs.readFile(path.join(home, '.nexakit', 'ahorro.jsonl'), 'utf8');
84
+ // El temporal del sistema puede ser un alias (por ejemplo /var en macOS).
85
+ const temporal = await fs.realpath(options.tempDirectory ?? os.tmpdir());
86
+ const uid = process.getuid?.() ?? 'user';
87
+ fuentes.add(path.join(temporal, `nexakit-codex-${uid}`, '.nexakit', 'ahorro.jsonl'));
88
+ fuentes.add(path.join(temporal, `nexakit-antigravity-${uid}`, '.nexakit', 'ahorro.jsonl'));
41
89
  } catch {
42
- texto = null;
90
+ // No se crean directorios al consultar métricas.
43
91
  }
44
- const registros = texto === null ? [] : leerRegistros(texto);
92
+ const registros = [];
93
+ for (const fuente of fuentes) registros.push(...await leerFuente(fuente));
45
94
  const resumen = {
46
95
  ultimos7Dias: resumir(registros.filter((r) => r.fecha >= ahora - 7 * DIA_MS)),
47
96
  total: resumir(registros),
@@ -52,7 +101,7 @@ export async function runAhorroCommand(argv, { out, err }, options = {}) {
52
101
  }
53
102
  if (registros.length === 0) {
54
103
  await out(
55
- 'Aún no hay recortes registrados. El registro lo escribe el mod nexakit-ahorro cuando recorta una salida larga de Bash.\n',
104
+ 'Aún no hay recortes registrados. Los escriben el mod nexakit-ahorro de Claude y nexakit codex ejecutar al recortar salidas largas.\n',
56
105
  );
57
106
  return 0;
58
107
  }
@@ -0,0 +1,242 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import fs from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const SOURCE_AGENTS_DIR = fileURLToPath(new URL('../plugins/niveles/agents', import.meta.url));
9
+ const MAX_BYTES = 128 * 1024;
10
+
11
+ export const ANTIGRAVITY_AGENT_NAMES = Object.freeze([
12
+ 'nivel-ligero',
13
+ 'nivel-normal',
14
+ 'nivel-exigente',
15
+ 'nivel-alto',
16
+ 'investigador',
17
+ 'revisor-de-calidad',
18
+ 'cierre-de-memoria',
19
+ 'subir-al-repo',
20
+ 'sincronizador-docs',
21
+ 'cazador-de-flakes',
22
+ ]);
23
+
24
+ const MODEL_MAP = Object.freeze({
25
+ 'nivel-ligero': { model: 'flash_lite', effort: 'low' },
26
+ 'nivel-normal': { model: 'flash', effort: 'medium' },
27
+ 'nivel-exigente': { model: 'pro', effort: 'high' },
28
+ 'nivel-alto': { model: 'pro', effort: 'max' },
29
+ 'revisor-de-calidad': { model: 'pro', effort: 'high' },
30
+ });
31
+
32
+ const TOOL_MAP = Object.freeze({
33
+ Bash: 'run_command',
34
+ Read: 'read_file',
35
+ Grep: 'run_command',
36
+ Glob: 'run_command',
37
+ Edit: 'edit_file',
38
+ MultiEdit: 'edit_file',
39
+ Write: 'write_file',
40
+ WebSearch: 'search_web',
41
+ WebFetch: 'search_web',
42
+ });
43
+
44
+ const EXTRA_TOOLS = Object.freeze({
45
+ 'cierre-de-memoria': ['call_mcp_tool', 'list_resources', 'read_resource'],
46
+ });
47
+
48
+ function parseSimpleFrontmatter(raw) {
49
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/u.exec(raw);
50
+ if (!match) throw new Error('Frontmatter de agente inválido.');
51
+ const fields = {};
52
+ for (const line of match[1].split(/\r?\n/u)) {
53
+ const colon = line.indexOf(':');
54
+ if (colon <= 0) continue;
55
+ fields[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
56
+ }
57
+ return { fields, body: match[2] };
58
+ }
59
+
60
+ function mapTools(rawTools, agentName) {
61
+ if (!rawTools) return [];
62
+ const mapped = [];
63
+ const seen = new Set();
64
+ const push = (tool) => {
65
+ if (tool && !seen.has(tool)) {
66
+ seen.add(tool);
67
+ mapped.push(tool);
68
+ }
69
+ };
70
+ for (const token of rawTools.split(',').map((s) => s.trim()).filter(Boolean)) {
71
+ if (token === 'Skill') continue;
72
+ push(TOOL_MAP[token]);
73
+ }
74
+ for (const extra of EXTRA_TOOLS[agentName] ?? []) push(extra);
75
+ return mapped;
76
+ }
77
+
78
+ function adaptText(text) {
79
+ return String(text ?? '')
80
+ .replaceAll('(haiku, low)', '(flash_lite, low)')
81
+ .replaceAll('(sonnet, medium)', '(flash, medium)')
82
+ .replaceAll('(sonnet, high)', '(pro, high)')
83
+ .replaceAll('(opus, high)', '(pro, max)')
84
+ .replaceAll('(herramienta Skill)', '(con read_file)')
85
+ .replaceAll('CLAUDE.md, AGENTS.md', 'GEMINI.md, CLAUDE.md, AGENTS.md');
86
+ }
87
+
88
+ function renderAgentMarkdown(name, sourceRaw) {
89
+ const { fields, body } = parseSimpleFrontmatter(sourceRaw);
90
+ const spec = MODEL_MAP[name] ?? { model: 'flash', effort: fields.effort || 'medium' };
91
+ const tools = mapTools(fields.tools, name);
92
+ const lines = [
93
+ '---',
94
+ `name: ${name}`,
95
+ `description: ${adaptText(fields.description || '')}`,
96
+ `model: ${spec.model}`,
97
+ `effort: ${spec.effort}`,
98
+ ];
99
+ if (fields.maxTurns) lines.push(`maxSteps: ${fields.maxTurns}`);
100
+ if (tools.length) {
101
+ lines.push('tools:');
102
+ for (const tool of tools) lines.push(` - ${tool}`);
103
+ }
104
+ lines.push('---', '');
105
+ return `${lines.join('\n')}${adaptText(body).trimStart()}`;
106
+ }
107
+
108
+ /** Render all 10 NexaKit `niveles` agents adapted for Antigravity (`agy`). */
109
+ export async function renderAntigravityAgents({ sourceDirectory = SOURCE_AGENTS_DIR } = {}) {
110
+ const agents = [];
111
+ for (const name of ANTIGRAVITY_AGENT_NAMES) {
112
+ const filename = `${name}.md`;
113
+ const raw = await fs.readFile(path.join(sourceDirectory, filename), 'utf8');
114
+ agents.push({ name, filename, content: renderAgentMarkdown(name, raw) });
115
+ }
116
+ return agents;
117
+ }
118
+
119
+ const digest = (text) => createHash('sha256').update(text).digest('hex');
120
+
121
+ async function statOrNull(target) {
122
+ try {
123
+ return await fs.lstat(target);
124
+ } catch (error) {
125
+ if (error.code === 'ENOENT') return null;
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ async function inspectTargetFile(target, expectedContent) {
131
+ const stat = await statOrNull(target);
132
+ if (!stat) return { state: 'falta', size: null };
133
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > MAX_BYTES) {
134
+ return { state: 'bloqueado', size: stat.size ?? null };
135
+ }
136
+ let handle;
137
+ try {
138
+ handle = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
139
+ const current = await handle.readFile('utf8');
140
+ return {
141
+ state: digest(current) === digest(expectedContent) ? 'igual' : 'distinto',
142
+ size: stat.size,
143
+ };
144
+ } catch {
145
+ return { state: 'bloqueado', size: null };
146
+ } finally {
147
+ await handle?.close().catch(() => {});
148
+ }
149
+ }
150
+
151
+ async function isDarwinSystemLink(current) {
152
+ if (process.platform !== 'darwin' || (current !== '/tmp' && current !== '/var')) return false;
153
+ return (await fs.realpath(current).catch(() => null)) === `/private${current}`;
154
+ }
155
+
156
+ async function hasSymlinkAncestor(target) {
157
+ let current = path.resolve(target);
158
+ while (true) {
159
+ const stat = await statOrNull(current);
160
+ if (stat && !(await isDarwinSystemLink(current)) && (stat.isSymbolicLink() || !stat.isDirectory())) return true;
161
+ const parent = path.dirname(current);
162
+ if (parent === current) break;
163
+ current = parent;
164
+ }
165
+ return false;
166
+ }
167
+
168
+ /** Inspect target Antigravity agents directory and build an install/update plan. */
169
+ export async function planAntigravityAgents({
170
+ homeDirectory = os.homedir(),
171
+ projectRoot = process.cwd(),
172
+ outputDirectory,
173
+ project = false,
174
+ sourceDirectory = SOURCE_AGENTS_DIR,
175
+ } = {}) {
176
+ const targetDirectory = outputDirectory
177
+ ? path.resolve(outputDirectory)
178
+ : project
179
+ ? path.join(path.resolve(projectRoot), '.agents', 'agents')
180
+ : path.join(path.resolve(homeDirectory), '.gemini', 'config', 'agents');
181
+
182
+ const dirBlocked = await hasSymlinkAncestor(targetDirectory);
183
+ const rendered = await renderAntigravityAgents({ sourceDirectory });
184
+ const files = [];
185
+ for (const agent of rendered) {
186
+ const targetPath = path.join(targetDirectory, agent.filename);
187
+ const inspected = dirBlocked
188
+ ? { state: 'bloqueado', size: null }
189
+ : await inspectTargetFile(targetPath, agent.content);
190
+ files.push({
191
+ name: agent.name,
192
+ filename: agent.filename,
193
+ path: targetPath,
194
+ model: (MODEL_MAP[agent.name] ?? { model: 'flash' }).model,
195
+ effort: (MODEL_MAP[agent.name] ?? { effort: 'medium' }).effort,
196
+ state: inspected.state,
197
+ content: agent.content,
198
+ });
199
+ }
200
+ return {
201
+ targetDirectory,
202
+ files,
203
+ limitations: [
204
+ 'Los presupuestos de pasos y límites de palabras en las instrucciones son guías para el subagente.',
205
+ 'No modifica configuraciones de plugins ni hooks; instala los hooks por separado con `nexakit antigravity preparar`.',
206
+ ],
207
+ };
208
+ }
209
+
210
+ /** Apply an Antigravity agents plan safely with atomic writes and optional `.bak` backup on update. */
211
+ export async function writeAntigravityAgents(plan, { apply = false, update = false } = {}) {
212
+ if (!apply) return plan;
213
+ if (await hasSymlinkAncestor(plan.targetDirectory)) {
214
+ return {
215
+ ...plan,
216
+ files: plan.files.map((f) => ({ ...f, state: 'bloqueado' })),
217
+ };
218
+ }
219
+ await fs.mkdir(plan.targetDirectory, { recursive: true, mode: 0o700 });
220
+ const nextFiles = [];
221
+ for (const file of plan.files) {
222
+ if (file.state === 'bloqueado' || file.state === 'igual' || (file.state === 'distinto' && !update)) {
223
+ nextFiles.push({ ...file });
224
+ continue;
225
+ }
226
+ let backupPath;
227
+ if (file.state === 'distinto' && update) {
228
+ backupPath = `${file.path}.${Date.now()}.bak`;
229
+ await fs.copyFile(file.path, backupPath, constants.COPYFILE_EXCL);
230
+ await fs.chmod(backupPath, 0o600);
231
+ }
232
+ const temp = path.join(plan.targetDirectory, `.tmp-${file.name}-${randomUUID()}.md`);
233
+ try {
234
+ await fs.writeFile(temp, file.content, { flag: 'wx', mode: 0o600 });
235
+ await fs.rename(temp, file.path);
236
+ nextFiles.push({ ...file, state: 'igual', ...(backupPath ? { backupPath } : {}) });
237
+ } finally {
238
+ await fs.rm(temp, { force: true }).catch(() => {});
239
+ }
240
+ }
241
+ return { ...plan, files: nextFiles };
242
+ }
@@ -0,0 +1,179 @@
1
+ import { etiquetaDeAgente, formatoReinicio, medidor, tono } from '../plugins/nexakit-modelo/hooks/barra.js';
2
+ import { LIMITE_ALTO } from '../plugins/nexakit-modelo/hooks/decidir.js';
3
+ import { parseAntigravityModel } from './antigravity-recommendation.js';
4
+
5
+ const MAX_FILAS = 4;
6
+ const MIN_ETIQUETA = 8;
7
+ const MAX_ETIQUETA = 18;
8
+ const MAX_ROL = 36;
9
+
10
+ const ICONO = Object.freeze({
11
+ pending: ['●', 'warning'],
12
+ running: ['●', 'warning'],
13
+ waiting: ['●', 'warning'],
14
+ idle: ['✓', 'success'],
15
+ completed: ['✓', 'success'],
16
+ failed: ['✗', 'error'],
17
+ error: ['✗', 'error'],
18
+ killed: ['✗', 'error'],
19
+ });
20
+
21
+ const ANSI = Object.freeze({
22
+ antigravity: '36',
23
+ success: '32',
24
+ warning: '33',
25
+ error: '31',
26
+ suggestion: '35',
27
+ });
28
+
29
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
30
+ const clampPercent = (v) => Math.min(100, Math.max(0, v));
31
+ const tonoCache = (p) => (p >= 80 ? 'success' : p >= 50 ? 'warning' : 'error');
32
+ const fitText = (text, width) => (text.length > width ? `${text.slice(0, width - 1)}…` : text.padEnd(width));
33
+
34
+ /** Extract highest active quota bucket usage percentage and ISO reset timestamp. */
35
+ export function extractQuotaSummary(quota, now = Date.now()) {
36
+ if (!quota || typeof quota !== 'object' || Array.isArray(quota)) return null;
37
+ let best = null;
38
+ for (const bucket of Object.values(quota)) {
39
+ if (!bucket || typeof bucket !== 'object' || bucket.disabled === true) continue;
40
+ if (!isNum(bucket.remaining_fraction)) continue;
41
+ const percentUsed = clampPercent((1 - bucket.remaining_fraction) * 100);
42
+ let resetsAt = null;
43
+ if (typeof bucket.reset_time === 'string') {
44
+ resetsAt = bucket.reset_time;
45
+ } else if (isNum(bucket.reset_in_seconds) && bucket.reset_in_seconds > 0) {
46
+ resetsAt = new Date(now + bucket.reset_in_seconds * 1000).toISOString();
47
+ }
48
+ if (!best || percentUsed > best.percentUsed) best = { percentUsed, resetsAt };
49
+ }
50
+ return best;
51
+ }
52
+
53
+ /** Extract cache hit percentage only when current_usage reports explicit cache read tokens. */
54
+ export function extractCachePercent(contextWindow) {
55
+ const usage = contextWindow?.current_usage;
56
+ if (!usage || typeof usage !== 'object' || Array.isArray(usage)) return null;
57
+ const read = isNum(usage.cache_read_input_tokens)
58
+ ? usage.cache_read_input_tokens
59
+ : isNum(usage.cached_content_token_count)
60
+ ? usage.cached_content_token_count
61
+ : null;
62
+ if (read === null || read < 0) return null;
63
+ const creation = isNum(usage.cache_creation_input_tokens) && usage.cache_creation_input_tokens > 0
64
+ ? usage.cache_creation_input_tokens
65
+ : 0;
66
+ const input = isNum(usage.input_tokens) && usage.input_tokens > 0
67
+ ? usage.input_tokens
68
+ : isNum(usage.prompt_token_count) && usage.prompt_token_count > 0
69
+ ? usage.prompt_token_count
70
+ : 0;
71
+ const total = read + creation + input;
72
+ return total > 0 ? clampPercent((read / total) * 100) : null;
73
+ }
74
+
75
+ /** Extract context window used percentage without inventing values on unknown/zero windows. */
76
+ export function extractContextPercent(contextWindow) {
77
+ if (!contextWindow || typeof contextWindow !== 'object' || Array.isArray(contextWindow)) return null;
78
+ if (isNum(contextWindow.used_percentage)) return clampPercent(contextWindow.used_percentage);
79
+ if (isNum(contextWindow.remaining_percentage)) return clampPercent(100 - contextWindow.remaining_percentage);
80
+ if (isNum(contextWindow.context_window_size) && contextWindow.context_window_size > 0 && isNum(contextWindow.total_input_tokens)) {
81
+ return clampPercent((contextWindow.total_input_tokens / contextWindow.context_window_size) * 100);
82
+ }
83
+ return null;
84
+ }
85
+
86
+ function recommendationSegment(recommendation, current, quotaPercent) {
87
+ if (!recommendation || typeof recommendation !== 'object') return null;
88
+ if (recommendation.delegate === 'nivel-ligero' && current.family === recommendation.family && current.effort === recommendation.effort) {
89
+ return { text: ' ✓', color: 'success' };
90
+ }
91
+ if (recommendation.delegate) {
92
+ return { text: ` → delega: ${recommendation.delegate}`, color: 'suggestion' };
93
+ }
94
+ if (current.family && current.family === recommendation.family) {
95
+ return current.effort === recommendation.effort
96
+ ? { text: ' ✓', color: 'success' }
97
+ : { text: ` → ${recommendation.label}`, color: 'suggestion' };
98
+ }
99
+ if (recommendation.level === 'Alto' && isNum(quotaPercent) && quotaPercent >= LIMITE_ALTO) {
100
+ return { text: ` → Hydrogen · high (cuota ${Math.round(quotaPercent)} %)`, color: 'suggestion' };
101
+ }
102
+ return recommendation.label ? { text: ` → ${recommendation.label}`, color: 'suggestion' } : null;
103
+ }
104
+
105
+ function buildSubagentRows(subagents) {
106
+ if (!Array.isArray(subagents) || subagents.length === 0) return [];
107
+ const recent = subagents.slice(-MAX_FILAS);
108
+ const labels = recent.map((entry) => etiquetaDeAgente(entry?.name));
109
+ const roles = recent.map((entry) => (typeof entry?.role === 'string' ? entry.role.trim() : ''));
110
+ const column = Math.min(MAX_ETIQUETA, Math.max(MIN_ETIQUETA, ...labels.map((label) => label.length))) + 2;
111
+ const roleWidth = Math.min(MAX_ROL, Math.max(0, ...roles.map((role) => role.length)));
112
+ return recent.map((entry, index) => {
113
+ const label = labels[index].length > MAX_ETIQUETA ? `${labels[index].slice(0, MAX_ETIQUETA - 1)}…` : labels[index];
114
+ const role = roles[index];
115
+ const statusKey = typeof entry?.status === 'string' ? entry.status.toLowerCase() : '';
116
+ const [icon, color] = ICONO[statusKey] ?? ['?', undefined];
117
+ return [
118
+ { text: ` ↳ ${label.padEnd(column)}`, dim: true },
119
+ ...(roleWidth > 0 ? [{ text: `${fitText(role, roleWidth)} ` }] : []),
120
+ { text: icon, color },
121
+ ];
122
+ });
123
+ }
124
+
125
+ /** Build structured bar segments and subagent rows from an Antigravity statusLine payload. */
126
+ export function buildAntigravityStatusSegments(payload, { recommendation = null, now = Date.now() } = {}) {
127
+ const safe = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {};
128
+ const model = parseAntigravityModel(safe.model);
129
+ const segments = [
130
+ { text: model.name, color: model.name === 'modelo ?' ? undefined : 'antigravity', bold: model.name !== 'modelo ?' },
131
+ ...(model.effort ? [{ text: ` · ${model.effort}` }] : []),
132
+ ];
133
+
134
+ const quota = extractQuotaSummary(safe.quota, now);
135
+ const advice = recommendationSegment(recommendation, model, quota?.percentUsed);
136
+ if (advice) segments.push(advice);
137
+
138
+ const cache = extractCachePercent(safe.context_window);
139
+ if (cache !== null) {
140
+ segments.push({ text: ' caché ', dim: true }, { text: `${Math.round(cache)}%`, color: tonoCache(cache) });
141
+ }
142
+
143
+ const ctx = extractContextPercent(safe.context_window);
144
+ if (ctx !== null) {
145
+ segments.push({ text: ' ctx ', dim: true }, { text: medidor(ctx), color: tono(ctx) }, { text: ` ${Math.round(ctx)}%` });
146
+ }
147
+
148
+ if (quota !== null) {
149
+ const quotaColor = tono(quota.percentUsed);
150
+ segments.push({ text: ' cuota ', dim: true }, { text: `${Math.round(quota.percentUsed)}%`, color: quotaColor });
151
+ const resetLabel = quotaColor === 'success' ? null : formatoReinicio(quota.resetsAt, now);
152
+ if (resetLabel) segments.push({ text: ` ↻ ${resetLabel}`, dim: true });
153
+ }
154
+
155
+ if (typeof safe.cycle_mode === 'string' && safe.cycle_mode.trim()) {
156
+ segments.push({ text: ` ${safe.cycle_mode.trim()}`, dim: true });
157
+ }
158
+ if (safe.sandbox?.enabled === true) {
159
+ segments.push({ text: ' sandbox', dim: true });
160
+ }
161
+
162
+ return { segments, subagents: buildSubagentRows(safe.subagents) };
163
+ }
164
+
165
+ function renderSegment(segment, color) {
166
+ if (!color) return segment.text;
167
+ const codes = [];
168
+ if (segment.bold) codes.push('1');
169
+ if (segment.dim) codes.push('2');
170
+ if (segment.color && ANSI[segment.color]) codes.push(ANSI[segment.color]);
171
+ return codes.length ? `\x1b[${codes.join(';')}m${segment.text}\x1b[0m` : segment.text;
172
+ }
173
+
174
+ /** Render Antigravity statusLine payload as ANSI or plain text lines. */
175
+ export function formatAntigravityStatusLine(payload, { recommendation = null, now = Date.now(), color = true } = {}) {
176
+ const { segments, subagents } = buildAntigravityStatusSegments(payload, { recommendation, now });
177
+ const renderRow = (row) => row.map((segment) => renderSegment(segment, color)).join('');
178
+ return [renderRow(segments), ...subagents.map(renderRow)].join('\n');
179
+ }