@codetelemetry/mcp 0.3.8 → 0.3.12

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 (79) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +90 -9
  3. package/dist/src/client/agent.d.ts +221 -3
  4. package/dist/src/client/agent.js +174 -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 +7 -0
  16. package/dist/src/client/config.js +7 -0
  17. package/dist/src/client/graderSeed.d.ts +50 -0
  18. package/dist/src/client/graderSeed.js +289 -0
  19. package/dist/src/client/hostMetrics.d.ts +54 -0
  20. package/dist/src/client/hostMetrics.js +425 -0
  21. package/dist/src/client/import/browser.d.ts +30 -0
  22. package/dist/src/client/import/browser.js +157 -0
  23. package/dist/src/client/import/convert.d.ts +20 -0
  24. package/dist/src/client/import/convert.js +165 -0
  25. package/dist/src/client/import/core.d.ts +143 -0
  26. package/dist/src/client/import/core.js +441 -0
  27. package/dist/src/client/import/ledger.d.ts +52 -0
  28. package/dist/src/client/import/ledger.js +161 -0
  29. package/dist/src/client/import/model.d.ts +70 -0
  30. package/dist/src/client/import/model.js +42 -0
  31. package/dist/src/client/import/options.d.ts +24 -0
  32. package/dist/src/client/import/options.js +71 -0
  33. package/dist/src/client/import/otlpImport.d.ts +7 -0
  34. package/dist/src/client/import/otlpImport.js +81 -0
  35. package/dist/src/client/import/protocol.d.ts +35 -0
  36. package/dist/src/client/import/protocol.js +51 -0
  37. package/dist/src/client/import/run.d.ts +30 -0
  38. package/dist/src/client/import/run.js +127 -0
  39. package/dist/src/client/import/sources/claudeCodeText.d.ts +19 -0
  40. package/dist/src/client/import/sources/claudeCodeText.js +214 -0
  41. package/dist/src/client/import/sources/codexText.d.ts +20 -0
  42. package/dist/src/client/import/sources/codexText.js +319 -0
  43. package/dist/src/client/import/sources/files.d.ts +24 -0
  44. package/dist/src/client/import/sources/files.js +129 -0
  45. package/dist/src/client/import/transport.d.ts +76 -0
  46. package/dist/src/client/import/transport.js +141 -0
  47. package/dist/src/client/index.d.ts +19 -0
  48. package/dist/src/client/index.js +19 -0
  49. package/dist/src/client/kiro/collector.d.ts +88 -0
  50. package/dist/src/client/kiro/collector.js +577 -0
  51. package/dist/src/client/kiro/command.d.ts +3 -0
  52. package/dist/src/client/kiro/command.js +109 -0
  53. package/dist/src/client/kiro/config.d.ts +39 -0
  54. package/dist/src/client/kiro/config.js +107 -0
  55. package/dist/src/client/kiro/records.d.ts +52 -0
  56. package/dist/src/client/kiro/records.js +206 -0
  57. package/dist/src/client/kiro/service.d.ts +21 -0
  58. package/dist/src/client/kiro/service.js +183 -0
  59. package/dist/src/client/kiro/state.d.ts +45 -0
  60. package/dist/src/client/kiro/state.js +205 -0
  61. package/dist/src/client/kiro/transport.d.ts +9 -0
  62. package/dist/src/client/kiro/transport.js +90 -0
  63. package/dist/src/client/onboard.d.ts +5 -1
  64. package/dist/src/client/onboard.js +28 -23
  65. package/dist/src/client/piConfig.d.ts +29 -0
  66. package/dist/src/client/piConfig.js +112 -0
  67. package/dist/src/client/plan.d.ts +1 -1
  68. package/dist/src/client/plan.js +2 -1
  69. package/dist/src/client/settings.d.ts +4 -0
  70. package/dist/src/client/settings.js +17 -0
  71. package/dist/src/client/yaml.d.ts +5 -0
  72. package/dist/src/client/yaml.js +72 -0
  73. package/dist/src/mcpServer.js +1 -1
  74. package/dist/src/tools.d.ts +9 -6
  75. package/dist/src/tools.js +478 -60
  76. package/dist/src/version.d.ts +1 -1
  77. package/dist/src/version.js +1 -1
  78. package/package.json +178 -9
  79. package/tool-manifest.json +497 -21
