@krtclcdy/tersio 2.19.0 → 2.20.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.
Files changed (34) hide show
  1. package/cli/common.js +13 -1
  2. package/cli/doctor.js +7 -7
  3. package/cli/install.js +28 -28
  4. package/extensions/ai-addons-updater/index.ts +377 -0
  5. package/extensions/caveman-session/index.ts +161 -0
  6. package/extensions/combo-toggle/index.ts +217 -0
  7. package/extensions/lib/utils.ts +162 -0
  8. package/extensions/rtk-session/index.ts +164 -0
  9. package/extensions/shared/carbon.ts +123 -0
  10. package/extensions/shared/mode-reinforcement.ts +29 -0
  11. package/extensions/shared/plugin-settings.ts +57 -0
  12. package/extensions/shared/pricing.ts +168 -0
  13. package/extensions/shared/rtk-gain.ts +105 -0
  14. package/extensions/shared/session-state.ts +201 -0
  15. package/extensions/shared/types.ts +85 -0
  16. package/extensions/shared/usage-ledger.ts +406 -0
  17. package/extensions/shared/usage-store.ts +325 -0
  18. package/extensions/tersio-commands/index.ts +110 -0
  19. package/package.json +19 -24
  20. package/extensions/ai-addons-updater/index.js +0 -331
  21. package/extensions/caveman-session/index.js +0 -152
  22. package/extensions/combo-toggle/index.js +0 -165
  23. package/extensions/lib/utils.js +0 -154
  24. package/extensions/rtk-session/index.js +0 -148
  25. package/extensions/shared/carbon.js +0 -88
  26. package/extensions/shared/mode-reinforcement.js +0 -26
  27. package/extensions/shared/plugin-settings.js +0 -51
  28. package/extensions/shared/pricing.js +0 -163
  29. package/extensions/shared/rtk-gain.js +0 -79
  30. package/extensions/shared/session-state.js +0 -177
  31. package/extensions/shared/types.js +0 -3
  32. package/extensions/shared/usage-ledger.js +0 -354
  33. package/extensions/shared/usage-store.js +0 -294
  34. package/extensions/tersio-commands/index.js +0 -102
