@codetelemetry/mcp 0.3.9 → 0.3.14

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.
Files changed (81) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +135 -9
  3. package/dist/src/client/agent.d.ts +201 -3
  4. package/dist/src/client/agent.js +154 -0
  5. package/dist/src/client/assistants.d.ts +4 -0
  6. package/dist/src/client/assistants.js +5 -0
  7. package/dist/src/client/bin.d.ts +2 -0
  8. package/dist/src/client/bin.js +3 -0
  9. package/dist/src/client/cli.d.ts +1 -0
  10. package/dist/src/client/cli.js +567 -0
  11. package/dist/src/client/clients.d.ts +34 -0
  12. package/dist/src/client/clients.js +74 -0
  13. package/dist/src/client/codexConfig.d.ts +1 -0
  14. package/dist/src/client/codexConfig.js +5 -0
  15. package/dist/src/client/config.d.ts +6 -0
  16. package/dist/src/client/config.js +6 -0
  17. package/dist/src/client/graderArtifact.d.ts +14 -0
  18. package/dist/src/client/graderArtifact.js +94 -0
  19. package/dist/src/client/graderSeed.d.ts +50 -0
  20. package/dist/src/client/graderSeed.js +289 -0
  21. package/dist/src/client/hostMetrics.d.ts +54 -0
  22. package/dist/src/client/hostMetrics.js +425 -0
  23. package/dist/src/client/import/browser.d.ts +30 -0
  24. package/dist/src/client/import/browser.js +157 -0
  25. package/dist/src/client/import/convert.d.ts +20 -0
  26. package/dist/src/client/import/convert.js +165 -0
  27. package/dist/src/client/import/core.d.ts +143 -0
  28. package/dist/src/client/import/core.js +441 -0
  29. package/dist/src/client/import/ledger.d.ts +52 -0
  30. package/dist/src/client/import/ledger.js +161 -0
  31. package/dist/src/client/import/model.d.ts +70 -0
  32. package/dist/src/client/import/model.js +42 -0
  33. package/dist/src/client/import/options.d.ts +24 -0
  34. package/dist/src/client/import/options.js +71 -0
  35. package/dist/src/client/import/otlpImport.d.ts +7 -0
  36. package/dist/src/client/import/otlpImport.js +81 -0
  37. package/dist/src/client/import/protocol.d.ts +35 -0
  38. package/dist/src/client/import/protocol.js +51 -0
  39. package/dist/src/client/import/run.d.ts +30 -0
  40. package/dist/src/client/import/run.js +127 -0
  41. package/dist/src/client/import/sources/claudeCodeText.d.ts +19 -0
  42. package/dist/src/client/import/sources/claudeCodeText.js +214 -0
  43. package/dist/src/client/import/sources/codexText.d.ts +20 -0
  44. package/dist/src/client/import/sources/codexText.js +319 -0
  45. package/dist/src/client/import/sources/files.d.ts +24 -0
  46. package/dist/src/client/import/sources/files.js +129 -0
  47. package/dist/src/client/import/transport.d.ts +76 -0
  48. package/dist/src/client/import/transport.js +141 -0
  49. package/dist/src/client/index.d.ts +19 -0
  50. package/dist/src/client/index.js +19 -0
  51. package/dist/src/client/kiro/collector.d.ts +88 -0
  52. package/dist/src/client/kiro/collector.js +577 -0
  53. package/dist/src/client/kiro/command.d.ts +3 -0
  54. package/dist/src/client/kiro/command.js +109 -0
  55. package/dist/src/client/kiro/config.d.ts +39 -0
  56. package/dist/src/client/kiro/config.js +107 -0
  57. package/dist/src/client/kiro/records.d.ts +52 -0
  58. package/dist/src/client/kiro/records.js +206 -0
  59. package/dist/src/client/kiro/service.d.ts +21 -0
  60. package/dist/src/client/kiro/service.js +183 -0
  61. package/dist/src/client/kiro/state.d.ts +45 -0
  62. package/dist/src/client/kiro/state.js +205 -0
  63. package/dist/src/client/kiro/transport.d.ts +9 -0
  64. package/dist/src/client/kiro/transport.js +90 -0
  65. package/dist/src/client/onboard.d.ts +5 -1
  66. package/dist/src/client/onboard.js +28 -23
  67. package/dist/src/client/piConfig.d.ts +29 -0
  68. package/dist/src/client/piConfig.js +112 -0
  69. package/dist/src/client/plan.d.ts +1 -1
  70. package/dist/src/client/plan.js +2 -1
  71. package/dist/src/client/settings.d.ts +4 -0
  72. package/dist/src/client/settings.js +17 -0
  73. package/dist/src/client/yaml.d.ts +5 -0
  74. package/dist/src/client/yaml.js +72 -0
  75. package/dist/src/mcpServer.js +1 -1
  76. package/dist/src/tools.d.ts +9 -6
  77. package/dist/src/tools.js +428 -60
  78. package/dist/src/version.d.ts +1 -1
  79. package/dist/src/version.js +1 -1
  80. package/package.json +178 -9
  81. package/tool-manifest.json +708 -21
