@codetelemetry/mcp 0.3.14 → 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,157 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { spawnSync } from "node:child_process";
4
+ function command(binary, args, cwd, deadline) {
5
+ const remaining = deadline - Date.now();
6
+ if (remaining <= 0)
7
+ throw new Error("Bootstrap time limit reached; resume to finish GitHub verification.");
8
+ const result = spawnSync(binary, args, {
9
+ cwd,
10
+ encoding: "utf8",
11
+ timeout: Math.min(8000, remaining),
12
+ maxBuffer: 65536,
13
+ windowsHide: true,
14
+ });
15
+ if (result.error || result.status !== 0)
16
+ throw new Error("GitHub verification needs an authenticated gh CLI and access to this repository's workflow and branch rules.");
17
+ return result.stdout;
18
+ }
19
+ export function decisionForHead(decisions, repository, head, startedAt, policyVersion) {
20
+ if (!/^[a-f0-9]{40,64}$/.test(head))
21
+ return undefined;
22
+ return decisions
23
+ .slice(0, 100)
24
+ .find((d) => d &&
25
+ d.via === "actions" &&
26
+ d.headSha === head &&
27
+ new RegExp(`^https://github\\.com/${repository.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/pull/[0-9]+$`, "i").test(d.prUrl) &&
28
+ Number.isFinite(Date.parse(d.at)) &&
29
+ Date.parse(d.at) >= startedAt &&
30
+ ["success", "failure"].includes(d.posted) &&
31
+ Number.isFinite(d.score) &&
32
+ d.score >= 0 &&
33
+ d.score <= 100 &&
34
+ Array.isArray(d.sessionIds) &&
35
+ d.sessionIds.length > 0 &&
36
+ (policyVersion === undefined || d.policyVersion === policyVersion));
37
+ }
38
+ export function prepareGitHubWorkflow(root, workflow) {
39
+ if (workflow.path !== ".github/workflows/codetelemetry-pr-gate.yml" ||
40
+ typeof workflow.content !== "string" ||
41
+ Buffer.byteLength(workflow.content) > 48 * 1024 ||
42
+ /cot_[A-Za-z0-9_-]{16,}/.test(workflow.content))
43
+ throw new Error("Invalid generated GitHub workflow.");
44
+ for (const suffix of [".github", ".github/workflows", workflow.path]) {
45
+ const file = path.join(root, suffix);
46
+ try {
47
+ if (fs.lstatSync(file).isSymbolicLink())
48
+ throw new Error("Workflow paths cannot contain symbolic links.");
49
+ }
50
+ catch (error) {
51
+ if (error.code !== "ENOENT")
52
+ throw error;
53
+ }
54
+ }
55
+ const file = path.join(root, workflow.path);
56
+ if (fs.existsSync(file)) {
57
+ if (!fs.lstatSync(file).isFile() ||
58
+ fs.statSync(file).size > 48 * 1024 ||
59
+ fs.readFileSync(file, "utf8") !== workflow.content)
60
+ throw new Error("An existing gate workflow differs. Review and update it explicitly before resuming.");
61
+ }
62
+ else {
63
+ fs.mkdirSync(path.dirname(file), { recursive: true });
64
+ const fd = fs.openSync(file, fs.constants.O_WRONLY |
65
+ fs.constants.O_CREAT |
66
+ fs.constants.O_EXCL |
67
+ fs.constants.O_NOFOLLOW, 0o644);
68
+ try {
69
+ fs.writeFileSync(fd, workflow.content);
70
+ }
71
+ finally {
72
+ fs.closeSync(fd);
73
+ }
74
+ }
75
+ return file;
76
+ }
77
+ export function verifyGitHubSetup(gate, repository, root, startedAt, deadline, policyVersion) {
78
+ const api = (suffix) => JSON.parse(command("gh", ["api", `repos/${repository}${suffix}`], root, deadline));
79
+ const metadata = api("");
80
+ if (typeof metadata.default_branch !== "string" ||
81
+ metadata.default_branch.length > 256)
82
+ throw new Error("GitHub default branch is unavailable.");
83
+ const workflow = gate.actions?.workflow;
84
+ const remote = api(`/contents/${workflow.path}?ref=${encodeURIComponent(metadata.default_branch)}`);
85
+ if (remote.encoding !== "base64" ||
86
+ typeof remote.content !== "string" ||
87
+ Buffer.from(remote.content, "base64").toString("utf8") !== workflow.content)
88
+ return {
89
+ verified: false,
90
+ reason: "Commit the generated workflow to the repository's default branch.",
91
+ };
92
+ const required = gate.actions.requiredCheck;
93
+ let enforced = false;
94
+ try {
95
+ const protection = api(`/branches/${encodeURIComponent(metadata.default_branch)}/protection/required_status_checks`);
96
+ enforced =
97
+ Array.isArray(protection.checks) &&
98
+ protection.checks.some((c) => c.context === required.name &&
99
+ (c.app_id === required.appId || c.app_id === null));
100
+ }
101
+ catch {
102
+ }
103
+ if (!enforced) {
104
+ const summaries = api("/rulesets?includes_parents=true&per_page=21");
105
+ if (!Array.isArray(summaries) || summaries.length > 20)
106
+ return {
107
+ verified: false,
108
+ reason: "Inspect branch rules explicitly; automatic verification supports at most 20 rulesets.",
109
+ };
110
+ for (const summary of summaries) {
111
+ if (!Number.isSafeInteger(summary.id) || summary.enforcement !== "active")
112
+ continue;
113
+ const ruleset = api(`/rulesets/${summary.id}`), names = ruleset.conditions?.ref_name;
114
+ const applies = names &&
115
+ Array.isArray(names.include) &&
116
+ Array.isArray(names.exclude) &&
117
+ names.exclude.length === 0 &&
118
+ names.include.some((n) => [
119
+ "~DEFAULT_BRANCH",
120
+ "~ALL",
121
+ `refs/heads/${metadata.default_branch}`,
122
+ ].includes(n));
123
+ if (applies &&
124
+ Array.isArray(ruleset.rules) &&
125
+ ruleset.rules.some((r) => r.type === "required_status_checks" &&
126
+ r.parameters?.required_status_checks?.some((c) => c.context === required.name &&
127
+ (c.integration_id === required.appId ||
128
+ c.integration_id === null)))) {
129
+ enforced = true;
130
+ break;
131
+ }
132
+ }
133
+ }
134
+ if (!enforced)
135
+ return {
136
+ verified: false,
137
+ reason: `Require ${required.name} on the default branch, then resume.`,
138
+ };
139
+ const head = command("git", ["rev-parse", "HEAD"], root, deadline).trim();
140
+ const decision = decisionForHead(gate.recentDecisions ?? [], repository, head, startedAt, policyVersion);
141
+ if (!decision)
142
+ return {
143
+ verified: false,
144
+ reason: "Run a real organization-scoped PR for this checkout's current HEAD and policy, then resume.",
145
+ };
146
+ return {
147
+ verified: true,
148
+ decision: {
149
+ prUrl: decision.prUrl,
150
+ headSha: decision.headSha,
151
+ verdict: decision.posted,
152
+ score: decision.score,
153
+ threshold: decision.threshold,
154
+ policyVersion: decision.policyVersion,
155
+ },
156
+ };
157
+ }
@@ -1,4 +1,6 @@
1
1
  import fs from "node:fs";
