@codetelemetry/connect 0.1.0 → 0.1.3
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 +8 -24
- package/dist/agent.d.ts +699 -0
- package/dist/agent.js +435 -0
- package/dist/assistants.d.ts +4 -0
- package/dist/assistants.js +5 -0
- package/dist/bin.js +3 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +567 -0
- package/dist/clients.d.ts +34 -0
- package/dist/clients.js +74 -0
- package/dist/{src/codexConfig.d.ts → codexConfig.d.ts} +1 -0
- package/dist/{src/codexConfig.js → codexConfig.js} +5 -0
- package/dist/{src/config.d.ts → config.d.ts} +16 -0
- package/dist/{src/config.js → config.js} +16 -0
- package/dist/connectivity.d.ts +51 -0
- package/dist/connectivity.js +118 -0
- package/dist/{src/deviceClient.d.ts → deviceClient.d.ts} +9 -2
- package/dist/{src/deviceClient.js → deviceClient.js} +45 -13
- package/dist/graderSeed.d.ts +50 -0
- package/dist/graderSeed.js +289 -0
- package/dist/hostMetrics.d.ts +54 -0
- package/dist/hostMetrics.js +425 -0
- package/dist/import/browser.d.ts +30 -0
- package/dist/import/browser.js +157 -0
- package/dist/import/convert.d.ts +20 -0
- package/dist/import/convert.js +165 -0
- package/dist/import/core.d.ts +143 -0
- package/dist/import/core.js +441 -0
- package/dist/import/ledger.d.ts +52 -0
- package/dist/import/ledger.js +161 -0
- package/dist/import/model.d.ts +70 -0
- package/dist/import/model.js +42 -0
- package/dist/import/options.d.ts +24 -0
- package/dist/import/options.js +71 -0
- package/dist/import/otlpImport.d.ts +7 -0
- package/dist/import/otlpImport.js +81 -0
- package/dist/import/protocol.d.ts +35 -0
- package/dist/import/protocol.js +51 -0
- package/dist/import/run.d.ts +30 -0
- package/dist/import/run.js +127 -0
- package/dist/import/sources/claudeCodeText.d.ts +19 -0
- package/dist/import/sources/claudeCodeText.js +214 -0
- package/dist/import/sources/codexText.d.ts +20 -0
- package/dist/import/sources/codexText.js +319 -0
- package/dist/import/sources/files.d.ts +24 -0
- package/dist/import/sources/files.js +129 -0
- package/dist/import/transport.d.ts +76 -0
- package/dist/import/transport.js +141 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +19 -0
- package/dist/kiro/collector.d.ts +88 -0
- package/dist/kiro/collector.js +577 -0
- package/dist/kiro/command.d.ts +3 -0
- package/dist/kiro/command.js +109 -0
- package/dist/kiro/config.d.ts +39 -0
- package/dist/kiro/config.js +107 -0
- package/dist/kiro/records.d.ts +52 -0
- package/dist/kiro/records.js +206 -0
- package/dist/kiro/service.d.ts +21 -0
- package/dist/kiro/service.js +183 -0
- package/dist/kiro/state.d.ts +45 -0
- package/dist/kiro/state.js +205 -0
- package/dist/kiro/transport.d.ts +9 -0
- package/dist/kiro/transport.js +90 -0
- package/dist/{src/onboard.d.ts → onboard.d.ts} +8 -2
- package/dist/onboard.js +116 -0
- package/dist/piConfig.d.ts +29 -0
- package/dist/piConfig.js +112 -0
- package/dist/plan.d.ts +53 -0
- package/dist/plan.js +113 -0
- package/dist/{src/settings.d.ts → settings.d.ts} +4 -0
- package/dist/{src/settings.js → settings.js} +17 -0
- package/dist/yaml.d.ts +5 -0
- package/dist/yaml.js +72 -0
- package/package.json +27 -18
- package/dist/bin/connect.js +0 -6
- package/dist/src/cli.d.ts +0 -10
- package/dist/src/cli.js +0 -172
- package/dist/src/connectivity.d.ts +0 -27
- package/dist/src/connectivity.js +0 -54
- package/dist/src/index.d.ts +0 -8
- package/dist/src/index.js +0 -8
- package/dist/src/onboard.js +0 -84
- /package/dist/{bin/connect.d.ts → bin.d.ts} +0 -0
- /package/dist/{src/keys.d.ts → keys.d.ts} +0 -0
- /package/dist/{src/keys.js → keys.js} +0 -0
- /package/dist/{src/otlp.d.ts → otlp.d.ts} +0 -0
- /package/dist/{src/otlp.js → otlp.js} +0 -0
- /package/dist/{src/repositoryHook.d.ts → repositoryHook.d.ts} +0 -0
- /package/dist/{src/repositoryHook.js → repositoryHook.js} +0 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { claimKiroState } from "./state.js";
|
|
8
|
+
import { kiroPaths, readKiroConfig, resolveKiroConfigPath, setKiroEnabled } from "./config.js";
|
|
9
|
+
const MARKER = "CodeTelemetry Kiro V3 collector v1";
|
|
10
|
+
const LINUX_NAME = "codetelemetry-kiro-v3.service";
|
|
11
|
+
const MAC_NAME = "com.codetelemetry.kiro-v3";
|
|
12
|
+
const command = (command, args) => execFileSync(command, args, { encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
13
|
+
const safePath = (value) => {
|
|
14
|
+
if (!path.isAbsolute(value) || /[\0\r\n]/.test(value) || value.length > 4096)
|
|
15
|
+
throw new Error("invalid Kiro service path");
|
|
16
|
+
return value;
|
|
17
|
+
};
|
|
18
|
+
const systemdArg = (value) => `"${safePath(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$")}"`;
|
|
19
|
+
const xml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
20
|
+
export function renderKiroService(platform, node, entry, config) {
|
|
21
|
+
[node, entry, config].forEach(safePath);
|
|
22
|
+
if (platform === "linux")
|
|
23
|
+
return `# ${MARKER}\n[Unit]\nDescription=CodeTelemetry Kiro V3 telemetry\nAfter=network.target\n\n[Service]\nType=simple\nExecStart=${systemdArg(node)} ${systemdArg(entry)} kiro collect --settings ${systemdArg(config)}\nRestart=on-failure\nRestartSec=5\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
|
|
24
|
+
if (platform === "darwin")
|
|
25
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<!-- ${MARKER} -->\n<plist version="1.0"><dict><key>Label</key><string>${MAC_NAME}</string><key>ProgramArguments</key><array>${[node, entry, "kiro", "collect", "--settings", config].map(arg => `<string>${xml(arg)}</string>`).join("")}</array><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict><key>ThrottleInterval</key><integer>5</integer><key>Umask</key><integer>63</integer></dict></plist>\n`;
|
|
26
|
+
throw new Error("Kiro background installation currently supports Linux and macOS; foreground collection remains available");
|
|
27
|
+
}
|
|
28
|
+
function installRuntime(opts) {
|
|
29
|
+
const source = opts.runtimeSource ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
30
|
+
const extension = opts.extension ?? (import.meta.url.endsWith(".ts") ? ".ts" : ".js");
|
|
31
|
+
const files = [];
|
|
32
|
+
let totalBytes = 0, entries = 0;
|
|
33
|
+
const visit = (directory, depth) => {
|
|
34
|
+
if (depth > 5)
|
|
35
|
+
throw new Error("Kiro runtime directory depth exceeds bound");
|
|
36
|
+
const dir = fs.opendirSync(path.join(source, directory), { bufferSize: 16 });
|
|
37
|
+
try {
|
|
38
|
+
while (true) {
|
|
39
|
+
const entry = dir.readSync();
|
|
40
|
+
if (!entry)
|
|
41
|
+
break;
|
|
42
|
+
if (++entries > 512)
|
|
43
|
+
throw new Error("Kiro runtime inventory exceeds bound");
|
|
44
|
+
const relative = path.join(directory, entry.name);
|
|
45
|
+
if (entry.isDirectory())
|
|
46
|
+
visit(relative, depth + 1);
|
|
47
|
+
else if (entry.isFile() && entry.name.endsWith(extension) && !entry.name.endsWith(".d.ts")) {
|
|
48
|
+
const file = path.join(source, relative), stat = fs.statSync(file);
|
|
49
|
+
if (stat.size > 256 * 1024 || files.length >= 256)
|
|
50
|
+
throw new Error("Kiro runtime file exceeds bound");
|
|
51
|
+
const bytes = fs.readFileSync(file);
|
|
52
|
+
totalBytes += bytes.length;
|
|
53
|
+
if (totalBytes > 4 * 1024 * 1024)
|
|
54
|
+
throw new Error("Kiro runtime bytes exceed bound");
|
|
55
|
+
files.push({ relative, bytes });
|
|
56
|
+
}
|
|
57
|
+
else if (entry.isSymbolicLink())
|
|
58
|
+
throw new Error("Kiro runtime cannot contain symlinks");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
dir.closeSync();
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
visit(".", 0);
|
|
66
|
+
files.sort((a, b) => a.relative.localeCompare(b.relative));
|
|
67
|
+
const hash = createHash("sha256");
|
|
68
|
+
files.forEach(file => hash.update(file.relative).update("\0").update(file.bytes));
|
|
69
|
+
const identity = hash.digest("hex").slice(0, 16);
|
|
70
|
+
const root = path.join(kiroPaths(opts.home).runtimeDir, `runtime-${identity}`);
|
|
71
|
+
const relativeEntry = `bin${extension}`;
|
|
72
|
+
if (!files.some(file => file.relative === relativeEntry))
|
|
73
|
+
throw new Error("Kiro runtime entry is missing");
|
|
74
|
+
fs.mkdirSync(path.dirname(root), { recursive: true, mode: 0o700 });
|
|
75
|
+
const inventory = fs.opendirSync(path.dirname(root), { bufferSize: 8 });
|
|
76
|
+
let count = 0;
|
|
77
|
+
try {
|
|
78
|
+
while (inventory.readSync())
|
|
79
|
+
if (++count > 8)
|
|
80
|
+
throw new Error("Kiro runtime retention capacity exceeded");
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
inventory.closeSync();
|
|
84
|
+
}
|
|
85
|
+
if (!fs.existsSync(root)) {
|
|
86
|
+
fs.mkdirSync(root, { mode: 0o700 });
|
|
87
|
+
for (const file of files) {
|
|
88
|
+
const target = path.join(root, file.relative);
|
|
89
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
90
|
+
fs.writeFileSync(target, file.bytes, { flag: "wx", mode: 0o600 });
|
|
91
|
+
}
|
|
92
|
+
fs.writeFileSync(path.join(root, "package.json"), '{"type":"module"}\n', { flag: "wx", mode: 0o600 });
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
for (const file of files)
|
|
96
|
+
if (!fs.readFileSync(path.join(root, file.relative)).equals(file.bytes))
|
|
97
|
+
throw new Error("Kiro runtime integrity mismatch");
|
|
98
|
+
}
|
|
99
|
+
return { entry: path.join(root, relativeEntry), root };
|
|
100
|
+
}
|
|
101
|
+
function unitPath(opts) {
|
|
102
|
+
const home = opts.home ?? os.homedir(), platform = opts.platform ?? process.platform;
|
|
103
|
+
return platform === "linux" ? path.join(home, ".config", "systemd", "user", LINUX_NAME)
|
|
104
|
+
: path.join(home, "Library", "LaunchAgents", `${MAC_NAME}.plist`);
|
|
105
|
+
}
|
|
106
|
+
function ownedUnit(file) {
|
|
107
|
+
if (!fs.existsSync(file))
|
|
108
|
+
return false;
|
|
109
|
+
const stat = fs.lstatSync(file);
|
|
110
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16 * 1024 || !fs.readFileSync(file, "utf8").includes(MARKER))
|
|
111
|
+
throw new Error("refusing to replace an unrecognized Kiro service definition");
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
export async function enableKiroService(configPath, opts = {}) {
|
|
115
|
+
const file = resolveKiroConfigPath({ path: configPath });
|
|
116
|
+
readKiroConfig(file);
|
|
117
|
+
if (Number(process.versions.node.split(".")[0]) < 24)
|
|
118
|
+
throw new Error("Kiro collection requires Node 24 or newer");
|
|
119
|
+
const platform = opts.platform ?? process.platform;
|
|
120
|
+
if (platform !== "linux" && platform !== "darwin")
|
|
121
|
+
return { ok: false, detail: "Background setup supports Linux/macOS; use kiro collect for a foreground collector." };
|
|
122
|
+
const release = await claimKiroState(kiroPaths(opts.home).runtimeDir);
|
|
123
|
+
try {
|
|
124
|
+
const runtime = installRuntime(opts), unit = unitPath(opts), execute = opts.execute ?? command;
|
|
125
|
+
ownedUnit(unit);
|
|
126
|
+
fs.mkdirSync(path.dirname(unit), { recursive: true, mode: 0o700 });
|
|
127
|
+
const body = renderKiroService(platform, opts.node ?? process.execPath, runtime.entry, file);
|
|
128
|
+
fs.writeFileSync(unit, body, { mode: 0o600 });
|
|
129
|
+
fs.chmodSync(unit, 0o600);
|
|
130
|
+
setKiroEnabled(file, true);
|
|
131
|
+
try {
|
|
132
|
+
if (platform === "linux") {
|
|
133
|
+
execute("systemctl", ["--user", "daemon-reload"]);
|
|
134
|
+
execute("systemctl", ["--user", "enable", LINUX_NAME]);
|
|
135
|
+
execute("systemctl", ["--user", "restart", LINUX_NAME]);
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
const target = `gui/${process.getuid?.() ?? 0}`;
|
|
139
|
+
try {
|
|
140
|
+
execute("launchctl", ["bootout", `${target}/${MAC_NAME}`]);
|
|
141
|
+
}
|
|
142
|
+
catch { }
|
|
143
|
+
execute("launchctl", ["enable", `${target}/${MAC_NAME}`]);
|
|
144
|
+
execute("launchctl", ["bootstrap", target, unit]);
|
|
145
|
+
}
|
|
146
|
+
return { ok: true, detail: "Kiro background collector service enabled. Check kiro status for source coverage and delivery health." };
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return { ok: false, detail: "Kiro service manager could not start collection. Config is preserved; run kiro collect in a foreground process or repair the user service." };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
await release();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
export function disableKiroService(configPath, opts = {}) {
|
|
157
|
+
const file = resolveKiroConfigPath({ path: configPath });
|
|
158
|
+
setKiroEnabled(file, false);
|
|
159
|
+
const platform = opts.platform ?? process.platform, execute = opts.execute ?? command;
|
|
160
|
+
if (ownedUnit(unitPath(opts))) {
|
|
161
|
+
try {
|
|
162
|
+
if (platform === "linux")
|
|
163
|
+
execute("systemctl", ["--user", "disable", "--now", LINUX_NAME]);
|
|
164
|
+
else if (platform === "darwin")
|
|
165
|
+
execute("launchctl", ["bootout", `gui/${process.getuid?.() ?? 0}/${MAC_NAME}`]);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return { ok: false, detail: "Collection disabled in config; service manager stop could not be confirmed." };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return { ok: true, detail: "Kiro collection disabled; acknowledged checkpoints and any pending envelope are preserved." };
|
|
172
|
+
}
|
|
173
|
+
export function uninstallKiroService(configPath, opts = {}) {
|
|
174
|
+
const result = disableKiroService(configPath, opts);
|
|
175
|
+
if (!result.ok)
|
|
176
|
+
return result;
|
|
177
|
+
const unit = unitPath(opts);
|
|
178
|
+
if (ownedUnit(unit))
|
|
179
|
+
fs.unlinkSync(unit);
|
|
180
|
+
if ((opts.platform ?? process.platform) === "linux")
|
|
181
|
+
(opts.execute ?? command)("systemctl", ["--user", "daemon-reload"]);
|
|
182
|
+
return { ok: true, detail: "Kiro service uninstalled. Private config, bounded runtime and recovery state are preserved for deliberate recovery or removal." };
|
|
183
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type KiroRecordState } from "./records.ts";
|
|
2
|
+
export declare const KIRO_SESSION_ID: RegExp;
|
|
3
|
+
export declare const KIRO_WORKSPACE: RegExp;
|
|
4
|
+
export type KiroSessionCheckpoint = {
|
|
5
|
+
id: string;
|
|
6
|
+
relative: string;
|
|
7
|
+
physical: string;
|
|
8
|
+
offset: number;
|
|
9
|
+
generation?: number;
|
|
10
|
+
anchor?: string;
|
|
11
|
+
skipInitialLine?: boolean;
|
|
12
|
+
skippingOversize?: true;
|
|
13
|
+
records: KiroRecordState;
|
|
14
|
+
observedSize?: number;
|
|
15
|
+
observedMtimeMs?: number;
|
|
16
|
+
activationOffset?: number;
|
|
17
|
+
awaitingMore?: boolean;
|
|
18
|
+
blocked?: "unsupported_schema" | "source_conflict" | "source_error";
|
|
19
|
+
};
|
|
20
|
+
export type KiroCheckpoint = {
|
|
21
|
+
version: 3;
|
|
22
|
+
rootHash: string;
|
|
23
|
+
destinationHash: string;
|
|
24
|
+
cursor: number;
|
|
25
|
+
retirementCursor: number;
|
|
26
|
+
sessions: KiroSessionCheckpoint[];
|
|
27
|
+
parked: KiroSessionCheckpoint[];
|
|
28
|
+
};
|
|
29
|
+
export type KiroPending = {
|
|
30
|
+
version: 1;
|
|
31
|
+
privacyVersion?: 2;
|
|
32
|
+
id: string;
|
|
33
|
+
body: string;
|
|
34
|
+
digest: string;
|
|
35
|
+
createdAt: number;
|
|
36
|
+
attempts: number;
|
|
37
|
+
nextAttemptAt: number;
|
|
38
|
+
updates: KiroSessionCheckpoint[];
|
|
39
|
+
};
|
|
40
|
+
export declare function validateSession(value: unknown): asserts value is KiroSessionCheckpoint;
|
|
41
|
+
export declare function normalizeKiroCheckpoint(value: unknown, rootHash: string, destinationHash: string): KiroCheckpoint;
|
|
42
|
+
export declare function readBoundedJson(file: string, maxBytes: number): Promise<unknown | null>;
|
|
43
|
+
export declare function writeAtomicJson(file: string, value: unknown, maxBytes: number): Promise<void>;
|
|
44
|
+
export declare function cleanKiroState(directory: string): Promise<void>;
|
|
45
|
+
export declare function claimKiroState(directory: string): Promise<() => Promise<void>>;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { KIRO_LIMITS } from "./records.js";
|
|
6
|
+
export const KIRO_SESSION_ID = /^sess_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
7
|
+
export const KIRO_WORKSPACE = /^[a-f0-9]{16,64}$/;
|
|
8
|
+
export function validateSession(value) {
|
|
9
|
+
const v = value;
|
|
10
|
+
if (!v || typeof v.id !== "string" || typeof v.relative !== "string" || !KIRO_SESSION_ID.test(v.id) || v.relative.split("/").length !== 2 || !KIRO_WORKSPACE.test(v.relative.split("/")[0]) ||
|
|
11
|
+
v.relative.split("/")[1] !== v.id || typeof v.physical !== "string" || v.physical.length > 100 ||
|
|
12
|
+
!Number.isSafeInteger(v.offset) || v.offset < 0 ||
|
|
13
|
+
(v.generation !== undefined && (!Number.isSafeInteger(v.generation) || v.generation < 0)) ||
|
|
14
|
+
(v.anchor !== undefined && !/^[a-f0-9]{64}$/.test(v.anchor)) ||
|
|
15
|
+
(v.skipInitialLine !== undefined && typeof v.skipInitialLine !== "boolean") ||
|
|
16
|
+
(v.skippingOversize !== undefined && v.skippingOversize !== true) ||
|
|
17
|
+
[v.observedSize, v.activationOffset].some(n => n !== undefined && (!Number.isSafeInteger(n) || n < 0)) ||
|
|
18
|
+
(v.observedMtimeMs !== undefined && (!Number.isFinite(v.observedMtimeMs) || v.observedMtimeMs < 0)) ||
|
|
19
|
+
(v.awaitingMore !== undefined && typeof v.awaitingMore !== "boolean") ||
|
|
20
|
+
(v.blocked !== undefined && !["unsupported_schema", "source_conflict", "source_error"].includes(v.blocked)) || !v.records || !Array.isArray(v.records.seen) || !Array.isArray(v.records.calls) ||
|
|
21
|
+
v.records.seen.length > KIRO_LIMITS.replayEntriesPerSession || v.records.calls.length > KIRO_LIMITS.callsPerSession)
|
|
22
|
+
throw new Error("invalid Kiro checkpoint session");
|
|
23
|
+
for (const pair of v.records.seen)
|
|
24
|
+
if (!Array.isArray(pair) || pair.length !== 2 || pair.some(value => !/^[a-f0-9]{64}$/.test(value)))
|
|
25
|
+
throw new Error("invalid Kiro replay ledger");
|
|
26
|
+
for (const call of v.records.calls) {
|
|
27
|
+
if (!call || typeof call.id !== "string" || call.id.length > 256 || typeof call.name !== "string" || call.name.length > 128 ||
|
|
28
|
+
(call.executionId !== null && (typeof call.executionId !== "string" || call.executionId.length > 256)) ||
|
|
29
|
+
(call.input !== undefined && (typeof call.input !== "string" || call.input.length > KIRO_LIMITS.toolInputChars)) ||
|
|
30
|
+
(call.status !== undefined && (typeof call.status !== "string" || call.status.length > 256)) ||
|
|
31
|
+
(call.denied !== undefined && call.denied !== true))
|
|
32
|
+
throw new Error("invalid Kiro call checkpoint");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function normalizeKiroCheckpoint(value, rootHash, destinationHash) {
|
|
36
|
+
if (value === null)
|
|
37
|
+
return { version: 3, rootHash, destinationHash, cursor: 0, retirementCursor: 0, sessions: [], parked: [] };
|
|
38
|
+
const v = value;
|
|
39
|
+
if (!v || (v.version !== 1 && v.version !== 2 && v.version !== 3) || v.rootHash !== rootHash || v.destinationHash !== destinationHash || !Array.isArray(v.sessions) || v.sessions.length > KIRO_LIMITS.sessions || !Number.isSafeInteger(v.cursor) || Number(v.cursor) < 0)
|
|
40
|
+
throw new Error("unsupported Kiro checkpoint contract");
|
|
41
|
+
const parked = v.version !== 1 ? v.parked : [];
|
|
42
|
+
const retirementCursor = v.version !== 1 ? v.retirementCursor : 0;
|
|
43
|
+
if (!Array.isArray(parked) || parked.length + v.sessions.length > KIRO_LIMITS.registeredSessions || !Number.isSafeInteger(retirementCursor) || Number(retirementCursor) < 0)
|
|
44
|
+
throw new Error("unsupported Kiro checkpoint registry");
|
|
45
|
+
for (const row of [...v.sessions, ...parked])
|
|
46
|
+
validateSession(row);
|
|
47
|
+
if (parked.some(row => row.records.seen.length > KIRO_LIMITS.parkedReplayEntries))
|
|
48
|
+
throw new Error("oversized Kiro dormant replay ledger");
|
|
49
|
+
if (new Set([...v.sessions, ...parked].map(row => row.id)).size !== v.sessions.length + parked.length)
|
|
50
|
+
throw new Error("duplicate Kiro checkpoint ownership");
|
|
51
|
+
return { version: 3, rootHash, destinationHash, cursor: Number(v.cursor), retirementCursor: Number(retirementCursor), sessions: v.sessions.map(row => ({ ...row, activationOffset: row.activationOffset ?? row.offset })), parked: parked };
|
|
52
|
+
}
|
|
53
|
+
export async function readBoundedJson(file, maxBytes) {
|
|
54
|
+
let handle;
|
|
55
|
+
try {
|
|
56
|
+
handle = await fs.open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (error.code === "ENOENT")
|
|
60
|
+
return null;
|
|
61
|
+
throw new Error("Kiro state file is unreadable");
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const stat = await handle.stat();
|
|
65
|
+
if (!stat.isFile() || stat.size > maxBytes)
|
|
66
|
+
throw new Error("Kiro state file exceeds bound");
|
|
67
|
+
const bytes = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));
|
|
68
|
+
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
|
|
69
|
+
if (bytesRead > maxBytes)
|
|
70
|
+
throw new Error("Kiro state file exceeds bound");
|
|
71
|
+
try {
|
|
72
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, bytesRead)));
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
throw new Error("Kiro state file is not valid JSON");
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
await handle.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function writeAtomicJson(file, value, maxBytes) {
|
|
83
|
+
const body = JSON.stringify(value);
|
|
84
|
+
if (Buffer.byteLength(body) > maxBytes)
|
|
85
|
+
throw new Error("Kiro persisted state exceeds byte bound");
|
|
86
|
+
const directory = path.dirname(file);
|
|
87
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
88
|
+
if ((await fs.lstat(directory)).isSymbolicLink())
|
|
89
|
+
throw new Error("Kiro state directory must not be a symlink");
|
|
90
|
+
const temporary = path.join(directory, `${path.basename(file)}.tmp`);
|
|
91
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
92
|
+
try {
|
|
93
|
+
await handle.writeFile(body);
|
|
94
|
+
await handle.sync();
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
await fs.unlink(temporary).catch(() => { });
|
|
98
|
+
throw new Error("Kiro state write failed");
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
await handle.close();
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
await fs.rename(temporary, file);
|
|
105
|
+
if (process.platform !== "win32") {
|
|
106
|
+
const dir = await fs.open(directory, "r");
|
|
107
|
+
try {
|
|
108
|
+
await dir.sync();
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
await dir.close();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
await fs.unlink(temporary).catch(() => { });
|
|
117
|
+
throw new Error("Kiro state commit failed");
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
export async function cleanKiroState(directory) {
|
|
121
|
+
const known = new Set(["collector.lock", "checkpoint.json", "pending.json", "health.json", "collector.recovery"]);
|
|
122
|
+
const temporary = new Map([["checkpoint.json.tmp", KIRO_LIMITS.checkpointBytes], ["pending.json.tmp", KIRO_LIMITS.spoolBytes], ["health.json.tmp", 4096]]);
|
|
123
|
+
const dir = await fs.opendir(directory, { bufferSize: 8 });
|
|
124
|
+
let count = 0;
|
|
125
|
+
try {
|
|
126
|
+
for await (const entry of dir) {
|
|
127
|
+
if (++count > 16 || !entry.isFile() || (!known.has(entry.name) && !temporary.has(entry.name) && !/^owner-[a-f0-9-]{36}[.]tmp$/.test(entry.name)))
|
|
128
|
+
throw new Error("unrecognized Kiro state entry");
|
|
129
|
+
const limit = /^owner-[a-f0-9-]{36}[.]tmp$/.test(entry.name) ? 1024 : temporary.get(entry.name);
|
|
130
|
+
if (limit !== undefined) {
|
|
131
|
+
const file = path.join(directory, entry.name);
|
|
132
|
+
const stat = await fs.lstat(file);
|
|
133
|
+
if (stat.size > limit || !stat.isFile())
|
|
134
|
+
throw new Error("Kiro temporary state exceeds bound");
|
|
135
|
+
await fs.unlink(file);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
await dir.close().catch(() => { });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
export async function claimKiroState(directory) {
|
|
144
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
145
|
+
if ((await fs.lstat(directory)).isSymbolicLink())
|
|
146
|
+
throw new Error("Kiro state directory must not be a symlink");
|
|
147
|
+
const file = path.join(directory, "collector.lock");
|
|
148
|
+
const token = randomUUID();
|
|
149
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
150
|
+
try {
|
|
151
|
+
const temporary = path.join(directory, `owner-${token}.tmp`);
|
|
152
|
+
const lock = await fs.open(temporary, "wx", 0o600);
|
|
153
|
+
try {
|
|
154
|
+
await lock.writeFile(JSON.stringify({ version: 1, pid: process.pid, token }));
|
|
155
|
+
await lock.sync();
|
|
156
|
+
await fs.link(temporary, file);
|
|
157
|
+
}
|
|
158
|
+
finally {
|
|
159
|
+
await lock.close();
|
|
160
|
+
await fs.unlink(temporary).catch(() => { });
|
|
161
|
+
}
|
|
162
|
+
return async () => {
|
|
163
|
+
const owner = await readBoundedJson(file, 1024);
|
|
164
|
+
if (owner?.token === token)
|
|
165
|
+
await fs.unlink(file);
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (error.code !== "EEXIST")
|
|
170
|
+
throw error;
|
|
171
|
+
const owner = await readBoundedJson(file, 1024);
|
|
172
|
+
if (!Number.isSafeInteger(owner?.pid) || (owner?.pid ?? 0) < 1)
|
|
173
|
+
throw new Error("Kiro collector ownership is unknown");
|
|
174
|
+
try {
|
|
175
|
+
process.kill(owner.pid, 0);
|
|
176
|
+
throw new Error("Kiro collector is already running");
|
|
177
|
+
}
|
|
178
|
+
catch (cause) {
|
|
179
|
+
if (cause.code !== "ESRCH")
|
|
180
|
+
throw cause;
|
|
181
|
+
const recoveryFile = path.join(directory, "collector.recovery");
|
|
182
|
+
let recovery;
|
|
183
|
+
try {
|
|
184
|
+
recovery = await fs.open(recoveryFile, "wx", 0o600);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
throw new Error("Kiro ownership recovery needs inspection");
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
await recovery.writeFile(JSON.stringify({ pid: process.pid, token }));
|
|
191
|
+
await recovery.sync();
|
|
192
|
+
const current = await readBoundedJson(file, 1024);
|
|
193
|
+
if (current?.pid !== owner.pid || current?.token !== owner.token)
|
|
194
|
+
throw new Error("Kiro ownership changed during recovery");
|
|
195
|
+
await fs.unlink(file);
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
await recovery.close();
|
|
199
|
+
await fs.unlink(recoveryFile);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
throw new Error("Kiro collector ownership changed during recovery");
|
|
205
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { FetchLike } from "../otlp.ts";
|
|
2
|
+
export type KiroPostResult = "ok" | "retry" | "auth" | "budget" | "rejected";
|
|
3
|
+
export type KiroPost = (body: string, idempotencyKey: string) => Promise<KiroPostResult>;
|
|
4
|
+
export declare function kiroTransport(opts: {
|
|
5
|
+
endpoint: string;
|
|
6
|
+
key: string;
|
|
7
|
+
fetchImpl?: FetchLike;
|
|
8
|
+
allowHttp?: boolean;
|
|
9
|
+
}): KiroPost;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { assertKey } from "../keys.js";
|
|
2
|
+
import { KIRO_LIMITS } from "./records.js";
|
|
3
|
+
export function kiroTransport(opts) {
|
|
4
|
+
const key = assertKey(opts.key);
|
|
5
|
+
const url = new URL(opts.endpoint.replace(/\/$/, "") + "/v1/logs");
|
|
6
|
+
if (url.username || url.password || url.search || url.hash ||
|
|
7
|
+
(url.protocol !== "https:" && !(opts.allowHttp && url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))))
|
|
8
|
+
throw new Error("invalid Kiro ingest endpoint");
|
|
9
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
10
|
+
return async (body, idempotencyKey) => {
|
|
11
|
+
if (Buffer.byteLength(body) > KIRO_LIMITS.envelopeBytes || !/^[a-f0-9-]{36}$/.test(idempotencyKey))
|
|
12
|
+
throw new Error("invalid Kiro retry envelope");
|
|
13
|
+
let sourceEnvelope = false;
|
|
14
|
+
try {
|
|
15
|
+
const document = JSON.parse(body);
|
|
16
|
+
sourceEnvelope = Array.isArray(document?.resourceLogs) && document.resourceLogs.some((r) => Array.isArray(r?.scopeLogs) && r.scopeLogs.some((s) => Array.isArray(s?.logRecords) && s.logRecords.some((row) => Array.isArray(row?.attributes) && row.attributes.some((a) => a?.key === "event.name" && a.value?.stringValue === "kiro.source_record"))));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return "rejected";
|
|
20
|
+
}
|
|
21
|
+
const sourceHeader = "x-codetelemetry-source-format";
|
|
22
|
+
const sourceFormat = "kiro-v3-source-v1";
|
|
23
|
+
const controller = new AbortController();
|
|
24
|
+
const timer = setTimeout(() => controller.abort(), KIRO_LIMITS.requestMs);
|
|
25
|
+
try {
|
|
26
|
+
const response = await fetchImpl(url.toString(), { method: "POST", body,
|
|
27
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${key}`, "x-code-telemetry-idempotency-key": idempotencyKey, ...(sourceEnvelope ? { [sourceHeader]: sourceFormat } : {}) },
|
|
28
|
+
signal: controller.signal, redirect: "error" });
|
|
29
|
+
if (response.status === 401 || response.status === 403) {
|
|
30
|
+
await response.body?.cancel();
|
|
31
|
+
return "auth";
|
|
32
|
+
}
|
|
33
|
+
if (response.status === 402) {
|
|
34
|
+
await response.body?.cancel();
|
|
35
|
+
return "budget";
|
|
36
|
+
}
|
|
37
|
+
if (response.status >= 200 && response.status < 300) {
|
|
38
|
+
if (sourceEnvelope && response.headers.get(sourceHeader) !== sourceFormat) {
|
|
39
|
+
await response.body?.cancel();
|
|
40
|
+
return "rejected";
|
|
41
|
+
}
|
|
42
|
+
let bytes = 0;
|
|
43
|
+
const chunks = [];
|
|
44
|
+
const reader = response.body?.getReader();
|
|
45
|
+
if (reader) {
|
|
46
|
+
try {
|
|
47
|
+
while (true) {
|
|
48
|
+
const part = await reader.read();
|
|
49
|
+
if (part.done)
|
|
50
|
+
break;
|
|
51
|
+
bytes += part.value.byteLength;
|
|
52
|
+
if (bytes > 4096) {
|
|
53
|
+
await reader.cancel();
|
|
54
|
+
return "retry";
|
|
55
|
+
}
|
|
56
|
+
chunks.push(part.value);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
reader.releaseLock();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const text = Buffer.concat(chunks).toString("utf8").trim();
|
|
64
|
+
if (!text)
|
|
65
|
+
return "ok";
|
|
66
|
+
try {
|
|
67
|
+
const result = JSON.parse(text);
|
|
68
|
+
if (!result || typeof result !== "object" || Array.isArray(result) ||
|
|
69
|
+
(result.partialSuccess !== undefined && (!result.partialSuccess || typeof result.partialSuccess !== "object" || Array.isArray(result.partialSuccess))))
|
|
70
|
+
return "retry";
|
|
71
|
+
const rejected = result.partialSuccess?.rejectedLogRecords;
|
|
72
|
+
if (rejected !== undefined && String(rejected) !== "0")
|
|
73
|
+
return "rejected";
|
|
74
|
+
return "ok";
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return "retry";
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
await response.body?.cancel();
|
|
81
|
+
return response.status === 408 || response.status === 429 || response.status >= 500 ? "retry" : "rejected";
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return "retry";
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { type SettingsScope } from "./config.ts";
|
|
2
2
|
import { type WriteResult } from "./settings.ts";
|
|
3
3
|
import { type SendTestResult, type FetchLike } from "./otlp.ts";
|
|
4
|
-
import { type ConfirmResult } from "./connectivity.ts";
|
|
4
|
+
import { type ConfirmResult, type ExpectedKeyScope, type KeyScope } from "./connectivity.ts";
|
|
5
|
+
import { type KiroServiceOptions } from "./kiro/service.ts";
|
|
6
|
+
import type { OnboardClient } from "./assistants.ts";
|
|
5
7
|
export type OnboardStep = {
|
|
6
8
|
name: string;
|
|
7
9
|
ok: boolean;
|
|
@@ -18,12 +20,13 @@ export type OnboardResult = {
|
|
|
18
20
|
verify: ConfirmResult | null;
|
|
19
21
|
steps: OnboardStep[];
|
|
20
22
|
};
|
|
21
|
-
export type OnboardClient
|
|
23
|
+
export type { OnboardClient };
|
|
22
24
|
export type OnboardOptions = {
|
|
23
25
|
key?: string;
|
|
24
26
|
getKey?: () => Promise<{
|
|
25
27
|
apiKey: string;
|
|
26
28
|
ingestEndpoint?: string;
|
|
29
|
+
scope?: KeyScope;
|
|
27
30
|
}>;
|
|
28
31
|
client?: OnboardClient;
|
|
29
32
|
endpoints?: Partial<{
|
|
@@ -41,7 +44,10 @@ export type OnboardOptions = {
|
|
|
41
44
|
verify?: boolean;
|
|
42
45
|
verifyTimeoutMs?: number;
|
|
43
46
|
verifyIntervalMs?: number;
|
|
47
|
+
expectedScope?: ExpectedKeyScope;
|
|
44
48
|
fetchImpl?: FetchLike;
|
|
49
|
+
activateCollector?: boolean;
|
|
50
|
+
kiroService?: KiroServiceOptions;
|
|
45
51
|
logger?: (msg: string) => void;
|
|
46
52
|
};
|
|
47
53
|
export declare function onboard(opts: OnboardOptions): Promise<OnboardResult>;
|