@codetelemetry/connect 0.3.1 → 0.4.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.
@@ -1,4 +1,4 @@
1
- import { NO_CONTENT, sessionKeyOf, trimSessionToWindow } from "./model.js";
1
+ import { NO_CONTENT, addToMonths, maskIdentity, sessionKeyOf, tokensByMonth, trimSessionToWindow } from "./model.js";
2
2
  import { CLAUDE_SERVICE, CODEX_SERVICE, completionMarker, convertSession } from "./convert.js";
3
3
  import { chunkForPost, toOtlpLogs, toOtlpMetrics } from "./otlpImport.js";
4
4
  import { COMMIT_PART_LABEL, decide, logPartLabel, metricPartLabel } from "./protocol.js";
@@ -63,6 +63,9 @@ export const emptySummary = (source) => ({
63
63
  events: 0,
64
64
  metricPoints: 0,
65
65
  tokens: { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 },
66
+ months: [],
67
+ firstEventMs: null,
68
+ lastEventMs: null,
66
69
  });
67
70
  export const bump = (s, reason, n = 1) => {
68
71
  s.skipped[reason] = (s.skipped[reason] ?? 0) + n;
@@ -102,16 +105,23 @@ function stableResource(session, email) {
102
105
  "ingest.source": "history-import",
103
106
  "import.source": session.source,
104
107
  "import.version": IMPORT_VERSION,
108
+ ...(session.repositoryUrl ? { "vcs.repository.url.full": session.repositoryUrl } : {}),
109
+ ...(session.parentThreadId ? { "codex.parent_thread_id": session.parentThreadId } : {}),
105
110
  ...(session.cwd ? { "project.path": session.cwd } : {}),
106
111
  ...(email ? { "user.email": email } : {}),
107
112
  };
108
113
  }
