nexakit 0.9.0 → 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 +2 -0
- package/assets/runtime/package-lock.json +2 -2
- package/bin/nexakit.js +16 -10
- package/package.json +1 -1
- package/src/ahorro-command.js +3 -1
- package/src/antigravity-agents.js +242 -0
- package/src/antigravity-barra.js +179 -0
- package/src/antigravity-command.js +226 -0
- package/src/antigravity-hook.js +159 -0
- package/src/antigravity-pre-tool.js +233 -0
- package/src/antigravity-recommendation.js +179 -0
- package/src/antigravity-session.js +291 -0
- package/src/antigravity-setup.js +175 -0
- package/src/codex-output.js +8 -3
- package/src/codex-pre-tool.js +30 -17
- package/src/review-instructions.js +1 -1
- package/src/toolkit-cli.js +3 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import {
|
|
3
|
+
buildAntigravityStatusSegments,
|
|
4
|
+
extractContextPercent,
|
|
5
|
+
extractQuotaSummary,
|
|
6
|
+
formatAntigravityStatusLine,
|
|
7
|
+
} from './antigravity-barra.js';
|
|
8
|
+
import { syncAndReadAntigravityBarraSession } from './antigravity-session.js';
|
|
9
|
+
|
|
10
|
+
const MAX_STDIN_BYTES = 1024 * 1024;
|
|
11
|
+
|
|
12
|
+
const HELP = `Uso: nexakit antigravity barra [--sin-color] [--json]
|
|
13
|
+
nexakit antigravity preparar [--salida carpeta] [--apply] [--json]
|
|
14
|
+
nexakit antigravity agentes [--proyecto] [--salida carpeta] [--apply] [--actualizar] [--json]
|
|
15
|
+
nexakit antigravity recomendar --tarea texto [--json]
|
|
16
|
+
nexakit antigravity hook
|
|
17
|
+
nexakit antigravity ejecutar -- programa [argumentos...]\n`;
|
|
18
|
+
|
|
19
|
+
const FLAGS = Object.freeze({
|
|
20
|
+
barra: { '--sin-color': 'bool', '--json': 'bool' },
|
|
21
|
+
preparar: { '--salida': 'value', '--apply': 'bool', '--json': 'bool' },
|
|
22
|
+
agentes: { '--proyecto': 'bool', '--salida': 'value', '--apply': 'bool', '--actualizar': 'bool', '--json': 'bool' },
|
|
23
|
+
recomendar: { '--tarea': 'value', '--json': 'bool' },
|
|
24
|
+
hook: {},
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
function parseFlags(command, argv) {
|
|
28
|
+
if (!Object.hasOwn(FLAGS, command)) throw new Error('Uso inválido.');
|
|
29
|
+
const spec = FLAGS[command];
|
|
30
|
+
const parsed = {};
|
|
31
|
+
for (let i = 0; i < argv.length; i++) {
|
|
32
|
+
const flag = argv[i];
|
|
33
|
+
if (!Object.hasOwn(spec, flag) || Object.hasOwn(parsed, flag)) throw new Error('Uso inválido.');
|
|
34
|
+
if (spec[flag] === 'bool') {
|
|
35
|
+
parsed[flag] = true;
|
|
36
|
+
} else {
|
|
37
|
+
const value = argv[++i];
|
|
38
|
+
if (!value || value.startsWith('--')) throw new Error('Falta el valor.');
|
|
39
|
+
parsed[flag] = value;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (command === 'recomendar' && !parsed['--tarea']?.trim()) throw new Error('Falta la tarea.');
|
|
43
|
+
if (command === 'agentes' && parsed['--actualizar'] && !parsed['--apply']) throw new Error('Actualizar requiere apply.');
|
|
44
|
+
if (command === 'agentes' && parsed['--proyecto'] && parsed['--salida']) throw new Error('Conflicto de destino.');
|
|
45
|
+
return parsed;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function readBoundedJson(input) {
|
|
49
|
+
let size = 0;
|
|
50
|
+
const chunks = [];
|
|
51
|
+
for await (const chunk of input) {
|
|
52
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
53
|
+
size += buffer.length;
|
|
54
|
+
if (size > MAX_STDIN_BYTES) throw new Error('Límite de entrada.');
|
|
55
|
+
chunks.push(buffer);
|
|
56
|
+
}
|
|
57
|
+
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
|
58
|
+
if (!raw) return null;
|
|
59
|
+
const parsed = JSON.parse(raw);
|
|
60
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Payload inválido.');
|
|
61
|
+
return parsed;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function handleBarra(flags, io, options) {
|
|
65
|
+
let payload;
|
|
66
|
+
try {
|
|
67
|
+
payload = await readBoundedJson(io.input ?? process.stdin);
|
|
68
|
+
} catch {
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
if (!payload) return 0;
|
|
72
|
+
|
|
73
|
+
const sessionId = typeof payload.conversation_id === 'string' && payload.conversation_id
|
|
74
|
+
? payload.conversation_id
|
|
75
|
+
: payload.session_id;
|
|
76
|
+
const now = options.now ?? Date.now();
|
|
77
|
+
const contextPercent = extractContextPercent(payload.context_window);
|
|
78
|
+
const quotaPercent = extractQuotaSummary(payload.quota, now)?.percentUsed ?? null;
|
|
79
|
+
const recommendation = await syncAndReadAntigravityBarraSession(
|
|
80
|
+
sessionId,
|
|
81
|
+
{ contextPercent, quotaPercent },
|
|
82
|
+
options,
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
if (flags['--json']) {
|
|
86
|
+
await io.out(JSON.stringify(buildAntigravityStatusSegments(payload, { recommendation, now })) + '\n');
|
|
87
|
+
return 0;
|
|
88
|
+
}
|
|
89
|
+
const color = !flags['--sin-color'] && !(options.environment?.NO_COLOR || process.env.NO_COLOR);
|
|
90
|
+
const line = formatAntigravityStatusLine(payload, { recommendation, now, color });
|
|
91
|
+
if (line) await io.out(`${line}\n`);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function handleHook(io, options) {
|
|
96
|
+
let result = {};
|
|
97
|
+
try {
|
|
98
|
+
const payload = await readBoundedJson(io.input ?? process.stdin);
|
|
99
|
+
if (payload && typeof payload.hookEventName === 'string') {
|
|
100
|
+
const { runAntigravityHook } = await import('./antigravity-hook.js');
|
|
101
|
+
result = (await runAntigravityHook(payload, options)) ?? {};
|
|
102
|
+
}
|
|
103
|
+
} catch {
|
|
104
|
+
await io.err('No se pudo procesar el hook de Antigravity; la sesión puede continuar.\n');
|
|
105
|
+
}
|
|
106
|
+
await io.out(JSON.stringify(result) + '\n');
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function formatRecommendation(report) {
|
|
111
|
+
return [
|
|
112
|
+
report.message,
|
|
113
|
+
report.recommendation
|
|
114
|
+
? `Recomendación: ${report.recommendation.level} (${report.recommendation.label}).`
|
|
115
|
+
: 'Recomendación no disponible.',
|
|
116
|
+
`Razón: ${report.reason}`,
|
|
117
|
+
`Fuente: ${report.source}`,
|
|
118
|
+
`Acción: ${report.action ?? 'sin acción'}`,
|
|
119
|
+
...(report.delegate ? [`Subagente: ${report.delegate}`] : []),
|
|
120
|
+
'Sin cambios automáticos.',
|
|
121
|
+
'',
|
|
122
|
+
].join('\n');
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function formatPrepare(report) {
|
|
126
|
+
return [
|
|
127
|
+
report.applied
|
|
128
|
+
? `Paquete Antigravity CLI creado en: ${report.outputDirectory}`
|
|
129
|
+
: 'Vista previa Antigravity CLI (no se escribió ningún archivo):',
|
|
130
|
+
'',
|
|
131
|
+
'Comando rápido dentro de agy:',
|
|
132
|
+
` /statusline ${report.statusLineCommand}`,
|
|
133
|
+
'',
|
|
134
|
+
'Limitaciones:',
|
|
135
|
+
...report.limitations.map((item) => `- ${item}`),
|
|
136
|
+
'',
|
|
137
|
+
].join('\n');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function formatAgents(report, apply) {
|
|
141
|
+
const rows = [
|
|
142
|
+
['Nombre', 'Modelo', 'Esfuerzo', 'Estado'],
|
|
143
|
+
...report.files.map((file) => [file.name, file.model, file.effort, file.state]),
|
|
144
|
+
];
|
|
145
|
+
const widths = rows[0].map((_, index) => Math.max(...rows.map((row) => row[index].length)));
|
|
146
|
+
return [
|
|
147
|
+
apply ? `Agentes de Antigravity (${report.targetDirectory}):` : `Vista previa de agentes (${report.targetDirectory}):`,
|
|
148
|
+
...rows.map((row) => row.map((value, index) => value.padEnd(widths[index])).join(' ').trimEnd()),
|
|
149
|
+
...report.files.filter((f) => f.backupPath).map((f) => `Respaldo ${f.name}: ${f.backupPath}`),
|
|
150
|
+
'Limitaciones:',
|
|
151
|
+
...report.limitations.map((item) => `- ${item}`),
|
|
152
|
+
'',
|
|
153
|
+
].join('\n');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Run `nexakit antigravity <subcommand>` CLI actions. */
|
|
157
|
+
export async function runAntigravityCommand(argv, io, options = {}) {
|
|
158
|
+
const [command, ...rest] = argv;
|
|
159
|
+
if (argv.length === 1 && ['--help', '-h'].includes(command)) {
|
|
160
|
+
await io.out(HELP);
|
|
161
|
+
return 0;
|
|
162
|
+
}
|
|
163
|
+
if (command === 'ejecutar') {
|
|
164
|
+
if (rest[0] !== '--' || !rest[1]) {
|
|
165
|
+
await io.err(HELP);
|
|
166
|
+
return 2;
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
const { runCodexOutput } = await import('./codex-output.js');
|
|
170
|
+
return await runCodexOutput(rest.slice(1), io, { ...options, agent: 'antigravity' });
|
|
171
|
+
} catch {
|
|
172
|
+
await io.err('No se pudo ejecutar el programa.\n');
|
|
173
|
+
return 1;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
let flags;
|
|
177
|
+
try {
|
|
178
|
+
flags = parseFlags(command, rest);
|
|
179
|
+
} catch {
|
|
180
|
+
await io.err(HELP);
|
|
181
|
+
return 2;
|
|
182
|
+
}
|
|
183
|
+
if (command === 'barra') return handleBarra(flags, io, options);
|
|
184
|
+
if (command === 'hook') return handleHook(io, options);
|
|
185
|
+
try {
|
|
186
|
+
if (command === 'agentes') {
|
|
187
|
+
const { planAntigravityAgents, writeAntigravityAgents } = await import('./antigravity-agents.js');
|
|
188
|
+
let plan = await planAntigravityAgents({
|
|
189
|
+
...options,
|
|
190
|
+
project: Boolean(flags['--proyecto']),
|
|
191
|
+
outputDirectory: flags['--salida'] ? path.resolve(flags['--salida']) : undefined,
|
|
192
|
+
});
|
|
193
|
+
if (flags['--apply']) {
|
|
194
|
+
plan = await writeAntigravityAgents(plan, { apply: true, update: Boolean(flags['--actualizar']) });
|
|
195
|
+
}
|
|
196
|
+
const report = {
|
|
197
|
+
targetDirectory: plan.targetDirectory,
|
|
198
|
+
files: plan.files.map(({ name, path: filePath, model, effort, state, backupPath }) => ({
|
|
199
|
+
name, path: filePath, model, effort, state, ...(backupPath ? { backupPath } : {}),
|
|
200
|
+
})),
|
|
201
|
+
limitations: plan.limitations,
|
|
202
|
+
};
|
|
203
|
+
await io.out(flags['--json'] ? JSON.stringify(report) + '\n' : formatAgents(report, Boolean(flags['--apply'])));
|
|
204
|
+
const blocked = report.files.some((f) => f.state === 'bloqueado');
|
|
205
|
+
const incomplete = report.files.some((f) => f.state !== 'igual');
|
|
206
|
+
return blocked || (flags['--apply'] && incomplete) ? 1 : 0;
|
|
207
|
+
}
|
|
208
|
+
if (command === 'recomendar') {
|
|
209
|
+
const { recommendAntigravityTask } = await import('./antigravity-recommendation.js');
|
|
210
|
+
const report = await recommendAntigravityTask(flags['--tarea'], options);
|
|
211
|
+
await io.out(flags['--json'] ? JSON.stringify(report) + '\n' : formatRecommendation(report));
|
|
212
|
+
return 0;
|
|
213
|
+
}
|
|
214
|
+
const { prepareAntigravity } = await import('./antigravity-setup.js');
|
|
215
|
+
const report = await prepareAntigravity({
|
|
216
|
+
...options,
|
|
217
|
+
outputDirectory: flags['--salida'] ? path.resolve(flags['--salida']) : undefined,
|
|
218
|
+
apply: Boolean(flags['--apply']),
|
|
219
|
+
});
|
|
220
|
+
await io.out(flags['--json'] ? JSON.stringify(report) + '\n' : formatPrepare(report));
|
|
221
|
+
return 0;
|
|
222
|
+
} catch {
|
|
223
|
+
await io.err('No se pudo completar el comando Antigravity. Revisa formato, rutas y permisos.\n');
|
|
224
|
+
return 1;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import {
|
|
2
|
+
avisoPendientes,
|
|
3
|
+
esCorreccion,
|
|
4
|
+
NOTA_CORRECCION,
|
|
5
|
+
pendientes,
|
|
6
|
+
textoSeguro,
|
|
7
|
+
} from '../plugins/nexakit-lecciones/hooks/lecciones.js';
|
|
8
|
+
import {
|
|
9
|
+
avisoDeContexto,
|
|
10
|
+
CUOTA_CRITICA,
|
|
11
|
+
CUOTA_SERIE,
|
|
12
|
+
mensajeDeAviso,
|
|
13
|
+
notaDeCuota,
|
|
14
|
+
} from '../plugins/nexakit-sesion/hooks/aviso.js';
|
|
15
|
+
import { recommendAntigravityTask } from './antigravity-recommendation.js';
|
|
16
|
+
import { mutateAntigravitySessionState } from './antigravity-session.js';
|
|
17
|
+
|
|
18
|
+
const SESSION_GUIDANCE =
|
|
19
|
+
'Usa /statusline para ver o configurar la barra de estado y /model para cambiar modelo o esfuerzo. ' +
|
|
20
|
+
'Las recomendaciones locales de NexaKit son orientativas y nunca cambian el modelo automáticamente. ' +
|
|
21
|
+
'Para delegar tareas de más de 1–2 pasos usa subagentes (nivel-ligero, nivel-normal, nivel-exigente, nivel-alto o especialistas) sin autorizar cambios ni memoria por tu cuenta.';
|
|
22
|
+
|
|
23
|
+
const quotaLevelOf = (percent) =>
|
|
24
|
+
typeof percent !== 'number' || !Number.isFinite(percent)
|
|
25
|
+
? 0
|
|
26
|
+
: percent >= CUOTA_CRITICA
|
|
27
|
+
? 2
|
|
28
|
+
: percent >= CUOTA_SERIE
|
|
29
|
+
? 1
|
|
30
|
+
: 0;
|
|
31
|
+
|
|
32
|
+
/** Handle Antigravity lifecycle hooks (`SessionStart`, `PreInvocation`, `PreToolUse`, `PostToolUse`). */
|
|
33
|
+
export async function runAntigravityHook(payload, options = {}) {
|
|
34
|
+
try {
|
|
35
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload) || typeof payload.hookEventName !== 'string') {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (payload.hookEventName === 'PreToolUse') {
|
|
40
|
+
const { handleAntigravityPreToolUse } = await import('./antigravity-pre-tool.js');
|
|
41
|
+
return await handleAntigravityPreToolUse(payload, options);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (payload.hookEventName === 'PostToolUse') {
|
|
45
|
+
const { handleAntigravityPostToolUse } = await import('./antigravity-pre-tool.js');
|
|
46
|
+
return await handleAntigravityPostToolUse(payload, options);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (payload.hookEventName === 'SessionStart') {
|
|
50
|
+
let message = SESSION_GUIDANCE;
|
|
51
|
+
const { appendAntigravityLesson, readAntigravityLessons } = await import('./antigravity-pre-tool.js');
|
|
52
|
+
const unreminded = pendientes(await readAntigravityLessons(options));
|
|
53
|
+
if (unreminded.length > 0) {
|
|
54
|
+
message += `\n${avisoPendientes(unreminded)}`;
|
|
55
|
+
await appendAntigravityLesson({ tipo: 'avisada' }, options);
|
|
56
|
+
}
|
|
57
|
+
if (typeof payload.conversationId === 'string') {
|
|
58
|
+
await mutateAntigravitySessionState(payload.conversationId, (state) => {
|
|
59
|
+
state.lecciones.avisoHecho = true;
|
|
60
|
+
return state;
|
|
61
|
+
}, options);
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
injectSteps: [{ systemMessage: { systemMessage: message } }],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (payload.hookEventName === 'PreInvocation') {
|
|
69
|
+
const userInput = typeof payload.lastUserInput === 'string' ? payload.lastUserInput : '';
|
|
70
|
+
const currentModel = typeof payload.modelName === 'string' && payload.modelName.toLowerCase() !== 'auto'
|
|
71
|
+
? payload.modelName
|
|
72
|
+
: null;
|
|
73
|
+
const result = await recommendAntigravityTask(userInput, {
|
|
74
|
+
currentModel,
|
|
75
|
+
catalog: options.catalog,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const systemNotes = [];
|
|
79
|
+
let needsPendingCheck = false;
|
|
80
|
+
const correction = esCorreccion(userInput);
|
|
81
|
+
|
|
82
|
+
if (typeof payload.conversationId === 'string') {
|
|
83
|
+
const updatedState = await mutateAntigravitySessionState(payload.conversationId, (state) => {
|
|
84
|
+
if (result.available && !result.silent && result.recommendation) {
|
|
85
|
+
state.recommendation = {
|
|
86
|
+
...result.recommendation,
|
|
87
|
+
delegate: result.delegate,
|
|
88
|
+
reason: result.reason,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (!state.lecciones.avisoHecho) {
|
|
92
|
+
needsPendingCheck = true;
|
|
93
|
+
state.lecciones.avisoHecho = true;
|
|
94
|
+
}
|
|
95
|
+
if (state.lecciones.pendingRepetitionNotice) {
|
|
96
|
+
systemNotes.push(state.lecciones.pendingRepetitionNotice);
|
|
97
|
+
state.lecciones.pendingRepetitionNotice = null;
|
|
98
|
+
}
|
|
99
|
+
const ctxLevel = avisoDeContexto(state.usage.contextPercent);
|
|
100
|
+
if (ctxLevel > state.usage.warnedContextLevel) {
|
|
101
|
+
state.usage.warnedContextLevel = ctxLevel;
|
|
102
|
+
const warn = mensajeDeAviso(ctxLevel, state.usage.contextPercent);
|
|
103
|
+
if (warn) systemNotes.push(`[nexakit: ${warn}]`);
|
|
104
|
+
}
|
|
105
|
+
const quotaLevel = quotaLevelOf(state.usage.quotaPercent);
|
|
106
|
+
if (quotaLevel > state.usage.warnedQuotaLevel) {
|
|
107
|
+
state.usage.warnedQuotaLevel = quotaLevel;
|
|
108
|
+
const warn = notaDeCuota(quotaLevel, state.usage.quotaPercent);
|
|
109
|
+
if (warn) systemNotes.push(warn);
|
|
110
|
+
}
|
|
111
|
+
return state;
|
|
112
|
+
}, options);
|
|
113
|
+
|
|
114
|
+
if (needsPendingCheck || correction) {
|
|
115
|
+
const { appendAntigravityLesson, readAntigravityLessons } = await import('./antigravity-pre-tool.js');
|
|
116
|
+
if (needsPendingCheck) {
|
|
117
|
+
const unreminded = pendientes(await readAntigravityLessons(options));
|
|
118
|
+
if (unreminded.length > 0) {
|
|
119
|
+
systemNotes.push(avisoPendientes(unreminded));
|
|
120
|
+
await appendAntigravityLesson({ tipo: 'avisada' }, options);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (correction) {
|
|
124
|
+
await appendAntigravityLesson({ tipo: 'correccion', texto: textoSeguro(userInput) }, options);
|
|
125
|
+
systemNotes.push(NOTA_CORRECCION);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
void updatedState;
|
|
129
|
+
} else if (correction) {
|
|
130
|
+
systemNotes.push(NOTA_CORRECCION);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const injectSteps = [];
|
|
134
|
+
if (result.available && !result.silent && result.recommendation && result.action !== 'keep') {
|
|
135
|
+
const notice = result.delegate
|
|
136
|
+
? `NexaKit: → delega a ${result.delegate} (${result.recommendation.label}) · ${result.reason}`
|
|
137
|
+
: `NexaKit: → ${result.recommendation.label} · ${result.reason} (usa /model)`;
|
|
138
|
+
injectSteps.push({
|
|
139
|
+
systemMessage: {
|
|
140
|
+
systemMessage: '',
|
|
141
|
+
metadata: { user_markdown: notice },
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
if (systemNotes.length > 0) {
|
|
146
|
+
injectSteps.push({
|
|
147
|
+
systemMessage: {
|
|
148
|
+
systemMessage: systemNotes.join('\n'),
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
return injectSteps.length > 0 ? { injectSteps } : {};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {};
|
|
156
|
+
} catch {
|
|
157
|
+
return {};
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { 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 { motivoBash, motivoEscritura } from '../plugins/nexakit-guardarrailes/hooks/guardarrailes.js';
|
|
7
|
+
import {
|
|
8
|
+
claveDeComando,
|
|
9
|
+
claveDeError,
|
|
10
|
+
esRutaDeMemoria,
|
|
11
|
+
leerEventos,
|
|
12
|
+
podarEventos,
|
|
13
|
+
sinGuardar,
|
|
14
|
+
} from '../plugins/nexakit-lecciones/hooks/lecciones.js';
|
|
15
|
+
import { mutateAntigravitySessionState, readAntigravitySessionState } from './antigravity-session.js';
|
|
16
|
+
import { buildOutputWrapperCommand } from './codex-pre-tool.js';
|
|
17
|
+
|
|
18
|
+
const REPETIR = /(^|\s)NEXAKIT_REPETIR=1(\s|$)/u;
|
|
19
|
+
const TOPE_MISMO_ERROR = 3;
|
|
20
|
+
const MAX_LEDGER_BYTES = 1024 * 1024;
|
|
21
|
+
const SHELL_TOOLS = new Set(['run_command', 'Bash']);
|
|
22
|
+
const WRITE_TOOLS = new Set(['write_file', 'write_to_file', 'Write']);
|
|
23
|
+
const EDIT_TOOLS = new Set(['edit_file', 'Edit', 'MultiEdit', 'replace_file_content', 'multi_replace_file_content']);
|
|
24
|
+
|
|
25
|
+
function isAntigravityMemoryNote(filePath) {
|
|
26
|
+
if (typeof filePath !== 'string' || !filePath) return false;
|
|
27
|
+
if (esRutaDeMemoria(filePath)) return true;
|
|
28
|
+
const normalized = filePath.replaceAll('\\', '/');
|
|
29
|
+
return /\/memory\/[^/]+\.md$/u.test(normalized) && !/\/MEMORY\.md$/u.test(normalized);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function unquotePosix(token) {
|
|
33
|
+
if (!token.startsWith("'") || !token.endsWith("'")) return token;
|
|
34
|
+
return token.slice(1, -1).replaceAll("'\"'\"'", "'").replaceAll("'\\''", "'");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Recover the original wrapped command if `CommandLine` invokes `nexakit antigravity ejecutar -- ...`. */
|
|
38
|
+
export function unwrapAntigravityCommand(command) {
|
|
39
|
+
if (typeof command !== 'string') return '';
|
|
40
|
+
const match = /^NEXAKIT_ANTIGRAVITY_TEMP_OUTPUT=1\s+.*?\s+'antigravity'\s+'ejecutar'\s+'--'\s+(.+)$/u.exec(command.trim());
|
|
41
|
+
if (!match) return command;
|
|
42
|
+
const tokens = match[1].match(/'(?:[^']|'"'"'|'\\'')*'/gu);
|
|
43
|
+
return tokens?.length ? tokens.map(unquotePosix).join(' ') : command;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function extractToolAction(payload) {
|
|
47
|
+
const call = payload?.toolCall;
|
|
48
|
+
if (!call || typeof call !== 'object') return null;
|
|
49
|
+
const name = call.name;
|
|
50
|
+
const args = call.args && typeof call.args === 'object' && !Array.isArray(call.args) ? call.args : {};
|
|
51
|
+
if (SHELL_TOOLS.has(name)) {
|
|
52
|
+
const key = typeof args.CommandLine === 'string' ? 'CommandLine' : 'command';
|
|
53
|
+
const command = typeof args[key] === 'string' ? args[key] : '';
|
|
54
|
+
return { kind: 'shell', key, command, args };
|
|
55
|
+
}
|
|
56
|
+
const filePath = args.Path ?? args.TargetFile ?? args.file_path ?? args.path;
|
|
57
|
+
if (WRITE_TOOLS.has(name)) {
|
|
58
|
+
const content = args.Content ?? args.CodeContent ?? args.content;
|
|
59
|
+
return { kind: 'write', filePath, texts: typeof content === 'string' ? [content] : [], args };
|
|
60
|
+
}
|
|
61
|
+
if (EDIT_TOOLS.has(name)) {
|
|
62
|
+
const texts = [];
|
|
63
|
+
if (typeof args.Replacement === 'string') texts.push(args.Replacement);
|
|
64
|
+
if (typeof args.new_string === 'string') texts.push(args.new_string);
|
|
65
|
+
if (Array.isArray(args.edits)) {
|
|
66
|
+
for (const edit of args.edits) {
|
|
67
|
+
if (typeof edit?.new_string === 'string') texts.push(edit.new_string);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (Array.isArray(args.ReplacementChunks)) {
|
|
71
|
+
for (const chunk of args.ReplacementChunks) {
|
|
72
|
+
if (typeof chunk?.ReplacementContent === 'string') texts.push(chunk.ReplacementContent);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { kind: 'edit', filePath, texts, args };
|
|
76
|
+
}
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function safeNexakitDir(options, create) {
|
|
81
|
+
const home = path.resolve(options.homeDirectory ?? os.homedir());
|
|
82
|
+
const dir = path.join(home, '.nexakit');
|
|
83
|
+
if (create) await fs.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
84
|
+
const stat = await fs.lstat(dir).catch(() => null);
|
|
85
|
+
if (!stat || !stat.isDirectory() || stat.isSymbolicLink()) return null;
|
|
86
|
+
if (create) await fs.chmod(dir, 0o700).catch(() => {});
|
|
87
|
+
return dir;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Read `~/.nexakit/lecciones.jsonl` safely (no symlinks, bounded size). */
|
|
91
|
+
export async function readAntigravityLessons(options = {}) {
|
|
92
|
+
try {
|
|
93
|
+
const dir = await safeNexakitDir(options, false);
|
|
94
|
+
if (!dir) return [];
|
|
95
|
+
const target = path.join(dir, 'lecciones.jsonl');
|
|
96
|
+
const stat = await fs.lstat(target).catch(() => null);
|
|
97
|
+
if (!stat || !stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > MAX_LEDGER_BYTES) return [];
|
|
98
|
+
const fd = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
99
|
+
try {
|
|
100
|
+
return leerEventos(await fd.readFile('utf8'));
|
|
101
|
+
} finally {
|
|
102
|
+
await fd.close().catch(() => {});
|
|
103
|
+
}
|
|
104
|
+
} catch {
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Append an event atomically to `~/.nexakit/lecciones.jsonl`, pruning to 90d / 500 entries. */
|
|
110
|
+
export async function appendAntigravityLesson(event, options = {}) {
|
|
111
|
+
try {
|
|
112
|
+
const dir = await safeNexakitDir(options, true);
|
|
113
|
+
if (!dir) return;
|
|
114
|
+
const target = path.join(dir, 'lecciones.jsonl');
|
|
115
|
+
const existing = await fs.lstat(target).catch(() => null);
|
|
116
|
+
if (existing && (!existing.isFile() || existing.isSymbolicLink() || existing.nlink !== 1)) return;
|
|
117
|
+
const now = typeof options.now === 'number' && Number.isFinite(options.now) ? options.now : Date.now();
|
|
118
|
+
const events = podarEventos([...(await readAntigravityLessons(options)), { fecha: now, ...event }], now);
|
|
119
|
+
const body = `${events.map((item) => JSON.stringify(item)).join('\n')}\n`;
|
|
120
|
+
const temp = path.join(dir, `.tmp-lec-${process.pid}-${randomUUID()}.jsonl`);
|
|
121
|
+
try {
|
|
122
|
+
await fs.writeFile(temp, body, { flag: 'wx', mode: 0o600 });
|
|
123
|
+
await fs.rename(temp, target);
|
|
124
|
+
} finally {
|
|
125
|
+
await fs.rm(temp, { force: true }).catch(() => {});
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
// Lessons recording must never block execution.
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Handle Antigravity `PreToolUse`: guardarrailes, duplicate-failure block, and ahorro wrapper. */
|
|
133
|
+
export async function handleAntigravityPreToolUse(payload, options = {}) {
|
|
134
|
+
try {
|
|
135
|
+
const action = extractToolAction(payload);
|
|
136
|
+
if (!action) return { decision: 'allow' };
|
|
137
|
+
|
|
138
|
+
if (action.kind === 'write' || action.kind === 'edit') {
|
|
139
|
+
const deny = motivoEscritura(action.filePath, action.texts);
|
|
140
|
+
return deny ? { decision: 'deny', reason: deny } : { decision: 'allow' };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const rawCommand = unwrapAntigravityCommand(action.command);
|
|
144
|
+
const guardDeny = motivoBash(rawCommand);
|
|
145
|
+
if (guardDeny) return { decision: 'deny', reason: guardDeny };
|
|
146
|
+
|
|
147
|
+
const cmdKey = claveDeComando(rawCommand);
|
|
148
|
+
if (cmdKey && payload.conversationId && !REPETIR.test(rawCommand)) {
|
|
149
|
+
const state = await readAntigravitySessionState(payload.conversationId, options);
|
|
150
|
+
const prevFailure = state?.lecciones?.fallidos?.[cmdKey];
|
|
151
|
+
if (prevFailure) {
|
|
152
|
+
await appendAntigravityLesson({ tipo: 'freno' }, options);
|
|
153
|
+
return {
|
|
154
|
+
decision: 'deny',
|
|
155
|
+
reason: `nexakit: este comando ya falló así y no ha cambiado nada desde entonces:\n${prevFailure}\nCambia de enfoque. Si de verdad corregiste la causa por otra vía, repítelo con NEXAKIT_REPETIR=1 delante.`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const isDaemon = ['IsDaemon', 'Background', 'background', 'run_in_background'].some((k) => Boolean(action.args[k]));
|
|
161
|
+
if (!isDaemon) {
|
|
162
|
+
const wrapper = buildOutputWrapperCommand(rawCommand, {
|
|
163
|
+
executable: options.executable,
|
|
164
|
+
entrypoint: options.entrypoint,
|
|
165
|
+
agent: 'antigravity',
|
|
166
|
+
tempEnv: 'NEXAKIT_ANTIGRAVITY_TEMP_OUTPUT=1',
|
|
167
|
+
platform: options.platform ?? process.platform,
|
|
168
|
+
environment: options.environment ?? process.env,
|
|
169
|
+
});
|
|
170
|
+
if (wrapper) {
|
|
171
|
+
return { decision: 'allow', overwrite: { [action.key]: wrapper } };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { decision: 'allow' };
|
|
175
|
+
} catch {
|
|
176
|
+
return { decision: 'allow' };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Handle Antigravity `PostToolUse`: clear failures on progress, track errors & memory writes. */
|
|
181
|
+
export async function handleAntigravityPostToolUse(payload, options = {}) {
|
|
182
|
+
try {
|
|
183
|
+
const action = extractToolAction(payload);
|
|
184
|
+
const failed = typeof payload?.error === 'string' && payload.error.trim() !== '';
|
|
185
|
+
|
|
186
|
+
if (action && (action.kind === 'write' || action.kind === 'edit')) {
|
|
187
|
+
if (!failed && payload.conversationId) {
|
|
188
|
+
await mutateAntigravitySessionState(payload.conversationId, (state) => {
|
|
189
|
+
state.lecciones.fallidos = {};
|
|
190
|
+
return state;
|
|
191
|
+
}, options);
|
|
192
|
+
}
|
|
193
|
+
if (!failed && isAntigravityMemoryNote(action.filePath)) {
|
|
194
|
+
const events = await readAntigravityLessons(options);
|
|
195
|
+
if (sinGuardar(events).length > 0) {
|
|
196
|
+
await appendAntigravityLesson({ tipo: 'guardada' }, options);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return {};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (action?.kind === 'shell' && payload.conversationId) {
|
|
203
|
+
const cmdKey = claveDeComando(unwrapAntigravityCommand(action.command));
|
|
204
|
+
if (!failed) {
|
|
205
|
+
await mutateAntigravitySessionState(payload.conversationId, (state) => {
|
|
206
|
+
state.lecciones.fallidos = {};
|
|
207
|
+
return state;
|
|
208
|
+
}, options);
|
|
209
|
+
return {};
|
|
210
|
+
}
|
|
211
|
+
const errText = payload.error;
|
|
212
|
+
const errType = claveDeError(errText);
|
|
213
|
+
let triggeredRepetition = false;
|
|
214
|
+
await mutateAntigravitySessionState(payload.conversationId, (state) => {
|
|
215
|
+
if (cmdKey) state.lecciones.fallidos[cmdKey] = errText.split('\n').slice(0, 3).join('\n').slice(0, 400);
|
|
216
|
+
if (errType) {
|
|
217
|
+
const count = (state.lecciones.errores[errType] ?? 0) + 1;
|
|
218
|
+
state.lecciones.errores[errType] = count;
|
|
219
|
+
if (count === TOPE_MISMO_ERROR) {
|
|
220
|
+
triggeredRepetition = true;
|
|
221
|
+
state.lecciones.pendingRepetitionNotice =
|
|
222
|
+
`[nexakit: el mismo tipo de error salió ${count} veces en esta tarea («${errType}»). Para, explica la causa raíz antes de otro intento y cambia de enfoque; si es una lección que vale para el futuro, guárdala en tu memoria persistente.]`;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return state;
|
|
226
|
+
}, options);
|
|
227
|
+
if (triggeredRepetition) await appendAntigravityLesson({ tipo: 'repeticion' }, options);
|
|
228
|
+
}
|
|
229
|
+
return {};
|
|
230
|
+
} catch {
|
|
231
|
+
return {};
|
|
232
|
+
}
|
|
233
|
+
}
|