@codetelemetry/connect 0.3.2 → 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.
@@ -4,6 +4,133 @@ export const MAX_EVENTS_PER_SESSION = 200_000;
4
4
  export const MAX_PROMPT_CHARS = 64_000;
5
5
  export const MAX_TOOL_INPUT_CHARS = 16_000;
6
6
  export const capText = (s, n) => (s.length > n ? s.slice(0, n) : s);
7
+ export const TOOL_INPUT_KEEP_KEYS = new Set(["file_path", "notebook_path", "command", "path"]);
8
+ const TRUNCATION_MARK = "…";
9
+ const prefix = (s, n) => {
10
+ if (s.length <= n)
11
+ return s;
12
+ let end = Math.max(0, n);
13
+ if (end > 0 && end < s.length) {
14
+ const code = s.charCodeAt(end - 1);
15
+ if (code >= 0xd800 && code <= 0xdbff)
16
+ end--;
17
+ }
18
+ return s.slice(0, end);
19
+ };
20
+ function shortenStrings(value, cap, keepKeys, key) {
21
+ if (typeof value === "string") {
22
+ if (keepKeys && key !== undefined && TOOL_INPUT_KEEP_KEYS.has(key))
23
+ return value;
24
+ return value.length > cap ? prefix(value, cap) + TRUNCATION_MARK : value;
25
+ }
26
+ if (Array.isArray(value))
27
+ return value.map((v) => shortenStrings(v, cap, keepKeys));
28
+ if (value && typeof value === "object") {
29
+ const out = {};
30
+ for (const [k, v] of Object.entries(value))
31
+ out[k] = shortenStrings(v, cap, keepKeys, k);
32
+ return out;
33
+ }
34
+ return value;
35
+ }
36
+ const jsonLength = (value) => {
37
+ try {
38
+ return JSON.stringify(value)?.length ?? 0;
39
+ }
40
+ catch {
41
+ return Infinity;
42
+ }
43
+ };
44
+ function fitStrings(value, max, keepKeys) {
45
+ let hi = max;
46
+ if (jsonLength(shortenStrings(value, hi, keepKeys)) <= max)
47
+ return JSON.stringify(shortenStrings(value, hi, keepKeys));
48
+ let lo = 0;
49
+ if (jsonLength(shortenStrings(value, lo, keepKeys)) > max)
50
+ return null;
51
+ while (hi - lo > 1) {
52
+ const mid = (lo + hi) >>> 1;
53
+ if (jsonLength(shortenStrings(value, mid, keepKeys)) <= max)
54
+ lo = mid;
55
+ else
56
+ hi = mid;
57
+ }
58
+ return JSON.stringify(shortenStrings(value, lo, keepKeys));
59
+ }
60
+ export function capToolInput(value, full, max) {
61
+ if (full.length <= max)
62
+ return full;
63
+ if (value === null || typeof value !== "object") {
64
+ if (typeof value === "string") {
65
+ const fitted = fitStrings(value, max, false);
66
+ if (fitted !== null)
67
+ return fitted;
68
+ }
69
+ return JSON.stringify({ truncated: true });
70
+ }
71
+ const kept = fitStrings(value, max, true) ?? fitStrings(value, max, false);
72
+ if (kept !== null)
73
+ return kept;
74
+ const summary = { truncated: true };
75
+ if (!Array.isArray(value)) {
76
+ for (const [k, v] of Object.entries(value)) {
77
+ if (TOOL_INPUT_KEEP_KEYS.has(k) && typeof v === "string")
78
+ summary[k] = v;
79
+ }
80
+ }
81
+ return fitStrings(summary, max, false) ?? JSON.stringify({ truncated: true });
82
+ }
83
+ export function maskEmail(email) {
84
+ const at = email.lastIndexOf("@");
85
+ if (at <= 0)
86
+ return email ? `${email[0]}***` : "";
87
+ const local = email.slice(0, at);
88
+ const domain = email.slice(at + 1);
89
+ const dot = domain.lastIndexOf(".");
90
+ const host = dot > 0 ? domain.slice(0, dot) : domain;
91
+ const tld = dot > 0 ? domain.slice(dot) : "";
92
+ return `${local[0]}***@${host ? host[0] : ""}***${tld}`;
93
+ }
94
+ export function maskIdentity(identity) {
95
+ const out = {};
96
+ for (const [source, attrs] of Object.entries(identity)) {
97
+ if (!attrs || Object.keys(attrs).length === 0)
98
+ continue;
99
+ const masked = {};
100
+ for (const [k, v] of Object.entries(attrs))
101
+ masked[k] = k === "user.email" ? maskEmail(v) : v.length > 8 ? `${v.slice(0, 6)}…` : "…";
102
+ out[source] = masked;
103
+ }
104
+ return out;
105
+ }
106
+ export const MONTH_OF = (ms) => new Date(ms).toISOString().slice(0, 7);
107
+ export const DAY_OF = (ms) => new Date(ms).toISOString().slice(0, 10);
108
+ export const callTokens = (c) => c.inputTokens + c.outputTokens + c.cacheReadTokens + c.cacheCreationTokens;
109
+ export function tokensByMonth(session) {
110
+ const out = {};
111
+ for (const c of session.modelCalls) {
112
+ const n = callTokens(c);
113
+ if (n <= 0)
114
+ continue;
115
+ const m = MONTH_OF(c.tsMs);
116
+ out[m] = (out[m] ?? 0) + n;
117
+ }
118
+ return out;
119
+ }
120
+ export function addToMonths(months, startMs, monthTokens) {
121
+ const bucket = (month) => {
122
+ let b = months.find((x) => x.month === month);
123
+ if (!b) {
124
+ b = { month, sessions: 0, tokens: 0 };
125
+ months.push(b);
126
+ months.sort((x, y) => (x.month < y.month ? -1 : x.month > y.month ? 1 : 0));
127
+ }
128
+ return b;
129
+ };
130
+ bucket(MONTH_OF(startMs)).sessions++;
131
+ for (const [month, tokens] of Object.entries(monthTokens))
132
+ bucket(month).tokens += tokens;
133
+ }
7
134
  export function toNano(ms) {
8
135
  return (BigInt(Math.floor(ms)) * 1000000n).toString();
9
136
  }
