@codetelemetry/mcp 0.3.9 → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +135 -9
  3. package/dist/src/client/agent.d.ts +201 -3
  4. package/dist/src/client/agent.js +154 -0
  5. package/dist/src/client/assistants.d.ts +4 -0
  6. package/dist/src/client/assistants.js +5 -0
  7. package/dist/src/client/bin.d.ts +2 -0
  8. package/dist/src/client/bin.js +3 -0
  9. package/dist/src/client/cli.d.ts +1 -0
  10. package/dist/src/client/cli.js +567 -0
  11. package/dist/src/client/clients.d.ts +34 -0
  12. package/dist/src/client/clients.js +74 -0
  13. package/dist/src/client/codexConfig.d.ts +1 -0
  14. package/dist/src/client/codexConfig.js +5 -0
  15. package/dist/src/client/config.d.ts +6 -0
  16. package/dist/src/client/config.js +6 -0
  17. package/dist/src/client/graderArtifact.d.ts +14 -0
  18. package/dist/src/client/graderArtifact.js +94 -0
  19. package/dist/src/client/graderSeed.d.ts +50 -0
  20. package/dist/src/client/graderSeed.js +289 -0
  21. package/dist/src/client/hostMetrics.d.ts +54 -0
  22. package/dist/src/client/hostMetrics.js +425 -0
  23. package/dist/src/client/import/browser.d.ts +30 -0
  24. package/dist/src/client/import/browser.js +157 -0
  25. package/dist/src/client/import/convert.d.ts +20 -0
  26. package/dist/src/client/import/convert.js +165 -0
  27. package/dist/src/client/import/core.d.ts +143 -0
  28. package/dist/src/client/import/core.js +441 -0
  29. package/dist/src/client/import/ledger.d.ts +52 -0
  30. package/dist/src/client/import/ledger.js +161 -0
  31. package/dist/src/client/import/model.d.ts +70 -0
  32. package/dist/src/client/import/model.js +42 -0
  33. package/dist/src/client/import/options.d.ts +24 -0
  34. package/dist/src/client/import/options.js +71 -0
  35. package/dist/src/client/import/otlpImport.d.ts +7 -0
  36. package/dist/src/client/import/otlpImport.js +81 -0
  37. package/dist/src/client/import/protocol.d.ts +35 -0
  38. package/dist/src/client/import/protocol.js +51 -0
  39. package/dist/src/client/import/run.d.ts +30 -0
  40. package/dist/src/client/import/run.js +127 -0
  41. package/dist/src/client/import/sources/claudeCodeText.d.ts +19 -0
  42. package/dist/src/client/import/sources/claudeCodeText.js +214 -0
  43. package/dist/src/client/import/sources/codexText.d.ts +20 -0
  44. package/dist/src/client/import/sources/codexText.js +319 -0
  45. package/dist/src/client/import/sources/files.d.ts +24 -0
  46. package/dist/src/client/import/sources/files.js +129 -0
  47. package/dist/src/client/import/transport.d.ts +76 -0
  48. package/dist/src/client/import/transport.js +141 -0
  49. package/dist/src/client/index.d.ts +19 -0
  50. package/dist/src/client/index.js +19 -0
  51. package/dist/src/client/kiro/collector.d.ts +88 -0
  52. package/dist/src/client/kiro/collector.js +577 -0
  53. package/dist/src/client/kiro/command.d.ts +3 -0
  54. package/dist/src/client/kiro/command.js +109 -0
  55. package/dist/src/client/kiro/config.d.ts +39 -0
  56. package/dist/src/client/kiro/config.js +107 -0
  57. package/dist/src/client/kiro/records.d.ts +52 -0
  58. package/dist/src/client/kiro/records.js +206 -0
  59. package/dist/src/client/kiro/service.d.ts +21 -0
  60. package/dist/src/client/kiro/service.js +183 -0
  61. package/dist/src/client/kiro/state.d.ts +45 -0
  62. package/dist/src/client/kiro/state.js +205 -0
  63. package/dist/src/client/kiro/transport.d.ts +9 -0
  64. package/dist/src/client/kiro/transport.js +90 -0
  65. package/dist/src/client/onboard.d.ts +5 -1
  66. package/dist/src/client/onboard.js +28 -23
  67. package/dist/src/client/piConfig.d.ts +29 -0
  68. package/dist/src/client/piConfig.js +112 -0
  69. package/dist/src/client/plan.d.ts +1 -1
  70. package/dist/src/client/plan.js +2 -1
  71. package/dist/src/client/settings.d.ts +4 -0
  72. package/dist/src/client/settings.js +17 -0
  73. package/dist/src/client/yaml.d.ts +5 -0
  74. package/dist/src/client/yaml.js +72 -0
  75. package/dist/src/mcpServer.js +1 -1
  76. package/dist/src/tools.d.ts +9 -6
  77. package/dist/src/tools.js +428 -60
  78. package/dist/src/version.d.ts +1 -1
  79. package/dist/src/version.js +1 -1
  80. package/package.json +178 -9
  81. package/tool-manifest.json +708 -21