109
- export async function buildPlan(session, content, email, sha256Hex) {
110
- const { logs, metrics } = convertSession(session, content);
114
+ export function identityFor(source, identity, email) {
115
+ return { ...(identity?.[source] ?? {}), ...(email ? { "user.email": email } : {}) };
116
+ }
117
+ export async function buildPlan(session, content, email, sha256Hex, identity) {
118
+ const who = identityFor(session.source, identity, email);
119
+ const { logs, metrics } = convertSession(session, content, who);
111
120
  const stable = stableResource(session, email);
112
121
  const id = (await sha256Hex(JSON.stringify({ v: IMPORT_VERSION, stable, sessionId: session.sessionId, logs, metrics }))).slice(0, 32);
113
122
  return {
114
123
  stable,
124
+ identity: who,
115
125
  plan: {
116
126
  id,
117
127
  logParts: chunkForPost(logs, LOG_PART_MAX_RECORDS, LOG_PART_MAX_BYTES),
@@ -141,7 +151,7 @@ export async function prepareSession(session, fileSig, reload, opts) {
141
151
  const trimmed = trimSessionToWindow(session, opts.sinceMs, opts.untilMs);
142
152
  if (!trimmed)
143
153
  return "older";
144
- const { plan } = await buildPlan(trimmed, opts.content[session.source], opts.email, opts.sha256Hex);
154
+ const { plan } = await buildPlan(trimmed, opts.content[session.source], opts.email, opts.sha256Hex, opts.identity);
145
155
  return {
146
156
  source: session.source,
147
157
  sessionId: trimmed.sessionId,
@@ -156,6 +166,7 @@ export async function prepareSession(session, fileSig, reload, opts) {
156
166
  metricPoints: plan.metricPoints,
157
167
  },
158
168
  tokens: tokensOf(trimmed),
169
+ monthTokens: tokensByMonth(trimmed),
159
170
  warnings: trimmed.warnings,
160
171
  reload,
161
172
  };
@@ -193,6 +204,7 @@ export async function importPrepared(prepared, o) {
193
204
  let stoppedBy = null;
194
205
  const statuses = new Map();
195
206
  let settleMs = 5 * 60_000;
207
+ let billing;
196
208
  const askStatus = async (items, probe) => {
197
209
  const batches = statusBatches(items).flatMap((b) => probe
198
210
  ? Array.from({ length: Math.ceil(b.length / MAX_STATUS_PROBES) }, (_, i) => b.slice(i * MAX_STATUS_PROBES, (i + 1) * MAX_STATUS_PROBES))
@@ -220,6 +232,8 @@ export async function importPrepared(prepared, o) {
220
232
  return false;
221
233
  }
222
234
  settleMs = r.value.settleMs;
235
+ if (r.value.billing)
236
+ billing = r.value.billing;
223
237
  for (const st of r.value.sessions)
224
238
  statuses.set(st.sessionId, st);
225
239
  }
@@ -269,8 +283,37 @@ export async function importPrepared(prepared, o) {
269
283
  const deferred = ready.length - toSend.length;
270
284
  for (const r of ready.slice(toSend.length))
271
285
  bump(summaries.get(r.p.source), "deferred");
286
+ let runBilling;
287
+ let budgetCut = 0;
288
+ if (billing) {
289
+ const priced = billing;
290
+ const cost = (tokens) => importCostUsd(tokens, priced);
291
+ const credit = Math.max(0, priced.creditUsd);
292
+ let cumulative = 0;
293
+ let fits = toSend.length;
294
+ for (let i = 0; i < toSend.length; i++) {
295
+ cumulative += tokenTotal(toSend[i].p.tokens);
296
+ if (fits === toSend.length && cost(cumulative) > credit + 1e-9)
297
+ fits = i;
298
+ }
299
+ runBilling = { ...priced, estimatedTokens: cumulative, estimatedCostUsd: roundUsd(cost(cumulative)), affordable: fits === toSend.length };
300
+ if (!dryRun && fits < toSend.length) {
301
+ const over = toSend.splice(fits);
302
+ budgetCut = over.length;
303
+ for (const r of over)
304
+ bump(summaries.get(r.p.source), "budget");
305
+ const fitTokens = toSend.reduce((n, r) => n + tokenTotal(r.p.tokens), 0);
306
+ runBilling = { ...runBilling, estimatedTokens: fitTokens, estimatedCostUsd: roundUsd(cost(fitTokens)) };
307
+ errors.push(`Stopped before ${budgetCut} session(s): importing every eligible session would cost about ` +
308
+ `${usd(cost(cumulative))} (${cumulative} tokens at ${usd(priced.tokenPriceUsdPerMillion)} per million, after ` +
309
+ `${Math.floor(priced.includedTokensRemaining)} included seat tokens left this month), more than the ${usd(credit)} prepaid credit. ` +
310
+ (toSend.length ? `This run was limited to the ${toSend.length} oldest session(s) that fit (${fitTokens} tokens). ` : "Nothing was sent. ") +
311
+ "Add credit or seats, then re-run the same command; finished sessions are skipped.");
312
+ }
313
+ }
272
314
  const pacer = makePacer(ratePerMinute, sleep, clock);
273
315
  let topup;
316
+ let refusedForBudget = false;
274
317
  let sent = 0;
275
318
  let processed = 0;
276
319
  for (let i = 0; i < toSend.length; i++) {
@@ -281,6 +324,9 @@ export async function importPrepared(prepared, o) {
281
324
  s.metricPoints += p.plan.metricPoints;
282
325
  for (const k of ["input", "output", "cacheRead", "cacheCreation"])
283
326
  s.tokens[k] += p.tokens[k];
327
+ addToMonths(s.months, p.startMs, p.monthTokens);
328
+ s.firstEventMs = s.firstEventMs === null ? p.startMs : Math.min(s.firstEventMs, p.startMs);
329
+ s.lastEventMs = s.lastEventMs === null ? p.endMs : Math.max(s.lastEventMs, p.endMs);
284
330
  };
285
331
  if (dryRun) {
286
332
  s.imported++;
@@ -299,12 +345,12 @@ export async function importPrepared(prepared, o) {
299
345
  processed++;
300
346
  const reloaded = await p.reload();
301
347
  const session = reloaded ? trimSessionToWindow(reloaded, o.sinceMs, o.untilMs) : null;
302
- const rebuilt = session ? await buildPlan(session, o.content[p.source], o.email, o.sha256Hex) : null;
348
+ const rebuilt = session ? await buildPlan(session, o.content[p.source], o.email, o.sha256Hex, o.identity) : null;
303
349
  if (!session || !rebuilt || rebuilt.plan.id !== p.plan.id) {
304
350
  bump(s, "changed_during_run");
305
351
  continue;
306
352
  }
307
- const { plan, stable } = rebuilt;
353
+ const { plan, stable, identity: who } = rebuilt;
308
354
  for (const w of p.warnings)
309
355
  warnings.push(`${p.source} ${p.sessionId}: ${w}`);
310
356
  const sessionKey = sessionKeyOf(p.source, p.sessionId);
@@ -327,6 +373,7 @@ export async function importPrepared(prepared, o) {
327
373
  const stopOn = (outcome) => {
328
374
  if (outcome.kind === "budget") {
329
375
  stoppedBy = "budget";
376
+ refusedForBudget = true;
330
377
  topup = outcome.topup;
331
378
  return true;
332
379
  }
@@ -377,7 +424,7 @@ export async function importPrepared(prepared, o) {
377
424
  if (!sessionFailed && !stoppedBy) {
378
425
  const marker = completionMarker(session, {
379
426
  id: plan.id, logParts: plan.logParts.length, metricParts: plan.metricParts.length, events: plan.events + plan.metricPoints,
380
- });
427
+ }, who);
381
428
  const outcome = await postOtlp({
382
429
  url: `${o.ingestEndpoint}/v1/logs`, key, fetchImpl, pacer, sleep, retryAmbiguous: true,
383
430
  body: toOtlpLogs([marker], resource(COMMIT_PART_LABEL)),
@@ -401,8 +448,10 @@ export async function importPrepared(prepared, o) {
401
448
  break;
402
449
  }
403
450
  }
404
- const remaining = deferred + (toSend.length - processed);
405
- if (stoppedBy === "budget") {
451
+ const remaining = deferred + budgetCut + (toSend.length - processed);
452
+ if (budgetCut > 0 && !stoppedBy)
453
+ stoppedBy = "budget";
454
+ if (refusedForBudget) {
406
455
  errors.push("Ingest refused with HTTP 402: this workspace's prepaid credit is exhausted, so it is not accepting " +
407
456
  "telemetry (live sessions included). Add credit or seats" + (topup ? ` at ${topup}` : "") +
408
457
  ", then re-run the same command — finished sessions are skipped and the interrupted one resumes.");
@@ -430,11 +479,31 @@ export async function importPrepared(prepared, o) {
430
479
  remaining,
431
480
  stoppedBy,
432
481
  ...(topup !== undefined ? { topup } : {}),
482
+ ...(runBilling ? { billing: runBilling } : {}),
483
+ ...maskedIdentity(sources.map((x) => x.source), o.identity, o.email),
433
484
  cleanup,
434
485
  warnings,
435
486
  errors,
436
487
  };
437
488
  }
489
+ const tokenTotal = (t) => t.input + t.output + t.cacheRead + t.cacheCreation;
490
+ export const roundUsd = (amount) => Math.round(amount * 1e6) / 1e6;
491
+ const usd = (amount) => "$" + (amount > 0 && amount < 0.01 ? amount.toFixed(4) : amount.toFixed(2));
492
+ export function importCostUsd(tokens, billing) {
493
+ if (!billing.importsBilled || billing.unlimited)
494
+ return 0;
495
+ return (Math.max(0, tokens - billing.includedTokensRemaining) * billing.tokenPriceUsdPerMillion) / 1e6;
496
+ }
497
+ export function maskedIdentity(sources, identity, email) {
498
+ const who = {};
499
+ for (const source of sources) {
500
+ const attrs = identityFor(source, identity, email);
501
+ if (Object.keys(attrs).length)
502
+ who[source] = attrs;
503
+ }
504
+ const masked = maskIdentity(who);
505
+ return Object.keys(masked).length ? { identity: masked } : {};
506
+ }
438
507
  export const contentOrDefault = (c) => ({
439
508
  "claude-code": c?.["claude-code"] ?? NO_CONTENT,
440
509
  codex: c?.codex ?? NO_CONTENT,
@@ -0,0 +1,87 @@
1
+ import type { ImportSource, ImportedSession, MonthBucket } from "./model.ts";
2
+ import type { FetchLike } from "../otlp.ts";
3
+ export type { MonthBucket } from "./model.ts";
4
+ export type HistoryEstimateSource = {
5
+ source: ImportSource;
6
+ filesFound: number;
7
+ sessions: number;
8
+ tokens: {
9
+ input: number;
10
+ output: number;
11
+ cacheRead: number;
12
+ cacheCreation: number;
13
+ };
14
+ events: number;
15
+ firstEventMs: number | null;
16
+ lastEventMs: number | null;
17
+ skipped: Record<string, number>;
18
+ };
19
+ export type HistoryEstimate = {
20
+ window: {
21
+ sinceIso: string;
22
+ untilIso: string;
23
+ };
24
+ sources: HistoryEstimateSource[];
25
+ months: MonthBucket[];
26
+ days: Array<{
27
+ day: string;
28
+ tokens: number;
29
+ }>;
30
+ totals: {
31
+ sessions: number;
32
+ tokens: number;
33
+ events: number;
34
+ };
35
+ oldestEventMs: number | null;
36
+ newestEventMs: number | null;
37
+ trailing30dTokens: number;
38
+ claudeCleanupPeriodDays: number | null;
39
+ warnings: string[];
40
+ };
41
+ export declare const ESTIMATE_DEFAULT_DAYS: number;
42
+ export declare const MAX_ESTIMATE_DAYS = 366;
43
+ export declare const MAX_ESTIMATE_WARNINGS = 50;
44
+ export declare const CLAUDE_DEFAULT_CLEANUP_DAYS = 30;
45
+ export declare const IMPORT_NEVER_RECOVERS: string;
46
+ export declare function estimateWindow(nowMs: number, sinceMs?: number): {
47
+ sinceMs: number;
48
+ untilMs: number;
49
+ clamped: boolean;
50
+ warning?: string;
51
+ };
52
+ export declare class EstimateBuilder {
53
+ #private;
54
+ constructor(opts: {
55
+ sinceMs: number;
56
+ untilMs: number;
57
+ nowMs: number;
58
+ sources: ImportSource[];
59
+ });
60
+ found(source: ImportSource, n?: number): void;
61
+ skip(source: ImportSource, reason: string, n?: number): void;
62
+ warn(message: string): void;
63
+ add(session: ImportedSession): "added" | "older" | "newer";
64
+ finish(extra: {
65
+ claudeCleanupPeriodDays: number | null;
66
+ }): HistoryEstimate;
67
+ }
68
+ export type PublicPricing = {
69
+ seatPriceUsdPerMonth: number;
70
+ tokenPriceUsdPerMillion: number;
71
+ includedTokensPerSeat: number;
72
+ signupCreditUsd: number;
73
+ retentionDays: number;
74
+ importsBilled: boolean;
75
+ };
76
+ export declare function parsePricing(raw: unknown): PublicPricing | null;
77
+ export declare function fetchPricing(apiBase: string, fetchImpl?: FetchLike, timeoutMs?: number): Promise<PublicPricing | null>;
78
+ export type EstimateCost = {
79
+ uploadCostUsd: number;
80
+ monthlyUsdOneSeat: number;
81
+ tokenPriceUsdPerMillion: number;
82
+ includedTokensPerSeat: number;
83
+ seatPriceUsdPerMonth: number;
84
+ importsBilled: boolean;
85
+ };
86
+ export declare function priceEstimate(estimate: Pick<HistoryEstimate, "totals" | "trailing30dTokens">, pricing: PublicPricing): EstimateCost;
87
+ export declare function claudeRetentionCutoffMs(nowMs: number, days: number): number;
@@ -0,0 +1,187 @@
1
+ import { DAY_OF, MONTH_OF, callTokens, sessionEventCount, trimSessionToWindow } from "./model.js";
2
+ import { DAY_MS, RETENTION_DAYS, RETENTION_MARGIN_DAYS, resolveWindow, startOfUtcDay } from "./core.js";
3
+ export const ESTIMATE_DEFAULT_DAYS = RETENTION_DAYS - RETENTION_MARGIN_DAYS;
4
+ export const MAX_ESTIMATE_DAYS = 366;
5
+ export const MAX_ESTIMATE_WARNINGS = 50;
6
+ export const CLAUDE_DEFAULT_CLEANUP_DAYS = 30;
7
+ const TRAILING_DAYS = 30;
8
+ export const IMPORT_NEVER_RECOVERS = "per-request latency and retries, permission decisions, active time, lines-of-code / commit / pull-request counters, " +
9
+ "model responses and tool output content";
10
+ export function estimateWindow(nowMs, sinceMs) {
11
+ return resolveWindow(nowMs, sinceMs ?? startOfUtcDay(nowMs - ESTIMATE_DEFAULT_DAYS * DAY_MS));
12
+ }
13
+ const emptySource = (source) => ({
14
+ source,
15
+ filesFound: 0,
16
+ sessions: 0,
17
+ tokens: { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 },
18
+ events: 0,
19
+ firstEventMs: null,
20
+ lastEventMs: null,
21
+ skipped: {},
22
+ });
23
+ export class EstimateBuilder {
24
+ #sinceMs;
25
+ #untilMs;
26
+ #nowMs;
27
+ #sources = new Map();
28
+ #months = [];
29
+ #days = new Map();
30
+ #warnings = [];
31
+ #warningsDropped = 0;
32
+ #trailing = 0;
33
+ constructor(opts) {
34
+ this.#sinceMs = opts.sinceMs;
35
+ this.#untilMs = opts.untilMs;
36
+ this.#nowMs = opts.nowMs;
37
+ for (const s of opts.sources)
38
+ this.#sources.set(s, emptySource(s));
39
+ }
40
+ #source(source) {
41
+ let s = this.#sources.get(source);
42
+ if (!s) {
43
+ s = emptySource(source);
44
+ this.#sources.set(source, s);
45
+ }
46
+ return s;
47
+ }
48
+ found(source, n = 1) {
49
+ this.#source(source).filesFound += n;
50
+ }
51
+ skip(source, reason, n = 1) {
52
+ const s = this.#source(source);
53
+ s.skipped[reason] = (s.skipped[reason] ?? 0) + n;
54
+ }
55
+ warn(message) {
56
+ if (this.#warnings.length < MAX_ESTIMATE_WARNINGS)
57
+ this.#warnings.push(message);
58
+ else
59
+ this.#warningsDropped++;
60
+ }
61
+ add(session) {
62
+ if (session.endMs < this.#sinceMs)
63
+ return "older";
64
+ if (session.startMs > this.#untilMs)
65
+ return "newer";
66
+ const trimmed = trimSessionToWindow(session, this.#sinceMs, this.#untilMs);
67
+ if (!trimmed)
68
+ return "older";
69
+ const s = this.#source(session.source);
70
+ s.sessions++;
71
+ s.events += sessionEventCount(trimmed);
72
+ s.firstEventMs = s.firstEventMs === null ? trimmed.startMs : Math.min(s.firstEventMs, trimmed.startMs);
73
+ s.lastEventMs = s.lastEventMs === null ? trimmed.endMs : Math.max(s.lastEventMs, trimmed.endMs);
74
+ this.#month(MONTH_OF(trimmed.startMs)).sessions++;
75
+ const trailingFrom = this.#nowMs - TRAILING_DAYS * DAY_MS;
76
+ for (const c of trimmed.modelCalls) {
77
+ s.tokens.input += c.inputTokens;
78
+ s.tokens.output += c.outputTokens;
79
+ s.tokens.cacheRead += c.cacheReadTokens;
80
+ s.tokens.cacheCreation += c.cacheCreationTokens;
81
+ const n = callTokens(c);
82
+ if (n <= 0)
83
+ continue;
84
+ const ts = Number.isFinite(c.tsMs) ? c.tsMs : trimmed.startMs;
85
+ this.#month(MONTH_OF(ts)).tokens += n;
86
+ const day = DAY_OF(ts);
87
+ this.#days.set(day, (this.#days.get(day) ?? 0) + n);
88
+ if (ts > trailingFrom && ts <= this.#nowMs)
89
+ this.#trailing += n;
90
+ }
91
+ return "added";
92
+ }
93
+ #month(month) {
94
+ let b = this.#months.find((m) => m.month === month);
95
+ if (!b) {
96
+ b = { month, sessions: 0, tokens: 0 };
97
+ this.#months.push(b);
98
+ }
99
+ return b;
100
+ }
101
+ finish(extra) {
102
+ const sources = [...this.#sources.values()];
103
+ const tokensOf = (s) => s.tokens.input + s.tokens.output + s.tokens.cacheRead + s.tokens.cacheCreation;
104
+ const firsts = sources.map((s) => s.firstEventMs).filter((v) => v !== null);
105
+ const lasts = sources.map((s) => s.lastEventMs).filter((v) => v !== null);
106
+ const days = [...this.#days.entries()]
107
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
108
+ .slice(-MAX_ESTIMATE_DAYS)
109
+ .map(([day, tokens]) => ({ day, tokens }));
110
+ const warnings = [...this.#warnings];
111
+ if (this.#warningsDropped)
112
+ warnings.push(`…and ${this.#warningsDropped} more warning(s)`);
113
+ const windowDays = (this.#nowMs - this.#sinceMs) / DAY_MS;
114
+ if (windowDays < TRAILING_DAYS) {
115
+ warnings.push(`The window covers only ${Math.max(0, Math.round(windowDays * 10) / 10)} day(s), so the last-30-day pace ` +
116
+ "(trailing30dTokens, and any monthly price from it) is understated; widen the window to 30 days or more.");
117
+ }
118
+ warnings.push("Sessions CodeTelemetry already captured live are counted here too; an import checks with the server and skips them.");
119
+ return {
120
+ window: { sinceIso: new Date(this.#sinceMs).toISOString(), untilIso: new Date(this.#untilMs).toISOString() },
121
+ sources,
122
+ months: [...this.#months].sort((a, b) => (a.month < b.month ? -1 : a.month > b.month ? 1 : 0)),
123
+ days,
124
+ totals: {
125
+ sessions: sources.reduce((n, s) => n + s.sessions, 0),
126
+ tokens: sources.reduce((n, s) => n + tokensOf(s), 0),
127
+ events: sources.reduce((n, s) => n + s.events, 0),
128
+ },
129
+ oldestEventMs: firsts.length ? Math.min(...firsts) : null,
130
+ newestEventMs: lasts.length ? Math.max(...lasts) : null,
131
+ trailing30dTokens: this.#trailing,
132
+ claudeCleanupPeriodDays: extra.claudeCleanupPeriodDays,
133
+ warnings,
134
+ };
135
+ }
136
+ }
137
+ const nonNegative = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
138
+ export function parsePricing(raw) {
139
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
140
+ return null;
141
+ const p = raw;
142
+ if (!nonNegative(p.seatPriceUsdPerMonth) || !nonNegative(p.tokenPriceUsdPerMillion) || !nonNegative(p.includedTokensPerSeat) ||
143
+ !nonNegative(p.signupCreditUsd) || !nonNegative(p.retentionDays) || typeof p.importsBilled !== "boolean")
144
+ return null;
145
+ return {
146
+ seatPriceUsdPerMonth: p.seatPriceUsdPerMonth,
147
+ tokenPriceUsdPerMillion: p.tokenPriceUsdPerMillion,
148
+ includedTokensPerSeat: p.includedTokensPerSeat,
149
+ signupCreditUsd: p.signupCreditUsd,
150
+ retentionDays: p.retentionDays,
151
+ importsBilled: p.importsBilled,
152
+ };
153
+ }
154
+ export async function fetchPricing(apiBase, fetchImpl = (i, init) => fetch(i, init), timeoutMs = 5_000) {
155
+ const ac = new AbortController();
156
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
157
+ try {
158
+ const res = await fetchImpl(`${apiBase.replace(/\/$/, "")}/api/pricing`, { method: "GET", headers: { accept: "application/json" }, signal: ac.signal });
159
+ if (res.status !== 200)
160
+ return null;
161
+ const text = await res.text();
162
+ if (text.length > 16_384)
163
+ return null;
164
+ return parsePricing(JSON.parse(text));
165
+ }
166
+ catch {
167
+ return null;
168
+ }
169
+ finally {
170
+ clearTimeout(timer);
171
+ }
172
+ }
173
+ const round2 = (usd) => Math.round(usd * 100) / 100;
174
+ export function priceEstimate(estimate, pricing) {
175
+ const perToken = pricing.tokenPriceUsdPerMillion / 1e6;
176
+ return {
177
+ uploadCostUsd: pricing.importsBilled ? round2(estimate.totals.tokens * perToken) : 0,
178
+ monthlyUsdOneSeat: round2(pricing.seatPriceUsdPerMonth + Math.max(0, estimate.trailing30dTokens - pricing.includedTokensPerSeat) * perToken),
179
+ tokenPriceUsdPerMillion: pricing.tokenPriceUsdPerMillion,
180
+ includedTokensPerSeat: pricing.includedTokensPerSeat,
181
+ seatPriceUsdPerMonth: pricing.seatPriceUsdPerMonth,
182
+ importsBilled: pricing.importsBilled,
183
+ };
184
+ }
185
+ export function claudeRetentionCutoffMs(nowMs, days) {
186
+ return startOfUtcDay(nowMs - days * DAY_MS);
187
+ }
@@ -0,0 +1,25 @@
1
+ import type { IdentityBySource, ImportIdentity, ImportSource } from "./model.ts";
2
+ export declare function taggedId(tag: string, uuid: string): string | undefined;
3
+ export declare function claudeGlobalConfigPath(env?: NodeJS.ProcessEnv, home?: string): string;
4
+ export declare function codexAuthPath(env?: NodeJS.ProcessEnv, home?: string): string;
5
+ export declare function readClaudeIdentity(opts?: {
6
+ configPath?: string;
7
+ settingsPath?: string;
8
+ env?: NodeJS.ProcessEnv;
9
+ home?: string;
10
+ }): ImportIdentity;
11
+ export declare function readCodexIdentity(opts?: {
12
+ authPath?: string;
13
+ env?: NodeJS.ProcessEnv;
14
+ home?: string;
15
+ }): ImportIdentity;
16
+ export type IdentityResolveOptions = {
17
+ source: ImportSource | "all";
18
+ disabled?: boolean;
19
+ env?: NodeJS.ProcessEnv;
20
+ home?: string;
21
+ claudeConfigPath?: string;
22
+ claudeSettingsPath?: string;
23
+ codexAuthPath?: string;
24
+ };
25
+ export declare function resolveImportIdentity(opts: IdentityResolveOptions): IdentityBySource;
@@ -0,0 +1,118 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { defaultClaudeSettingsPath } from "./sources/files.js";
5
+ const MAX_CLAUDE_CONFIG_BYTES = 32 * 1024 * 1024;
6
+ const MAX_AUTH_BYTES = 1024 * 1024;
7
+ const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
8
+ export function taggedId(tag, uuid) {
9
+ const hex = uuid.replace(/-/g, "");
10
+ if (!/^[0-9a-fA-F]{32}$/.test(hex))
11
+ return undefined;
12
+ const out = Array(22).fill("1");
13
+ let n = BigInt("0x" + hex);
14
+ for (let i = 21; n > 0n && i >= 0; i--) {
15
+ out[i] = BASE58[Number(n % 58n)];
16
+ n /= 58n;
17
+ }
18
+ return `${tag}_01${out.join("")}`;
19
+ }
20
+ export function claudeGlobalConfigPath(env = process.env, home = os.homedir()) {
21
+ const dir = env.CLAUDE_CONFIG_DIR || undefined;
22
+ const legacy = path.join(dir ?? path.join(home, ".claude"), ".config.json");
23
+ if (fs.existsSync(legacy))
24
+ return legacy;
25
+ return path.join(dir ?? home, ".claude.json");
26
+ }
27
+ export function codexAuthPath(env = process.env, home = os.homedir()) {
28
+ return env.CODEX_HOME ? path.join(env.CODEX_HOME, "auth.json") : path.join(home, ".codex", "auth.json");
29
+ }
30
+ function readJson(file, maxBytes) {
31
+ try {
32
+ const st = fs.statSync(file);
33
+ if (!st.isFile() || st.size > maxBytes)
34
+ return null;
35
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
36
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ const EMAIL_RE = /^[^\s@]{1,128}@[^\s@]{1,190}$/;
43
+ const ID_RE = /^[A-Za-z0-9_.:-]{1,256}$/;
44
+ const email = (v) => (typeof v === "string" && EMAIL_RE.test(v.trim()) ? v.trim() : undefined);
45
+ const id = (v) => (typeof v === "string" && ID_RE.test(v) ? v : undefined);
46
+ const off = (v) => typeof v === "string" && /^(false|0|no|off)$/i.test(v.trim());
47
+ const compact = (attrs) => {
48
+ const out = {};
49
+ for (const [k, v] of Object.entries(attrs))
50
+ if (v)
51
+ out[k] = v;
52
+ return out;
53
+ };
54
+ export function readClaudeIdentity(opts = {}) {
55
+ const env = opts.env ?? process.env;
56
+ const config = readJson(opts.configPath ?? claudeGlobalConfigPath(env, opts.home), MAX_CLAUDE_CONFIG_BYTES);
57
+ if (!config)
58
+ return {};
59
+ const account = config.oauthAccount && typeof config.oauthAccount === "object" ? config.oauthAccount : {};
60
+ const settings = readJson(opts.settingsPath ?? defaultClaudeSettingsPath(env, opts.home), MAX_AUTH_BYTES);
61
+ const settingsEnv = settings?.env && typeof settings.env === "object" ? settings.env : {};
62
+ const includeUuid = !off(env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID) && !off(settingsEnv.OTEL_METRICS_INCLUDE_ACCOUNT_UUID);
63
+ const accountUuid = id(account.accountUuid);
64
+ const tagged = id(env.CLAUDE_CODE_ACCOUNT_TAGGED_ID ?? settingsEnv.CLAUDE_CODE_ACCOUNT_TAGGED_ID) ??
65
+ (accountUuid ? taggedId("user", accountUuid) : undefined);
66
+ return compact({
67
+ "organization.id": id(account.organizationUuid),
68
+ "user.account_id": includeUuid ? tagged : undefined,
69
+ "user.account_uuid": includeUuid ? accountUuid : undefined,
70
+ "user.email": email(account.emailAddress),
71
+ "user.id": id(config.userID),
72
+ });
73
+ }
74
+ function jwtPayload(token) {
75
+ if (typeof token !== "string" || token.length > 64 * 1024)
76
+ return null;
77
+ const parts = token.split(".");
78
+ if (parts.length < 2)
79
+ return null;
80
+ try {
81
+ const value = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
82
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ export function readCodexIdentity(opts = {}) {
89
+ const auth = readJson(opts.authPath ?? codexAuthPath(opts.env ?? process.env, opts.home), MAX_AUTH_BYTES);
90
+ const tokens = auth?.tokens && typeof auth.tokens === "object" ? auth.tokens : null;
91
+ if (!tokens)
92
+ return {};
93
+ const claims = jwtPayload(tokens.id_token) ?? {};
94
+ const openai = claims["https://api.openai.com/auth"];
95
+ const authClaims = openai && typeof openai === "object" ? openai : {};
96
+ const profile = claims["https://api.openai.com/profile"];
97
+ const profileClaims = profile && typeof profile === "object" ? profile : {};
98
+ return compact({
99
+ "user.account_id": id(authClaims.chatgpt_account_id) ?? id(tokens.account_id),
100
+ "user.email": email(claims.email) ?? email(profileClaims.email),
101
+ });
102
+ }
103
+ export function resolveImportIdentity(opts) {
104
+ if (opts.disabled)
105
+ return {};
106
+ const out = {};
107
+ if (opts.source !== "codex") {
108
+ const claude = readClaudeIdentity({ configPath: opts.claudeConfigPath, settingsPath: opts.claudeSettingsPath, env: opts.env, home: opts.home });
109
+ if (Object.keys(claude).length)
110
+ out["claude-code"] = claude;
111
+ }
112
+ if (opts.source !== "claude-code") {
113
+ const codex = readCodexIdentity({ authPath: opts.codexAuthPath, env: opts.env, home: opts.home });
114
+ if (Object.keys(codex).length)
115
+ out.codex = codex;
116
+ }
117
+ return out;
118
+ }
@@ -39,6 +39,8 @@ export type ImportedSession = {
39
39
  files: string[];
40
40
  fileSig: string;
41
41
  cwd: string | null;
42
+ repositoryUrl?: string;
43
+ parentThreadId?: string;
42
44
  startMs: number;
43
45
  endMs: number;
44
46
  prompts: ImportedPrompt[];
@@ -52,6 +54,22 @@ export declare const MAX_EVENTS_PER_SESSION = 200000;
52
54
  export declare const MAX_PROMPT_CHARS = 64000;
53
55
  export declare const MAX_TOOL_INPUT_CHARS = 16000;
54
56
  export declare const capText: (s: string, n: number) => string;
57
+ export declare const TOOL_INPUT_KEEP_KEYS: ReadonlySet<string>;
58
+ export declare function capToolInput(value: unknown, full: string, max: number): string;
59
+ export type ImportIdentity = Readonly<Record<string, string>>;
60
+ export type IdentityBySource = Partial<Record<ImportSource, ImportIdentity>>;
61
+ export declare function maskEmail(email: string): string;
62
+ export declare function maskIdentity(identity: IdentityBySource): Partial<Record<ImportSource, Record<string, string>>>;
63
+ export declare const MONTH_OF: (ms: number) => string;
64
+ export declare const DAY_OF: (ms: number) => string;
65
+ export declare const callTokens: (c: Pick<ImportedModelCall, "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheCreationTokens">) => number;
66
+ export declare function tokensByMonth(session: Pick<ImportedSession, "modelCalls">): Record<string, number>;
67
+ export type MonthBucket = {
68
+ month: string;
69
+ sessions: number;
70
+ tokens: number;
71
+ };
72
+ export declare function addToMonths(months: MonthBucket[], startMs: number, monthTokens: Record<string, number>): void;
55
73
  export type ImportLog = {
56
74
  timeUnixNano: string;
57
75
  attributes: ImportAttributes;