Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/agy-sync.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { createHash } from 'node:crypto';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { aggregateRecords } from './parser.js';
import { parseAgy } from './parsers/agy.js';
import { syncRecords } from './sync.js';

// AGY의 과거 사용량을 다시 보내도 기존 CLI가 같은 모델로 저장한 사용량과 키가 겹치지 않는다.
function agyDeviceId(deviceId) {
const digest = createHash('sha256').update('tokenphage/agy/' + deviceId.toLowerCase()).digest();
digest[6] = (digest[6] & 15) | 128; // UUIDv8
digest[8] = (digest[8] & 63) | 128;
const hex = digest.toString('hex', 0, 16);
return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
}

export async function syncAgy({ apiBase, token, deviceId, home = process.env.TOKENPHAGE_AGY_HOME,
fetchImpl, log = console.log }) {
const dir = home || join(homedir(), '.gemini', 'antigravity-cli');
const records = aggregateRecords(await parseAgy(dir, Boolean(home)));
if (!records.length) return;

const id = agyDeviceId(deviceId);
const maxRecords = 10000; // SyncRequest.MAX_RECORDS
for (let i = 0; i < records.length; i += maxRecords) {
await syncRecords(apiBase, token, id, records.slice(i, i + maxRecords), [], { fetchImpl });
}
log(`Synced ${records.length} AGY records (date×model).`);
}
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 맨 끝 program.parse()가 argv를 해석해 실제 시동을 건다.
*/
import { Command } from 'commander';
import { syncAgy } from './agy-sync.js';
import { parseLogs } from './parser.js';
import { loadConfig, loadToken, saveToken, getOrCreateDeviceId, gistLogin, setHookInstalled, clearSyncState } from './auth.js';
import { resetData } from './sync.js';
Expand Down Expand Up @@ -131,6 +132,7 @@ async function runSync() {
const token = requireToken();
const deviceId = getOrCreateDeviceId();
await runSyncFlow({ apiBase: API_BASE, token, deviceId, parseLogs });
await syncAgy({ apiBase: API_BASE, token, deviceId });
}

