@akilium/telemetry-collector 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @akilium/telemetry-collector
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Platform-owned installer for the local OpenTelemetry Collector. The package preserves the existing operations collector's native macOS/Linux and Docker rendering, local archive, agent settings, status, doctor, and uninstall behavior. It uses `~/.local/share/akilium-agent-telemetry` by default. Run `akilium-telemetry help` for commands. Collector release downloads use pinned SHA-256 digests.
4
+
5
+ This package migrates the reviewed operations installer into the Akila platform monorepo. A rendered local config does not establish hosted acceptance or artifact linkage.
6
+
7
+ ## Supported paths and migration
8
+
9
+ Node.js 22 or newer is required for the CLI. Native installation supports macOS launchd and Linux user systemd with pinned Collector Contrib `0.161.0`; Docker installation uses the matching image and local loopback ports 4317 and 4318. The installed Codex JSONL action adapter is separately version-limited to CLI `0.160.0`. Other harnesses use the explicit SDK wrappers.
10
+
11
+ Before changing an existing operations-managed installation, run `akilium-telemetry migrate`. It writes a mode-0700 backup folder under the collector state directory, with mode-0600 copies of the manifest, configuration, existing Akila forwarding overlay and environment file, service definition, binary, and agent settings. Existing collector and Compose files are retained on reinstall; custom pipeline files are never rewritten by `set-destination`. Run `akilium-telemetry rollback` to restore the backup, or `upgrade` to install the pinned Collector version while retaining custom Compose content. `uninstall` stops the managed service and removes only managed agent telemetry settings; local archives, state, and forwarding files remain for review.
12
+
13
+ ## Protected enrollment
14
+
15
+ Use a source-approved HTTPS completion receiver URL and pass its one-time enrollment token on stdin, for example:
16
+
17
+ ```sh
18
+ printf '%s' "$AKILA_CODEX_TOKEN" | akilium-telemetry enroll --endpoint https://YOUR_PROJECT.supabase.co/functions/v1/codex-usage-ingestion/v1/logs
19
+ ```
20
+
21
+ The CLI validates the URL and token, writes `akila-forwarding.env` with mode 0600, preserves unrelated variables, and never prints the credential. New overlays use the identity-free v1 mapping by default. Specify `--mapping v2` only for a source already approved for v2 identity hints; existing custom overlays are preserved and must be reviewed manually before changing mappings. Docker Compose mounts the allowlisted, metadata-only `akila-forwarding.yaml`; native services use a local launcher that reads the protected environment file. Enroll does not restart a running collector. Rotate by running `enroll` again with a new authorized token, then restart the service and check hosted connection health. Action lineage uses a separate capability-bound receiver and the `@akilium/instrumentation` SDK token; a completion credential cannot authorize action reports.
22
+
23
+ ## Operational limits and diagnostics, v1
24
+
25
+ The Collector retains local rotated archive files for seven days with up to 20 backups of 10 MiB each per signal. File-backed queue storage is capped at 64 MiB. Newly rendered generic forwarding uses a 1,000-entry queue and a one-hour retry window; inherited custom configurations keep their existing settings until reviewed. The Codex completion overlay forwards only allowlisted metadata after dropping bodies, resource and scope attributes. The receiver independently enforces privacy and authorization.
26
+
27
+ The SDK's action export queue is in memory: 128 reports, one-hour expiry, exponential retries capped at a 60-second delay by default. `lineage.status()` exposes queued, dropped, accepted, duplicate, rejected, and unavailable counts; `lineage.flush()` retries due reports. Process exit or queue overflow can lose reports. `akilium-telemetry status` shows local service/archive state, while hosted receipt, normalization, and artifact linkage remain explicitly unknown until checked through their respective Akila health/read surfaces. `doctor` checks only local OTLP receipt and archive capture.
@@ -0,0 +1,406 @@
1
+ #!/usr/bin/env node
2
+ /** Install and operate the local OTLP receiver. Runtime files live outside Git. */
3
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
4
+ import { homedir, platform, arch } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { execFileSync } from "node:child_process";
8
+ import {
9
+ VERSION, DIGESTS, SIGNALS, paths, atomicWrite, digest, renderCollector, renderCompose,
10
+ setCodexTelemetry, restoreCodexTelemetry, setClaudeTelemetry, restoreClaudeTelemetry,
11
+ renderAkilaForwarding,
12
+ readJson, fileBytes,
13
+ } from "../lib/agent-telemetry.mjs";
14
+
15
+ const [action = "help", ...args] = process.argv.slice(2);
16
+ const home = process.env.AGENT_TELEMETRY_HOME || homedir();
17
+ const p = paths(home);
18
+ const launcher = fileURLToPath(new URL("./collector-launcher.mjs", import.meta.url));
19
+ const quiet = args.includes("--quiet");
20
+
21
+ function option(name, fallback = null) {
22
+ const index = args.indexOf(name);
23
+ if (index < 0) return fallback;
24
+ if (!args[index + 1] || args[index + 1].startsWith("--")) throw new Error(`${name} needs a value`);
25
+ return args[index + 1];
26
+ }
27
+
28
+ function run(file, argv, ignoreFailure = false) {
29
+ try {
30
+ return execFileSync(file, argv, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
31
+ } catch (error) {
32
+ if (ignoreFailure) return "";
33
+ throw new Error(`${file} failed: ${error.stderr?.toString().trim() || error.message}`);
34
+ }
35
+ }
36
+
37
+ function saveManifest(manifest) {
38
+ atomicWrite(p.manifest, JSON.stringify(manifest, null, 2) + "\n");
39
+ }
40
+
41
+ function backupExisting(manifest) {
42
+ if (manifest.migrationBackup) return manifest.migrationBackup;
43
+ const folder = join(p.state, `platform-backup-${Date.now()}`);
44
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
45
+ const files = [p.manifest, p.config, p.compose, p.launchd, p.systemd, p.binary,
46
+ join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), p.codex, p.claude];
47
+ const saved = [];
48
+ for (const file of files) {
49
+ if (!existsSync(file)) continue;
50
+ const target = join(folder, `file-${saved.length}`);
51
+ copyFileSync(file, target);
52
+ chmodSync(target, 0o600);
53
+ saved.push({ path: file, backup: target, mode: statSync(file).mode & 0o777 });
54
+ }
55
+ atomicWrite(join(folder, "index.json"), JSON.stringify(saved, null, 2) + "\n");
56
+ manifest.migrationBackup = folder;
57
+ saveManifest(manifest);
58
+ return folder;
59
+ }
60
+
61
+ function osMode() {
62
+ if (platform() === "darwin") return "launchd";
63
+ if (platform() === "linux") return "systemd";
64
+ throw new Error("Native installation supports macOS and Linux only; use Docker on this platform");
65
+ }
66
+
67
+ function serviceFile(mode) {
68
+ return mode === "launchd" ? p.launchd : p.systemd;
69
+ }
70
+
71
+ function stopService(mode) {
72
+ if (mode === "docker") run("docker", ["compose", "-f", p.compose, "down"], true);
73
+ if (mode === "launchd") run("launchctl", ["bootout", `gui/${process.getuid()}`, p.launchd], true);
74
+ if (mode === "systemd") run("systemctl", ["--user", "disable", "--now", "akilium-agent-telemetry.service"], true);
75
+ }
76
+
77
+ function startService(mode) {
78
+ if (mode === "docker") {
79
+ run("docker", ["compose", "-f", p.compose, "up", "-d"]);
80
+ } else if (mode === "launchd") {
81
+ run("launchctl", ["bootstrap", `gui/${process.getuid()}`, p.launchd]);
82
+ } else {
83
+ run("systemctl", ["--user", "daemon-reload"]);
84
+ run("systemctl", ["--user", "enable", "--now", "akilium-agent-telemetry.service"]);
85
+ }
86
+ }
87
+
88
+ function launchdPlist() {
89
+ const xml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
90
+ const args = readJson(p.manifest)?.akilaCompletionForwarding
91
+ ? [process.execPath, launcher, p.binary, p.config, join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env")]
92
+ : [p.binary, `--config=${p.config}`];
93
+ 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<plist version="1.0"><dict>\n<key>Label</key><string>ai.akilium.agent-telemetry</string>\n<key>ProgramArguments</key><array>${args.map((arg) => `<string>${xml(arg)}</string>`).join("")}</array>\n<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><true/>\n<key>StandardOutPath</key><string>${xml(join(p.root, "collector.stdout.log"))}</string>\n<key>StandardErrorPath</key><string>${xml(join(p.root, "collector.stderr.log"))}</string>\n</dict></plist>\n`;
94
+ }
95
+
96
+ function systemdUnit() {
97
+ const args = readJson(p.manifest)?.akilaCompletionForwarding
98
+ ? [process.execPath, launcher, p.binary, p.config, join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env")]
99
+ : [p.binary, `--config=${p.config}`];
100
+ if (args.some((arg) => /[\n\r%"\\]/.test(arg))) throw new Error("Unsafe install path for systemd service");
101
+ return `[Unit]\nDescription=Akilium local agent telemetry collector\nAfter=network-online.target\n\n[Service]\nType=simple\nExecStart=${args.map((arg) => `"${arg}"`).join(" ")}\nRestart=on-failure\nRestartSec=5\nNoNewPrivileges=true\n\n[Install]\nWantedBy=default.target\n`;
102
+ }
103
+
104
+ async function downloadBinary() {
105
+ const target = `${platform()}-${arch() === "x64" ? "amd64" : arch()}`;
106
+ const expected = DIGESTS[target];
107
+ if (!expected) throw new Error(`No pinned Collector release for ${target}`);
108
+ const file = `otelcol-contrib_${VERSION}_${target.replace("-", "_")}.tar.gz`;
109
+ const url = `https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v${VERSION}/${file}`;
110
+ const response = await fetch(url, { signal: AbortSignal.timeout(120_000) });
111
+ if (!response.ok) throw new Error(`Collector download failed: HTTP ${response.status}`);
112
+ const bytes = Buffer.from(await response.arrayBuffer());
113
+ if (digest(bytes) !== expected) throw new Error(`Collector SHA-256 mismatch for ${file}`);
114
+ mkdirSync(dirname(p.binary), { recursive: true, mode: 0o700 });
115
+ const archive = join(p.root, file);
116
+ atomicWrite(archive, bytes);
117
+ try {
118
+ run("tar", ["-xzf", archive, "-C", dirname(p.binary), "otelcol-contrib"]);
119
+ chmodSync(p.binary, 0o700);
120
+ } finally {
121
+ rmSync(archive, { force: true });
122
+ }
123
+ }
124
+
125
+ function configureAgents(manifest, selected) {
126
+ if (selected.includes("codex")) {
127
+ if (!existsSync(p.codex)) manifest.codexCreated = true;
128
+ const raw = existsSync(p.codex) ? readFileSync(p.codex, "utf8") : "";
129
+ const result = setCodexTelemetry(raw);
130
+ atomicWrite(p.codex, result.content);
131
+ manifest.codexManaged = true;
132
+ saveManifest(manifest);
133
+ }
134
+ if (selected.includes("claude")) {
135
+ if (!existsSync(p.claude)) manifest.claudeCreated = true;
136
+ const raw = existsSync(p.claude) ? readFileSync(p.claude, "utf8") : "";
137
+ const result = setClaudeTelemetry(raw);
138
+ atomicWrite(p.claude, result.content);
139
+ manifest.claudeAdded = [...new Set([...(manifest.claudeAdded || []), ...result.added])];
140
+ saveManifest(manifest);
141
+ }
142
+ }
143
+
144
+ function installAgents(manifest) {
145
+ const selected = option("--agents", "codex,claude").split(",").map((s) => s.trim());
146
+ if (selected.some((s) => !["codex", "claude"].includes(s))) throw new Error("--agents accepts codex,claude");
147
+ // Check all existing settings before changing either file.
148
+ if (selected.includes("codex")) setCodexTelemetry(existsSync(p.codex) ? readFileSync(p.codex, "utf8") : "");
149
+ if (selected.includes("claude")) setClaudeTelemetry(existsSync(p.claude) ? readFileSync(p.claude, "utf8") : "");
150
+ configureAgents(manifest, selected);
151
+ saveManifest(manifest);
152
+ console.log(`Configured ${selected.join(", ")}; restart those agents to enable telemetry.`);
153
+ }
154
+
155
+ async function install(modeOverride = null) {
156
+ const prior = readJson(p.manifest);
157
+ const mode = modeOverride || option("--mode", prior?.mode === "docker" ? "docker" : "native");
158
+ if (!["native", "docker"].includes(mode)) throw new Error("--mode must be native or docker");
159
+ const service = mode === "docker" ? "docker" : osMode();
160
+ if (prior && prior.mode !== service) throw new Error(`Existing ${prior.mode} install; uninstall it before changing mode`);
161
+ if (service === "docker") {
162
+ run("docker", ["compose", "version"]);
163
+ run("docker", ["info", "--format", "{{.ServerVersion}}"]);
164
+ }
165
+ const selected = option("--agents", "codex,claude").split(",").map((s) => s.trim());
166
+ if (selected.some((s) => !["codex", "claude"].includes(s))) throw new Error("--agents accepts codex,claude");
167
+ if (selected.includes("codex")) setCodexTelemetry(existsSync(p.codex) ? readFileSync(p.codex, "utf8") : "");
168
+ if (selected.includes("claude")) setClaudeTelemetry(existsSync(p.claude) ? readFileSync(p.claude, "utf8") : "");
169
+ mkdirSync(p.data, { recursive: true, mode: 0o700 });
170
+ mkdirSync(p.state, { recursive: true, mode: 0o700 });
171
+ mkdirSync(join(p.data, "archive"), { recursive: true, mode: 0o700 });
172
+ mkdirSync(join(p.data, "state"), { recursive: true, mode: 0o700 });
173
+ const manifest = prior || { mode: service, version: VERSION, destination: null, claudeAdded: [] };
174
+ if (prior) backupExisting(manifest);
175
+ if (service !== "docker" && (!existsSync(p.binary) || !run(p.binary, ["--version"], true).includes(VERSION))) await downloadBinary();
176
+ const dataDir = service === "docker" ? "/data" : p.data;
177
+ if (!prior || !existsSync(p.config)) atomicWrite(p.config,
178
+ renderCollector(manifest.destination, dataDir, service === "docker" ? "0.0.0.0" : "127.0.0.1"));
179
+ if (service !== "docker") run(p.binary, ["validate", "--config", p.config]);
180
+ if (service === "docker") {
181
+ if (!prior || !existsSync(p.compose)) atomicWrite(p.compose, renderCompose(p.root));
182
+ else if (manifest.version !== VERSION) {
183
+ const original = readFileSync(p.compose, "utf8");
184
+ const oldImage = `otel/opentelemetry-collector-contrib:${manifest.version}`;
185
+ if (!original.includes(oldImage)) throw new Error("Custom Collector image cannot be upgraded automatically");
186
+ atomicWrite(p.compose, original.replaceAll(oldImage,
187
+ `otel/opentelemetry-collector-contrib:${VERSION}`));
188
+ }
189
+ } else {
190
+ if (!prior || !existsSync(serviceFile(service)))
191
+ atomicWrite(serviceFile(service), service === "launchd" ? launchdPlist() : systemdUnit(), 0o644);
192
+ }
193
+ manifest.version = VERSION;
194
+ saveManifest(manifest);
195
+ if (prior) stopService(service);
196
+ startService(service);
197
+ installAgents(manifest);
198
+ console.log(`Installed Collector Contrib ${VERSION} (${service}); data: ${p.data}`);
199
+ }
200
+
201
+ async function upgrade() {
202
+ const manifest = readJson(p.manifest);
203
+ if (!manifest) throw new Error("Install the collector first");
204
+ await install(manifest.mode === "docker" ? "docker" : "native");
205
+ }
206
+
207
+ function rollback() {
208
+ const manifest = readJson(p.manifest);
209
+ if (!manifest?.migrationBackup) throw new Error("No platform migration backup is recorded");
210
+ const folder = manifest.migrationBackup;
211
+ const saved = readJson(join(folder, "index.json"));
212
+ if (!Array.isArray(saved)) throw new Error("Migration backup index is missing");
213
+ const allowed = new Set([p.manifest, p.config, p.compose, p.launchd, p.systemd, p.binary,
214
+ join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), p.codex, p.claude]);
215
+ if (saved.some((entry) => !allowed.has(entry.path) || dirname(entry.backup) !== folder ||
216
+ !existsSync(entry.backup))) throw new Error("Migration backup index is invalid");
217
+ stopService(manifest.mode);
218
+ for (const entry of saved) {
219
+ mkdirSync(dirname(entry.path), { recursive: true, mode: 0o700 });
220
+ copyFileSync(entry.backup, entry.path);
221
+ chmodSync(entry.path, entry.mode);
222
+ }
223
+ const restored = readJson(p.manifest);
224
+ if (restored?.mode) startService(restored.mode);
225
+ console.log("Previous collector configuration restored from the protected backup");
226
+ }
227
+
228
+ function migrate() {
229
+ const manifest = readJson(p.manifest);
230
+ if (!manifest) throw new Error("Existing operations collector installation was not found");
231
+ const folder = backupExisting(manifest);
232
+ console.log(`Existing configuration backed up at ${folder}; collector and agents were not restarted`);
233
+ }
234
+
235
+ function enroll() {
236
+ const manifest = readJson(p.manifest);
237
+ if (!manifest) throw new Error("Install or migrate the collector first");
238
+ const endpoint = option("--endpoint");
239
+ const mappingVersion = option("--mapping", "v1");
240
+ if (!["v1", "v2"].includes(mappingVersion)) throw new Error("--mapping must be v1 or v2");
241
+ if (!endpoint) throw new Error("--endpoint is required");
242
+ const url = new URL(endpoint);
243
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash ||
244
+ !url.pathname.endsWith("/functions/v1/codex-usage-ingestion/v1/logs")) {
245
+ throw new Error("Enrollment requires a verified HTTPS Codex completion receiver URL");
246
+ }
247
+ const overlay = join(p.root, "akila-forwarding.yaml");
248
+ const envFile = join(p.root, "akila-forwarding.env");
249
+ const currentCompose = existsSync(p.compose) ? readFileSync(p.compose, "utf8") : "";
250
+ const plainCompose = renderCompose(p.root);
251
+ if (manifest.mode === "docker" && currentCompose && currentCompose !== plainCompose &&
252
+ (!currentCompose.includes("akila-forwarding.yaml") || !currentCompose.includes("akila-forwarding.env"))) {
253
+ throw new Error("Custom Compose config lacks Akila forwarding mounts; review it before enrollment");
254
+ }
255
+ if (manifest.mode !== "docker") {
256
+ const service = serviceFile(manifest.mode);
257
+ const existing = existsSync(service) ? readFileSync(service, "utf8") : "";
258
+ if (existing && !(existing.includes("ai.akilium.agent-telemetry") ||
259
+ existing.includes("Description=Akilium local agent telemetry collector"))) {
260
+ throw new Error("Native service file has custom content; review it before enrollment");
261
+ }
262
+ }
263
+ const token = readFileSync(0, "utf8").trim();
264
+ if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw new Error("Invalid enrollment token on stdin");
265
+ backupExisting(manifest);
266
+ if (!existsSync(overlay)) atomicWrite(overlay, renderAkilaForwarding(mappingVersion));
267
+ if (manifest.mode === "docker" && (!currentCompose || currentCompose === plainCompose))
268
+ atomicWrite(p.compose, renderCompose(p.root, true));
269
+ // Replace only our protected variables. No credential value is printed or stored in the manifest.
270
+ const previous = existsSync(envFile) ? readFileSync(envFile, "utf8").split("\n") : [];
271
+ const retained = previous.filter((line) => line && !/^AKILA_(INGESTION_ENDPOINT|CODEX_TOKEN)=/.test(line));
272
+ atomicWrite(envFile, [...retained, `AKILA_INGESTION_ENDPOINT=${url.toString()}`,
273
+ `AKILA_CODEX_TOKEN=${token}`, ""].join("\n"));
274
+ chmodSync(envFile, 0o600);
275
+ manifest.akilaCompletionForwarding = true;
276
+ saveManifest(manifest);
277
+ if (manifest.mode !== "docker") {
278
+ const service = serviceFile(manifest.mode);
279
+ atomicWrite(service, manifest.mode === "launchd" ? launchdPlist() : systemdUnit(), 0o644);
280
+ }
281
+ console.log("Protected completion forwarding configured; restart the collector and check hosted acceptance");
282
+ }
283
+
284
+ function setDestination() {
285
+ const manifest = readJson(p.manifest);
286
+ if (!manifest) throw new Error("Install the collector first");
287
+ const clear = args.includes("--clear");
288
+ const endpoint = option("--endpoint");
289
+ if (clear === Boolean(endpoint)) throw new Error("Use exactly one of --endpoint URL or --clear");
290
+ let destination = null;
291
+ if (endpoint) {
292
+ const url = new URL(endpoint);
293
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
294
+ throw new Error("Destination must be an OTLP/HTTP base URL without credentials, query, or fragment");
295
+ }
296
+ if (url.protocol !== "https:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) {
297
+ throw new Error("Remote destination must use HTTPS");
298
+ }
299
+ destination = url.toString().replace(/\/$/, "");
300
+ }
301
+ const config = renderCollector(destination, manifest.mode === "docker" ? "/data" : p.data, manifest.mode === "docker" ? "0.0.0.0" : "127.0.0.1");
302
+ const managed = renderCollector(manifest.destination, manifest.mode === "docker" ? "/data" : p.data,
303
+ manifest.mode === "docker" ? "0.0.0.0" : "127.0.0.1");
304
+ if (existsSync(p.config) && readFileSync(p.config, "utf8") !== managed)
305
+ throw new Error("Collector config contains custom pipelines; review destination manually");
306
+ if (manifest.mode !== "docker") {
307
+ const candidate = `${p.config}.candidate`;
308
+ atomicWrite(candidate, config);
309
+ try { run(p.binary, ["validate", "--config", candidate]); }
310
+ finally { rmSync(candidate, { force: true }); }
311
+ }
312
+ backupExisting(manifest);
313
+ stopService(manifest.mode);
314
+ manifest.destination = destination;
315
+ atomicWrite(p.config, config);
316
+ saveManifest(manifest);
317
+ startService(manifest.mode);
318
+ console.log(destination ? `Forwarding retained telemetry to ${destination}` : "Forwarding disabled; local capture continues");
319
+ }
320
+
321
+ function directorySize(folder) {
322
+ if (!existsSync(folder)) return 0;
323
+ return readdirSync(folder, { withFileTypes: true }).reduce((sum, entry) => {
324
+ const file = join(folder, entry.name);
325
+ return sum + (entry.isDirectory() ? directorySize(file) : entry.isFile() ? statSync(file).size : 0);
326
+ }, 0);
327
+ }
328
+
329
+ function status() {
330
+ const manifest = readJson(p.manifest);
331
+ if (!manifest) throw new Error("Collector is not installed");
332
+ console.log(`Collector: ${manifest.version} (${manifest.mode})`);
333
+ console.log(`Destination: ${manifest.destination || "local only"}`);
334
+ for (const signal of SIGNALS) {
335
+ const folder = join(p.data, "archive");
336
+ const bytes = existsSync(folder) ? readdirSync(folder).filter((name) => name === `${signal}.json` || name.startsWith(`${signal}-`)).reduce((sum, name) => sum + fileBytes(join(folder, name)), 0) : 0;
337
+ console.log(`${signal}: ${(bytes / 1_048_576).toFixed(1)} MiB`);
338
+ }
339
+ console.log(`State: ${(directorySize(join(p.data, "state")) / 1_048_576).toFixed(1)} MiB`);
340
+ console.log(`Total data: ${(directorySize(p.data) / 1_048_576).toFixed(1)} MiB`);
341
+ if (manifest.mode === "docker") console.log(run("docker", ["compose", "-f", p.compose, "ps", "--status", "running"], true) || "Docker service unavailable");
342
+ else if (manifest.mode === "systemd") console.log(`Service: ${run("systemctl", ["--user", "is-active", "akilium-agent-telemetry.service"], true) || "inactive"}`);
343
+ else console.log(`Service: ${run("launchctl", ["list", "ai.akilium.agent-telemetry"], true) ? "loaded" : "inactive"}`);
344
+ console.log("Hosted receipt: unknown (inspect Akila connection health)");
345
+ console.log("Normalization: unknown (inspect Akila worker/inbox health)");
346
+ console.log("Artifact linkage: unknown (inspect authorized event and artifact views)");
347
+ }
348
+
349
+ async function doctor() {
350
+ const manifest = readJson(p.manifest);
351
+ if (!manifest) throw new Error("Collector is not installed");
352
+ const marker = `akilium-doctor-${Date.now()}`;
353
+ const body = { resourceLogs: [{ resource: { attributes: [{ key: "service.name", value: { stringValue: "agent-telemetry-doctor" } }] }, scopeLogs: [{ scope: { name: "akilium-doctor" }, logRecords: [{ timeUnixNano: `${BigInt(Date.now()) * 1000000n}`, body: { stringValue: marker } }] }] }] };
354
+ const response = await fetch("http://127.0.0.1:4318/v1/logs", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(5000) });
355
+ if (!response.ok) throw new Error(`OTLP receiver returned HTTP ${response.status}`);
356
+ const folder = join(p.data, "archive");
357
+ for (let i = 0; i < 20; i++) {
358
+ await new Promise((resolve) => setTimeout(resolve, 250));
359
+ const files = existsSync(folder) ? readdirSync(folder).filter((name) => name.startsWith("logs") && name.endsWith(".json")) : [];
360
+ if (files.some((name) => readFileSync(join(folder, name), "utf8").includes(marker))) {
361
+ console.log("OTLP receiver and local capture: healthy");
362
+ return;
363
+ }
364
+ }
365
+ throw new Error("Collector accepted OTLP, but no local log record appeared");
366
+ }
367
+
368
+ function uninstall() {
369
+ const manifest = readJson(p.manifest);
370
+ if (!manifest) throw new Error("Collector is not installed");
371
+ stopService(manifest.mode);
372
+ if (manifest.codexManaged && existsSync(p.codex)) {
373
+ const restored = restoreCodexTelemetry(readFileSync(p.codex, "utf8"));
374
+ if (restored !== null) {
375
+ if (manifest.codexCreated && !restored.trim()) rmSync(p.codex);
376
+ else atomicWrite(p.codex, restored);
377
+ }
378
+ }
379
+ if (manifest.claudeAdded?.length && existsSync(p.claude)) {
380
+ const restored = restoreClaudeTelemetry(readFileSync(p.claude, "utf8"), manifest.claudeAdded);
381
+ if (restored === null && manifest.claudeCreated) rmSync(p.claude);
382
+ else atomicWrite(p.claude, restored ?? "{}\n");
383
+ }
384
+ if (manifest.mode !== "docker") rmSync(serviceFile(manifest.mode), { force: true });
385
+ if (manifest.mode === "systemd") run("systemctl", ["--user", "daemon-reload"], true);
386
+ rmSync(p.manifest, { force: true });
387
+ console.log(`Service removed. Retained telemetry remains at ${p.data}; remove it separately after review.`);
388
+ }
389
+
390
+ try {
391
+ if (action === "install") await install();
392
+ else if (action === "migrate") migrate();
393
+ else if (action === "upgrade") await upgrade();
394
+ else if (action === "rollback") rollback();
395
+ else if (action === "enroll") enroll();
396
+ else if (action === "configure") installAgents(readJson(p.manifest) || (() => { throw new Error("Install the collector first"); })());
397
+ else if (action === "set-destination") setDestination();
398
+ else if (action === "status") status();
399
+ else if (action === "doctor") await doctor();
400
+ else if (action === "uninstall") uninstall();
401
+ else if (action === "help") console.log("Usage: akilium-telemetry <install|migrate|enroll|configure|status|doctor|upgrade|rollback|set-destination|uninstall> [--mode native|docker] [--agents codex,claude] [--endpoint URL|--clear] [--mapping v1|v2]; enroll reads token from stdin");
402
+ else throw new Error(`Unknown action: ${action}`);
403
+ } catch (error) {
404
+ if (!quiet) console.error(`agent-telemetry: ${error.message}`);
405
+ process.exitCode = 1;
406
+ }
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ /** Native service bridge: load only the protected Akila forwarding variables. */
3
+ import { readFileSync, statSync } from "node:fs";
4
+ import { spawn } from "node:child_process";
5
+
6
+ const [binary, primaryConfig, overlayConfig, envFile] = process.argv.slice(2);
7
+ if (!binary || !primaryConfig || !overlayConfig || !envFile) throw new Error("Collector launcher arguments missing");
8
+ const stat = statSync(envFile);
9
+ if ((stat.mode & 0o077) !== 0) throw new Error("Collector enrollment file must be mode 0600");
10
+ const env = { ...process.env };
11
+ for (const line of readFileSync(envFile, "utf8").split("\n")) {
12
+ if (!line) continue;
13
+ const match = /^(AKILA_INGESTION_ENDPOINT|AKILA_CODEX_TOKEN)=(.*)$/.exec(line);
14
+ if (match) env[match[1]] = match[2];
15
+ }
16
+ if (!env.AKILA_INGESTION_ENDPOINT || !env.AKILA_CODEX_TOKEN) throw new Error("Collector enrollment is incomplete");
17
+ const child = spawn(binary, [`--config=${primaryConfig}`, `--config=${overlayConfig}`],
18
+ { env, stdio: "inherit" });
19
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => child.kill(signal));
20
+ child.on("error", (error) => { console.error(`Collector failed to start: ${error.message}`); process.exitCode = 1; });
21
+ child.on("exit", (code, signal) => { process.exitCode = code ?? (signal ? 1 : 0); });
@@ -0,0 +1,155 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+
5
+ export const VERSION = "0.161.0";
6
+ export const DIGESTS = Object.freeze({
7
+ "darwin-amd64": "357fc0a7a77f5d42cab2f46af6be301062a7824b82454cc264cb8661fa9a8734",
8
+ "darwin-arm64": "ccc0cf5de5242adcaedc7b5aebed43a1dc56aa2dc7de6ebc495d5db60512d34c",
9
+ "linux-amd64": "778c689efa681ff6e4722ce9f66b9b7f57c3ba009ab2e2b43dc2e0315862c731",
10
+ "linux-arm64": "cd5de93213a0dbb90e4998b3b9e4e15ed691ec635cf7cf4147f95799fb16b676",
11
+ });
12
+
13
+ export const SIGNALS = ["logs", "metrics", "traces"];
14
+ const managedCodexMarker = "# Managed by akilium agent-telemetry";
15
+ const claudeEnv = Object.freeze({
16
+ CLAUDE_CODE_ENABLE_TELEMETRY: "1",
17
+ OTEL_METRICS_EXPORTER: "otlp",
18
+ OTEL_LOGS_EXPORTER: "otlp",
19
+ OTEL_TRACES_EXPORTER: "otlp",
20
+ OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf",
21
+ OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318",
22
+ OTEL_LOG_USER_PROMPTS: "0",
23
+ OTEL_LOG_TOOL_DETAILS: "0",
24
+ OTEL_LOG_TOOL_CONTENT: "0",
25
+ });
26
+
27
+ export function paths(home) {
28
+ const root = join(home, ".local", "share", "akilium-agent-telemetry");
29
+ return {
30
+ root,
31
+ data: join(root, "data"),
32
+ state: join(root, "state"),
33
+ config: join(root, "collector.yaml"),
34
+ compose: join(root, "compose.yaml"),
35
+ manifest: join(root, "install.json"),
36
+ binary: join(root, "bin", "otelcol-contrib"),
37
+ codex: join(home, ".codex", "config.toml"),
38
+ claude: join(home, ".claude", "settings.json"),
39
+ launchd: join(home, "Library", "LaunchAgents", "ai.akilium.agent-telemetry.plist"),
40
+ systemd: join(home, ".config", "systemd", "user", "akilium-agent-telemetry.service"),
41
+ };
42
+ }
43
+
44
+ export function atomicWrite(file, content, mode = 0o600) {
45
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
46
+ const temporary = `${file}.tmp-${process.pid}`;
47
+ writeFileSync(temporary, content, { mode });
48
+ renameSync(temporary, file);
49
+ }
50
+
51
+ export function digest(bytes) {
52
+ return createHash("sha256").update(bytes).digest("hex");
53
+ }
54
+
55
+ function quoteYaml(value) {
56
+ return JSON.stringify(value);
57
+ }
58
+
59
+ export function renderCollector(destination = null, dataDir = "/data", bindHost = "127.0.0.1") {
60
+ const storage = `${dataDir}/state`;
61
+ const archive = `${dataDir}/archive`;
62
+ const receiver = destination ? SIGNALS.map((signal) => ` otlp_json_file/${signal}:\n include: [${quoteYaml(`${archive}/${signal}*.json`)}]\n start_at: beginning\n storage: file_storage\n include_file_name: false`).join("\n") : "";
63
+ const forwarding = destination ? ` otlp_http/forward:\n endpoint: ${quoteYaml(destination)}\n sending_queue:\n enabled: true\n storage: file_storage\n queue_size: 1000\n retry_on_failure:\n enabled: true\n max_elapsed_time: 1h\n` : "";
64
+ const pipelines = SIGNALS.map((signal) => ` ${signal}/capture:\n receivers: [otlp]\n processors: [memory_limiter, batch]\n exporters: [file/${signal}]${destination ? `\n ${signal}/forward:\n receivers: [otlp_json_file/${signal}]\n processors: [memory_limiter, batch]\n exporters: [otlp_http/forward]` : ""}`).join("\n");
65
+ return `# Generated by Akilium agent-telemetry. Edit via the CLI.\nreceivers:\n otlp:\n protocols:\n grpc:\n endpoint: ${bindHost}:4317\n http:\n endpoint: ${bindHost}:4318\n${receiver ? receiver + "\n" : ""}processors:\n memory_limiter:\n check_interval: 1s\n limit_mib: 256\n spike_limit_mib: 64\n batch:\n timeout: 1s\nexporters:\n${SIGNALS.map((signal) => ` file/${signal}:\n path: ${quoteYaml(`${archive}/${signal}.json`)}\n create_directory: true\n rotation:\n max_megabytes: 10\n max_days: 7\n max_backups: 20`).join("\n")}\n${forwarding}extensions:\n file_storage:\n directory: ${quoteYaml(storage)}\n max_size: 67108864\n create_directory: true\n health_check:\n endpoint: 127.0.0.1:13133\nservice:\n extensions: [file_storage, health_check]\n pipelines:\n${pipelines}\n`;
66
+ }
67
+
68
+ export function renderCompose(root, akilaForwarding = false) {
69
+ const overlay = akilaForwarding ? "akila-forwarding.yaml" : null;
70
+ return `services:\n collector:\n image: otel/opentelemetry-collector-contrib:${VERSION}\n restart: unless-stopped\n command: ["--config=/etc/otelcol-contrib/config.yaml"${overlay ? ', "--config=/etc/otelcol-contrib/akila-forwarding.yaml"' : ""}]\n${overlay ? ` env_file: [${quoteYaml(join(root, "akila-forwarding.env"))}]\n` : ""} ports:\n - "127.0.0.1:4317:4317"\n - "127.0.0.1:4318:4318"\n volumes:\n - ${quoteYaml(`${join(root, "collector.yaml")}:/etc/otelcol-contrib/config.yaml:ro`)}\n - ${quoteYaml(`${join(root, "data")}:/data`)}\n${overlay ? ` - ${quoteYaml(`${join(root, overlay)}:/etc/otelcol-contrib/${overlay}:ro`)}\n` : ""}`;
71
+ }
72
+
73
+ /** Completion-only allowlist. A lineage action report uses the separate SDK receiver. */
74
+ export function renderAkilaForwarding(mappingVersion = "v1") {
75
+ if (!["v1", "v2"].includes(mappingVersion)) throw new Error("Unsupported Codex mapping version");
76
+ const keys = ["event.name", "event.kind", "input_token_count", "output_token_count",
77
+ "cached_token_count", "cache_write_token_count", "reasoning_token_count", "tool_token_count",
78
+ "model", "app.version", "auth_mode", "conversation.id"];
79
+ if (mappingVersion === "v2") keys.push("user.account_id", "user.email");
80
+ return `processors:\n filter/codex_completion:\n error_mode: ignore\n log_conditions:\n - 'log.attributes["event.name"] != "codex.sse_event"'\n - 'log.attributes["event.kind"] != "response.completed"'\n transform/codex_allowlist:\n error_mode: propagate\n log_statements:\n - keep_keys(log.attributes, ${JSON.stringify(keys)})\n - keep_keys(resource.attributes, [])\n - keep_keys(scope.attributes, [])\n - set(log.body, nil)\nexporters:\n otlphttp/akila:\n logs_endpoint: \${env:AKILA_INGESTION_ENDPOINT}\n encoding: json\n compression: none\n headers:\n Authorization: "Bearer \${env:AKILA_CODEX_TOKEN}"\nservice:\n pipelines:\n logs/akila:\n receivers: [otlp]\n processors: [filter/codex_completion, transform/codex_allowlist]\n exporters: [otlphttp/akila]\n`;
81
+ }
82
+
83
+ export function codexBlock() {
84
+ const endpoint = "http://127.0.0.1:4318";
85
+ return `${managedCodexMarker}\n[otel]\nenvironment = "local"\nlog_user_prompt = false\nexporter = { otlp-http = { endpoint = "${endpoint}/v1/logs", protocol = "binary" } }\nmetrics_exporter = { otlp-http = { endpoint = "${endpoint}/v1/metrics", protocol = "binary" } }\ntrace_exporter = { otlp-http = { endpoint = "${endpoint}/v1/traces", protocol = "binary" } }\n`;
86
+ }
87
+
88
+ export function locateCodexBlock(raw) {
89
+ const lines = raw.split("\n");
90
+ let start = -1;
91
+ let end = lines.length;
92
+ for (let i = 0; i < lines.length; i++) {
93
+ if (/^\s*\[otel\]\s*(?:#.*)?$/.test(lines[i])) {
94
+ start = i;
95
+ if (i > 0 && lines[i - 1].trim() === managedCodexMarker) start = i - 1;
96
+ for (let j = i + 1; j < lines.length; j++) {
97
+ if (/^\s*\[.+\]\s*(?:#.*)?$/.test(lines[j])) {
98
+ end = j;
99
+ break;
100
+ }
101
+ }
102
+ break;
103
+ }
104
+ }
105
+ return start < 0 ? null : { start, end, lines };
106
+ }
107
+
108
+ export function setCodexTelemetry(raw) {
109
+ const found = locateCodexBlock(raw);
110
+ if (!found) return { content: `${raw.trimEnd()}${raw.trim() ? "\n\n" : ""}${codexBlock()}`, added: true };
111
+ if (found.lines[found.start].trim() !== managedCodexMarker) throw new Error("Existing Codex [otel] settings are unmanaged; configure them manually");
112
+ const content = [...found.lines.slice(0, found.start), codexBlock().trimEnd(), ...found.lines.slice(found.end)].join("\n");
113
+ return { content: content.endsWith("\n") ? content : content + "\n", added: false };
114
+ }
115
+
116
+ export function restoreCodexTelemetry(raw) {
117
+ const found = locateCodexBlock(raw);
118
+ if (!found || !found.lines[found.start].includes(managedCodexMarker)) return null;
119
+ const lines = [...found.lines.slice(0, found.start), ...found.lines.slice(found.end)];
120
+ return lines.join("\n").trimEnd() + "\n";
121
+ }
122
+
123
+ export function setClaudeTelemetry(raw) {
124
+ const settings = raw.trim() ? JSON.parse(raw) : {};
125
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) throw new Error("Claude settings must be a JSON object");
126
+ const env = settings.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : {};
127
+ const added = [];
128
+ for (const [key, value] of Object.entries(claudeEnv)) {
129
+ if (Object.hasOwn(env, key) && env[key] !== value) throw new Error(`Existing Claude setting ${key} conflicts; configure it manually`);
130
+ if (!Object.hasOwn(env, key)) added.push(key);
131
+ env[key] = value;
132
+ }
133
+ settings.env = env;
134
+ return { content: JSON.stringify(settings, null, 2) + "\n", added };
135
+ }
136
+
137
+ export function restoreClaudeTelemetry(raw, added) {
138
+ const settings = JSON.parse(raw);
139
+ const env = settings.env || {};
140
+ for (const key of added) {
141
+ if (env[key] === claudeEnv[key]) delete env[key];
142
+ }
143
+ if (Object.keys(env).length) settings.env = env;
144
+ else delete settings.env;
145
+ if (!Object.keys(settings).length) return null;
146
+ return JSON.stringify(settings, null, 2) + "\n";
147
+ }
148
+
149
+ export function readJson(file, fallback = null) {
150
+ return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : fallback;
151
+ }
152
+
153
+ export function fileBytes(file) {
154
+ return existsSync(file) ? statSync(file).size : 0;
155
+ }
package/package.json CHANGED
@@ -1,6 +1,13 @@
1
1
  {
2
2
  "name": "@akilium/telemetry-collector",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Akilium local OpenTelemetry Collector installer and diagnostic CLI",
5
+ "type": "module",
6
+ "engines": { "node": ">=22" },
7
+ "license": "MIT",
8
+ "repository": { "type": "git", "url": "git+https://github.com/Akilium/akila-platform.git", "directory": "packages/telemetry-collector" },
9
+ "bin": { "akilium-telemetry": "./bin/akilium-telemetry.mjs" },
10
+ "files": ["bin", "lib", "README.md"],
11
+ "scripts": { "test": "node --test test/*.test.mjs" },
12
+ "publishConfig": { "access": "public" }
13
+ }