@aliip/pilah 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BUILD_STATUS.md +23 -0
- package/LICENSE +21 -0
- package/README.md +108 -2
- package/assets/logo.svg +5 -0
- package/docs/ACCEPTANCE_GATE.md +41 -0
- package/docs/ADAPTIVE_RCA_WORKFLOW.md +93 -0
- package/docs/AGENT_DECISION_REVIEW.md +17 -0
- package/docs/ALWAYS_ON_5_WHYS.md +75 -0
- package/docs/ARCHITECTURE.md +43 -0
- package/docs/BEHAVIORAL_5_WHYS_V2_0_1.md +117 -0
- package/docs/CHECKPOINT_RECOVERY.md +86 -0
- package/docs/CI_EFFICIENCY.md +63 -0
- package/docs/COMPATIBILITY.md +84 -0
- package/docs/CONTRACTS.md +177 -0
- package/docs/CONVERSATION_USAGE.md +52 -0
- package/docs/ENGINEERING_METHOD.md +68 -0
- package/docs/HOST_VALIDATION.md +35 -0
- package/docs/INDEPENDENT_ACCEPTANCE_RUNBOOK.md +72 -0
- package/docs/INTERVENTION_LEDGER.md +25 -0
- package/docs/MAIN_VALIDATION_BACKLOG.md +19 -0
- package/docs/NATIVE_FIRST_WORKFLOW.md +27 -0
- package/docs/OPEN_SOURCE_ENGINEERING_STANDARDS.md +62 -0
- package/docs/ORCHESTRATION_ADVISOR.md +36 -0
- package/docs/PRE_VNEXT_INTEGRATION.md +27 -0
- package/docs/README.md +54 -0
- package/docs/RELEASE.md +33 -0
- package/docs/RELEASE_AUTHORIZATION.md +33 -0
- package/docs/RISK_GUIDANCE.md +18 -0
- package/docs/SECURITY.md +76 -0
- package/docs/SECURITY_RELIABILITY_AUDIT_V2_0_1.md +55 -0
- package/docs/SEMANTIC_EVIDENCE.md +27 -0
- package/docs/SOURCES.md +13 -0
- package/docs/TOKEN_EFFICIENCY.md +71 -0
- package/docs/TOKEN_PROVENANCE.md +15 -0
- package/docs/V2_0_1_TRACEABILITY.md +66 -0
- package/hooks.json +45 -0
- package/mcp_config.json +16 -0
- package/package.json +31 -4
- package/plugin.json +27 -0
- package/rules/AGENTS.md +2 -0
- package/schemas/database.sql +84 -0
- package/schemas/mcp-tools.json +552 -0
- package/scripts/a2a.mjs +344 -0
- package/scripts/check-release.mjs +42 -0
- package/scripts/check-syntax.mjs +30 -0
- package/scripts/checkpoint.mjs +50 -0
- package/scripts/compare-agent-traces.mjs +53 -0
- package/scripts/context-guardian.mjs +132 -0
- package/scripts/evaluate-acceptance.mjs +110 -0
- package/scripts/export-benchmark.mjs +31 -0
- package/scripts/generate-contracts.mjs +6 -0
- package/scripts/hook.mjs +406 -0
- package/scripts/host-check.mjs +40 -0
- package/scripts/intervention-ledger.mjs +94 -0
- package/scripts/pilah.mjs +3 -0
- package/scripts/release-authorization.mjs +137 -0
- package/scripts/review-agent-decisions.mjs +34 -0
- package/scripts/semantic-evidence.mjs +15 -0
- package/scripts/verifykit.mjs +3 -0
- package/skills/pilah/SKILL.md +24 -0
- package/src/acceptance-matrix.mjs +84 -0
- package/src/browser-evidence.mjs +40 -0
- package/src/context-health.mjs +14 -0
- package/src/conversations.mjs +302 -0
- package/src/engine.mjs +494 -0
- package/src/graph.mjs +169 -0
- package/src/mcp-diagnostics.mjs +53 -0
- package/src/mcp.mjs +151 -0
- package/src/model-recovery.mjs +108 -0
- package/src/native-tool-recovery.mjs +45 -0
- package/src/node-runtime.mjs +13 -0
- package/src/orchestration-advisor.mjs +24 -0
- package/src/rca.mjs +174 -0
- package/src/risk-guidance.mjs +95 -0
- package/src/scanner.mjs +303 -0
- package/src/security.mjs +793 -0
- package/src/semantic-evidence.mjs +144 -0
- package/src/skill-discovery.mjs +23 -0
- package/src/sqlite-compat.mjs +11 -0
- package/src/storage.mjs +455 -0
- package/src/tokens.mjs +627 -0
- package/src/tools.mjs +164 -0
- package/src/verification.mjs +567 -0
- package/src/workflow-router.mjs +34 -0
package/src/tokens.mjs
ADDED
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { dataDir,getHomeDir } from './security.mjs';
|
|
4
|
+
|
|
5
|
+
export const estimateTokens = (textOrBytes) => {
|
|
6
|
+
if (typeof textOrBytes === 'string') {
|
|
7
|
+
if (textOrBytes.length === 0) return 0;
|
|
8
|
+
return Math.max(1, Math.round(textOrBytes.length / 3.8));
|
|
9
|
+
}
|
|
10
|
+
if (typeof textOrBytes === 'number') {
|
|
11
|
+
if (!Number.isFinite(textOrBytes) || textOrBytes <= 0) return 0;
|
|
12
|
+
return Math.max(1, Math.round(textOrBytes / 3.8));
|
|
13
|
+
}
|
|
14
|
+
return 0;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const C_STYLE_EXTS = new Set([
|
|
18
|
+
'.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts',
|
|
19
|
+
'.go', '.rs', '.java', '.kt', '.kts', '.swift', '.dart', '.cs',
|
|
20
|
+
'.c', '.h', '.cpp', '.hpp', '.cc', '.php', '.scss',
|
|
21
|
+
]);
|
|
22
|
+
const JS_LIKE_EXTS = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts']);
|
|
23
|
+
const HASH_EXTS = new Set(['.py', '.rb', '.sh', '.bash', '.zsh', '.yaml', '.yml', '.toml', '.php', '.ex', '.exs', '.gd']);
|
|
24
|
+
const DASH_EXTS = new Set(['.sql', '.lua']);
|
|
25
|
+
const HTML_EXTS = new Set(['.html', '.htm', '.xml', '.vue', '.svelte']);
|
|
26
|
+
const REGEX_PREFIX_KEYWORDS = new Set([
|
|
27
|
+
'return', 'throw', 'case', 'in', 'of', 'typeof', 'void', 'delete', 'yield', 'await', 'else', 'new', 'do',
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Single-pass state-machine lexer that strips comments while preserving string literals,
|
|
32
|
+
* template literals (including ${...} expressions), and JS/TS regex literals.
|
|
33
|
+
*/
|
|
34
|
+
export function stripCommentsLex(code, ext = '', { preserveLines = false } = {}) {
|
|
35
|
+
if (!code || typeof code !== 'string') return '';
|
|
36
|
+
let normExt = String(ext || '').trim().toLowerCase();
|
|
37
|
+
if (normExt && !normExt.startsWith('.')) normExt = '.' + normExt;
|
|
38
|
+
|
|
39
|
+
const isHtml = HTML_EXTS.has(normExt);
|
|
40
|
+
const isCssOnly = normExt === '.css';
|
|
41
|
+
const isCStyle = !normExt || C_STYLE_EXTS.has(normExt);
|
|
42
|
+
const isHash = HASH_EXTS.has(normExt);
|
|
43
|
+
const isDashDash = DASH_EXTS.has(normExt);
|
|
44
|
+
const isJsLike = !normExt || JS_LIKE_EXTS.has(normExt);
|
|
45
|
+
const isGo = normExt === '.go';
|
|
46
|
+
const isRust = normExt === '.rs';
|
|
47
|
+
const isPhp = normExt === '.php';
|
|
48
|
+
const isPython = normExt === '.py';
|
|
49
|
+
|
|
50
|
+
const len = code.length;
|
|
51
|
+
let out = '';
|
|
52
|
+
let i = 0;
|
|
53
|
+
let canStartRegex = true;
|
|
54
|
+
const templateBraceStack = [];
|
|
55
|
+
|
|
56
|
+
const emitCommentGap = (start, end) => {
|
|
57
|
+
if (!preserveLines) {
|
|
58
|
+
for (let k = start; k < end; k++) {
|
|
59
|
+
if (code[k] === '\n') { out += '\n'; break; }
|
|
60
|
+
}
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
for (let k = start; k < end; k++) {
|
|
64
|
+
out += code[k] === '\n' ? '\n' : ' ';
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
while (i < len) {
|
|
69
|
+
const ch = code[i];
|
|
70
|
+
|
|
71
|
+
// Inside template literal backtick text when returning from a ${...} expression
|
|
72
|
+
if (ch === '}' && templateBraceStack.length > 0 && templateBraceStack[templateBraceStack.length - 1] === 0) {
|
|
73
|
+
templateBraceStack.pop();
|
|
74
|
+
out += '}';
|
|
75
|
+
i++;
|
|
76
|
+
// Continue consuming template literal until closing ` or next ${
|
|
77
|
+
while (i < len) {
|
|
78
|
+
const tc = code[i];
|
|
79
|
+
if (tc === '\\' && i + 1 < len) {
|
|
80
|
+
out += tc + code[i + 1];
|
|
81
|
+
i += 2;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (tc === '$' && code[i + 1] === '{') {
|
|
85
|
+
out += '${';
|
|
86
|
+
i += 2;
|
|
87
|
+
templateBraceStack.push(0);
|
|
88
|
+
canStartRegex = true;
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
out += tc;
|
|
92
|
+
i++;
|
|
93
|
+
if (tc === '`') {
|
|
94
|
+
canStartRegex = false;
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Track brace nesting inside ${...}
|
|
102
|
+
if (templateBraceStack.length > 0) {
|
|
103
|
+
if (ch === '{') templateBraceStack[templateBraceStack.length - 1]++;
|
|
104
|
+
else if (ch === '}') templateBraceStack[templateBraceStack.length - 1]--;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// HTML / XML / Vue / Svelte comments <!-- ... -->
|
|
108
|
+
if (isHtml && code.startsWith('<!--', i)) {
|
|
109
|
+
const endIdx = code.indexOf('-->', i + 4);
|
|
110
|
+
const end = endIdx === -1 ? len : endIdx + 3;
|
|
111
|
+
emitCommentGap(i, end);
|
|
112
|
+
i = end;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Block comments /* ... */
|
|
117
|
+
if ((isCStyle || isCssOnly) && ch === '/' && code[i + 1] === '*') {
|
|
118
|
+
const endIdx = code.indexOf('*/', i + 2);
|
|
119
|
+
const end = endIdx === -1 ? len : endIdx + 2;
|
|
120
|
+
emitCommentGap(i, end);
|
|
121
|
+
i = end;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Line comments // ...
|
|
126
|
+
if (isCStyle && ch === '/' && code[i + 1] === '/') {
|
|
127
|
+
let end = code.indexOf('\n', i + 2);
|
|
128
|
+
if (end === -1) end = len;
|
|
129
|
+
if (preserveLines) emitCommentGap(i, end);
|
|
130
|
+
i = end;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Hash comments # ... (preserve PHP 8 attributes #[...])
|
|
135
|
+
if (isHash && ch === '#' && !(isPhp && code[i + 1] === '[')) {
|
|
136
|
+
let end = code.indexOf('\n', i + 1);
|
|
137
|
+
if (end === -1) end = len;
|
|
138
|
+
if (preserveLines) emitCommentGap(i, end);
|
|
139
|
+
i = end;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// SQL / Lua comments -- ...
|
|
144
|
+
if (isDashDash && ch === '-' && code[i + 1] === '-') {
|
|
145
|
+
let end = code.indexOf('\n', i + 2);
|
|
146
|
+
if (end === -1) end = len;
|
|
147
|
+
if (preserveLines) emitCommentGap(i, end);
|
|
148
|
+
i = end;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Python triple-quoted strings
|
|
153
|
+
if (isPython && (code.startsWith('"""', i) || code.startsWith("'''", i))) {
|
|
154
|
+
const delim = code.slice(i, i + 3);
|
|
155
|
+
out += delim;
|
|
156
|
+
i += 3;
|
|
157
|
+
while (i < len) {
|
|
158
|
+
if (code[i] === '\\' && i + 1 < len) {
|
|
159
|
+
out += code[i] + code[i + 1];
|
|
160
|
+
i += 2;
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (code.startsWith(delim, i)) {
|
|
164
|
+
out += delim;
|
|
165
|
+
i += 3;
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
out += code[i++];
|
|
169
|
+
}
|
|
170
|
+
canStartRegex = false;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Double-quoted strings
|
|
175
|
+
if (ch === '"') {
|
|
176
|
+
out += ch;
|
|
177
|
+
i++;
|
|
178
|
+
while (i < len) {
|
|
179
|
+
const sc = code[i];
|
|
180
|
+
out += sc;
|
|
181
|
+
i++;
|
|
182
|
+
if (sc === '\\' && i < len) {
|
|
183
|
+
out += code[i++];
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
if (sc === '"') break;
|
|
187
|
+
}
|
|
188
|
+
canStartRegex = false;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Single-quoted strings (skip Rust lifetimes like 'a or 'static)
|
|
193
|
+
if (ch === "'") {
|
|
194
|
+
let isCharOrStr = true;
|
|
195
|
+
if (isRust) {
|
|
196
|
+
const isEscChar = code[i + 1] === '\\' && i + 3 < len && code[i + 3] === "'";
|
|
197
|
+
const isPlainChar = code[i + 1] && code[i + 1] !== '\\' && code[i + 2] === "'";
|
|
198
|
+
isCharOrStr = isEscChar || isPlainChar;
|
|
199
|
+
}
|
|
200
|
+
if (isCharOrStr) {
|
|
201
|
+
out += ch;
|
|
202
|
+
i++;
|
|
203
|
+
while (i < len) {
|
|
204
|
+
const sc = code[i];
|
|
205
|
+
out += sc;
|
|
206
|
+
i++;
|
|
207
|
+
if (sc === '\\' && i < len) {
|
|
208
|
+
out += code[i++];
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (sc === "'") break;
|
|
212
|
+
}
|
|
213
|
+
canStartRegex = false;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Backtick template literals (JS/TS) or raw strings (Go)
|
|
219
|
+
if (ch === '`' && (isJsLike || isGo)) {
|
|
220
|
+
out += ch;
|
|
221
|
+
i++;
|
|
222
|
+
while (i < len) {
|
|
223
|
+
const tc = code[i];
|
|
224
|
+
if (!isGo && tc === '\\' && i + 1 < len) {
|
|
225
|
+
out += tc + code[i + 1];
|
|
226
|
+
i += 2;
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (isJsLike && tc === '$' && code[i + 1] === '{') {
|
|
230
|
+
out += '${';
|
|
231
|
+
i += 2;
|
|
232
|
+
templateBraceStack.push(0);
|
|
233
|
+
canStartRegex = true;
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
out += tc;
|
|
237
|
+
i++;
|
|
238
|
+
if (tc === '`') {
|
|
239
|
+
canStartRegex = false;
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// JS/TS regex literals /.../flags
|
|
247
|
+
if (isJsLike && ch === '/' && canStartRegex && code[i + 1] !== '/' && code[i + 1] !== '*') {
|
|
248
|
+
out += ch;
|
|
249
|
+
i++;
|
|
250
|
+
let inClass = false;
|
|
251
|
+
while (i < len) {
|
|
252
|
+
const rc = code[i];
|
|
253
|
+
if (rc === '\n') break;
|
|
254
|
+
out += rc;
|
|
255
|
+
i++;
|
|
256
|
+
if (rc === '\\' && i < len) {
|
|
257
|
+
out += code[i++];
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
if (rc === '[') inClass = true;
|
|
261
|
+
else if (rc === ']' && inClass) inClass = false;
|
|
262
|
+
else if (rc === '/' && !inClass) break;
|
|
263
|
+
}
|
|
264
|
+
while (i < len && /[a-zA-Z]/.test(code[i])) out += code[i++];
|
|
265
|
+
canStartRegex = false;
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Identifiers and keywords
|
|
270
|
+
if (/[A-Za-z_$]/.test(ch)) {
|
|
271
|
+
let end = i + 1;
|
|
272
|
+
while (end < len && /[\w$]/.test(code[end])) end++;
|
|
273
|
+
const word = code.slice(i, end);
|
|
274
|
+
out += word;
|
|
275
|
+
i = end;
|
|
276
|
+
canStartRegex = REGEX_PREFIX_KEYWORDS.has(word);
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// Numbers
|
|
281
|
+
if (/[0-9]/.test(ch)) {
|
|
282
|
+
let end = i + 1;
|
|
283
|
+
while (end < len && /[\w.]/.test(code[end])) end++;
|
|
284
|
+
out += code.slice(i, end);
|
|
285
|
+
i = end;
|
|
286
|
+
canStartRegex = false;
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
out += ch;
|
|
291
|
+
i++;
|
|
292
|
+
if (ch === ')' || ch === ']' || ch === '}') {
|
|
293
|
+
canStartRegex = false;
|
|
294
|
+
} else if ('([,;:?=!&|^~+-*%<>\n'.includes(ch)) {
|
|
295
|
+
canStartRegex = true;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
return out;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* A2A Code Skeletonizer: Strips comments and redundant blank lines using a
|
|
304
|
+
* single-pass lexer while preserving strings, templates, regexes, and code structure.
|
|
305
|
+
*/
|
|
306
|
+
export function skeletonizeCode(code, ext = '') {
|
|
307
|
+
if (!code || typeof code !== 'string') return '';
|
|
308
|
+
const stripped = stripCommentsLex(code, ext, { preserveLines: false });
|
|
309
|
+
return stripped
|
|
310
|
+
.replace(/[ \t]+$/gm, '')
|
|
311
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
312
|
+
.trim();
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* A2A Context Minifier: Compacts whitespace while preserving leading indentation.
|
|
317
|
+
*/
|
|
318
|
+
export function minifyContext(text) {
|
|
319
|
+
if (!text || typeof text !== 'string') return '';
|
|
320
|
+
return text
|
|
321
|
+
.split('\n')
|
|
322
|
+
.map(line => {
|
|
323
|
+
const m = line.match(/^([ \t]*)(.*)$/);
|
|
324
|
+
const indent = m[1];
|
|
325
|
+
const body = m[2].replace(/[ \t]+/g, ' ').trimEnd();
|
|
326
|
+
return indent + body;
|
|
327
|
+
})
|
|
328
|
+
.join('\n')
|
|
329
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
330
|
+
.trim();
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* A2A cannot infer billable savings from tool/source-size estimates. Retained
|
|
335
|
+
* as a compatibility helper but deliberately does not fabricate a USD amount.
|
|
336
|
+
*/
|
|
337
|
+
export function estimateCostSavings() { return null; }
|
|
338
|
+
|
|
339
|
+
export function estimateSessionCost() {
|
|
340
|
+
return {
|
|
341
|
+
approximate:false,
|
|
342
|
+
estimated_usd:null,
|
|
343
|
+
reason:'Model-specific price, billing plan, and verified token accounting were not provided.',
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function sanitizeConversationId(raw) {
|
|
348
|
+
if (!raw || typeof raw !== 'string') return null;
|
|
349
|
+
const trimmed = raw.trim();
|
|
350
|
+
if (!trimmed || trimmed.includes('\0') || trimmed.includes('..') || trimmed.includes('/') || trimmed.includes('\\')) {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
if (!/^[A-Za-z0-9._-]{1,128}$/.test(trimmed)) return null;
|
|
354
|
+
return trimmed;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function getBrainRoots() {
|
|
358
|
+
if (process.env.ANTIGRAVITY_APP_DATA_DIR) {
|
|
359
|
+
return [path.join(path.resolve(process.env.ANTIGRAVITY_APP_DATA_DIR), 'brain')];
|
|
360
|
+
}
|
|
361
|
+
const home = getHomeDir();
|
|
362
|
+
return ['antigravity', 'antigravity-cli', 'antigravity-ide'].map(d => path.join(home, '.gemini', d, 'brain'));
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function isSubagentTranscript(filePath) {
|
|
366
|
+
try {
|
|
367
|
+
const fd = fs.openSync(filePath, 'r');
|
|
368
|
+
try {
|
|
369
|
+
const buf = Buffer.alloc(4096);
|
|
370
|
+
const read = fs.readSync(fd, buf, 0, 4096, 0);
|
|
371
|
+
return buf.subarray(0, read).toString('utf8').includes('<subagent_reminder>');
|
|
372
|
+
} finally {
|
|
373
|
+
fs.closeSync(fd);
|
|
374
|
+
}
|
|
375
|
+
} catch {
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// A transcript reference is metadata supplied by a hook or caller, not permission
|
|
381
|
+
// to read arbitrary local files. Require the exact Antigravity brain layout.
|
|
382
|
+
export function vettedTranscript(candidate,expectedId=null){
|
|
383
|
+
if(typeof candidate!=='string'||!candidate)return null;
|
|
384
|
+
const requested=path.resolve(candidate);
|
|
385
|
+
for(const brain of getBrainRoots()){
|
|
386
|
+
const base=path.resolve(brain);
|
|
387
|
+
const rel=path.relative(base,requested);
|
|
388
|
+
const seg=rel.split(path.sep);
|
|
389
|
+
if(seg.length!==4||!sanitizeConversationId(seg[0])||
|
|
390
|
+
seg[1]!=='.system_generated'||seg[2]!=='logs'||seg[3]!=='transcript.jsonl'||
|
|
391
|
+
(expectedId&&seg[0]!==expectedId))continue;
|
|
392
|
+
try{
|
|
393
|
+
// Reject symlinks at every descendant path component, including files.
|
|
394
|
+
let cursor=base;
|
|
395
|
+
for(const part of seg){
|
|
396
|
+
cursor=path.join(cursor,part);
|
|
397
|
+
if(fs.lstatSync(cursor).isSymbolicLink())throw Error('Symlink transcript denied');
|
|
398
|
+
}
|
|
399
|
+
const canonical=fs.realpathSync(requested);
|
|
400
|
+
const realRel=path.relative(fs.realpathSync(base),canonical);
|
|
401
|
+
if(realRel!==rel||!fs.statSync(canonical).isFile())continue;
|
|
402
|
+
return {convId:seg[0],logFile:canonical};
|
|
403
|
+
}catch{}
|
|
404
|
+
}
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
function resolveTranscriptTarget({ conversationId = null, transcriptPath = null, workspace = null, dataDirPath = null } = {}) {
|
|
408
|
+
const cleanId = sanitizeConversationId(conversationId);
|
|
409
|
+
if (conversationId && !cleanId) return null;
|
|
410
|
+
|
|
411
|
+
if(transcriptPath){
|
|
412
|
+
const candidate=vettedTranscript(transcriptPath,cleanId);
|
|
413
|
+
return candidate?{...candidate,source:'explicit-transcript-path'}:null;
|
|
414
|
+
}
|
|
415
|
+
if(cleanId){
|
|
416
|
+
for(const brain of getBrainRoots()){
|
|
417
|
+
const candidate=vettedTranscript(path.join(brain,cleanId,'.system_generated','logs','transcript.jsonl'),cleanId);
|
|
418
|
+
if(candidate)return {...candidate,source:'explicit-conversation-id'};
|
|
419
|
+
}
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
const envId=sanitizeConversationId(process.env.ANTIGRAVITY_CONVERSATION_ID);
|
|
423
|
+
if(envId){
|
|
424
|
+
for(const brain of getBrainRoots()){
|
|
425
|
+
const candidate=vettedTranscript(path.join(brain,envId,'.system_generated','logs','transcript.jsonl'),envId);
|
|
426
|
+
if(candidate)return {...candidate,source:'env-conversation-id'};
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
try{
|
|
430
|
+
const base=dataDirPath||dataDir();
|
|
431
|
+
const sessionFile=path.join(base,'active-session.json');
|
|
432
|
+
const stat=fs.lstatSync(sessionFile);
|
|
433
|
+
if(!stat.isFile()||stat.size>128*1024)return null;
|
|
434
|
+
const sessionData=JSON.parse(fs.readFileSync(sessionFile,'utf8'));
|
|
435
|
+
const entry=(workspace&&sessionData?.byWorkspace?.[workspace])||sessionData?.latest;
|
|
436
|
+
const sid=sanitizeConversationId(entry?.conversationId);
|
|
437
|
+
if(entry?.transcriptPath){
|
|
438
|
+
const candidate=vettedTranscript(entry.transcriptPath,sid);
|
|
439
|
+
if(candidate)return {...candidate,source:'active-session-hook'};
|
|
440
|
+
}
|
|
441
|
+
if(sid){
|
|
442
|
+
for(const brain of getBrainRoots()){
|
|
443
|
+
const candidate=vettedTranscript(path.join(brain,sid,'.system_generated','logs','transcript.jsonl'),sid);
|
|
444
|
+
if(candidate)return {...candidate,source:'active-session-hook'};
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}catch{}
|
|
448
|
+
// Never guess the most recent transcript: it may belong to another session.
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export function getSessionTokenUsage(conversationId = null, opts = {}) {
|
|
453
|
+
const target = resolveTranscriptTarget({ conversationId, ...opts });
|
|
454
|
+
if (!target || !fs.existsSync(target.logFile)) return null;
|
|
455
|
+
|
|
456
|
+
try {
|
|
457
|
+
if(fs.statSync(target.logFile).size > 8*1024*1024){
|
|
458
|
+
return {status:'unavailable',reason:'Transcript is too large for safe synchronous parsing',source:target.source};
|
|
459
|
+
}
|
|
460
|
+
const content = fs.readFileSync(target.logFile, 'utf8');
|
|
461
|
+
const lines = content.split('\n').filter(Boolean);
|
|
462
|
+
|
|
463
|
+
let uncachedInputTokens = 0;
|
|
464
|
+
let outputTokens = 0;
|
|
465
|
+
let cacheReadTokens = 0;
|
|
466
|
+
let currentContextTokens = 0;
|
|
467
|
+
let llmSteps = 0;
|
|
468
|
+
let userTurns = 0;
|
|
469
|
+
let totalToolCalls = 0;
|
|
470
|
+
let a2aToolCalls = 0;
|
|
471
|
+
let readFileCalls = 0;
|
|
472
|
+
let lastModel = null;
|
|
473
|
+
|
|
474
|
+
for (const line of lines) {
|
|
475
|
+
try {
|
|
476
|
+
const obj = JSON.parse(line);
|
|
477
|
+
if (obj.type === 'USER_INPUT') userTurns++;
|
|
478
|
+
const isPlanner = obj.type === 'PLANNER_RESPONSE' || (!obj.type && obj.input_tokens !== undefined);
|
|
479
|
+
if (isPlanner) {
|
|
480
|
+
llmSteps++;
|
|
481
|
+
const inp = Number(obj.input_tokens || 0);
|
|
482
|
+
const cr = Number(obj.cache_read_tokens || 0);
|
|
483
|
+
const out = Number(obj.output_tokens || 0);
|
|
484
|
+
uncachedInputTokens += inp;
|
|
485
|
+
cacheReadTokens += cr;
|
|
486
|
+
outputTokens += out;
|
|
487
|
+
if (inp > 0 || cr > 0) currentContextTokens = inp;
|
|
488
|
+
}
|
|
489
|
+
if (obj.model) lastModel = obj.model;
|
|
490
|
+
if (Array.isArray(obj.tool_calls)) {
|
|
491
|
+
for (const tc of obj.tool_calls) {
|
|
492
|
+
totalToolCalls++;
|
|
493
|
+
const name = String(tc?.name || '');
|
|
494
|
+
if (name.startsWith('a2a_') || name.startsWith('verifykit_') || (name === 'call_mcp_tool' && (tc?.args?.ServerName === 'a2a_a2a' || String(tc?.args?.ToolName || '').startsWith('a2a_')))) {
|
|
495
|
+
a2aToolCalls++;
|
|
496
|
+
} else if (name === 'read_file' || name === 'view_file') {
|
|
497
|
+
readFileCalls++;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
} catch {}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// PLANNER_RESPONSE is an undocumented internal format. Its input/cache
|
|
505
|
+
// accounting is not guaranteed to match the CLI's official usage object.
|
|
506
|
+
// Expose diagnostics only, not invented billable tokens or fake totals.
|
|
507
|
+
return {
|
|
508
|
+
status:'diagnostic_only',
|
|
509
|
+
source:target.source,
|
|
510
|
+
conversation_id:target.convId,
|
|
511
|
+
latest_model:lastModel,
|
|
512
|
+
llm_steps:llmSteps,
|
|
513
|
+
user_turns:userTurns,
|
|
514
|
+
tool_calls:{
|
|
515
|
+
total:totalToolCalls,
|
|
516
|
+
a2a_calls:a2aToolCalls,
|
|
517
|
+
read_file_calls:readFileCalls,
|
|
518
|
+
},
|
|
519
|
+
usage:null,
|
|
520
|
+
total_tokens_consumed:null,
|
|
521
|
+
cache_hit_ratio:null,
|
|
522
|
+
cost_estimate:null,
|
|
523
|
+
note:'Internal transcript counters have unknown accounting semantics. For real token totals, import Antigravity CLI JSON usage with a2a tokens --usage-file <path>.',
|
|
524
|
+
};
|
|
525
|
+
} catch {
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
export function analyzeWorkspaceTokens(index, changedFiles = [], telemetrySummary = null) {
|
|
531
|
+
const files=index?.files||[];
|
|
532
|
+
const fileBreakdown=files.map(f=>{
|
|
533
|
+
const bytes=Math.max(0,Number(f.bytes)||0);
|
|
534
|
+
return {path:f.path,language:f.language,bytes,estimated_source_tokens:estimateTokens(bytes)};
|
|
535
|
+
}).sort((a,b)=>b.bytes-a.bytes);
|
|
536
|
+
const totalBytes=fileBreakdown.reduce((n,f)=>n+f.bytes,0);
|
|
537
|
+
const indexBytes=Buffer.byteLength(JSON.stringify(files.map(f=>({p:f.path,l:f.language,b:f.bytes||0}))),'utf8');
|
|
538
|
+
const changedSet=new Set(changedFiles||[]);
|
|
539
|
+
const changedBytes=fileBreakdown.filter(f=>changedSet.has(f.path)).reduce((n,f)=>n+f.bytes,0);
|
|
540
|
+
const scopeEstimate={
|
|
541
|
+
calls:Math.max(0,Number(telemetrySummary?.calls)||0),
|
|
542
|
+
estimated_scope_tokens:Math.max(0,Number(telemetrySummary?.raw_scope_tokens)||0),
|
|
543
|
+
estimated_tool_response_tokens:Math.max(0,Number(telemetrySummary?.response_tokens)||0),
|
|
544
|
+
data_quality:'estimated_character_count',
|
|
545
|
+
note:'These are approximate tool/source payload sizes, NOT actual model usage. Summed tool calls may overlap and cached content is not accounted for.',
|
|
546
|
+
};
|
|
547
|
+
return {
|
|
548
|
+
measurement_status:'source_inventory_only',
|
|
549
|
+
total_files:files.length,
|
|
550
|
+
total_source_bytes:totalBytes,
|
|
551
|
+
total_estimated_tokens:estimateTokens(totalBytes),
|
|
552
|
+
compact_index_tokens:estimateTokens(indexBytes),
|
|
553
|
+
changed_files_tokens:estimateTokens(changedBytes),
|
|
554
|
+
top_consumers:fileBreakdown.slice(0,10),
|
|
555
|
+
tool_payload_estimates:scopeEstimate,
|
|
556
|
+
net_token_savings:null,
|
|
557
|
+
net_token_savings_pct:null,
|
|
558
|
+
model_usage:null,
|
|
559
|
+
// Explicitly preserve compatibility with consumers of the old efficiency
|
|
560
|
+
// object, but do not populate its unreliable token-savings claims.
|
|
561
|
+
efficiency:{
|
|
562
|
+
measurement_basis:'no_controlled_baseline',
|
|
563
|
+
raw_source_tokens:null,
|
|
564
|
+
a2a_compact_tokens:null,
|
|
565
|
+
estimated_tokens_saved:null,
|
|
566
|
+
savings_ratio:null,
|
|
567
|
+
estimated_cost_saved:null,
|
|
568
|
+
limitation:'No A/B baseline or provider token usage was observed. Source-byte estimates cannot prove actual Gemini token savings.',
|
|
569
|
+
},
|
|
570
|
+
caveat:'Estimated source inventory size is NOT Gemini context window, session token usage, or billed tokens.',
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// Only provider-reported output can be used for a trustworthy per-run total.
|
|
575
|
+
// The official CLI emits usage.total_tokens, with total=input+output;
|
|
576
|
+
// cache_read and thinking are separate informational counters, not additions.
|
|
577
|
+
export function parseOfficialAgyUsage(envelope) {
|
|
578
|
+
const result=envelope?.event==='result'?envelope.result:envelope?.result?.usage?envelope.result:envelope;
|
|
579
|
+
const usage=result?.usage;
|
|
580
|
+
if(!usage||typeof usage!=='object')throw new Error('Missing official Antigravity CLI usage object');
|
|
581
|
+
const read=(key,required=true)=>{
|
|
582
|
+
const value=usage[key];
|
|
583
|
+
if(value===undefined||value===null){
|
|
584
|
+
if(required)throw new Error('Missing usage.'+key);
|
|
585
|
+
return null;
|
|
586
|
+
}
|
|
587
|
+
if(typeof value!=='number'||!Number.isSafeInteger(value)||value<0)throw new Error('Invalid usage.'+key);
|
|
588
|
+
return value;
|
|
589
|
+
};
|
|
590
|
+
const input=read('input_tokens'),output=read('output_tokens'),total=read('total_tokens');
|
|
591
|
+
const thinking=read('thinking_tokens',false),cache=read('cache_read_tokens',false);
|
|
592
|
+
// Optional fields are reported only when the host provides them; no cache miss is inferred.
|
|
593
|
+
const cacheWrite=read('cache_write_tokens',false),cacheCreation=read('cache_creation_tokens',false),cacheMiss=read('cache_miss_tokens',false);
|
|
594
|
+
if(total!==input+output)throw new Error('Inconsistent CLI usage total: expected input_tokens + output_tokens');
|
|
595
|
+
return {
|
|
596
|
+
status:'reported',
|
|
597
|
+
source:'antigravity-cli-json',
|
|
598
|
+
conversation_id:typeof result.conversation_id==='string'?result.conversation_id:null,
|
|
599
|
+
run_status:typeof result.status==='string'?result.status:null,
|
|
600
|
+
duration_seconds:typeof result.duration_seconds==='number'&&result.duration_seconds>=0?result.duration_seconds:null,
|
|
601
|
+
num_turns:Number.isSafeInteger(result.num_turns)&&result.num_turns>=0?result.num_turns:null,
|
|
602
|
+
usage:{input_tokens:input,output_tokens:output,total_tokens:total,thinking_tokens:thinking,cache_read_tokens:cache,cache_write_tokens:cacheWrite,cache_creation_tokens:cacheCreation,cache_miss_tokens:cacheMiss},
|
|
603
|
+
cost_usd:null,
|
|
604
|
+
net_token_savings:null,
|
|
605
|
+
note:'Reported by Antigravity CLI for this specific run only. Cache/thinking fields are not added to the reported total. No controlled native-versus-PILAH baseline is available.',
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
export function readOfficialAgyUsageFile(file) {
|
|
610
|
+
if(typeof file!=='string'||!file.trim())throw new Error('Provide a JSON file path');
|
|
611
|
+
const full=fs.realpathSync(path.resolve(file));
|
|
612
|
+
const stat=fs.statSync(full);
|
|
613
|
+
if(!stat.isFile()||stat.size>4*1024*1024)throw new Error('Usage file must be a regular JSON/NDJSON file of at most 4 MiB');
|
|
614
|
+
const raw=fs.readFileSync(full,'utf8');
|
|
615
|
+
try{return parseOfficialAgyUsage(JSON.parse(raw))}catch(e){
|
|
616
|
+
// Stream JSON ends with event=result. Ignore earlier step_update totals:
|
|
617
|
+
// summing them would double-count a run already summarized by result.
|
|
618
|
+
const lines=raw.trimEnd().split(/\r?\n/);
|
|
619
|
+
for(let i=lines.length-1;i>=0;i--){
|
|
620
|
+
try{
|
|
621
|
+
const event=JSON.parse(lines[i]);
|
|
622
|
+
if(event?.event==='result')return parseOfficialAgyUsage(event);
|
|
623
|
+
}catch{}
|
|
624
|
+
}
|
|
625
|
+
throw e;
|
|
626
|
+
}
|
|
627
|
+
}
|