@codetelemetry/mcp 0.3.9 → 0.3.12
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 +1 -1
- package/README.md +81 -9
- package/dist/src/client/agent.d.ts +201 -3
- package/dist/src/client/agent.js +154 -0
- package/dist/src/client/assistants.d.ts +4 -0
- package/dist/src/client/assistants.js +5 -0
- package/dist/src/client/bin.d.ts +2 -0
- package/dist/src/client/bin.js +3 -0
- package/dist/src/client/cli.d.ts +1 -0
- package/dist/src/client/cli.js +567 -0
- package/dist/src/client/clients.d.ts +34 -0
- package/dist/src/client/clients.js +74 -0
- package/dist/src/client/codexConfig.d.ts +1 -0
- package/dist/src/client/codexConfig.js +5 -0
- package/dist/src/client/config.d.ts +5 -0
- package/dist/src/client/config.js +5 -0
- package/dist/src/client/graderSeed.d.ts +50 -0
- package/dist/src/client/graderSeed.js +289 -0
- package/dist/src/client/hostMetrics.d.ts +54 -0
- package/dist/src/client/hostMetrics.js +425 -0
- package/dist/src/client/import/browser.d.ts +30 -0
- package/dist/src/client/import/browser.js +157 -0
- package/dist/src/client/import/convert.d.ts +20 -0
- package/dist/src/client/import/convert.js +165 -0
- package/dist/src/client/import/core.d.ts +143 -0
- package/dist/src/client/import/core.js +441 -0
- package/dist/src/client/import/ledger.d.ts +52 -0
- package/dist/src/client/import/ledger.js +161 -0
- package/dist/src/client/import/model.d.ts +70 -0
- package/dist/src/client/import/model.js +42 -0
- package/dist/src/client/import/options.d.ts +24 -0
- package/dist/src/client/import/options.js +71 -0
- package/dist/src/client/import/otlpImport.d.ts +7 -0
- package/dist/src/client/import/otlpImport.js +81 -0
- package/dist/src/client/import/protocol.d.ts +35 -0
- package/dist/src/client/import/protocol.js +51 -0
- package/dist/src/client/import/run.d.ts +30 -0
- package/dist/src/client/import/run.js +127 -0
- package/dist/src/client/import/sources/claudeCodeText.d.ts +19 -0
- package/dist/src/client/import/sources/claudeCodeText.js +214 -0
- package/dist/src/client/import/sources/codexText.d.ts +20 -0
- package/dist/src/client/import/sources/codexText.js +319 -0
- package/dist/src/client/import/sources/files.d.ts +24 -0
- package/dist/src/client/import/sources/files.js +129 -0
- package/dist/src/client/import/transport.d.ts +76 -0
- package/dist/src/client/import/transport.js +141 -0
- package/dist/src/client/index.d.ts +19 -0
- package/dist/src/client/index.js +19 -0
- package/dist/src/client/kiro/collector.d.ts +88 -0
- package/dist/src/client/kiro/collector.js +577 -0
- package/dist/src/client/kiro/command.d.ts +3 -0
- package/dist/src/client/kiro/command.js +109 -0
- package/dist/src/client/kiro/config.d.ts +39 -0
- package/dist/src/client/kiro/config.js +107 -0
- package/dist/src/client/kiro/records.d.ts +52 -0
- package/dist/src/client/kiro/records.js +206 -0
- package/dist/src/client/kiro/service.d.ts +21 -0
- package/dist/src/client/kiro/service.js +183 -0
- package/dist/src/client/kiro/state.d.ts +45 -0
- package/dist/src/client/kiro/state.js +205 -0
- package/dist/src/client/kiro/transport.d.ts +9 -0
- package/dist/src/client/kiro/transport.js +90 -0
- package/dist/src/client/onboard.d.ts +5 -1
- package/dist/src/client/onboard.js +28 -23
- package/dist/src/client/piConfig.d.ts +29 -0
- package/dist/src/client/piConfig.js +112 -0
- package/dist/src/client/plan.d.ts +1 -1
- package/dist/src/client/plan.js +2 -1
- package/dist/src/client/settings.d.ts +4 -0
- package/dist/src/client/settings.js +17 -0
- package/dist/src/client/yaml.d.ts +5 -0
- package/dist/src/client/yaml.js +72 -0
- package/dist/src/mcpServer.js +1 -1
- package/dist/src/tools.d.ts +9 -6
- package/dist/src/tools.js +370 -60
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +178 -9
- package/tool-manifest.json +430 -21
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
+
import { KiroCollector } from "./collector.js";
|
|
5
|
+
import { readKiroConfig, resolveKiroConfigPath } from "./config.js";
|
|
6
|
+
import { kiroTransport } from "./transport.js";
|
|
7
|
+
import { readBoundedJson, writeAtomicJson } from "./state.js";
|
|
8
|
+
import { enableKiroService, disableKiroService, uninstallKiroService } from "./service.js";
|
|
9
|
+
const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
10
|
+
export async function runKiroCommand(args, flags, out) {
|
|
11
|
+
const operation = args[0] ?? "status";
|
|
12
|
+
if (args.length > 1 || !["collect", "status", "enable", "disable", "uninstall"].includes(operation)) {
|
|
13
|
+
out("Usage: codetelemetry-connect kiro status|collect|enable|disable|uninstall [--settings <path>] [--json]; collect supports --once.");
|
|
14
|
+
return 1;
|
|
15
|
+
}
|
|
16
|
+
const rogue = Object.keys(flags).find(key => !["settings", "json", "once"].includes(key));
|
|
17
|
+
if (rogue || (flags.settings !== undefined && typeof flags.settings !== "string") ||
|
|
18
|
+
["json", "once"].some(key => flags[key] !== undefined && typeof flags[key] !== "boolean") ||
|
|
19
|
+
(flags.once !== undefined && operation !== "collect")) {
|
|
20
|
+
out("Invalid Kiro command options.");
|
|
21
|
+
return 1;
|
|
22
|
+
}
|
|
23
|
+
const file = resolveKiroConfigPath({ path: typeof flags.settings === "string" ? flags.settings : undefined });
|
|
24
|
+
if (operation === "enable" || operation === "disable" || operation === "uninstall") {
|
|
25
|
+
const result = operation === "enable" ? await enableKiroService(file)
|
|
26
|
+
: operation === "disable" ? disableKiroService(file) : uninstallKiroService(file);
|
|
27
|
+
out(flags.json ? JSON.stringify(result) : result.detail);
|
|
28
|
+
return result.ok ? 0 : 1;
|
|
29
|
+
}
|
|
30
|
+
const config = readKiroConfig(file);
|
|
31
|
+
if (operation === "status") {
|
|
32
|
+
const raw = await readBoundedJson(path.join(config.stateDir, "health.json"), 16 * 1024);
|
|
33
|
+
const fields = ["version", "trackedSessions", "parkedSessions", "skippingOversizeSessions", "cachedTailBytes", "cachedTailSessions", "carryEvictions", "discoveryBacklog", "backloggedSessions", "unsupportedSessions", "sourceConflicts", "sourceErrors", "ignoredRecords", "malformedRecords", "duplicateRecords", "evictedCalls", "missingCalls", "unsupportedToolDetails", "discoveryOverflow", "oversizeRecords", "readBytes", "logsAcknowledged", "requests", "lastTickAt", "pid"];
|
|
34
|
+
const health = raw ? Object.fromEntries(fields.filter(key => Number.isSafeInteger(raw[key]) && Number(raw[key]) >= 0).map(key => [key, raw[key]])) : null;
|
|
35
|
+
if (health && raw) {
|
|
36
|
+
health.status = ["idle", "pending", "ok", "retry", "auth", "budget", "rejected", "retry_horizon_exhausted", "clock_rollback", "capacity"].includes(String(raw.status)) ? raw.status : "unknown";
|
|
37
|
+
health.pending = raw.pending === true;
|
|
38
|
+
}
|
|
39
|
+
let running = false;
|
|
40
|
+
if (raw?.running === true && health && Number(health.pid) > 0 && Date.now() - Number(health.lastTickAt) >= 0 && Date.now() - Number(health.lastTickAt) < 30000) {
|
|
41
|
+
try {
|
|
42
|
+
process.kill(Number(health.pid), 0);
|
|
43
|
+
running = true;
|
|
44
|
+
}
|
|
45
|
+
catch { }
|
|
46
|
+
}
|
|
47
|
+
const value = { running, enabled: config.enabled, capture: config.content.prompts || config.content.toolDetails ? "content opt-in" : "metadata-only", health };
|
|
48
|
+
out(JSON.stringify(value, null, flags.json ? undefined : 2));
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
if (Number(process.versions.node.split(".")[0]) < 24) {
|
|
52
|
+
out("Kiro collection requires Node 24 or newer.");
|
|
53
|
+
return 1;
|
|
54
|
+
}
|
|
55
|
+
if (!config.enabled) {
|
|
56
|
+
out("Kiro collection is disabled. Run kiro enable to start it.");
|
|
57
|
+
return 1;
|
|
58
|
+
}
|
|
59
|
+
const binding = digest([config.key, config.ingestEndpoint]);
|
|
60
|
+
const fingerprint = digest(config);
|
|
61
|
+
const collector = new KiroCollector({ sourceRoot: config.sourceRoot, stateDir: config.stateDir, destinationHash: binding,
|
|
62
|
+
policy: config.content, bootstrap: config.backfill ? "start" : "end", post: kiroTransport({ endpoint: config.ingestEndpoint, key: config.key }) });
|
|
63
|
+
const abort = new AbortController();
|
|
64
|
+
const stop = () => abort.abort();
|
|
65
|
+
process.on("SIGINT", stop);
|
|
66
|
+
process.on("SIGTERM", stop);
|
|
67
|
+
let exit = 0, opened = false;
|
|
68
|
+
try {
|
|
69
|
+
await collector.open();
|
|
70
|
+
opened = true;
|
|
71
|
+
do {
|
|
72
|
+
const current = readKiroConfig(file);
|
|
73
|
+
if (!current.enabled)
|
|
74
|
+
break;
|
|
75
|
+
if (digest(current) !== fingerprint) {
|
|
76
|
+
out("Kiro configuration changed; restart required, recovery state preserved.");
|
|
77
|
+
exit = 1;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
let health = await collector.tick();
|
|
81
|
+
if (flags.once && health.pending)
|
|
82
|
+
health = await collector.tick();
|
|
83
|
+
await writeAtomicJson(path.join(config.stateDir, "health.json"), { ...health, running: !flags.once, pid: process.pid }, 16 * 1024);
|
|
84
|
+
if (flags.once) {
|
|
85
|
+
out(JSON.stringify(health));
|
|
86
|
+
exit = health.status === "capacity" || health.pending || health.sourceConflicts || health.sourceErrors || health.unsupportedSessions || health.discoveryOverflow || health.discoveryBacklog || health.backloggedSessions ? 1 : 0;
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
await delay(1000, undefined, { signal: abort.signal }).catch(error => { if (!abort.signal.aborted)
|
|
90
|
+
throw error; });
|
|
91
|
+
} while (!abort.signal.aborted);
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
try {
|
|
95
|
+
if (opened)
|
|
96
|
+
await writeAtomicJson(path.join(config.stateDir, "health.json"), { ...collector.snapshot(), running: false, pid: process.pid }, 16 * 1024);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
try {
|
|
100
|
+
await collector.close();
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
process.off("SIGINT", stop);
|
|
104
|
+
process.off("SIGTERM", stop);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return exit;
|
|
109
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { WriteResult } from "../settings.ts";
|
|
2
|
+
import type { ContentPolicy } from "../import/model.ts";
|
|
3
|
+
export type KiroConfig = {
|
|
4
|
+
kind: "codetelemetry-kiro-v3";
|
|
5
|
+
version: 1;
|
|
6
|
+
enabled: boolean;
|
|
7
|
+
key: string;
|
|
8
|
+
ingestEndpoint: string;
|
|
9
|
+
sourceRoot: string;
|
|
10
|
+
stateDir: string;
|
|
11
|
+
content: ContentPolicy;
|
|
12
|
+
backfill: boolean;
|
|
13
|
+
};
|
|
14
|
+
export declare function kiroPaths(home?: string): {
|
|
15
|
+
config: string;
|
|
16
|
+
sourceRoot: string;
|
|
17
|
+
stateDir: string;
|
|
18
|
+
runtimeDir: string;
|
|
19
|
+
};
|
|
20
|
+
export declare function resolveKiroConfigPath(opts?: {
|
|
21
|
+
path?: string;
|
|
22
|
+
home?: string;
|
|
23
|
+
}): string;
|
|
24
|
+
export declare function readKiroConfig(file: string): KiroConfig;
|
|
25
|
+
export declare function writeKiroConfig(opts: {
|
|
26
|
+
key: string;
|
|
27
|
+
ingestEndpoint: string;
|
|
28
|
+
configPath: string;
|
|
29
|
+
enrich?: boolean;
|
|
30
|
+
backup?: boolean;
|
|
31
|
+
}): WriteResult;
|
|
32
|
+
export declare function setKiroEnabled(file: string, enabled: boolean): void;
|
|
33
|
+
export declare function readKiroKey(file: string): string | null;
|
|
34
|
+
export declare function readKiroSummary(file: string): {
|
|
35
|
+
exists: boolean;
|
|
36
|
+
otelKeys: string[];
|
|
37
|
+
hasKey: boolean;
|
|
38
|
+
collectorEnabled: boolean;
|
|
39
|
+
};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { assertKey, looksLikeKey } from "../keys.js";
|
|
5
|
+
export function kiroPaths(home = os.homedir()) {
|
|
6
|
+
return { config: path.join(home, ".config", "codetelemetry", "kiro-v3.json"),
|
|
7
|
+
sourceRoot: path.join(home, ".kiro", "sessions"), stateDir: path.join(home, ".local", "state", "codetelemetry", "kiro-v3"),
|
|
8
|
+
runtimeDir: path.join(home, ".local", "share", "codetelemetry", "kiro-v3") };
|
|
9
|
+
}
|
|
10
|
+
export function resolveKiroConfigPath(opts = {}) {
|
|
11
|
+
const file = path.resolve(opts.path ?? kiroPaths(opts.home).config);
|
|
12
|
+
if (file.split(path.sep).includes(".kiro"))
|
|
13
|
+
throw new Error("CodeTelemetry Kiro config must be outside Kiro's own configuration directory");
|
|
14
|
+
return file;
|
|
15
|
+
}
|
|
16
|
+
export function readKiroConfig(file) {
|
|
17
|
+
const stat = fs.lstatSync(file);
|
|
18
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024)
|
|
19
|
+
throw new Error("Kiro collector config is unreadable or exceeds bound");
|
|
20
|
+
let config;
|
|
21
|
+
try {
|
|
22
|
+
config = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new Error("Kiro collector config is not valid JSON");
|
|
26
|
+
}
|
|
27
|
+
if (config?.kind !== "codetelemetry-kiro-v3" || config.version !== 1)
|
|
28
|
+
throw new Error("unsupported Kiro collector config contract");
|
|
29
|
+
assertKey(config.key);
|
|
30
|
+
if (typeof config.enabled !== "boolean" || typeof config.backfill !== "boolean" ||
|
|
31
|
+
typeof config.sourceRoot !== "string" || !path.isAbsolute(config.sourceRoot) || config.sourceRoot.length > 4096 ||
|
|
32
|
+
typeof config.stateDir !== "string" || !path.isAbsolute(config.stateDir) || config.stateDir.length > 4096 ||
|
|
33
|
+
typeof config.content?.prompts !== "boolean" || typeof config.content.toolDetails !== "boolean")
|
|
34
|
+
throw new Error("invalid Kiro collector config fields");
|
|
35
|
+
let endpoint;
|
|
36
|
+
try {
|
|
37
|
+
endpoint = new URL(config.ingestEndpoint);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error("invalid Kiro ingest endpoint");
|
|
41
|
+
}
|
|
42
|
+
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash)
|
|
43
|
+
throw new Error("invalid Kiro ingest endpoint");
|
|
44
|
+
return config;
|
|
45
|
+
}
|
|
46
|
+
function persistConfig(file, config) {
|
|
47
|
+
const body = JSON.stringify(config, null, 2) + "\n";
|
|
48
|
+
if (Buffer.byteLength(body) > 64 * 1024)
|
|
49
|
+
throw new Error("Kiro collector config exceeds bound");
|
|
50
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
51
|
+
const temporary = file + ".tmp";
|
|
52
|
+
const fd = fs.openSync(temporary, "wx", 0o600);
|
|
53
|
+
try {
|
|
54
|
+
fs.writeFileSync(fd, body);
|
|
55
|
+
fs.fsyncSync(fd);
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
fs.closeSync(fd);
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
fs.renameSync(temporary, file);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
fs.unlinkSync(temporary);
|
|
65
|
+
throw new Error("Kiro collector config commit failed");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function writeKiroConfig(opts) {
|
|
69
|
+
const file = resolveKiroConfigPath({ path: opts.configPath });
|
|
70
|
+
const exists = fs.existsSync(file), prior = exists ? readKiroConfig(file) : null;
|
|
71
|
+
const defaults = kiroPaths();
|
|
72
|
+
const config = { kind: "codetelemetry-kiro-v3", version: 1, enabled: true,
|
|
73
|
+
sourceRoot: prior?.sourceRoot ?? defaults.sourceRoot, stateDir: prior?.stateDir ?? defaults.stateDir,
|
|
74
|
+
backfill: prior?.backfill ?? false, content: opts.enrich ? { prompts: true, toolDetails: true } : prior?.content ?? { prompts: false, toolDetails: false },
|
|
75
|
+
key: assertKey(opts.key), ingestEndpoint: opts.ingestEndpoint };
|
|
76
|
+
const endpoint = new URL(config.ingestEndpoint);
|
|
77
|
+
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash)
|
|
78
|
+
throw new Error("invalid Kiro ingest endpoint");
|
|
79
|
+
let backupPath = null;
|
|
80
|
+
if (exists && opts.backup !== false) {
|
|
81
|
+
backupPath = file + ".previous";
|
|
82
|
+
fs.copyFileSync(file, backupPath);
|
|
83
|
+
fs.chmodSync(backupPath, 0o600);
|
|
84
|
+
}
|
|
85
|
+
persistConfig(file, config);
|
|
86
|
+
return { path: file, created: !exists, backupPath, wrote: ["key", "ingestEndpoint", "enabled", "sourceRoot", "stateDir", "content", "backfill"] };
|
|
87
|
+
}
|
|
88
|
+
export function setKiroEnabled(file, enabled) {
|
|
89
|
+
const config = readKiroConfig(resolveKiroConfigPath({ path: file }));
|
|
90
|
+
persistConfig(file, { ...config, enabled });
|
|
91
|
+
}
|
|
92
|
+
export function readKiroKey(file) { try {
|
|
93
|
+
return readKiroConfig(file).key;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
} }
|
|
98
|
+
export function readKiroSummary(file) {
|
|
99
|
+
const exists = fs.existsSync(file);
|
|
100
|
+
try {
|
|
101
|
+
const config = readKiroConfig(file);
|
|
102
|
+
return { exists, otelKeys: ["ingestEndpoint", "content", "sourceRoot"], hasKey: looksLikeKey(config.key), collectorEnabled: config.enabled };
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return { exists, otelKeys: [], hasKey: false, collectorEnabled: false };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { ContentPolicy, ImportLog } from "../import/model.ts";
|
|
2
|
+
export declare const KIRO_LIMITS: Readonly<{
|
|
3
|
+
sessions: 128;
|
|
4
|
+
sessionsPerTick: 8;
|
|
5
|
+
directoryEntriesPerTick: 512;
|
|
6
|
+
readBytesPerSession: number;
|
|
7
|
+
recordBytes: number;
|
|
8
|
+
recordsPerTick: 1024;
|
|
9
|
+
logsPerBatch: 256;
|
|
10
|
+
envelopeBytes: number;
|
|
11
|
+
replayEntriesPerSession: 128;
|
|
12
|
+
callsPerSession: 32;
|
|
13
|
+
registeredSessions: 8192;
|
|
14
|
+
parkedReplayEntries: 8;
|
|
15
|
+
candidateChecksPerTick: 32;
|
|
16
|
+
carrySessions: 256;
|
|
17
|
+
carryBytes: number;
|
|
18
|
+
checkpointBytes: number;
|
|
19
|
+
spoolBytes: number;
|
|
20
|
+
toolInputChars: 1024;
|
|
21
|
+
promptChars: number;
|
|
22
|
+
requestMs: 10000;
|
|
23
|
+
retryHorizonMs: number;
|
|
24
|
+
maxAttempts: 1000;
|
|
25
|
+
requestGapMs: 1000;
|
|
26
|
+
}>;
|
|
27
|
+
export type KiroCall = {
|
|
28
|
+
id: string;
|
|
29
|
+
name: string;
|
|
30
|
+
executionId: string | null;
|
|
31
|
+
input?: string;
|
|
32
|
+
status?: string;
|
|
33
|
+
denied?: true;
|
|
34
|
+
};
|
|
35
|
+
export type KiroRecordState = {
|
|
36
|
+
seen: Array<[string, string]>;
|
|
37
|
+
calls: KiroCall[];
|
|
38
|
+
};
|
|
39
|
+
export type KiroRecordCounters = {
|
|
40
|
+
unknown: number;
|
|
41
|
+
malformed: number;
|
|
42
|
+
duplicates: number;
|
|
43
|
+
callsEvicted: number;
|
|
44
|
+
unsupportedDetails: number;
|
|
45
|
+
};
|
|
46
|
+
export declare const emptyRecordState: () => KiroRecordState;
|
|
47
|
+
export declare const emptyRecordCounters: () => KiroRecordCounters;
|
|
48
|
+
export declare const KIRO_CREDENTIAL_RE: RegExp;
|
|
49
|
+
export declare class KiroSourceConflictError extends Error {
|
|
50
|
+
constructor();
|
|
51
|
+
}
|
|
52
|
+
export declare function applyKiroRecord(state: KiroRecordState, line: Uint8Array, sessionId: string, policy: ContentPolicy, counters: KiroRecordCounters): ImportLog[];
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { looksLikeKey, scrub as scrubKey } from "../keys.js";
|
|
3
|
+
export const KIRO_LIMITS = Object.freeze({
|
|
4
|
+
sessions: 128, sessionsPerTick: 8, directoryEntriesPerTick: 512,
|
|
5
|
+
readBytesPerSession: 64 * 1024, recordBytes: 128 * 1024,
|
|
6
|
+
recordsPerTick: 1024, logsPerBatch: 256, envelopeBytes: 256 * 1024,
|
|
7
|
+
replayEntriesPerSession: 128, callsPerSession: 32,
|
|
8
|
+
registeredSessions: 8192, parkedReplayEntries: 8, candidateChecksPerTick: 32,
|
|
9
|
+
carrySessions: 256, carryBytes: 32 * 1024 * 1024,
|
|
10
|
+
checkpointBytes: 16 * 1024 * 1024, spoolBytes: 4 * 1024 * 1024,
|
|
11
|
+
toolInputChars: 1024, promptChars: 16 * 1024,
|
|
12
|
+
requestMs: 10_000, retryHorizonMs: 23 * 60 * 60 * 1000,
|
|
13
|
+
maxAttempts: 1000, requestGapMs: 1000,
|
|
14
|
+
});
|
|
15
|
+
export const emptyRecordState = () => ({ seen: [], calls: [] });
|
|
16
|
+
export const emptyRecordCounters = () => ({ unknown: 0, malformed: 0, duplicates: 0, callsEvicted: 0, unsupportedDetails: 0 });
|
|
17
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
18
|
+
export const KIRO_CREDENTIAL_RE = /(?:-----BEGIN [A-Z ]+(?:PRIVATE KEY|CREDENTIAL)-----|\bBearer\s+[A-Za-z0-9._~+\/-]+=*|\b(?:api[_-]?key|authorization|client[_-]?secret|password|passwd|secret|token|accountkey)\s*[:=]\s*\S+|\bAKIA[0-9A-Z]{16}\b|\bASIA[0-9A-Z]{16}\b|\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}\b|\bgh[pousr]_[A-Za-z0-9]{20,}\b|\bxox[baprs]-[A-Za-z0-9-]{10,}\b|\bnpm_[A-Za-z0-9]{20,}\b|\bAIza[A-Za-z0-9_-]{20,}\b|\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b|https?:\/\/[^\s/]*:[^\s/@]+@)/i;
|
|
19
|
+
const sourceId = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value) && !KIRO_CREDENTIAL_RE.test(value) && !looksLikeKey(value) ? value : null;
|
|
20
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
21
|
+
export class KiroSourceConflictError extends Error {
|
|
22
|
+
constructor() { super("Kiro source record identity conflicts with previously captured content"); this.name = "KiroSourceConflictError"; }
|
|
23
|
+
}
|
|
24
|
+
function recordDigest(value) {
|
|
25
|
+
let nodes = 0;
|
|
26
|
+
const ordered = (item, depth) => {
|
|
27
|
+
if (++nodes > 20_000 || depth > 32)
|
|
28
|
+
throw new Error("Kiro source structure exceeds bound");
|
|
29
|
+
if (Array.isArray(item))
|
|
30
|
+
return item.map(value => ordered(value, depth + 1));
|
|
31
|
+
const record = object(item);
|
|
32
|
+
return record ? Object.fromEntries(Object.keys(record).sort().map(key => [key, ordered(record[key], depth + 1)])) : item;
|
|
33
|
+
};
|
|
34
|
+
return hash(JSON.stringify(ordered(value, 0)));
|
|
35
|
+
}
|
|
36
|
+
function sourceNano(value) {
|
|
37
|
+
if (typeof value !== "string")
|
|
38
|
+
return null;
|
|
39
|
+
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:[.](\d{1,9}))?Z$/.exec(value);
|
|
40
|
+
if (!match)
|
|
41
|
+
return null;
|
|
42
|
+
const ms = Date.parse(`${match[1]}Z`);
|
|
43
|
+
if (!Number.isFinite(ms) || new Date(ms).toISOString().slice(0, 19) !== match[1])
|
|
44
|
+
return null;
|
|
45
|
+
return String(BigInt(ms) * 1000000n + BigInt((match[2] ?? "").padEnd(9, "0")));
|
|
46
|
+
}
|
|
47
|
+
function scrub(value, max) {
|
|
48
|
+
return scrubKey(value)
|
|
49
|
+
.replace(/-----BEGIN ([A-Z ]*(?:PRIVATE KEY|CREDENTIAL))-----[\s\S]*?(?:-----END \1-----|$)/gi, "<REDACTED>")
|
|
50
|
+
.replace(new RegExp(KIRO_CREDENTIAL_RE.source, "gi"), "<REDACTED>")
|
|
51
|
+
.replace(/(["']?(?:api[_-]?key|authorization|client[_-]?secret|password|passwd|secret|token)["']?\s*[:=]\s*["']?)[^\s,"'}]+/gi, "$1<REDACTED>")
|
|
52
|
+
.slice(0, max);
|
|
53
|
+
}
|
|
54
|
+
function allowedToolArgs(name, value) {
|
|
55
|
+
const args = object(value);
|
|
56
|
+
if (!args)
|
|
57
|
+
return null;
|
|
58
|
+
const only = (keys) => Object.keys(args).every(key => keys.includes(key));
|
|
59
|
+
if (name === "execute_bash")
|
|
60
|
+
return only(["command", "cwd", "run_in_background"]) && typeof args.command === "string" && typeof args.cwd === "string" && typeof args.run_in_background === "boolean" ? args : null;
|
|
61
|
+
if (typeof args.path !== "string")
|
|
62
|
+
return null;
|
|
63
|
+
if (name === "read_file")
|
|
64
|
+
return only(["path", "offset", "limit"]) &&
|
|
65
|
+
(args.offset == null || (Number.isSafeInteger(args.offset) && Number(args.offset) >= 0)) &&
|
|
66
|
+
(args.limit == null || (Number.isSafeInteger(args.limit) && Number(args.limit) >= 1)) ? args : null;
|
|
67
|
+
if (name === "fs_write")
|
|
68
|
+
return only(["path", "text"]) && typeof args.text === "string" ? args : null;
|
|
69
|
+
if (name === "str_replace")
|
|
70
|
+
return only(["path", "oldStr", "newStr", "replace_all"]) && typeof args.oldStr === "string" && typeof args.newStr === "string" && typeof args.replace_all === "boolean" ? args : null;
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
function privateInput(name, value) {
|
|
74
|
+
const args = allowedToolArgs(name, value);
|
|
75
|
+
if (!args)
|
|
76
|
+
return undefined;
|
|
77
|
+
const encoded = JSON.stringify(args);
|
|
78
|
+
if (encoded.length > KIRO_LIMITS.toolInputChars)
|
|
79
|
+
return undefined;
|
|
80
|
+
if (Object.values(args).some(item => typeof item === "string" && (scrub(item, item.length) !== item || /<REDACTED>|cot_…/.test(item))))
|
|
81
|
+
return undefined;
|
|
82
|
+
return encoded;
|
|
83
|
+
}
|
|
84
|
+
export function applyKiroRecord(state, line, sessionId, policy, counters) {
|
|
85
|
+
if (line.byteLength > KIRO_LIMITS.recordBytes || !sourceId(sessionId)) {
|
|
86
|
+
counters.malformed++;
|
|
87
|
+
return [];
|
|
88
|
+
}
|
|
89
|
+
let record;
|
|
90
|
+
try {
|
|
91
|
+
record = object(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line)));
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
counters.malformed++;
|
|
95
|
+
return [];
|
|
96
|
+
}
|
|
97
|
+
const payload = object(record?.payload);
|
|
98
|
+
if (!record || !payload) {
|
|
99
|
+
counters.malformed++;
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
const kind = payload.type;
|
|
103
|
+
if (!["user", "tool_call", "tool_result", "usage_summary", "turn_end"].includes(String(kind))) {
|
|
104
|
+
counters.unknown++;
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
107
|
+
const id = sourceId(record.id), executionId = sourceId(payload.executionId), nano = sourceNano(record.timestamp);
|
|
108
|
+
if (!id || !nano) {
|
|
109
|
+
counters.malformed++;
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
let digest;
|
|
113
|
+
try {
|
|
114
|
+
digest = recordDigest(record);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
counters.malformed++;
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
const identity = hash(id), prior = state.seen.find(entry => entry[0] === identity);
|
|
121
|
+
if (prior) {
|
|
122
|
+
if (prior[1] !== digest)
|
|
123
|
+
throw new KiroSourceConflictError();
|
|
124
|
+
counters.duplicates++;
|
|
125
|
+
return [];
|
|
126
|
+
}
|
|
127
|
+
const source = { type: kind, ...(executionId ? { executionId } : {}) };
|
|
128
|
+
if (kind === "user") {
|
|
129
|
+
if (typeof payload.content === "string") {
|
|
130
|
+
source.contentLength = payload.content.length;
|
|
131
|
+
if (policy.prompts)
|
|
132
|
+
source.content = scrub(payload.content, KIRO_LIMITS.promptChars);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
else if (kind === "tool_call") {
|
|
136
|
+
const callId = sourceId(payload.toolCallId), name = sourceId(payload.toolName);
|
|
137
|
+
if (!callId || !name || name.length > 128) {
|
|
138
|
+
counters.malformed++;
|
|
139
|
+
return [];
|
|
140
|
+
}
|
|
141
|
+
const input = policy.toolDetails ? privateInput(name, payload.args) : undefined;
|
|
142
|
+
if (policy.toolDetails && input === undefined)
|
|
143
|
+
counters.unsupportedDetails++;
|
|
144
|
+
const status = sourceId(payload.status);
|
|
145
|
+
state.calls.push({ id: callId, name, executionId, ...(input ? { input } : {}), ...(status ? { status } : {}) });
|
|
146
|
+
if (state.calls.length > KIRO_LIMITS.callsPerSession) {
|
|
147
|
+
state.calls.shift();
|
|
148
|
+
counters.callsEvicted++;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
else if (kind === "tool_result") {
|
|
152
|
+
const callId = sourceId(payload.toolCallId);
|
|
153
|
+
if (!callId) {
|
|
154
|
+
counters.malformed++;
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
source.toolCallId = callId;
|
|
158
|
+
if (typeof payload.success === "boolean")
|
|
159
|
+
source.success = payload.success;
|
|
160
|
+
}
|
|
161
|
+
else if (kind === "usage_summary") {
|
|
162
|
+
if (!executionId || !Array.isArray(payload.promptTurnSummaries) || payload.promptTurnSummaries.length > 16) {
|
|
163
|
+
counters.malformed++;
|
|
164
|
+
return [];
|
|
165
|
+
}
|
|
166
|
+
source.promptTurnSummaries = payload.promptTurnSummaries.map(value => {
|
|
167
|
+
const item = object(value);
|
|
168
|
+
return { ...(sourceId(item?.unit) ? { unit: item.unit } : {}), ...(typeof item?.usage === "number" && Number.isFinite(item.usage) ? { usage: item.usage } : {}) };
|
|
169
|
+
});
|
|
170
|
+
if (typeof payload.elapsedTime === "number" && Number.isFinite(payload.elapsedTime))
|
|
171
|
+
source.elapsedTime = payload.elapsedTime;
|
|
172
|
+
if (sourceId(payload.status))
|
|
173
|
+
source.status = payload.status;
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
if (!executionId) {
|
|
177
|
+
counters.malformed++;
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
if (sourceId(payload.stopReason))
|
|
181
|
+
source.stopReason = payload.stopReason;
|
|
182
|
+
}
|
|
183
|
+
const context = kind === "tool_result" ? state.calls.map(call => {
|
|
184
|
+
let input;
|
|
185
|
+
if (policy.toolDetails && call.input) {
|
|
186
|
+
try {
|
|
187
|
+
input = privateInput(call.name, JSON.parse(call.input));
|
|
188
|
+
}
|
|
189
|
+
catch { }
|
|
190
|
+
if (input === undefined)
|
|
191
|
+
counters.unsupportedDetails++;
|
|
192
|
+
}
|
|
193
|
+
return { id: sourceId(call.id), name: sourceId(call.name), executionId: sourceId(call.executionId),
|
|
194
|
+
...(input ? { input } : {}), ...(sourceId(call.status) ? { status: call.status } : call.denied ? { status: "denied" } : {}) };
|
|
195
|
+
}) : undefined;
|
|
196
|
+
if (kind === "tool_result")
|
|
197
|
+
state.calls = state.calls.filter(call => call.id !== source.toolCallId);
|
|
198
|
+
state.seen.push([identity, digest]);
|
|
199
|
+
if (state.seen.length > KIRO_LIMITS.replayEntriesPerSession)
|
|
200
|
+
state.seen.shift();
|
|
201
|
+
if (kind === "tool_call")
|
|
202
|
+
return [];
|
|
203
|
+
return [{ timeUnixNano: nano, attributes: { "session.id": sessionId, "source.event.id": id,
|
|
204
|
+
"event.name": "kiro.source_record", "kiro.source.version": 1,
|
|
205
|
+
"kiro.source.record": JSON.stringify({ payload: source, ...(context ? { context } : {}) }) } }];
|
|
206
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type KiroServiceOptions = {
|
|
2
|
+
home?: string;
|
|
3
|
+
platform?: NodeJS.Platform;
|
|
4
|
+
node?: string;
|
|
5
|
+
execute?: (command: string, args: string[]) => string;
|
|
6
|
+
runtimeSource?: string;
|
|
7
|
+
extension?: ".ts" | ".js";
|
|
8
|
+
};
|
|
9
|
+
export declare function renderKiroService(platform: NodeJS.Platform, node: string, entry: string, config: string): string;
|
|
10
|
+
export declare function enableKiroService(configPath: string, opts?: KiroServiceOptions): Promise<{
|
|
11
|
+
ok: boolean;
|
|
12
|
+
detail: string;
|
|
13
|
+
}>;
|
|
14
|
+
export declare function disableKiroService(configPath: string, opts?: KiroServiceOptions): {
|
|
15
|
+
ok: boolean;
|
|
16
|
+
detail: string;
|
|
17
|
+
};
|
|
18
|
+
export declare function uninstallKiroService(configPath: string, opts?: KiroServiceOptions): {
|
|
19
|
+
ok: boolean;
|
|
20
|
+
detail: string;
|
|
21
|
+
};
|