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,179 @@
|
|
|
1
|
+
import { LIMITE_ALTO } from '../plugins/nexakit-modelo/hooks/decidir.js';
|
|
2
|
+
import { recomendarPorTexto } from '../plugins/nexakit-modelo/hooks/recomendar.js';
|
|
3
|
+
|
|
4
|
+
const MAX_TASK_BYTES = 16 * 1024;
|
|
5
|
+
const CONFIRMATION_RE = /^(?:¡?)(?:s[ií]|ok|okay|dale|listo|vale|perfecto|bien|contin[uú]a|sigue|hazlo|adelante|gracias|de una|claro|no)(?:[\s.!,¡]+(?:s[ií]|ok|okay|dale|listo|vale|perfecto|bien|contin[uú]a|sigue|hazlo|adelante|gracias|de una|claro|no))*[\s.!,]*$/iu;
|
|
6
|
+
const EFFORT_SUFFIX_RE = /-(low|medium|high|xhigh|max)$/iu;
|
|
7
|
+
const EFFORT_PAREN_RE = /\s*\((low|medium|high|xhigh|max)\)\s*$/iu;
|
|
8
|
+
const KNOWN_FAMILY_RE = /\b(flash|hydrogen|argon|carbon|luna|terra|sol|astra|haiku|sonnet|opus)\b/iu;
|
|
9
|
+
const SLUG_FAMILY_RE = /^(?:gpt|gemini|claude)-\d+(?:\.\d+)*-([a-z][a-z0-9]*)$/iu;
|
|
10
|
+
const VALID_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
|
|
11
|
+
|
|
12
|
+
const FAMILIES_BY_LEVEL = Object.freeze({
|
|
13
|
+
Ligero: ['flash', 'hydrogen'],
|
|
14
|
+
Normal: ['hydrogen', 'flash'],
|
|
15
|
+
Exigente: ['hydrogen', 'argon', 'flash'],
|
|
16
|
+
Alto: ['carbon', 'argon'],
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const DEFAULT_FAMILY_BY_LEVEL = Object.freeze({
|
|
20
|
+
Ligero: 'flash',
|
|
21
|
+
Normal: 'hydrogen',
|
|
22
|
+
Exigente: 'hydrogen',
|
|
23
|
+
Alto: 'carbon',
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const FAMILY_LABELS = Object.freeze({
|
|
27
|
+
flash: 'Flash',
|
|
28
|
+
hydrogen: 'Hydrogen',
|
|
29
|
+
argon: 'Argon',
|
|
30
|
+
carbon: 'Carbon',
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
|
|
34
|
+
|
|
35
|
+
/** Extract clean display name, family, and effort from an Antigravity model payload or string. */
|
|
36
|
+
export function parseAntigravityModel(model) {
|
|
37
|
+
const rawName = typeof model === 'string'
|
|
38
|
+
? model.trim()
|
|
39
|
+
: model && typeof model === 'object'
|
|
40
|
+
? String(model.display_name || model.id || '').trim()
|
|
41
|
+
: '';
|
|
42
|
+
if (!rawName) return { name: 'modelo ?', family: null, effort: null };
|
|
43
|
+
|
|
44
|
+
const rawEffort = model && typeof model === 'object' && typeof model.effort === 'string'
|
|
45
|
+
? model.effort.trim().toLowerCase()
|
|
46
|
+
: null;
|
|
47
|
+
const suffixEffort = rawName.match(EFFORT_SUFFIX_RE)?.[1]?.toLowerCase() ?? null;
|
|
48
|
+
const parenEffort = rawName.match(EFFORT_PAREN_RE)?.[1]?.toLowerCase() ?? null;
|
|
49
|
+
const candidateEffort = rawEffort || parenEffort || suffixEffort;
|
|
50
|
+
const effort = candidateEffort && VALID_EFFORTS.has(candidateEffort) ? candidateEffort : null;
|
|
51
|
+
|
|
52
|
+
const cleanName = rawName.replace(EFFORT_PAREN_RE, '').replace(EFFORT_SUFFIX_RE, '').trim() || rawName;
|
|
53
|
+
const family = cleanName.match(KNOWN_FAMILY_RE)?.[1]?.toLowerCase()
|
|
54
|
+
?? cleanName.match(SLUG_FAMILY_RE)?.[1]?.toLowerCase()
|
|
55
|
+
?? null;
|
|
56
|
+
return { name: cleanName, family, effort };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function resolveCatalogPick(catalog, level, effort) {
|
|
60
|
+
if (!Array.isArray(catalog) || catalog.length === 0) return null;
|
|
61
|
+
const families = FAMILIES_BY_LEVEL[level] ?? [];
|
|
62
|
+
const valid = catalog.filter((entry) => entry && typeof entry.model === 'string' && entry.model.trim());
|
|
63
|
+
for (const family of families) {
|
|
64
|
+
const exact = valid.find((entry) => {
|
|
65
|
+
const parsed = parseAntigravityModel(entry.model);
|
|
66
|
+
const efforts = Array.isArray(entry.efforts) && entry.efforts.length ? entry.efforts : parsed.effort ? [parsed.effort] : [];
|
|
67
|
+
return parsed.family === family && efforts.includes(effort);
|
|
68
|
+
});
|
|
69
|
+
if (exact) return { model: exact.model, family, effort };
|
|
70
|
+
}
|
|
71
|
+
for (const family of families) {
|
|
72
|
+
const fallback = valid.find((entry) => parseAntigravityModel(entry.model).family === family);
|
|
73
|
+
if (fallback) {
|
|
74
|
+
const parsed = parseAntigravityModel(fallback.model);
|
|
75
|
+
const pickedEffort = Array.isArray(fallback.efforts) && fallback.efforts[0] ? fallback.efforts[0] : (parsed.effort ?? effort);
|
|
76
|
+
return { model: fallback.model, family, effort: pickedEffort };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function classifyToAntigravity(classification, quotaPercent) {
|
|
83
|
+
if (classification.delegar === 'nivel-ligero') {
|
|
84
|
+
return { level: 'Ligero', effort: 'low', delegate: 'nivel-ligero', reason: 'tarea mecánica: mejor delegarla', isDesign: false };
|
|
85
|
+
}
|
|
86
|
+
if (classification.delegar === 'nivel-alto') {
|
|
87
|
+
return { level: 'Alto', effort: 'high', delegate: 'nivel-alto', reason: 'fallo difícil o seguridad', isDesign: false };
|
|
88
|
+
}
|
|
89
|
+
if (classification.model === 'opus') {
|
|
90
|
+
if (typeof quotaPercent === 'number' && Number.isFinite(quotaPercent) && quotaPercent >= LIMITE_ALTO) {
|
|
91
|
+
return {
|
|
92
|
+
level: 'Exigente',
|
|
93
|
+
effort: 'high',
|
|
94
|
+
delegate: null,
|
|
95
|
+
reason: `cuota al ${Math.round(quotaPercent)} %: Hydrogen con más esfuerzo`,
|
|
96
|
+
isDesign: true,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
return { level: 'Alto', effort: 'high', delegate: null, reason: 'diseño o ambigüedad', isDesign: true };
|
|
100
|
+
}
|
|
101
|
+
if (classification.effort === 'high') {
|
|
102
|
+
return { level: 'Exigente', effort: 'high', delegate: null, reason: 'fallo o pruebas: verificar importa', isDesign: false };
|
|
103
|
+
}
|
|
104
|
+
if (classification.effort === 'low') {
|
|
105
|
+
return { level: 'Normal', effort: 'low', delegate: null, reason: 'pregunta breve: respuesta rápida', isDesign: false };
|
|
106
|
+
}
|
|
107
|
+
return { level: 'Normal', effort: 'medium', delegate: null, reason: 'trabajo habitual', isDesign: false };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function unavailableResult(reason) {
|
|
111
|
+
return {
|
|
112
|
+
available: false,
|
|
113
|
+
silent: false,
|
|
114
|
+
recommendation: null,
|
|
115
|
+
action: 'unavailable',
|
|
116
|
+
delegate: null,
|
|
117
|
+
reason,
|
|
118
|
+
message: `NexaKit no pudo recomendar para Antigravity: ${reason}.`,
|
|
119
|
+
source: 'family-guide',
|
|
120
|
+
automaticChange: false,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Classify a task locally for Antigravity CLI without calling any model or network. */
|
|
125
|
+
export async function recommendAntigravityTask(text, options = {}) {
|
|
126
|
+
if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > MAX_TASK_BYTES) {
|
|
127
|
+
return unavailableResult('texto no válido o superior al límite de 16 KiB');
|
|
128
|
+
}
|
|
129
|
+
const trimmed = text.trim();
|
|
130
|
+
const classification = recomendarPorTexto(trimmed);
|
|
131
|
+
if (!trimmed || (classification.reason === 'trabajo habitual' && !classification.delegar && !classification.fallo && trimmed.length < 40 && CONFIRMATION_RE.test(trimmed))) {
|
|
132
|
+
return {
|
|
133
|
+
available: true,
|
|
134
|
+
silent: true,
|
|
135
|
+
recommendation: null,
|
|
136
|
+
action: 'keep',
|
|
137
|
+
delegate: null,
|
|
138
|
+
reason: '',
|
|
139
|
+
message: '',
|
|
140
|
+
source: Array.isArray(options.catalog) && options.catalog.length ? 'agy-models' : 'family-guide',
|
|
141
|
+
automaticChange: false,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const target = classifyToAntigravity(classification, options.quotaPercent);
|
|
146
|
+
const pick = resolveCatalogPick(options.catalog, target.level, target.effort);
|
|
147
|
+
const source = pick ? 'agy-models' : 'family-guide';
|
|
148
|
+
const family = pick?.family ?? DEFAULT_FAMILY_BY_LEVEL[target.level];
|
|
149
|
+
const effort = pick?.effort ?? target.effort;
|
|
150
|
+
const model = pick?.model ?? null;
|
|
151
|
+
const familyLabel = FAMILY_LABELS[family] ?? capitalize(family);
|
|
152
|
+
const label = `${familyLabel} · ${effort}`;
|
|
153
|
+
|
|
154
|
+
const current = parseAntigravityModel(options.currentModel);
|
|
155
|
+
let action = 'model';
|
|
156
|
+
if (target.delegate) {
|
|
157
|
+
action = target.delegate === 'nivel-ligero' && current.family === family && current.effort === effort ? 'keep' : 'delegate';
|
|
158
|
+
} else if (current.family && current.family === family) {
|
|
159
|
+
action = current.effort === effort ? 'keep' : 'effort';
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const proposal = target.delegate
|
|
163
|
+
? `delegar a ${target.delegate} (${label})`
|
|
164
|
+
: model
|
|
165
|
+
? `${model} (${label})`
|
|
166
|
+
: label;
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
available: true,
|
|
170
|
+
silent: false,
|
|
171
|
+
recommendation: { level: target.level, family, model, effort, label },
|
|
172
|
+
action,
|
|
173
|
+
delegate: target.delegate,
|
|
174
|
+
reason: target.reason,
|
|
175
|
+
message: `NexaKit recomienda ${proposal}. Razón: ${target.reason}.`,
|
|
176
|
+
source,
|
|
177
|
+
automaticChange: false,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
@@ -0,0 +1,291 @@
|
|
|
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
|
+
|
|
7
|
+
const SAFE_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/u;
|
|
8
|
+
const MAX_SESSION_BYTES = 16 * 1024;
|
|
9
|
+
const DEFAULT_TTL_MS = 6 * 60 * 60 * 1000;
|
|
10
|
+
const PRUNE_THRESHOLD = 50;
|
|
11
|
+
const PRUNE_AGE_MS = 24 * 60 * 60 * 1000;
|
|
12
|
+
const MAX_MAP_ENTRIES = 32;
|
|
13
|
+
|
|
14
|
+
function validSessionId(id) {
|
|
15
|
+
return typeof id === 'string' && SAFE_ID_RE.test(id);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const cleanText = (value, max = 120) =>
|
|
19
|
+
typeof value === 'string' && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(value)
|
|
20
|
+
? value.slice(0, max)
|
|
21
|
+
: null;
|
|
22
|
+
|
|
23
|
+
const clampPercent = (v) =>
|
|
24
|
+
typeof v === 'number' && Number.isFinite(v) ? Math.min(100, Math.max(0, Math.round(v))) : null;
|
|
25
|
+
|
|
26
|
+
async function resolveSafeDirectory(options, create) {
|
|
27
|
+
const home = path.resolve(options.homeDirectory ?? os.homedir());
|
|
28
|
+
const root = path.parse(home).root;
|
|
29
|
+
const ancestors = home.slice(root.length).split(path.sep).filter(Boolean);
|
|
30
|
+
let current = root;
|
|
31
|
+
for (const [index, segment] of [...ancestors, '.nexakit', 'antigravity', 'sessions'].entries()) {
|
|
32
|
+
current = path.join(current, segment);
|
|
33
|
+
const isPrivate = index >= ancestors.length;
|
|
34
|
+
try {
|
|
35
|
+
if (create && isPrivate) {
|
|
36
|
+
try { await fs.mkdir(current, { mode: 0o700 }); }
|
|
37
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
38
|
+
}
|
|
39
|
+
const stat = await fs.lstat(current);
|
|
40
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) return null;
|
|
41
|
+
if (create && isPrivate) await fs.chmod(current, 0o700);
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return current;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function sanitizeRecommendation(record) {
|
|
50
|
+
if (!record || typeof record !== 'object') return null;
|
|
51
|
+
const normalized = {
|
|
52
|
+
level: cleanText(record.level, 32),
|
|
53
|
+
family: cleanText(record.family, 32),
|
|
54
|
+
model: cleanText(record.model, 100),
|
|
55
|
+
effort: cleanText(record.effort, 24),
|
|
56
|
+
delegate: cleanText(record.delegate, 40),
|
|
57
|
+
label: cleanText(record.label, 80),
|
|
58
|
+
reason: cleanText(record.reason, 160),
|
|
59
|
+
};
|
|
60
|
+
return Object.values(normalized).some(Boolean) ? normalized : null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function boundedStringMap(obj, maxVal = 400) {
|
|
64
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return {};
|
|
65
|
+
const entries = Object.entries(obj).slice(-MAX_MAP_ENTRIES);
|
|
66
|
+
const out = {};
|
|
67
|
+
for (const [k, v] of entries) {
|
|
68
|
+
if (typeof k === 'string' && k && typeof v === 'string') out[k.slice(0, 240)] = v.slice(0, maxVal);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function boundedNumberMap(obj) {
|
|
74
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return {};
|
|
75
|
+
const entries = Object.entries(obj).slice(-MAX_MAP_ENTRIES);
|
|
76
|
+
const out = {};
|
|
77
|
+
for (const [k, v] of entries) {
|
|
78
|
+
if (typeof k === 'string' && k && typeof v === 'number' && Number.isFinite(v)) out[k.slice(0, 200)] = Math.max(0, Math.round(v));
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function defaultState(now) {
|
|
84
|
+
return {
|
|
85
|
+
version: 2,
|
|
86
|
+
updatedAt: now,
|
|
87
|
+
recommendation: null,
|
|
88
|
+
usage: { contextPercent: null, quotaPercent: null, warnedContextLevel: 0, warnedQuotaLevel: 0 },
|
|
89
|
+
lecciones: { avisoHecho: false, fallidos: {}, errores: {}, pendingRepetitionNotice: null },
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function normalizeState(parsed, now) {
|
|
94
|
+
if (!parsed || typeof parsed !== 'object' || typeof parsed.updatedAt !== 'number' || !Number.isFinite(parsed.updatedAt)) {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
if (parsed.version === 1) {
|
|
98
|
+
return {
|
|
99
|
+
...defaultState(parsed.updatedAt),
|
|
100
|
+
recommendation: sanitizeRecommendation(parsed),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
if (parsed.version !== 2) return null;
|
|
104
|
+
const usage = parsed.usage && typeof parsed.usage === 'object' ? parsed.usage : {};
|
|
105
|
+
const lec = parsed.lecciones && typeof parsed.lecciones === 'object' ? parsed.lecciones : {};
|
|
106
|
+
return {
|
|
107
|
+
version: 2,
|
|
108
|
+
updatedAt: parsed.updatedAt ?? now,
|
|
109
|
+
recommendation: sanitizeRecommendation(parsed.recommendation),
|
|
110
|
+
usage: {
|
|
111
|
+
contextPercent: clampPercent(usage.contextPercent),
|
|
112
|
+
quotaPercent: clampPercent(usage.quotaPercent),
|
|
113
|
+
warnedContextLevel: Number.isInteger(usage.warnedContextLevel) ? usage.warnedContextLevel : 0,
|
|
114
|
+
warnedQuotaLevel: Number.isInteger(usage.warnedQuotaLevel) ? usage.warnedQuotaLevel : 0,
|
|
115
|
+
},
|
|
116
|
+
lecciones: {
|
|
117
|
+
avisoHecho: lec.avisoHecho === true,
|
|
118
|
+
fallidos: boundedStringMap(lec.fallidos, 400),
|
|
119
|
+
errores: boundedNumberMap(lec.errores),
|
|
120
|
+
pendingRepetitionNotice: cleanText(lec.pendingRepetitionNotice, 360),
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function pruneExpiredSessions(dir, now) {
|
|
126
|
+
try {
|
|
127
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
128
|
+
if (entries.length <= PRUNE_THRESHOLD) return;
|
|
129
|
+
for (const entry of entries) {
|
|
130
|
+
if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
|
|
131
|
+
const file = path.join(dir, entry.name);
|
|
132
|
+
const stat = await fs.lstat(file).catch(() => null);
|
|
133
|
+
if (stat && stat.isFile() && !stat.isSymbolicLink() && now - stat.mtimeMs > PRUNE_AGE_MS) {
|
|
134
|
+
await fs.rm(file, { force: true }).catch(() => {});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
} catch {
|
|
138
|
+
// Opportunistic cleanup never blocks session writes.
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function readSafeJson(target, options) {
|
|
143
|
+
let handle;
|
|
144
|
+
try {
|
|
145
|
+
const before = await fs.lstat(target);
|
|
146
|
+
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size > MAX_SESSION_BYTES) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
handle = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
150
|
+
const stat = await handle.stat();
|
|
151
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_SESSION_BYTES || stat.dev !== before.dev || stat.ino !== before.ino) {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
const now = typeof options.now === 'number' && Number.isFinite(options.now) ? options.now : Date.now();
|
|
155
|
+
const state = normalizeState(JSON.parse(await handle.readFile('utf8')), now);
|
|
156
|
+
if (!state) return null;
|
|
157
|
+
const maxAgeMs = options.maxAgeMs ?? DEFAULT_TTL_MS;
|
|
158
|
+
if (now - state.updatedAt > maxAgeMs || state.updatedAt > now + 60_000) return null;
|
|
159
|
+
return state;
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
} finally {
|
|
163
|
+
await handle?.close().catch(() => {});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function writeSafeState(dir, target, state, now) {
|
|
168
|
+
const existing = await fs.lstat(target).catch((error) => (error.code === 'ENOENT' ? null : 'blocked'));
|
|
169
|
+
if (existing === 'blocked' || (existing && (!existing.isFile() || existing.isSymbolicLink()))) return false;
|
|
170
|
+
const sanitized = normalizeState({ ...state, version: 2, updatedAt: now }, now) ?? defaultState(now);
|
|
171
|
+
const payload = JSON.stringify(sanitized) + '\n';
|
|
172
|
+
if (Buffer.byteLength(payload, 'utf8') > MAX_SESSION_BYTES) return false;
|
|
173
|
+
const temp = path.join(dir, `.tmp-${process.pid}-${randomUUID()}.json`);
|
|
174
|
+
try {
|
|
175
|
+
await fs.writeFile(temp, payload, { flag: 'wx', mode: 0o600 });
|
|
176
|
+
await fs.rename(temp, target);
|
|
177
|
+
await pruneExpiredSessions(dir, now);
|
|
178
|
+
return true;
|
|
179
|
+
} catch {
|
|
180
|
+
return false;
|
|
181
|
+
} finally {
|
|
182
|
+
await fs.rm(temp, { force: true }).catch(() => {});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Read full bounded Antigravity conversation state if safe and fresh. */
|
|
187
|
+
export async function readAntigravitySessionState(conversationId, options = {}) {
|
|
188
|
+
if (!validSessionId(conversationId)) return null;
|
|
189
|
+
const dir = await resolveSafeDirectory(options, false);
|
|
190
|
+
if (!dir) return null;
|
|
191
|
+
return readSafeJson(path.join(dir, `${conversationId}.json`), options);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Read-modify-write conversation state atomically with private permissions and no prompt text. */
|
|
195
|
+
export async function mutateAntigravitySessionState(conversationId, updater, options = {}) {
|
|
196
|
+
if (!validSessionId(conversationId) || typeof updater !== 'function') return null;
|
|
197
|
+
const dir = await resolveSafeDirectory(options, true);
|
|
198
|
+
if (!dir) return null;
|
|
199
|
+
const target = path.join(dir, `${conversationId}.json`);
|
|
200
|
+
const now = typeof options.now === 'number' && Number.isFinite(options.now) ? options.now : Date.now();
|
|
201
|
+
const current = (await readSafeJson(target, options)) ?? defaultState(now);
|
|
202
|
+
const next = await updater(structuredClone(current));
|
|
203
|
+
if (!next) return current;
|
|
204
|
+
const ok = await writeSafeState(dir, target, next, now);
|
|
205
|
+
return ok ? normalizeState({ ...next, version: 2, updatedAt: now }, now) : null;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const bucketOf = (pct, thresholds) => (pct === null ? 0 : thresholds.filter((t) => pct >= t).length);
|
|
209
|
+
|
|
210
|
+
/** Record latest context/quota percentages only when crossing thresholds or shifting noticeably. */
|
|
211
|
+
export async function updateAntigravitySessionUsage(conversationId, { contextPercent = null, quotaPercent = null } = {}, options = {}) {
|
|
212
|
+
if (!validSessionId(conversationId)) return false;
|
|
213
|
+
const nextCtx = clampPercent(contextPercent);
|
|
214
|
+
const nextQuota = clampPercent(quotaPercent);
|
|
215
|
+
if (nextCtx === null && nextQuota === null) return false;
|
|
216
|
+
|
|
217
|
+
const existing = await readAntigravitySessionState(conversationId, options);
|
|
218
|
+
if (existing) {
|
|
219
|
+
const prevCtx = existing.usage.contextPercent;
|
|
220
|
+
const prevQuota = existing.usage.quotaPercent;
|
|
221
|
+
const ctxChanged = nextCtx !== null && (
|
|
222
|
+
prevCtx === null ||
|
|
223
|
+
Math.abs(nextCtx - prevCtx) >= 5 ||
|
|
224
|
+
bucketOf(nextCtx, [60, 80]) !== bucketOf(prevCtx, [60, 80])
|
|
225
|
+
);
|
|
226
|
+
const quotaChanged = nextQuota !== null && (
|
|
227
|
+
prevQuota === null ||
|
|
228
|
+
Math.abs(nextQuota - prevQuota) >= 5 ||
|
|
229
|
+
bucketOf(nextQuota, [70, 90]) !== bucketOf(prevQuota, [70, 90])
|
|
230
|
+
);
|
|
231
|
+
if (!ctxChanged && !quotaChanged) return true;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const saved = await mutateAntigravitySessionState(conversationId, (state) => {
|
|
235
|
+
if (nextCtx !== null) state.usage.contextPercent = nextCtx;
|
|
236
|
+
if (nextQuota !== null) state.usage.quotaPercent = nextQuota;
|
|
237
|
+
return state;
|
|
238
|
+
}, options);
|
|
239
|
+
return Boolean(saved);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Persist structured recommendation metadata for an Antigravity conversation without saving prompt text. */
|
|
243
|
+
export async function writeAntigravitySessionRecommendation(conversationId, record, options = {}) {
|
|
244
|
+
if (!validSessionId(conversationId) || !record || typeof record !== 'object') return false;
|
|
245
|
+
const rec = sanitizeRecommendation(record);
|
|
246
|
+
if (!rec) return false;
|
|
247
|
+
const saved = await mutateAntigravitySessionState(conversationId, (state) => {
|
|
248
|
+
state.recommendation = rec;
|
|
249
|
+
return state;
|
|
250
|
+
}, options);
|
|
251
|
+
return Boolean(saved);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Read recommendation metadata once and lazily sync usage thresholds only when needed. */
|
|
255
|
+
export async function syncAndReadAntigravityBarraSession(conversationId, { contextPercent = null, quotaPercent = null } = {}, options = {}) {
|
|
256
|
+
if (!validSessionId(conversationId)) return null;
|
|
257
|
+
const state = await readAntigravitySessionState(conversationId, options);
|
|
258
|
+
const nextCtx = clampPercent(contextPercent);
|
|
259
|
+
const nextQuota = clampPercent(quotaPercent);
|
|
260
|
+
if (nextCtx !== null || nextQuota !== null) {
|
|
261
|
+
const needsWrite = !state || (
|
|
262
|
+
nextCtx !== null && (
|
|
263
|
+
state.usage.contextPercent === null ||
|
|
264
|
+
Math.abs(nextCtx - state.usage.contextPercent) >= 5 ||
|
|
265
|
+
bucketOf(nextCtx, [60, 80]) !== bucketOf(state.usage.contextPercent, [60, 80])
|
|
266
|
+
)
|
|
267
|
+
) || (
|
|
268
|
+
nextQuota !== null && (
|
|
269
|
+
state.usage.quotaPercent === null ||
|
|
270
|
+
Math.abs(nextQuota - state.usage.quotaPercent) >= 5 ||
|
|
271
|
+
bucketOf(nextQuota, [70, 90]) !== bucketOf(state.usage.quotaPercent, [70, 90])
|
|
272
|
+
)
|
|
273
|
+
);
|
|
274
|
+
if (needsWrite) {
|
|
275
|
+
await mutateAntigravitySessionState(conversationId, (draft) => {
|
|
276
|
+
if (nextCtx !== null) draft.usage.contextPercent = nextCtx;
|
|
277
|
+
if (nextQuota !== null) draft.usage.quotaPercent = nextQuota;
|
|
278
|
+
return draft;
|
|
279
|
+
}, options);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (!state?.recommendation) return null;
|
|
283
|
+
return { version: 1, updatedAt: state.updatedAt, ...state.recommendation };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Read structured recommendation metadata for an Antigravity conversation if safe and fresh. */
|
|
287
|
+
export async function readAntigravitySessionRecommendation(conversationId, options = {}) {
|
|
288
|
+
const state = await readAntigravitySessionState(conversationId, options);
|
|
289
|
+
if (!state?.recommendation) return null;
|
|
290
|
+
return { version: 1, updatedAt: state.updatedAt, ...state.recommendation };
|
|
291
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { renderAntigravityAgents } from './antigravity-agents.js';
|
|
6
|
+
|
|
7
|
+
const TOOL_MATCHER = 'run_command|write_file|write_to_file|edit_file|replace_file_content|multi_replace_file_content';
|
|
8
|
+
|
|
9
|
+
/** Build a safely quoted shell command invoking `nexakit antigravity <subcommand>`. */
|
|
10
|
+
export function buildAntigravityCommand(subcommand, {
|
|
11
|
+
executable = process.execPath,
|
|
12
|
+
entrypoint = fileURLToPath(new URL('../bin/nexakit.js', import.meta.url)),
|
|
13
|
+
platform = process.platform,
|
|
14
|
+
} = {}) {
|
|
15
|
+
const pathApi = platform === 'win32' ? path.win32 : path.posix;
|
|
16
|
+
for (const value of [executable, entrypoint]) {
|
|
17
|
+
if (!pathApi.isAbsolute(value) || /[\0\r\n]/u.test(value)) {
|
|
18
|
+
throw new Error('El comando requiere rutas absolutas seguras.');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (platform === 'win32') {
|
|
22
|
+
if ([executable, entrypoint].some((value) => /[%!"\r\n]/u.test(value))) {
|
|
23
|
+
throw new Error('Ruta incompatible con quoting seguro en Windows.');
|
|
24
|
+
}
|
|
25
|
+
return `"${executable}" "${entrypoint}" antigravity ${subcommand}`;
|
|
26
|
+
}
|
|
27
|
+
const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
28
|
+
return `${quote(executable)} ${quote(entrypoint)} antigravity ${subcommand}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function isDarwinSystemLink(current) {
|
|
32
|
+
if (process.platform !== 'darwin' || (current !== '/tmp' && current !== '/var')) return false;
|
|
33
|
+
return (await fs.realpath(current).catch(() => null)) === `/private${current}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function assertNoSymlinkAncestors(destination) {
|
|
37
|
+
let current = destination;
|
|
38
|
+
while (true) {
|
|
39
|
+
try {
|
|
40
|
+
const stat = await fs.lstat(current);
|
|
41
|
+
if (stat.isSymbolicLink() && !(await isDarwinSystemLink(current))) {
|
|
42
|
+
throw new Error('No se admiten enlaces simbólicos en el destino.');
|
|
43
|
+
}
|
|
44
|
+
if (current !== destination && !stat.isDirectory() && !(await isDarwinSystemLink(current))) {
|
|
45
|
+
throw new Error('El padre no es una carpeta.');
|
|
46
|
+
}
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (error.code !== 'ENOENT') throw error;
|
|
49
|
+
}
|
|
50
|
+
const parent = path.dirname(current);
|
|
51
|
+
if (parent === current) break;
|
|
52
|
+
current = parent;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const within = (root, destination) => {
|
|
57
|
+
const relative = path.relative(path.resolve(root), destination);
|
|
58
|
+
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** Generate manual preview or write a valid standalone Antigravity CLI plugin + statusLine package. */
|
|
62
|
+
export async function prepareAntigravity({
|
|
63
|
+
outputDirectory,
|
|
64
|
+
apply = false,
|
|
65
|
+
homeDirectory = os.homedir(),
|
|
66
|
+
projectRoot = process.cwd(),
|
|
67
|
+
} = {}) {
|
|
68
|
+
if (apply && !outputDirectory) throw new Error('--apply requiere --salida.');
|
|
69
|
+
const destination = outputDirectory ? path.resolve(outputDirectory) : null;
|
|
70
|
+
if (destination) {
|
|
71
|
+
const protectedRoots = [
|
|
72
|
+
path.join(homeDirectory, '.gemini'),
|
|
73
|
+
path.join(projectRoot, '.agents'),
|
|
74
|
+
path.join(projectRoot, '.agent'),
|
|
75
|
+
path.join(projectRoot, '_agents'),
|
|
76
|
+
path.join(projectRoot, '_agent'),
|
|
77
|
+
];
|
|
78
|
+
if (protectedRoots.some((root) => within(root, destination))) {
|
|
79
|
+
throw new Error('El paquete debe quedar fuera de la configuración activa de Antigravity.');
|
|
80
|
+
}
|
|
81
|
+
await assertNoSymlinkAncestors(destination);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const statusLineCommand = buildAntigravityCommand('barra');
|
|
85
|
+
const hookCommand = buildAntigravityCommand('hook');
|
|
86
|
+
|
|
87
|
+
const pluginManifest = {
|
|
88
|
+
name: 'nexakit-antigravity',
|
|
89
|
+
version: '1.0.0',
|
|
90
|
+
description: 'Barra statusLine, niveles/subagentes, guardarraíles, ahorro, lecciones y avisos de sesión de NexaKit para Antigravity.',
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const settingsSnippet = {
|
|
94
|
+
statusLine: {
|
|
95
|
+
type: 'command',
|
|
96
|
+
command: statusLineCommand,
|
|
97
|
+
enabled: true,
|
|
98
|
+
padding: 0,
|
|
99
|
+
stack_with_default: false,
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const hooksSnippet = {
|
|
104
|
+
'nexakit-antigravity': {
|
|
105
|
+
SessionStart: [{ type: 'command', command: hookCommand, timeout: 5 }],
|
|
106
|
+
PreInvocation: [{ type: 'command', command: hookCommand, timeout: 5 }],
|
|
107
|
+
PreToolUse: [{ matcher: TOOL_MATCHER, hooks: [{ type: 'command', command: hookCommand, timeout: 5 }] }],
|
|
108
|
+
PostToolUse: [{ matcher: TOOL_MATCHER, hooks: [{ type: 'command', command: hookCommand, timeout: 5 }] }],
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const renderedAgents = await renderAntigravityAgents();
|
|
113
|
+
const readme = [
|
|
114
|
+
'# Paquete Antigravity CLI: activación manual',
|
|
115
|
+
'',
|
|
116
|
+
'Vista previa / plugin válido para Antigravity CLI (`agy`); no modifica `~/.gemini` automáticamente.',
|
|
117
|
+
'',
|
|
118
|
+
'## 1. Activar la barra de estado',
|
|
119
|
+
'',
|
|
120
|
+
'Dentro de `agy`, ejecuta:',
|
|
121
|
+
'',
|
|
122
|
+
'```text',
|
|
123
|
+
`/statusline ${statusLineCommand}`,
|
|
124
|
+
'```',
|
|
125
|
+
'',
|
|
126
|
+
'O copia el bloque `statusLine` de `settings.statusline.json` dentro de `~/.gemini/antigravity-cli/settings.json`.',
|
|
127
|
+
'La barra muestra modelo, esfuerzo, acierto de caché, contexto, cuota con reinicio desde el 60 % y hasta 4 subagentes recientes.',
|
|
128
|
+
'',
|
|
129
|
+
'## 2. Instalar hooks y subagentes (`niveles`, guardarraíles, ahorro, lecciones y sesión)',
|
|
130
|
+
'',
|
|
131
|
+
'Puedes instalar esta carpeta directamente como plugin en Antigravity (`agy plugin install <carpeta>`) o instalar por partes:',
|
|
132
|
+
'- **Subagentes (`agents/*.md`)**: `nexakit antigravity agentes --apply` (global en `~/.gemini/config/agents/`) o `--proyecto` (`.agents/agents/`).',
|
|
133
|
+
'- **Hooks (`hooks.json`)**: fusiona `nexakit-antigravity` en `~/.gemini/config/hooks.json` o `.agents/hooks.json`.',
|
|
134
|
+
'',
|
|
135
|
+
'Cobertura incluida:',
|
|
136
|
+
'- `PreInvocation` / `SessionStart`: recomendación de modelo por tarea (sin guardar texto del prompt), recordatorio y registro de correcciones/lecciones, y avisos únicos al 60 % / 80 % de contexto y 70 % / 90 % de cuota.',
|
|
137
|
+
'- `PreToolUse` / `PostToolUse`: bloqueo de comandos peligrosos, secretos en `.env`/claves y commits mal formateados (`guardarrailes`), recorte de salidas largas de pruebas/build/lint (`ahorro` vía `nexakit antigravity ejecutar`) y freno a reintentos fallidos idénticos (`lecciones`).',
|
|
138
|
+
'',
|
|
139
|
+
'## Limitaciones de Antigravity CLI (`agy`)',
|
|
140
|
+
'',
|
|
141
|
+
'- La barra aplica solo a Antigravity CLI (`agy`), no a la app de escritorio ni al IDE.',
|
|
142
|
+
'- `agy` no emite evento mientras escribes (`prompt.edit`), así que la recomendación aparece al enviar el mensaje.',
|
|
143
|
+
'- `subagents` en `statusLine` informa nombre, rol y estado, sin contadores de tokens por subagente.',
|
|
144
|
+
'- Los comandos usan rutas absolutas: regenera el paquete si mueves NexaKit o Node.',
|
|
145
|
+
'',
|
|
146
|
+
].join('\n');
|
|
147
|
+
|
|
148
|
+
const files = {
|
|
149
|
+
'plugin.json': JSON.stringify(pluginManifest, null, 2) + '\n',
|
|
150
|
+
'settings.statusline.json': JSON.stringify(settingsSnippet, null, 2) + '\n',
|
|
151
|
+
'hooks.json': JSON.stringify(hooksSnippet, null, 2) + '\n',
|
|
152
|
+
'README.md': readme,
|
|
153
|
+
...Object.fromEntries(renderedAgents.map((agent) => [`agents/${agent.filename}`, agent.content])),
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
if (apply) {
|
|
157
|
+
await fs.mkdir(destination, { mode: 0o700 });
|
|
158
|
+
await fs.mkdir(path.join(destination, 'agents'), { mode: 0o700 });
|
|
159
|
+
for (const [name, contents] of Object.entries(files)) {
|
|
160
|
+
await fs.writeFile(path.join(destination, name), contents, { flag: 'wx', mode: 0o600 });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
applied: apply,
|
|
166
|
+
outputDirectory: destination,
|
|
167
|
+
statusLineCommand,
|
|
168
|
+
files,
|
|
169
|
+
limitations: [
|
|
170
|
+
'Activación manual; aplica solo a Antigravity CLI (agy).',
|
|
171
|
+
'Sin evento mientras escribes: la recomendación se evalúa al enviar vía PreInvocation.',
|
|
172
|
+
'subagents en statusLine no incluye tokens por subagente.',
|
|
173
|
+
],
|
|
174
|
+
};
|
|
175
|
+
}
|
package/src/codex-output.js
CHANGED
|
@@ -132,8 +132,13 @@ export async function runCodexOutput(argv, { out, err, input }, options = {}) {
|
|
|
132
132
|
try {
|
|
133
133
|
// Automatic wrapping runs inside the tool sandbox. Its private temporary
|
|
134
134
|
// store requires no additional access to the real user home.
|
|
135
|
-
const
|
|
136
|
-
?
|
|
135
|
+
const tempAgent = env.NEXAKIT_ANTIGRAVITY_TEMP_OUTPUT === '1'
|
|
136
|
+
? 'antigravity'
|
|
137
|
+
: env.NEXAKIT_CODEX_TEMP_OUTPUT === '1'
|
|
138
|
+
? 'codex'
|
|
139
|
+
: null;
|
|
140
|
+
const root = tempAgent
|
|
141
|
+
? privateDirectory(path.join(directory(fs.realpathSync(options.tempDirectory ?? os.tmpdir())), `nexakit-${tempAgent}-${process.getuid?.() ?? 'user'}`))
|
|
137
142
|
: directory(options.homeDirectory ?? os.homedir());
|
|
138
143
|
home = privateDirectory(path.join(root, '.nexakit'));
|
|
139
144
|
const folder = privateDirectory(path.join(home, 'salidas'));
|
|
@@ -215,7 +220,7 @@ export async function runCodexOutput(argv, { out, err, input }, options = {}) {
|
|
|
215
220
|
const linesAfter = results.reduce((sum, result) => sum + (result.text ? result.text.split('\n').length : 0), 0);
|
|
216
221
|
if (results.some(result => result.trimmed) && before > after && linesBefore >= linesAfter) {
|
|
217
222
|
try {
|
|
218
|
-
record(home, { fecha: Date.now(), antes: before, despues: after, lineasAntes: linesBefore, lineasDespues: linesAfter, agent: 'codex' });
|
|
223
|
+
record(home, { fecha: Date.now(), antes: before, despues: after, lineasAntes: linesBefore, lineasDespues: linesAfter, agent: options.agent ?? 'codex' });
|
|
219
224
|
} catch { emit(err, 'nexakit: no se pudo guardar el registro de ahorro.\n'); }
|
|
220
225
|
}
|
|
221
226
|
}
|