@@ -0,0 +1,70 @@
1
+ export type ImportSource = "claude-code" | "codex";
2
+ export type Primitive = string | number | boolean;
3
+ export type ImportAttributes = Record<string, Primitive | undefined>;
4
+ export type ContentPolicy = {
5
+ prompts: boolean;
6
+ toolDetails: boolean;
7
+ };
8
+ export declare const NO_CONTENT: ContentPolicy;
9
+ export declare const ALL_CONTENT: ContentPolicy;
10
+ export type ImportedPrompt = {
11
+ promptId: string;
12
+ tsMs: number;
13
+ text: string | null;
14
+ length: number;
15
+ };
16
+ export type ImportedModelCall = {
17
+ responseId: string;
18
+ tsMs: number;
19
+ model: string;
20
+ inputTokens: number;
21
+ outputTokens: number;
22
+ cacheReadTokens: number;
23
+ cacheCreationTokens: number;
24
+ promptId?: string;
25
+ };
26
+ export type ImportedToolCall = {
27
+ toolUseId: string;
28
+ toolName: string;
29
+ tsMs: number;
30
+ input: string | null;
31
+ inputBytes: number;
32
+ success?: boolean;
33
+ resultBytes?: number;
34
+ promptId?: string;
35
+ };
36
+ export type ImportedSession = {
37
+ source: ImportSource;
38
+ sessionId: string;
39
+ files: string[];
40
+ fileSig: string;
41
+ cwd: string | null;
42
+ startMs: number;
43
+ endMs: number;
44
+ prompts: ImportedPrompt[];
45
+ modelCalls: ImportedModelCall[];
46
+ toolCalls: ImportedToolCall[];
47
+ warnings: string[];
48
+ skippedRecords: number;
49
+ totalRecords: number;
50
+ };
51
+ export declare const MAX_EVENTS_PER_SESSION = 200000;
52
+ export declare const MAX_PROMPT_CHARS = 64000;
53
+ export declare const MAX_TOOL_INPUT_CHARS = 16000;
54
+ export declare const capText: (s: string, n: number) => string;
55
+ export type ImportLog = {
56
+ timeUnixNano: string;
57
+ attributes: ImportAttributes;
58
+ body?: string;
59
+ };
60
+ export type ImportMetric = {
61
+ name: string;
62
+ timeUnixNano: string;
63
+ startTimeUnixNano: string;
64
+ asInt: number;
65
+ attributes: ImportAttributes;
66
+ };
67
+ export declare function toNano(ms: number): string;
68
+ export declare function sessionKeyOf(source: ImportSource, sessionId: string): string;
69
+ export declare function sessionEventCount(s: Pick<ImportedSession, "prompts" | "modelCalls" | "toolCalls">): number;
70
+ export declare function trimSessionToWindow(session: ImportedSession, sinceMs: number, untilMs: number): ImportedSession | null;
@@ -0,0 +1,42 @@
1
+ export const NO_CONTENT = Object.freeze({ prompts: false, toolDetails: false });
2
+ export const ALL_CONTENT = Object.freeze({ prompts: true, toolDetails: true });
3
+ export const MAX_EVENTS_PER_SESSION = 200_000;
4
+ export const MAX_PROMPT_CHARS = 64_000;
5
+ export const MAX_TOOL_INPUT_CHARS = 16_000;
6
+ export const capText = (s, n) => (s.length > n ? s.slice(0, n) : s);
7
+ export function toNano(ms) {
8
+ return (BigInt(Math.floor(ms)) * 1000000n).toString();
9
+ }
10
+ export function sessionKeyOf(source, sessionId) {
11
+ return `${source}:${sessionId}`;
12
+ }
13
+ export function sessionEventCount(s) {
14
+ return s.prompts.length + s.modelCalls.length + s.toolCalls.length;
15
+ }
16
+ export function trimSessionToWindow(session, sinceMs, untilMs) {
17
+ if (session.startMs >= sinceMs && session.endMs <= untilMs)
18
+ return session;
19
+ const keep = (tsMs) => tsMs >= sinceMs && tsMs <= untilMs;
20
+ const prompts = session.prompts.filter((p) => keep(p.tsMs));
21
+ const modelCalls = session.modelCalls.filter((c) => keep(c.tsMs));
22
+ const toolCalls = session.toolCalls.filter((t) => keep(t.tsMs));
23
+ if (prompts.length + modelCalls.length + toolCalls.length === 0)
24
+ return null;
25
+ let startMs = Infinity;
26
+ let endMs = -Infinity;
27
+ for (const e of [...prompts, ...modelCalls, ...toolCalls]) {
28
+ if (e.tsMs < startMs)
29
+ startMs = e.tsMs;
30
+ if (e.tsMs > endMs)
31
+ endMs = e.tsMs;
32
+ }
33
+ return {
34
+ ...session,
35
+ prompts,
36
+ modelCalls,
37
+ toolCalls,
38
+ startMs,
39
+ endMs,
40
+ warnings: [...session.warnings, "session spans the import window; only in-window events were imported"],
41
+ };
42
+ }
@@ -0,0 +1,24 @@
1
+ import type { ContentPolicy, ImportSource } from "./model.ts";
2
+ import type { ContentBySource } from "./run.ts";
3
+ export type KeyPaths = {
4
+ claudeSettings: string;
5
+ codexConfig: string;
6
+ };
7
+ export declare function resolveImportKey(opts: {
8
+ explicit?: string;
9
+ env?: string;
10
+ envName?: string;
11
+ source: ImportSource | "all";
12
+ paths: KeyPaths;
13
+ readClaude?: (p: string) => string | null;
14
+ readCodex?: (p: string) => string | null;
15
+ }): {
16
+ key: string;
17
+ from: string;
18
+ } | {
19
+ error: string;
20
+ };
21
+ export type ContentMode = "none" | "live" | "all" | ContentPolicy;
22
+ export declare function parseContentFlag(raw: string | undefined): ContentMode | null;
23
+ export declare function resolveImportContent(mode: ContentMode, paths: KeyPaths): ContentBySource;
24
+ export declare function parseWhen(raw: string, nowMs: number): number | null;
@@ -0,0 +1,71 @@
1
+ import { looksLikeKey } from "../keys.js";
2
+ import { readClaudeContentFlags } from "../settings.js";
3
+ import { readClaudeKey } from "../clients.js";
4
+ import { readCodexKey, readCodexLogUserPrompt } from "../codexConfig.js";
5
+ import { ALL_CONTENT, NO_CONTENT } from "./model.js";
6
+ export function resolveImportKey(opts) {
7
+ if (opts.explicit !== undefined) {
8
+ return looksLikeKey(opts.explicit) ? { key: opts.explicit.trim(), from: "argument" } : { error: "That is not a CodeTelemetry ingest key (cot_…)." };
9
+ }
10
+ const fromEnv = opts.env?.trim();
11
+ if (fromEnv) {
12
+ if (!looksLikeKey(fromEnv))
13
+ return { error: `$${opts.envName ?? "CODETELEMETRY_INGEST_KEY"} is set but is not an ingest key.` };
14
+ return { key: fromEnv, from: `$${opts.envName ?? "CODETELEMETRY_INGEST_KEY"}` };
15
+ }
16
+ const claude = (opts.readClaude ?? readClaudeKey)(opts.paths.claudeSettings);
17
+ const codex = (opts.readCodex ?? readCodexKey)(opts.paths.codexConfig);
18
+ if (opts.source === "all" && claude && codex && claude !== codex) {
19
+ return {
20
+ error: "Claude Code and Codex are configured with different ingest keys (different workspaces). " +
21
+ "Import each separately with --source claude-code and --source codex.",
22
+ };
23
+ }
24
+ const order = opts.source === "codex"
25
+ ? [[codex, opts.paths.codexConfig], [claude, opts.paths.claudeSettings]]
26
+ : [[claude, opts.paths.claudeSettings], [codex, opts.paths.codexConfig]];
27
+ for (const [key, from] of order)
28
+ if (key)
29
+ return { key, from };
30
+ return {
31
+ error: `No ingest key found in ${opts.paths.claudeSettings} or ${opts.paths.codexConfig}. ` +
32
+ "Run `codetelemetry-connect login` (or `login --codex`) first, or set CODETELEMETRY_INGEST_KEY.",
33
+ };
34
+ }
35
+ export function parseContentFlag(raw) {
36
+ if (raw === undefined)
37
+ return "live";
38
+ const v = raw.trim().toLowerCase();
39
+ if (v === "none" || v === "live" || v === "all")
40
+ return v;
41
+ const parts = v.split(",").map((s) => s.trim()).filter(Boolean);
42
+ if (!parts.length || parts.some((p) => p !== "prompts" && p !== "tools"))
43
+ return null;
44
+ return { prompts: parts.includes("prompts"), toolDetails: parts.includes("tools") };
45
+ }
46
+ export function resolveImportContent(mode, paths) {
47
+ if (mode === "none")
48
+ return { "claude-code": NO_CONTENT, codex: NO_CONTENT };
49
+ if (mode === "all")
50
+ return { "claude-code": ALL_CONTENT, codex: ALL_CONTENT };
51
+ if (mode === "live") {
52
+ return {
53
+ "claude-code": readClaudeContentFlags(paths.claudeSettings),
54
+ codex: { prompts: readCodexLogUserPrompt(paths.codexConfig), toolDetails: true },
55
+ };
56
+ }
57
+ return { "claude-code": mode, codex: mode };
58
+ }
59
+ export function parseWhen(raw, nowMs) {
60
+ const rel = raw.trim().match(/^(\d{1,4})([dh])$/i);
61
+ if (rel) {
62
+ const n = Number(rel[1]);
63
+ if (rel[2].toLowerCase() === "d")
64
+ return Math.floor((nowMs - n * 86_400_000) / 86_400_000) * 86_400_000;
65
+ return nowMs - n * 3_600_000;
66
+ }
67
+ if (!/^\d{4}-\d{2}-\d{2}/.test(raw.trim()))
68
+ return null;
69
+ const ms = Date.parse(raw.trim());
70
+ return Number.isFinite(ms) ? ms : null;
71
+ }
@@ -0,0 +1,7 @@
1
+ import type { ImportAttributes, ImportLog, ImportMetric } from "./model.ts";
2
+ export declare function toOtlpLogs(logs: ImportLog[], resource: ImportAttributes, scope?: {
3
+ name: string;
4
+ version?: string;
5
+ }): unknown;
6
+ export declare function toOtlpMetrics(metrics: ImportMetric[], resource: ImportAttributes): unknown;
7
+ export declare function chunkForPost<T>(items: T[], maxCount: number, maxBytes: number): T[][];
@@ -0,0 +1,81 @@
1
+ function anyValue(value) {
2
+ if (typeof value === "string")
3
+ return { stringValue: value };
4
+ if (typeof value === "boolean")
5
+ return { boolValue: value };
6
+ return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };
7
+ }
8
+ function kvList(attrs) {
9
+ return Object.entries(attrs)
10
+ .filter(([, v]) => v !== undefined && v !== null)
11
+ .map(([key, value]) => ({ key, value: anyValue(value) }));
12
+ }
13
+ const SCOPE = { name: "codetelemetry-connect.history-import" };
14
+ export function toOtlpLogs(logs, resource, scope = SCOPE) {
15
+ return {
16
+ resourceLogs: [{
17
+ resource: { attributes: kvList(resource) },
18
+ scopeLogs: [{
19
+ scope,
20
+ logRecords: logs.map((l) => ({
21
+ timeUnixNano: l.timeUnixNano,
22
+ observedTimeUnixNano: l.timeUnixNano,
23
+ severityNumber: 9,
24
+ severityText: "INFO",
25
+ attributes: kvList(l.attributes),
26
+ ...(l.body !== undefined ? { body: { stringValue: l.body } } : {}),
27
+ })),
28
+ }],
29
+ }],
30
+ };
31
+ }
32
+ export function toOtlpMetrics(metrics, resource) {
33
+ const byName = new Map();
34
+ for (const m of metrics) {
35
+ const list = byName.get(m.name);
36
+ if (list)
37
+ list.push(m);
38
+ else
39
+ byName.set(m.name, [m]);
40
+ }
41
+ return {
42
+ resourceMetrics: [{
43
+ resource: { attributes: kvList(resource) },
44
+ scopeMetrics: [{
45
+ scope: SCOPE,
46
+ metrics: [...byName.entries()].map(([name, points]) => ({
47
+ name,
48
+ unit: "tokens",
49
+ sum: {
50
+ aggregationTemporality: 1,
51
+ isMonotonic: true,
52
+ dataPoints: points.map((m) => ({
53
+ startTimeUnixNano: m.startTimeUnixNano,
54
+ timeUnixNano: m.timeUnixNano,
55
+ asInt: String(m.asInt),
56
+ attributes: kvList(m.attributes),
57
+ })),
58
+ },
59
+ })),
60
+ }],
61
+ }],
62
+ };
63
+ }
64
+ export function chunkForPost(items, maxCount, maxBytes) {
65
+ const out = [];
66
+ let batch = [];
67
+ let bytes = 0;
68
+ for (const item of items) {
69
+ const size = JSON.stringify(item).length;
70
+ if (batch.length > 0 && (batch.length >= maxCount || bytes + size > maxBytes)) {
71
+ out.push(batch);
72
+ batch = [];
73
+ bytes = 0;
74
+ }
75
+ batch.push(item);
76
+ bytes += size;
77
+ }
78
+ if (batch.length > 0)
79
+ out.push(batch);
80
+ return out;
81
+ }
@@ -0,0 +1,35 @@
1
+ import type { LedgerEntry } from "./ledger.ts";
2
+ export type PlanStatus = {
3
+ plan: string;
4
+ complete: boolean;
5
+ logParts: string[];
6
+ metricParts?: string[];
7
+ lastArrivalMs: number;
8
+ };
9
+ export type SessionStatus = {
10
+ sessionId: string;
11
+ live: boolean;
12
+ plans: PlanStatus[];
13
+ };
14
+ export type PlanShape = {
15
+ id: string;
16
+ logParts: number;
17
+ metricParts: number;
18
+ };
19
+ export type SkipReason = "live" | "already_imported" | "changed_since_import" | "conflicting_partial" | "settling" | "unverifiable";
20
+ export type Decision = {
21
+ action: "skip";
22
+ reason: SkipReason;
23
+ plans?: string[];
24
+ } | {
25
+ action: "probe";
26
+ } | {
27
+ action: "send";
28
+ skipLogParts: number[];
29
+ skipMetricParts: number[];
30
+ resumed: boolean;
31
+ };
32
+ export declare const logPartLabel: (i: number) => string;
33
+ export declare const metricPartLabel: (i: number) => string;
34
+ export declare const COMMIT_PART_LABEL = "C";
35
+ export declare function decide(plan: PlanShape, status: SessionStatus, ledger: LedgerEntry | undefined, nowMs: number, settleMs: number, probed?: boolean): Decision;
@@ -0,0 +1,51 @@
1
+ export const logPartLabel = (i) => `L${i}`;
2
+ export const metricPartLabel = (i) => `M${i}`;
3
+ export const COMMIT_PART_LABEL = "C";
4
+ const parseLabels = (labels, prefix) => (labels ?? [])
5
+ .filter((l) => l.startsWith(prefix))
6
+ .map((l) => Number(l.slice(prefix.length)))
7
+ .filter((n) => Number.isInteger(n) && n >= 0);
8
+ export function decide(plan, status, ledger, nowMs, settleMs, probed = false) {
9
+ if (status.live)
10
+ return { action: "skip", reason: "live" };
11
+ const committed = status.plans.filter((p) => p.complete);
12
+ if (committed.some((p) => p.plan === plan.id))
13
+ return { action: "skip", reason: "already_imported" };
14
+ if (committed.length > 0)
15
+ return { action: "skip", reason: "changed_since_import", plans: committed.map((p) => p.plan) };
16
+ const others = status.plans.filter((p) => p.plan !== plan.id && !p.complete);
17
+ if (others.length > 0)
18
+ return { action: "skip", reason: "conflicting_partial", plans: others.map((p) => p.plan) };
19
+ if (ledger && ledger.plan !== plan.id && ledger.state === "partial" &&
20
+ (ledger.metricParts.length > 0 || ledger.uncertainMetricParts.length > 0)) {
21
+ return { action: "skip", reason: "conflicting_partial", plans: [ledger.plan] };
22
+ }
23
+ const ours = status.plans.find((p) => p.plan === plan.id);
24
+ const mine = ledger && ledger.plan === plan.id ? ledger : undefined;
25
+ const fresh = !ours && (!mine || (mine.logParts.length === 0 && mine.metricParts.length === 0 && mine.uncertainMetricParts.length === 0));
26
+ if (fresh)
27
+ return { action: "send", skipLogParts: [], skipMetricParts: [], resumed: false };
28
+ const lastTouch = Math.max(ours?.lastArrivalMs ?? 0, mine?.atMs ?? 0);
29
+ if (lastTouch > nowMs - settleMs)
30
+ return { action: "skip", reason: "settling" };
31
+ const skipLogParts = new Set([...(mine?.logParts ?? []), ...parseLabels(ours?.logParts, "L")]);
32
+ const landedMetric = new Set(mine?.metricParts ?? []);
33
+ if (plan.metricParts > 0) {
34
+ const ledgerComplete = !!mine && mine.uncertainMetricParts.length === 0;
35
+ if (!ledgerComplete) {
36
+ if (!probed)
37
+ return { action: "probe" };
38
+ const fromServer = ours?.metricParts;
39
+ if (!fromServer)
40
+ return { action: "skip", reason: "unverifiable" };
41
+ for (const n of parseLabels(fromServer, "M"))
42
+ landedMetric.add(n);
43
+ }
44
+ }
45
+ return {
46
+ action: "send",
47
+ skipLogParts: [...skipLogParts].filter((n) => n < plan.logParts).sort((a, b) => a - b),
48
+ skipMetricParts: [...landedMetric].filter((n) => n < plan.metricParts).sort((a, b) => a - b),
49
+ resumed: true,
50
+ };
51
+ }
@@ -0,0 +1,30 @@
1
+ import type { FetchLike } from "../otlp.ts";
2
+ import type { ImportSource } from "./model.ts";
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";
5
+ export type ImportRunOptions = {
6
+ key: string;
7
+ endpoints?: Partial<{
8
+ apiBase: string;
9
+ ingestEndpoint: string;
10
+ }>;
11
+ source?: ImportSource | "all";
12
+ sinceMs?: number;
13
+ untilMs?: number;
14
+ project?: string;
15
+ email?: string;
16
+ content?: Partial<ContentBySource>;
17
+ dryRun?: boolean;
18
+ maxSessions?: number;
19
+ ratePerMinute?: number;
20
+ timeLimitMs?: number;
21
+ importTool?: ImportTool;
22
+ claudeDir?: string;
23
+ codexDir?: string;
24
+ ledgerPath?: string;
25
+ nowMs?: number;
26
+ fetchImpl?: FetchLike;
27
+ sleep?: (ms: number) => Promise<void>;
28
+ logger?: (msg: string) => void;
29
+ };
30
+ export declare function runImport(opts: ImportRunOptions): Promise<ImportRunResult>;
@@ -0,0 +1,127 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { assertKey, keyHash, mask } from "../keys.js";
3
+ import { resolveEndpoints } from "../config.js";
4
+ import { sessionKeyOf } from "./model.js";
5
+ import { ACTIVE_GRACE_MS, bump, contentOrDefault, emptySummary, importPrepared, prepareSession, resolveWindow, } from "./core.js";
6
+ import { defaultClaudeProjectsDir, defaultCodexSessionsDir, parseCandidate, scanClaudeSessions, scanCodexSessions, } from "./sources/files.js";
7
+ import { LedgerStore, resolveLedgerPath } from "./ledger.js";
8
+ 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
+ const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
10
+ export async function runImport(opts) {
11
+ const key = assertKey(opts.key);
12
+ const hash = keyHash(key);
13
+ const endpoints = resolveEndpoints(opts.endpoints);
14
+ const now = opts.nowMs ?? Date.now();
15
+ const clock = () => (opts.nowMs === undefined ? Date.now() : opts.nowMs);
16
+ const dryRun = !!opts.dryRun;
17
+ const warnings = [];
18
+ const content = contentOrDefault(opts.content);
19
+ const window = resolveWindow(now, opts.sinceMs, opts.untilMs);
20
+ if (window.warning)
21
+ warnings.push(window.warning);
22
+ const ledger = LedgerStore.open(opts.ledgerPath ?? resolveLedgerPath());
23
+ if (ledger.readOnly)
24
+ warnings.push("the import ledger was written by a newer importer; it is used read-only this run");
25
+ const wantClaude = !opts.source || opts.source === "all" || opts.source === "claude-code";
26
+ const wantCodex = !opts.source || opts.source === "all" || opts.source === "codex";
27
+ const summaries = new Map();
28
+ const found = [];
29
+ if (wantClaude) {
30
+ const s = emptySummary("claude-code");
31
+ summaries.set("claude-code", s);
32
+ const files = scanClaudeSessions(opts.claudeDir ?? defaultClaudeProjectsDir());
33
+ s.filesFound = files.length;
34
+ found.push(...files);
35
+ }
36
+ if (wantCodex) {
37
+ const s = emptySummary("codex");
38
+ summaries.set("codex", s);
39
+ const files = scanCodexSessions(opts.codexDir ?? defaultCodexSessionsDir());
40
+ s.filesFound = files.length;
41
+ found.push(...files);
42
+ }
43
+ const prepared = [];
44
+ const seen = new Set();
45
+ const prepareOpts = {
46
+ sinceMs: window.sinceMs,
47
+ untilMs: window.untilMs,
48
+ project: opts.project,
49
+ caseInsensitivePaths: process.platform === "win32" || process.platform === "darwin",
50
+ content,
51
+ email: opts.email,
52
+ sha256Hex,
53
+ };
54
+ for (const c of found) {
55
+ const s = summaries.get(c.source);
56
+ if (c.mtimeMs < window.sinceMs) {
57
+ bump(s, "older");
58
+ continue;
59
+ }
60
+ if (c.mtimeMs > now - ACTIVE_GRACE_MS) {
61
+ bump(s, "active");
62
+ continue;
63
+ }
64
+ const parsed = await parseCandidate(c, content[c.source]);
65
+ if (!parsed.ok) {
66
+ bump(s, parsed.reason);
67
+ warnings.push(`${c.source} ${c.file}: ${parsed.detail}; not imported`);
68
+ continue;
69
+ }
70
+ if (!parsed.session) {
71
+ bump(s, "empty");
72
+ continue;
73
+ }
74
+ s.sessionsParsed++;
75
+ const sessionKey = sessionKeyOf(parsed.session.source, parsed.session.sessionId);
76
+ const done = ledger.get(hash, sessionKey);
77
+ if (done && done.state === "complete" && done.fileSig === c.fileSig) {
78
+ bump(s, "ledger");
79
+ continue;
80
+ }
81
+ const reload = async () => {
82
+ const again = await parseCandidate(c, content[c.source]);
83
+ return again.ok ? again.session : null;
84
+ };
85
+ const p = await prepareSession(parsed.session, c.fileSig, reload, prepareOpts);
86
+ if (typeof p === "string") {
87
+ bump(s, p);
88
+ continue;
89
+ }
90
+ if (seen.has(sessionKey)) {
91
+ warnings.push(`${sessionKey} appears in more than one file; only the first is imported`);
92
+ continue;
93
+ }
94
+ seen.add(sessionKey);
95
+ s.candidates++;
96
+ prepared.push(p);
97
+ }
98
+ try {
99
+ return await importPrepared(prepared, {
100
+ ...prepareOpts,
101
+ key,
102
+ keyHash: hash,
103
+ keyMasked: mask(key),
104
+ statusUrl: endpoints.agentImportStatusUrl,
105
+ ingestEndpoint: endpoints.ingestEndpoint,
106
+ dryRun,
107
+ run: randomUUID(),
108
+ importTool: opts.importTool ?? "connect-cli",
109
+ maxSessions: opts.maxSessions,
110
+ ratePerMinute: opts.ratePerMinute,
111
+ timeLimitMs: opts.timeLimitMs,
112
+ clamped: window.clamped,
113
+ now,
114
+ clock,
115
+ fetchImpl: opts.fetchImpl ?? fetch,
116
+ sleep: opts.sleep,
117
+ ledger,
118
+ summaries,
119
+ warnings,
120
+ logger: opts.logger,
121
+ });
122
+ }
123
+ finally {
124
+ if (!dryRun)
125
+ ledger.compact();
126
+ }
127
+ }
@@ -0,0 +1,19 @@
1
+ import type { ContentPolicy, ImportedSession } from "../model.ts";
2
+ export type ClaudeParseOptions = {
3
+ keep?: ContentPolicy;
4
+ };
5
+ export declare class ClaudeSessionAccumulator {
6
+ #private;
7
+ constructor(opts?: ClaudeParseOptions);
8
+ get overflowed(): boolean;
9
+ line(raw: string): void;
10
+ finish(meta: {
11
+ files: string[];
12
+ fileSig: string;
13
+ fallbackSessionId?: string;
14
+ }): ImportedSession | null;
15
+ }
16
+ export declare function parseClaudeTranscriptText(raw: string, meta?: {
17
+ filePath?: string;
18
+ fileSig?: string;
19
+ }, opts?: ClaudeParseOptions): ImportedSession | null;