@@ -1,7 +1,9 @@
1
1
  import type { FetchLike } from "../otlp.ts";
2
- import type { ImportSource } from "./model.ts";
2
+ import type { IdentityBySource, ImportSource } from "./model.ts";
3
3
  import { type ContentBySource, type ImportRunResult, type ImportTool } from "./core.ts";
4
- export { RETENTION_DAYS, DEFAULT_SINCE_DAYS, ACTIVE_GRACE_MS, IMPORT_VERSION, DEFAULT_RATE_PER_MINUTE, MAX_RATE_PER_MINUTE, DEFAULT_TIME_LIMIT_MS, type ContentBySource, type ImportRunResult, type ImportSourceSummary, type SkipCounts, type StopReason, } from "./core.ts";
4
+ import { type HistoryEstimate } from "./estimate.ts";
5
+ export { RETENTION_DAYS, DEFAULT_SINCE_DAYS, ACTIVE_GRACE_MS, IMPORT_VERSION, DEFAULT_RATE_PER_MINUTE, MAX_RATE_PER_MINUTE, DEFAULT_TIME_LIMIT_MS, type ContentBySource, type ImportRunResult, type ImportSourceSummary, type SkipCounts, type StopReason, type ImportRunBilling, } from "./core.ts";
6
+ export type { HistoryEstimate, HistoryEstimateSource, MonthBucket } from "./estimate.ts";
5
7
  export type ImportRunOptions = {
6
8
  key: string;
7
9
  endpoints?: Partial<{
@@ -13,6 +15,7 @@ export type ImportRunOptions = {
13
15
  untilMs?: number;
14
16
  project?: string;
15
17
  email?: string;
18
+ identity?: IdentityBySource;
16
19
  content?: Partial<ContentBySource>;
17
20
  dryRun?: boolean;
18
21
  previewOnly?: boolean;
@@ -31,3 +34,13 @@ export type ImportRunOptions = {
31
34
  logger?: (msg: string) => void;
32
35
  };
33
36
  export declare function runImport(opts: ImportRunOptions): Promise<ImportRunResult>;
37
+ export type EstimateRunOptions = {
38
+ source?: ImportSource | "all";
39
+ sinceMs?: number;
40
+ nowMs?: number;
41
+ claudeDir?: string;
42
+ codexDir?: string;
43
+ claudeSettingsPath?: string;
44
+ timeLimitMs?: number;
45
+ };
46
+ export declare function runEstimate(opts?: EstimateRunOptions): Promise<HistoryEstimate>;
@@ -1,10 +1,11 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { assertKey, keyHash, mask } from "../keys.js";
3
3
  import { resolveEndpoints } from "../config.js";
4
- import { sessionKeyOf } from "./model.js";
4
+ import { NO_CONTENT, sessionKeyOf } from "./model.js";
5
5
  import { ACTIVE_GRACE_MS, bump, contentOrDefault, emptySummary, importPrepared, prepareSession, resolveWindow, underProject, } from "./core.js";
6
- import { defaultClaudeProjectsDir, defaultCodexSessionsDir, parseCandidate, candidateProjectDirectory, scanClaudeSessions, scanCodexSessions, } from "./sources/files.js";
6
+ import { HistoryReadBudgetError, MAX_SESSION_FILE_BYTES, defaultClaudeProjectsDir, defaultClaudeSettingsPath, defaultCodexSessionsDir, readClaudeCleanupPeriodDays, parseCandidate, candidateProjectDirectory, scanClaudeSessions, scanCodexSessions, } from "./sources/files.js";
7
7
  import { LedgerStore, resolveLedgerPath } from "./ledger.js";
8
+ import { EstimateBuilder, estimateWindow } from "./estimate.js";
8
9
  export { RETENTION_DAYS, DEFAULT_SINCE_DAYS, ACTIVE_GRACE_MS, IMPORT_VERSION, DEFAULT_RATE_PER_MINUTE, MAX_RATE_PER_MINUTE, DEFAULT_TIME_LIMIT_MS, } from "./core.js";
9
10
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
10
11
  export async function runImport(opts) {
@@ -53,6 +54,7 @@ export async function runImport(opts) {
53
54
  caseInsensitivePaths: process.platform === "win32" || process.platform === "darwin",
54
55
  content,
55
56
  email: opts.email,
57
+ identity: opts.identity,
56
58
  sha256Hex,
57
59
  };
58
60
  for (const c of found) {
@@ -155,3 +157,79 @@ export async function runImport(opts) {
155
157
  ledger.compact();
156
158
  }
157
159
  }
160
+ export async function runEstimate(opts = {}) {
161
+ const now = opts.nowMs ?? Date.now();
162
+ const window = estimateWindow(now, opts.sinceMs);
163
+ const wantClaude = !opts.source || opts.source === "all" || opts.source === "claude-code";
164
+ const wantCodex = !opts.source || opts.source === "all" || opts.source === "codex";
165
+ const sources = [...(wantClaude ? ["claude-code"] : []), ...(wantCodex ? ["codex"] : [])];
166
+ const builder = new EstimateBuilder({ sinceMs: window.sinceMs, untilMs: window.untilMs, nowMs: now, sources });
167
+ if (window.warning)
168
+ builder.warn(window.warning);
169
+ const found = [];
170
+ if (wantClaude) {
171
+ const files = scanClaudeSessions(opts.claudeDir ?? defaultClaudeProjectsDir());
172
+ builder.found("claude-code", files.length);
173
+ found.push(...files);
174
+ }
175
+ if (wantCodex) {
176
+ const files = scanCodexSessions(opts.codexDir ?? defaultCodexSessionsDir());
177
+ builder.found("codex", files.length);
178
+ found.push(...files);
179
+ }
180
+ const deadline = opts.timeLimitMs ? Date.now() + opts.timeLimitMs : Infinity;
181
+ const limits = Number.isFinite(deadline) ? { deadline, maxBytes: MAX_SESSION_FILE_BYTES } : undefined;
182
+ const seen = new Set();
183
+ let timedOut = false;
184
+ for (const c of found) {
185
+ if (timedOut || Date.now() >= deadline) {
186
+ timedOut = true;
187
+ builder.skip(c.source, "time_limit");
188
+ continue;
189
+ }
190
+ if (c.mtimeMs < window.sinceMs) {
191
+ builder.skip(c.source, "older");
192
+ continue;
193
+ }
194
+ if (c.mtimeMs > now - ACTIVE_GRACE_MS) {
195
+ builder.skip(c.source, "active");
196
+ continue;
197
+ }
198
+ let parsed;
199
+ try {
200
+ parsed = await parseCandidate(c, NO_CONTENT, limits);
201
+ }
202
+ catch (err) {
203
+ if (!(err instanceof HistoryReadBudgetError))
204
+ throw err;
205
+ timedOut = true;
206
+ builder.skip(c.source, "time_limit");
207
+ continue;
208
+ }
209
+ if (!parsed.ok) {
210
+ builder.skip(c.source, parsed.reason);
211
+ builder.warn(`${c.source} ${c.file}: ${parsed.detail}; not counted`);
212
+ continue;
213
+ }
214
+ if (!parsed.session) {
215
+ builder.skip(c.source, "empty");
216
+ continue;
217
+ }
218
+ const sessionKey = sessionKeyOf(parsed.session.source, parsed.session.sessionId);
219
+ if (seen.has(sessionKey)) {
220
+ builder.warn(`${sessionKey} appears in more than one file; only the first is counted`);
221
+ continue;
222
+ }
223
+ const outcome = builder.add(parsed.session);
224
+ if (outcome !== "added") {
225
+ builder.skip(c.source, outcome);
226
+ continue;
227
+ }
228
+ seen.add(sessionKey);
229
+ }
230
+ if (timedOut)
231
+ builder.warn("The estimate reached its time bound; the totals cover only the sessions read (see skipped.time_limit).");
232
+ return builder.finish({
233
+ claudeCleanupPeriodDays: wantClaude ? readClaudeCleanupPeriodDays(opts.claudeSettingsPath ?? defaultClaudeSettingsPath()) : null,
234
+ });
235
+ }
@@ -1,4 +1,4 @@
1
- import { MAX_EVENTS_PER_SESSION, MAX_PROMPT_CHARS, MAX_TOOL_INPUT_CHARS, NO_CONTENT, capText } from "../model.js";
1
+ import { MAX_EVENTS_PER_SESSION, MAX_PROMPT_CHARS, MAX_TOOL_INPUT_CHARS, NO_CONTENT, capText, capToolInput } from "../model.js";
2
2
  const textOfBlocks = (content) => {
3
3
  if (typeof content === "string")
4
4
  return content;
@@ -130,7 +130,7 @@ export class ClaudeSessionAccumulator {
130
130
  }
131
131
  this.#pending.set(block.id, {
132
132
  name: String(block.name ?? "unknown"),
133
- input: this.#keep.toolDetails && full ? capText(full, MAX_TOOL_INPUT_CHARS) : null,
133
+ input: this.#keep.toolDetails && full ? capToolInput(block.input, full, MAX_TOOL_INPUT_CHARS) : null,
134
134
  inputBytes: full.length,
135
135
  });
136
136
  }
@@ -1,4 +1,5 @@
1
- import { MAX_EVENTS_PER_SESSION, MAX_PROMPT_CHARS, MAX_TOOL_INPUT_CHARS, NO_CONTENT, capText } from "../model.js";
1
+ import { githubOrigin } from "../../repositoryOrigin.js";
2
+ import { MAX_EVENTS_PER_SESSION, MAX_PROMPT_CHARS, MAX_TOOL_INPUT_CHARS, NO_CONTENT, capText, capToolInput } from "../model.js";
2
3
  const count = (value) => Math.max(0, Math.trunc(Number(value) || 0));
3
4
  const usageOf = (u) => {
4
5
  if (!u || typeof u !== "object")
@@ -36,6 +37,20 @@ const userMessageText = (item) => {
36
37
  .map((c) => c.text)
37
38
  .join("\n");
38
39
  };
40
+ const codexToolInput = (raw, full) => {
41
+ if (full.length <= MAX_TOOL_INPUT_CHARS)
42
+ return full;
43
+ if (typeof raw !== "string")
44
+ return capToolInput(raw, full, MAX_TOOL_INPUT_CHARS);
45
+ if (!/^\s*[[{]/.test(raw))
46
+ return capText(full, MAX_TOOL_INPUT_CHARS);
47
+ try {
48
+ return capToolInput(JSON.parse(raw), full, MAX_TOOL_INPUT_CHARS);
49
+ }
50
+ catch {
51
+ return capText(full, MAX_TOOL_INPUT_CHARS);
52
+ }
53
+ };
39
54
  export class CodexSessionAccumulator {
40
55
  #keep;
41
56
  #prompts = [];
@@ -46,6 +61,8 @@ export class CodexSessionAccumulator {
46
61
  #verdicts = new Map();
47
62
  #warnings = new Set();
48
63
  #sessionId = "";
64
+ #repositoryUrl;
65
+ #parentThreadId;
49
66
  #cwd = null;
50
67
  #model = "";
51
68
  #prevTotal = null;
@@ -83,6 +100,11 @@ export class CodexSessionAccumulator {
83
100
  this.#sessionId = p.id;
84
101
  else if (typeof p.session_id === "string" && p.session_id)
85
102
  this.#sessionId = p.session_id;
103
+ if (this.#sessionId) {
104
+ this.#repositoryUrl = githubOrigin(p.git?.repository_url);
105
+ if (typeof p.parent_thread_id === "string" && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(p.parent_thread_id) && p.parent_thread_id !== this.#sessionId)
106
+ this.#parentThreadId = p.parent_thread_id;
107
+ }
86
108
  }
87
109
  if (!this.#cwd && typeof p.cwd === "string" && p.cwd)
88
110
  this.#cwd = p.cwd;
@@ -161,7 +183,7 @@ export class CodexSessionAccumulator {
161
183
  }
162
184
  this.#pending.set(callId, {
163
185
  name: String(p.name ?? (p.type === "local_shell_call" ? "shell" : "unknown")),
164
- input: this.#keep.toolDetails && full ? capText(full, MAX_TOOL_INPUT_CHARS) : null,
186
+ input: this.#keep.toolDetails && full ? codexToolInput(rawInput, full) : null,
165
187
  inputBytes: full.length,
166
188
  });
167
189
  return;
@@ -280,6 +302,8 @@ export class CodexSessionAccumulator {
280
302
  if (e.tsMs > endMs)
281
303
  endMs = e.tsMs;
282
304
  }
305
+ const matchesRollout = !!this.#sessionId && meta.files.length > 0 &&
306
+ meta.files.every(file => codexSessionIdFromName(file) === this.#sessionId);
283
307
  const warnings = [...this.#warnings];
284
308
  if (this.#pending.size > 0)
285
309
  warnings.push(`${this.#pending.size} tool call(s) without a recorded output (not imported)`);
@@ -289,6 +313,8 @@ export class CodexSessionAccumulator {
289
313
  files: meta.files,
290
314
  fileSig: meta.fileSig,
291
315
  cwd: this.#cwd,
316
+ ...(matchesRollout && this.#repositoryUrl ? { repositoryUrl: this.#repositoryUrl } : {}),
317
+ ...(matchesRollout && this.#parentThreadId ? { parentThreadId: this.#parentThreadId } : {}),
292
318
  startMs,
293
319
  endMs,
294
320
  prompts,
@@ -9,7 +9,11 @@ export type SessionCandidate = {
9
9
  bytes: number;
10
10
  fileSig: string;
11
11
  };
12
- export declare function defaultClaudeProjectsDir(home?: string): string;
12
+ export declare function claudeConfigDir(home?: string, env?: NodeJS.ProcessEnv): string;
13
+ export declare function defaultClaudeProjectsDir(home?: string, env?: NodeJS.ProcessEnv): string;
14
+ export declare function defaultClaudeSettingsPath(env?: NodeJS.ProcessEnv, home?: string): string;
15
+ export declare const CLAUDE_CLEANUP_DEFAULT_DAYS = 30;
16
+ export declare function readClaudeCleanupPeriodDays(settingsPath?: string): number;
13
17
  export declare function defaultCodexSessionsDir(home?: string, env?: NodeJS.ProcessEnv): string;
14
18
  export type ScanBudget = {
15
19
  remainingEntries: number;
@@ -7,8 +7,29 @@ import { ClaudeSessionAccumulator } from "./claudeCodeText.js";
7
7
  import { CodexSessionAccumulator, codexSessionIdFromName } from "./codexText.js";
8
8
  export const MAX_SESSION_FILE_BYTES = 512 * 1024 * 1024;
9
9
  export const MAX_SUBAGENT_FILES = 2_000;
10
- export function defaultClaudeProjectsDir(home) {
11
- return path.join(home ?? os.homedir(), ".claude", "projects");
10
+ export function claudeConfigDir(home, env = process.env) {
11
+ if (!home && env.CLAUDE_CONFIG_DIR)
12
+ return env.CLAUDE_CONFIG_DIR;
13
+ return path.join(home ?? os.homedir(), ".claude");
14
+ }
15
+ export function defaultClaudeProjectsDir(home, env = process.env) {
16
+ return path.join(claudeConfigDir(home, env), "projects");
17
+ }
18
+ export function defaultClaudeSettingsPath(env = process.env, home) {
19
+ return path.join(claudeConfigDir(home, env), "settings.json");
20
+ }
21
+ export const CLAUDE_CLEANUP_DEFAULT_DAYS = 30;
22
+ export function readClaudeCleanupPeriodDays(settingsPath = defaultClaudeSettingsPath()) {
23
+ try {
24
+ const st = fs.statSync(settingsPath);
25
+ if (!st.isFile() || st.size > 1024 * 1024)
26
+ return CLAUDE_CLEANUP_DEFAULT_DAYS;
27
+ const v = JSON.parse(fs.readFileSync(settingsPath, "utf8"))?.cleanupPeriodDays;
28
+ return typeof v === "number" && Number.isInteger(v) && v >= 1 ? v : CLAUDE_CLEANUP_DEFAULT_DAYS;
29
+ }
30
+ catch {
31
+ return CLAUDE_CLEANUP_DEFAULT_DAYS;
32
+ }
12
33
  }
13
34
  export function defaultCodexSessionsDir(home, env = process.env) {
14
35
  if (!home && env.CODEX_HOME)
@@ -41,6 +41,15 @@ export type StatusRequestSession = {
41
41
  endMs: number;
42
42
  probePlan?: string;
43
43
  };
44
+ export type ImportBilling = {
45
+ importsBilled: boolean;
46
+ tokenPriceUsdPerMillion: number;
47
+ includedTokensRemaining: number;
48
+ creditUsd: number;
49
+ unlimited: boolean;
50
+ };
51
+ export declare const UNLIMITED_TOKENS = 1000000000000000;
52
+ export declare function parseImportBilling(raw: unknown): ImportBilling | undefined;
44
53
  export type StatusResponse = {
45
54
  sessions: Array<{
46
55
  sessionId: string;
@@ -55,6 +64,7 @@ export type StatusResponse = {
55
64
  }>;
56
65
  settleMs: number;
57
66
  nowMs: number;
67
+ billing?: ImportBilling;
58
68
  };
59
69
  export type StatusOutcome = {
60
70
  kind: "ok";
@@ -86,6 +86,30 @@ export async function postOtlp(opts) {
86
86
  return { kind: "busy", detail: lastDetail };
87
87
  return opts.retryAmbiguous ? { kind: "rejected", status: 0, message: lastDetail } : { kind: "uncertain", detail: lastDetail };
88
88
  }
89
+ export const UNLIMITED_TOKENS = 1e15;
90
+ const finite = (v) => typeof v === "number" && Number.isFinite(v);
91
+ export function parseImportBilling(raw) {
92
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
93
+ return undefined;
94
+ const b = raw;
95
+ if (typeof b.importsBilled !== "boolean")
96
+ return undefined;
97
+ if (!finite(b.tokenPriceUsdPerMillion) || b.tokenPriceUsdPerMillion < 0)
98
+ return undefined;
99
+ if (!finite(b.includedTokensRemaining) || b.includedTokensRemaining < 0)
100
+ return undefined;
101
+ if (!finite(b.creditUsd))
102
+ return undefined;
103
+ if (b.unlimited !== undefined && typeof b.unlimited !== "boolean")
104
+ return undefined;
105
+ return {
106
+ importsBilled: b.importsBilled,
107
+ tokenPriceUsdPerMillion: b.tokenPriceUsdPerMillion,
108
+ includedTokensRemaining: b.includedTokensRemaining,
109
+ creditUsd: b.creditUsd,
110
+ unlimited: typeof b.unlimited === "boolean" ? b.unlimited : b.includedTokensRemaining >= UNLIMITED_TOKENS,
111
+ };
112
+ }
89
113
  export async function fetchStatus(opts) {
90
114
  let detail = "";
91
115
  for (let attempt = 1; attempt <= 5; attempt++) {
@@ -124,12 +148,14 @@ export async function fetchStatus(opts) {
124
148
  const json = (await res.json());
125
149
  if (!Array.isArray(json.sessions))
126
150
  return { kind: "unavailable", detail: "malformed status response" };
151
+ const billing = parseImportBilling(json.billing);
127
152
  return {
128
153
  kind: "ok",
129
154
  value: {
130
155
  sessions: json.sessions,
131
156
  settleMs: typeof json.settleMs === "number" ? json.settleMs : 300_000,
132
157
  nowMs: typeof json.nowMs === "number" ? json.nowMs : Date.now(),
158
+ ...(billing ? { billing } : {}),
133
159
  },
134
160
  };
135
161
  }
package/dist/index.d.ts CHANGED
@@ -13,7 +13,9 @@ export { ONBOARD_CLIENTS, SESSION_FILTER_ASSISTANTS, isOnboardClient, } from "./
13
13
  export { buildHostMetricsConfig, renderHostMetricsConfig, writeHostMetricsConfig, hostMetricsOptionsFromFlags, defaultHostMetricsPaths, defaultInstanceId, HOST_METRIC_CONTRACT, REDACTED_RESOURCE_ATTRIBUTES, DEFAULT_PROCESS_NAMES, DEFAULT_KEY_ENV, DEFAULT_SERVICE_NAME, SERVICE_NAMESPACE, type HostMetricsOptions, type HostMetricsMode, type HostMetricsPaths, type HostMetricsWriteOptions, type HostMetricsWriteResult, } from "./hostMetrics.ts";
14
14
  export { resolveCodexConfigPath, buildOtelSection, writeCodexConfig, readCodexKey, readCodexSummary, readCodexLogUserPrompt, type CodexWriteOptions, } from "./codexConfig.ts";
15
15
  export { readClaudeContentFlags } from "./settings.ts";
16
- export { runImport, RETENTION_DAYS, DEFAULT_SINCE_DAYS, type ImportRunOptions, type ImportRunResult, type ImportSourceSummary, type ContentBySource, } from "./import/run.ts";
16
+ export { runImport, runEstimate, RETENTION_DAYS, DEFAULT_SINCE_DAYS, type ImportRunOptions, type ImportRunResult, type ImportRunBilling, type ImportSourceSummary, type ContentBySource, type EstimateRunOptions, type HistoryEstimate, type HistoryEstimateSource, type MonthBucket, } from "./import/run.ts";
17
+ export { ESTIMATE_DEFAULT_DAYS, IMPORT_NEVER_RECOVERS, claudeRetentionCutoffMs, fetchPricing, parsePricing, priceEstimate, type EstimateCost, type PublicPricing, } from "./import/estimate.ts";
18
+ export { resolveImportIdentity, readClaudeIdentity, readCodexIdentity, type IdentityResolveOptions } from "./import/identity.ts";
17
19
  export { resolveImportKey, resolveImportContent, parseContentFlag, parseWhen } from "./import/options.ts";
18
20
  export { NO_CONTENT, ALL_CONTENT, type ContentPolicy, type ImportSource } from "./import/model.ts";
19
21
  export { graderConfigRequest } from "./agent.ts";
package/dist/index.js CHANGED
@@ -13,7 +13,9 @@ export { ONBOARD_CLIENTS, SESSION_FILTER_ASSISTANTS, isOnboardClient, } from "./
13
13
  export { buildHostMetricsConfig, renderHostMetricsConfig, writeHostMetricsConfig, hostMetricsOptionsFromFlags, defaultHostMetricsPaths, defaultInstanceId, HOST_METRIC_CONTRACT, REDACTED_RESOURCE_ATTRIBUTES, DEFAULT_PROCESS_NAMES, DEFAULT_KEY_ENV, DEFAULT_SERVICE_NAME, SERVICE_NAMESPACE, } from "./hostMetrics.js";
14
14
  export { resolveCodexConfigPath, buildOtelSection, writeCodexConfig, readCodexKey, readCodexSummary, readCodexLogUserPrompt, } from "./codexConfig.js";
15
15
  export { readClaudeContentFlags } from "./settings.js";
16
- export { runImport, RETENTION_DAYS, DEFAULT_SINCE_DAYS, } from "./import/run.js";
16
+ export { runImport, runEstimate, RETENTION_DAYS, DEFAULT_SINCE_DAYS, } from "./import/run.js";
17
+ export { ESTIMATE_DEFAULT_DAYS, IMPORT_NEVER_RECOVERS, claudeRetentionCutoffMs, fetchPricing, parsePricing, priceEstimate, } from "./import/estimate.js";
18
+ export { resolveImportIdentity, readClaudeIdentity, readCodexIdentity } from "./import/identity.js";
17
19
  export { resolveImportKey, resolveImportContent, parseContentFlag, parseWhen } from "./import/options.js";
18
20
  export { NO_CONTENT, ALL_CONTENT } from "./import/model.js";
19
21
  export { graderConfigRequest } from "./agent.js";
@@ -1,3 +1,4 @@
1
+ import { githubOrigin } from "./repositoryOrigin.js";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  export const REPOSITORY_HOOK_MARKER = "codetelemetry-repository-observation";
@@ -146,6 +147,7 @@ function git(cwd, args) {
146
147
  }).trim(); }
147
148
  catch { return ""; }
148
149
  }
150
+ const githubOrigin = ${githubOrigin.toString()};
149
151
  const repositoryRemoteIdentity = ${normalizeRepositoryRemote.toString()};
150
152
  const selectCodexOtelExporterLine = ${selectCodexOtelExporterLine.toString()};
151
153
  function remoteName(value) {
@@ -384,7 +386,9 @@ async function main() {
384
386
  if (!permitsAuthorization(url, destination.headers)) return;
385
387
  const cwd = path.resolve(String(input.new_cwd || input.cwd || process.cwd()));
386
388
  const root = git(cwd, ["rev-parse", "--show-toplevel"]) || cwd;
387
- const remote = repositoryRemoteIdentity(git(root, ["config", "--get", "remote.origin.url"]));
389
+ const rawRemote = git(root, ["config", "--get", "remote.origin.url"]);
390
+ const remote = repositoryRemoteIdentity(rawRemote);
391
+ const originUrl = githubOrigin(rawRemote);
388
392
  const initialCommit = git(root, ["rev-list", "--max-parents=0", "HEAD"]).split(/\s+/).filter(Boolean).sort()[0] || "";
389
393
  const commonDir = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
390
394
  const commonRoot = commonDir.endsWith(path.sep + ".git") ? path.dirname(commonDir) : root;
@@ -406,6 +410,7 @@ async function main() {
406
410
  attr("code.workspace.path", cwd),
407
411
  attr("hook.event", hookEvent),
408
412
  ];
413
+ if (originUrl) attributes.push(attr("vcs.repository.url.full", originUrl));
409
414
  if (sessionId) attributes.push(attr("session.id", sessionId));
410
415
  const body = JSON.stringify({ resourceLogs: [{
411
416
  resource: { attributes: [attr("service.name", "codetelemetry-connect")] },
@@ -0,0 +1 @@
1
+ export declare function githubOrigin(value: unknown): string | undefined;
@@ -0,0 +1,13 @@
1
+ export function githubOrigin(value) {
2
+ if (typeof value !== "string" || value.length > 200 || /\s/.test(value))
3
+ return;
4
+ const match = /^(?:https:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?)\/([a-z0-9._-]{1,104})\/?$/i.exec(value);
5
+ if (!match)
6
+ return;
7
+ const name = match[2].replace(/\.git$/i, "");
8
+ if (!name || name.length > 100 || name === "." || name === "..")
9
+ return;
10
+ if (/(?:cot_|gh[pousr]_|github_pat_|AKIA|ASIA|sk-|xox[baprs]-|npm_|AIza|eyJ)[a-z0-9_-]{12,}/i.test(match[1] + "/" + name))
11
+ return;
12
+ return "https://github.com/" + match[1] + "/" + name;
13
+ }
@@ -0,0 +1,29 @@
1
+ export declare function rolloutRepository(file: string): {
2
+ timeUnixNano: string;
3
+ attributes: {
4
+ "codex.parent_thread_id"?: string | undefined;
5
+ "vcs.repository.url.full"?: string | undefined;
6
+ "event.name": string;
7
+ "session.id": string;
8
+ };
9
+ } | null;
10
+ export declare function reportRolloutRepositories(files: string[], send: boolean, stateFile?: string): Promise<{
11
+ sent: number;
12
+ skipped: number;
13
+ observations: {
14
+ timeUnixNano: string;
15
+ attributes: {
16
+ "event.name": string;
17
+ "session.id": string;
18
+ "vcs.repository.url.full": string;
19
+ };
20
+ }[] | {
21
+ timeUnixNano: string;
22
+ attributes: {
23
+ "codex.parent_thread_id"?: string | undefined;
24
+ "vcs.repository.url.full"?: string | undefined;
25
+ "event.name": string;
26
+ "session.id": string;
27
+ };
28
+ }[];
29
+ }>;