@@ -0,0 +1,74 @@
1
+ import fs from "node:fs";
2
+ import { resolveKiroConfigPath, writeKiroConfig, readKiroKey, readKiroSummary } from "./kiro/config.js";
3
+ import { resolveSettingsPath } from "./config.js";
4
+ import { buildEnvBlock, readSettingsSummary, writeSettings } from "./settings.js";
5
+ import { buildOtelSection, readCodexKey, readCodexSummary, resolveCodexConfigPath, writeCodexConfig } from "./codexConfig.js";
6
+ import { buildPiOtelBlock, readPiKey, readPiSummary, resolvePiConfigPath, writePiConfig } from "./piConfig.js";
7
+ import { ONBOARD_CLIENTS, isOnboardClient } from "./assistants.js";
8
+ export function readClaudeKey(settingsPath) {
9
+ if (!fs.existsSync(settingsPath))
10
+ return null;
11
+ try {
12
+ const headers = JSON.parse(fs.readFileSync(settingsPath, "utf8"))?.env?.OTEL_EXPORTER_OTLP_HEADERS;
13
+ const match = typeof headers === "string" ? /Bearer\s+(cot_[A-Za-z0-9_-]+)/.exec(headers) : null;
14
+ return match ? match[1] : null;
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ export const CLIENTS = Object.freeze({
21
+ kiro: {
22
+ id: "kiro", label: "Kiro", noun: "collector settings", cliFlag: " --client kiro",
23
+ resolveConfigPath: opts => resolveKiroConfigPath({ path: opts.path }), write: writeKiroConfig, readKey: readKiroKey, readSummary: readKiroSummary,
24
+ printConfig: (ingestEndpoint, enrich) => JSON.stringify({ kind: "codetelemetry-kiro-v3", version: 1, enabled: true, key: "cot_<YOUR_INGEST_KEY>", ingestEndpoint,
25
+ sourceRoot: "<HOME>/.kiro/sessions", stateDir: "<HOME>/.local/state/codetelemetry/kiro-v3", backfill: false, content: { prompts: enrich, toolDetails: enrich } }, null, 2),
26
+ },
27
+ claude: {
28
+ id: "claude",
29
+ label: "Claude Code",
30
+ noun: "OTEL vars",
31
+ cliFlag: "",
32
+ resolveConfigPath: (opts) => resolveSettingsPath({ scope: opts.scope, path: opts.path }),
33
+ write: (opts) => writeSettings({
34
+ key: opts.key, ingestEndpoint: opts.ingestEndpoint, settingsPath: opts.configPath, enrich: opts.enrich, repositoryObservation: opts.repositoryObservation, backup: opts.backup,
35
+ }),
36
+ readKey: readClaudeKey,
37
+ readSummary: readSettingsSummary,
38
+ printConfig: (ingestEndpoint, enrich) => JSON.stringify({ env: buildEnvBlock("<YOUR_INGEST_KEY>", ingestEndpoint, enrich) }, null, 2),
39
+ },
40
+ codex: {
41
+ id: "codex",
42
+ label: "Codex",
43
+ noun: "OTEL keys",
44
+ cliFlag: " --codex",
45
+ resolveConfigPath: (opts) => resolveCodexConfigPath({ path: opts.path }),
46
+ write: (opts) => writeCodexConfig({
47
+ key: opts.key, ingestEndpoint: opts.ingestEndpoint, configPath: opts.configPath, enrich: opts.enrich, repositoryObservation: opts.repositoryObservation, backup: opts.backup,
48
+ }),
49
+ readKey: readCodexKey,
50
+ readSummary: readCodexSummary,
51
+ printConfig: (ingestEndpoint, enrich) => buildOtelSection("cot_<YOUR_INGEST_KEY>", ingestEndpoint, enrich),
52
+ },
53
+ pi: {
54
+ id: "pi",
55
+ label: "pi",
56
+ noun: "otel settings",
57
+ cliFlag: " --client pi",
58
+ resolveConfigPath: (opts) => resolvePiConfigPath({ path: opts.path }),
59
+ write: (opts) => writePiConfig({
60
+ key: opts.key, ingestEndpoint: opts.ingestEndpoint, configPath: opts.configPath, enrich: opts.enrich, backup: opts.backup,
61
+ }),
62
+ readKey: readPiKey,
63
+ readSummary: readPiSummary,
64
+ printConfig: (ingestEndpoint, enrich) => JSON.stringify({ otel: buildPiOtelBlock("cot_<YOUR_INGEST_KEY>", ingestEndpoint, enrich) }, null, 2),
65
+ },
66
+ });
67
+ export const PI_EXTENSION_HINT = "pi exports through its pi-otel extension: run `pi install npm:pi-otel` once, then start pi.";
68
+ export function resolveClient(name) {
69
+ if (name === undefined)
70
+ return CLIENTS.claude;
71
+ if (isOnboardClient(name))
72
+ return CLIENTS[name];
73
+ throw new Error(`unknown client ${JSON.stringify(name)} (expected one of: ${ONBOARD_CLIENTS.join(", ")})`);
74
+ }
@@ -21,3 +21,4 @@ export declare function readCodexSummary(configPath: string): {
21
21
  otelKeys: string[];
22
22
  hasKey: boolean;
23
23
  };
24
+ export declare function readCodexLogUserPrompt(configPath: string): boolean;
@@ -263,3 +263,8 @@ export function readCodexSummary(configPath) {
263
263
  .filter((k) => k !== null);
264
264
  return { exists: true, otelKeys, hasKey: /Bearer\s+cot_/.test(exporterKeyText(raw)) };
265
265
  }
266
+ export function readCodexLogUserPrompt(configPath) {
267
+ if (!fs.existsSync(configPath))
268
+ return false;
269
+ return activeOtelLines(fs.readFileSync(configPath, "utf8")).some((l) => keyOf(l) === "log_user_prompt" && /=\s*true$/.test(stripComment(l).trimEnd()));
270
+ }
@@ -21,8 +21,14 @@ export type Endpoints = {
21
21
  agentReadSessionEventsUrl: string;
22
22
  agentCompareSessionsUrl: string;
23
23
  agentPlanNextSessionUrl: string;
24
+ agentHostHealthUrl: string;
24
25
  agentGitHubGateUrl: string;
25
26
  agentGitHubGateConfigureUrl: string;
27
+ agentReplyPhrasesUrl: string;
28
+ agentImportStatusUrl: string;
29
+ agentGraderUrl: string;
30
+ agentGraderConfigureUrl: string;
31
+ agentGraderPublishUrl?: string;
26
32
  };
27
33
  export declare function resolveEndpoints(overrides?: Partial<{
28
34
  apiBase: string;
@@ -28,8 +28,14 @@ export function resolveEndpoints(overrides = {}) {
28
28
  agentReadSessionEventsUrl: `${apiBase}/api/agent/read-session-events`,
29
29
  agentCompareSessionsUrl: `${apiBase}/api/agent/compare-sessions`,
30
30
  agentPlanNextSessionUrl: `${apiBase}/api/agent/plan-next-session`,
31
+ agentHostHealthUrl: `${apiBase}/api/agent/host-health`,
31
32
  agentGitHubGateUrl: `${apiBase}/api/agent/github-gate`,
32
33
  agentGitHubGateConfigureUrl: `${apiBase}/api/agent/github-gate/configure`,
34
+ agentReplyPhrasesUrl: `${apiBase}/api/agent/reply-phrases`,
35
+ agentImportStatusUrl: `${apiBase}/api/agent/import-status`,
36
+ agentGraderUrl: `${apiBase}/api/agent/grader`,
37
+ agentGraderConfigureUrl: `${apiBase}/api/agent/grader/configure`,
38
+ agentGraderPublishUrl: `${apiBase}/api/agent/grader/publish`,
33
39
  };
34
40
  }
35
41
  export function resolveSettingsPath(opts = {}) {
@@ -0,0 +1,14 @@
1
+ type Format = "auto" | "terraform" | "pulumi";
2
+ export declare function writeGraderArtifact(options: {
3
+ repositoryPath: string;
4
+ format?: Format;
5
+ features: string;
6
+ checks: unknown[];
7
+ }): {
8
+ path: string;
9
+ format: string;
10
+ evidence: string[];
11
+ nextSteps: string;
12
+ note: string;
13
+ };
14
+ export {};
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ const SKIP = new Set([".git", "node_modules", "vendor", "dist", "build", "target", ".terraform", ".pulumi", ".venv", "venv"]);
5
+ export function writeGraderArtifact(options) {
6
+ const root = fs.realpathSync(options.repositoryPath);
7
+ if (!fs.statSync(root).isDirectory() || root === os.homedir() || root === path.parse(root).root)
8
+ throw new Error("Choose a project directory for the artifact.");
9
+ let entries = 0;
10
+ let truncated = false;
11
+ const detected = new Set();
12
+ const evidence = [];
13
+ const walk = (directory, depth) => {
14
+ const handle = fs.opendirSync(directory);
15
+ const children = [];
16
+ try {
17
+ let entry;
18
+ while ((entry = handle.readSync()) !== null) {
19
+ if (++entries > 4000) {
20
+ truncated = true;
21
+ break;
22
+ }
23
+ children.push(entry);
24
+ }
25
+ }
26
+ finally {
27
+ handle.closeSync();
28
+ }
29
+ for (const entry of children.sort((a, b) => a.name.localeCompare(b.name))) {
30
+ if (entry.isSymbolicLink() || SKIP.has(entry.name))
31
+ continue;
32
+ const file = path.join(directory, entry.name);
33
+ if (entry.isFile()) {
34
+ const format = /\.tf(?:\.json)?$/.test(entry.name) ? "terraform" : /^Pulumi\.ya?ml$/.test(entry.name) ? "pulumi" : undefined;
35
+ if (format) {
36
+ detected.add(format);
37
+ if (evidence.length < 20)
38
+ evidence.push(path.relative(root, file));
39
+ }
40
+ }
41
+ else if (entry.isDirectory() && !entry.name.startsWith(".")) {
42
+ if (depth >= 5)
43
+ truncated = true;
44
+ else if (entries <= 4000)
45
+ walk(file, depth + 1);
46
+ }
47
+ if (entries > 4000)
48
+ break;
49
+ }
50
+ };
51
+ const requested = options.format ?? "auto";
52
+ if (requested === "auto")
53
+ walk(root, 0);
54
+ if (requested === "auto" && (detected.size !== 1 || truncated))
55
+ throw new Error("IaC context is absent, mixed, or incomplete. Set format to terraform or pulumi, or choose a narrower repositoryPath.");
56
+ const format = requested === "auto" ? [...detected][0] : requested;
57
+ const relative = format === "terraform" ? "codetelemetry-grader.tf.json" : "codetelemetry-grader.pulumi.yaml";
58
+ const terraformLiteral = (value) => value.replaceAll("${", () => "$${").replaceAll("%{", "%%{");
59
+ const pulumiLiteral = (value) => value.replaceAll("${", () => "$${");
60
+ const contents = format === "terraform" ? {
61
+ locals: { codetelemetry_grader_requested_features: terraformLiteral(options.features) },
62
+ resource: { codetelemetry_grader_config: { instructions: { checks_json: terraformLiteral(JSON.stringify(options.checks)) } } },
63
+ } : {
64
+ name: "codetelemetry-grader", runtime: "yaml", description: options.features,
65
+ packages: { codetelemetry: { source: "terraform-provider", version: "1.5.0", parameters: ["./bin/terraform-provider-codetelemetry"] } },
66
+ resources: { grader: { type: "codetelemetry:index/graderConfig:GraderConfig", properties: { checksJson: { "fn::secret": pulumiLiteral(JSON.stringify(options.checks)) } } } },
67
+ };
68
+ const text = JSON.stringify(contents, null, 2) + "\n";
69
+ if (/\b(?:cot_[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|npm_[A-Za-z0-9]{20,}|(?:AKIA|ASIA)[A-Z0-9]{16})\b|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(text))
70
+ throw new Error("Remove credential-shaped values from features and checks before writing an artifact.");
71
+ if (Buffer.byteLength(text) > 128 * 1024)
72
+ throw new Error("Artifact exceeds 128 KiB; select fewer checks.");
73
+ const directory = fs.openSync(root, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
74
+ try {
75
+ const destination = process.platform === "linux" ? `/proc/self/fd/${directory}/${relative}` : path.join(root, relative);
76
+ if (fs.realpathSync(root) !== root)
77
+ throw new Error("Repository path changed; retry.");
78
+ const fd = fs.openSync(destination, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
79
+ try {
80
+ fs.writeFileSync(fd, text);
81
+ }
82
+ finally {
83
+ fs.closeSync(fd);
84
+ }
85
+ }
86
+ finally {
87
+ fs.closeSync(directory);
88
+ }
89
+ return { path: path.join(root, relative), format, evidence,
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."
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." };
94
+ }
@@ -0,0 +1,50 @@
1
+ export type GraderMatcherNode = {
2
+ field: string;
3
+ operator: string;
4
+ value?: string | string[];
5
+ } | {
6
+ all: GraderMatcherNode[];
7
+ } | {
8
+ any: GraderMatcherNode[];
9
+ } | {
10
+ not: GraderMatcherNode;
11
+ };
12
+ export type GraderCheck = {
13
+ id: string;
14
+ name: string;
15
+ category: string;
16
+ description?: string;
17
+ weight: number;
18
+ satisfactionMode: "observed" | "successful";
19
+ minimumOccurrences: number;
20
+ aggregationMode: "once";
21
+ enabled: boolean;
22
+ repositoryId?: string;
23
+ matcherRule: {
24
+ include: GraderMatcherNode;
25
+ exclude?: GraderMatcherNode;
26
+ };
27
+ };
28
+ export type GraderSeed = {
29
+ features: string;
30
+ sources: Array<{
31
+ path: string;
32
+ kind: "instructions" | "skill";
33
+ text: string;
34
+ truncated: boolean;
35
+ }>;
36
+ candidates: Array<{
37
+ source: string;
38
+ command: string;
39
+ inferred: boolean;
40
+ check: GraderCheck;
41
+ }>;
42
+ warnings: string[];
43
+ truncated: boolean;
44
+ };
45
+ export declare function seedGraderConfig(options: {
46
+ root: string;
47
+ features: string;
48
+ skillPaths?: string[];
49
+ repositoryId?: string;
50
+ }): GraderSeed;
@@ -0,0 +1,289 @@
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
+ const SKIP = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "__pycache__", "venv", "env"]);
6
+ const TASK_FILES = new Set([
7
+ "package.json", "Makefile", "makefile", "GNUmakefile", "justfile", "Justfile",
8
+ "pyproject.toml", "tox.ini", "noxfile.py", "go.mod", "Cargo.toml", "pom.xml",
9
+ "build.gradle", "build.gradle.kts", "composer.json", "Rakefile", "mix.exs", "Package.swift", "CMakeLists.txt",
10
+ ]);
11
+ const MAX_FILE_BYTES = 64 * 1024;
12
+ const MAX_ENTRIES = 4000;
13
+ const MAX_CANDIDATES = 30;
14
+ const MAX_SOURCE_CHARS = 6000;
15
+ const MAX_DEPTH = 6;
16
+ function readSource(file) {
17
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
18
+ try {
19
+ const stat = fs.fstatSync(fd);
20
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES)
21
+ throw new Error("not a regular file of at most 64 KiB");
22
+ const data = Buffer.alloc(MAX_FILE_BYTES + 1);
23
+ const bytes = fs.readSync(fd, data, 0, data.length, 0);
24
+ if (bytes > MAX_FILE_BYTES)
25
+ throw new Error("file exceeds 64 KiB");
26
+ return data.subarray(0, bytes).toString("utf8");
27
+ }
28
+ finally {
29
+ fs.closeSync(fd);
30
+ }
31
+ }
32
+ function category(name) {
33
+ if (/(?:^|[:_\-])(deploy|publish|release|install|watch|dev|serve|clean|fix)(?:$|[:_\-])/.test(name))
34
+ return undefined;
35
+ if (/(?:e2e|end.to.end)/.test(name))
36
+ return "end_to_end_test";
37
+ if (/integration/.test(name))
38
+ return "integration_test";
39
+ if (/coverage|cov$/.test(name))
40
+ return "coverage";
41
+ if (/(?:^|[:_\-])(test|tests|spec|unit)(?:$|[:_\-])/.test(name))
42
+ return "unit_test";
43
+ if (/audit|security/.test(name))
44
+ return "security_validation";
45
+ if (/lint|check|typecheck|type-check|format|verify/.test(name))
46
+ return "static_analysis";
47
+ if (/^build$|^compile$/.test(name))
48
+ return "environment_validation";
49
+ return undefined;
50
+ }
51
+ const condition = (field, value) => ({
52
+ field, operator: Array.isArray(value) ? "contains" : "equals", value,
53
+ });
54
+ const shell = (executable, args = [], operation) => ({ all: [
55
+ condition("source", "shell"), condition("executable", executable),
56
+ ...(operation ? [condition("operation", operation)] : []),
57
+ ...args.map((arg) => condition("normalizedArguments", [arg])),
58
+ ] });
59
+ const targetMatcher = (executable, target) => ({ all: [
60
+ condition("source", "shell"), condition("executable", executable),
61
+ { any: [condition("operation", target), condition("normalizedArguments", [target])] },
62
+ ] });
63
+ export function seedGraderConfig(options) {
64
+ const root = fs.realpathSync(options.root);
65
+ const home = fs.realpathSync(os.homedir());
66
+ if (root === home || root === path.parse(root).root)
67
+ throw new Error("Choose a project directory as repositoryPath; select global SKILL.md files explicitly with skillPaths.");
68
+ if (!fs.statSync(root).isDirectory())
69
+ throw new Error("repositoryPath must be a directory");
70
+ const result = { features: options.features, sources: [], candidates: [], warnings: [], truncated: false };
71
+ let entries = 0;
72
+ let sourceChars = 0;
73
+ const visited = new Set();
74
+ const seenCandidates = new Set();
75
+ const warn = (message) => { if (result.warnings.length < 12)
76
+ result.warnings.push(message); result.truncated = true; };
77
+ const add = (file, command, label, matcher, inferred = false) => {
78
+ const kind = category(label.toLowerCase());
79
+ if (!kind || command.length > 256 || /[\r\n\x00]/.test(command))
80
+ return;
81
+ const source = path.relative(root, file).split(path.sep).join("/");
82
+ const identity = `${options.repositoryId ?? root}\0${source}\0${command}`;
83
+ if (seenCandidates.has(identity))
84
+ return;
85
+ seenCandidates.add(identity);
86
+ if (result.candidates.length >= MAX_CANDIDATES) {
87
+ warn("Command candidate limit reached; narrow repositoryPath to inspect another package.");
88
+ return;
89
+ }
90
+ const directory = path.dirname(file);
91
+ if (directory.length > 200)
92
+ warn("Working-directory scope exceeds matcher limits; set repositoryId before saving.");
93
+ result.candidates.push({ source, command, inferred, check: {
94
+ id: `seed-${createHash("sha256").update(identity).digest("hex").slice(0, 16)}`,
95
+ name: `${source}: ${label}`.slice(0, 120), category: kind,
96
+ description: `Seeded from ${source}. ${inferred ? "Conventional command; confirm project support." : "Declared project task."}`.slice(0, 500),
97
+ weight: 1, satisfactionMode: "successful", minimumOccurrences: 1, aggregationMode: "once", enabled: true,
98
+ ...(options.repositoryId ? { repositoryId: options.repositoryId } : {}),
99
+ matcherRule: { include: { all: [matcher, ...(directory.length <= 200 ? [condition("workingDirectory", directory)] : [])] },
100
+ exclude: { field: "normalizedArguments", operator: "contains", value: ["--watch", "--watchAll", "--collect-only", "--listTests", "--dry-run", "--no-run", "--help", "--version"] } },
101
+ } });
102
+ };
103
+ const inspect = (file) => {
104
+ if (visited.has(file))
105
+ return;
106
+ visited.add(file);
107
+ const name = path.basename(file);
108
+ let text;
109
+ try {
110
+ text = readSource(file);
111
+ }
112
+ catch {
113
+ warn(`Skipped unreadable, linked, or oversized source: ${path.relative(root, file)}`);
114
+ return;
115
+ }
116
+ if (/^agents\.md$/i.test(name) || name === "SKILL.md") {
117
+ const remaining = MAX_SOURCE_CHARS - sourceChars;
118
+ if (remaining <= 0 || result.sources.length >= 12) {
119
+ warn("Instruction budget reached; use a narrower repositoryPath or fewer skillPaths.");
120
+ return;
121
+ }
122
+ const clipped = text.slice(0, Math.min(3000, remaining));
123
+ sourceChars += clipped.length;
124
+ const truncated = clipped.length !== text.length;
125
+ if (truncated)
126
+ result.truncated = true;
127
+ result.sources.push({ path: path.relative(root, file).split(path.sep).join("/"), kind: name === "SKILL.md" ? "skill" : "instructions", text: clipped, truncated });
128
+ return;
129
+ }
130
+ if (name === "package.json" || name === "composer.json") {
131
+ try {
132
+ const data = JSON.parse(text);
133
+ let runner = "npm";
134
+ if (typeof data.packageManager === "string")
135
+ runner = /^(pnpm|yarn|bun)@/.exec(data.packageManager)?.[1] ?? "npm";
136
+ else
137
+ for (const [lock, manager] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lock", "bun"], ["bun.lockb", "bun"]]) {
138
+ if (fs.existsSync(path.join(path.dirname(file), lock))) {
139
+ runner = manager;
140
+ break;
141
+ }
142
+ }
143
+ if (data.scripts && typeof data.scripts === "object" && !Array.isArray(data.scripts))
144
+ for (const [task, body] of Object.entries(data.scripts)) {
145
+ if (!/^[A-Za-z0-9][A-Za-z0-9:_\-.]{0,79}$/.test(task) || typeof body !== "string")
146
+ continue;
147
+ if (/--(?:watch|fix|collect-only|listTests|dry-run)\b|no test specified|echo\s+["']?no tests/i.test(body))
148
+ continue;
149
+ if (/format/i.test(task) && !/--check|--list-different|--check-formatted/.test(body))
150
+ continue;
151
+ add(file, `${name === "composer.json" ? "composer" : runner} run ${task}`, task, name === "composer.json" ? shell("composer", [task], "run") : { all: [
152
+ condition("source", "shell"), { field: "executable", operator: "in", value: ["npm", "pnpm", "yarn", "bun"] }, condition("packageScript", task),
153
+ ] });
154
+ }
155
+ }
156
+ catch {
157
+ warn(`Invalid JSON in ${path.relative(root, file)}`);
158
+ }
159
+ return;
160
+ }
161
+ if (/^(?:GNUmakefile|[Mm]akefile|[Jj]ustfile|Rakefile)$/.test(name)) {
162
+ const just = /justfile/i.test(name);
163
+ const rake = name === "Rakefile";
164
+ const targetPattern = rake ? /^\s*task\s+[:"']([\w:-]+)/gm : /^([A-Za-z][\w.\-]*(?:[ \t]+[A-Za-z][\w.\-]*)*)[ \t]*:(?!=)/gm;
165
+ for (const match of text.matchAll(targetPattern))
166
+ for (const task of match[1].split(/\s+/)) {
167
+ const runner = rake ? "rake" : just ? "just" : "make";
168
+ add(file, `${runner} ${task}`, task, targetMatcher(runner, task));
169
+ }
170
+ return;
171
+ }
172
+ const conventional = (command, label, exe, args = [], operation) => add(file, command, label, shell(exe, args, operation), true);
173
+ if (name === "pyproject.toml") {
174
+ if (/^\[tool\.pytest(?:\.|\])/m.test(text) || /["']pytest(?:["'\s><=~!\[])/m.test(text))
175
+ conventional("python -m pytest", "test", "pytest");
176
+ if (/^\[tool\.ruff(?:\.|\])/m.test(text))
177
+ conventional("ruff check .", "lint", "ruff", ["check", "<path>"]);
178
+ if (/^\[tool\.mypy\]/m.test(text))
179
+ conventional("mypy .", "typecheck", "mypy");
180
+ }
181
+ else if (name === "tox.ini")
182
+ conventional("tox", "test", "tox");
183
+ else if (name === "noxfile.py") {
184
+ for (const match of text.matchAll(/^@nox\.session(?:\([^\n]*\))?\s*\n(?:@[^\n]*\n)*def\s+(\w+)\s*\(/gm))
185
+ conventional(`nox -s ${match[1]}`, match[1], "nox", ["-s", match[1]]);
186
+ }
187
+ else if (name === "go.mod") {
188
+ conventional("go test ./...", "test", "go", ["<path>"], "test");
189
+ conventional("go vet ./...", "lint", "go", ["<path>"], "vet");
190
+ }
191
+ else if (name === "Cargo.toml") {
192
+ conventional("cargo test", "test", "cargo", [], "test");
193
+ conventional("cargo check", "check", "cargo", [], "check");
194
+ }
195
+ else if (name === "pom.xml")
196
+ conventional("mvn test", "test", "mvn", [], "test");
197
+ else if (/^build\.gradle/.test(name)) {
198
+ const wrapper = fs.existsSync(path.join(path.dirname(file), "gradlew"));
199
+ conventional(`${wrapper ? "./gradlew" : "gradle"} test`, "test", wrapper ? "gradlew" : "gradle", wrapper ? ["test"] : [], wrapper ? undefined : "test");
200
+ }
201
+ else if (name === "mix.exs")
202
+ conventional("mix test", "test", "mix", [], "test");
203
+ else if (name === "Package.swift")
204
+ conventional("swift test", "test", "swift", [], "test");
205
+ else if (name.endsWith(".csproj") || name.endsWith(".fsproj"))
206
+ conventional(`dotnet test ${name}`, "test", "dotnet", ["<path>"], "test");
207
+ else if (name === "CMakeLists.txt" && /enable_testing\s*\(|include\s*\(\s*CTest\s*\)/i.test(text))
208
+ conventional("ctest --test-dir build", "test", "ctest", ["--test-dir", "build"]);
209
+ };
210
+ const walk = (directory, depth, skillsOnly = false) => {
211
+ if (depth > MAX_DEPTH) {
212
+ warn("Directory depth limit reached.");
213
+ return;
214
+ }
215
+ const children = [];
216
+ try {
217
+ const handle = fs.opendirSync(directory);
218
+ try {
219
+ let entry;
220
+ while ((entry = handle.readSync()) !== null) {
221
+ if (++entries > MAX_ENTRIES) {
222
+ warn("File discovery limit reached.");
223
+ break;
224
+ }
225
+ children.push(entry);
226
+ }
227
+ }
228
+ finally {
229
+ handle.closeSync();
230
+ }
231
+ children.sort((a, b) => a.name.localeCompare(b.name));
232
+ }
233
+ catch {
234
+ warn(`Skipped unreadable directory: ${path.relative(root, directory)}`);
235
+ return;
236
+ }
237
+ for (const entry of children) {
238
+ const file = path.join(directory, entry.name);
239
+ if (entry.isFile() && (skillsOnly ? entry.name === "SKILL.md" : /^agents\.md$/i.test(entry.name) || entry.name === "SKILL.md" || TASK_FILES.has(entry.name) || /\.(?:csproj|fsproj)$/.test(entry.name)))
240
+ inspect(file);
241
+ }
242
+ for (const entry of children) {
243
+ if (entries >= MAX_ENTRIES)
244
+ return;
245
+ if (!entry.isDirectory() || SKIP.has(entry.name))
246
+ continue;
247
+ const child = path.join(directory, entry.name);
248
+ if (entry.name.startsWith(".")) {
249
+ if ([".claude", ".codex", ".agents"].includes(entry.name)) {
250
+ const skills = path.join(child, "skills");
251
+ try {
252
+ if (fs.lstatSync(skills).isDirectory())
253
+ walk(skills, depth + 1, true);
254
+ }
255
+ catch { }
256
+ }
257
+ continue;
258
+ }
259
+ walk(child, depth + 1, skillsOnly);
260
+ }
261
+ };
262
+ walk(root, 0);
263
+ for (const selected of options.skillPaths ?? []) {
264
+ const absolute = path.resolve(root, selected);
265
+ if (fs.realpathSync(absolute) !== absolute)
266
+ throw new Error("skillPaths must not contain symbolic links");
267
+ if (path.basename(absolute) !== "SKILL.md")
268
+ throw new Error("skillPaths must name SKILL.md files");
269
+ inspect(absolute);
270
+ }
271
+ const wireBytes = () => Buffer.byteLength(JSON.stringify(result)) + Buffer.byteLength(JSON.stringify(JSON.stringify(result, null, 2)));
272
+ while (wireBytes() > 52 * 1024) {
273
+ warn("Response budget reached; narrow repositoryPath or select fewer sources.");
274
+ if (result.candidates.length > 1)
275
+ result.candidates.pop();
276
+ else if (result.sources.length) {
277
+ const source = result.sources[result.sources.length - 1];
278
+ if (source.text.length > 256) {
279
+ source.text = source.text.slice(0, Math.floor(source.text.length / 2));
280
+ source.truncated = true;
281
+ }
282
+ else
283
+ result.sources.pop();
284
+ }
285
+ else
286
+ break;
287
+ }
288
+ return result;
289
+ }
@@ -0,0 +1,54 @@
1
+ import { type YamlValue } from "./yaml.ts";
2
+ export declare const DEFAULT_KEY_ENV = "CODETELEMETRY_INGEST_KEY";
3
+ export declare const DEFAULT_SERVICE_NAME = "agentd-host";
4
+ export declare const SERVICE_NAMESPACE = "codetelemetry";
5
+ export declare const HOST_METRIC_CONTRACT: readonly string[];
6
+ export declare const PSEUDO_FS_TYPES: readonly string[];
7
+ export declare const VOLUME_KEY_STATEMENT: string;
8
+ export declare const REDACTED_RESOURCE_ATTRIBUTES: readonly string[];
9
+ export declare const DEFAULT_PROCESS_NAMES: readonly string[];
10
+ export type HostMetricsMode = "direct" | "gateway";
11
+ export type HostMetricsOptions = {
12
+ mode?: HostMetricsMode;
13
+ endpoint: string;
14
+ keyEnvVar?: string;
15
+ noAuth?: boolean;
16
+ serviceName?: string;
17
+ instanceId: string;
18
+ environment?: string;
19
+ intervalSec?: number;
20
+ processNames?: readonly string[];
21
+ includeInterfaceNames?: boolean;
22
+ includeMountPoints?: boolean;
23
+ queueDir?: string;
24
+ queueSize?: number;
25
+ allowInsecure?: boolean;
26
+ memoryLimitMib?: number;
27
+ };
28
+ export declare function buildHostMetricsConfig(opts: HostMetricsOptions): Record<string, YamlValue>;
29
+ export declare function renderHostMetricsConfig(opts: HostMetricsOptions): string;
30
+ export type CliFlags = Record<string, string | boolean>;
31
+ export declare function hostMetricsOptionsFromFlags(flags: CliFlags, defaults: {
32
+ ingestEndpoint: string;
33
+ paths: HostMetricsPaths;
34
+ instanceId: string;
35
+ }): HostMetricsOptions & {
36
+ configPath: string;
37
+ };
38
+ export type HostMetricsPaths = {
39
+ configPath: string;
40
+ queueDir: string;
41
+ };
42
+ export declare function defaultHostMetricsPaths(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): HostMetricsPaths;
43
+ export declare function defaultInstanceId(hostname?: string): string;
44
+ export type HostMetricsWriteResult = {
45
+ path: string;
46
+ created: boolean;
47
+ backupPath: string | null;
48
+ requiredEnv: string[];
49
+ };
50
+ export type HostMetricsWriteOptions = HostMetricsOptions & {
51
+ configPath: string;
52
+ backup?: boolean;
53
+ };
54
+ export declare function writeHostMetricsConfig(opts: HostMetricsWriteOptions): HostMetricsWriteResult;