@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.
package/README.md CHANGED
@@ -13,7 +13,7 @@ privacy, client setup and service removal.
13
13
 
14
14
  ## Organization projects
15
15
 
16
- Use `npx -y @codetelemetry/connect@0.3.1 join --organization-id tm_example --client codex --project .`
16
+ Use `npx -y @codetelemetry/connect@0.4.0 join --organization-id tm_example --client codex --project .`
17
17
  from the project you choose, or use `--client claude`. Approve the displayed existing
18
18
  organization and follow the saved workspace's launch instructions. New connections
19
19
  capture prompts and supported tool content; `--no-enrich` opts out on new setup.
package/dist/cli.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { reportRolloutRepositories } from "./rolloutRepository.js";
1
2
  import fs from "node:fs";
2
3
  import { joinOrganization, workspaceProject } from "./join.js";
3
4
  import { importWorkspaceHistory } from "./workspaceImport.js";
@@ -10,8 +11,10 @@ import { resolveEndpoints } from "./config.js";
10
11
  import { CLIENTS, PI_EXTENSION_HINT } from "./clients.js";
11
12
  import { ONBOARD_CLIENTS, isOnboardClient } from "./assistants.js";
12
13
  import { looksLikeKey, mask } from "./keys.js";
13
- import { runImport } from "./import/run.js";
14
+ import { runImport, runEstimate } from "./import/run.js";
14
15
  import { parseContentFlag, parseWhen, resolveImportContent, resolveImportKey } from "./import/options.js";
16
+ import { resolveImportIdentity } from "./import/identity.js";
17
+ import { ESTIMATE_DEFAULT_DAYS, IMPORT_NEVER_RECOVERS, claudeRetentionCutoffMs, fetchPricing, priceEstimate, } from "./import/estimate.js";
15
18
  import { requestDeviceCode, pollForKey } from "./deviceClient.js";
16
19
  import { sendTestEvent } from "./otlp.js";
17
20
  import { confirmLanded, verifyScope } from "./connectivity.js";