@@ -0,0 +1,441 @@
1
+ import { NO_CONTENT, sessionKeyOf, trimSessionToWindow } from "./model.js";
2
+ import { CLAUDE_SERVICE, CODEX_SERVICE, completionMarker, convertSession } from "./convert.js";
3
+ import { chunkForPost, toOtlpLogs, toOtlpMetrics } from "./otlpImport.js";
4
+ import { COMMIT_PART_LABEL, decide, logPartLabel, metricPartLabel } from "./protocol.js";
5
+ import { fetchStatus, makePacer, postOtlp, sleepMs } from "./transport.js";
6
+ export const RETENTION_DAYS = 365;
7
+ export const RETENTION_MARGIN_DAYS = 1;
8
+ export const DEFAULT_SINCE_DAYS = 30;
9
+ export const ACTIVE_GRACE_MS = 15 * 60_000;
10
+ export const IMPORT_VERSION = "1";
11
+ export const DEFAULT_RATE_PER_MINUTE = 120;
12
+ export const MAX_RATE_PER_MINUTE = 300;
13
+ export const DEFAULT_TIME_LIMIT_MS = 60 * 60_000;
14
+ export const DAY_MS = 86_400_000;
15
+ const LOG_PART_MAX_RECORDS = 500;
16
+ const LOG_PART_MAX_BYTES = 1_000_000;
17
+ const METRIC_PART_MAX_RECORDS = 2_000;
18
+ const METRIC_PART_MAX_BYTES = 1_000_000;
19
+ const STATUS_BATCH = 100;
20
+ const MAX_STATUS_PROBES = 10;
21
+ const STATUS_BATCH_SPAN_MS = 30 * DAY_MS;
22
+ export function memoryLedger() {
23
+ const entries = new Map();
24
+ return {
25
+ get: (k, s) => entries.get(`${k}\u0000${s}`),
26
+ record(e) {
27
+ const id = `${e.k}\u0000${e.s}`;
28
+ if (e.ev === "begin") {
29
+ const prev = entries.get(id);
30
+ if (prev && prev.plan === e.plan)
31
+ return;
32
+ entries.set(id, {
33
+ plan: e.plan, fileSig: e.fileSig, state: "partial", logParts: [], metricParts: [], uncertainMetricParts: [],
34
+ logPartCount: e.logPartCount, metricPartCount: e.metricPartCount, run: e.run, atMs: e.atMs,
35
+ });
36
+ return;
37
+ }
38
+ const entry = entries.get(id);
39
+ if (!entry || entry.plan !== e.plan)
40
+ return;
41
+ entry.atMs = e.atMs;
42
+ if (e.ev === "log" && !entry.logParts.includes(e.part))
43
+ entry.logParts.push(e.part);
44
+ if (e.ev === "metric" && !entry.metricParts.includes(e.part)) {
45
+ entry.metricParts.push(e.part);
46
+ entry.uncertainMetricParts = entry.uncertainMetricParts.filter((p) => p !== e.part);
47
+ }
48
+ if (e.ev === "uncertain" && !entry.uncertainMetricParts.includes(e.part))
49
+ entry.uncertainMetricParts.push(e.part);
50
+ if (e.ev === "complete")
51
+ entry.state = "complete";
52
+ },
53
+ };
54
+ }
55
+ export const emptySummary = (source) => ({
56
+ source,
57
+ filesFound: 0,
58
+ sessionsParsed: 0,
59
+ candidates: 0,
60
+ imported: 0,
61
+ resumed: 0,
62
+ skipped: {},
63
+ events: 0,
64
+ metricPoints: 0,
65
+ tokens: { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 },
66
+ });
67
+ export const bump = (s, reason, n = 1) => {
68
+ s.skipped[reason] = (s.skipped[reason] ?? 0) + n;
69
+ };
70
+ export const underProject = (cwd, project, caseInsensitive) => {
71
+ if (!cwd)
72
+ return false;
73
+ const norm = (p) => {
74
+ const s = p.replace(/\\/g, "/").replace(/\/+$/, "");
75
+ return caseInsensitive ? s.toLowerCase() : s;
76
+ };
77
+ const a = norm(cwd);
78
+ const b = norm(project);
79
+ return a === b || a.startsWith(b + "/");
80
+ };
81
+ export const startOfUtcDay = (ms) => Math.floor(ms / DAY_MS) * DAY_MS;
82
+ export function resolveWindow(now, sinceMs, untilMs) {
83
+ const floorMs = startOfUtcDay(now - (RETENTION_DAYS - RETENTION_MARGIN_DAYS) * DAY_MS);
84
+ const requested = sinceMs ?? startOfUtcDay(now - DEFAULT_SINCE_DAYS * DAY_MS);
85
+ const clamped = requested < floorMs;
86
+ const since = Math.max(requested, floorMs);
87
+ return {
88
+ sinceMs: since,
89
+ untilMs: Math.min(untilMs ?? now, now),
90
+ clamped,
91
+ ...(clamped
92
+ ? {
93
+ warning: `--since was moved forward to ${new Date(since).toISOString().slice(0, 10)}: raw telemetry is kept ` +
94
+ `${RETENTION_DAYS} days by event time, so older events would be deleted as soon as they landed`,
95
+ }
96
+ : {}),
97
+ };
98
+ }
99
+ function stableResource(session, email) {
100
+ return {
101
+ "service.name": session.source === "claude-code" ? CLAUDE_SERVICE : CODEX_SERVICE,
102
+ "ingest.source": "history-import",
103
+ "import.source": session.source,
104
+ "import.version": IMPORT_VERSION,
105
+ ...(session.cwd ? { "project.path": session.cwd } : {}),
106
+ ...(email ? { "user.email": email } : {}),
107
+ };
108
+ }
109
+ export async function buildPlan(session, content, email, sha256Hex) {
110
+ const { logs, metrics } = convertSession(session, content);
111
+ const stable = stableResource(session, email);
112
+ const id = (await sha256Hex(JSON.stringify({ v: IMPORT_VERSION, stable, sessionId: session.sessionId, logs, metrics }))).slice(0, 32);
113
+ return {
114
+ stable,
115
+ plan: {
116
+ id,
117
+ logParts: chunkForPost(logs, LOG_PART_MAX_RECORDS, LOG_PART_MAX_BYTES),
118
+ metricParts: chunkForPost(metrics, METRIC_PART_MAX_RECORDS, METRIC_PART_MAX_BYTES),
119
+ events: logs.length,
120
+ metricPoints: metrics.length,
121
+ },
122
+ };
123
+ }
124
+ function tokensOf(session) {
125
+ const t = { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 };
126
+ for (const c of session.modelCalls) {
127
+ t.input += c.inputTokens;
128
+ t.output += c.outputTokens;
129
+ t.cacheRead += c.cacheReadTokens;
130
+ t.cacheCreation += c.cacheCreationTokens;
131
+ }
132
+ return t;
133
+ }
134
+ export async function prepareSession(session, fileSig, reload, opts) {
135
+ if (opts.project && !underProject(session.cwd, opts.project, opts.caseInsensitivePaths))
136
+ return "filtered";
137
+ if (session.endMs < opts.sinceMs)
138
+ return "older";
139
+ if (session.startMs > opts.untilMs)
140
+ return "newer";
141
+ const trimmed = trimSessionToWindow(session, opts.sinceMs, opts.untilMs);
142
+ if (!trimmed)
143
+ return "older";
144
+ const { plan } = await buildPlan(trimmed, opts.content[session.source], opts.email, opts.sha256Hex);
145
+ return {
146
+ source: session.source,
147
+ sessionId: trimmed.sessionId,
148
+ fileSig,
149
+ startMs: trimmed.startMs,
150
+ endMs: trimmed.endMs,
151
+ plan: {
152
+ id: plan.id,
153
+ logParts: plan.logParts.length,
154
+ metricParts: plan.metricParts.length,
155
+ events: plan.events,
156
+ metricPoints: plan.metricPoints,
157
+ },
158
+ tokens: tokensOf(trimmed),
159
+ warnings: trimmed.warnings,
160
+ reload,
161
+ };
162
+ }
163
+ function statusBatches(items) {
164
+ const out = [];
165
+ let batch = [];
166
+ let minStart = Infinity;
167
+ let maxEnd = -Infinity;
168
+ for (const p of [...items].sort((a, b) => a.startMs - b.startMs)) {
169
+ const lo = Math.min(minStart, p.startMs);
170
+ const hi = Math.max(maxEnd, p.endMs);
171
+ if (batch.length > 0 && (batch.length >= STATUS_BATCH || hi - lo > STATUS_BATCH_SPAN_MS)) {
172
+ out.push(batch);
173
+ batch = [];
174
+ minStart = Infinity;
175
+ maxEnd = -Infinity;
176
+ }
177
+ batch.push(p);
178
+ minStart = Math.min(minStart, p.startMs);
179
+ maxEnd = Math.max(maxEnd, p.endMs);
180
+ }
181
+ if (batch.length)
182
+ out.push(batch);
183
+ return out;
184
+ }
185
+ export async function importPrepared(prepared, o) {
186
+ const { key, keyHash: hash, ledger, summaries, warnings, dryRun, now, clock, fetchImpl } = o;
187
+ const sleep = o.sleep ?? sleepMs;
188
+ const log = o.logger ?? (() => { });
189
+ const errors = [];
190
+ const cleanup = [];
191
+ const ratePerMinute = Math.min(Math.max(1, o.ratePerMinute ?? DEFAULT_RATE_PER_MINUTE), MAX_RATE_PER_MINUTE);
192
+ const deadline = now + (o.timeLimitMs ?? DEFAULT_TIME_LIMIT_MS);
193
+ let stoppedBy = null;
194
+ const statuses = new Map();
195
+ let settleMs = 5 * 60_000;
196
+ const askStatus = async (items, probe) => {
197
+ const batches = statusBatches(items).flatMap((b) => probe
198
+ ? Array.from({ length: Math.ceil(b.length / MAX_STATUS_PROBES) }, (_, i) => b.slice(i * MAX_STATUS_PROBES, (i + 1) * MAX_STATUS_PROBES))
199
+ : [b]);
200
+ for (const batch of batches) {
201
+ const sessions = batch.map((p) => ({
202
+ sessionId: p.sessionId,
203
+ startMs: p.startMs,
204
+ endMs: p.endMs,
205
+ ...(probe ? { probePlan: p.plan.id } : {}),
206
+ }));
207
+ const r = await fetchStatus({ url: o.statusUrl, key, sessions, fetchImpl, sleep });
208
+ if (r.kind === "auth") {
209
+ errors.push(`The ingest key is invalid or revoked (import status returned HTTP ${r.status}).`);
210
+ stoppedBy = "auth";
211
+ return false;
212
+ }
213
+ if (r.kind === "unavailable") {
214
+ const msg = `The server-side import status check is unavailable (${r.detail}).`;
215
+ if (dryRun)
216
+ warnings.push(msg + " Live-overlap and duplicate checks were skipped for this dry run.");
217
+ else
218
+ errors.push(msg + " Nothing was sent: without it, sessions already captured live could be counted twice.");
219
+ stoppedBy = "status_unavailable";
220
+ return false;
221
+ }
222
+ settleMs = r.value.settleMs;
223
+ for (const st of r.value.sessions)
224
+ statuses.set(st.sessionId, st);
225
+ }
226
+ return true;
227
+ };
228
+ const statusOk = prepared.length === 0 || (await askStatus(prepared, false));
229
+ const ready = [];
230
+ if (statusOk) {
231
+ const probes = [];
232
+ const settle = (p, probed) => decide({ id: p.plan.id, logParts: p.plan.logParts, metricParts: p.plan.metricParts }, statuses.get(p.sessionId) ?? { sessionId: p.sessionId, live: false, plans: [] }, ledger.get(hash, sessionKeyOf(p.source, p.sessionId)), now, settleMs, probed);
233
+ const apply = (p, d) => {
234
+ const s = summaries.get(p.source);
235
+ if (d.action === "skip") {
236
+ bump(s, d.reason);
237
+ if (d.reason === "conflicting_partial" && d.plans)
238
+ cleanup.push({ source: p.source, sessionId: p.sessionId, plans: d.plans });
239
+ }
240
+ else if (d.action === "send")
241
+ ready.push({ p, decision: d });
242
+ };
243
+ for (const p of prepared) {
244
+ const d = settle(p, false);
245
+ if (d.action === "probe")
246
+ probes.push(p);
247
+ else
248
+ apply(p, d);
249
+ }
250
+ if (probes.length && (await askStatus(probes, true))) {
251
+ for (const p of probes) {
252
+ const d = settle(p, true);
253
+ apply(p, d.action === "probe" ? { action: "skip", reason: "unverifiable" } : d);
254
+ }
255
+ }
256
+ else {
257
+ for (const p of probes)
258
+ bump(summaries.get(p.source), "unverifiable");
259
+ }
260
+ }
261
+ else if (dryRun && stoppedBy === "status_unavailable") {
262
+ stoppedBy = null;
263
+ for (const p of prepared)
264
+ ready.push({ p, decision: { action: "send", skipLogParts: [], skipMetricParts: [], resumed: false } });
265
+ }
266
+ ready.sort((a, b) => a.p.startMs - b.p.startMs);
267
+ const cap = o.maxSessions && o.maxSessions > 0 ? o.maxSessions : Infinity;
268
+ const toSend = ready.slice(0, cap === Infinity ? undefined : cap);
269
+ const deferred = ready.length - toSend.length;
270
+ for (const r of ready.slice(toSend.length))
271
+ bump(summaries.get(r.p.source), "deferred");
272
+ const pacer = makePacer(ratePerMinute, sleep, clock);
273
+ let topup;
274
+ let sent = 0;
275
+ let processed = 0;
276
+ for (let i = 0; i < toSend.length; i++) {
277
+ const { p, decision } = toSend[i];
278
+ const s = summaries.get(p.source);
279
+ const tally = () => {
280
+ s.events += p.plan.events;
281
+ s.metricPoints += p.plan.metricPoints;
282
+ for (const k of ["input", "output", "cacheRead", "cacheCreation"])
283
+ s.tokens[k] += p.tokens[k];
284
+ };
285
+ if (dryRun) {
286
+ s.imported++;
287
+ if (decision.resumed)
288
+ s.resumed++;
289
+ tally();
290
+ processed++;
291
+ continue;
292
+ }
293
+ if (stoppedBy)
294
+ break;
295
+ if (clock() > deadline) {
296
+ stoppedBy = "time_limit";
297
+ break;
298
+ }
299
+ processed++;
300
+ const reloaded = await p.reload();
301
+ 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;
303
+ if (!session || !rebuilt || rebuilt.plan.id !== p.plan.id) {
304
+ bump(s, "changed_during_run");
305
+ continue;
306
+ }
307
+ const { plan, stable } = rebuilt;
308
+ for (const w of p.warnings)
309
+ warnings.push(`${p.source} ${p.sessionId}: ${w}`);
310
+ const sessionKey = sessionKeyOf(p.source, p.sessionId);
311
+ const resource = (part) => ({
312
+ ...stable,
313
+ "import.tool": o.importTool,
314
+ "import.plan": plan.id,
315
+ "import.part": part,
316
+ "import.run": o.run,
317
+ });
318
+ ledger.record({
319
+ k: hash, s: sessionKey, ev: "begin", plan: plan.id, fileSig: p.fileSig,
320
+ logPartCount: plan.logParts.length, metricPartCount: plan.metricParts.length, run: o.run, atMs: clock(),
321
+ });
322
+ let sessionFailed = false;
323
+ const fail = (msg) => {
324
+ errors.push(`${p.source} ${p.sessionId}: ${msg}`);
325
+ sessionFailed = true;
326
+ };
327
+ const stopOn = (outcome) => {
328
+ if (outcome.kind === "budget") {
329
+ stoppedBy = "budget";
330
+ topup = outcome.topup;
331
+ return true;
332
+ }
333
+ if (outcome.kind === "auth") {
334
+ stoppedBy = "auth";
335
+ errors.push(`The ingest key was refused (HTTP ${outcome.status}); nothing more was sent.`);
336
+ return true;
337
+ }
338
+ if (outcome.kind === "busy") {
339
+ stoppedBy = "busy";
340
+ errors.push(`Ingest kept refusing as busy/rate-limited (${outcome.detail}); stopped to leave room for live telemetry.`);
341
+ return true;
342
+ }
343
+ return false;
344
+ };
345
+ const skipLogs = new Set(decision.skipLogParts);
346
+ for (let li = 0; li < plan.logParts.length && !sessionFailed && !stoppedBy; li++) {
347
+ if (skipLogs.has(li))
348
+ continue;
349
+ const outcome = await postOtlp({
350
+ url: `${o.ingestEndpoint}/v1/logs`, key, fetchImpl, pacer, sleep, retryAmbiguous: true,
351
+ body: toOtlpLogs(plan.logParts[li], resource(logPartLabel(li))),
352
+ });
353
+ if (outcome.kind === "ok")
354
+ ledger.record({ k: hash, s: sessionKey, ev: "log", plan: plan.id, part: li, atMs: clock() });
355
+ else if (!stopOn(outcome))
356
+ fail(`log part ${li} was refused (${outcome.kind === "rejected" ? `HTTP ${outcome.status}` : outcome.kind})`);
357
+ }
358
+ const skipMetrics = new Set(decision.skipMetricParts);
359
+ for (let mi = 0; mi < plan.metricParts.length && !sessionFailed && !stoppedBy; mi++) {
360
+ if (skipMetrics.has(mi))
361
+ continue;
362
+ const outcome = await postOtlp({
363
+ url: `${o.ingestEndpoint}/v1/metrics`, key, fetchImpl, pacer, sleep, retryAmbiguous: false,
364
+ body: toOtlpMetrics(plan.metricParts[mi], resource(metricPartLabel(mi))),
365
+ });
366
+ if (outcome.kind === "ok") {
367
+ ledger.record({ k: hash, s: sessionKey, ev: "metric", plan: plan.id, part: mi, atMs: clock() });
368
+ }
369
+ else if (outcome.kind === "uncertain") {
370
+ ledger.record({ k: hash, s: sessionKey, ev: "uncertain", plan: plan.id, part: mi, atMs: clock() });
371
+ fail(`token part ${mi} got no definitive answer (${outcome.detail}); it will be verified, never blindly resent, on the next run`);
372
+ }
373
+ else if (!stopOn(outcome)) {
374
+ fail(`token part ${mi} was refused (${outcome.kind === "rejected" ? `HTTP ${outcome.status}` : outcome.kind})`);
375
+ }
376
+ }
377
+ if (!sessionFailed && !stoppedBy) {
378
+ const marker = completionMarker(session, {
379
+ id: plan.id, logParts: plan.logParts.length, metricParts: plan.metricParts.length, events: plan.events + plan.metricPoints,
380
+ });
381
+ const outcome = await postOtlp({
382
+ url: `${o.ingestEndpoint}/v1/logs`, key, fetchImpl, pacer, sleep, retryAmbiguous: true,
383
+ body: toOtlpLogs([marker], resource(COMMIT_PART_LABEL)),
384
+ });
385
+ if (outcome.kind === "ok") {
386
+ ledger.record({ k: hash, s: sessionKey, ev: "complete", plan: plan.id, atMs: clock() });
387
+ s.imported++;
388
+ if (decision.resumed)
389
+ s.resumed++;
390
+ tally();
391
+ sent++;
392
+ if (sent % 10 === 0)
393
+ log(`…${sent}/${toSend.length} sessions imported`);
394
+ }
395
+ else if (!stopOn(outcome)) {
396
+ fail("the completion marker was refused; the session will resume on the next run");
397
+ }
398
+ }
399
+ if (stoppedBy) {
400
+ processed--;
401
+ break;
402
+ }
403
+ }
404
+ const remaining = deferred + (toSend.length - processed);
405
+ if (stoppedBy === "budget") {
406
+ errors.push("Ingest refused with HTTP 402: this workspace's prepaid credit is exhausted, so it is not accepting " +
407
+ "telemetry (live sessions included). Add credit or seats" + (topup ? ` at ${topup}` : "") +
408
+ ", then re-run the same command — finished sessions are skipped and the interrupted one resumes.");
409
+ }
410
+ if (stoppedBy === "time_limit")
411
+ warnings.push("Stopped at the run's time limit; re-run to continue where it left off.");
412
+ if (cleanup.length) {
413
+ warnings.push(`${cleanup.length} session(s) hold an unfinished import of a different version of the session and were ` +
414
+ "skipped; see `cleanup` for the import.plan ids an operator must remove before they can be imported.");
415
+ }
416
+ const sources = [...summaries.values()];
417
+ return {
418
+ ok: errors.length === 0 && stoppedBy === null,
419
+ run: o.run,
420
+ dryRun,
421
+ key: { masked: o.keyMasked, keyHash: hash },
422
+ window: { sinceIso: new Date(o.sinceMs).toISOString(), untilIso: new Date(o.untilMs).toISOString(), clamped: o.clamped },
423
+ content: o.content,
424
+ sources,
425
+ totals: {
426
+ sessions: sources.reduce((n, s) => n + s.imported, 0),
427
+ events: sources.reduce((n, s) => n + s.events, 0),
428
+ metricPoints: sources.reduce((n, s) => n + s.metricPoints, 0),
429
+ },
430
+ remaining,
431
+ stoppedBy,
432
+ ...(topup !== undefined ? { topup } : {}),
433
+ cleanup,
434
+ warnings,
435
+ errors,
436
+ };
437
+ }
438
+ export const contentOrDefault = (c) => ({
439
+ "claude-code": c?.["claude-code"] ?? NO_CONTENT,
440
+ codex: c?.codex ?? NO_CONTENT,
441
+ });
@@ -0,0 +1,52 @@
1
+ export declare const LEDGER_VERSION = 1;
2
+ export declare const MAX_LEDGER_SESSIONS = 50000;
3
+ export declare const MAX_LEDGER_KEYS = 16;
4
+ export type LedgerEntry = {
5
+ plan: string;
6
+ fileSig: string;
7
+ state: "partial" | "complete";
8
+ logParts: number[];
9
+ metricParts: number[];
10
+ uncertainMetricParts: number[];
11
+ logPartCount: number;
12
+ metricPartCount: number;
13
+ run: string;
14
+ atMs: number;
15
+ };
16
+ export type JournalEvent = {
17
+ k: string;
18
+ s: string;
19
+ ev: "begin";
20
+ plan: string;
21
+ fileSig: string;
22
+ logPartCount: number;
23
+ metricPartCount: number;
24
+ run: string;
25
+ atMs: number;
26
+ } | {
27
+ k: string;
28
+ s: string;
29
+ ev: "log" | "metric" | "uncertain";
30
+ plan: string;
31
+ part: number;
32
+ atMs: number;
33
+ } | {
34
+ k: string;
35
+ s: string;
36
+ ev: "complete";
37
+ plan: string;
38
+ atMs: number;
39
+ };
40
+ export declare function resolveLedgerPath(home?: string): string;
41
+ export declare class LedgerStore {
42
+ #private;
43
+ readonly path: string;
44
+ readonly journalPath: string;
45
+ readonly readOnly: boolean;
46
+ private constructor();
47
+ static open(ledgerPath: string): LedgerStore;
48
+ entries(keyHash: string): Record<string, LedgerEntry>;
49
+ get(keyHash: string, sessionKey: string): LedgerEntry | undefined;
50
+ record(e: JournalEvent): void;
51
+ compact(): void;
52
+ }
@@ -0,0 +1,161 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ export const LEDGER_VERSION = 1;
5
+ export const MAX_LEDGER_SESSIONS = 50_000;
6
+ export const MAX_LEDGER_KEYS = 16;
7
+ const COMPACT_AFTER_LINES = 5_000;
8
+ export function resolveLedgerPath(home) {
9
+ return path.join(home ?? os.homedir(), ".codetelemetry", "import-ledger.json");
10
+ }
11
+ const journalPathOf = (ledgerPath) => ledgerPath.replace(/\.json$/, "") + ".journal";
12
+ const addUnique = (list, n) => {
13
+ if (!list.includes(n))
14
+ list.push(n);
15
+ };
16
+ export class LedgerStore {
17
+ path;
18
+ journalPath;
19
+ readOnly;
20
+ #snap;
21
+ #journalLines = 0;
22
+ constructor(ledgerPath, snap, readOnly) {
23
+ this.path = ledgerPath;
24
+ this.journalPath = journalPathOf(ledgerPath);
25
+ this.#snap = snap;
26
+ this.readOnly = readOnly;
27
+ }
28
+ static open(ledgerPath) {
29
+ let snap = { version: LEDGER_VERSION, keys: {} };
30
+ let readOnly = false;
31
+ try {
32
+ const parsed = JSON.parse(fs.readFileSync(ledgerPath, "utf8"));
33
+ if (parsed && parsed.version === LEDGER_VERSION && parsed.keys && typeof parsed.keys === "object") {
34
+ snap = parsed;
35
+ }
36
+ else if (parsed && typeof parsed.version === "number" && parsed.version > LEDGER_VERSION) {
37
+ readOnly = true;
38
+ }
39
+ }
40
+ catch {
41
+ }
42
+ const store = new LedgerStore(ledgerPath, snap, readOnly);
43
+ if (!readOnly) {
44
+ let raw = "";
45
+ try {
46
+ raw = fs.readFileSync(store.journalPath, "utf8");
47
+ }
48
+ catch {
49
+ }
50
+ for (const line of raw.split("\n")) {
51
+ if (!line.trim())
52
+ continue;
53
+ try {
54
+ store.#apply(JSON.parse(line));
55
+ store.#journalLines++;
56
+ }
57
+ catch {
58
+ }
59
+ }
60
+ }
61
+ return store;
62
+ }
63
+ entries(keyHash) {
64
+ return this.#snap.keys[keyHash] ?? {};
65
+ }
66
+ get(keyHash, sessionKey) {
67
+ return this.#snap.keys[keyHash]?.[sessionKey];
68
+ }
69
+ #apply(e) {
70
+ const bucket = (this.#snap.keys[e.k] ??= {});
71
+ if (e.ev === "begin") {
72
+ const prev = bucket[e.s];
73
+ if (prev && prev.plan === e.plan) {
74
+ prev.run = e.run;
75
+ prev.atMs = e.atMs;
76
+ prev.fileSig = e.fileSig;
77
+ return;
78
+ }
79
+ bucket[e.s] = {
80
+ plan: e.plan,
81
+ fileSig: e.fileSig,
82
+ state: "partial",
83
+ logParts: [],
84
+ metricParts: [],
85
+ uncertainMetricParts: [],
86
+ logPartCount: e.logPartCount,
87
+ metricPartCount: e.metricPartCount,
88
+ run: e.run,
89
+ atMs: e.atMs,
90
+ };
91
+ return;
92
+ }
93
+ const entry = bucket[e.s];
94
+ if (!entry || entry.plan !== e.plan)
95
+ return;
96
+ entry.atMs = e.atMs;
97
+ if (e.ev === "log")
98
+ addUnique(entry.logParts, e.part);
99
+ else if (e.ev === "metric") {
100
+ addUnique(entry.metricParts, e.part);
101
+ entry.uncertainMetricParts = entry.uncertainMetricParts.filter((p) => p !== e.part);
102
+ }
103
+ else if (e.ev === "uncertain")
104
+ addUnique(entry.uncertainMetricParts, e.part);
105
+ else if (e.ev === "complete")
106
+ entry.state = "complete";
107
+ }
108
+ record(e) {
109
+ this.#apply(e);
110
+ if (this.readOnly)
111
+ return;
112
+ fs.mkdirSync(path.dirname(this.journalPath), { recursive: true });
113
+ const fd = fs.openSync(this.journalPath, "a", 0o600);
114
+ try {
115
+ fs.writeSync(fd, JSON.stringify(e) + "\n");
116
+ fs.fsyncSync(fd);
117
+ }
118
+ finally {
119
+ fs.closeSync(fd);
120
+ }
121
+ if (++this.#journalLines >= COMPACT_AFTER_LINES)
122
+ this.compact();
123
+ }
124
+ compact() {
125
+ if (this.readOnly)
126
+ return;
127
+ prune(this.#snap);
128
+ fs.mkdirSync(path.dirname(this.path), { recursive: true });
129
+ const tmp = `${this.path}.${process.pid}.tmp`;
130
+ fs.writeFileSync(tmp, JSON.stringify(this.#snap) + "\n", { mode: 0o600 });
131
+ fs.renameSync(tmp, this.path);
132
+ try {
133
+ fs.chmodSync(this.path, 0o600);
134
+ }
135
+ catch {
136
+ }
137
+ try {
138
+ fs.rmSync(this.journalPath, { force: true });
139
+ }
140
+ catch {
141
+ }
142
+ this.#journalLines = 0;
143
+ }
144
+ }
145
+ function prune(snap) {
146
+ const newest = (k) => Object.values(snap.keys[k]).reduce((m, e) => Math.max(m, e.atMs), 0);
147
+ const keys = Object.keys(snap.keys);
148
+ if (keys.length > MAX_LEDGER_KEYS) {
149
+ for (const k of keys.sort((a, b) => newest(a) - newest(b)).slice(0, keys.length - MAX_LEDGER_KEYS)) {
150
+ delete snap.keys[k];
151
+ }
152
+ }
153
+ for (const bucket of Object.values(snap.keys)) {
154
+ const entries = Object.entries(bucket);
155
+ if (entries.length <= MAX_LEDGER_SESSIONS)
156
+ continue;
157
+ const complete = entries.filter(([, e]) => e.state === "complete").sort(([, a], [, b]) => a.atMs - b.atMs);
158
+ for (const [k] of complete.slice(0, entries.length - MAX_LEDGER_SESSIONS))
159
+ delete bucket[k];
160
+ }
161
+ }