@codetelemetry/connect 0.3.2 → 0.4.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.
@@ -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.7.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.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codetelemetry/connect",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "CodeTelemetry local client and onboarding CLI",
5
5
  "type": "module",
6
6
  "license": "MIT",