@@ -46,6 +49,9 @@ function parse(argv) {
46
49
  const HELP = `codetelemetry-connect — wire Claude Code, OpenAI Codex or pi into CodeTelemetry
47
50
 
48
51
  Usage:
52
+ codetelemetry-connect repository-metadata <rollout files> [--send]
53
+ Preview GitHub origins and parent IDs. --send uses CODETELEMETRY_INGEST_KEY.
54
+ codetelemetry-connect repository-metadata --state <Codex state database> <thread IDs> [--send]
49
55
  codetelemetry-connect join --organization-id ID --client claude|codex [--project PATH]
50
56
  Connect this project; resume the same command after interruption.
51
57
  codetelemetry-connect import --workspace NAME --preview
@@ -68,6 +74,9 @@ Usage:
68
74
  process health (see below)
69
75
  codetelemetry-connect kiro status|collect|enable|disable|uninstall
70
76
  Manage the background V3 transcript collector
77
+ codetelemetry-connect estimate [opts] Price past Claude Code / Codex
78
+ sessions before importing them:
79
+ no key, nothing sent (see below)
71
80
  codetelemetry-connect import [opts] Backfill past Claude Code / Codex
72
81
  sessions from local history files
73
82
  (see below)
@@ -123,6 +132,18 @@ host-metrics options:
123
132
  --interfaces Keep per-interface network breakdown (off by default)
124
133
  --mounts Keep per-mount filesystem breakdown (off by default)
125
134
 
135
+ estimate options:
136
+ Reads the same local history as import, counts sessions and tokens per
137
+ source, month and day, and prices them with the public price list
138
+ (GET /api/pricing, the only request it makes). Claude Code deletes local
139
+ transcripts cleanupPeriodDays (default 30) after their last activity; the
140
+ estimate prints the cutoff before which a session survives only if it was
141
+ captured live or its transcript is still on disk.
142
+ --source claude-code|codex|all Which history to read (default: all)
143
+ --since <Nd|date> Window start (default: 364d, the whole retained year)
144
+ --api-base <url> Where the price list is read (default: https://codetelemetry.com)
145
+ --json Emit the estimate (and pricing) as JSON
146
+
126
147
  import options:
127
148
  Reads ~/.claude/projects/**/*.jsonl (Claude Code) and ~/.codex/sessions/**
128
149
  (Codex) locally and sends them as telemetry through the normal ingest, tagged
@@ -130,6 +151,10 @@ import options:
130
151
  imported, are skipped; an interrupted import resumes on the next run.
131
152
  Imported history has tokens, prompts and tool results, but no per-request
132
153
  latency, retries, permission decisions or active time.
154
+ Imported tokens are billed like live usage: they count toward this month's
155
+ included seat tokens first, then 5¢ per million from prepaid credit. When the
156
+ server reports billing state, an import starts no session the credit cannot
157
+ cover (--dry-run reports whether the whole window is affordable).
133
158
  --dry-run Parse, check and summarize; send nothing
134
159
  --source claude-code|codex|all Which history to read (default: all; --client
135
160
  claude|codex narrows it too). pi is refused: it keeps
@@ -138,7 +163,13 @@ import options:
138
163
  telemetry is kept 365 days by event time)
139
164
  --until <Nd|date> Window end (default: now)
140
165
  --project <path> Only sessions whose working directory is under <path>
141
- --email <addr> Stamp user.email on imported rows
166
+ --email <addr> Stamp user.email on imported rows (overrides the
167
+ signed-in account's email)
168
+ --no-identity Do not stamp the signed-in account's identity (by
169
+ default rows carry what live exporters send: Claude
170
+ organization.id, user.account_id, user.account_uuid,
171
+ user.email, user.id from ~/.claude.json; Codex
172
+ user.account_id, user.email from ~/.codex/auth.json)
142
173
  --content none|live|all|prompts,tools
143
174
  Text to include (default: live — exactly what your
144
175
  live exporters send: Claude OTEL_LOG_USER_PROMPTS /
@@ -238,8 +269,9 @@ const ONBOARDING_FLAGS = new Set([
238
269
  const IMPORT_FLAGS = new Set([
239
270
  "json", "help", "h", "api-base", "endpoint", "codex", "settings",
240
271
  "dry-run", "source", "since", "until", "project", "email", "content", "max-sessions", "rate",
241
- "time-limit", "key-env", "codex-config", "client",
272
+ "time-limit", "key-env", "codex-config", "client", "identity",
242
273
  ]);
274
+ const ESTIMATE_FLAGS = new Set(["json", "help", "h", "source", "since", "api-base"]);
243
275
  function unknownFlag(flags, allowed) {
244
276
  for (const key of Object.keys(flags))
245
277
  if (!allowed.has(key))
@@ -264,7 +296,121 @@ const SKIP_LABELS = {
264
296
  unreadable: "unreadable",
265
297
  changed_during_run: "changed while importing",
266
298
  deferred: "deferred (session cap / time limit)",
299
+ budget: "would exceed the prepaid credit (add credit, then re-run)",
300
+ time_limit: "not read before the time limit",
267
301
  };
302
+ const fmtInt = (n) => Math.round(n).toLocaleString("en-US");
303
+ const fmtUsd = (n) => (n > 0 && n < 0.01 ? "less than $0.01" : `$${n.toFixed(2)}`);
304
+ const perMillionLabel = (usd) => usd < 1 ? `${Math.round(usd * 100 * 1000) / 1000}¢` : `$${usd.toFixed(2)}`;
305
+ const dateOf = (ms) => new Date(ms).toISOString().slice(0, 10);
306
+ const sourceLabel = (s) => (s === "claude-code" ? "Claude Code" : "Codex");
307
+ function identityLine(identity) {
308
+ if (!identity)
309
+ return null;
310
+ const parts = Object.entries(identity).map(([source, attrs]) => `${sourceLabel(source)} ${attrs["user.email"] ?? "(no email)"}` +
311
+ (Object.keys(attrs).filter((k) => k !== "user.email").length ? ` + ${Object.keys(attrs).filter((k) => k !== "user.email").join(", ")}` : ""));
312
+ return parts.length ? `Identity on imported rows: ${parts.join("; ")} (--no-identity to omit)` : null;
313
+ }
314
+ function billingLines(result) {
315
+ const b = result.billing;
316
+ if (!b)
317
+ return [];
318
+ if (!b.importsBilled)
319
+ return [`Billing: imported tokens are not billed for this workspace (${fmtInt(b.estimatedTokens)} tokens).`];
320
+ if (b.unlimited)
321
+ return [`Billing: ${fmtInt(b.estimatedTokens)} tokens; this workspace's token allowance is unlimited, so the import costs nothing.`];
322
+ return [
323
+ `Billing: ${fmtInt(b.estimatedTokens)} tokens ${result.dryRun ? "would cost" : "cost"} about ${fmtUsd(b.estimatedCostUsd)} at ` +
324
+ `${perMillionLabel(b.tokenPriceUsdPerMillion)} per million, after ${fmtInt(b.includedTokensRemaining)} included seat tokens left this month.`,
325
+ ` prepaid credit ${fmtUsd(Math.max(0, b.creditUsd))}: ` +
326
+ (b.affordable ? "affordable" : result.dryRun
327
+ ? "NOT affordable; a real import stops before the first session the credit cannot cover"
328
+ : "not enough for every session; the rest were skipped (add credit, then re-run)"),
329
+ ];
330
+ }
331
+ async function runEstimateCommand(flags, fetchImpl) {
332
+ const rogue = unknownFlag(flags, ESTIMATE_FLAGS);
333
+ if (rogue) {
334
+ out(`Unknown option --${rogue} for estimate.`);
335
+ return 1;
336
+ }
337
+ const source = str(flags, "source") ?? "all";
338
+ if (source !== "all" && source !== "claude-code" && source !== "codex") {
339
+ out("--source must be claude-code, codex or all.");
340
+ return 1;
341
+ }
342
+ const now = Date.now();
343
+ let sinceMs;
344
+ if (hasFlag(flags, "since")) {
345
+ const raw = str(flags, "since");
346
+ const parsed = raw === undefined ? null : parseWhen(raw, now);
347
+ if (parsed === null) {
348
+ out("--since takes a number of days or hours (30d, 90d, 364d) or an ISO date (2026-09-01).");
349
+ return 1;
350
+ }
351
+ sinceMs = parsed;
352
+ }
353
+ const json = flags.json !== undefined && flags.json !== false;
354
+ const estimate = await runEstimate({ source, sinceMs, nowMs: now });
355
+ const apiBase = resolveEndpoints({ apiBase: str(flags, "api-base") }).apiBase;
356
+ const pricing = await fetchPricing(apiBase, fetchImpl);
357
+ const cost = pricing ? priceEstimate(estimate, pricing) : null;
358
+ if (json) {
359
+ out(JSON.stringify({ ...estimate, pricing, cost }, null, 2));
360
+ return 0;
361
+ }
362
+ for (const line of estimateLines(estimate, { pricing, cost, apiBase, now, since: str(flags, "since") }))
363
+ out(line);
364
+ return 0;
365
+ }
366
+ function estimateLines(e, o) {
367
+ const lines = [];
368
+ lines.push("Estimate from local history: nothing was sent and no key was used.");
369
+ lines.push(`Window ${e.window.sinceIso.slice(0, 10)} → ${e.window.untilIso.slice(0, 16).replace("T", " ")} UTC`);
370
+ lines.push("");
371
+ for (const s of e.sources) {
372
+ const tokens = s.tokens.input + s.tokens.output + s.tokens.cacheRead + s.tokens.cacheCreation;
373
+ lines.push(`${sourceLabel(s.source)}: ${fmtInt(s.sessions)} session(s), ${fmtInt(tokens)} tokens (${fmtInt(s.filesFound)} session file(s) found)`);
374
+ for (const [reason, n] of Object.entries(s.skipped))
375
+ if (n)
376
+ lines.push(` skipped ${n}: ${SKIP_LABELS[reason] ?? reason}`);
377
+ }
378
+ if (e.months.length) {
379
+ lines.push("");
380
+ lines.push("Tokens by month (UTC):");
381
+ for (const m of e.months)
382
+ lines.push(` ${m.month} ${fmtInt(m.sessions).padStart(6)} session(s) ${fmtInt(m.tokens).padStart(16)} tokens`);
383
+ }
384
+ if (e.oldestEventMs !== null && e.newestEventMs !== null) {
385
+ lines.push(`Oldest session: ${dateOf(e.oldestEventMs)} · newest session: ${dateOf(e.newestEventMs)}`);
386
+ }
387
+ lines.push("");
388
+ if (o.pricing && o.cost) {
389
+ const rate = `${perMillionLabel(o.pricing.tokenPriceUsdPerMillion)} per million tokens`;
390
+ lines.push(o.cost.importsBilled
391
+ ? `Uploading these sessions: about ${fmtUsd(o.cost.uploadCostUsd)} at ${rate} (included seat tokens apply first).`
392
+ : "Uploading these sessions: imported tokens are not billed.");
393
+ lines.push(`At this pace: about ${fmtUsd(o.cost.monthlyUsdOneSeat)}/month for one seat ` +
394
+ `(${fmtInt(e.trailing30dTokens)} tokens in the last 30 days; ${fmtInt(o.pricing.includedTokensPerSeat)} included per seat at ` +
395
+ `${fmtUsd(o.pricing.seatPriceUsdPerMonth)}/month, then ${rate}).`);
396
+ }
397
+ else {
398
+ lines.push(`${fmtInt(e.totals.tokens)} tokens in total (${fmtInt(e.trailing30dTokens)} in the last 30 days). ` +
399
+ `Prices could not be read; see ${o.apiBase}/estimate`);
400
+ }
401
+ if (e.claudeCleanupPeriodDays !== null) {
402
+ const n = e.claudeCleanupPeriodDays;
403
+ lines.push(`Gone for good: Claude Code deletes transcripts ${n} day(s) after their last activity (cleanupPeriodDays, default 30), ` +
404
+ `so a Claude Code session from before ${dateOf(claudeRetentionCutoffMs(o.now, n))} survives only if CodeTelemetry captured it live or its transcript is still on disk (those are counted above). ` +
405
+ "Codex keeps its rollouts until you remove them.");
406
+ }
407
+ lines.push(`An import never recovers ${IMPORT_NEVER_RECOVERS}; those exist only in live telemetry.`);
408
+ for (const w of e.warnings.slice(0, 10))
409
+ lines.push(`warning: ${w}`);
410
+ lines.push("");
411
+ lines.push(`Next: codetelemetry-connect import --dry-run --since ${o.since ?? `${ESTIMATE_DEFAULT_DAYS}d`}`);
412
+ return lines;
413
+ }
268
414
  async function runImportCommand(positional, flags, endpoints, settingsOpts, client) {
269
415
  const rogue = unknownFlag(flags, IMPORT_FLAGS);
270
416
  if (rogue) {
@@ -345,6 +491,11 @@ async function runImportCommand(positional, flags, endpoints, settingsOpts, clie
345
491
  out("--project and --email need a value.");
346
492
  return 1;
347
493
  }
494
+ if (hasFlag(flags, "identity") && flags.identity !== false) {
495
+ out("--no-identity takes no value.");
496
+ return 1;
497
+ }
498
+ const identity = resolveImportIdentity({ source, disabled: flags.identity === false });
348
499
  const log = json.on ? undefined : out;
349
500
  log?.(`${dry.on ? "Dry run: reading" : "Importing"} local history with ${mask(resolved.key)} (from ${resolved.from})…`);
350
501
  const result = await runImport({
@@ -355,6 +506,7 @@ async function runImportCommand(positional, flags, endpoints, settingsOpts, clie
355
506
  untilMs,
356
507
  project,
357
508
  email,
509
+ identity,
358
510
  content: resolveImportContent(content, paths),
359
511
  dryRun: dry.on,
360
512
  maxSessions,
@@ -381,11 +533,24 @@ async function runImportCommand(positional, flags, endpoints, settingsOpts, clie
381
533
  if (tok.input + tok.output + tok.cacheRead + tok.cacheCreation > 0) {
382
534
  out(` tokens: ${tok.input} input, ${tok.output} output, ${tok.cacheRead} cache read, ${tok.cacheCreation} cache write`);
383
535
  }
536
+ if (s.months.length) {
537
+ out(` by month: ${s.months.map((m) => `${m.month} ${m.sessions} session(s) ${fmtInt(m.tokens)} tokens`).join("; ")}`);
538
+ }
539
+ if (s.firstEventMs !== null && s.lastEventMs !== null)
540
+ out(` sessions from ${dateOf(s.firstEventMs)} to ${dateOf(s.lastEventMs)}`);
384
541
  for (const [reason, n] of Object.entries(s.skipped)) {
385
542
  if (n)
386
543
  out(` skipped ${n}: ${SKIP_LABELS[reason] ?? reason}`);
387
544
  }
388
545
  }
546
+ const who = identityLine(result.identity);
547
+ if (who)
548
+ out(`\n${who}`);
549
+ const billing = billingLines(result);
550
+ if (billing.length)
551
+ out("");
552
+ for (const line of billing)
553
+ out(line);
389
554
  if (result.remaining)
390
555
  out(`\n${result.remaining} session(s) remain — re-run the same command to continue.`);
391
556
  for (const c of result.cleanup)
@@ -424,6 +589,14 @@ export async function run(argv) {
424
589
  out(HELP);
425
590
  return 0;
426
591
  }
592
+ if (cmd === "estimate")
593
+ return runEstimateCommand(flags);
594
+ if (cmd === "repository-metadata") {
595
+ if (unknownFlag(flags, new Set(["send", "state"])) || (flags.state !== undefined && typeof flags.state !== "string") || (flags.send !== undefined && typeof flags.send !== "boolean"))
596
+ throw new Error("Put --send after the selected files.");
597
+ out(JSON.stringify(await reportRolloutRepositories(_.slice(1), flags.send === true, str(flags, "state"))));
598
+ return 0;
599
+ }
427
600
  if (cmd === "join") {
428
601
  const rogue = unknownFlag(flags, new Set(["organization-id", "client", "project", "enrich", "reauthorize", "open", "json", "api-base"]));
429
602
  if (rogue)
@@ -463,7 +636,7 @@ export async function run(argv) {
463
636
  result.previewSessions.forEach((session, i) => out(`${i + 1}. ${session.source} ${session.sessionId} · ${new Date(session.endMs).toISOString()} · ${session.events} events`));
464
637
  if (result.remaining)
465
638
  out(`${result.remaining} additional sessions remain; narrow --since for another preview.`);
466
- out(`Import selected numbers: npx -y @codetelemetry/connect@0.3.1 import --workspace ${flags.workspace} --select 1,2 --confirm`);
639
+ out(`Import selected numbers: npx -y @codetelemetry/connect@0.4.0 import --workspace ${flags.workspace} --select 1,2 --confirm`);
467
640
  }
468
641
  else
469
642
  out(`Imported ${result.totals.sessions} sessions; ${result.remaining} remain. ${result.errors.slice(0, 3).join(" ")}`);
@@ -1,4 +1,5 @@
1
1
  import { type ContentBySource, type ImportRunResult } from "./core.ts";
2
+ import { type HistoryEstimate } from "./estimate.ts";
2
3
  import type { FetchLike } from "../otlp.ts";
3
4
  export type UploadFile = {
4
5
  name: string;
@@ -22,9 +23,16 @@ export type BrowserImportOptions = {
22
23
  sinceMs?: number;
23
24
  content?: Partial<ContentBySource>;
24
25
  maxSessions?: number;
26
+ identity?: {
27
+ email?: string;
28
+ };
25
29
  fetchImpl?: FetchLike;
26
30
  nowMs?: number;
27
31
  sleep?: (ms: number) => Promise<void>;
28
32
  logger?: (msg: string) => void;
29
33
  };
30
34
  export declare function importFiles(files: UploadFile[], opts: BrowserImportOptions): Promise<ImportRunResult>;
35
+ export declare function estimateFiles(files: UploadFile[], opts?: {
36
+ nowMs?: number;
37
+ sinceMs?: number;
38
+ }): Promise<HistoryEstimate>;
@@ -1,6 +1,8 @@
1
+ import { NO_CONTENT } from "./model.js";
1
2
  import { ClaudeSessionAccumulator } from "./sources/claudeCodeText.js";
2
3
  import { CodexSessionAccumulator, codexSessionIdFromName } from "./sources/codexText.js";
3
4
  import { ACTIVE_GRACE_MS, bump, contentOrDefault, emptySummary, importPrepared, memoryLedger, prepareSession, resolveWindow, } from "./core.js";
5
+ import { EstimateBuilder, estimateWindow } from "./estimate.js";
4
6
  export const MAX_UPLOAD_FILE_BYTES = 128 * 1024 * 1024;
5
7
  export const MAX_UPLOAD_TOTAL_BYTES = 512 * 1024 * 1024;
6
8
  export const MAX_UPLOAD_FILES = 2_000;
@@ -51,87 +53,101 @@ async function parseGroup(g, keep) {
51
53
  const mtime = Math.max(...g.files.map((f) => f.lastModified));
52
54
  return acc.finish({ files: g.files.map((f) => f.name), fileSig: `${bytes}:${mtime}:${g.files.length}`, fallbackSessionId: g.sessionId });
53
55
  }
54
- export async function importFiles(files, opts) {
55
- const key = opts.key.trim();
56
- if (!looksLikeBrowserKey(key))
57
- throw new Error("not a CodeTelemetry ingest key (expected cot_…)");
58
- const now = opts.nowMs ?? Date.now();
59
- const content = contentOrDefault(opts.content);
60
- const warnings = [];
61
- const window = resolveWindow(now, opts.sinceMs);
62
- if (window.warning)
63
- warnings.push(window.warning);
64
- const summaries = new Map([
65
- ["claude-code", emptySummary("claude-code")],
66
- ["codex", emptySummary("codex")],
67
- ]);
56
+ async function visitUploads(files, o, visit) {
68
57
  const groups = new Map();
69
58
  let total = 0;
70
59
  for (const f of files.slice(0, MAX_UPLOAD_FILES)) {
71
60
  if (!f.name.endsWith(".jsonl")) {
72
- warnings.push(`${f.name}: not a .jsonl session file; skipped`);
61
+ o.warnings.push(`${f.name}: not a .jsonl session file; skipped`);
73
62
  continue;
74
63
  }
75
64
  if (f.size > MAX_UPLOAD_FILE_BYTES || total + f.size > MAX_UPLOAD_TOTAL_BYTES) {
76
- warnings.push(`${f.name}: too large to import in the browser; use \`npx @codetelemetry/connect import\``);
65
+ o.warnings.push(`${f.name}: too large to read in the browser; use \`npx @codetelemetry/connect import\``);
77
66
  continue;
78
67
  }
79
68
  total += f.size;
80
69
  const head = await (f.slice ? f.slice(0, 256 * 1024).text() : f.text().then((t) => t.slice(0, 256 * 1024)));
81
70
  const kind = classify(f.name, head);
82
71
  if (!kind) {
83
- warnings.push(`${f.name}: not a Claude Code transcript or Codex rollout; skipped`);
72
+ o.warnings.push(`${f.name}: not a Claude Code transcript or Codex rollout; skipped`);
84
73
  continue;
85
74
  }
86
75
  const id = `${kind.source}:${kind.sessionId}`;
87
76
  const g = groups.get(id) ?? { ...kind, files: [] };
88
77
  g.files.push(f);
89
78
  groups.set(id, g);
90
- summaries.get(kind.source).filesFound++;
79
+ visit.found(kind.source);
91
80
  }
92
81
  if (files.length > MAX_UPLOAD_FILES)
93
- warnings.push(`only the first ${MAX_UPLOAD_FILES} files were read`);
94
- const prepareOpts = {
95
- sinceMs: window.sinceMs,
96
- untilMs: window.untilMs,
97
- caseInsensitivePaths: false,
98
- content,
99
- sha256Hex: sha256HexWeb,
100
- };
101
- const prepared = [];
82
+ o.warnings.push(`only the first ${MAX_UPLOAD_FILES} files were read`);
102
83
  for (const g of groups.values()) {
103
- const s = summaries.get(g.source);
104
84
  const mtime = Math.max(...g.files.map((f) => f.lastModified));
105
- if (mtime < window.sinceMs) {
106
- bump(s, "older");
85
+ if (mtime < o.sinceMs) {
86
+ visit.skip(g.source, "older");
107
87
  continue;
108
88
  }
109
- if (mtime > now - ACTIVE_GRACE_MS) {
110
- bump(s, "active");
89
+ if (mtime > o.now - ACTIVE_GRACE_MS) {
90
+ visit.skip(g.source, "active");
111
91
  continue;
112
92
  }
113
- const session = await parseGroup(g, content[g.source]);
93
+ const session = await parseGroup(g, o.keep(g.source));
114
94
  if (session === "too_many_events") {
115
- bump(s, "too_many_events");
95
+ visit.skip(g.source, "too_many_events");
116
96
  continue;
117
97
  }
118
98
  if (!session) {
119
- bump(s, "empty");
120
- continue;
121
- }
122
- s.sessionsParsed++;
123
- const reload = async () => {
124
- const again = await parseGroup(g, content[g.source]);
125
- return again === "too_many_events" ? null : again;
126
- };
127
- const p = await prepareSession(session, session.fileSig, reload, prepareOpts);
128
- if (typeof p === "string") {
129
- bump(s, p);
99
+ visit.skip(g.source, "empty");
130
100
  continue;
131
101
  }
132
- s.candidates++;
133
- prepared.push(p);
102
+ await visit.session(session, g);
134
103
  }
104
+ }
105
+ export async function importFiles(files, opts) {
106
+ const key = opts.key.trim();
107
+ if (!looksLikeBrowserKey(key))
108
+ throw new Error("not a CodeTelemetry ingest key (expected cot_…)");
109
+ const now = opts.nowMs ?? Date.now();
110
+ const content = contentOrDefault(opts.content);
111
+ const warnings = [];
112
+ const window = resolveWindow(now, opts.sinceMs);
113
+ if (window.warning)
114
+ warnings.push(window.warning);
115
+ const summaries = new Map([
116
+ ["claude-code", emptySummary("claude-code")],
117
+ ["codex", emptySummary("codex")],
118
+ ]);
119
+ const email = opts.identity?.email?.trim();
120
+ const identity = email ? { "claude-code": { "user.email": email }, codex: { "user.email": email } } : undefined;
121
+ const prepareOpts = {
122
+ sinceMs: window.sinceMs,
123
+ untilMs: window.untilMs,
124
+ caseInsensitivePaths: false,
125
+ content,
126
+ identity,
127
+ sha256Hex: sha256HexWeb,
128
+ };
129
+ const prepared = [];
130
+ await visitUploads(files, { now, sinceMs: window.sinceMs, keep: (source) => content[source], warnings }, {
131
+ found: (source) => {
132
+ summaries.get(source).filesFound++;
133
+ },
134
+ skip: (source, reason) => bump(summaries.get(source), reason),
135
+ session: async (session, g) => {
136
+ const s = summaries.get(g.source);
137
+ s.sessionsParsed++;
138
+ const reload = async () => {
139
+ const again = await parseGroup(g, content[g.source]);
140
+ return again === "too_many_events" ? null : again;
141
+ };
142
+ const p = await prepareSession(session, session.fileSig, reload, prepareOpts);
143
+ if (typeof p === "string") {
144
+ bump(s, p);
145
+ return;
146
+ }
147
+ s.candidates++;
148
+ prepared.push(p);
149
+ },
150
+ });
135
151
  const keyHash = await sha256HexWeb(key);
136
152
  return importPrepared(prepared, {
137
153
  ...prepareOpts,
@@ -155,3 +171,23 @@ export async function importFiles(files, opts) {
155
171
  logger: opts.logger,
156
172
  });
157
173
  }
174
+ export async function estimateFiles(files, opts = {}) {
175
+ const now = opts.nowMs ?? Date.now();
176
+ const window = estimateWindow(now, opts.sinceMs);
177
+ const builder = new EstimateBuilder({ sinceMs: window.sinceMs, untilMs: window.untilMs, nowMs: now, sources: ["claude-code", "codex"] });
178
+ const warnings = [];
179
+ if (window.warning)
180
+ warnings.push(window.warning);
181
+ await visitUploads(files, { now, sinceMs: window.sinceMs, keep: () => NO_CONTENT, warnings }, {
182
+ found: (source) => builder.found(source),
183
+ skip: (source, reason) => builder.skip(source, reason),
184
+ session: async (session) => {
185
+ const outcome = builder.add(session);
186
+ if (outcome !== "added")
187
+ builder.skip(session.source, outcome);
188
+ },
189
+ });
190
+ for (const w of warnings)
191
+ builder.warn(w);
192
+ return builder.finish({ claudeCleanupPeriodDays: null });
193
+ }
@@ -1,4 +1,4 @@
1
- import type { ContentPolicy, ImportLog, ImportMetric, ImportedSession } from "./model.ts";
1
+ import type { ContentPolicy, ImportIdentity, ImportLog, ImportMetric, ImportedSession } from "./model.ts";
2
2
  export declare const CLAUDE_SERVICE = "claude-code";
3
3
  export declare const CODEX_SERVICE = "codex-cli";
4
4
  export declare const TOKEN_USAGE_METRIC = "claude_code.token.usage";
@@ -11,10 +11,10 @@ export type ConvertedSession = {
11
11
  logs: ImportLog[];
12
12
  metrics: ImportMetric[];
13
13
  };
14
- export declare function convertSession(session: ImportedSession, content: ContentPolicy): ConvertedSession;
14
+ export declare function convertSession(session: ImportedSession, content: ContentPolicy, identity?: ImportIdentity): ConvertedSession;
15
15
  export declare function completionMarker(session: ImportedSession, plan: {
16
16
  id: string;
17
17
  logParts: number;
18
18
  metricParts: number;
19
19
  events: number;
20
- }): ImportLog;
20
+ }, identity?: ImportIdentity): ImportLog;
@@ -1,4 +1,4 @@
1
- import { toNano } from "./model.js";
1
+ import { callTokens, toNano } from "./model.js";
2
2
  export const CLAUDE_SERVICE = "claude-code";
3
3
  export const CODEX_SERVICE = "codex-cli";
4
4
  export const TOKEN_USAGE_METRIC = "claude_code.token.usage";
@@ -147,19 +147,30 @@ function convertCodex(session, content) {
147
147
  }
148
148
  return { logs: finishLogs(staged), metrics: [] };
149
149
  }
150
- export function convertSession(session, content) {
151
- return session.source === "claude-code" ? convertClaude(session, content) : convertCodex(session, content);
150
+ export function convertSession(session, content, identity) {
151
+ const converted = session.source === "claude-code" ? convertClaude(session, content) : convertCodex(session, content);
152
+ return identity && Object.keys(identity).length ? stampIdentity(converted, identity) : converted;
152
153
  }
153
- export function completionMarker(session, plan) {
154
+ function stampIdentity(converted, identity) {
155
+ return {
156
+ logs: converted.logs.map((l) => ({ ...l, attributes: { ...identity, ...l.attributes } })),
157
+ metrics: converted.metrics.map((m) => ({ ...m, attributes: { ...identity, ...m.attributes } })),
158
+ };
159
+ }
160
+ export function completionMarker(session, plan, identity) {
161
+ const tokens = session.modelCalls.reduce((n, c) => n + callTokens(c), 0);
154
162
  return {
155
163
  timeUnixNano: toNano(session.endMs),
156
164
  attributes: {
165
+ ...(identity ?? {}),
157
166
  "event.name": IMPORT_COMPLETE_EVENT,
158
167
  "session.id": session.sessionId,
159
168
  "import.plan": plan.id,
160
169
  "import.log_parts": plan.logParts,
161
170
  "import.metric_parts": plan.metricParts,
162
171
  "import.events": plan.events,
172
+ "import.session_start_ms": String(Math.floor(session.startMs)),
173
+ "import.tokens": String(tokens),
163
174
  },
164
175
  };
165
176
  }
@@ -1,6 +1,7 @@
1
- import type { ContentPolicy, ImportAttributes, ImportLog, ImportMetric, ImportSource, ImportedSession } from "./model.ts";
1
+ import type { ContentPolicy, IdentityBySource, ImportAttributes, ImportIdentity, ImportLog, ImportMetric, ImportSource, ImportedSession, MonthBucket } from "./model.ts";
2
2
  import type { JournalEvent, LedgerEntry } from "./ledger.ts";
3
3
  import { type SkipReason } from "./protocol.ts";
4
+ import { type ImportBilling } from "./transport.ts";
4
5
  import type { FetchLike } from "../otlp.ts";
5
6
  export declare const RETENTION_DAYS = 365;
6
7
  export declare const RETENTION_MARGIN_DAYS = 1;
@@ -13,7 +14,7 @@ export declare const DEFAULT_TIME_LIMIT_MS: number;
13
14
  export declare const DAY_MS = 86400000;
14
15
  export type ContentBySource = Record<ImportSource, ContentPolicy>;
15
16
  export type ImportTool = "connect-cli" | "mcp" | "web-upload";
16
- export type SkipCounts = Partial<Record<SkipReason | "older" | "newer" | "active" | "filtered" | "ledger" | "empty" | "too_large" | "too_many_events" | "unreadable" | "changed_during_run" | "deferred", number>>;
17
+ export type SkipCounts = Partial<Record<SkipReason | "older" | "newer" | "active" | "filtered" | "ledger" | "empty" | "too_large" | "too_many_events" | "unreadable" | "changed_during_run" | "deferred" | "budget", number>>;
17
18
  export type ImportSourceSummary = {
18
19
  source: ImportSource;
19
20
  filesFound: number;
@@ -30,6 +31,14 @@ export type ImportSourceSummary = {
30
31
  cacheRead: number;
31
32
  cacheCreation: number;
32
33
  };
34
+ months: MonthBucket[];
35
+ firstEventMs: number | null;
36
+ lastEventMs: number | null;
37
+ };
38
+ export type ImportRunBilling = ImportBilling & {
39
+ estimatedTokens: number;
40
+ estimatedCostUsd: number;
41
+ affordable: boolean;
33
42
  };
34
43
  export type StopReason = "budget" | "auth" | "busy" | "time_limit" | "status_unavailable";
35
44
  export type ImportRunResult = {
@@ -63,6 +72,8 @@ export type ImportRunResult = {
63
72
  remaining: number;
64
73
  stoppedBy: StopReason | null;
65
74
  topup?: string | null;
75
+ billing?: ImportRunBilling;
76
+ identity?: Partial<Record<ImportSource, Record<string, string>>>;
66
77
  cleanup: Array<{
67
78
  source: ImportSource;
68
79
  sessionId: string;
@@ -98,6 +109,7 @@ export type Prepared = {
98
109
  metricPoints: number;
99
110
  };
100
111
  tokens: ImportSourceSummary["tokens"];
112
+ monthTokens: Record<string, number>;
101
113
  warnings: string[];
102
114
  reload: () => Promise<ImportedSession | null>;
103
115
  };
@@ -111,9 +123,11 @@ export declare function resolveWindow(now: number, sinceMs?: number, untilMs?: n
111
123
  clamped: boolean;
112
124
  warning?: string;
113
125
  };
114
- export declare function buildPlan(session: ImportedSession, content: ContentPolicy, email: string | undefined, sha256Hex: Sha256Hex): Promise<{
126
+ export declare function identityFor(source: ImportSource, identity: IdentityBySource | undefined, email: string | undefined): ImportIdentity;
127
+ export declare function buildPlan(session: ImportedSession, content: ContentPolicy, email: string | undefined, sha256Hex: Sha256Hex, identity?: IdentityBySource): Promise<{
115
128
  plan: Plan;
116
129
  stable: ImportAttributes;
130
+ identity: ImportIdentity;
117
131
  }>;
118
132
  export type PrepareOptions = {
119
133
  sinceMs: number;
@@ -122,6 +136,7 @@ export type PrepareOptions = {
122
136
  caseInsensitivePaths: boolean;
123
137
  content: ContentBySource;
124
138
  email?: string;
139
+ identity?: IdentityBySource;
125
140
  sha256Hex: Sha256Hex;
126
141
  };
127
142
  export declare function prepareSession(session: ImportedSession, fileSig: string, reload: () => Promise<ImportedSession | null>, opts: PrepareOptions): Promise<Prepared | keyof SkipCounts>;
@@ -148,4 +163,9 @@ export type ImportPreparedOptions = PrepareOptions & {
148
163
  logger?: (msg: string) => void;
149
164
  };
150
165
  export declare function importPrepared(prepared: Prepared[], o: ImportPreparedOptions): Promise<ImportRunResult>;
166
+ export declare const roundUsd: (amount: number) => number;
167
+ export declare function importCostUsd(tokens: number, billing: ImportBilling): number;
168
+ export declare function maskedIdentity(sources: ImportSource[], identity: IdentityBySource | undefined, email: string | undefined): {
169
+ identity?: Partial<Record<ImportSource, Record<string, string>>>;
170
+ };
151
171
  export declare const contentOrDefault: (c: Partial<ContentBySource> | undefined) => ContentBySource;