@codetelemetry/connect 0.2.0 → 0.3.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 CHANGED
@@ -6,5 +6,21 @@ This package builds directly from the shared public client source, with no runti
6
6
  dependency on the MCP server or its SDK.
7
7
 
8
8
  Run `npx -y @codetelemetry/connect --help`. Kiro collection requires Node 24.
9
- Content and repository-observation telemetry are disabled by default. See the
10
- repository README for privacy, client setup and service removal.
9
+ New `bootstrap` workspace setups enable prompt and tool-content capture by default;
10
+ use `--no-enrich` to opt out. Saved choices survive resumption. Personal onboarding
11
+ and repository-observation defaults are unchanged. See the repository README for
12
+ privacy, client setup and service removal.
13
+
14
+ ## Organization projects
15
+
16
+ Use `npx -y @codetelemetry/connect@0.3.0 join --organization-id tm_example --client codex --project .`
17
+ from the project you choose, or use `--client claude`. Approve the displayed existing
18
+ organization and follow the saved workspace's launch instructions. New connections
19
+ capture prompts and supported tool content; `--no-enrich` opts out on new setup.
20
+ Repeat the same command to resume. Unrelated project configurations are preserved.
21
+
22
+ Optionally run `import --workspace <name> --preview` for a local-only preview, then
23
+ `import --workspace <name> --select 1,2 --confirm` for chosen sessions. Credentials
24
+ and content choices come from the saved workspace; a destination change fails
25
+ before upload. The preview defaults to 30 days, contains at most 100 sessions, and
26
+ expires after 24 hours. Existing import deduplication and resumability still apply.
@@ -19,6 +19,7 @@ export declare function bootstrapWorkspace(options: BootstrapOptions, environmen
19
19
  apiBase?: string;
20
20
  fetchImpl?: FetchLike;
21
21
  timeoutMs?: number;
22
+ connectionOnly?: boolean;
22
23
  }): Promise<{
23
24
  nextAction?: string | undefined;
24
25
  ok: boolean;
package/dist/bootstrap.js CHANGED
@@ -3,7 +3,7 @@ import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { randomUUID } from "node:crypto";
6
- import { bindWorkspace, bindingOf, codexWorkspaceProfilePath, writeCodexWorkspaceProfile, WORKSPACE_MCP_PACKAGE, contextPath, workspaceLock, loadWorkspace, readWorkspaceFile, saveWorkspace, workspaceHome, workspaceName, workspaceOrigin, writeWorkspaceFile, } from "./workspaces.js";
6
+ import { bindWorkspace, bindingOf, codexWorkspaceProfilePath, writeCodexWorkspaceProfile, workspaceCaptureDefault, WORKSPACE_MCP_PACKAGE, contextPath, workspaceLock, loadWorkspace, readWorkspaceFile, saveWorkspace, workspaceHome, workspaceName, workspaceOrigin, writeWorkspaceFile, } from "./workspaces.js";
7
7
  import { resolveEndpoints } from "./config.js";
8
8
  import { verifyScope, confirmLanded } from "./connectivity.js";
9
9
  import { pollOnce } from "./deviceClient.js";
@@ -55,7 +55,7 @@ async function request(base, route, body, fetchImpl, deadline, key, scope) {
55
55
  throw new Error(`Bootstrap request failed (HTTP ${response.status}${typeof result.error === "string" && /^[a-z_]{1,64}$/.test(result.error) ? `, ${result.error}` : ""}); resume after resolving it.`);
56
56
  return result;
57
57
  }
58
- function validatePlan(options) {
58
+ function validatePlan(options, enrichDefault) {
59
59
  workspaceName(options.name);
60
60
  const allowed = new Set([
61
61
  "name",
@@ -136,7 +136,11 @@ function validatePlan(options) {
136
136
  : path.join(repositoryPath, ".claude", "settings.local.json");
137
137
  if (configPath !== allowedConfig)
138
138
  throw new Error("Bootstrap writes only this workspace's named Codex profile or repository-local Claude settings.");
139
- return { ...options, repositoryPath, client, configPath };
139
+ return {
140
+ ...options,
141
+ ...(options.enrich === undefined && enrichDefault !== undefined ? { enrich: enrichDefault } : {}),
142
+ repositoryPath, client, configPath,
143
+ };
140
144
  }
141
145
  export async function bootstrapWorkspace(options, environment = {}) {
142
146
  if (options.reauthorize !== undefined &&
@@ -183,7 +187,8 @@ export async function bootstrapWorkspace(options, environment = {}) {
183
187
  else {
184
188
  if (options.organizationName && fs.existsSync(contextPath(name)))
185
189
  throw new Error("This context already exists. Omit organizationName to configure it, or choose a new context name to create another organization.");
186
- const plan = validatePlan(options);
190
+ const existing = fs.existsSync(contextPath(name)) ? loadWorkspace(name) : null;
191
+ const plan = validatePlan(options, existing ? workspaceCaptureDefault(existing) : true);
187
192
  state = {
188
193
  version: 1,
189
194
  name,
@@ -328,7 +333,7 @@ export async function bootstrapWorkspace(options, environment = {}) {
328
333
  state.steps.scope = "verified";
329
334
  delete state.steps.funding;
330
335
  delete state.steps.telemetry;
331
- bindWorkspace(state.plan.repositoryPath, context);
336
+ bindWorkspace(state.plan.repositoryPath, context, state.plan.client);
332
337
  state.steps.repository = "bound";
333
338
  checkpoint();
334
339
  if (verified.state === "budget_exhausted")
@@ -429,6 +434,7 @@ export async function bootstrapWorkspace(options, environment = {}) {
429
434
  state.probe.key !== keyHash(context.ingestKey) ||
430
435
  Date.now() - state.probe.at > 3_000_000) {
431
436
  const sent = await sendTestEvent({
437
+ context: { project: state.plan.repositoryPath, client: state.plan.client },
432
438
  key: context.ingestKey,
433
439
  ingestEndpoint: context.ingestEndpoint,
434
440
  fetchImpl,
@@ -455,6 +461,10 @@ export async function bootstrapWorkspace(options, environment = {}) {
455
461
  return result("ingestion_pending", `Telemetry verification returned ${landed.state}; resume to check the same probe.`);
456
462
  state.steps.telemetry = "verified";
457
463
  checkpoint();
464
+ if (environment.connectionOnly)
465
+ return result("ready", undefined, {
466
+ scope: context.scope, binding: bindingOf(context), verification: { ingestion: true, liveSession: "not_verified" },
467
+ });
458
468
  if (state.plan.checks?.length) {
459
469
  const checks = [];
460
470
  let config = {};
package/dist/cli.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import fs from "node:fs";
2
+ import { joinOrganization, workspaceProject } from "./join.js";
3
+ import { importWorkspaceHistory } from "./workspaceImport.js";
2
4
  import { bootstrapWorkspace } from "./bootstrap.js";
3
5
  import { listWorkspaces, loadWorkspace, bindWorkspace, bindingOf, findWorkspaceBinding, sameWorkspace, writeCodexWorkspaceProfile } from "./workspaces.js";
4
6
  import { runKiroCommand } from "./kiro/command.js";
@@ -44,6 +46,12 @@ function parse(argv) {
44
46
  const HELP = `codetelemetry-connect — wire Claude Code, OpenAI Codex or pi into CodeTelemetry
45
47
 
46
48
  Usage:
49
+ codetelemetry-connect join --organization-id ID --client claude|codex [--project PATH]
50
+ Connect this project; resume the same command after interruption.
51
+ codetelemetry-connect import --workspace NAME --preview
52
+ Preview this project's past sessions locally; nothing uploads.
53
+ codetelemetry-connect import --workspace NAME --select 1,2 --confirm
54
+ Import selected sessions from the latest preview.
47
55
  codetelemetry-connect <cot_key> [options] Write config, send a test event, confirm it landed
48
56
  codetelemetry-connect run <name> -- <coding-client arguments>
49
57
  Start the coding client with this context and isolated telemetry.
@@ -51,6 +59,7 @@ Usage:
51
59
  codetelemetry-connect bootstrap <name> [--organization-name NAME | --organization-id ID]
52
60
  [--client codex|claude] [--project PATH] [--plan FILE]
53
61
  Resume with just bootstrap <name>. --plan supplies Grader checks/features.
62
+ New setups capture prompts/tool content; --no-enrich opts out.
54
63
  codetelemetry-connect login [options] Authenticate via device code, then do the above
55
64
  codetelemetry-connect doctor [options] Re-test the already-configured key
56
65
  codetelemetry-connect print-config Print the config block (no key)
@@ -394,7 +403,7 @@ async function runImportCommand(positional, flags, endpoints, settingsOpts, clie
394
403
  export async function run(argv) {
395
404
  if (argv[0] === "run") {
396
405
  const context = loadWorkspace(argv[1]);
397
- const binding = findWorkspaceBinding();
406
+ const binding = findWorkspaceBinding(process.cwd(), context.name);
398
407
  if (binding && !sameWorkspace(binding, context))
399
408
  throw new Error("Selected context conflicts with this repository.");
400
409
  const verified = await verifyScope({ key: context.ingestKey, connectivityUrl: resolveEndpoints({ apiBase: context.apiBase }).connectivityUrl, expected: context.scope });
@@ -404,7 +413,9 @@ export async function run(argv) {
404
413
  const args = argv.slice(argv[2] === "--" ? 3 : 2);
405
414
  if (client === "codex")
406
415
  writeCodexWorkspaceProfile(context, context.clientConfig);
407
- const child = spawn(client, client === "codex" ? ["--profile", `codetelemetry-${context.name}`, ...args] : args, { stdio: "inherit", env: { ...process.env, CODETELEMETRY_WORKSPACE: context.name } });
416
+ if (args.some(arg => arg === "-C" || arg === "--cd" || arg.startsWith("--cd=")))
417
+ throw new Error("Run uses the saved project directory; connect a different project before changing it.");
418
+ const child = spawn(client, client === "codex" ? ["--profile", `codetelemetry-${context.name}`, ...args] : args, { cwd: workspaceProject(context), stdio: "inherit", env: { ...process.env, CODETELEMETRY_WORKSPACE: context.name } });
408
419
  return await new Promise((resolve, reject) => { child.once("error", () => reject(new Error("Coding client could not start; check its installation."))); child.once("exit", code => resolve(code ?? 1)); });
409
420
  }
410
421
  const { _, flags } = parse(argv);
@@ -413,6 +424,51 @@ export async function run(argv) {
413
424
  out(HELP);
414
425
  return 0;
415
426
  }
427
+ if (cmd === "join") {
428
+ const rogue = unknownFlag(flags, new Set(["organization-id", "client", "project", "enrich", "reauthorize", "open", "json", "api-base"]));
429
+ if (rogue)
430
+ throw new Error(`Unknown join option --${rogue}.`);
431
+ if (typeof flags["organization-id"] !== "string" || (flags.client !== "claude" && flags.client !== "codex") ||
432
+ (flags.project !== undefined && typeof flags.project !== "string") ||
433
+ (flags.enrich !== undefined && typeof flags.enrich !== "boolean") ||
434
+ (flags.reauthorize !== undefined && typeof flags.reauthorize !== "boolean"))
435
+ throw new Error("Use join --organization-id ID --client claude|codex [--project PATH].");
436
+ const result = await joinOrganization({ organizationId: flags["organization-id"], client: flags.client,
437
+ repositoryPath: typeof flags.project === "string" ? flags.project : undefined,
438
+ enrich: typeof flags.enrich === "boolean" ? flags.enrich : undefined,
439
+ reauthorize: flags.reauthorize === true, apiBase: typeof flags["api-base"] === "string" ? flags["api-base"] : undefined }, { interactive: !flags.json, log: flags.json ? undefined : out,
440
+ open: flags.open !== false && !flags.json ? url => { openBrowser(url); } : undefined });
441
+ if (flags.json)
442
+ out(JSON.stringify(result, null, 2));
443
+ return result.ok ? 0 : 2;
444
+ }
445
+ if (cmd === "import" && flags.workspace !== undefined) {
446
+ const rogue = unknownFlag(flags, new Set(["workspace", "preview", "select", "confirm", "since", "json"]));
447
+ if (rogue)
448
+ throw new Error(`Unknown workspace-import option --${rogue}; destination and content come from the saved workspace.`);
449
+ if (typeof flags.workspace !== "string" || (flags.preview !== undefined && typeof flags.preview !== "boolean") ||
450
+ (flags.confirm !== undefined && typeof flags.confirm !== "boolean") ||
451
+ (flags.select !== undefined && (typeof flags.select !== "string" || !/^\d+(,\d+)*$/.test(flags.select) || flags.select.length > 400)))
452
+ throw new Error("Use import --workspace NAME --preview, or --select 1,2 --confirm.");
453
+ const since = typeof flags.since === "string" ? parseWhen(flags.since, Date.now()) : undefined;
454
+ if (since === null || (flags.since !== undefined && typeof flags.since !== "string"))
455
+ throw new Error("--since takes days, hours, or an ISO date.");
456
+ const result = await importWorkspaceHistory({ name: flags.workspace, preview: flags.preview === true,
457
+ confirm: flags.confirm === true, selections: typeof flags.select === "string" ? flags.select.split(",").map(Number) : undefined,
458
+ sinceMs: since });
459
+ if (flags.json)
460
+ out(JSON.stringify(result, null, 2));
461
+ else if (result.previewSessions) {
462
+ out(`Local preview for ${flags.workspace}: ${result.previewSessions.length} sessions. Nothing uploaded.`);
463
+ result.previewSessions.forEach((session, i) => out(`${i + 1}. ${session.source} ${session.sessionId} · ${new Date(session.endMs).toISOString()} · ${session.events} events`));
464
+ if (result.remaining)
465
+ out(`${result.remaining} additional sessions remain; narrow --since for another preview.`);
466
+ out(`Import selected numbers: npx -y @codetelemetry/connect@0.3.0 import --workspace ${flags.workspace} --select 1,2 --confirm`);
467
+ }
468
+ else
469
+ out(`Imported ${result.totals.sessions} sessions; ${result.remaining} remain. ${result.errors.slice(0, 3).join(" ")}`);
470
+ return result.ok ? 0 : 1;
471
+ }
416
472
  if (cmd === "workspace") {
417
473
  if (_[1] === "list") {
418
474
  out(JSON.stringify(listWorkspaces(), null, 2));
@@ -442,6 +498,11 @@ export async function run(argv) {
442
498
  options.organizationId = flags["organization-id"];
443
499
  if (typeof flags.client === "string")
444
500
  options.client = flags.client;
501
+ if (flags.enrich !== undefined) {
502
+ if (typeof flags.enrich !== "boolean")
503
+ throw new Error("--enrich/--no-enrich must be a boolean flag.");
504
+ options.enrich = flags.enrich;
505
+ }
445
506
  const result = await bootstrapWorkspace(options, { apiBase: typeof flags["api-base"] === "string" ? flags["api-base"] : undefined });
446
507
  out(JSON.stringify(result, null, 2));
447
508
  if (result.status === "authorization_required" && flags.open !== false && !flags.json)
@@ -33,6 +33,14 @@ export type ImportSourceSummary = {
33
33
  };
34
34
  export type StopReason = "budget" | "auth" | "busy" | "time_limit" | "status_unavailable";
35
35
  export type ImportRunResult = {
36
+ previewSessions?: Array<{
37
+ source: ImportSource;
38
+ sessionId: string;
39
+ planId: string;
40
+ startMs: number;
41
+ endMs: number;
42
+ events: number;
43
+ }>;
36
44
  ok: boolean;
37
45
  run: string;
38
46
  dryRun: boolean;
@@ -15,6 +15,9 @@ export type ImportRunOptions = {
15
15
  email?: string;
16
16
  content?: Partial<ContentBySource>;
17
17
  dryRun?: boolean;
18
+ previewOnly?: boolean;
19
+ selectedPlans?: Readonly<Record<string, string>>;
20
+ boundedDiscovery?: boolean;
18
21
  maxSessions?: number;
19
22
  ratePerMinute?: number;
20
23
  timeLimitMs?: number;
@@ -2,8 +2,8 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { assertKey, keyHash, mask } from "../keys.js";
3
3
  import { resolveEndpoints } from "../config.js";
4
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";
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";
7
7
  import { LedgerStore, resolveLedgerPath } from "./ledger.js";
8
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
9
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
@@ -13,7 +13,7 @@ export async function runImport(opts) {
13
13
  const endpoints = resolveEndpoints(opts.endpoints);
14
14
  const now = opts.nowMs ?? Date.now();
15
15
  const clock = () => (opts.nowMs === undefined ? Date.now() : opts.nowMs);
16
- const dryRun = !!opts.dryRun;
16
+ const dryRun = !!opts.dryRun || !!opts.previewOnly;
17
17
  const warnings = [];
18
18
  const content = contentOrDefault(opts.content);
19
19
  const window = resolveWindow(now, opts.sinceMs, opts.untilMs);
@@ -26,17 +26,21 @@ export async function runImport(opts) {
26
26
  const wantCodex = !opts.source || opts.source === "all" || opts.source === "codex";
27
27
  const summaries = new Map();
28
28
  const found = [];
29
+ const boundedSelection = Boolean(opts.previewOnly || opts.selectedPlans || opts.boundedDiscovery);
30
+ const scanBudget = boundedSelection ? { remainingEntries: 10_000, deadline: Date.now() + 120_000 } : undefined;
31
+ const readBudget = scanBudget ? { remainingBytes: 128 * 1024 * 1024, deadline: scanBudget.deadline } : undefined;
32
+ const parseLimits = scanBudget ? { deadline: scanBudget.deadline, maxBytes: 64 * 1024 * 1024, budget: readBudget } : undefined;
29
33
  if (wantClaude) {
30
34
  const s = emptySummary("claude-code");
31
35
  summaries.set("claude-code", s);
32
- const files = scanClaudeSessions(opts.claudeDir ?? defaultClaudeProjectsDir());
36
+ const files = scanClaudeSessions(opts.claudeDir ?? defaultClaudeProjectsDir(), scanBudget);
33
37
  s.filesFound = files.length;
34
38
  found.push(...files);
35
39
  }
36
40
  if (wantCodex) {
37
41
  const s = emptySummary("codex");
38
42
  summaries.set("codex", s);
39
- const files = scanCodexSessions(opts.codexDir ?? defaultCodexSessionsDir());
43
+ const files = scanCodexSessions(opts.codexDir ?? defaultCodexSessionsDir(), scanBudget);
40
44
  s.filesFound = files.length;
41
45
  found.push(...files);
42
46
  }
@@ -52,6 +56,8 @@ export async function runImport(opts) {
52
56
  sha256Hex,
53
57
  };
54
58
  for (const c of found) {
59
+ if ((opts.previewOnly || opts.selectedPlans) && clock() - now > 120_000)
60
+ throw new Error("History scan reached its two-minute bound; narrow the date window and preview again.");
55
61
  const s = summaries.get(c.source);
56
62
  if (c.mtimeMs < window.sinceMs) {
57
63
  bump(s, "older");
@@ -61,7 +67,14 @@ export async function runImport(opts) {
61
67
  bump(s, "active");
62
68
  continue;
63
69
  }
64
- const parsed = await parseCandidate(c, content[c.source]);
70
+ if (readBudget && opts.project) {
71
+ const cwd = candidateProjectDirectory(c, readBudget);
72
+ if (cwd && !underProject(cwd, opts.project, prepareOpts.caseInsensitivePaths)) {
73
+ bump(s, "filtered");
74
+ continue;
75
+ }
76
+ }
77
+ const parsed = await parseCandidate(c, content[c.source], parseLimits);
65
78
  if (!parsed.ok) {
66
79
  bump(s, parsed.reason);
67
80
  warnings.push(`${c.source} ${c.file}: ${parsed.detail}; not imported`);
@@ -73,13 +86,15 @@ export async function runImport(opts) {
73
86
  }
74
87
  s.sessionsParsed++;
75
88
  const sessionKey = sessionKeyOf(parsed.session.source, parsed.session.sessionId);
89
+ if (opts.selectedPlans && !Object.prototype.hasOwnProperty.call(opts.selectedPlans, sessionKey))
90
+ continue;
76
91
  const done = ledger.get(hash, sessionKey);
77
92
  if (done && done.state === "complete" && done.fileSig === c.fileSig) {
78
93
  bump(s, "ledger");
79
94
  continue;
80
95
  }
81
96
  const reload = async () => {
82
- const again = await parseCandidate(c, content[c.source]);
97
+ const again = await parseCandidate(c, content[c.source], parseLimits);
83
98
  return again.ok ? again.session : null;
84
99
  };
85
100
  const p = await prepareSession(parsed.session, c.fileSig, reload, prepareOpts);
@@ -87,6 +102,8 @@ export async function runImport(opts) {
87
102
  bump(s, p);
88
103
  continue;
89
104
  }
105
+ if (opts.selectedPlans && opts.selectedPlans[sessionKey] !== p.plan.id)
106
+ throw new Error("A selected session changed since preview. Preview it again before importing.");
90
107
  if (seen.has(sessionKey)) {
91
108
  warnings.push(`${sessionKey} appears in more than one file; only the first is imported`);
92
109
  continue;
@@ -95,6 +112,19 @@ export async function runImport(opts) {
95
112
  s.candidates++;
96
113
  prepared.push(p);
97
114
  }
115
+ if (opts.previewOnly) {
116
+ const selected = prepared.sort((a, b) => b.endMs - a.endMs).slice(0, 100);
117
+ return {
118
+ ok: true, run: randomUUID(), dryRun: true, key: { masked: mask(key), keyHash: hash },
119
+ window: { sinceIso: new Date(window.sinceMs).toISOString(), untilIso: new Date(window.untilMs).toISOString(), clamped: window.clamped },
120
+ content, sources: [...summaries.values()],
121
+ totals: { sessions: selected.length, events: selected.reduce((n, p) => n + p.plan.events, 0),
122
+ metricPoints: selected.reduce((n, p) => n + p.plan.metricPoints, 0) },
123
+ remaining: Math.max(0, prepared.length - selected.length), stoppedBy: null, cleanup: [], warnings, errors: [],
124
+ previewSessions: selected.map(p => ({ source: p.source, sessionId: p.sessionId, planId: p.plan.id,
125
+ startMs: p.startMs, endMs: p.endMs, events: p.plan.events })),
126
+ };
127
+ }
98
128
  try {
99
129
  return await importPrepared(prepared, {
100
130
  ...prepareOpts,
@@ -11,8 +11,19 @@ export type SessionCandidate = {
11
11
  };
12
12
  export declare function defaultClaudeProjectsDir(home?: string): string;
13
13
  export declare function defaultCodexSessionsDir(home?: string, env?: NodeJS.ProcessEnv): string;
14
- export declare function scanClaudeSessions(projectsDir: string): SessionCandidate[];
15
- export declare function scanCodexSessions(sessionsDir: string): SessionCandidate[];
14
+ export type ScanBudget = {
15
+ remainingEntries: number;
16
+ deadline: number;
17
+ };
18
+ export type HistoryReadBudget = {
19
+ remainingBytes: number;
20
+ deadline: number;
21
+ };
22
+ export declare class HistoryReadBudgetError extends Error {
23
+ }
24
+ export declare function candidateProjectDirectory(c: SessionCandidate, budget: HistoryReadBudget): string | null;
25
+ export declare function scanClaudeSessions(projectsDir: string, budget?: ScanBudget): SessionCandidate[];
26
+ export declare function scanCodexSessions(sessionsDir: string, budget?: ScanBudget): SessionCandidate[];
16
27
  export type ParseOutcome = {
17
28
  ok: true;
18
29
  session: ImportedSession | null;
@@ -21,4 +32,8 @@ export type ParseOutcome = {
21
32
  reason: "too_large" | "too_many_events" | "unreadable";
22
33
  detail: string;
23
34
  };
24
- export declare function parseCandidate(c: SessionCandidate, keep: ContentPolicy): Promise<ParseOutcome>;
35
+ export declare function parseCandidate(c: SessionCandidate, keep: ContentPolicy, limits?: {
36
+ deadline: number;
37
+ maxBytes: number;
38
+ budget?: HistoryReadBudget;
39
+ }): Promise<ParseOutcome>;
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import readline from "node:readline";
5
+ import { StringDecoder } from "node:string_decoder";
5
6
  import { ClaudeSessionAccumulator } from "./claudeCodeText.js";
6
7
  import { CodexSessionAccumulator, codexSessionIdFromName } from "./codexText.js";
7
8
  export const MAX_SESSION_FILE_BYTES = 512 * 1024 * 1024;
@@ -22,7 +23,80 @@ const statOrNull = (p) => {
22
23
  return null;
23
24
  }
24
25
  };
25
- const readDir = (dir) => {
26
+ export class HistoryReadBudgetError extends Error {
27
+ }
28
+ export function candidateProjectDirectory(c, budget) {
29
+ const decoder = new StringDecoder("utf8");
30
+ const buffer = Buffer.allocUnsafe(4096);
31
+ let pending = "", consumed = 0;
32
+ const cwdOf = (line) => {
33
+ try {
34
+ const row = JSON.parse(line);
35
+ const cwd = c.source === "claude-code" ? row?.cwd
36
+ : row?.type === "session_meta" || row?.type === "turn_context" ? row?.payload?.cwd : null;
37
+ return typeof cwd === "string" && cwd ? cwd : null;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ };
43
+ let fd;
44
+ try {
45
+ fd = fs.openSync(c.file, "r");
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ try {
51
+ while (consumed < Math.min(c.bytes, 256 * 1024)) {
52
+ if (Date.now() >= budget.deadline)
53
+ throw new HistoryReadBudgetError("History discovery reached its time bound; narrow --since and preview again.");
54
+ if (budget.remainingBytes <= 0)
55
+ throw new HistoryReadBudgetError("History preview reached its 128 MiB read bound; narrow --since and preview again.");
56
+ const take = Math.min(buffer.length, c.bytes - consumed, 256 * 1024 - consumed, budget.remainingBytes);
57
+ const count = fs.readSync(fd, buffer, 0, take, consumed);
58
+ if (!count)
59
+ break;
60
+ consumed += count;
61
+ budget.remainingBytes -= count;
62
+ pending += decoder.write(buffer.subarray(0, count));
63
+ let end;
64
+ while ((end = pending.indexOf("\n")) >= 0) {
65
+ const cwd = cwdOf(pending.slice(0, end));
66
+ pending = pending.slice(end + 1);
67
+ if (cwd)
68
+ return cwd;
69
+ }
70
+ }
71
+ return cwdOf(pending + decoder.end());
72
+ }
73
+ finally {
74
+ fs.closeSync(fd);
75
+ }
76
+ }
77
+ const readDir = (dir, budget) => {
78
+ if (budget) {
79
+ let handle;
80
+ try {
81
+ handle = fs.opendirSync(dir);
82
+ }
83
+ catch {
84
+ return [];
85
+ }
86
+ const rows = [];
87
+ try {
88
+ let entry;
89
+ while ((entry = handle.readSync())) {
90
+ if (--budget.remainingEntries < 0 || Date.now() >= budget.deadline)
91
+ throw new Error("History discovery reached its file/time bound; narrow the local history directory and preview again.");
92
+ rows.push(entry);
93
+ }
94
+ }
95
+ finally {
96
+ handle.closeSync();
97
+ }
98
+ return rows;
99
+ }
26
100
  try {
27
101
  return fs.readdirSync(dir, { withFileTypes: true });
28
102
  }
@@ -47,17 +121,17 @@ function describe(source, file, extraFiles) {
47
121
  }
48
122
  return { source, file, extraFiles: kept, mtimeMs, bytes, fileSig: `${bytes}:${mtimeMs}:${kept.length}` };
49
123
  }
50
- export function scanClaudeSessions(projectsDir) {
124
+ export function scanClaudeSessions(projectsDir, budget) {
51
125
  const out = [];
52
- for (const project of readDir(projectsDir)) {
126
+ for (const project of readDir(projectsDir, budget)) {
53
127
  if (!project.isDirectory())
54
128
  continue;
55
129
  const dir = path.join(projectsDir, project.name);
56
- for (const entry of readDir(dir)) {
130
+ for (const entry of readDir(dir, budget)) {
57
131
  if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
58
132
  continue;
59
133
  const sessionDir = path.join(dir, entry.name.slice(0, -".jsonl".length), "subagents");
60
- const extras = readDir(sessionDir)
134
+ const extras = readDir(sessionDir, budget)
61
135
  .filter((e) => e.isFile() && e.name.endsWith(".jsonl"))
62
136
  .map((e) => path.join(sessionDir, e.name))
63
137
  .sort()
@@ -69,12 +143,12 @@ export function scanClaudeSessions(projectsDir) {
69
143
  }
70
144
  return out.sort((a, b) => a.file.localeCompare(b.file));
71
145
  }
72
- export function scanCodexSessions(sessionsDir) {
146
+ export function scanCodexSessions(sessionsDir, budget) {
73
147
  const out = [];
74
148
  const walk = (dir, depth) => {
75
149
  if (depth > 4)
76
150
  return;
77
- for (const e of readDir(dir)) {
151
+ for (const e of readDir(dir, budget)) {
78
152
  const full = path.join(dir, e.name);
79
153
  if (e.isDirectory())
80
154
  walk(full, depth + 1);
@@ -88,31 +162,51 @@ export function scanCodexSessions(sessionsDir) {
88
162
  walk(sessionsDir, 0);
89
163
  return out.sort((a, b) => a.file.localeCompare(b.file));
90
164
  }
91
- async function feedLines(file, onLine) {
92
- const stream = fs.createReadStream(file, { encoding: "utf8" });
165
+ async function feedLines(file, onLine, remaining, limits) {
166
+ const stream = fs.createReadStream(file, { highWaterMark: 16 * 1024,
167
+ end: Math.min(remaining.bytes, limits?.budget?.remainingBytes ?? remaining.bytes) });
168
+ stream.on("data", (chunk) => {
169
+ const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk.length;
170
+ remaining.bytes -= bytes;
171
+ if (limits?.budget)
172
+ limits.budget.remainingBytes -= bytes;
173
+ if (limits?.budget && limits.budget.remainingBytes < 0)
174
+ stream.destroy(new HistoryReadBudgetError("History preview reached its 128 MiB read bound; narrow --since and preview again."));
175
+ else if (remaining.bytes < 0)
176
+ stream.destroy(new Error("Session grew beyond its byte bound; preview it again."));
177
+ else if (limits && Date.now() >= limits.deadline)
178
+ stream.destroy(new HistoryReadBudgetError("History parsing reached its time bound; narrow --since and preview again."));
179
+ });
93
180
  const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
94
181
  try {
95
- for await (const line of rl)
182
+ for await (const line of rl) {
183
+ if (limits && Date.now() >= limits.deadline)
184
+ throw new HistoryReadBudgetError("History parsing reached its time bound.");
96
185
  onLine(line);
186
+ }
97
187
  }
98
188
  finally {
99
189
  rl.close();
100
190
  stream.destroy();
101
191
  }
102
192
  }
103
- export async function parseCandidate(c, keep) {
104
- if (c.bytes > MAX_SESSION_FILE_BYTES) {
105
- return { ok: false, reason: "too_large", detail: `${c.bytes} bytes exceeds the ${MAX_SESSION_FILE_BYTES}-byte session bound` };
193
+ export async function parseCandidate(c, keep, limits) {
194
+ const byteLimit = Math.min(MAX_SESSION_FILE_BYTES, limits?.maxBytes ?? MAX_SESSION_FILE_BYTES);
195
+ if (c.bytes > byteLimit) {
196
+ return { ok: false, reason: "too_large", detail: `${c.bytes} bytes exceeds the ${byteLimit}-byte session bound` };
106
197
  }
107
198
  const acc = c.source === "claude-code" ? new ClaudeSessionAccumulator({ keep }) : new CodexSessionAccumulator({ keep });
199
+ const remaining = { bytes: byteLimit };
108
200
  try {
109
201
  for (const f of [c.file, ...c.extraFiles]) {
110
- await feedLines(f, (line) => acc.line(line));
202
+ await feedLines(f, (line) => acc.line(line), remaining, limits);
111
203
  if (acc.overflowed)
112
204
  break;
113
205
  }
114
206
  }
115
207
  catch (err) {
208
+ if (err instanceof HistoryReadBudgetError)
209
+ throw err;
116
210
  return { ok: false, reason: "unreadable", detail: err instanceof Error ? err.message : String(err) };
117
211
  }
118
212
  if (acc.overflowed)
package/dist/join.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { type BootstrapOptions } from "./bootstrap.ts";
2
+ import { type WorkspaceContext } from "./workspaces.ts";
3
+ import type { FetchLike } from "./otlp.ts";
4
+ export type JoinOptions = {
5
+ organizationId: string;
6
+ repositoryPath?: string;
7
+ client: "claude" | "codex";
8
+ enrich?: boolean;
9
+ reauthorize?: boolean;
10
+ apiBase?: string;
11
+ };
12
+ export declare function joinPlan(options: JoinOptions): BootstrapOptions;
13
+ export declare function workspaceProject(context: WorkspaceContext): string;
14
+ export declare function joinOrganization(options: JoinOptions, environment?: {
15
+ fetchImpl?: FetchLike;
16
+ interactive?: boolean;
17
+ open?: (url: string) => void;
18
+ log?: (message: string) => void;
19
+ timeoutMs?: number;
20
+ sleep?: (ms: number) => Promise<void>;
21
+ }): Promise<{
22
+ nextAction?: string | undefined;
23
+ ok: boolean;
24
+ status: string;
25
+ workspace: string;
26
+ steps: Record<string, string>;
27
+ } | {
28
+ progressUrl: string;
29
+ liveSessionVerified: boolean;
30
+ nextAction?: string | undefined;
31
+ ok: boolean;
32
+ status: string;
33
+ workspace: string;
34
+ steps: Record<string, string>;
35
+ }>;
package/dist/join.js ADDED
@@ -0,0 +1,99 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { createHash } from "node:crypto";
5
+ import { bootstrapWorkspace } from "./bootstrap.js";
6
+ import { contextPath, findWorkspaceBinding, loadWorkspace, readWorkspaceFile, sameWorkspace, workspaceHome, workspaceOrigin } from "./workspaces.js";
7
+ export function joinPlan(options) {
8
+ if (!/^tm_[a-zA-Z0-9_-]{1,128}$/.test(options.organizationId))
9
+ throw new Error("Choose a valid existing organization ID.");
10
+ if (options.client !== "claude" && options.client !== "codex")
11
+ throw new Error("Choose Claude Code or Codex.");
12
+ const repositoryPath = fs.realpathSync(options.repositoryPath ?? process.cwd());
13
+ if (!fs.statSync(repositoryPath).isDirectory() || repositoryPath === os.homedir() || repositoryPath === path.parse(repositoryPath).root)
14
+ throw new Error("Choose a project directory, rather than your home or filesystem root.");
15
+ const binding = findWorkspaceBinding(repositoryPath);
16
+ if (binding && (binding.scope.teamId !== options.organizationId ||
17
+ (options.apiBase && binding.apiBase !== workspaceOrigin(options.apiBase))))
18
+ throw new Error("This project is connected to another destination; its connection was preserved.");
19
+ const digest = createHash("sha256").update(JSON.stringify([options.organizationId, repositoryPath, options.client])).digest("hex").slice(0, 12);
20
+ const slug = path.basename(repositoryPath).toLowerCase().replace(/[^a-z0-9_-]/g, "-").slice(0, 36) || "project";
21
+ let name = `project-${slug}-${digest}`;
22
+ if (binding) {
23
+ const context = loadWorkspace(binding.name);
24
+ if (context.clientConfig?.client === options.client)
25
+ name = binding.name;
26
+ }
27
+ const selected = findWorkspaceBinding(repositoryPath, name);
28
+ if (selected?.name === name) {
29
+ const saved = loadWorkspace(name);
30
+ if (!sameWorkspace(saved, selected))
31
+ throw new Error("The project's saved destination has changed.");
32
+ }
33
+ const checkpoint = path.join(workspaceHome(), `${name}.bootstrap.json`);
34
+ if (fs.existsSync(checkpoint)) {
35
+ const saved = readWorkspaceFile(checkpoint);
36
+ if (saved.plan?.repositoryPath !== repositoryPath || saved.plan?.client !== options.client ||
37
+ (saved.plan.organizationId && saved.plan.organizationId !== options.organizationId))
38
+ throw new Error("The saved connection does not match this project and coding tool.");
39
+ if (options.enrich !== undefined && saved.plan.enrich !== options.enrich)
40
+ throw new Error("This connection has a saved capture choice. Resume without a capture flag to preserve it.");
41
+ return { name, ...(options.reauthorize ? { reauthorize: true } : {}) };
42
+ }
43
+ if (fs.existsSync(contextPath(name)) && loadWorkspace(name).scope.teamId !== options.organizationId)
44
+ throw new Error("Saved connection belongs to another organization.");
45
+ return { name, organizationId: options.organizationId, repositoryPath, client: options.client,
46
+ repositoryObservation: true, ...(options.enrich === undefined ? {} : { enrich: options.enrich }),
47
+ ...(options.reauthorize ? { reauthorize: true } : {}) };
48
+ }
49
+ export function workspaceProject(context) {
50
+ const checkpoint = path.join(workspaceHome(), `${context.name}.bootstrap.json`);
51
+ const state = readWorkspaceFile(checkpoint);
52
+ if (typeof state.plan?.repositoryPath !== "string")
53
+ throw new Error("This workspace has no saved project; connect it with join first.");
54
+ const project = fs.realpathSync(state.plan.repositoryPath);
55
+ const binding = findWorkspaceBinding(project, context.name);
56
+ if (!binding || !sameWorkspace(binding, context))
57
+ throw new Error("The saved project binding differs from this workspace.");
58
+ return project;
59
+ }
60
+ export async function joinOrganization(options, environment = {}) {
61
+ let plan = joinPlan(options);
62
+ const deadline = Date.now() + Math.min(600_000, environment.timeoutMs ?? 600_000);
63
+ const since = Date.now();
64
+ let opened = "";
65
+ let lastState = "";
66
+ while (true) {
67
+ const result = await bootstrapWorkspace(plan, { apiBase: options.apiBase, fetchImpl: environment.fetchImpl, connectionOnly: true,
68
+ timeoutMs: Math.min(45_000, Math.max(1, deadline - Date.now())) });
69
+ plan = { name: plan.name };
70
+ const authorizationUrl = result.authorizationUrl;
71
+ if (authorizationUrl && authorizationUrl !== opened) {
72
+ opened = authorizationUrl;
73
+ environment.log?.(`Approve your connection to ${options.organizationId}:\n${authorizationUrl}`);
74
+ environment.open?.(authorizationUrl);
75
+ }
76
+ if (result.status !== lastState) {
77
+ lastState = result.status;
78
+ if (result.status.startsWith("authorization_"))
79
+ environment.log?.("Waiting for browser approval. You can interrupt and run the same join command to resume.");
80
+ else if (result.nextAction)
81
+ environment.log?.(result.nextAction);
82
+ }
83
+ if (result.status === "ready") {
84
+ const context = loadWorkspace(plan.name);
85
+ if (context.scope.teamId !== options.organizationId)
86
+ throw new Error("Connected destination differs from the requested organization.");
87
+ const project = workspaceProject(context);
88
+ const progress = new URL(`/app/teams/${encodeURIComponent(options.organizationId)}/connect`, context.apiBase);
89
+ progress.search = new URLSearchParams({ client: options.client, project, workspace: context.name, since: String(since) }).toString();
90
+ environment.log?.(`Connection test received. Saved workspace: ${context.name}\n${result.steps.clientLaunch}\nRecord a real session to finish verification:\n${progress}`);
91
+ environment.open?.(String(progress));
92
+ return { ...result, progressUrl: String(progress), liveSessionVerified: false };
93
+ }
94
+ if (!environment.interactive || Date.now() >= deadline ||
95
+ !["authorization_required", "authorization_pending", "ingestion_pending"].includes(result.status))
96
+ return result;
97
+ await (environment.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))))(Math.min(5_000, Math.max(1, deadline - Date.now())));
98
+ }
99
+ }
package/dist/otlp.d.ts CHANGED
@@ -2,13 +2,20 @@ export type FetchLike = typeof fetch;
2
2
  export declare const PROBE_ATTR = "codetelemetry.probe.id";
3
3
  export declare const PROBE_EVENT = "codetelemetry_probe";
4
4
  export declare const PROBE_SERVICE = "codetelemetry-connect";
5
- export declare function buildProbeLog(probeId: string, nowMs?: number): unknown;
5
+ export declare function buildProbeLog(probeId: string, nowMs?: number, context?: {
6
+ project: string;
7
+ client: "claude" | "codex";
8
+ }): unknown;
6
9
  export type SendTestResult = {
7
10
  probeId: string;
8
11
  httpStatus: number;
9
12
  ok: boolean;
10
13
  };
11
14
  export type SendTestOptions = {
15
+ context?: {
16
+ project: string;
17
+ client: "claude" | "codex";
18
+ };
12
19
  key: string;
13
20
  ingestEndpoint: string;
14
21
  probeId?: string;
package/dist/otlp.js CHANGED
@@ -3,7 +3,7 @@ import { assertKey } from "./keys.js";
3
3
  export const PROBE_ATTR = "codetelemetry.probe.id";
4
4
  export const PROBE_EVENT = "codetelemetry_probe";
5
5
  export const PROBE_SERVICE = "codetelemetry-connect";
6
- export function buildProbeLog(probeId, nowMs = Date.now()) {
6
+ export function buildProbeLog(probeId, nowMs = Date.now(), context) {
7
7
  const nano = String(BigInt(Math.floor(nowMs)) * 1000000n);
8
8
  return {
9
9
  resourceLogs: [
@@ -11,6 +11,7 @@ export function buildProbeLog(probeId, nowMs = Date.now()) {
11
11
  resource: {
12
12
  attributes: [
13
13
  { key: "service.name", value: { stringValue: PROBE_SERVICE } },
14
+ ...(context ? [{ key: "project.path", value: { stringValue: context.project } }] : []),
14
15
  ],
15
16
  },
16
17
  scopeLogs: [
@@ -26,6 +27,7 @@ export function buildProbeLog(probeId, nowMs = Date.now()) {
26
27
  attributes: [
27
28
  { key: "event.name", value: { stringValue: PROBE_EVENT } },
28
29
  { key: PROBE_ATTR, value: { stringValue: probeId } },
30
+ ...(context ? [{ key: "codetelemetry.probe.client", value: { stringValue: context.client } }] : []),
29
31
  ],
30
32
  },
31
33
  ],
@@ -49,7 +51,7 @@ export async function sendTestEvent(opts) {
49
51
  "content-type": "application/json",
50
52
  authorization: `Bearer ${key}`,
51
53
  },
52
- body: JSON.stringify(buildProbeLog(probeId)),
54
+ body: JSON.stringify(buildProbeLog(probeId, Date.now(), opts.context)),
53
55
  signal: ac.signal,
54
56
  });
55
57
  return { probeId, httpStatus: res.status, ok: res.status >= 200 && res.status < 300 };
@@ -0,0 +1,9 @@
1
+ import { type ImportRunOptions } from "./import/run.ts";
2
+ import type { ImportRunResult } from "./import/core.ts";
3
+ export declare function importWorkspaceHistory(options: {
4
+ name: string;
5
+ preview?: boolean;
6
+ confirm?: boolean;
7
+ selections?: number[];
8
+ sinceMs?: number;
9
+ }, deps?: Pick<ImportRunOptions, "fetchImpl" | "claudeDir" | "codexDir" | "ledgerPath" | "nowMs" | "sleep">): Promise<ImportRunResult>;
@@ -0,0 +1,56 @@
1
+ import path from "node:path";
2
+ import { loadWorkspace, workspaceHome, writeWorkspaceFile, readWorkspaceFile, workspaceCaptureDefault } from "./workspaces.js";
3
+ import { workspaceProject } from "./join.js";
4
+ import { keyHash } from "./keys.js";
5
+ import { verifyScope } from "./connectivity.js";
6
+ import { resolveEndpoints } from "./config.js";
7
+ import { runImport } from "./import/run.js";
8
+ import { sessionKeyOf } from "./import/model.js";
9
+ export async function importWorkspaceHistory(options, deps = {}) {
10
+ const context = loadWorkspace(options.name);
11
+ if (!context.scope.teamId || !context.clientConfig)
12
+ throw new Error("Choose a connected organization workspace.");
13
+ const project = workspaceProject(context);
14
+ const endpoints = { apiBase: context.apiBase, ingestEndpoint: context.ingestEndpoint };
15
+ const expected = context.scope;
16
+ const previewFile = path.join(workspaceHome(), `${context.name}.import-preview.json`);
17
+ const source = context.clientConfig.client === "claude" ? "claude-code" : "codex";
18
+ if (options.preview) {
19
+ if (options.confirm || options.selections)
20
+ throw new Error("Preview and import confirmation are separate actions.");
21
+ const capture = workspaceCaptureDefault(context);
22
+ const content = { prompts: capture, toolDetails: capture };
23
+ const result = await runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
24
+ sinceMs: options.sinceMs, content: { "claude-code": content, codex: content }, previewOnly: true });
25
+ const preview = { version: 1, workspace: context.name, keyHash: keyHash(context.ingestKey),
26
+ project, createdAt: Date.now(), scope: expected, window: result.window, content: result.content,
27
+ sessions: result.previewSessions ?? [] };
28
+ writeWorkspaceFile(previewFile, preview);
29
+ return result;
30
+ }
31
+ if (!options.confirm || !options.selections?.length || options.selections.length > 100 ||
32
+ options.sinceMs !== undefined)
33
+ throw new Error("Preview first, then use --select 1,2,… --confirm to import only those sessions.");
34
+ const preview = readWorkspaceFile(previewFile);
35
+ if (preview.version !== 1 || preview.workspace !== context.name || preview.keyHash !== keyHash(context.ingestKey) ||
36
+ preview.project !== project || JSON.stringify(preview.scope) !== JSON.stringify(expected) ||
37
+ !Number.isFinite(preview.createdAt) || Date.now() - preview.createdAt > 24 * 60 * 60_000 ||
38
+ !Array.isArray(preview.sessions) || preview.sessions.length > 100)
39
+ throw new Error("The preview expired or its destination changed. Preview again.");
40
+ const selectedPlans = Object.create(null);
41
+ for (const index of options.selections) {
42
+ if (!Number.isInteger(index) || index < 1 || index > preview.sessions.length)
43
+ throw new Error("Choose session numbers from the latest preview.");
44
+ const item = preview.sessions[index - 1];
45
+ if ((item.source !== "codex" && item.source !== "claude-code") || typeof item.sessionId !== "string" || item.sessionId.length > 512 || !/^[a-f0-9]{32}$/.test(item.planId))
46
+ throw new Error("Invalid preview; generate it again.");
47
+ selectedPlans[sessionKeyOf(item.source, item.sessionId)] = item.planId;
48
+ }
49
+ const verified = await verifyScope({ key: context.ingestKey, expected,
50
+ connectivityUrl: resolveEndpoints(endpoints).connectivityUrl, fetchImpl: deps.fetchImpl });
51
+ if (verified.state !== "scope_verified")
52
+ throw new Error(`Workspace is unavailable: ${verified.state}. No history was uploaded.`);
53
+ return runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
54
+ sinceMs: Date.parse(preview.window.sinceIso), untilMs: Date.parse(preview.window.untilIso),
55
+ content: preview.content, selectedPlans, maxSessions: 100, timeLimitMs: 120_000 });
56
+ }
@@ -1,5 +1,5 @@
1
1
  import type { KeyScope } from "./connectivity.ts";
2
- export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.4.0";
2
+ export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.5.0";
3
3
  export declare const MAX_WORKSPACE_BYTES: number;
4
4
  export declare const MAX_WORKSPACES = 64;
5
5
  export type WorkspaceBinding = {
@@ -28,6 +28,7 @@ export declare function readWorkspaceFile(file: string, privateFile?: boolean):
28
28
  export declare function writeWorkspaceText(file: string, data: string): void;
29
29
  export declare function writeWorkspaceFile(file: string, value: unknown): void;
30
30
  export declare function codexWorkspaceProfilePath(name: string): string;
31
+ export declare function workspaceCaptureDefault(context: WorkspaceContext): boolean;
31
32
  export declare function writeCodexWorkspaceProfile(context: WorkspaceContext, options?: {
32
33
  enrich?: boolean;
33
34
  repositoryObservation?: boolean;
@@ -40,5 +41,5 @@ export declare function contextPath(name: string): string;
40
41
  export declare function loadWorkspace(name: string): WorkspaceContext;
41
42
  export declare function saveWorkspace(context: WorkspaceContext): void;
42
43
  export declare function listWorkspaces(): WorkspaceBinding[];
43
- export declare function findWorkspaceBinding(start?: string): WorkspaceBinding | null;
44
- export declare function bindWorkspace(repositoryPath: string, context: WorkspaceBinding): string;
44
+ export declare function findWorkspaceBinding(start?: string, selectedName?: string | undefined): WorkspaceBinding | null;
45
+ export declare function bindWorkspace(repositoryPath: string, context: WorkspaceBinding, client?: "claude" | "codex"): string;
@@ -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 } from "./repositoryHook.js";
7
7
  import { looksLikeKey } from "./keys.js";
8
- export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.4.0";
8
+ export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.5.0";
9
9
  export const MAX_WORKSPACE_BYTES = 64 * 1024;
10
10
  export const MAX_WORKSPACES = 64;
11
11
  export function workspaceName(value) {
@@ -145,7 +145,25 @@ export function writeWorkspaceFile(file, value) {
145
145
  export function codexWorkspaceProfilePath(name) {
146
146
  return path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), `codetelemetry-${workspaceName(name)}.config.toml`);
147
147
  }
148
+ export function workspaceCaptureDefault(context) {
149
+ if (context.clientConfig)
150
+ return context.clientConfig.enrich;
151
+ const file = codexWorkspaceProfilePath(context.name);
152
+ if (!fs.existsSync(file))
153
+ return true;
154
+ noLinks(file);
155
+ const stat = fs.lstatSync(file);
156
+ if (!stat.isFile() || stat.size > MAX_WORKSPACE_BYTES)
157
+ throw new Error("Invalid workspace profile.");
158
+ const text = fs.readFileSync(file, "utf8");
159
+ if (!text.startsWith(`# CodeTelemetry workspace ${context.name}\n`)) {
160
+ throw new Error("The Codex workspace profile is not managed by CodeTelemetry; choose a different context name.");
161
+ }
162
+ const section = text.match(/^\[otel\]\r?\n([\s\S]*?)(?=^\[|(?![\s\S]))/m)?.[1] ?? "";
163
+ return /^\s*log_user_prompt\s*=\s*true\s*(?:#.*)?$/m.test(section);
164
+ }
148
165
  export function writeCodexWorkspaceProfile(context, options = {}) {
166
+ const enrich = options.enrich ?? workspaceCaptureDefault(context);
149
167
  const profilePath = codexWorkspaceProfilePath(context.name), marker = `# CodeTelemetry workspace ${context.name}\n`;
150
168
  upgradeLegacyCodexObserver(path.dirname(profilePath));
151
169
  if (fs.existsSync(profilePath)) {
@@ -157,9 +175,9 @@ export function writeCodexWorkspaceProfile(context, options = {}) {
157
175
  throw new Error("The Codex workspace profile is not managed by CodeTelemetry; choose a different context name.");
158
176
  }
159
177
  let text = marker +
160
- buildOtelSection(context.ingestKey, context.ingestEndpoint, options.enrich === true) +
178
+ buildOtelSection(context.ingestKey, context.ingestEndpoint, enrich) +
161
179
  "\n";
162
- if (!options.enrich)
180
+ if (!enrich)
163
181
  text = text.replace("[otel]\n", "[otel]\nlog_user_prompt = false\n");
164
182
  if (options.repositoryObservation) {
165
183
  const hookPath = path.join(workspaceHome(), `${context.name}.hook.cjs`);
@@ -339,28 +357,67 @@ export function listWorkspaces() {
339
357
  .sort()
340
358
  .map((file) => bindingOf(loadWorkspace(file.slice(0, -5))));
341
359
  }
342
- export function findWorkspaceBinding(start = process.cwd()) {
360
+ export function findWorkspaceBinding(start = process.cwd(), selectedName = process.env.CODETELEMETRY_WORKSPACE) {
343
361
  let dir = path.resolve(start);
344
362
  for (let depth = 0; depth < 64; depth++) {
345
363
  const file = path.join(dir, ".codetelemetry", "workspace.json");
346
- if (fs.existsSync(file))
347
- return bindingOf(readWorkspaceFile(file, false));
364
+ if (fs.existsSync(file)) {
365
+ const raw = readWorkspaceFile(file, false);
366
+ const primary = bindingOf(raw);
367
+ if (selectedName && primary.name !== selectedName) {
368
+ const clients = raw.clientBindings;
369
+ if (clients && typeof clients === "object" && !Array.isArray(clients)) {
370
+ for (const client of ["claude", "codex"]) {
371
+ if (clients[client]) {
372
+ const candidate = bindingOf(clients[client]);
373
+ if (candidate.name === selectedName)
374
+ return candidate;
375
+ }
376
+ }
377
+ }
378
+ }
379
+ return primary;
380
+ }
348
381
  if (fs.existsSync(path.join(dir, ".git")) || path.dirname(dir) === dir)
349
382
  return null;
350
383
  dir = path.dirname(dir);
351
384
  }
352
385
  throw new Error("Workspace binding search exceeded 64 parents.");
353
386
  }
354
- export function bindWorkspace(repositoryPath, context) {
387
+ export function bindWorkspace(repositoryPath, context, client) {
355
388
  const root = fs.realpathSync(repositoryPath);
356
389
  if (!fs.statSync(root).isDirectory() ||
357
390
  root === os.homedir() ||
358
391
  root === path.parse(root).root)
359
392
  throw new Error("Choose a repository directory.");
360
393
  const file = path.join(root, ".codetelemetry", "workspace.json");
361
- if (fs.existsSync(file) &&
362
- !sameWorkspace(bindingOf(readWorkspaceFile(file, false)), context))
363
- throw new Error("Repository is bound to another workspace; remove its binding explicitly before switching.");
364
- writeWorkspaceFile(file, bindingOf(context));
365
- return file;
394
+ noLinks(file);
395
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
396
+ const releaseBinding = workspaceLock(".store");
397
+ try {
398
+ const existing = fs.existsSync(file) ? readWorkspaceFile(file, false) : null;
399
+ const primary = existing ? bindingOf(existing) : null;
400
+ const sameDestination = primary && primary.apiBase === context.apiBase &&
401
+ JSON.stringify(primary.scope) === JSON.stringify(context.scope);
402
+ const rawClients = existing?.clientBindings;
403
+ const clientBindings = {};
404
+ if (rawClients !== undefined) {
405
+ if (!rawClients || typeof rawClients !== "object" || Array.isArray(rawClients) ||
406
+ Object.keys(rawClients).some(key => key !== "claude" && key !== "codex"))
407
+ throw new Error("Invalid repository client bindings.");
408
+ for (const [key, value] of Object.entries(rawClients))
409
+ clientBindings[key] = bindingOf(value);
410
+ }
411
+ if (primary && !sameWorkspace(primary, context) && (!client || !sameDestination ||
412
+ (clientBindings[client] && !sameWorkspace(clientBindings[client], context))))
413
+ throw new Error("Repository is bound to another workspace; remove its binding explicitly before switching.");
414
+ if (client)
415
+ clientBindings[client] = bindingOf(context);
416
+ writeWorkspaceFile(file, { ...(primary ?? bindingOf(context)),
417
+ ...(Object.keys(clientBindings).length ? { clientBindings } : {}) });
418
+ return file;
419
+ }
420
+ finally {
421
+ releaseBinding();
422
+ }
366
423
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codetelemetry/connect",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "CodeTelemetry local client and onboarding CLI",
5
5
  "type": "module",
6
6
  "license": "MIT",