@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,425 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { renderYaml } from "./yaml.js";
5
+ export const DEFAULT_KEY_ENV = "CODETELEMETRY_INGEST_KEY";
6
+ export const DEFAULT_SERVICE_NAME = "agentd-host";
7
+ export const SERVICE_NAMESPACE = "codetelemetry";
8
+ export const HOST_METRIC_CONTRACT = [
9
+ "system.cpu.utilization",
10
+ "system.cpu.load_average.1m",
11
+ "system.cpu.load_average.5m",
12
+ "system.cpu.load_average.15m",
13
+ "system.memory.usage",
14
+ "system.memory.utilization",
15
+ "system.paging.usage",
16
+ "system.paging.utilization",
17
+ "system.paging.operations",
18
+ "system.network.io",
19
+ "system.network.errors",
20
+ "system.network.dropped",
21
+ "system.network.packets",
22
+ "system.network.connections",
23
+ "system.filesystem.usage",
24
+ "system.filesystem.utilization",
25
+ "system.disk.io",
26
+ "system.disk.operations",
27
+ "system.disk.io_time",
28
+ "system.disk.operation_time",
29
+ "system.disk.pending_operations",
30
+ "system.uptime",
31
+ "process.cpu.utilization",
32
+ "process.cpu.time",
33
+ "process.memory.usage",
34
+ "process.memory.virtual",
35
+ "process.memory.utilization",
36
+ "process.threads",
37
+ "process.open_file_descriptors",
38
+ "process.handles",
39
+ "process.disk.io",
40
+ ];
41
+ export const PSEUDO_FS_TYPES = [
42
+ "autofs", "binfmt_misc", "cgroup", "cgroup2", "configfs", "debugfs",
43
+ "devpts", "devtmpfs", "fusectl", "hugetlbfs", "mqueue", "overlay",
44
+ "proc", "procfs", "pstore", "ramfs", "securityfs", "selinuxfs",
45
+ "squashfs", "sysfs", "tracefs",
46
+ ];
47
+ export const VOLUME_KEY_STATEMENT = 'set(attributes["device"], SHA256(attributes["device"])) ' +
48
+ 'where (metric.name == "system.filesystem.usage" ' +
49
+ 'or metric.name == "system.filesystem.utilization") ' +
50
+ 'and attributes["device"] != nil';
51
+ export const REDACTED_RESOURCE_ATTRIBUTES = [
52
+ "process.command_line",
53
+ "process.command",
54
+ "process.owner",
55
+ "process.executable.path",
56
+ "process.parent_pid",
57
+ ];
58
+ export const DEFAULT_PROCESS_NAMES = [
59
+ "agentd",
60
+ "agentd.exe",
61
+ "node",
62
+ "node.exe",
63
+ "claude",
64
+ "claude.exe",
65
+ "codex",
66
+ "codex.exe",
67
+ ];
68
+ function resolve(opts) {
69
+ const endpoint = opts.endpoint?.trim().replace(/\/$/, "");
70
+ if (!endpoint)
71
+ throw new Error("endpoint is required");
72
+ if (!/^https?:\/\//.test(endpoint)) {
73
+ throw new Error(`endpoint must be an http(s) URL, got: ${endpoint}`);
74
+ }
75
+ const allowInsecure = !!opts.allowInsecure;
76
+ if (endpoint.startsWith("http://") && !allowInsecure) {
77
+ throw new Error(`refusing to configure a plaintext endpoint (${endpoint}): the ingest key ` +
78
+ `travels on every request. Use https, or pass allowInsecure for a loopback gateway.`);
79
+ }
80
+ const instanceId = opts.instanceId?.trim();
81
+ if (!instanceId)
82
+ throw new Error("instanceId is required (it becomes service.instance.id)");
83
+ const intervalSec = opts.intervalSec ?? 60;
84
+ if (!Number.isInteger(intervalSec) || intervalSec < 10 || intervalSec > 3600) {
85
+ throw new Error(`intervalSec must be an integer between 10 and 3600, got: ${intervalSec}`);
86
+ }
87
+ const queueSize = opts.queueSize ?? 1000;
88
+ if (!Number.isInteger(queueSize) || queueSize < 1) {
89
+ throw new Error(`queueSize must be a positive integer, got: ${queueSize}`);
90
+ }
91
+ const memoryLimitMib = opts.memoryLimitMib ?? 128;
92
+ if (!Number.isInteger(memoryLimitMib) || memoryLimitMib < 32) {
93
+ throw new Error(`memoryLimitMib must be an integer >= 32, got: ${memoryLimitMib}`);
94
+ }
95
+ return {
96
+ mode: opts.mode ?? "direct",
97
+ endpoint,
98
+ keyEnvVar: opts.keyEnvVar ?? DEFAULT_KEY_ENV,
99
+ noAuth: !!opts.noAuth,
100
+ serviceName: opts.serviceName ?? DEFAULT_SERVICE_NAME,
101
+ instanceId,
102
+ environment: opts.environment ?? "production",
103
+ intervalSec,
104
+ processNames: opts.processNames ?? DEFAULT_PROCESS_NAMES,
105
+ includeInterfaceNames: !!opts.includeInterfaceNames,
106
+ includeMountPoints: !!opts.includeMountPoints,
107
+ queueDir: opts.queueDir?.trim() || null,
108
+ queueSize,
109
+ allowInsecure,
110
+ memoryLimitMib,
111
+ };
112
+ }
113
+ function enabled(...names) {
114
+ return Object.fromEntries(names.map((n) => [n, { enabled: true }]));
115
+ }
116
+ function disabled(...names) {
117
+ return Object.fromEntries(names.map((n) => [n, { enabled: false }]));
118
+ }
119
+ function scrapers(r) {
120
+ const out = {
121
+ cpu: {
122
+ metrics: {
123
+ ...disabled("system.cpu.time"),
124
+ ...enabled("system.cpu.utilization"),
125
+ },
126
+ },
127
+ load: {},
128
+ memory: { metrics: enabled("system.memory.usage", "system.memory.utilization") },
129
+ paging: {
130
+ metrics: enabled("system.paging.usage", "system.paging.utilization", "system.paging.operations"),
131
+ },
132
+ network: {
133
+ exclude: {
134
+ interfaces: ["^lo\\d*$", "^Loopback", "^isatap", "^Teredo", "^veth", "^docker", "^br-"],
135
+ match_type: "regexp",
136
+ },
137
+ metrics: enabled("system.network.io", "system.network.errors", "system.network.dropped", "system.network.packets", "system.network.connections"),
138
+ },
139
+ filesystem: {
140
+ include_virtual_filesystems: false,
141
+ exclude_fs_types: {
142
+ fs_types: [...PSEUDO_FS_TYPES],
143
+ match_type: "strict",
144
+ },
145
+ exclude_mount_points: {
146
+ mount_points: ["^/dev/", "^/proc/", "^/sys/", "^/run/", "^/var/lib/docker/", "^/snap/"],
147
+ match_type: "regexp",
148
+ },
149
+ metrics: enabled("system.filesystem.usage", "system.filesystem.utilization"),
150
+ },
151
+ disk: {
152
+ metrics: enabled("system.disk.io", "system.disk.operations", "system.disk.io_time", "system.disk.operation_time", "system.disk.pending_operations"),
153
+ },
154
+ system: { metrics: enabled("system.uptime") },
155
+ };
156
+ if (r.processNames.length > 0) {
157
+ out.process = {
158
+ include: { names: [...r.processNames], match_type: "strict" },
159
+ mute_process_name_error: true,
160
+ mute_process_exe_error: true,
161
+ mute_process_io_error: true,
162
+ mute_process_user_error: true,
163
+ metrics: enabled("process.cpu.utilization", "process.memory.utilization", "process.threads", "process.open_file_descriptors", "process.handles", "process.disk.io"),
164
+ };
165
+ }
166
+ return out;
167
+ }
168
+ function processors(r) {
169
+ const aggregations = [];
170
+ if (!r.includeInterfaceNames) {
171
+ aggregations.push({
172
+ include: "^system\\.network\\.",
173
+ match_type: "regexp",
174
+ action: "update",
175
+ operations: [{ action: "aggregate_labels", label_set: ["direction"], aggregation_type: "sum" }],
176
+ });
177
+ }
178
+ if (!r.includeMountPoints) {
179
+ aggregations.push({
180
+ include: "^system\\.paging\\.usage$",
181
+ match_type: "regexp",
182
+ action: "update",
183
+ operations: [{ action: "aggregate_labels", label_set: ["state"], aggregation_type: "sum" }],
184
+ }, {
185
+ include: "^system\\.paging\\.utilization$",
186
+ match_type: "regexp",
187
+ action: "update",
188
+ operations: [{ action: "aggregate_labels", label_set: ["state"], aggregation_type: "mean" }],
189
+ }, {
190
+ include: "^system\\.filesystem\\.usage$",
191
+ match_type: "regexp",
192
+ action: "update",
193
+ operations: [{
194
+ action: "aggregate_labels",
195
+ label_set: ["state", "type", "device"],
196
+ aggregation_type: "sum",
197
+ }],
198
+ }, {
199
+ include: "^system\\.filesystem\\.utilization$",
200
+ match_type: "regexp",
201
+ action: "update",
202
+ operations: [{ action: "aggregate_labels", label_set: ["type"], aggregation_type: "mean" }],
203
+ });
204
+ }
205
+ aggregations.push({
206
+ include: "^system\\.cpu\\.utilization$",
207
+ match_type: "regexp",
208
+ action: "update",
209
+ operations: [{ action: "aggregate_labels", label_set: ["state"], aggregation_type: "mean" }],
210
+ });
211
+ const resourceAttrs = [
212
+ { key: "service.name", value: r.serviceName, action: "upsert" },
213
+ { key: "service.namespace", value: SERVICE_NAMESPACE, action: "upsert" },
214
+ { key: "service.instance.id", value: r.instanceId, action: "upsert" },
215
+ { key: "deployment.environment", value: r.environment, action: "upsert" },
216
+ { key: "deployment.environment.name", value: r.environment, action: "upsert" },
217
+ { key: "telemetry.source", value: "agentd-host-metrics", action: "upsert" },
218
+ ];
219
+ return {
220
+ memory_limiter: {
221
+ check_interval: "1s",
222
+ limit_mib: r.memoryLimitMib,
223
+ spike_limit_mib: Math.max(16, Math.floor(r.memoryLimitMib / 4)),
224
+ },
225
+ "resourcedetection/system": {
226
+ detectors: ["env", "system"],
227
+ timeout: "5s",
228
+ override: false,
229
+ system: {
230
+ hostname_sources: ["os"],
231
+ resource_attributes: {
232
+ ...enabled("host.name", "host.arch", "os.type"),
233
+ ...disabled("host.id", "host.ip", "host.mac", "os.description", "host.cpu.vendor.id", "host.cpu.family", "host.cpu.model.id", "host.cpu.model.name", "host.cpu.stepping", "host.cpu.cache.l2.size"),
234
+ },
235
+ },
236
+ },
237
+ "resource/identity": { attributes: resourceAttrs },
238
+ "resource/redact": {
239
+ attributes: REDACTED_RESOURCE_ATTRIBUTES.map((key) => ({ key, action: "delete" })),
240
+ },
241
+ "filter/contract": {
242
+ error_mode: "ignore",
243
+ metrics: {
244
+ metric: [`not (${HOST_METRIC_CONTRACT.map((n) => `name == "${n}"`).join(" or ")})`],
245
+ },
246
+ },
247
+ ...(r.includeMountPoints ? {} : {
248
+ "transform/volume_key": {
249
+ error_mode: "ignore",
250
+ metric_statements: [
251
+ { context: "datapoint", statements: [VOLUME_KEY_STATEMENT] },
252
+ ],
253
+ },
254
+ }),
255
+ "metricstransform/cardinality": { transforms: aggregations },
256
+ batch: {
257
+ timeout: "10s",
258
+ send_batch_size: 512,
259
+ send_batch_max_size: 1024,
260
+ },
261
+ };
262
+ }
263
+ function exporters(r) {
264
+ const otlp = {
265
+ endpoint: r.endpoint,
266
+ compression: "gzip",
267
+ timeout: "30s",
268
+ tls: { insecure: r.endpoint.startsWith("http://"), min_version: "1.2" },
269
+ retry_on_failure: {
270
+ enabled: true,
271
+ initial_interval: "5s",
272
+ max_interval: "5m",
273
+ max_elapsed_time: "30m",
274
+ },
275
+ sending_queue: {
276
+ enabled: true,
277
+ num_consumers: 2,
278
+ queue_size: r.queueSize,
279
+ ...(r.queueDir ? { storage: "file_storage/otlp_queue" } : {}),
280
+ },
281
+ };
282
+ if (!r.noAuth) {
283
+ otlp.headers = { authorization: `Bearer \${env:${r.keyEnvVar}}` };
284
+ }
285
+ return { "otlphttp/codetelemetry": otlp };
286
+ }
287
+ export function buildHostMetricsConfig(opts) {
288
+ const r = resolve(opts);
289
+ const extensions = {
290
+ health_check: { endpoint: "127.0.0.1:13133" },
291
+ };
292
+ if (r.queueDir) {
293
+ extensions["file_storage/otlp_queue"] = {
294
+ directory: r.queueDir,
295
+ create_directory: true,
296
+ timeout: "10s",
297
+ compaction: { on_start: true, directory: r.queueDir, max_transaction_size: 65536 },
298
+ };
299
+ }
300
+ return {
301
+ extensions,
302
+ receivers: {
303
+ hostmetrics: {
304
+ collection_interval: `${r.intervalSec}s`,
305
+ scrapers: scrapers(r),
306
+ },
307
+ },
308
+ processors: processors(r),
309
+ exporters: exporters(r),
310
+ service: {
311
+ extensions: Object.keys(extensions),
312
+ telemetry: {
313
+ logs: { level: "warn" },
314
+ metrics: { level: "basic" },
315
+ },
316
+ pipelines: {
317
+ "metrics/host": {
318
+ receivers: ["hostmetrics"],
319
+ processors: [
320
+ "memory_limiter",
321
+ "resourcedetection/system",
322
+ "resource/identity",
323
+ "resource/redact",
324
+ "filter/contract",
325
+ ...(r.includeMountPoints ? [] : ["transform/volume_key"]),
326
+ "metricstransform/cardinality",
327
+ "batch",
328
+ ],
329
+ exporters: ["otlphttp/codetelemetry"],
330
+ },
331
+ },
332
+ },
333
+ };
334
+ }
335
+ export function renderHostMetricsConfig(opts) {
336
+ const header = [
337
+ "# CodeTelemetry agentd host metrics — generated by `codetelemetry-connect host-metrics`.",
338
+ "# Docs: docs/otel/agentd-host-metrics.md",
339
+ "#",
340
+ `# The ingest key is NOT in this file. Set the env var below on the collector`,
341
+ "# service before starting it.",
342
+ "",
343
+ ].join("\n");
344
+ return header + renderYaml(buildHostMetricsConfig(opts));
345
+ }
346
+ function str(flags, name) {
347
+ const v = flags[name];
348
+ return typeof v === "string" ? v : undefined;
349
+ }
350
+ function int(flags, name) {
351
+ const v = str(flags, name);
352
+ if (v === undefined)
353
+ return undefined;
354
+ const n = Number(v);
355
+ if (!v.trim() || !Number.isFinite(n))
356
+ throw new Error(`--${name} must be a number, got: ${v}`);
357
+ return n;
358
+ }
359
+ export function hostMetricsOptionsFromFlags(flags, defaults) {
360
+ const gateway = str(flags, "gateway");
361
+ const processes = str(flags, "processes");
362
+ const processNames = processes === undefined
363
+ ? undefined
364
+ : processes.split(",").map((s) => s.trim()).filter(Boolean);
365
+ const queueDir = flags["queue-dir"] === false ? undefined : str(flags, "queue-dir") ?? defaults.paths.queueDir;
366
+ return {
367
+ mode: gateway ? "gateway" : "direct",
368
+ endpoint: gateway ?? str(flags, "endpoint") ?? defaults.ingestEndpoint,
369
+ configPath: str(flags, "out") ?? defaults.paths.configPath,
370
+ keyEnvVar: str(flags, "key-env"),
371
+ noAuth: flags.auth === false,
372
+ instanceId: str(flags, "instance") ?? defaults.instanceId,
373
+ environment: str(flags, "env"),
374
+ intervalSec: int(flags, "interval"),
375
+ processNames,
376
+ includeInterfaceNames: flags.interfaces === true,
377
+ includeMountPoints: flags.mounts === true,
378
+ queueDir,
379
+ queueSize: int(flags, "queue-size"),
380
+ memoryLimitMib: int(flags, "memory-limit"),
381
+ allowInsecure: flags["allow-insecure"] === true,
382
+ };
383
+ }
384
+ export function defaultHostMetricsPaths(env = process.env, platform = process.platform) {
385
+ if (platform === "win32") {
386
+ const base = path.win32.join(env.ProgramData || "C:\\ProgramData", "CodeTelemetry");
387
+ return {
388
+ configPath: path.win32.join(base, "otelcol-hostmetrics.yaml"),
389
+ queueDir: path.win32.join(base, "queue"),
390
+ };
391
+ }
392
+ const etc = platform === "darwin" ? "/usr/local/etc/otelcol-contrib" : "/etc/otelcol-contrib";
393
+ const varlib = platform === "darwin" ? "/usr/local/var/lib/otelcol-contrib" : "/var/lib/otelcol-contrib";
394
+ return {
395
+ configPath: path.posix.join(etc, "codetelemetry-hostmetrics.yaml"),
396
+ queueDir: path.posix.join(varlib, "codetelemetry-queue"),
397
+ };
398
+ }
399
+ export function defaultInstanceId(hostname = os.hostname()) {
400
+ const cleaned = hostname.trim().toLowerCase().replace(/[^a-z0-9._-]/g, "-").replace(/^-+|-+$/g, "");
401
+ return cleaned || "unknown-host";
402
+ }
403
+ export function writeHostMetricsConfig(opts) {
404
+ const yaml = renderHostMetricsConfig(opts);
405
+ const filePath = path.resolve(opts.configPath);
406
+ const existed = fs.existsSync(filePath);
407
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
408
+ let backupPath = null;
409
+ if (existed && opts.backup !== false) {
410
+ backupPath = `${filePath}.bak`;
411
+ fs.copyFileSync(filePath, backupPath);
412
+ }
413
+ fs.writeFileSync(filePath, yaml, { mode: 0o600 });
414
+ try {
415
+ fs.chmodSync(filePath, 0o600);
416
+ }
417
+ catch {
418
+ }
419
+ return {
420
+ path: filePath,
421
+ created: !existed,
422
+ backupPath,
423
+ requiredEnv: opts.noAuth ? [] : [opts.keyEnvVar ?? DEFAULT_KEY_ENV],
424
+ };
425
+ }
@@ -0,0 +1,30 @@
1
+ import { type ContentBySource, type ImportRunResult } from "./core.ts";
2
+ import type { FetchLike } from "../otlp.ts";
3
+ export type UploadFile = {
4
+ name: string;
5
+ size: number;
6
+ lastModified: number;
7
+ text(): Promise<string>;
8
+ slice?(start: number, end: number): {
9
+ text(): Promise<string>;
10
+ };
11
+ };
12
+ export declare const MAX_UPLOAD_FILE_BYTES: number;
13
+ export declare const MAX_UPLOAD_TOTAL_BYTES: number;
14
+ export declare const MAX_UPLOAD_FILES = 2000;
15
+ export declare const looksLikeBrowserKey: (v: string) => boolean;
16
+ export declare function sha256HexWeb(text: string): Promise<string>;
17
+ export type BrowserImportOptions = {
18
+ key: string;
19
+ apiBase: string;
20
+ ingestEndpoint: string;
21
+ dryRun: boolean;
22
+ sinceMs?: number;
23
+ content?: Partial<ContentBySource>;
24
+ maxSessions?: number;
25
+ fetchImpl?: FetchLike;
26
+ nowMs?: number;
27
+ sleep?: (ms: number) => Promise<void>;
28
+ logger?: (msg: string) => void;
29
+ };
30
+ export declare function importFiles(files: UploadFile[], opts: BrowserImportOptions): Promise<ImportRunResult>;
@@ -0,0 +1,157 @@
1
+ import { ClaudeSessionAccumulator } from "./sources/claudeCodeText.js";
2
+ import { CodexSessionAccumulator, codexSessionIdFromName } from "./sources/codexText.js";
3
+ import { ACTIVE_GRACE_MS, bump, contentOrDefault, emptySummary, importPrepared, memoryLedger, prepareSession, resolveWindow, } from "./core.js";
4
+ export const MAX_UPLOAD_FILE_BYTES = 128 * 1024 * 1024;
5
+ export const MAX_UPLOAD_TOTAL_BYTES = 512 * 1024 * 1024;
6
+ export const MAX_UPLOAD_FILES = 2_000;
7
+ const KEY_RE = /^cot_[A-Za-z0-9_-]{16,}$/;
8
+ export const looksLikeBrowserKey = (v) => KEY_RE.test(v.trim());
9
+ const maskKey = (k) => `cot_…${k.slice(-4)}`;
10
+ export async function sha256HexWeb(text) {
11
+ const bytes = new TextEncoder().encode(text);
12
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
13
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
14
+ }
15
+ function classify(name, head) {
16
+ for (const line of head.split("\n").slice(0, 50)) {
17
+ if (!line.trim())
18
+ continue;
19
+ let r;
20
+ try {
21
+ r = JSON.parse(line);
22
+ }
23
+ catch {
24
+ continue;
25
+ }
26
+ if (r?.type === "session_meta") {
27
+ const id = r.payload?.id ?? r.payload?.session_id;
28
+ return { source: "codex", sessionId: typeof id === "string" && id ? id : codexSessionIdFromName(name) ?? name };
29
+ }
30
+ if (typeof r?.sessionId === "string" && r.sessionId)
31
+ return { source: "claude-code", sessionId: r.sessionId };
32
+ }
33
+ if (/^rollout-/i.test(name))
34
+ return { source: "codex", sessionId: codexSessionIdFromName(name) ?? name };
35
+ return null;
36
+ }
37
+ async function parseGroup(g, keep) {
38
+ const acc = g.source === "claude-code" ? new ClaudeSessionAccumulator({ keep }) : new CodexSessionAccumulator({ keep });
39
+ for (const f of g.files) {
40
+ const text = await f.text();
41
+ let start = 0;
42
+ while (start < text.length) {
43
+ const end = text.indexOf("\n", start);
44
+ acc.line(text.slice(start, end === -1 ? text.length : end));
45
+ if (acc.overflowed)
46
+ return "too_many_events";
47
+ start = end === -1 ? text.length : end + 1;
48
+ }
49
+ }
50
+ const bytes = g.files.reduce((n, f) => n + f.size, 0);
51
+ const mtime = Math.max(...g.files.map((f) => f.lastModified));
52
+ return acc.finish({ files: g.files.map((f) => f.name), fileSig: `${bytes}:${mtime}:${g.files.length}`, fallbackSessionId: g.sessionId });
53
+ }
54
+ export async function importFiles(files, opts) {
55
+ const key = opts.key.trim();
56
+ if (!looksLikeBrowserKey(key))
57
+ throw new Error("not a CodeTelemetry ingest key (expected cot_…)");
58
+ const now = opts.nowMs ?? Date.now();
59
+ const content = contentOrDefault(opts.content);
60
+ const warnings = [];
61
+ const window = resolveWindow(now, opts.sinceMs);
62
+ if (window.warning)
63
+ warnings.push(window.warning);
64
+ const summaries = new Map([
65
+ ["claude-code", emptySummary("claude-code")],
66
+ ["codex", emptySummary("codex")],
67
+ ]);
68
+ const groups = new Map();
69
+ let total = 0;
70
+ for (const f of files.slice(0, MAX_UPLOAD_FILES)) {
71
+ if (!f.name.endsWith(".jsonl")) {
72
+ warnings.push(`${f.name}: not a .jsonl session file; skipped`);
73
+ continue;
74
+ }
75
+ if (f.size > MAX_UPLOAD_FILE_BYTES || total + f.size > MAX_UPLOAD_TOTAL_BYTES) {
76
+ warnings.push(`${f.name}: too large to import in the browser; use \`npx @codetelemetry/connect import\``);
77
+ continue;
78
+ }
79
+ total += f.size;
80
+ const head = await (f.slice ? f.slice(0, 256 * 1024).text() : f.text().then((t) => t.slice(0, 256 * 1024)));
81
+ const kind = classify(f.name, head);
82
+ if (!kind) {
83
+ warnings.push(`${f.name}: not a Claude Code transcript or Codex rollout; skipped`);
84
+ continue;
85
+ }
86
+ const id = `${kind.source}:${kind.sessionId}`;
87
+ const g = groups.get(id) ?? { ...kind, files: [] };
88
+ g.files.push(f);
89
+ groups.set(id, g);
90
+ summaries.get(kind.source).filesFound++;
91
+ }
92
+ if (files.length > MAX_UPLOAD_FILES)
93
+ warnings.push(`only the first ${MAX_UPLOAD_FILES} files were read`);
94
+ const prepareOpts = {
95
+ sinceMs: window.sinceMs,
96
+ untilMs: window.untilMs,
97
+ caseInsensitivePaths: false,
98
+ content,
99
+ sha256Hex: sha256HexWeb,
100
+ };
101
+ const prepared = [];
102
+ for (const g of groups.values()) {
103
+ const s = summaries.get(g.source);
104
+ const mtime = Math.max(...g.files.map((f) => f.lastModified));
105
+ if (mtime < window.sinceMs) {
106
+ bump(s, "older");
107
+ continue;
108
+ }
109
+ if (mtime > now - ACTIVE_GRACE_MS) {
110
+ bump(s, "active");
111
+ continue;
112
+ }
113
+ const session = await parseGroup(g, content[g.source]);
114
+ if (session === "too_many_events") {
115
+ bump(s, "too_many_events");
116
+ continue;
117
+ }
118
+ if (!session) {
119
+ bump(s, "empty");
120
+ continue;
121
+ }
122
+ s.sessionsParsed++;
123
+ const reload = async () => {
124
+ const again = await parseGroup(g, content[g.source]);
125
+ return again === "too_many_events" ? null : again;
126
+ };
127
+ const p = await prepareSession(session, session.fileSig, reload, prepareOpts);
128
+ if (typeof p === "string") {
129
+ bump(s, p);
130
+ continue;
131
+ }
132
+ s.candidates++;
133
+ prepared.push(p);
134
+ }
135
+ const keyHash = await sha256HexWeb(key);
136
+ return importPrepared(prepared, {
137
+ ...prepareOpts,
138
+ key,
139
+ keyHash,
140
+ keyMasked: maskKey(key),
141
+ statusUrl: `${opts.apiBase.replace(/\/$/, "")}/api/agent/import-status`,
142
+ ingestEndpoint: opts.ingestEndpoint.replace(/\/$/, ""),
143
+ dryRun: opts.dryRun,
144
+ run: crypto.randomUUID(),
145
+ importTool: "web-upload",
146
+ maxSessions: opts.maxSessions,
147
+ clamped: window.clamped,
148
+ now,
149
+ clock: () => (opts.nowMs === undefined ? Date.now() : opts.nowMs),
150
+ fetchImpl: opts.fetchImpl ?? ((input, init) => fetch(input, init)),
151
+ sleep: opts.sleep,
152
+ ledger: memoryLedger(),
153
+ summaries,
154
+ warnings,
155
+ logger: opts.logger,
156
+ });
157
+ }
@@ -0,0 +1,20 @@
1
+ import type { ContentPolicy, ImportLog, ImportMetric, ImportedSession } from "./model.ts";
2
+ export declare const CLAUDE_SERVICE = "claude-code";
3
+ export declare const CODEX_SERVICE = "codex-cli";
4
+ export declare const TOKEN_USAGE_METRIC = "claude_code.token.usage";
5
+ export declare const REDACTED = "<REDACTED>";
6
+ export declare const IMPORT_COMPLETE_EVENT = "import.session_complete";
7
+ export declare const IMPORT_FORBIDDEN_EVENTS: readonly string[];
8
+ export declare const IMPORT_FORBIDDEN_ATTRIBUTES: readonly string[];
9
+ export declare const IMPORT_FORBIDDEN_METRICS: readonly string[];
10
+ export type ConvertedSession = {
11
+ logs: ImportLog[];
12
+ metrics: ImportMetric[];
13
+ };
14
+ export declare function convertSession(session: ImportedSession, content: ContentPolicy): ConvertedSession;
15
+ export declare function completionMarker(session: ImportedSession, plan: {
16
+ id: string;
17
+ logParts: number;
18
+ metricParts: number;
19
+ events: number;
20
+ }): ImportLog;