@codetelemetry/mcp 0.7.0 → 0.8.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 +72 -6
- package/dist/src/client/cli.js +177 -4
- package/dist/src/client/import/browser.d.ts +8 -0
- package/dist/src/client/import/browser.js +83 -47
- package/dist/src/client/import/convert.d.ts +3 -3
- package/dist/src/client/import/convert.js +15 -4
- package/dist/src/client/import/core.d.ts +23 -3
- package/dist/src/client/import/core.js +78 -9
- package/dist/src/client/import/estimate.d.ts +87 -0
- package/dist/src/client/import/estimate.js +187 -0
- package/dist/src/client/import/identity.d.ts +25 -0
- package/dist/src/client/import/identity.js +118 -0
- package/dist/src/client/import/model.d.ts +18 -0
- package/dist/src/client/import/model.js +127 -0
- package/dist/src/client/import/run.d.ts +15 -2
- package/dist/src/client/import/run.js +80 -2
- package/dist/src/client/import/sources/claudeCodeText.js +2 -2
- package/dist/src/client/import/sources/codexText.js +28 -2
- package/dist/src/client/import/sources/files.d.ts +5 -1
- package/dist/src/client/import/sources/files.js +23 -2
- package/dist/src/client/import/transport.d.ts +10 -0
- package/dist/src/client/import/transport.js +26 -0
- package/dist/src/client/index.d.ts +3 -1
- package/dist/src/client/index.js +3 -1
- package/dist/src/client/repositoryHook.js +6 -1
- package/dist/src/client/repositoryOrigin.d.ts +1 -0
- package/dist/src/client/repositoryOrigin.js +13 -0
- package/dist/src/client/rolloutRepository.d.ts +29 -0
- package/dist/src/client/rolloutRepository.js +84 -0
- package/dist/src/client/workspaceImport.js +4 -2
- package/dist/src/client/workspaces.d.ts +1 -1
- package/dist/src/client/workspaces.js +3 -1
- package/dist/src/tools.d.ts +5 -0
- package/dist/src/tools.js +88 -8
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +9 -1
- package/tool-manifest.json +48 -6
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
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;
|
|
@@ -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
|
|
110
|
-
|
|
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 (
|
|
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;
|