@@ -1,294 +0,0 @@
1
- // extensions/shared/usage-store.ts — tersio-owned usage.db.
2
- // Persists the same per-message rows importSessionTokens derives live (model,
3
- // tokens, cache, cost input, timing, status, tools), so top models, costing,
4
- // cache, CO2 inputs, and activity survive session-file rotation. Sync is
5
- // incremental: a files ledger (mtime+size) skips unchanged transcripts, and
6
- // every read applies the current reset watermark — the store is a cache,
7
- // never a fork. Missing sqlite3 CLI → sync false / read null, callers fall
8
- // back to the live path. Never touches RTK's history.db or host transcripts.
9
- import { execFileSync } from 'node:child_process';
10
- import fs from 'node:fs';
11
- import os from 'node:os';
12
- import path from 'node:path';
13
- import { RECENT_LIMIT, canonicalModelId, classifySessionLine, codexSessionsDir, costOf, durOf, ingestSessionRow, newSessionAccum, sessionsDir, walkJsonl, } from './usage-ledger.js';
14
- export function usageDbPath() {
15
- const override = process.env.TERSIO_USAGE_DB;
16
- if (override)
17
- return override;
18
- return path.join(os.homedir(), '.omp', 'plugins', 'tersio-usage.db');
19
- }
20
- function esc(v) {
21
- return `'${v.replace(/'/g, "''")}'`;
22
- }
23
- function intOf(v) {
24
- return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0;
25
- }
26
- function nullNum(v) {
27
- return v === undefined ? 'NULL' : String(v);
28
- }
29
- function nullStr(v) {
30
- return v === undefined ? 'NULL' : esc(v);
31
- }
32
- function run(db, sql) {
33
- execFileSync('sqlite3', [db, sql], { stdio: ['ignore', 'ignore', 'ignore'], timeout: 30000 });
34
- }
35
- function query(db, sql) {
36
- const out = execFileSync('sqlite3', ['-separator', '\t', db, sql], {
37
- encoding: 'utf8',
38
- timeout: 30000,
39
- stdio: ['ignore', 'pipe', 'ignore'],
40
- });
41
- return out
42
- .split('\n')
43
- .filter((line) => line.trim())
44
- .map((line) => line.split('\t'));
45
- }
46
- function ensureSchema(db) {
47
- fs.mkdirSync(path.dirname(db), { recursive: true });
48
- run(db, `CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);` +
49
- `CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, mtime REAL NOT NULL, size INTEGER NOT NULL);` +
50
- `CREATE TABLE IF NOT EXISTS messages (file TEXT NOT NULL, t REAL, model TEXT NOT NULL,` +
51
- ` i INTEGER NOT NULL, o INTEGER NOT NULL, d REAL, cr INTEGER NOT NULL, cw INTEGER NOT NULL,` +
52
- ` usd REAL, st TEXT NOT NULL, code REAL, note TEXT, tools TEXT NOT NULL DEFAULT '[]');` +
53
- `CREATE INDEX IF NOT EXISTS idx_messages_file ON messages(file);`);
54
- }
55
- function readFiles(db) {
56
- const known = {};
57
- try {
58
- for (const [p, mtime, size] of query(db, `SELECT path, mtime, size FROM files;`)) {
59
- known[p] = { mtime: Number(mtime) || 0, size: Number(size) || 0 };
60
- }
61
- }
62
- catch { /* fresh db */ }
63
- return known;
64
- }
65
- function parseFile(text) {
66
- const rows = [];
67
- let codexProvider = null;
68
- for (const line of text.split('\n')) {
69
- if (!line.trim())
70
- continue;
71
- try {
72
- const row = JSON.parse(line);
73
- const parsed = classifySessionLine(row);
74
- if (parsed.kind === 'codex_provider') {
75
- if (parsed.provider)
76
- codexProvider = parsed.provider;
77
- continue;
78
- }
79
- const ts = row.timestamp;
80
- const ms = ts === undefined ? NaN : typeof ts === 'number' ? ts : Date.parse(ts);
81
- const t = Number.isFinite(ms) ? ms : null;
82
- if (parsed.kind === 'token_row') {
83
- const provider = parsed.provider ?? codexProvider;
84
- const usage = parsed.usage ?? {};
85
- rows.push({
86
- t,
87
- model: canonicalModelId(provider ? `codex/${provider}` : 'codex'),
88
- i: intOf(usage.input),
89
- o: intOf(usage.output),
90
- d: undefined,
91
- cr: intOf(usage.cacheRead),
92
- cw: intOf(usage.cacheWrite),
93
- usd: costOf(usage),
94
- st: 'completed',
95
- code: undefined,
96
- note: undefined,
97
- tools: [],
98
- });
99
- continue;
100
- }
101
- if (parsed.kind !== 'assistant_row' || !parsed.model || !parsed.usage)
102
- continue;
103
- const usage = parsed.usage;
104
- const dur = durOf(parsed.durMs);
105
- const run = parsed.run ?? { st: 'completed' };
106
- const note = run.note?.replace(/[\t\n\r]/g, ' ').slice(0, 180);
107
- rows.push({
108
- t,
109
- model: canonicalModelId(parsed.model),
110
- i: intOf(usage.input),
111
- o: intOf(usage.output),
112
- d: dur,
113
- cr: intOf(usage.cacheRead),
114
- cw: intOf(usage.cacheWrite),
115
- usd: costOf(usage),
116
- st: run.st,
117
- code: run.code,
118
- note,
119
- tools: parsed.tools ?? [],
120
- });
121
- }
122
- catch { /* skip corrupt lines */ }
123
- }
124
- return rows;
125
- }
126
- function insertSql(file, r) {
127
- return `INSERT INTO messages (file, t, model, i, o, d, cr, cw, usd, st, code, note, tools) VALUES (` +
128
- `${esc(file)},${r.t === null ? 'NULL' : String(r.t)},${esc(r.model)},${r.i},${r.o},` +
129
- `${nullNum(r.d)},${r.cr},${r.cw},${nullNum(r.usd)},${esc(r.st)},` +
130
- `${nullNum(r.code)},${nullStr(r.note)},${esc(JSON.stringify(r.tools))});`;
131
- }
132
- // Incremental sync: unchanged transcripts are skipped via mtime+size, changed
133
- // ones are deleted and re-inserted, removed ones are dropped. True on success
134
- // (including nothing-to-do), false when sqlite3 or disk is unavailable.
135
- export function syncUsageDb() {
136
- let db;
137
- try {
138
- db = usageDbPath();
139
- ensureSchema(db);
140
- }
141
- catch {
142
- return false;
143
- }
144
- const files = [];
145
- try {
146
- walkJsonl(sessionsDir(), files, 2000);
147
- if (process.env.TERSIO_SESSIONS_DIR === undefined || process.env.TERSIO_CODEX_DIR !== undefined) {
148
- walkJsonl(codexSessionsDir(), files, 2000);
149
- }
150
- }
151
- catch {
152
- return false;
153
- }
154
- const known = readFiles(db);
155
- const current = {};
156
- const changed = [];
157
- for (const file of files) {
158
- let st;
159
- try {
160
- st = fs.statSync(file);
161
- }
162
- catch {
163
- continue;
164
- }
165
- const entry = { mtime: st.mtimeMs, size: st.size };
166
- current[file] = entry;
167
- const prev = known[file];
168
- if (!prev || prev.mtime !== entry.mtime || prev.size !== entry.size)
169
- changed.push(file);
170
- }
171
- const removed = Object.keys(known).filter((p) => current[p] === undefined);
172
- if (!changed.length && !removed.length)
173
- return true;
174
- const chunks = [];
175
- let chunkBytes = 0;
176
- const flush = () => {
177
- if (!chunks.length)
178
- return true;
179
- try {
180
- run(db, `BEGIN;${chunks.join('')}COMMIT;`);
181
- }
182
- catch {
183
- return false;
184
- }
185
- chunks.length = 0;
186
- chunkBytes = 0;
187
- return true;
188
- };
189
- const push = (sql) => {
190
- chunks.push(sql);
191
- chunkBytes += sql.length;
192
- if (chunkBytes < 400_000)
193
- return true;
194
- return flush();
195
- };
196
- for (const file of [...changed, ...removed]) {
197
- if (!push(`DELETE FROM messages WHERE file=${esc(file)};DELETE FROM files WHERE path=${esc(file)};`))
198
- return false;
199
- }
200
- try {
201
- for (const file of changed) {
202
- const entry = current[file];
203
- const text = fs.readFileSync(file, 'utf8');
204
- for (const r of parseFile(text)) {
205
- if (!push(insertSql(file, r)))
206
- return false;
207
- }
208
- if (!push(`INSERT OR REPLACE INTO files (path, mtime, size) VALUES (${esc(file)},${entry.mtime},${entry.size});`))
209
- return false;
210
- }
211
- }
212
- catch {
213
- return false;
214
- }
215
- if (!push(`INSERT OR REPLACE INTO meta (k, v) VALUES ('last_sync',${esc(String(Date.now()))});`))
216
- return false;
217
- return flush();
218
- }
219
- export function readUsageDb() {
220
- const db = usageDbPath();
221
- try {
222
- if (!fs.existsSync(db))
223
- return null;
224
- }
225
- catch {
226
- return null;
227
- }
228
- let rows;
229
- try {
230
- rows = query(db, `SELECT t, model, i, o, d, cr, cw, usd, st, code, note, tools FROM messages;`);
231
- }
232
- catch {
233
- return null;
234
- }
235
- const accum = newSessionAccum();
236
- for (const [t, model, i, o, d, cr, cw, usd, st, code, note, tools] of rows) {
237
- const ts = t === '' ? undefined : Number(t);
238
- let toolNames = [];
239
- try {
240
- const parsed = JSON.parse(tools || '[]');
241
- if (Array.isArray(parsed))
242
- toolNames = parsed.filter((x) => typeof x === 'string');
243
- }
244
- catch { /* keep empty */ }
245
- const usage = {
246
- input: Number(i) || 0,
247
- output: Number(o) || 0,
248
- cacheRead: Number(cr) || 0,
249
- cacheWrite: Number(cw) || 0,
250
- };
251
- if (usd !== '') {
252
- const measured = Number(usd);
253
- if (Number.isFinite(measured))
254
- usage.cost = measured;
255
- }
256
- ingestSessionRow(accum, model || 'unknown', usage, Number.isFinite(ts) ? ts : undefined, d === '' ? undefined : Number(d), {
257
- st: st === 'error' || st === 'aborted' ? st : 'completed',
258
- code: code === '' ? undefined : Number(code),
259
- note: note === '' ? undefined : note,
260
- }, toolNames);
261
- }
262
- accum.recent.sort((a, b) => b.t - a.t);
263
- let syncedAt = 0;
264
- try {
265
- const meta = query(db, `SELECT v FROM meta WHERE k='last_sync';`);
266
- if (meta.length)
267
- syncedAt = Number(meta[0][0]) || 0;
268
- }
269
- catch { /* keep 0 */ }
270
- return {
271
- tokens: {
272
- messages: accum.messages,
273
- totals: accum.totals,
274
- byModel: accum.byModel,
275
- byDay: accum.byDay,
276
- byDayModel: accum.byDayModel,
277
- byTool: accum.byTool,
278
- byModelMessages: accum.byModelMessages,
279
- costMeasured: accum.costMeasured,
280
- recent: accum.recent.slice(0, RECENT_LIMIT),
281
- },
282
- syncedAt,
283
- };
284
- }
285
- // Delete the store file. Returns 1 when removed, 0 when already absent.
286
- export function clearUsageDb() {
287
- try {
288
- fs.unlinkSync(usageDbPath());
289
- return 1;
290
- }
291
- catch {
292
- return 0;
293
- }
294
- }
@@ -1,102 +0,0 @@
1
- // /tersio root command — status, check, update, gain, usage, help.
2
- // Mode switches live on their own commands (/caveman, /rtk, /combo, and the
3
- // upstream /ponytail): the router keeps no redundant copies. Shared-state
4
- // publishes sync sibling mirrors live, so switches notify and take effect
5
- // next turn — no reload.
6
- import { getSharedComboState, reconcileSharedComboEntries, sessionEntries, } from '../shared/session-state.js';
7
- import os from 'node:os';
8
- import path from 'node:path';
9
- import { appendUsage, readUsage } from '../shared/usage-ledger.js';
10
- import { checkAddonsSummary, runAddonUpdate } from '../ai-addons-updater/index.js';
11
- const HELP = [
12
- '/tersio status — active modes + combo level',
13
- '/tersio check — add-on version check',
14
- '/tersio update <ponytail|rtk|caveman|all> [--dry-run]',
15
- '/tersio gain — savings summary + dashboard hint',
16
- '/tersio usage — ledger report for this machine',
17
- '/tersio help — this table',
18
- 'mode switches: /caveman /rtk /combo (tersio) + /ponytail (upstream)',
19
- ].join('\n');
20
- function statusLine() {
21
- const s = getSharedComboState();
22
- const level = s.level === 'custom' ? 'INACTIVE' : s.level.toUpperCase();
23
- return `tersio — caveman=${s.caveman.toUpperCase()} · rtk=${s.rtk.toUpperCase()} · ponytail=${s.ponytail.toUpperCase()} (combo ${level})`;
24
- }
25
- function usageSummary() {
26
- const rows = readUsage();
27
- if (rows.length === 0)
28
- return 'tersio usage: no ledger yet — run commands first.';
29
- const byKind = {};
30
- for (const r of rows)
31
- byKind[r.kind] = (byKind[r.kind] ?? 0) + 1;
32
- const parts = Object.entries(byKind).map(([k, n]) => `${k}×${n}`);
33
- const last = new Date(rows[rows.length - 1].ts).toISOString();
34
- return `tersio usage: ${rows.length} rows (${parts.join(', ')}), last write ${last}.`;
35
- }
36
- // Gain opens instantaneously in the default browser: export a file://-ready
37
- // snapshot (data inlined, no server to babysit) and open it. Falls back to
38
- // the shell command when export or open fails.
39
- async function openGainDashboard(pi, ctx) {
40
- const file = path.join(os.tmpdir(), `tersio-gain-${Date.now()}.html`);
41
- try {
42
- const exported = await pi.exec?.('tersio', ['gain', '--export', file], { cwd: ctx?.cwd });
43
- if (!exported || exported.code !== 0)
44
- throw new Error((exported?.stderr || 'export failed').trim());
45
- const openCmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
46
- await pi.exec?.(openCmd, [file], { cwd: ctx?.cwd });
47
- ctx?.ui?.notify?.(`tersio gain: dashboard opened in your browser.`, 'info');
48
- }
49
- catch (e) {
50
- ctx?.ui?.notify?.(`tersio gain: could not open dashboard (${e.message}). Run 'tersio gain --open' in a shell.`, 'warning');
51
- }
52
- }
53
- export default function tersioCommandsExtension(pi) {
54
- pi.setLabel?.('Tersio unified root command');
55
- pi.registerCommand?.('tersio', {
56
- description: 'Tersio root: status|check|update|gain|usage|help (modes: /caveman /rtk /combo /ponytail)',
57
- handler: async (args, ctx) => {
58
- const parts = String(args || '').trim().toLowerCase().split(/\s+/).filter(Boolean);
59
- const [sub] = [parts[0]];
60
- appendUsage('command', `/tersio ${parts.join(' ')}`.trim());
61
- if (!sub || sub === 'status') {
62
- if (ctx?.hasUI)
63
- reconcileSharedComboEntries(sessionEntries(ctx));
64
- ctx?.ui?.notify?.(statusLine(), 'info');
65
- return;
66
- }
67
- if (sub === 'help') {
68
- ctx?.ui?.notify?.(HELP, 'info');
69
- return;
70
- }
71
- if (sub === 'check') {
72
- await checkAddonsSummary(ctx);
73
- return;
74
- }
75
- if (sub === 'update') {
76
- const dryRun = parts.includes('--dry-run');
77
- const target = parts.filter((p) => p !== '--dry-run' && p !== 'update' && p !== 'tersio').join(' ');
78
- if (!target) {
79
- ctx?.ui?.notify?.('Usage: /tersio update <ponytail|rtk|caveman|all> [--dry-run]', 'warning');
80
- return;
81
- }
82
- await runAddonUpdate(pi, ctx, target, dryRun);
83
- return;
84
- }
85
- if (sub === 'gain') {
86
- await openGainDashboard(pi, ctx);
87
- return;
88
- }
89
- if (sub === 'usage') {
90
- ctx?.ui?.notify?.(usageSummary(), 'info');
91
- return;
92
- }
93
- // Removed mode switches redirect to their own commands so only one
94
- // spelling exists to learn: /caveman, /rtk, /combo, /ponytail.
95
- if (sub === 'caveman' || sub === 'rtk' || sub === 'combo' || sub === 'ponytail') {
96
- ctx?.ui?.notify?.(`Use /${sub} instead — /tersio no longer duplicates mode switches.\n${HELP}`, 'warning');
97
- return;
98
- }
99
- ctx?.ui?.notify?.(`Unknown subcommand: ${sub}.\n${HELP}`, 'warning');
100
- },
101
- });
102
- }