/**
Expand Down
38 changes: 38 additions & 0 deletions src/parsers/agy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { readDatabase } from './agy/database.js';
import { readTranscript } from './agy/transcript.js';

async function children(dir, optional) {
try {
return await readdir(dir, { withFileTypes: true });
} catch (err) {
if (optional && err.code === 'ENOENT') return [];
throw err;
}
}

export async function parseAgy(home, explicit = false) {
const dirs = await children(home, !explicit);
const sessions = new Map();
if (dirs.some(d => d.name === 'brain')) {
for (const d of await children(join(home, 'brain'))) {
if (d.isDirectory()) sessions.set(d.name, { log: join(home, 'brain', d.name, '.system_generated', 'logs', 'transcript.jsonl') });
}
}
if (dirs.some(d => d.name === 'conversations')) {
for (const d of await children(join(home, 'conversations'))) {
if (!d.isFile() || !d.name.endsWith('.db')) continue;
const id = d.name.slice(0, -3);
sessions.set(id, { ...sessions.get(id), db: join(home, 'conversations', d.name) });
}
}
const entries = [];
for (const session of sessions.values()) {
const turns = new Map();
if (session.log) await readTranscript(session.log, turns);
if (session.db) await readDatabase(session.db, turns);
for (const row of turns.values()) entries.push(row);
}
return entries;
}
67 changes: 67 additions & 0 deletions src/parsers/agy/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { localDateOf } from '../../lib/dates.js';
import { tokenRecord } from './record.js';

// AGY stores protobuf messages in steps.metadata. Read individual fields without
// decoding prompt text or tool payloads. Fixed-width fields can be skipped.
function fields(bytes = []) {
const result = new Map();
let offset = 0;
function varint() {
let n = 0n;
for (let shift = 0n; shift < 70n && offset < bytes.length; shift += 7n) {
const b = bytes[offset++];
n |= BigInt(b & 127) << shift;
if (b < 128) return Number(n);
}
throw new Error('Invalid AGY protobuf integer');
}
while (offset < bytes.length) {
const key = varint();
const field = Math.floor(key / 8);
switch (key % 8) {
case 0: result.set(field, varint()); break;
case 1: offset += 8; break;
case 2: {
const length = varint();
result.set(field, bytes.subarray(offset, offset + length));
offset += length;
break;
}
case 5: offset += 4; break;
default: throw new Error('Unsupported AGY protobuf field');
}
if (offset > bytes.length) throw new Error('Truncated AGY metadata');
}
return result;
}

export async function readDatabase(file, turns) {
const { default: Database } = await import('better-sqlite3');
const db = new Database(file, { readonly: true, fileMustExist: true });
try {
const names = new Map();
const missing = [];
for (const { idx, metadata } of db.prepare('SELECT idx, metadata FROM steps WHERE metadata IS NOT NULL').iterate()) {
const meta = fields(metadata);
const usage = fields(meta.get(9));
if (!usage.size) continue;
const modelId = usage.get(1);
if (turns.has(idx)) names.set(modelId, turns.get(idx).model);
else if ([2, 3, 5].some(k => usage.get(k))) missing.push({ meta, usage, idx, modelId });
}
if (missing.length) {
for (const { data } of db.prepare('SELECT data FROM gen_metadata').iterate()) {
const request = fields(fields(data).get(1));
const name = request.get(19)?.toString();
if (name) names.set(fields(request.get(4)).get(1), name);
}
}
for (const { meta, usage, idx, modelId } of missing) {
const seconds = fields(meta.get(1)).get(1);
turns.set(idx, tokenRecord(localDateOf(new Date(seconds * 1000)), names.get(modelId) ?? `agy-model-${modelId}`,
usage.get(2), usage.get(3), usage.get(5)));
}
} finally {
db.close();
}
}
6 changes: 6 additions & 0 deletions src/parsers/agy/record.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export function tokenRecord(date, model, input = 0, output = 0, cache = 0, write = 0) {
if (!date || !model || ![input, output, cache, write].every(n => Number.isSafeInteger(n) && n >= 0)) {
throw new Error('Invalid AGY token record');
}
return { date, model, inputTok: input, outputTok: output, cacheReadTok: cache, cacheCreateTok: write };
}
22 changes: 22 additions & 0 deletions src/parsers/agy/transcript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
import { localDateOf } from '../../lib/dates.js';
import { tokenRecord } from './record.js';

export async function readTranscript(file, turns) {
const lines = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
try {
for await (const line of lines) {
if (!line.trim()) continue;
const r = JSON.parse(line);
if (!['input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_creation_input_tokens'].some(k => k in r)) continue;
if (!Number.isSafeInteger(r.step_index)) throw new Error('Invalid AGY step index');
turns.set(r.step_index, tokenRecord(localDateOf(r.created_at), r.model, r.input_tokens,
r.output_tokens, r.cache_read_tokens, r.cache_creation_input_tokens));
}
} catch (err) {
if (err.code !== 'ENOENT') throw err;
} finally {
lines.close();
}
}
41 changes: 41 additions & 0 deletions test/parser-agy.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import Database from 'better-sqlite3';
import { parseAgy } from '../src/parsers/agy.js';
import { aggregateRecords } from '../src/parser.js';
import { syncAgy } from '../src/agy-sync.js';

test('AGY merges steps from both representations and syncs historical totals idempotently', async t => {
const home = await mkdtemp(join(tmpdir(), 'agy-test-'));
t.after(() => rm(home, { recursive: true, force: true }));
const logs = join(home, 'brain', 'session', '.system_generated', 'logs');
await mkdir(logs, { recursive: true });
const ts = '1970-01-01T00:00:25Z';
const turn = { step_index: 1, model: 'test', created_at: ts, input_tokens: 4,
cache_read_tokens: 9, output_tokens: 3, thinking_tokens: 1 };
await writeFile(join(logs, 'transcript.jsonl'), [turn, turn].map(r => JSON.stringify(r)).join('\n'));
await mkdir(join(home, 'conversations'));
const db = new Database(join(home, 'conversations', 'session.db'));
db.exec('CREATE TABLE steps(idx INTEGER, metadata BLOB); CREATE TABLE gen_metadata(data BLOB)');
// timestamp 25, model ID 1, input 4, output 3 (includes thinking 1), cache 9.
const meta = Buffer.from([10,2,8,25,74,10,8,1,16,4,24,3,40,9,72,1]);
for (const idx of [1, 2]) db.prepare('INSERT INTO steps VALUES (?,?)').run(idx, meta);
db.close();
const records = aggregateRecords(await parseAgy(home));
assert.equal(records.length, 1);
assert.deepEqual(records[0], { date: records[0].date, model: 'test', inputTok: 8,
outputTok: 6, cacheReadTok: 18, cacheCreateTok: 0 });
const payloads = [];
const deviceId = '013cc5eb-b623-4175-a096-8a7145c47815';
for (let run = 0; run < 2; run++) {
await syncAgy({ home, deviceId, apiBase: 'https://example.test', token: 'test', log() {},
fetchImpl: async (_, init) => { payloads.push(JSON.parse(init.body)); return { ok: true }; } });
}
assert.equal(payloads.length, 2);
assert.deepEqual(payloads[0], payloads[1]);
assert.deepEqual(payloads[0].records, records);
assert.notEqual(payloads[0].deviceId, deviceId);
});