@trazum/core 2.6.0 → 2.7.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.
Files changed (48) hide show
  1. package/dist/billing.d.ts.map +1 -1
  2. package/dist/billing.js +2 -1
  3. package/dist/billing.js.map +1 -1
  4. package/dist/claude-code.d.ts +2 -0
  5. package/dist/claude-code.d.ts.map +1 -1
  6. package/dist/claude-code.js +6 -0
  7. package/dist/claude-code.js.map +1 -1
  8. package/dist/gateway.d.ts +8 -0
  9. package/dist/gateway.d.ts.map +1 -1
  10. package/dist/gateway.js +55 -12
  11. package/dist/gateway.js.map +1 -1
  12. package/dist/gemini-cli.d.ts +65 -0
  13. package/dist/gemini-cli.d.ts.map +1 -0
  14. package/dist/gemini-cli.js +162 -0
  15. package/dist/gemini-cli.js.map +1 -0
  16. package/dist/harnesses.d.ts +2 -2
  17. package/dist/harnesses.d.ts.map +1 -1
  18. package/dist/harnesses.js +1 -0
  19. package/dist/harnesses.js.map +1 -1
  20. package/dist/index.d.ts +5 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +5 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/pricing.d.ts +2 -0
  25. package/dist/pricing.d.ts.map +1 -1
  26. package/dist/pricing.js +504 -22
  27. package/dist/pricing.js.map +1 -1
  28. package/dist/slim-line.d.ts +37 -0
  29. package/dist/slim-line.d.ts.map +1 -0
  30. package/dist/slim-line.js +68 -0
  31. package/dist/slim-line.js.map +1 -0
  32. package/dist/types.d.ts +16 -0
  33. package/dist/types.d.ts.map +1 -1
  34. package/dist/usage.d.ts +48 -0
  35. package/dist/usage.d.ts.map +1 -1
  36. package/dist/usage.js +129 -7
  37. package/dist/usage.js.map +1 -1
  38. package/package.json +2 -2
  39. package/src/billing.ts +2 -1
  40. package/src/claude-code.ts +8 -0
  41. package/src/gateway.ts +61 -11
  42. package/src/gemini-cli.ts +187 -0
  43. package/src/harnesses.ts +3 -2
  44. package/src/index.ts +10 -0
  45. package/src/pricing.ts +510 -22
  46. package/src/slim-line.ts +66 -0
  47. package/src/types.ts +14 -1
  48. package/src/usage.ts +174 -7
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Gemini CLI session files, from explicit caller-supplied text.
3
+ *
4
+ * Read against the recorder's own source rather than a sample: google-gemini/
5
+ * gemini-cli, `packages/core/src/services/chatRecordingService.ts` and
6
+ * `chatRecordingTypes.ts` (Apache-2.0). Sessions live under
7
+ * `~/.gemini/tmp/<project>/chats/` as `session-*.jsonl`, one JSON record per
8
+ * line; older versions wrote one `session-*.json` document per chat, which the
9
+ * CLI converts on resume and which is read here too. No prompt, reply,
10
+ * thought, tool argument, tool result or path is copied: only the model, the
11
+ * moment, the session and the token counts.
12
+ *
13
+ * How the recorder writes, and what follows for a bill:
14
+ *
15
+ * - **A message is appended whole every time it changes.** Tokens arrive after
16
+ * the reply, so the same message id appears twice or more, and the last one
17
+ * stands. Counting every line would bill one reply several times.
18
+ * - **Tokens attach once per reply.** `recordMessageTokens` sets them only on a
19
+ * `gemini` message that has none, so one id carries one response's usage.
20
+ * - **History edits do not undo spend.** `$rewindTo`, `$patch.removeIds` and a
21
+ * rewritten file change what the conversation shows, not what was called; a
22
+ * reply that was billed stays billed.
23
+ * - **`$set.messages`** is a deprecated full-history checkpoint: its messages
24
+ * are read through the same id rule, so a checkpoint never counts twice.
25
+ */
26
+ export interface GeminiCliRecord {
27
+ model: string;
28
+ ts?: string;
29
+ session?: string;
30
+ label?: string;
31
+ usage: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number };
32
+ }
33
+
34
+ export interface GeminiCliConversion {
35
+ records: GeminiCliRecord[];
36
+ /** Lines that repeat a message already read: the recorder's own rewrites, not calls. */
37
+ repeats: number;
38
+ unparseable: number;
39
+ /** Replies whose token counts were present and impossible: refused, never zeroed. */
40
+ unsupported: number;
41
+ missingModel: number;
42
+ /**
43
+ * Replies from a recorder that kept no reasoning or tool-use count, whose
44
+ * total exceeded the parts it did keep. The remainder is priced as output,
45
+ * the dearer side, rather than dropped; counted so the bill can say so.
46
+ */
47
+ remainderAsOutput: number;
48
+ }
49
+
50
+ const object = (value: unknown): value is Record<string, unknown> =>
51
+ typeof value === 'object' && value !== null && !Array.isArray(value);
52
+
53
+ const count = (value: unknown): number | null =>
54
+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
55
+
56
+ /** A signature, not a filename: the session header, or a reply with its token summary. */
57
+ export function looksLikeGeminiCliSession(text: string): boolean {
58
+ const trimmed = text.trimStart();
59
+ if (trimmed.startsWith('{')) {
60
+ // A legacy single-document session, which the recorder pretty-printed:
61
+ // the whole text parses as one object. JSONL fails fast at its second line.
62
+ try {
63
+ const doc: unknown = JSON.parse(trimmed);
64
+ if (object(doc) && typeof doc.sessionId === 'string' && typeof doc.projectHash === 'string' &&
65
+ Array.isArray(doc.messages)) return true;
66
+ } catch { /* fall through to the line rule */ }
67
+ }
68
+ for (const line of text.split('\n').slice(0, 50)) {
69
+ if (line.trim() === '') continue;
70
+ try {
71
+ const row: unknown = JSON.parse(line);
72
+ if (!object(row)) continue;
73
+ if (typeof row.sessionId === 'string' && typeof row.projectHash === 'string') return true;
74
+ if (row.type === 'gemini' && typeof row.id === 'string' && object(row.tokens)) return true;
75
+ } catch { /* Malformed lines are reported by conversion, never executed. */ }
76
+ }
77
+ return false;
78
+ }
79
+
80
+ interface Reply {
81
+ model: unknown;
82
+ timestamp: unknown;
83
+ tokens: Record<string, unknown>;
84
+ }
85
+
86
+ /**
87
+ * One usage record per reply that carried token counts.
88
+ *
89
+ * Gemini's `input` is `promptTokenCount`, which **includes** the cached tokens,
90
+ * so the cached part is taken out of it; `thoughts` (reasoning, billed as
91
+ * output) and `tool` (tool results fed back to the model, billed as input) sit
92
+ * outside the first two counts, and `total` is the sum of all four.
93
+ */
94
+ export function geminiCliRecords(text: string, options: { label?: string } = {}): GeminiCliConversion {
95
+ const result: GeminiCliConversion = {
96
+ records: [], repeats: 0, unparseable: 0, unsupported: 0, missingModel: 0, remainderAsOutput: 0,
97
+ };
98
+ let session: string | null = null;
99
+ // Insertion order is first appearance; the value is the last version seen.
100
+ const replies = new Map<string, Reply>();
101
+ const sessionOf = new Map<string, string | null>();
102
+ const seen = new Set<string>();
103
+
104
+ const take = (message: unknown): void => {
105
+ if (!object(message) || typeof message.id !== 'string' || message.type !== 'gemini') return;
106
+ const key = `${session ?? ''}\n${message.id}`;
107
+ if (seen.has(key)) result.repeats++;
108
+ seen.add(key);
109
+ if (!object(message.tokens)) return;
110
+ replies.set(key, { model: message.model, timestamp: message.timestamp, tokens: message.tokens });
111
+ if (!sessionOf.has(key)) sessionOf.set(key, session);
112
+ };
113
+
114
+ const trimmed = text.trimStart();
115
+ let legacy: Record<string, unknown> | null = null;
116
+ if (trimmed.startsWith('{')) {
117
+ try {
118
+ const doc: unknown = JSON.parse(trimmed);
119
+ if (object(doc) && Array.isArray(doc.messages) && typeof doc.sessionId === 'string') legacy = doc;
120
+ } catch { /* not a single document: read it as lines */ }
121
+ }
122
+ if (legacy !== null) {
123
+ session = legacy.sessionId as string;
124
+ for (const message of legacy.messages as unknown[]) take(message);
125
+ } else {
126
+ for (const line of text.split('\n')) {
127
+ if (line.trim() === '') continue;
128
+ let row: unknown;
129
+ try { row = JSON.parse(line); } catch { result.unparseable++; continue; }
130
+ if (!object(row)) { result.unparseable++; continue; }
131
+ if (typeof row.sessionId === 'string' && row.sessionId !== '') session = row.sessionId;
132
+ if (object(row.$set) && Array.isArray(row.$set.messages)) {
133
+ for (const message of row.$set.messages as unknown[]) take(message);
134
+ continue;
135
+ }
136
+ take(row);
137
+ }
138
+ }
139
+
140
+ for (const [key, reply] of replies) {
141
+ const t = reply.tokens;
142
+ const input = count(t.input);
143
+ const output = count(t.output);
144
+ const cached = t.cached === undefined ? 0 : count(t.cached);
145
+ const thoughts = t.thoughts === undefined || t.thoughts === null ? null : count(t.thoughts);
146
+ const tool = t.tool === undefined || t.tool === null ? null : count(t.tool);
147
+ const total = t.total === undefined ? 0 : count(t.total);
148
+ if (input === null || output === null || cached === null || total === null ||
149
+ (t.thoughts !== undefined && t.thoughts !== null && thoughts === null) ||
150
+ (t.tool !== undefined && t.tool !== null && tool === null) ||
151
+ cached > input) {
152
+ result.unsupported++;
153
+ continue;
154
+ }
155
+ const known = input + output + (thoughts ?? 0) + (tool ?? 0);
156
+ // A total below its own parts is a record that contradicts itself.
157
+ if (total > 0 && total < known) { result.unsupported++; continue; }
158
+ let extraOutput = 0;
159
+ if (total > known) {
160
+ // Parts the recorder kept add up short of the total it also kept. With
161
+ // both breakdowns present that is a contradiction; without them the
162
+ // remainder is reasoning or tool input that went unrecorded, and output
163
+ // is the dearer reading.
164
+ if (thoughts !== null && tool !== null) { result.unsupported++; continue; }
165
+ extraOutput = total - known;
166
+ result.remainderAsOutput++;
167
+ }
168
+ if (input + output + (thoughts ?? 0) + (tool ?? 0) + extraOutput === 0) continue;
169
+ if (typeof reply.model !== 'string' || reply.model.trim() === '') { result.missingModel++; continue; }
170
+ const ts = typeof reply.timestamp === 'string' && Number.isFinite(Date.parse(reply.timestamp))
171
+ ? reply.timestamp
172
+ : undefined;
173
+ const owner = sessionOf.get(key) ?? null;
174
+ result.records.push({
175
+ model: reply.model,
176
+ ...(ts === undefined ? {} : { ts }),
177
+ ...(owner === null ? {} : { session: owner }),
178
+ ...(options.label === undefined ? {} : { label: options.label }),
179
+ usage: {
180
+ input_tokens: input - cached + (tool ?? 0),
181
+ output_tokens: output + (thoughts ?? 0) + extraOutput,
182
+ cache_read_input_tokens: cached,
183
+ },
184
+ });
185
+ }
186
+ return result;
187
+ }
package/src/harnesses.ts CHANGED
@@ -9,8 +9,8 @@ export interface HarnessCapability {
9
9
  readonly id: string;
10
10
  readonly name: string;
11
11
  readonly nativeImport: {
12
- readonly command: 'from-claude-code' | 'from-codex';
13
- readonly format: 'claude-code-transcript-jsonl' | 'codex-session-jsonl';
12
+ readonly command: 'from-claude-code' | 'from-codex' | 'from-gemini-cli';
13
+ readonly format: 'claude-code-transcript-jsonl' | 'codex-session-jsonl' | 'gemini-cli-session-jsonl';
14
14
  } | null;
15
15
  readonly normalizedUsage: { readonly command: 'bill'; readonly format: 'trazum-usage-jsonl' };
16
16
  readonly billingMode: 'unknown';
@@ -42,6 +42,7 @@ export const HARNESS_CAPABILITIES: HarnessCapabilities = Object.freeze({
42
42
  harnesses: Object.freeze([
43
43
  harness('claude-code', 'Claude Code', { command: 'from-claude-code', format: 'claude-code-transcript-jsonl' }),
44
44
  harness('codex', 'Codex', { command: 'from-codex', format: 'codex-session-jsonl' }),
45
+ harness('gemini-cli', 'Gemini CLI', { command: 'from-gemini-cli', format: 'gemini-cli-session-jsonl' }),
45
46
  harness('cursor', 'Cursor', null),
46
47
  harness('mcp-client', 'Generic MCP client', null),
47
48
  ]),
package/src/index.ts CHANGED
@@ -17,12 +17,16 @@ export {
17
17
  profileUsage,
18
18
  sharesOf,
19
19
  spendByMonth,
20
+ spendByPeriod,
20
21
  } from './usage.js';
21
22
  export type {
22
23
  CacheEconomics,
23
24
  CacheVerdict,
24
25
  MonthSpend,
25
26
  SpendByMonth,
27
+ BillPeriodUnit,
28
+ PeriodSpend,
29
+ SpendByPeriod,
26
30
  UsageProfileOptions,
27
31
  UsageBreakdown,
28
32
  FieldCoverage,
@@ -668,6 +672,12 @@ export type {
668
672
 
669
673
  export { codexRecords, looksLikeCodexTranscript } from './codex.js';
670
674
  export type { CodexRecord, CodexConversion } from './codex.js';
675
+ // Gemini CLI session files, read against the recorder's own source. See gemini-cli.ts.
676
+ export { geminiCliRecords, looksLikeGeminiCliSession } from './gemini-cli.js';
677
+ export type { GeminiCliRecord, GeminiCliConversion } from './gemini-cli.js';
678
+
679
+ // Usage-log lines with their content set aside, for files too large to hold whole. See slim-line.ts.
680
+ export { SLIM_STRING_CHARS, slimUsageLine } from './slim-line.js';
671
681
 
672
682
  export { HARNESS_CAPABILITIES, getHarnessCapability } from './harnesses.js';
673
683
  export type { HarnessCapability, HarnessCapabilities } from './harnesses.js';