@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
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { defaultClaudeSettingsPath } from "./sources/files.js";
|
|
5
|
+
const MAX_CLAUDE_CONFIG_BYTES = 32 * 1024 * 1024;
|
|
6
|
+
const MAX_AUTH_BYTES = 1024 * 1024;
|
|
7
|
+
const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
8
|
+
export function taggedId(tag, uuid) {
|
|
9
|
+
const hex = uuid.replace(/-/g, "");
|
|
10
|
+
if (!/^[0-9a-fA-F]{32}$/.test(hex))
|
|
11
|
+
return undefined;
|
|
12
|
+
const out = Array(22).fill("1");
|
|
13
|
+
let n = BigInt("0x" + hex);
|
|
14
|
+
for (let i = 21; n > 0n && i >= 0; i--) {
|
|
15
|
+
out[i] = BASE58[Number(n % 58n)];
|
|
16
|
+
n /= 58n;
|
|
17
|
+
}
|
|
18
|
+
return `${tag}_01${out.join("")}`;
|
|
19
|
+
}
|
|
20
|
+
export function claudeGlobalConfigPath(env = process.env, home = os.homedir()) {
|
|
21
|
+
const dir = env.CLAUDE_CONFIG_DIR || undefined;
|
|
22
|
+
const legacy = path.join(dir ?? path.join(home, ".claude"), ".config.json");
|
|
23
|
+
if (fs.existsSync(legacy))
|
|
24
|
+
return legacy;
|
|
25
|
+
return path.join(dir ?? home, ".claude.json");
|
|
26
|
+
}
|
|
27
|
+
export function codexAuthPath(env = process.env, home = os.homedir()) {
|
|
28
|
+
return env.CODEX_HOME ? path.join(env.CODEX_HOME, "auth.json") : path.join(home, ".codex", "auth.json");
|
|
29
|
+
}
|
|
30
|
+
function readJson(file, maxBytes) {
|
|
31
|
+
try {
|
|
32
|
+
const st = fs.statSync(file);
|
|
33
|
+
if (!st.isFile() || st.size > maxBytes)
|
|
34
|
+
return null;
|
|
35
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
36
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const EMAIL_RE = /^[^\s@]{1,128}@[^\s@]{1,190}$/;
|
|
43
|
+
const ID_RE = /^[A-Za-z0-9_.:-]{1,256}$/;
|
|
44
|
+
const email = (v) => (typeof v === "string" && EMAIL_RE.test(v.trim()) ? v.trim() : undefined);
|
|
45
|
+
const id = (v) => (typeof v === "string" && ID_RE.test(v) ? v : undefined);
|
|
46
|
+
const off = (v) => typeof v === "string" && /^(false|0|no|off)$/i.test(v.trim());
|
|
47
|
+
const compact = (attrs) => {
|
|
48
|
+
const out = {};
|
|
49
|
+
for (const [k, v] of Object.entries(attrs))
|
|
50
|
+
if (v)
|
|
51
|
+
out[k] = v;
|
|
52
|
+
return out;
|
|
53
|
+
};
|
|
54
|
+
export function readClaudeIdentity(opts = {}) {
|
|
55
|
+
const env = opts.env ?? process.env;
|
|
56
|
+
const config = readJson(opts.configPath ?? claudeGlobalConfigPath(env, opts.home), MAX_CLAUDE_CONFIG_BYTES);
|
|
57
|
+
if (!config)
|
|
58
|
+
return {};
|
|
59
|
+
const account = config.oauthAccount && typeof config.oauthAccount === "object" ? config.oauthAccount : {};
|
|
60
|
+
const settings = readJson(opts.settingsPath ?? defaultClaudeSettingsPath(env, opts.home), MAX_AUTH_BYTES);
|
|
61
|
+
const settingsEnv = settings?.env && typeof settings.env === "object" ? settings.env : {};
|
|
62
|
+
const includeUuid = !off(env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID) && !off(settingsEnv.OTEL_METRICS_INCLUDE_ACCOUNT_UUID);
|
|
63
|
+
const accountUuid = id(account.accountUuid);
|
|
64
|
+
const tagged = id(env.CLAUDE_CODE_ACCOUNT_TAGGED_ID ?? settingsEnv.CLAUDE_CODE_ACCOUNT_TAGGED_ID) ??
|
|
65
|
+
(accountUuid ? taggedId("user", accountUuid) : undefined);
|
|
66
|
+
return compact({
|
|
67
|
+
"organization.id": id(account.organizationUuid),
|
|
68
|
+
"user.account_id": includeUuid ? tagged : undefined,
|
|
69
|
+
"user.account_uuid": includeUuid ? accountUuid : undefined,
|
|
70
|
+
"user.email": email(account.emailAddress),
|
|
71
|
+
"user.id": id(config.userID),
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function jwtPayload(token) {
|
|
75
|
+
if (typeof token !== "string" || token.length > 64 * 1024)
|
|
76
|
+
return null;
|
|
77
|
+
const parts = token.split(".");
|
|
78
|
+
if (parts.length < 2)
|
|
79
|
+
return null;
|
|
80
|
+
try {
|
|
81
|
+
const value = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
82
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function readCodexIdentity(opts = {}) {
|
|
89
|
+
const auth = readJson(opts.authPath ?? codexAuthPath(opts.env ?? process.env, opts.home), MAX_AUTH_BYTES);
|
|
90
|
+
const tokens = auth?.tokens && typeof auth.tokens === "object" ? auth.tokens : null;
|
|
91
|
+
if (!tokens)
|
|
92
|
+
return {};
|
|
93
|
+
const claims = jwtPayload(tokens.id_token) ?? {};
|
|
94
|
+
const openai = claims["https://api.openai.com/auth"];
|
|
95
|
+
const authClaims = openai && typeof openai === "object" ? openai : {};
|
|
96
|
+
const profile = claims["https://api.openai.com/profile"];
|
|
97
|
+
const profileClaims = profile && typeof profile === "object" ? profile : {};
|
|
98
|
+
return compact({
|
|
99
|
+
"user.account_id": id(authClaims.chatgpt_account_id) ?? id(tokens.account_id),
|
|
100
|
+
"user.email": email(claims.email) ?? email(profileClaims.email),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
export function resolveImportIdentity(opts) {
|
|
104
|
+
if (opts.disabled)
|
|
105
|
+
return {};
|
|
106
|
+
const out = {};
|
|
107
|
+
if (opts.source !== "codex") {
|
|
108
|
+
const claude = readClaudeIdentity({ configPath: opts.claudeConfigPath, settingsPath: opts.claudeSettingsPath, env: opts.env, home: opts.home });
|
|
109
|
+
if (Object.keys(claude).length)
|
|
110
|
+
out["claude-code"] = claude;
|
|
111
|
+
}
|
|
112
|
+
if (opts.source !== "claude-code") {
|
|
113
|
+
const codex = readCodexIdentity({ authPath: opts.codexAuthPath, env: opts.env, home: opts.home });
|
|
114
|
+
if (Object.keys(codex).length)
|
|
115
|
+
out.codex = codex;
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
@@ -39,6 +39,8 @@ export type ImportedSession = {
|
|
|
39
39
|
files: string[];
|
|
40
40
|
fileSig: string;
|
|
41
41
|
cwd: string | null;
|
|
42
|
+
repositoryUrl?: string;
|
|
43
|
+
parentThreadId?: string;
|
|
42
44
|
startMs: number;
|
|
43
45
|
endMs: number;
|
|
44
46
|
prompts: ImportedPrompt[];
|
|
@@ -52,6 +54,22 @@ export declare const MAX_EVENTS_PER_SESSION = 200000;
|
|
|
52
54
|
export declare const MAX_PROMPT_CHARS = 64000;
|
|
53
55
|
export declare const MAX_TOOL_INPUT_CHARS = 16000;
|
|
54
56
|
export declare const capText: (s: string, n: number) => string;
|
|
57
|
+
export declare const TOOL_INPUT_KEEP_KEYS: ReadonlySet<string>;
|
|
58
|
+
export declare function capToolInput(value: unknown, full: string, max: number): string;
|
|
59
|
+
export type ImportIdentity = Readonly<Record<string, string>>;
|
|
60
|
+
export type IdentityBySource = Partial<Record<ImportSource, ImportIdentity>>;
|
|
61
|
+
export declare function maskEmail(email: string): string;
|
|
62
|
+
export declare function maskIdentity(identity: IdentityBySource): Partial<Record<ImportSource, Record<string, string>>>;
|
|
63
|
+
export declare const MONTH_OF: (ms: number) => string;
|
|
64
|
+
export declare const DAY_OF: (ms: number) => string;
|
|
65
|
+
export declare const callTokens: (c: Pick<ImportedModelCall, "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheCreationTokens">) => number;
|
|
66
|
+
export declare function tokensByMonth(session: Pick<ImportedSession, "modelCalls">): Record<string, number>;
|
|
67
|
+
export type MonthBucket = {
|
|
68
|
+
month: string;
|
|
69
|
+
sessions: number;
|
|
70
|
+
tokens: number;
|
|
71
|
+
};
|
|
72
|
+
export declare function addToMonths(months: MonthBucket[], startMs: number, monthTokens: Record<string, number>): void;
|
|
55
73
|
export type ImportLog = {
|
|
56
74
|
timeUnixNano: string;
|
|
57
75
|
attributes: ImportAttributes;
|
|
@@ -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
|
-
|
|
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 ?
|
|
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 {
|
|
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 ?
|
|
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
|
|
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
|
|
11
|
-
|
|
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
|
}
|
|
@@ -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/src/client/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";
|