@codetelemetry/mcp 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/LICENSE +21 -0
- package/README.md +242 -0
- package/dist/src/client/agent.d.ts +379 -0
- package/dist/src/client/agent.js +204 -0
- package/dist/src/client/codexConfig.d.ts +23 -0
- package/dist/src/client/codexConfig.js +265 -0
- package/dist/src/client/config.d.ts +26 -0
- package/dist/src/client/config.js +32 -0
- package/dist/src/client/connectivity.d.ts +27 -0
- package/dist/src/client/connectivity.js +54 -0
- package/dist/src/client/deviceClient.d.ts +32 -0
- package/dist/src/client/deviceClient.js +112 -0
- package/dist/src/client/keys.d.ts +5 -0
- package/dist/src/client/keys.js +24 -0
- package/dist/src/client/onboard.d.ts +47 -0
- package/dist/src/client/onboard.js +84 -0
- package/dist/src/client/otlp.d.ts +18 -0
- package/dist/src/client/otlp.js +60 -0
- package/dist/src/client/repositoryHook.d.ts +17 -0
- package/dist/src/client/repositoryHook.js +631 -0
- package/dist/src/client/settings.d.ts +28 -0
- package/dist/src/client/settings.js +97 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +2 -0
- package/dist/src/manifest.d.ts +29 -0
- package/dist/src/manifest.js +93 -0
- package/dist/src/mcpServer.d.ts +3 -0
- package/dist/src/mcpServer.js +18 -0
- package/dist/src/server.d.ts +2 -0
- package/dist/src/server.js +16 -0
- package/dist/src/session.d.ts +21 -0
- package/dist/src/session.js +44 -0
- package/dist/src/tools.d.ts +28 -0
- package/dist/src/tools.js +697 -0
- package/dist/src/version.d.ts +2 -0
- package/dist/src/version.js +2 -0
- package/package.json +55 -0
- package/tool-manifest.json +474 -0
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { assertKey } from "./keys.js";
|
|
2
|
+
async function postAgent(opts) {
|
|
3
|
+
const key = assertKey(opts.key);
|
|
4
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
5
|
+
const ac = new AbortController();
|
|
6
|
+
const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? 10_000);
|
|
7
|
+
try {
|
|
8
|
+
let res;
|
|
9
|
+
try {
|
|
10
|
+
res = await fetchImpl(opts.url, {
|
|
11
|
+
method: "POST",
|
|
12
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
|
|
13
|
+
body: JSON.stringify(opts.body),
|
|
14
|
+
signal: ac.signal,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (!ac.signal.aborted)
|
|
19
|
+
throw error;
|
|
20
|
+
return {
|
|
21
|
+
ok: false,
|
|
22
|
+
value: null,
|
|
23
|
+
httpStatus: 0,
|
|
24
|
+
error: "read_timeout",
|
|
25
|
+
message: "Telemetry read timed out before the server responded.",
|
|
26
|
+
bodyError: null,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
let value = null;
|
|
30
|
+
let error = null;
|
|
31
|
+
let message = null;
|
|
32
|
+
let bodyError = null;
|
|
33
|
+
try {
|
|
34
|
+
const decoded = await res.json();
|
|
35
|
+
value = decoded;
|
|
36
|
+
error = typeof decoded?.error === "string" ? decoded.error : null;
|
|
37
|
+
message = typeof decoded?.message === "string" ? decoded.message : null;
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
bodyError = err instanceof SyntaxError
|
|
41
|
+
? null
|
|
42
|
+
: ac.signal.aborted ? "read_timeout" : "read_unavailable";
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
bodyError,
|
|
46
|
+
ok: res.status >= 200 && res.status < 300,
|
|
47
|
+
value,
|
|
48
|
+
httpStatus: res.status,
|
|
49
|
+
error,
|
|
50
|
+
message,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export async function getCostSignal(opts) {
|
|
58
|
+
const key = assertKey(opts.key);
|
|
59
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
60
|
+
const ac = new AbortController();
|
|
61
|
+
const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? 10_000);
|
|
62
|
+
try {
|
|
63
|
+
const res = await fetchImpl(opts.url, {
|
|
64
|
+
method: "POST",
|
|
65
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
|
|
66
|
+
body: "{}",
|
|
67
|
+
signal: ac.signal,
|
|
68
|
+
});
|
|
69
|
+
let cost = null;
|
|
70
|
+
try {
|
|
71
|
+
const json = (await res.json());
|
|
72
|
+
cost = json?.cost ?? null;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
}
|
|
76
|
+
return { ok: res.status >= 200 && res.status < 300, cost, httpStatus: res.status };
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function getSessionPerformance(opts) {
|
|
83
|
+
const result = await postAgent({
|
|
84
|
+
...opts,
|
|
85
|
+
timeoutMs: opts.timeoutMs ?? 120_000,
|
|
86
|
+
body: {
|
|
87
|
+
sessionId: opts.sessionId,
|
|
88
|
+
...(opts.includeFresh === undefined ? {} : { includeFresh: opts.includeFresh }),
|
|
89
|
+
...(opts.cacheSamples === undefined ? {} : { cacheSamples: opts.cacheSamples }),
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
return {
|
|
93
|
+
ok: result.ok,
|
|
94
|
+
report: result.value?.report ?? null,
|
|
95
|
+
httpStatus: result.httpStatus,
|
|
96
|
+
error: result.error,
|
|
97
|
+
message: result.message,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export async function findSimilarSessionErrors(opts) {
|
|
101
|
+
const result = await postAgent({
|
|
102
|
+
...opts,
|
|
103
|
+
timeoutMs: opts.timeoutMs ?? 25_000,
|
|
104
|
+
body: {
|
|
105
|
+
sessionId: opts.sessionId,
|
|
106
|
+
...(opts.lookbackDays === undefined ? {} : { lookbackDays: opts.lookbackDays }),
|
|
107
|
+
...(opts.limit === undefined ? {} : { limit: opts.limit }),
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
return {
|
|
111
|
+
ok: result.ok,
|
|
112
|
+
report: result.value?.report ?? null,
|
|
113
|
+
performance: result.value?.performance ?? null,
|
|
114
|
+
httpStatus: result.httpStatus,
|
|
115
|
+
error: result.error,
|
|
116
|
+
message: result.message,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
export const SESSION_SEARCH_REQUEST_TIMEOUT_MS = 65_000;
|
|
120
|
+
export async function searchCodingSessions(opts) {
|
|
121
|
+
const result = await postAgent({
|
|
122
|
+
key: opts.key,
|
|
123
|
+
url: opts.url,
|
|
124
|
+
fetchImpl: opts.fetchImpl,
|
|
125
|
+
timeoutMs: opts.timeoutMs ?? SESSION_SEARCH_REQUEST_TIMEOUT_MS,
|
|
126
|
+
body: opts.query,
|
|
127
|
+
});
|
|
128
|
+
if (result.bodyError) {
|
|
129
|
+
return {
|
|
130
|
+
ok: false,
|
|
131
|
+
report: null,
|
|
132
|
+
httpStatus: result.httpStatus,
|
|
133
|
+
error: result.bodyError,
|
|
134
|
+
message: `Session-search response headers arrived but its body did not (${result.bodyError}).`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const report = result.value?.report;
|
|
138
|
+
if (result.ok && (!report || typeof report !== "object" || Array.isArray(report))) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
report: null,
|
|
142
|
+
httpStatus: result.httpStatus,
|
|
143
|
+
error: "read_unusable",
|
|
144
|
+
message: "Session-search response did not contain a usable report.",
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
ok: result.ok,
|
|
149
|
+
report: result.ok ? report ?? null : null,
|
|
150
|
+
httpStatus: result.httpStatus,
|
|
151
|
+
error: result.error,
|
|
152
|
+
message: result.message,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
export async function estimateTaskSize(opts) {
|
|
156
|
+
const result = await postAgent({
|
|
157
|
+
...opts,
|
|
158
|
+
timeoutMs: opts.timeoutMs ?? 60_000,
|
|
159
|
+
body: {
|
|
160
|
+
...(opts.taskText === undefined ? {} : { taskText: opts.taskText }),
|
|
161
|
+
...(opts.issue === undefined ? {} : { issue: opts.issue }),
|
|
162
|
+
...(opts.issueKey === undefined ? {} : { issueKey: opts.issueKey }),
|
|
163
|
+
...(opts.repo === undefined ? {} : { repo: opts.repo }),
|
|
164
|
+
...(opts.linearScale === undefined ? {} : { linearScale: opts.linearScale }),
|
|
165
|
+
...(opts.linearScaleExtended === undefined ? {} : { linearScaleExtended: opts.linearScaleExtended }),
|
|
166
|
+
...(opts.lookbackDays === undefined ? {} : { lookbackDays: opts.lookbackDays }),
|
|
167
|
+
...(opts.limit === undefined ? {} : { limit: opts.limit }),
|
|
168
|
+
},
|
|
169
|
+
});
|
|
170
|
+
return {
|
|
171
|
+
ok: result.ok,
|
|
172
|
+
estimate: result.value?.estimate ?? null,
|
|
173
|
+
performance: result.value?.performance ?? null,
|
|
174
|
+
httpStatus: result.httpStatus,
|
|
175
|
+
error: result.error,
|
|
176
|
+
message: result.message,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
export async function estimateLinearIssue(opts) {
|
|
180
|
+
const result = await postAgent({
|
|
181
|
+
...opts,
|
|
182
|
+
timeoutMs: opts.timeoutMs ?? 60_000,
|
|
183
|
+
body: {
|
|
184
|
+
reference: opts.reference,
|
|
185
|
+
...(opts.connectionId === undefined ? {} : { connectionId: opts.connectionId }),
|
|
186
|
+
...(opts.workspace === undefined ? {} : { workspace: opts.workspace }),
|
|
187
|
+
...(opts.repo === undefined ? {} : { repo: opts.repo }),
|
|
188
|
+
...(opts.linearScale === undefined ? {} : { linearScale: opts.linearScale }),
|
|
189
|
+
...(opts.linearScaleExtended === undefined ? {} : { linearScaleExtended: opts.linearScaleExtended }),
|
|
190
|
+
...(opts.lookbackDays === undefined ? {} : { lookbackDays: opts.lookbackDays }),
|
|
191
|
+
...(opts.limit === undefined ? {} : { limit: opts.limit }),
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
return {
|
|
195
|
+
ok: result.ok,
|
|
196
|
+
estimate: result.value?.estimate ?? null,
|
|
197
|
+
source: result.value?.source ?? null,
|
|
198
|
+
connections: result.value?.connections ?? null,
|
|
199
|
+
performance: result.value?.performance ?? null,
|
|
200
|
+
httpStatus: result.httpStatus,
|
|
201
|
+
error: result.error,
|
|
202
|
+
message: result.message,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { WriteResult } from "./settings.ts";
|
|
2
|
+
export declare function resolveCodexConfigPath(opts?: {
|
|
3
|
+
path?: string;
|
|
4
|
+
home?: string;
|
|
5
|
+
codexHome?: string;
|
|
6
|
+
}): string;
|
|
7
|
+
export declare function buildOtelSection(key: string, ingestEndpoint: string, enrich: boolean): string;
|
|
8
|
+
export declare function mergeOtelBody(body: string[], key: string, ingestEndpoint: string, enrich: boolean): string[];
|
|
9
|
+
export type CodexWriteOptions = {
|
|
10
|
+
key: string;
|
|
11
|
+
ingestEndpoint: string;
|
|
12
|
+
configPath: string;
|
|
13
|
+
enrich?: boolean;
|
|
14
|
+
repositoryObservation?: boolean;
|
|
15
|
+
backup?: boolean;
|
|
16
|
+
};
|
|
17
|
+
export declare function writeCodexConfig(opts: CodexWriteOptions): WriteResult;
|
|
18
|
+
export declare function readCodexKey(configPath: string): string | null;
|
|
19
|
+
export declare function readCodexSummary(configPath: string): {
|
|
20
|
+
exists: boolean;
|
|
21
|
+
otelKeys: string[];
|
|
22
|
+
hasKey: boolean;
|
|
23
|
+
};
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { assertKey } from "./keys.js";
|
|
5
|
+
import { installCodexRepositoryObservationHook, removeCodexRepositoryObservationHook, validateCodexRepositoryObservationHook, } from "./repositoryHook.js";
|
|
6
|
+
export function resolveCodexConfigPath(opts = {}) {
|
|
7
|
+
if (opts.path)
|
|
8
|
+
return path.resolve(opts.path);
|
|
9
|
+
const codexHome = opts.codexHome ?? process.env.CODEX_HOME;
|
|
10
|
+
if (codexHome)
|
|
11
|
+
return path.resolve(codexHome, "config.toml");
|
|
12
|
+
return path.join(opts.home ?? os.homedir(), ".codex", "config.toml");
|
|
13
|
+
}
|
|
14
|
+
function exporterLine(kind, signal, key, ingestEndpoint) {
|
|
15
|
+
return `${kind} = { otlp-http = { endpoint = "${ingestEndpoint}/v1/${signal}", protocol = "binary", headers = { authorization = "Bearer ${key}" } } }`;
|
|
16
|
+
}
|
|
17
|
+
const OWNED_KEYS = ["exporter", "trace_exporter", "metrics_exporter"];
|
|
18
|
+
const COMMENT_RE = /^\s*#/;
|
|
19
|
+
function keyOf(line) {
|
|
20
|
+
if (COMMENT_RE.test(line))
|
|
21
|
+
return null;
|
|
22
|
+
const eq = line.indexOf("=");
|
|
23
|
+
if (eq === -1)
|
|
24
|
+
return null;
|
|
25
|
+
const key = line.slice(0, eq).trim().replace(/\s*\.\s*/g, ".");
|
|
26
|
+
return key && /^[A-Za-z0-9_.\-"']+$/.test(key) ? key : null;
|
|
27
|
+
}
|
|
28
|
+
function rootKey(key) {
|
|
29
|
+
const q = key[0];
|
|
30
|
+
if (q === '"' || q === "'") {
|
|
31
|
+
const end = key.indexOf(q, 1);
|
|
32
|
+
if (end !== -1)
|
|
33
|
+
return key.slice(1, end);
|
|
34
|
+
}
|
|
35
|
+
return key.split(".")[0];
|
|
36
|
+
}
|
|
37
|
+
function ownedLines(key, ingestEndpoint, enrich) {
|
|
38
|
+
const lines = [];
|
|
39
|
+
if (enrich)
|
|
40
|
+
lines.push("log_user_prompt = true");
|
|
41
|
+
lines.push(exporterLine("exporter", "logs", key, ingestEndpoint), exporterLine("trace_exporter", "traces", key, ingestEndpoint), exporterLine("metrics_exporter", "metrics", key, ingestEndpoint));
|
|
42
|
+
return lines;
|
|
43
|
+
}
|
|
44
|
+
export function buildOtelSection(key, ingestEndpoint, enrich) {
|
|
45
|
+
return ["[otel]", ...ownedLines(key, ingestEndpoint, enrich)].join("\n");
|
|
46
|
+
}
|
|
47
|
+
export function mergeOtelBody(body, key, ingestEndpoint, enrich) {
|
|
48
|
+
const replaced = new Set(OWNED_KEYS);
|
|
49
|
+
if (enrich)
|
|
50
|
+
replaced.add("log_user_prompt");
|
|
51
|
+
const kept = body.filter((l) => {
|
|
52
|
+
const k = keyOf(l);
|
|
53
|
+
return k === null || !replaced.has(rootKey(k));
|
|
54
|
+
});
|
|
55
|
+
while (kept.length && kept[kept.length - 1].trim() === "")
|
|
56
|
+
kept.pop();
|
|
57
|
+
return [...kept, ...ownedLines(key, ingestEndpoint, enrich)];
|
|
58
|
+
}
|
|
59
|
+
function sectionKeys(enrich) {
|
|
60
|
+
return enrich ? ["log_user_prompt", ...OWNED_KEYS] : [...OWNED_KEYS];
|
|
61
|
+
}
|
|
62
|
+
function headerName(line) {
|
|
63
|
+
const text = stripComment(line).trim();
|
|
64
|
+
if (!text.startsWith("["))
|
|
65
|
+
return null;
|
|
66
|
+
const arrayTable = text.startsWith("[[");
|
|
67
|
+
const closer = arrayTable ? "]]" : "]";
|
|
68
|
+
if (!text.endsWith(closer) || text.length <= (arrayTable ? 4 : 2))
|
|
69
|
+
return null;
|
|
70
|
+
const inner = text.slice(arrayTable ? 2 : 1, text.length - closer.length);
|
|
71
|
+
const segments = [];
|
|
72
|
+
let current = "";
|
|
73
|
+
let quote = null;
|
|
74
|
+
for (let i = 0; i < inner.length; i++) {
|
|
75
|
+
const ch = inner[i];
|
|
76
|
+
if (quote) {
|
|
77
|
+
if (ch === "\\" && quote === '"')
|
|
78
|
+
current += inner[++i] ?? "";
|
|
79
|
+
else if (ch === quote)
|
|
80
|
+
quote = null;
|
|
81
|
+
else
|
|
82
|
+
current += ch;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (ch === '"' || ch === "'")
|
|
86
|
+
quote = ch;
|
|
87
|
+
else if (ch === ".") {
|
|
88
|
+
segments.push(current.trim());
|
|
89
|
+
current = "";
|
|
90
|
+
}
|
|
91
|
+
else if (ch === "[" || ch === "]" || ch === ",")
|
|
92
|
+
return null;
|
|
93
|
+
else
|
|
94
|
+
current += ch;
|
|
95
|
+
}
|
|
96
|
+
if (quote)
|
|
97
|
+
return null;
|
|
98
|
+
segments.push(current.trim());
|
|
99
|
+
return segments.some((s) => s === "") ? null : segments.join(".");
|
|
100
|
+
}
|
|
101
|
+
const isHeader = (line) => headerName(line) !== null;
|
|
102
|
+
const isOtelHeader = (line) => headerName(line) === "otel";
|
|
103
|
+
const isOtelSubtable = (line) => (headerName(line) ?? "").startsWith("otel.");
|
|
104
|
+
const MULTILINE_STRING_RE = /"""|'''/;
|
|
105
|
+
function structuralOnly(line) {
|
|
106
|
+
let out = "";
|
|
107
|
+
let quote = null;
|
|
108
|
+
for (let i = 0; i < line.length; i++) {
|
|
109
|
+
const ch = line[i];
|
|
110
|
+
if (quote) {
|
|
111
|
+
if (ch === "\\" && quote === '"')
|
|
112
|
+
i++;
|
|
113
|
+
else if (ch === quote)
|
|
114
|
+
quote = null;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (ch === '"' || ch === "'")
|
|
118
|
+
quote = ch;
|
|
119
|
+
else if (ch === "#")
|
|
120
|
+
break;
|
|
121
|
+
else
|
|
122
|
+
out += ch;
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
function depthDelta(line) {
|
|
127
|
+
let d = 0;
|
|
128
|
+
for (const ch of structuralOnly(line)) {
|
|
129
|
+
if (ch === "[" || ch === "{")
|
|
130
|
+
d++;
|
|
131
|
+
else if (ch === "]" || ch === "}")
|
|
132
|
+
d--;
|
|
133
|
+
}
|
|
134
|
+
return d;
|
|
135
|
+
}
|
|
136
|
+
function findOtelSection(lines) {
|
|
137
|
+
let depth = 0;
|
|
138
|
+
let start = -1;
|
|
139
|
+
for (let i = 0; i < lines.length; i++) {
|
|
140
|
+
if (depth === 0) {
|
|
141
|
+
if (start === -1) {
|
|
142
|
+
if (isOtelHeader(lines[i]))
|
|
143
|
+
start = i;
|
|
144
|
+
}
|
|
145
|
+
else if (i > start && isHeader(lines[i])) {
|
|
146
|
+
return { start, end: i };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
depth = Math.max(0, depth + depthDelta(lines[i]));
|
|
150
|
+
}
|
|
151
|
+
return start === -1 ? null : { start, end: lines.length };
|
|
152
|
+
}
|
|
153
|
+
function hasOtelSubtable(lines) {
|
|
154
|
+
let depth = 0;
|
|
155
|
+
for (const line of lines) {
|
|
156
|
+
if (depth === 0 && isOtelSubtable(line))
|
|
157
|
+
return true;
|
|
158
|
+
depth = Math.max(0, depth + depthDelta(line));
|
|
159
|
+
}
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
function splitLines(raw) {
|
|
163
|
+
const crlf = (raw.match(/\r\n/g) ?? []).length;
|
|
164
|
+
const lf = (raw.match(/\n/g) ?? []).length - crlf;
|
|
165
|
+
return { lines: raw.split(/\r?\n/), eol: crlf > lf ? "\r\n" : "\n" };
|
|
166
|
+
}
|
|
167
|
+
export function writeCodexConfig(opts) {
|
|
168
|
+
const key = assertKey(opts.key);
|
|
169
|
+
const filePath = path.resolve(opts.configPath);
|
|
170
|
+
const existed = fs.existsSync(filePath);
|
|
171
|
+
const raw = existed ? fs.readFileSync(filePath, "utf8") : "";
|
|
172
|
+
const { lines, eol } = splitLines(raw);
|
|
173
|
+
if (lines.some((l) => MULTILINE_STRING_RE.test(l))) {
|
|
174
|
+
throw new Error(`refusing to edit ${filePath}: it uses a multi-line TOML string (""" or '''), whose contents ` +
|
|
175
|
+
`this writer can't tell apart from real section headers. Configure the [otel] section by hand ` +
|
|
176
|
+
`(https://codetelemetry.com/docs/data-sources/openai-codex), or remove the multi-line string and retry.`);
|
|
177
|
+
}
|
|
178
|
+
if (hasOtelSubtable(lines)) {
|
|
179
|
+
throw new Error(`refusing to edit ${filePath}: it defines [otel.*] sub-tables this writer can't safely merge. ` +
|
|
180
|
+
`Remove or inline them, then retry.`);
|
|
181
|
+
}
|
|
182
|
+
if (opts.repositoryObservation)
|
|
183
|
+
validateCodexRepositoryObservationHook(filePath);
|
|
184
|
+
else
|
|
185
|
+
removeCodexRepositoryObservationHook(filePath);
|
|
186
|
+
const section = findOtelSection(lines);
|
|
187
|
+
let out;
|
|
188
|
+
if (section === null) {
|
|
189
|
+
const fresh = buildOtelSection(key, opts.ingestEndpoint, !!opts.enrich).split("\n");
|
|
190
|
+
const body = lines.length && lines[lines.length - 1] === "" ? lines.slice(0, -1) : lines;
|
|
191
|
+
out = body.length ? [...body, "", ...fresh] : [...fresh];
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
const { start, end } = section;
|
|
195
|
+
const merged = mergeOtelBody(lines.slice(start + 1, end), key, opts.ingestEndpoint, !!opts.enrich);
|
|
196
|
+
out = [...lines.slice(0, start), lines[start], ...merged, ...lines.slice(end)];
|
|
197
|
+
}
|
|
198
|
+
const next = out.join(eol).replace(/(\r?\n)+$/, "") + eol;
|
|
199
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
200
|
+
let backupPath = null;
|
|
201
|
+
if (existed && opts.backup !== false) {
|
|
202
|
+
backupPath = `${filePath}.bak`;
|
|
203
|
+
fs.copyFileSync(filePath, backupPath);
|
|
204
|
+
}
|
|
205
|
+
fs.writeFileSync(filePath, next, { mode: 0o600 });
|
|
206
|
+
try {
|
|
207
|
+
fs.chmodSync(filePath, 0o600);
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
}
|
|
211
|
+
if (opts.repositoryObservation)
|
|
212
|
+
installCodexRepositoryObservationHook(filePath);
|
|
213
|
+
return { path: filePath, wrote: sectionKeys(!!opts.enrich), backupPath, created: !existed };
|
|
214
|
+
}
|
|
215
|
+
function otelSectionLines(raw) {
|
|
216
|
+
const { lines } = splitLines(raw);
|
|
217
|
+
if (lines.some((l) => MULTILINE_STRING_RE.test(l)))
|
|
218
|
+
return [];
|
|
219
|
+
const section = findOtelSection(lines);
|
|
220
|
+
return section === null ? [] : lines.slice(section.start + 1, section.end);
|
|
221
|
+
}
|
|
222
|
+
function activeOtelLines(raw) {
|
|
223
|
+
return otelSectionLines(raw).filter((l) => keyOf(l) !== null);
|
|
224
|
+
}
|
|
225
|
+
function stripComment(line) {
|
|
226
|
+
let quote = null;
|
|
227
|
+
for (let i = 0; i < line.length; i++) {
|
|
228
|
+
const ch = line[i];
|
|
229
|
+
if (quote) {
|
|
230
|
+
if (ch === "\\" && quote === '"')
|
|
231
|
+
i++;
|
|
232
|
+
else if (ch === quote)
|
|
233
|
+
quote = null;
|
|
234
|
+
}
|
|
235
|
+
else if (ch === '"' || ch === "'")
|
|
236
|
+
quote = ch;
|
|
237
|
+
else if (ch === "#")
|
|
238
|
+
return line.slice(0, i);
|
|
239
|
+
}
|
|
240
|
+
return line;
|
|
241
|
+
}
|
|
242
|
+
function exporterKeyText(raw) {
|
|
243
|
+
return activeOtelLines(raw)
|
|
244
|
+
.filter((l) => {
|
|
245
|
+
const k = keyOf(l);
|
|
246
|
+
return k !== null && OWNED_KEYS.includes(rootKey(k));
|
|
247
|
+
})
|
|
248
|
+
.map(stripComment)
|
|
249
|
+
.join("\n");
|
|
250
|
+
}
|
|
251
|
+
export function readCodexKey(configPath) {
|
|
252
|
+
if (!fs.existsSync(configPath))
|
|
253
|
+
return null;
|
|
254
|
+
const m = exporterKeyText(fs.readFileSync(configPath, "utf8")).match(/Bearer\s+(cot_[A-Za-z0-9_-]+)/);
|
|
255
|
+
return m ? m[1] : null;
|
|
256
|
+
}
|
|
257
|
+
export function readCodexSummary(configPath) {
|
|
258
|
+
if (!fs.existsSync(configPath))
|
|
259
|
+
return { exists: false, otelKeys: [], hasKey: false };
|
|
260
|
+
const raw = fs.readFileSync(configPath, "utf8");
|
|
261
|
+
const otelKeys = activeOtelLines(raw)
|
|
262
|
+
.map((l) => keyOf(l))
|
|
263
|
+
.filter((k) => k !== null);
|
|
264
|
+
return { exists: true, otelKeys, hasKey: /Bearer\s+cot_/.test(exporterKeyText(raw)) };
|
|
265
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type Endpoints = {
|
|
2
|
+
apiBase: string;
|
|
3
|
+
ingestEndpoint: string;
|
|
4
|
+
deviceCodeUrl: string;
|
|
5
|
+
deviceApproveUrl: string;
|
|
6
|
+
deviceTokenUrl: string;
|
|
7
|
+
connectivityUrl: string;
|
|
8
|
+
verificationUri: string;
|
|
9
|
+
agentCostUrl: string;
|
|
10
|
+
agentSessionPerformanceUrl: string;
|
|
11
|
+
agentSimilarErrorsUrl: string;
|
|
12
|
+
agentSessionSearchUrl: string;
|
|
13
|
+
agentTaskSizeUrl: string;
|
|
14
|
+
agentLinearIssueSizeUrl: string;
|
|
15
|
+
};
|
|
16
|
+
export declare function resolveEndpoints(overrides?: Partial<{
|
|
17
|
+
apiBase: string;
|
|
18
|
+
ingestEndpoint: string;
|
|
19
|
+
}>): Endpoints;
|
|
20
|
+
export type SettingsScope = "user" | "project";
|
|
21
|
+
export declare function resolveSettingsPath(opts?: {
|
|
22
|
+
scope?: SettingsScope;
|
|
23
|
+
path?: string;
|
|
24
|
+
cwd?: string;
|
|
25
|
+
home?: string;
|
|
26
|
+
}): string;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
const DEFAULT_API_BASE = "https://codetelemetry.com";
|
|
4
|
+
const DEFAULT_INGEST = "https://ingest.codetelemetry.com";
|
|
5
|
+
export function resolveEndpoints(overrides = {}) {
|
|
6
|
+
const apiBase = (overrides.apiBase || process.env.CODETELEMETRY_API_BASE || DEFAULT_API_BASE).replace(/\/$/, "");
|
|
7
|
+
const ingestEndpoint = (overrides.ingestEndpoint || process.env.CODETELEMETRY_INGEST_ENDPOINT || DEFAULT_INGEST).replace(/\/$/, "");
|
|
8
|
+
return {
|
|
9
|
+
apiBase,
|
|
10
|
+
ingestEndpoint,
|
|
11
|
+
deviceCodeUrl: `${apiBase}/api/device/code`,
|
|
12
|
+
deviceApproveUrl: `${apiBase}/api/device/approve`,
|
|
13
|
+
deviceTokenUrl: `${apiBase}/api/device/token`,
|
|
14
|
+
connectivityUrl: `${apiBase}/api/connectivity/check`,
|
|
15
|
+
verificationUri: `${apiBase}/activate`,
|
|
16
|
+
agentCostUrl: `${apiBase}/api/agent/cost`,
|
|
17
|
+
agentSessionPerformanceUrl: `${apiBase}/api/agent/session-performance`,
|
|
18
|
+
agentSimilarErrorsUrl: `${apiBase}/api/agent/similar-errors`,
|
|
19
|
+
agentSessionSearchUrl: `${apiBase}/api/agent/session-search`,
|
|
20
|
+
agentTaskSizeUrl: `${apiBase}/api/agent/task-size`,
|
|
21
|
+
agentLinearIssueSizeUrl: `${apiBase}/api/agent/linear-issue-size`,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export function resolveSettingsPath(opts = {}) {
|
|
25
|
+
if (opts.path)
|
|
26
|
+
return path.resolve(opts.path);
|
|
27
|
+
const scope = opts.scope ?? "user";
|
|
28
|
+
if (scope === "project") {
|
|
29
|
+
return path.join(opts.cwd ?? process.cwd(), ".claude", "settings.json");
|
|
30
|
+
}
|
|
31
|
+
return path.join(opts.home ?? os.homedir(), ".claude", "settings.json");
|
|
32
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { FetchLike } from "./otlp.ts";
|
|
2
|
+
export type CheckResult = {
|
|
3
|
+
seen: boolean;
|
|
4
|
+
httpStatus: number;
|
|
5
|
+
};
|
|
6
|
+
export declare function checkOnce(opts: {
|
|
7
|
+
key: string;
|
|
8
|
+
connectivityUrl: string;
|
|
9
|
+
probeId: string;
|
|
10
|
+
fetchImpl?: FetchLike;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
}): Promise<CheckResult>;
|
|
13
|
+
export type ConfirmResult = {
|
|
14
|
+
landed: boolean;
|
|
15
|
+
elapsedMs: number;
|
|
16
|
+
polls: number;
|
|
17
|
+
};
|
|
18
|
+
export declare function confirmLanded(opts: {
|
|
19
|
+
key: string;
|
|
20
|
+
connectivityUrl: string;
|
|
21
|
+
probeId: string;
|
|
22
|
+
fetchImpl?: FetchLike;
|
|
23
|
+
intervalMs?: number;
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
onTick?: (poll: number) => void;
|
|
26
|
+
now?: () => number;
|
|
27
|
+
}): Promise<ConfirmResult>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { assertKey } from "./keys.js";
|
|
2
|
+
export async function checkOnce(opts) {
|
|
3
|
+
const key = assertKey(opts.key);
|
|
4
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
5
|
+
const ac = new AbortController();
|
|
6
|
+
const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? 8_000);
|
|
7
|
+
try {
|
|
8
|
+
const res = await fetchImpl(opts.connectivityUrl, {
|
|
9
|
+
method: "POST",
|
|
10
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
|
|
11
|
+
body: JSON.stringify({ probeId: opts.probeId }),
|
|
12
|
+
signal: ac.signal,
|
|
13
|
+
});
|
|
14
|
+
let seen = false;
|
|
15
|
+
try {
|
|
16
|
+
const json = (await res.json());
|
|
17
|
+
seen = !!json?.seen;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
}
|
|
21
|
+
return { seen, httpStatus: res.status };
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
clearTimeout(timer);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
28
|
+
export async function confirmLanded(opts) {
|
|
29
|
+
const interval = opts.intervalMs ?? 2_000;
|
|
30
|
+
const timeout = opts.timeoutMs ?? 30_000;
|
|
31
|
+
const now = opts.now ?? (() => Date.now());
|
|
32
|
+
const start = now();
|
|
33
|
+
let polls = 0;
|
|
34
|
+
while (true) {
|
|
35
|
+
const remaining = timeout - (now() - start);
|
|
36
|
+
if (remaining <= 0)
|
|
37
|
+
return { landed: false, elapsedMs: now() - start, polls };
|
|
38
|
+
polls += 1;
|
|
39
|
+
opts.onTick?.(polls);
|
|
40
|
+
const { seen } = await checkOnce({
|
|
41
|
+
key: opts.key,
|
|
42
|
+
connectivityUrl: opts.connectivityUrl,
|
|
43
|
+
probeId: opts.probeId,
|
|
44
|
+
fetchImpl: opts.fetchImpl,
|
|
45
|
+
timeoutMs: Math.min(8_000, remaining),
|
|
46
|
+
});
|
|
47
|
+
const elapsedMs = now() - start;
|
|
48
|
+
if (seen)
|
|
49
|
+
return { landed: true, elapsedMs, polls };
|
|
50
|
+
if (elapsedMs + interval >= timeout)
|
|
51
|
+
return { landed: false, elapsedMs, polls };
|
|
52
|
+
await sleep(interval);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { FetchLike } from "./otlp.ts";
|
|
2
|
+
import type { Endpoints } from "./config.ts";
|
|
3
|
+
export type DeviceCodeResponse = {
|
|
4
|
+
deviceCode: string;
|
|
5
|
+
userCode: string;
|
|
6
|
+
verificationUri: string;
|
|
7
|
+
expiresIn: number;
|
|
8
|
+
interval: number;
|
|
9
|
+
};
|
|
10
|
+
export declare function requestDeviceCode(endpoints: Endpoints, fetchImpl?: FetchLike, timeoutMs?: number): Promise<DeviceCodeResponse>;
|
|
11
|
+
export type DeviceKey = {
|
|
12
|
+
apiKey: string;
|
|
13
|
+
ingestEndpoint: string;
|
|
14
|
+
};
|
|
15
|
+
export type PollOnce = {
|
|
16
|
+
status: "authorized";
|
|
17
|
+
apiKey: string;
|
|
18
|
+
ingestEndpoint: string;
|
|
19
|
+
} | {
|
|
20
|
+
status: "pending";
|
|
21
|
+
} | {
|
|
22
|
+
status: "error";
|
|
23
|
+
error: string;
|
|
24
|
+
};
|
|
25
|
+
export declare function pollOnce(endpoints: Endpoints, deviceCode: string, fetchImpl?: FetchLike, timeoutMs?: number): Promise<PollOnce>;
|
|
26
|
+
export declare function pollForKey(endpoints: Endpoints, deviceCode: string, opts?: {
|
|
27
|
+
intervalMs?: number;
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
fetchImpl?: FetchLike;
|
|
30
|
+
now?: () => number;
|
|
31
|
+
sleepImpl?: (ms: number) => Promise<void>;
|
|
32
|
+
}): Promise<DeviceKey>;
|