@codetelemetry/mcp 0.6.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 +78 -7
- 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 +90 -9
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +9 -1
- package/tool-manifest.json +75 -7
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { githubOrigin } from "./repositoryOrigin.js";
|
|
1
2
|
import fs from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
export const REPOSITORY_HOOK_MARKER = "codetelemetry-repository-observation";
|
|
@@ -146,6 +147,7 @@ function git(cwd, args) {
|
|
|
146
147
|
}).trim(); }
|
|
147
148
|
catch { return ""; }
|
|
148
149
|
}
|
|
150
|
+
const githubOrigin = ${githubOrigin.toString()};
|
|
149
151
|
const repositoryRemoteIdentity = ${normalizeRepositoryRemote.toString()};
|
|
150
152
|
const selectCodexOtelExporterLine = ${selectCodexOtelExporterLine.toString()};
|
|
151
153
|
function remoteName(value) {
|
|
@@ -384,7 +386,9 @@ async function main() {
|
|
|
384
386
|
if (!permitsAuthorization(url, destination.headers)) return;
|
|
385
387
|
const cwd = path.resolve(String(input.new_cwd || input.cwd || process.cwd()));
|
|
386
388
|
const root = git(cwd, ["rev-parse", "--show-toplevel"]) || cwd;
|
|
387
|
-
const
|
|
389
|
+
const rawRemote = git(root, ["config", "--get", "remote.origin.url"]);
|
|
390
|
+
const remote = repositoryRemoteIdentity(rawRemote);
|
|
391
|
+
const originUrl = githubOrigin(rawRemote);
|
|
388
392
|
const initialCommit = git(root, ["rev-list", "--max-parents=0", "HEAD"]).split(/\s+/).filter(Boolean).sort()[0] || "";
|
|
389
393
|
const commonDir = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
|
|
390
394
|
const commonRoot = commonDir.endsWith(path.sep + ".git") ? path.dirname(commonDir) : root;
|
|
@@ -406,6 +410,7 @@ async function main() {
|
|
|
406
410
|
attr("code.workspace.path", cwd),
|
|
407
411
|
attr("hook.event", hookEvent),
|
|
408
412
|
];
|
|
413
|
+
if (originUrl) attributes.push(attr("vcs.repository.url.full", originUrl));
|
|
409
414
|
if (sessionId) attributes.push(attr("session.id", sessionId));
|
|
410
415
|
const body = JSON.stringify({ resourceLogs: [{
|
|
411
416
|
resource: { attributes: [attr("service.name", "codetelemetry-connect")] },
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function githubOrigin(value: unknown): string | undefined;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function githubOrigin(value) {
|
|
2
|
+
if (typeof value !== "string" || value.length > 200 || /\s/.test(value))
|
|
3
|
+
return;
|
|
4
|
+
const match = /^(?:https:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?)\/([a-z0-9._-]{1,104})\/?$/i.exec(value);
|
|
5
|
+
if (!match)
|
|
6
|
+
return;
|
|
7
|
+
const name = match[2].replace(/\.git$/i, "");
|
|
8
|
+
if (!name || name.length > 100 || name === "." || name === "..")
|
|
9
|
+
return;
|
|
10
|
+
if (/(?:cot_|gh[pousr]_|github_pat_|AKIA|ASIA|sk-|xox[baprs]-|npm_|AIza|eyJ)[a-z0-9_-]{12,}/i.test(match[1] + "/" + name))
|
|
11
|
+
return;
|
|
12
|
+
return "https://github.com/" + match[1] + "/" + name;
|
|
13
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export declare function rolloutRepository(file: string): {
|
|
2
|
+
timeUnixNano: string;
|
|
3
|
+
attributes: {
|
|
4
|
+
"codex.parent_thread_id"?: string | undefined;
|
|
5
|
+
"vcs.repository.url.full"?: string | undefined;
|
|
6
|
+
"event.name": string;
|
|
7
|
+
"session.id": string;
|
|
8
|
+
};
|
|
9
|
+
} | null;
|
|
10
|
+
export declare function reportRolloutRepositories(files: string[], send: boolean, stateFile?: string): Promise<{
|
|
11
|
+
sent: number;
|
|
12
|
+
skipped: number;
|
|
13
|
+
observations: {
|
|
14
|
+
timeUnixNano: string;
|
|
15
|
+
attributes: {
|
|
16
|
+
"event.name": string;
|
|
17
|
+
"session.id": string;
|
|
18
|
+
"vcs.repository.url.full": string;
|
|
19
|
+
};
|
|
20
|
+
}[] | {
|
|
21
|
+
timeUnixNano: string;
|
|
22
|
+
attributes: {
|
|
23
|
+
"codex.parent_thread_id"?: string | undefined;
|
|
24
|
+
"vcs.repository.url.full"?: string | undefined;
|
|
25
|
+
"event.name": string;
|
|
26
|
+
"session.id": string;
|
|
27
|
+
};
|
|
28
|
+
}[];
|
|
29
|
+
}>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { githubOrigin } from "./repositoryOrigin.js";
|
|
4
|
+
import { assertKey } from "./keys.js";
|
|
5
|
+
import { toOtlpLogs } from "./import/otlpImport.js";
|
|
6
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
7
|
+
export function rolloutRepository(file) {
|
|
8
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | (fs.constants.O_NOFOLLOW || 0));
|
|
9
|
+
try {
|
|
10
|
+
if (!fs.fstatSync(fd).isFile())
|
|
11
|
+
throw new Error("Expected a regular rollout file.");
|
|
12
|
+
const bytes = Buffer.alloc(256 * 1024);
|
|
13
|
+
const length = fs.readSync(fd, bytes, 0, bytes.length, 0);
|
|
14
|
+
const end = bytes.subarray(0, length).indexOf(10);
|
|
15
|
+
if (end < 0 && length === bytes.length)
|
|
16
|
+
throw new Error("Rollout header exceeds 256 KiB.");
|
|
17
|
+
const header = JSON.parse(bytes.toString("utf8", 0, end < 0 ? length : end));
|
|
18
|
+
const meta = header.payload;
|
|
19
|
+
const id = meta?.id;
|
|
20
|
+
if (header.type !== "session_meta" || typeof id !== "string" || !uuid.test(id) ||
|
|
21
|
+
!path.basename(file).endsWith("-" + id + ".jsonl"))
|
|
22
|
+
throw new Error("Rollout header and filename must identify the same session.");
|
|
23
|
+
const at = Date.parse(header.timestamp);
|
|
24
|
+
if (!Number.isFinite(at) || at <= 0 || at > Date.now() + 300000)
|
|
25
|
+
throw new Error("Invalid rollout timestamp.");
|
|
26
|
+
const url = githubOrigin(meta.git?.repository_url);
|
|
27
|
+
const parent = meta.parent_thread_id;
|
|
28
|
+
if (!url && !(typeof parent === "string" && uuid.test(parent) && parent !== id))
|
|
29
|
+
return null;
|
|
30
|
+
return { timeUnixNano: String(BigInt(at) * 1000000n), attributes: {
|
|
31
|
+
"event.name": "codetelemetry.repository_observed", "session.id": id,
|
|
32
|
+
...(url ? { "vcs.repository.url.full": url } : {}),
|
|
33
|
+
...(typeof parent === "string" && uuid.test(parent) && parent !== id ? { "codex.parent_thread_id": parent } : {}),
|
|
34
|
+
} };
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
fs.closeSync(fd);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async function stateRepositories(file, ids) {
|
|
41
|
+
if (ids.some(id => !uuid.test(id)))
|
|
42
|
+
throw new Error("Select exact Codex thread UUIDs with --state.");
|
|
43
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
44
|
+
const db = new DatabaseSync(file, { readOnly: true, allowExtension: false });
|
|
45
|
+
try {
|
|
46
|
+
db.exec("PRAGMA trusted_schema=OFF; PRAGMA query_only=ON; PRAGMA busy_timeout=500; BEGIN");
|
|
47
|
+
if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='threads'").get() ||
|
|
48
|
+
!db.prepare("SELECT count(*) FROM pragma_table_info('threads') WHERE pk>0 HAVING count(*)=1 AND max(name)='id'").get())
|
|
49
|
+
throw new Error("Unrecognized Codex state database.");
|
|
50
|
+
const read = db.prepare("SELECT updated_at, CASE WHEN length(CAST(git_origin_url AS BLOB)) <= 200 THEN git_origin_url END AS remote FROM threads WHERE id=?");
|
|
51
|
+
return ids.flatMap(id => {
|
|
52
|
+
const row = read.get(id);
|
|
53
|
+
const url = githubOrigin(row?.remote);
|
|
54
|
+
const seconds = Number(row?.updated_at);
|
|
55
|
+
if (!url || !Number.isSafeInteger(seconds) || seconds <= 0 || seconds > Date.now() / 1000 + 300)
|
|
56
|
+
return [];
|
|
57
|
+
return [{ timeUnixNano: String(BigInt(seconds) * 1000000000n), attributes: {
|
|
58
|
+
"event.name": "codetelemetry.repository_observed", "session.id": id, "vcs.repository.url.full": url,
|
|
59
|
+
} }];
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
db.close();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export async function reportRolloutRepositories(files, send, stateFile) {
|
|
67
|
+
if (!files.length || files.length > 100)
|
|
68
|
+
throw new Error("Select between 1 and 100 rollout files or thread IDs.");
|
|
69
|
+
const rows = stateFile ? await stateRepositories(stateFile, files) : files.map(rolloutRepository).filter(row => row !== null);
|
|
70
|
+
if (send && rows.length) {
|
|
71
|
+
const key = assertKey(process.env.CODETELEMETRY_INGEST_KEY);
|
|
72
|
+
const response = await fetch("https://ingest.codetelemetry.com/v1/logs", {
|
|
73
|
+
method: "POST", redirect: "error", signal: AbortSignal.timeout(10000),
|
|
74
|
+
headers: { authorization: "Bearer " + key, "content-type": "application/json" },
|
|
75
|
+
body: JSON.stringify(toOtlpLogs(rows, { "service.name": "codetelemetry-connect" }, { name: "codetelemetry.rollout-repository", version: "1" })),
|
|
76
|
+
});
|
|
77
|
+
if (!response.ok)
|
|
78
|
+
throw new Error("Repository metadata delivery returned HTTP " + response.status);
|
|
79
|
+
const body = await response.text();
|
|
80
|
+
if (body && Number(JSON.parse(body).partialSuccess?.rejectedLogRecords || 0))
|
|
81
|
+
throw new Error("Collector rejected repository metadata.");
|
|
82
|
+
}
|
|
83
|
+
return { sent: send ? rows.length : 0, skipped: files.length - rows.length, observations: rows };
|
|
84
|
+
}
|
|
@@ -6,6 +6,7 @@ import { verifyScope } from "./connectivity.js";
|
|
|
6
6
|
import { resolveEndpoints } from "./config.js";
|
|
7
7
|
import { runImport } from "./import/run.js";
|
|
8
8
|
import { sessionKeyOf } from "./import/model.js";
|
|
9
|
+
import { resolveImportIdentity } from "./import/identity.js";
|
|
9
10
|
export async function importWorkspaceHistory(options, deps = {}) {
|
|
10
11
|
const context = loadWorkspace(options.name);
|
|
11
12
|
if (!context.scope.teamId || !context.clientConfig)
|
|
@@ -15,12 +16,13 @@ export async function importWorkspaceHistory(options, deps = {}) {
|
|
|
15
16
|
const expected = context.scope;
|
|
16
17
|
const previewFile = path.join(workspaceHome(), `${context.name}.import-preview.json`);
|
|
17
18
|
const source = context.clientConfig.client === "claude" ? "claude-code" : "codex";
|
|
19
|
+
const identity = resolveImportIdentity({ source });
|
|
18
20
|
if (options.preview) {
|
|
19
21
|
if (options.confirm || options.selections)
|
|
20
22
|
throw new Error("Preview and import confirmation are separate actions.");
|
|
21
23
|
const capture = workspaceCaptureDefault(context);
|
|
22
24
|
const content = { prompts: capture, toolDetails: capture };
|
|
23
|
-
const result = await runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
|
|
25
|
+
const result = await runImport({ ...deps, key: context.ingestKey, endpoints, project, source, identity,
|
|
24
26
|
sinceMs: options.sinceMs, content: { "claude-code": content, codex: content }, previewOnly: true });
|
|
25
27
|
const preview = { version: 1, workspace: context.name, keyHash: keyHash(context.ingestKey),
|
|
26
28
|
project, createdAt: Date.now(), scope: expected, window: result.window, content: result.content,
|
|
@@ -50,7 +52,7 @@ export async function importWorkspaceHistory(options, deps = {}) {
|
|
|
50
52
|
connectivityUrl: resolveEndpoints(endpoints).connectivityUrl, fetchImpl: deps.fetchImpl });
|
|
51
53
|
if (verified.state !== "scope_verified")
|
|
52
54
|
throw new Error(`Workspace is unavailable: ${verified.state}. No history was uploaded.`);
|
|
53
|
-
return runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
|
|
55
|
+
return runImport({ ...deps, key: context.ingestKey, endpoints, project, source, identity,
|
|
54
56
|
sinceMs: Date.parse(preview.window.sinceIso), untilMs: Date.parse(preview.window.untilIso),
|
|
55
57
|
content: preview.content, selectedPlans, maxSessions: 100, timeLimitMs: 120_000 });
|
|
56
58
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { KeyScope } from "./connectivity.ts";
|
|
2
|
-
export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.
|
|
2
|
+
export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.8.0";
|
|
3
3
|
export declare const MAX_WORKSPACE_BYTES: number;
|
|
4
4
|
export declare const MAX_WORKSPACES = 64;
|
|
5
5
|
export type WorkspaceBinding = {
|
|
@@ -5,7 +5,7 @@ import { createHash, randomBytes } from "node:crypto";
|
|
|
5
5
|
import { buildOtelSection } from "./codexConfig.js";
|
|
6
6
|
import { repositoryHookSource, quotedCommand, REPOSITORY_HOOK_FILE, REPOSITORY_HOOK_STATE_FILE } from "./repositoryHook.js";
|
|
7
7
|
import { looksLikeKey } from "./keys.js";
|
|
8
|
-
export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.
|
|
8
|
+
export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.8.0";
|
|
9
9
|
export const MAX_WORKSPACE_BYTES = 64 * 1024;
|
|
10
10
|
export const MAX_WORKSPACES = 64;
|
|
11
11
|
const isContextFile = (name) => /^[a-z][a-z0-9_-]{0,63}\.json$/.test(name) && name !== REPOSITORY_HOOK_STATE_FILE;
|
|
@@ -230,6 +230,8 @@ function upgradeLegacyCodexObserver(codexHome) {
|
|
|
230
230
|
const declaration = `const codexConfigPath = ${JSON.stringify(configPath)};`;
|
|
231
231
|
const fingerprint = createHash("sha256").update(source.replace(declaration, 'const codexConfigPath = "";')).digest("hex");
|
|
232
232
|
const recognized = new Set([
|
|
233
|
+
"a4265abbe2ab5f2f8919b330a60c047226b708f6a42af34738f31f75004b9db3",
|
|
234
|
+
"92297bee16fd6a4111339d96aa7adc3b2d0ee5d9def9337470f468758b527eae",
|
|
233
235
|
"69dd5ad120636379875fc411bcaaa096defe475944d24a6e899dc9796472ab2d",
|
|
234
236
|
"65eaa30f6c565b0298137986bbe4e94d0435f8fedc2574fa284e7979a5fa9ef4",
|
|
235
237
|
]);
|
package/dist/src/tools.d.ts
CHANGED
|
@@ -19,6 +19,11 @@ export type ToolContext = {
|
|
|
19
19
|
ledgerPath?: string;
|
|
20
20
|
nowMs?: number;
|
|
21
21
|
sleep?: (ms: number) => Promise<void>;
|
|
22
|
+
identityPaths?: {
|
|
23
|
+
claudeConfigPath?: string;
|
|
24
|
+
claudeSettingsPath?: string;
|
|
25
|
+
codexAuthPath?: string;
|
|
26
|
+
};
|
|
22
27
|
};
|
|
23
28
|
};
|
|
24
29
|
export type ToolResult = {
|
package/dist/src/tools.js
CHANGED
|
@@ -4,7 +4,7 @@ import { workspaceProject } from "./client/join.js";
|
|
|
4
4
|
import fs from "node:fs";
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import path from "node:path";
|
|
7
|
-
import { resolveEndpoints, sendTestEvent, confirmLanded, verifyScope, getCostSignal, getSessionPerformance, normalizeSessionPerformanceService, findSimilarSessionErrors, searchCodingSessions, SESSION_SEARCH_REQUEST_TIMEOUT_MS, countReplyPhrases, estimateTaskSize, estimateLinearIssue, readGitHubGate, configureGitHubGate, interpretSession, readSessionEvents, compareSessions, planNextSession, graderConfigRequest, normalizePlan, PLAN_PROVIDERS, ONBOARD_CLIENTS, SESSION_FILTER_ASSISTANTS, isOnboardClient, CLIENTS, PI_EXTENSION_HINT, MAX_PLAN_TEXT, MAX_PLAN_STEPS, requestDeviceCode, pollOnce, onboard as onboardCore, looksLikeKey, scrub, runImport, resolveImportContent, } from "./client/index.js";
|
|
7
|
+
import { resolveEndpoints, sendTestEvent, confirmLanded, verifyScope, getCostSignal, getSessionPerformance, normalizeSessionPerformanceService, findSimilarSessionErrors, searchCodingSessions, SESSION_SEARCH_REQUEST_TIMEOUT_MS, countReplyPhrases, estimateTaskSize, estimateLinearIssue, readGitHubGate, configureGitHubGate, interpretSession, readSessionEvents, compareSessions, planNextSession, graderConfigRequest, normalizePlan, PLAN_PROVIDERS, ONBOARD_CLIENTS, SESSION_FILTER_ASSISTANTS, isOnboardClient, CLIENTS, PI_EXTENSION_HINT, MAX_PLAN_TEXT, MAX_PLAN_STEPS, requestDeviceCode, pollOnce, onboard as onboardCore, looksLikeKey, scrub, runImport, runEstimate, resolveImportContent, resolveImportIdentity, fetchPricing, priceEstimate, claudeRetentionCutoffMs, IMPORT_NEVER_RECOVERS, } from "./client/index.js";
|
|
8
8
|
import { seedGraderConfig } from "./client/graderSeed.js";
|
|
9
9
|
import { writeGraderArtifact } from "./client/graderArtifact.js";
|
|
10
10
|
import { OnboardingSession } from "./session.js";
|
|
@@ -344,8 +344,9 @@ const IMPORT_MAX_SESSIONS = 200;
|
|
|
344
344
|
const IMPORT_DEFAULT_SESSIONS = 50;
|
|
345
345
|
const IMPORT_TIME_LIMIT_MS = 4 * 60_000;
|
|
346
346
|
const IMPORT_MAX_MESSAGES = 10;
|
|
347
|
+
const stripPaths = (s) => s.replace(/(?:[A-Za-z]:)?[\\/][^\s:;,]+\.jsonl/g, "<session file>");
|
|
347
348
|
function importSummary(r) {
|
|
348
|
-
const
|
|
349
|
+
const unaffordable = r.billing && !r.billing.affordable;
|
|
349
350
|
return {
|
|
350
351
|
ok: r.ok,
|
|
351
352
|
dryRun: r.dryRun,
|
|
@@ -356,6 +357,8 @@ function importSummary(r) {
|
|
|
356
357
|
remaining: r.remaining,
|
|
357
358
|
stoppedBy: r.stoppedBy,
|
|
358
359
|
...(r.topup !== undefined ? { topup: r.topup } : {}),
|
|
360
|
+
...(r.billing ? { billing: r.billing } : {}),
|
|
361
|
+
...(r.identity ? { identity: r.identity } : {}),
|
|
359
362
|
sources: r.sources.map((s) => ({
|
|
360
363
|
source: s.source,
|
|
361
364
|
filesFound: s.filesFound,
|
|
@@ -365,6 +368,9 @@ function importSummary(r) {
|
|
|
365
368
|
events: s.events,
|
|
366
369
|
tokenPoints: s.metricPoints,
|
|
367
370
|
tokens: s.tokens,
|
|
371
|
+
months: s.months.slice(-13),
|
|
372
|
+
firstEventMs: s.firstEventMs,
|
|
373
|
+
lastEventMs: s.lastEventMs,
|
|
368
374
|
skipped: s.skipped,
|
|
369
375
|
})),
|
|
370
376
|
cleanupSessions: r.cleanup.length,
|
|
@@ -372,10 +378,14 @@ function importSummary(r) {
|
|
|
372
378
|
warningCount: r.warnings.length,
|
|
373
379
|
errors: r.errors.slice(0, IMPORT_MAX_MESSAGES).map(stripPaths),
|
|
374
380
|
note: r.dryRun
|
|
375
|
-
? "Nothing was sent. Show the user this summary
|
|
376
|
-
|
|
377
|
-
? "
|
|
378
|
-
|
|
381
|
+
? "Nothing was sent. Show the user this summary, the content setting" + (r.billing ? ", the billing estimate" : "") +
|
|
382
|
+
" and the identity stamped on the rows, and ask before importing (dryRun false)." +
|
|
383
|
+
(unaffordable ? " The prepaid credit does not cover every session: a real import stops before the first one it cannot pay for." : "")
|
|
384
|
+
: r.stoppedBy === "budget"
|
|
385
|
+
? "Stopped for budget: add credit or seats, then call import_history again with the same arguments; finished sessions are skipped."
|
|
386
|
+
: r.remaining > 0
|
|
387
|
+
? "More sessions remain: call import_history again with the same arguments to continue."
|
|
388
|
+
: "Import finished for this window. Imported sessions show in the dashboards like live ones, without latency, decisions or active time.",
|
|
379
389
|
};
|
|
380
390
|
}
|
|
381
391
|
const GITHUB_GATE_HOW_TO = {
|
|
@@ -414,13 +424,14 @@ const GRADER_CHECK_PROP = obj({
|
|
|
414
424
|
enabled: { type: "boolean" },
|
|
415
425
|
repositoryId: { type: "string", minLength: 1, maxLength: 512 },
|
|
416
426
|
environment: { type: "string", minLength: 1, maxLength: 64, pattern: "^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$" },
|
|
417
|
-
beforePush: { type: "boolean", description: "Require successful command evidence after the final edit and before pushing;
|
|
427
|
+
beforePush: { type: "boolean", description: "Require successful command evidence after the final edit and before pushing; the service accepts it only when matcherRule.include names the commands: one exactFingerprint equals/in condition, or all of source equals shell, executable equals/in and packageScript equals/in (each optionally with one repositoryRelativeWorkingDirectory equals condition). Broader matchers are refused." },
|
|
418
428
|
matcherRule: GRADER_MATCHER_PROP,
|
|
419
429
|
detectorRule: GRADER_MATCHER_PROP,
|
|
420
430
|
applicabilityRule: GRADER_MATCHER_PROP,
|
|
421
431
|
evidenceRequirement: { type: "string", enum: ["coverage_increase"] },
|
|
422
432
|
createdFromActivityId: { type: "string", maxLength: 512 },
|
|
423
433
|
components: { type: "array", minItems: 1, maxItems: 8, items: obj({ name: { type: "string", minLength: 1, maxLength: 120 }, matcherRule: GRADER_MATCHER_PROP, requireSuccess: { type: "boolean" } }, ["name", "matcherRule", "requireSuccess"]) },
|
|
434
|
+
issues: { type: "array", minItems: 1, maxItems: 20, uniqueItems: true, items: { type: "string", minLength: 3, maxLength: 220, pattern: "^[a-z0-9][a-z0-9-]{0,38}/[a-z0-9._-]{1,100}#[1-9][0-9]{0,9}$" }, description: "Task scope: the GitHub issues (lowercase owner/repo#number) this check is required for. It applies only when the pull request being judged closes one of them, as GitHub reports it, and adds to organization and repository checks; it never applies outside a pull request. Issue and PR text never select it." },
|
|
424
435
|
linkage: { type: "string", enum: ["signadot"], description: "Links a three-component composite to recorded sandbox readiness, an exact routing key and declared endpoint, and a positive validation result. May be required before push after the final edit. Keep it when re-saving a check read from get_grader_config; dropping it leaves an unlinked composite." },
|
|
425
436
|
}, ["id", "name", "category", "weight", "satisfactionMode", "minimumOccurrences", "aggregationMode", "enabled"]);
|
|
426
437
|
function graderSchemaValid(value, schema) {
|
|
@@ -909,6 +920,8 @@ export const TOOLS = [
|
|
|
909
920
|
assistant: { type: "string", enum: ["all", ...SESSION_FILTER_ASSISTANTS], description: "Assistant filter (default all)." },
|
|
910
921
|
minDurationMs: { type: "integer", minimum: 0, maximum: 31_536_000_000, description: "Inclusive minimum elapsed session span in milliseconds." },
|
|
911
922
|
maxDurationMs: { type: "integer", minimum: 0, maximum: 31_536_000_000, description: "Inclusive maximum elapsed session span in milliseconds." },
|
|
923
|
+
start: { type: "integer", minimum: 0, maximum: 253_402_300_799, description: "Only sessions last active at or after this time, in Unix seconds." },
|
|
924
|
+
end: { type: "integer", minimum: 0, maximum: 253_402_300_799, description: "Only sessions last active before this time, in Unix seconds (after start)." },
|
|
912
925
|
activity: {
|
|
913
926
|
type: "string",
|
|
914
927
|
enum: ["all", "substantive"],
|
|
@@ -1632,7 +1645,7 @@ export const TOOLS = [
|
|
|
1632
1645
|
{
|
|
1633
1646
|
name: "update_grader_config",
|
|
1634
1647
|
title: "Update the Grader draft",
|
|
1635
|
-
description: "Save selected instruction/skill-derived checks to the authenticated workspace's Grader draft. features records which instruction features the user wants graded. Use seed_grader_config to inspect sources, then get_grader_config to obtain expectedRevision. upsertChecks add or update by id, preserving unmentioned checks; removeCheckIds removes only named checks. Checks use the dashboard's ValidationCheck shape and deterministic matcherRule (source, executable, packageScript, normalizedArguments, toolNamespace/toolName, operation, workingDirectory, etc.). For example, a skill check can require source=agent_tool, toolName=Skill, and operation=<skill name>; do not equate invoking a skill with complying with all its prose. Match only observable evidence, keep rationale/source in description, and apply repositoryId/environment scope when appropriate. The backend validates checks and refuses stale revisions with conflict; read again before retrying any uncertain save. After saving, use write_grader_config_artifact to leave selected checks as Terraform or Pulumi when requested. This saves a draft; use publish_grader_config with the returned revision to apply it when the user wants publication.",
|
|
1648
|
+
description: "Save selected instruction/skill-derived checks to the authenticated workspace's Grader draft. features records which instruction features the user wants graded. Use seed_grader_config to inspect sources, then get_grader_config to obtain expectedRevision. upsertChecks add or update by id, preserving unmentioned checks; removeCheckIds removes only named checks. Checks use the dashboard's ValidationCheck shape and deterministic matcherRule (source, executable, packageScript, normalizedArguments, toolNamespace/toolName, operation, workingDirectory, etc.). For example, a skill check can require source=agent_tool, toolName=Skill, and operation=<skill name>; do not equate invoking a skill with complying with all its prose. Match only observable evidence, keep rationale/source in description, and apply repositoryId/environment scope when appropriate. Use issues for checks that only one GitHub issue's pull request must pass (task scope). The backend validates checks and refuses stale revisions with conflict; read again before retrying any uncertain save. After saving, use write_grader_config_artifact to leave selected checks as Terraform or Pulumi when requested. This saves a draft; use publish_grader_config with the returned revision to apply it when the user wants publication.",
|
|
1636
1649
|
inputSchema: obj({
|
|
1637
1650
|
expectedRevision: { type: "string", pattern: "^[a-f0-9]{64}$", description: "revision from get_grader_config; prevents overwriting a changed draft." },
|
|
1638
1651
|
features: GRADER_FEATURES_PROP,
|
|
@@ -1762,6 +1775,67 @@ export const TOOLS = [
|
|
|
1762
1775
|
return { ok: true, gate: r.gate, settingsUrl: `${ep.apiBase}${GITHUB_GATE_SETTINGS_PATH}`, howTo: GITHUB_GATE_HOW_TO };
|
|
1763
1776
|
},
|
|
1764
1777
|
},
|
|
1778
|
+
{
|
|
1779
|
+
name: "estimate_history",
|
|
1780
|
+
title: "Estimate past sessions before importing them",
|
|
1781
|
+
description: "Use this when the user asks what importing their EXISTING local Claude Code or Codex history would cost, or how much history they have. " +
|
|
1782
|
+
"Needs no key and sends nothing: it reads ~/.claude/projects and ~/.codex/sessions on this machine and returns sessions and tokens per source, per UTC month and per day, the oldest and newest session, and the last-30-day pace, " +
|
|
1783
|
+
"priced with CodeTelemetry's public price list when it can be read. Imported tokens are billed like live usage: this month's included seat tokens first, then the per-million price from prepaid credit. " +
|
|
1784
|
+
"Claude Code deletes local transcripts cleanupPeriodDays (default 30) after their last activity, so an older Claude session survives only if it was captured live or its transcript is still on disk; goneForGood says from when. " +
|
|
1785
|
+
"Sessions already captured live are counted here but skipped by an import. To import, call import_history (dry run first).",
|
|
1786
|
+
inputSchema: obj({
|
|
1787
|
+
source: { type: "string", enum: ["claude-code", "codex", "all"], description: "Which history to read (default all)." },
|
|
1788
|
+
sinceDays: { type: "integer", minimum: 1, maximum: 364, description: "How many days back (default 364, the whole retained year)." },
|
|
1789
|
+
}),
|
|
1790
|
+
async handler(args, ctx) {
|
|
1791
|
+
const source = args.source ?? "all";
|
|
1792
|
+
if (source !== "all" && source !== "claude-code" && source !== "codex") {
|
|
1793
|
+
return { ok: false, error: "bad_input", message: "source must be claude-code, codex or all" };
|
|
1794
|
+
}
|
|
1795
|
+
const sinceDays = args.sinceDays ?? 364;
|
|
1796
|
+
if (typeof sinceDays !== "number" || !Number.isInteger(sinceDays) || sinceDays < 1 || sinceDays > 364) {
|
|
1797
|
+
return { ok: false, error: "bad_input", message: "sinceDays must be 1-364" };
|
|
1798
|
+
}
|
|
1799
|
+
const o = ctx.importOverrides ?? {};
|
|
1800
|
+
const now = o.nowMs ?? Date.now();
|
|
1801
|
+
const estimate = await runEstimate({
|
|
1802
|
+
source,
|
|
1803
|
+
sinceMs: Math.floor((now - sinceDays * 86_400_000) / 86_400_000) * 86_400_000,
|
|
1804
|
+
nowMs: now,
|
|
1805
|
+
claudeDir: o.claudeDir,
|
|
1806
|
+
codexDir: o.codexDir,
|
|
1807
|
+
claudeSettingsPath: o.identityPaths?.claudeSettingsPath ?? ctx.configPathsOverride?.claude,
|
|
1808
|
+
timeLimitMs: IMPORT_TIME_LIMIT_MS,
|
|
1809
|
+
});
|
|
1810
|
+
const pricing = await fetchPricing(endpointsFor(ctx).apiBase, ctx.fetchImpl);
|
|
1811
|
+
const cost = pricing ? priceEstimate(estimate, pricing) : null;
|
|
1812
|
+
const days = estimate.claudeCleanupPeriodDays;
|
|
1813
|
+
return {
|
|
1814
|
+
ok: true,
|
|
1815
|
+
estimate: {
|
|
1816
|
+
...estimate,
|
|
1817
|
+
warnings: estimate.warnings.slice(0, IMPORT_MAX_MESSAGES).map(stripPaths),
|
|
1818
|
+
},
|
|
1819
|
+
pricing,
|
|
1820
|
+
cost,
|
|
1821
|
+
goneForGood: {
|
|
1822
|
+
...(days !== null ? {
|
|
1823
|
+
claudeCleanupPeriodDays: days,
|
|
1824
|
+
claudeCutoffIso: new Date(claudeRetentionCutoffMs(now, days)).toISOString(),
|
|
1825
|
+
claude: `Claude Code deletes transcripts ${days} day(s) after their last activity, so a Claude Code session from before the cutoff survives only if CodeTelemetry captured it live or its transcript is still on disk (those are counted here).`,
|
|
1826
|
+
} : {}),
|
|
1827
|
+
codex: "Codex keeps its rollouts until they are removed.",
|
|
1828
|
+
neverRecovered: `An import never recovers ${IMPORT_NEVER_RECOVERS}.`,
|
|
1829
|
+
},
|
|
1830
|
+
note: "Nothing was sent and no key was used. " +
|
|
1831
|
+
(cost
|
|
1832
|
+
? "cost.uploadCostUsd prices every estimated token before the included seat tokens (a real bill is at most this); cost.monthlyUsdOneSeat is one seat at the last-30-day pace. "
|
|
1833
|
+
: `Prices could not be read; see ${endpointsFor(ctx).apiBase}/estimate. `) +
|
|
1834
|
+
"Show the user the totals by month and the gone-for-good cutoff; to import, call import_history with dryRun true first " +
|
|
1835
|
+
`and sinceDays ${sinceDays} (its default is 30 days, so without it the import covers less than this estimate).`,
|
|
1836
|
+
};
|
|
1837
|
+
},
|
|
1838
|
+
},
|
|
1765
1839
|
{
|
|
1766
1840
|
name: "import_history",
|
|
1767
1841
|
title: "Import past Claude Code / Codex sessions",
|
|
@@ -1771,6 +1845,8 @@ export const TOOLS = [
|
|
|
1771
1845
|
"Sessions already captured live or already imported are skipped; an interrupted import resumes. Each call sends at most maxSessions; while `remaining` > 0, call again. " +
|
|
1772
1846
|
"A persistent workspace restricts imports to its bound project and coding client; it never falls back to a personal or machine-wide destination. " +
|
|
1773
1847
|
"Imported history has tokens, prompts and tool results but no per-request latency, retries, permission decisions or active time. " +
|
|
1848
|
+
"Imported tokens are billed like live usage (this month's included seat tokens first, then the per-million price from prepaid credit): when the server reports billing state, `billing` gives the run's estimated cost and whether the credit covers it, and a real import starts no session the credit cannot cover (stoppedBy budget). estimate_history prices the whole local history without a key. " +
|
|
1849
|
+
"Rows carry the signed-in account's identity as live rows do, shown masked in `identity`; identity false omits it. " +
|
|
1774
1850
|
"content defaults to live: exactly the prompt / tool text the user's live exporters are configured to send (Claude OTEL_LOG_USER_PROMPTS / OTEL_LOG_TOOL_DETAILS, Codex log_user_prompt); none sends no text; all sends prompt text and tool inputs regardless — only with the user's explicit agreement.",
|
|
1775
1851
|
inputSchema: obj({
|
|
1776
1852
|
dryRun: { type: "boolean", description: "Summarize without sending anything (default true)." },
|
|
@@ -1779,6 +1855,7 @@ export const TOOLS = [
|
|
|
1779
1855
|
content: { type: "string", enum: ["none", "live", "all"], description: "Text to include (default live: what the live exporters send)." },
|
|
1780
1856
|
maxSessions: { type: "integer", minimum: 1, maximum: IMPORT_MAX_SESSIONS, description: `Sessions to send in this call (default ${IMPORT_DEFAULT_SESSIONS}).` },
|
|
1781
1857
|
project: { type: "string", minLength: 1, maxLength: 1024, description: "Only sessions whose working directory is this path or under it." },
|
|
1858
|
+
identity: { type: "boolean", description: "Stamp the signed-in account's identity on imported rows, as live exporters do (default true; false omits it)." },
|
|
1782
1859
|
}),
|
|
1783
1860
|
async handler(args, ctx) {
|
|
1784
1861
|
if (!ctx.session.hasKey())
|
|
@@ -1803,6 +1880,9 @@ export const TOOLS = [
|
|
|
1803
1880
|
if (args.project !== undefined && (typeof args.project !== "string" || !args.project.trim() || args.project.length > 1024)) {
|
|
1804
1881
|
return { ok: false, error: "bad_input", message: "project must be a path" };
|
|
1805
1882
|
}
|
|
1883
|
+
if (args.identity !== undefined && typeof args.identity !== "boolean") {
|
|
1884
|
+
return { ok: false, error: "bad_input", message: "identity must be a boolean" };
|
|
1885
|
+
}
|
|
1806
1886
|
const o = ctx.importOverrides ?? {};
|
|
1807
1887
|
const now = o.nowMs ?? Date.now();
|
|
1808
1888
|
const r = await runImport({
|
|
@@ -1811,6 +1891,7 @@ export const TOOLS = [
|
|
|
1811
1891
|
source,
|
|
1812
1892
|
sinceMs: Math.floor((now - sinceDays * 86_400_000) / 86_400_000) * 86_400_000,
|
|
1813
1893
|
project: typeof args.project === "string" ? args.project.trim() : undefined,
|
|
1894
|
+
identity: resolveImportIdentity({ source, disabled: args.identity === false, ...(o.identityPaths ?? {}) }),
|
|
1814
1895
|
content: resolveImportContent(content, {
|
|
1815
1896
|
claudeSettings: ctx.configPathsOverride?.claude ?? CLIENTS.claude.resolveConfigPath({}),
|
|
1816
1897
|
codexConfig: ctx.configPathsOverride?.codex ?? CLIENTS.codex.resolveConfigPath({}),
|
|
@@ -1839,7 +1920,7 @@ export async function callTool(name, args, ctx) {
|
|
|
1839
1920
|
try {
|
|
1840
1921
|
if (!["workspace_context", "bootstrap_workspace"].includes(name))
|
|
1841
1922
|
await restoreWorkspace(ctx);
|
|
1842
|
-
if (ctx.workspace && !["status", "workspace_context", "bootstrap_workspace", "seed_grader_config", "write_grader_config_artifact"].includes(name)) {
|
|
1923
|
+
if (ctx.workspace && !["status", "workspace_context", "bootstrap_workspace", "seed_grader_config", "write_grader_config_artifact", "estimate_history"].includes(name)) {
|
|
1843
1924
|
if (["onboard", "write_local_config"].includes(name))
|
|
1844
1925
|
throw new Error("Use bootstrap_workspace to configure this persistent workspace and its scoped client profile.");
|
|
1845
1926
|
if (["authenticate", "auth_status", "get_ingest_key"].includes(name))
|
package/dist/src/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const MCP_SERVER_NAME = "codetelemetry";
|
|
2
|
-
export declare const MCP_SERVER_VERSION = "0.
|
|
2
|
+
export declare const MCP_SERVER_VERSION = "0.8.0";
|
package/dist/src/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export const MCP_SERVER_NAME = "codetelemetry";
|
|
2
|
-
export const MCP_SERVER_VERSION = "0.
|
|
2
|
+
export const MCP_SERVER_VERSION = "0.8.0";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codetelemetry/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "CodeTelemetry MCP server \u2014 lets a coding agent onboard a user end to end: authenticate (device code), obtain an ingest key, write the Claude Code OTEL config, send a test event, and confirm telemetry landed \u2014 then search, read, interpret and compare the user's own coding sessions, plan the next one, and size tasks, plans and Linear issues from that history. The plaintext key never enters the model's context.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -98,6 +98,14 @@
|
|
|
98
98
|
"types": "./dist/src/client/import/core.d.ts",
|
|
99
99
|
"default": "./dist/src/client/import/core.js"
|
|
100
100
|
},
|
|
101
|
+
"./client/import/estimate": {
|
|
102
|
+
"types": "./dist/src/client/import/estimate.d.ts",
|
|
103
|
+
"default": "./dist/src/client/import/estimate.js"
|
|
104
|
+
},
|
|
105
|
+
"./client/import/identity": {
|
|
106
|
+
"types": "./dist/src/client/import/identity.d.ts",
|
|
107
|
+
"default": "./dist/src/client/import/identity.js"
|
|
108
|
+
},
|
|
101
109
|
"./client/import/ledger": {
|
|
102
110
|
"types": "./dist/src/client/import/ledger.d.ts",
|
|
103
111
|
"default": "./dist/src/client/import/ledger.js"
|