2
+ import { bootstrapWorkspace } from "./bootstrap.js";
3
+ import { listWorkspaces, loadWorkspace, bindWorkspace, bindingOf, findWorkspaceBinding, sameWorkspace, writeCodexWorkspaceProfile } from "./workspaces.js";
2
4
  import { runKiroCommand } from "./kiro/command.js";
3
5
  import { spawn } from "node:child_process";
4
6
  import { onboard } from "./onboard.js";
@@ -43,6 +45,12 @@ const HELP = `codetelemetry-connect — wire Claude Code, OpenAI Codex or pi int
43
45
 
44
46
  Usage:
45
47
  codetelemetry-connect <cot_key> [options] Write config, send a test event, confirm it landed
48
+ codetelemetry-connect run <name> -- <coding-client arguments>
49
+ Start the coding client with this context and isolated telemetry.
50
+ codetelemetry-connect workspace list|use <name>
51
+ codetelemetry-connect bootstrap <name> [--organization-name NAME | --organization-id ID]
52
+ [--client codex|claude] [--project PATH] [--plan FILE]
53
+ Resume with just bootstrap <name>. --plan supplies Grader checks/features.
46
54
  codetelemetry-connect login [options] Authenticate via device code, then do the above
47
55
  codetelemetry-connect doctor [options] Re-test the already-configured key
48
56
  codetelemetry-connect print-config Print the config block (no key)
@@ -384,12 +392,62 @@ async function runImportCommand(positional, flags, endpoints, settingsOpts, clie
384
392
  return result.ok ? 0 : 1;
385
393
  }
386
394
  export async function run(argv) {
395
+ if (argv[0] === "run") {
396
+ const context = loadWorkspace(argv[1]);
397
+ const binding = findWorkspaceBinding();
398
+ if (binding && !sameWorkspace(binding, context))
399
+ throw new Error("Selected context conflicts with this repository.");
400
+ const verified = await verifyScope({ key: context.ingestKey, connectivityUrl: resolveEndpoints({ apiBase: context.apiBase }).connectivityUrl, expected: context.scope });
401
+ if (verified.state !== "scope_verified")
402
+ throw new Error(`Workspace is not ready to run: ${verified.state}.`);
403
+ const client = context.clientConfig?.client ?? "codex";
404
+ const args = argv.slice(argv[2] === "--" ? 3 : 2);
405
+ if (client === "codex")
406
+ 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 } });
408
+ 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
+ }
387
410
  const { _, flags } = parse(argv);
388
411
  const cmd = _[0];
389
412
  if (flags.help || flags.h || cmd === "help") {
390
413
  out(HELP);
391
414
  return 0;
392
415
  }
416
+ if (cmd === "workspace") {
417
+ if (_[1] === "list") {
418
+ out(JSON.stringify(listWorkspaces(), null, 2));
419
+ return 0;
420
+ }
421
+ if (_[1] === "use" && _[2]) {
422
+ const context = loadWorkspace(_[2]);
423
+ const bindingPath = bindWorkspace(typeof flags.project === "string" ? flags.project : process.cwd(), context);
424
+ out(JSON.stringify({ workspace: bindingOf(context), bindingPath }, null, 2));
425
+ return 0;
426
+ }
427
+ throw new Error("Use workspace list or workspace use <name>.");
428
+ }
429
+ if (cmd === "bootstrap") {
430
+ let options = { name: _[1] };
431
+ if (typeof flags.plan === "string") {
432
+ const st = fs.lstatSync(flags.plan);
433
+ if (!st.isFile() || st.size > 48 * 1024)
434
+ throw new Error("Bootstrap plan must be a regular JSON file within 48 KiB.");
435
+ options = { ...JSON.parse(fs.readFileSync(flags.plan, "utf8")), name: _[1] };
436
+ }
437
+ if (typeof flags.project === "string")
438
+ options.repositoryPath = flags.project;
439
+ if (typeof flags["organization-name"] === "string")
440
+ options.organizationName = flags["organization-name"];
441
+ if (typeof flags["organization-id"] === "string")
442
+ options.organizationId = flags["organization-id"];
443
+ if (typeof flags.client === "string")
444
+ options.client = flags.client;
445
+ const result = await bootstrapWorkspace(options, { apiBase: typeof flags["api-base"] === "string" ? flags["api-base"] : undefined });
446
+ out(JSON.stringify(result, null, 2));
447
+ if (result.status === "authorization_required" && flags.open !== false && !flags.json)
448
+ openBrowser(String(result.authorizationUrl));
449
+ return result.ok ? 0 : 2;
450
+ }
393
451
  if (cmd === "kiro")
394
452
  return runKiroCommand(_.slice(1), flags, out);
395
453
  const picked = pickClient(flags);
@@ -88,7 +88,7 @@ export function writeGraderArtifact(options) {
88
88
  }
89
89
  return { path: path.join(root, relative), format, evidence,
90
90
  nextSteps: format === "terraform"
91
- ? "Configure the local codetelemetry provider from codetelemetry-providers, then review terraform plan. The resource owns only the listed check ids. The locals retain requested focus; the dashboard API preserves its existing requestedFeatures."
91
+ ? "Use the CodeTelemetry/codetelemetry-iac provider with the repository workspace binding, then review terraform plan. The resource owns only the listed check ids. The locals retain requested focus; the dashboard API preserves its existing requestedFeatures."
92
92
  : "Move this file to a separate directory as Pulumi.yaml (JSON is valid YAML), build the codetelemetry-providers binary at ./bin/terraform-provider-codetelemetry in that directory, then run pulumi install and pulumi preview. The resource owns only the listed check ids. The program description retains requested focus; the dashboard API preserves its existing requestedFeatures.",
93
- note: "No commands ran and nothing was published. Supply CODETELEMETRY_ENDPOINT and a Cognito ID token as CODETELEMETRY_TOKEN through your secret manager when applying. This artifact contains no credentials. Use MCP publish_grader_config to publish draft changes separately when requested." };
93
+ note: "No commands ran and nothing was published. The organization-capable CodeTelemetry/codetelemetry-iac provider reads the repository workspace binding or CODETELEMETRY_WORKSPACE without a pasted JWT for Grader changes. Legacy management-token configuration remains supported. This artifact contains no credentials. Use MCP publish_grader_config to publish draft changes separately when requested." };
94
94
  }
@@ -17,3 +17,5 @@ export { runImport, RETENTION_DAYS, DEFAULT_SINCE_DAYS, type ImportRunOptions, t
17
17
  export { resolveImportKey, resolveImportContent, parseContentFlag, parseWhen } from "./import/options.ts";
18
18
  export { NO_CONTENT, ALL_CONTENT, type ContentPolicy, type ImportSource } from "./import/model.ts";
19
19
  export { graderConfigRequest } from "./agent.ts";
20
+ export { loadWorkspace, saveWorkspace, listWorkspaces, bindWorkspace, findWorkspaceBinding, type WorkspaceContext, type WorkspaceBinding } from "./workspaces.ts";
21
+ export { bootstrapWorkspace, type BootstrapOptions } from "./bootstrap.ts";
@@ -17,3 +17,5 @@ export { runImport, RETENTION_DAYS, DEFAULT_SINCE_DAYS, } from "./import/run.js"
17
17
  export { resolveImportKey, resolveImportContent, parseContentFlag, parseWhen } from "./import/options.js";
18
18
  export { NO_CONTENT, ALL_CONTENT } from "./import/model.js";
19
19
  export { graderConfigRequest } from "./agent.js";
20
+ export { loadWorkspace, saveWorkspace, listWorkspaces, bindWorkspace, findWorkspaceBinding } from "./workspaces.js";
21
+ export { bootstrapWorkspace } from "./bootstrap.js";
@@ -7,6 +7,7 @@ export declare function normalizeRepositoryRemote(value: string): string;
7
7
  export declare function selectCodexOtelExporterLine(raw: string): string;
8
8
  export declare function repositoryHookSource(options?: {
9
9
  codexConfigPath?: string;
10
+ workspaceName?: string;
10
11
  }): string;
11
12
  export declare function quotedCommand(filePath: string, platform?: string): string;
12
13
  export declare function validateCodexRepositoryObservationHook(configPath: string): void;
@@ -119,6 +119,7 @@ const https = require("node:https");
119
119
  const path = require("node:path");
120
120
  const { execFileSync } = require("node:child_process");
121
121
  const codexConfigPath = ${JSON.stringify(codexConfigPath)};
122
+ const workspaceName = ${JSON.stringify(options.workspaceName ?? "")};
122
123
  const observationStatePath = path.join(__dirname, ${JSON.stringify(REPOSITORY_HOOK_STATE_FILE)});
123
124
  const observationLockPath = observationStatePath + ".lock";
124
125
  const maxObservationStateEntries = ${REPOSITORY_HOOK_STATE_MAX_ENTRIES};
@@ -346,6 +347,36 @@ function permitsAuthorization(url, headers) {
346
347
  async function main() {
347
348
  let input = {};
348
349
  try { input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); } catch {}
350
+ // Codex merges global and profile hooks. The legacy global observer must
351
+ // abstain in named workspaces; only that workspace's opt-in hook may report.
352
+ if (codexConfigPath) {
353
+ const selectedWorkspace = String(process.env.CODETELEMETRY_WORKSPACE || "");
354
+ if (selectedWorkspace && selectedWorkspace !== workspaceName) return;
355
+ let directory = path.resolve(String(input.new_cwd || input.cwd || process.cwd()));
356
+ for (let depth = 0; depth < 64; depth++) {
357
+ const binding = path.join(directory, ".codetelemetry", "workspace.json");
358
+ if (fs.existsSync(binding)) {
359
+ if (!workspaceName) return;
360
+ try {
361
+ const fd = fs.openSync(binding, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
362
+ try {
363
+ const st = fs.fstatSync(fd);
364
+ if (!st.isFile() || st.size > 65536) return;
365
+ const bytes = Buffer.alloc(65537);
366
+ const count = fs.readSync(fd, bytes, 0, bytes.length, 0);
367
+ if (count > 65536) return;
368
+ const stored = JSON.parse(bytes.subarray(0, count).toString("utf8"));
369
+ if (stored.version !== 1 || stored.name !== workspaceName) return;
370
+ } finally { fs.closeSync(fd); }
371
+ } catch { return; }
372
+ break;
373
+ }
374
+ const parent = path.dirname(directory);
375
+ if (parent === directory || fs.existsSync(path.join(directory, ".git"))) break;
376
+ if (depth === 63) return;
377
+ directory = parent;
378
+ }
379
+ }
349
380
  const destination = deliveryDestination();
350
381
  let url;
351
382
  try { url = new URL(destination.endpoint); } catch { return; }
@@ -0,0 +1,44 @@
1
+ import type { KeyScope } from "./connectivity.ts";
2
+ export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.4.0";
3
+ export declare const MAX_WORKSPACE_BYTES: number;
4
+ export declare const MAX_WORKSPACES = 64;
5
+ export type WorkspaceBinding = {
6
+ version: 1;
7
+ name: string;
8
+ apiBase: string;
9
+ scope: KeyScope;
10
+ };
11
+ export type WorkspaceContext = WorkspaceBinding & {
12
+ ingestEndpoint: string;
13
+ ingestKey: string;
14
+ clientConfig?: {
15
+ client: "claude" | "codex";
16
+ path: string;
17
+ enrich: boolean;
18
+ repositoryObservation: boolean;
19
+ };
20
+ };
21
+ export declare function workspaceName(value: unknown): string;
22
+ export declare function workspaceOrigin(value: unknown): string;
23
+ export declare function workspaceScope(value: unknown): KeyScope;
24
+ export declare function bindingOf(value: unknown): WorkspaceBinding;
25
+ export declare function sameWorkspace(a: WorkspaceBinding, b: WorkspaceBinding): boolean;
26
+ export declare function workspaceHome(): string;
27
+ export declare function readWorkspaceFile(file: string, privateFile?: boolean): unknown;
28
+ export declare function writeWorkspaceText(file: string, data: string): void;
29
+ export declare function writeWorkspaceFile(file: string, value: unknown): void;
30
+ export declare function codexWorkspaceProfilePath(name: string): string;
31
+ export declare function writeCodexWorkspaceProfile(context: WorkspaceContext, options?: {
32
+ enrich?: boolean;
33
+ repositoryObservation?: boolean;
34
+ }): {
35
+ path: string;
36
+ };
37
+ export declare function workspaceEntries(): string[];
38
+ export declare function workspaceLock(name: string): () => void;
39
+ export declare function contextPath(name: string): string;
40
+ export declare function loadWorkspace(name: string): WorkspaceContext;
41
+ export declare function saveWorkspace(context: WorkspaceContext): void;
42
+ export declare function listWorkspaces(): WorkspaceBinding[];
43
+ export declare function findWorkspaceBinding(start?: string): WorkspaceBinding | null;
44
+ export declare function bindWorkspace(repositoryPath: string, context: WorkspaceBinding): string;