@akilium/telemetry-collector 0.1.8 → 0.1.9
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 +17 -2
- package/bin/akilium-telemetry.mjs +119 -6
- package/bin/status-reporter.mjs +2 -0
- package/lib/agent-telemetry.mjs +1 -0
- package/lib/execution-capture.mjs +61 -0
- package/lib/session-titles.mjs +83 -0
- package/package.json +28 -8
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ This package migrates the reviewed operations installer into the Akila platform
|
|
|
6
6
|
|
|
7
7
|
## Supported paths and migration
|
|
8
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
|
|
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 Codex JSONL action adapter remains version-limited to CLI `0.160.0`. The separate execution instrumentation adapter supports Codex CLI `0.166.0` `exec --json` command-item metadata only. It uses native thread/item IDs and status; turn IDs, request IDs, and source timestamps are unavailable. The background OpenTelemetry Collector remains completion-only and does not imply interactive-session execution coverage.
|
|
10
10
|
|
|
11
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
12
|
|
|
@@ -28,6 +28,17 @@ Select **Action and lineage telemetry** while approving the CLI access code. The
|
|
|
28
28
|
|
|
29
29
|
The login flow reloads a managed Docker or native collector only after its protected configuration has been fully applied. The second pipeline forwards Codex `tool_result` records and explicitly structured `akila.activity` records to the capability-bound receiver. For activity records, use allowlisted attributes such as `activity.call_id`, `activity.report_id`, `activity.purpose.category_id`, `activity.purpose.category_version`, `activity.purpose.category_scope`, `activity.purpose.declared_at`, `activity.purpose.evidence_references`, `activity.membership.*`, and `activity.output.*`. Purpose and output attributes require their independently enrolled capabilities. They reuse the deterministic action identity derived from the same Codex call ID. Arguments, output bodies, prompts, resource identifiers, and tool names are dropped before export. The completion credential is never accepted by this receiver.
|
|
30
30
|
|
|
31
|
+
The execution instrumentation helper consumes only Codex CLI 0.166.0 `exec --json` events, hashes native thread/item IDs before transmission, and sends terminal command status with a separate execution credential. It ignores prompt, command, output, model text, and usage fields. It does not infer a turn, request, duration, or occurrence time from receipt time. Forwarding runs independently of JSONL event consumption; receiver failure is reported as unavailable after the stream is consumed. This helper is not an automatic hook for ordinary interactive Codex sessions.
|
|
32
|
+
|
|
33
|
+
To opt in for a command, pipe the versioned JSONL stream through the installed CLI after execution enrollment:
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
set -o pipefail
|
|
37
|
+
codex exec --json "your task" | akilium-telemetry capture-execution --version 0.166.0
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The command passes each input line through to stdout, forwards only the allowlisted metadata, and saves aggregate delivery/capability diagnostics under the protected local state directory. `akilium-telemetry status` shows the latest local execution-capture health. Unsupported versions are passed through without parsing or sending reports; receiver failures do not fail the captured command stream. This is a manual command path, not an automatic hook for ordinary interactive Codex sessions.
|
|
41
|
+
|
|
31
42
|
## Operational limits and diagnostics, v1
|
|
32
43
|
|
|
33
44
|
The Collector retains local rotated archive files for seven days with up to 20 backups of 10 MiB each per signal. Local log capture drops bodies and known prompt, argument, output, and identity attributes before archiving. 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 and action overlays forward separate allowlisted metadata after dropping bodies and unapproved attributes. Each receiver independently enforces privacy and authorization.
|
|
@@ -41,4 +52,8 @@ Select **session** while approving the local collector’s access code. The inst
|
|
|
41
52
|
|
|
42
53
|
Managed setup captures new completions only. It does not offer retained-history import; previously captured evidence remains governed and unchanged.
|
|
43
54
|
|
|
44
|
-
Session capture uses protected source-qualified canonical metadata and does not collect prompts or responses. Token rotation, revocation, expiry or lost source approval stops capture; prepare a target-bound reconnect and approve the session capability to resume. `status` distinguishes local configuration from hosted validity; inspect Connections health, then refresh Sessions after processing. Missing protected identity remains unresolved, and a captured session may be unscored or have unavailable monetary cost.
|
|
55
|
+
Session capture uses protected source-qualified canonical metadata and does not collect prompts or responses. Collector 0.1.9 also synchronizes actual saved Codex chat names from `session_index.jsonl` for sessions already bound to the enrolled source. Only the saved title, update time and protected session digest are sent; transcripts, raw thread IDs and local paths are excluded. A manually edited Akila name takes precedence. Token rotation, revocation, expiry or lost source approval stops capture; prepare a target-bound reconnect and approve the session capability to resume. `status` distinguishes local configuration from hosted validity; inspect Connections health, then refresh Sessions after processing. Missing protected identity remains unresolved, and a captured session may be unscored or have unavailable monetary cost.
|
|
56
|
+
|
|
57
|
+
### Upgrading saved-name collection
|
|
58
|
+
|
|
59
|
+
Publish/install collector 0.1.9 and complete a target-bound session reconnect after deploying the coordinated database and session receiver changes. Successful session enrollment privately stores the session credential in `session-title-enrollment.json`; the existing background reporter synchronizes bounded name batches every check-in cycle. Existing installations without that file need the reconnect because their prior session credential was intentionally not retained. The status credential remains separate and cannot submit titles. A lost acknowledgement retries the same source versions; removing the capability, rotating credentials, pending setup or source revocation prevents further uploads.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { configureSessionCapture } from "../lib/session-capture.mjs";
|
|
3
|
+
import { captureExecutionJsonl, formatExecutionHealth, safeExecutionHealth } from "../lib/execution-capture.mjs";
|
|
3
4
|
/** Install and operate the local OTLP receiver. Runtime files live outside Git. */
|
|
4
5
|
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
5
6
|
import { homedir, platform, arch } from "node:os";
|
|
@@ -45,7 +46,7 @@ function backupExisting(manifest) {
|
|
|
45
46
|
const folder = join(p.state, `platform-backup-${Date.now()}`);
|
|
46
47
|
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
47
48
|
const files = [p.manifest, p.config, p.compose, p.launchd, p.systemd, p.binary,
|
|
48
|
-
join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), join(p.root, "telemetry-installation.json"), statusServiceFile(), p.codex, p.claude].filter(Boolean);
|
|
49
|
+
join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), join(p.root, "telemetry-installation.json"), join(p.root, "session-title-enrollment.json"), statusServiceFile(), p.codex, p.claude].filter(Boolean);
|
|
49
50
|
const saved = [];
|
|
50
51
|
for (const file of files) {
|
|
51
52
|
if (!existsSync(file)) continue;
|
|
@@ -225,9 +226,13 @@ async function upgrade() {
|
|
|
225
226
|
}
|
|
226
227
|
|
|
227
228
|
async function login() {
|
|
228
|
-
if (
|
|
229
|
-
|
|
230
|
-
|
|
229
|
+
if (args.includes("--invite-stdin")) {
|
|
230
|
+
if (args.includes("--include-history")) throw new Error("Managed enrollment captures new completions only; retained history is not imported");
|
|
231
|
+
return await managedLogin();
|
|
232
|
+
}
|
|
233
|
+
const installed = readJson(p.manifest);
|
|
234
|
+
if (args.includes("--legacy-device-link") || (installed && args.includes("--endpoint"))) return await legacyLogin();
|
|
235
|
+
throw new Error("Use login --invite-stdin for managed setup, or --legacy-device-link for an existing legacy source");
|
|
231
236
|
}
|
|
232
237
|
|
|
233
238
|
async function readInvitation() {
|
|
@@ -433,6 +438,64 @@ async function managedLogin() {
|
|
|
433
438
|
console.log("Akila local collector linked. No enrollment credential was displayed.");
|
|
434
439
|
}
|
|
435
440
|
|
|
441
|
+
async function legacyLogin() {
|
|
442
|
+
const manifest = readJson(p.manifest);
|
|
443
|
+
if (!manifest) throw new Error("Install or migrate the collector first");
|
|
444
|
+
const requestedEndpoint = option("--endpoint", null);
|
|
445
|
+
const pending = manifest.deviceLinkPending;
|
|
446
|
+
const endpoint = requestedEndpoint || pending?.endpoint || manifest.deviceLink?.endpoint;
|
|
447
|
+
const machineName = option("--name", pending?.machineName || process.env.HOSTNAME || "local collector");
|
|
448
|
+
if (!endpoint) throw new Error("--endpoint is required the first time you link this collector");
|
|
449
|
+
const base = new URL(endpoint);
|
|
450
|
+
if ((base.protocol !== "https:" && !["localhost", "127.0.0.1"].includes(base.hostname)) || base.username || base.password || base.search || base.hash) throw new Error("Device-link endpoint must be an HTTPS Supabase URL without credentials, query, or fragment");
|
|
451
|
+
const control = `${base.toString().replace(/\/$/, "")}/functions/v1/local-telemetry-device-link`;
|
|
452
|
+
const post = async (path, value) => {
|
|
453
|
+
const response = await fetch(`${control}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(value), signal: AbortSignal.timeout(15_000) });
|
|
454
|
+
if (!response.ok && response.status !== 204) throw new Error("Device-link service is unavailable");
|
|
455
|
+
return response.status === 204 ? null : await response.json();
|
|
456
|
+
};
|
|
457
|
+
const origin = base.toString().replace(/\/$/, "");
|
|
458
|
+
if (pending && pending.endpoint !== origin) throw new Error("A different device-link request is pending; finish or wait for it to expire before changing --endpoint");
|
|
459
|
+
let started = pending;
|
|
460
|
+
if (!started || !started.expiresAt || new Date(started.expiresAt).getTime() <= Date.now()) {
|
|
461
|
+
const created = await post("/start", { machineName, collectorVersion: "0.1.4" });
|
|
462
|
+
if (!created || typeof created.requestId !== "string" || typeof created.code !== "string" || typeof created.pollSecret !== "string" || typeof created.expiresAt !== "string") throw new Error("Invalid device-link response");
|
|
463
|
+
started = { ...created, endpoint: origin, machineName };
|
|
464
|
+
manifest.deviceLinkPending = started;
|
|
465
|
+
saveManifest(manifest);
|
|
466
|
+
}
|
|
467
|
+
console.log(`Akila access code: ${started.code}`);
|
|
468
|
+
console.log("In Akila, open Connections > AI providers > your Codex source, choose Link local collector, enter this code, and select capabilities.");
|
|
469
|
+
const deadline = new Date(started.expiresAt).getTime(); let approved = null;
|
|
470
|
+
while (Date.now() < deadline) {
|
|
471
|
+
await new Promise((resolve) => setTimeout(resolve, 5_000));
|
|
472
|
+
const status = await post("/poll", { requestId: started.requestId, pollSecret: started.pollSecret });
|
|
473
|
+
if (status?.status === "pending") continue;
|
|
474
|
+
if (status?.status === "approved" && status.payload && typeof status.deliveryId === "string") { approved = status; break; }
|
|
475
|
+
throw new Error("Device-link request was denied, revoked, or expired");
|
|
476
|
+
}
|
|
477
|
+
if (!approved) throw new Error("Device-link request expired before approval");
|
|
478
|
+
const payload = approved.payload;
|
|
479
|
+
if (payload.usage?.token) enroll(payload.usage.token, `${origin}/functions/v1/codex-usage-ingestion/v1/logs`);
|
|
480
|
+
if (payload.lineage?.token) enrollLineage(payload.lineage.token, `${origin}/functions/v1/codex-lineage-otel-ingestion`);
|
|
481
|
+
if (payload.session?.token) await enrollSessions(false, payload.session.token, `${origin}/functions/v1/ai-session-evidence/enroll`);
|
|
482
|
+
const executionEnrollment = payload.execution?.token
|
|
483
|
+
? enrollExecution(payload.execution.token, `${origin}/functions/v1/ai-execution-evidence`)
|
|
484
|
+
: null;
|
|
485
|
+
// The enrollment helpers write atomically and retain a rollback backup. Reload
|
|
486
|
+
// only after all selected capabilities have been configured successfully.
|
|
487
|
+
stopService(manifest.mode);
|
|
488
|
+
startService(manifest.mode);
|
|
489
|
+
manifest.deviceLink = { endpoint: origin, machineName, linkedAt: new Date().toISOString() };
|
|
490
|
+
if (executionEnrollment) manifest.akilaExecutionEnrollment = executionEnrollment;
|
|
491
|
+
else delete manifest.akilaExecutionEnrollment;
|
|
492
|
+
saveManifest(manifest);
|
|
493
|
+
await post("/acknowledge", { requestId: started.requestId, pollSecret: started.pollSecret, deliveryId: approved.deliveryId });
|
|
494
|
+
delete manifest.deviceLinkPending;
|
|
495
|
+
saveManifest(manifest);
|
|
496
|
+
console.log("Akila local collector linked. No enrollment credential was displayed.");
|
|
497
|
+
}
|
|
498
|
+
|
|
436
499
|
async function rollback() {
|
|
437
500
|
const manifest = readJson(p.manifest);
|
|
438
501
|
if (!manifest?.migrationBackup) throw new Error("No platform migration backup is recorded");
|
|
@@ -440,7 +503,7 @@ async function rollback() {
|
|
|
440
503
|
const saved = readJson(join(folder, "index.json"));
|
|
441
504
|
if (!Array.isArray(saved)) throw new Error("Migration backup index is missing");
|
|
442
505
|
const allowed = new Set([p.manifest, p.config, p.compose, p.launchd, p.systemd, p.binary,
|
|
443
|
-
join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), join(p.root, "telemetry-installation.json"), statusServiceFile(), p.codex, p.claude].filter(Boolean));
|
|
506
|
+
join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), join(p.root, "telemetry-installation.json"), join(p.root, "session-title-enrollment.json"), statusServiceFile(), p.codex, p.claude].filter(Boolean));
|
|
444
507
|
if (saved.some((entry) => !allowed.has(entry.path) || dirname(entry.backup) !== folder ||
|
|
445
508
|
!existsSync(entry.backup))) throw new Error("Migration backup index is invalid");
|
|
446
509
|
stopService(manifest.mode);
|
|
@@ -570,9 +633,57 @@ async function enrollSessions(previewOnly = false, tokenOverride = null, endpoin
|
|
|
570
633
|
if (binding.sourceId && result.sourceId !== binding.sourceId) throw new Error("Session source does not match this installation");
|
|
571
634
|
manifest.akilaSessionCapture = { endpoint, sourceId: result.sourceId, expiresAt: result.expiresAt, includeHistory };
|
|
572
635
|
saveManifest(manifest);
|
|
636
|
+
atomicWrite(join(p.root, "session-title-enrollment.json"), JSON.stringify({ endpoint: endpoint.replace(/\/enroll$/, ''),
|
|
637
|
+
token, sourceId: result.sourceId, generation: binding.generation, afterSessionId: null }) + '\n');
|
|
638
|
+
console.log("Saved Codex session names will sync only for sessions already enrolled in this source.");
|
|
573
639
|
console.log(`Session capture enrolled until ${result.expiresAt}. ${includeHistory ? "Exact retained history included." : "New completions only."}`);
|
|
574
640
|
}
|
|
575
641
|
|
|
642
|
+
function enrollExecution(tokenOverride = null, endpointOverride = null) {
|
|
643
|
+
const manifest = readJson(p.manifest);
|
|
644
|
+
if (!manifest) throw new Error("Install or migrate the collector first");
|
|
645
|
+
const envFile = join(p.root, "akila-forwarding.env");
|
|
646
|
+
if (!existsSync(envFile) || (statSync(envFile).mode & 0o077) !== 0) throw new Error("Protected completion forwarding enrollment is required");
|
|
647
|
+
const endpoint = endpointOverride || option("--endpoint");
|
|
648
|
+
if (!endpoint) throw new Error("--endpoint is required");
|
|
649
|
+
const url = new URL(endpoint);
|
|
650
|
+
if ((url.protocol !== "https:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) || url.username || url.password || url.search || url.hash ||
|
|
651
|
+
!url.pathname.endsWith("/functions/v1/ai-execution-evidence")) throw new Error("Execution enrollment requires the configured HTTPS execution receiver URL");
|
|
652
|
+
const lines = readFileSync(envFile, "utf8").split("\n");
|
|
653
|
+
const completionEndpoint = lines.find(line => line.startsWith("AKILA_INGESTION_ENDPOINT="))?.slice("AKILA_INGESTION_ENDPOINT=".length);
|
|
654
|
+
if (!completionEndpoint || new URL(completionEndpoint).origin !== url.origin) throw new Error("Execution and completion endpoints must use the same project");
|
|
655
|
+
const token = tokenOverride || readFileSync(0, "utf8").trim();
|
|
656
|
+
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw new Error("Invalid execution enrollment token");
|
|
657
|
+
backupExisting(manifest);
|
|
658
|
+
const retained = lines.filter(line => line && !/^AKILA_EXECUTION_(ENDPOINT|TOKEN)=/.test(line));
|
|
659
|
+
atomicWrite(envFile, [...retained, `AKILA_EXECUTION_ENDPOINT=${url.toString()}`, `AKILA_EXECUTION_TOKEN=${token}`, ""].join("\n"));
|
|
660
|
+
chmodSync(envFile, 0o600);
|
|
661
|
+
console.log("Execution credential stored with protected local permissions. The background OpenTelemetry collector remains completion-only; the separately versioned Codex exec JSONL instrumentation adapter handles verified command metadata.");
|
|
662
|
+
return { endpoint: url.toString(), capability: "ai_execution_evidence_v1", enrolledAt: new Date().toISOString() };
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
async function captureExecution() {
|
|
666
|
+
const manifest = readJson(p.manifest);
|
|
667
|
+
if (!manifest?.akilaExecutionEnrollment) throw new Error("Execution capture is not enrolled on this installation");
|
|
668
|
+
const envFile = join(p.root, "akila-forwarding.env");
|
|
669
|
+
if (!existsSync(envFile) || (statSync(envFile).mode & 0o077) !== 0) throw new Error("Protected execution enrollment is unavailable");
|
|
670
|
+
const values = new Map(readFileSync(envFile, "utf8").split("\n").filter(Boolean).map((line) => {
|
|
671
|
+
const separator = line.indexOf("=");
|
|
672
|
+
return separator > 0 ? [line.slice(0, separator), line.slice(separator + 1)] : ["", ""];
|
|
673
|
+
}));
|
|
674
|
+
const endpoint = values.get("AKILA_EXECUTION_ENDPOINT");
|
|
675
|
+
const token = values.get("AKILA_EXECUTION_TOKEN");
|
|
676
|
+
const sourceVersion = option("--version");
|
|
677
|
+
if (!endpoint || !token || !sourceVersion) throw new Error("Execution endpoint, credential, and --version are required");
|
|
678
|
+
if (manifest.akilaExecutionEnrollment.capability !== "ai_execution_evidence_v1" ||
|
|
679
|
+
manifest.akilaExecutionEnrollment.endpoint !== endpoint) throw new Error("Execution enrollment does not match the protected receiver configuration");
|
|
680
|
+
const diagnostics = await captureExecutionJsonl({ input: process.stdin, output: process.stdout, endpoint, token, sourceVersion });
|
|
681
|
+
mkdirSync(p.state, { recursive: true, mode: 0o700 });
|
|
682
|
+
const health = safeExecutionHealth(diagnostics);
|
|
683
|
+
atomicWrite(p.executionHealth, JSON.stringify(health) + "\n", 0o600);
|
|
684
|
+
console.error(formatExecutionHealth(health));
|
|
685
|
+
}
|
|
686
|
+
|
|
576
687
|
function setDestination() {
|
|
577
688
|
const manifest = readJson(p.manifest);
|
|
578
689
|
if (!manifest) throw new Error("Install the collector first");
|
|
@@ -647,6 +758,7 @@ function status() {
|
|
|
647
758
|
console.log("Hosted receipt: unknown (inspect Akila connection health)");
|
|
648
759
|
console.log("Normalization: unknown (inspect Akila worker/inbox health)");
|
|
649
760
|
console.log("Artifact linkage: unknown (inspect authorized event and artifact views)");
|
|
761
|
+
console.log(formatExecutionHealth(readJson(p.executionHealth)));
|
|
650
762
|
}
|
|
651
763
|
|
|
652
764
|
async function doctor() {
|
|
@@ -699,12 +811,13 @@ try {
|
|
|
699
811
|
else if (action === "rollback") await rollback();
|
|
700
812
|
else if (action === "enroll") enroll();
|
|
701
813
|
else if (action === "enroll-lineage") enrollLineage();
|
|
814
|
+
else if (action === "capture-execution") await captureExecution();
|
|
702
815
|
else if (action === "configure") installAgents(readJson(p.manifest) || (() => { throw new Error("Install the collector first"); })());
|
|
703
816
|
else if (action === "set-destination") setDestination();
|
|
704
817
|
else if (action === "status") { status(); if (args.includes("--repair")) { await startStatusReporter(); console.log("Status reporting restarted."); } }
|
|
705
818
|
else if (action === "doctor") await doctor();
|
|
706
819
|
else if (action === "uninstall") uninstall();
|
|
707
|
-
else if (action === "help") console.log("Usage: akilium-telemetry <install|migrate|login|enroll|enroll-lineage|configure|status|doctor|upgrade|rollback|set-destination|uninstall> [--mode native|docker] [--agents codex,claude] [--endpoint URL|--clear] [--name MACHINE] [--mapping v1|v2] [--invite-stdin]; enrollment secrets are read through protected stdin");
|
|
820
|
+
else if (action === "help") console.log("Usage: akilium-telemetry <install|migrate|login|enroll|enroll-lineage|capture-execution|configure|status|doctor|upgrade|rollback|set-destination|uninstall> [--mode native|docker] [--agents codex,claude] [--endpoint URL|--clear] [--name MACHINE] [--mapping v1|v2] [--include-history] [--invite-stdin|--legacy-device-link]; enrollment secrets are read through protected stdin");
|
|
708
821
|
else throw new Error(`Unknown action: ${action}`);
|
|
709
822
|
} catch (error) {
|
|
710
823
|
if (!quiet) console.error(`agent-telemetry: ${error.message}`);
|
package/bin/status-reporter.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
|
+
import { syncSessionTitlesOnce } from '../lib/session-titles.mjs';
|
|
4
5
|
import { checkInOnce, retryDelay } from '../lib/status-reporter.mjs';
|
|
5
6
|
const home=process.env.AGENT_TELEMETRY_HOME || homedir();
|
|
6
7
|
const root=join(home,'.local','share','akilium-agent-telemetry');
|
|
@@ -9,6 +10,7 @@ for (const signal of ['SIGINT','SIGTERM']) process.on(signal,()=>{stopped=true;
|
|
|
9
10
|
async function cycle() {
|
|
10
11
|
if (stopped) return;
|
|
11
12
|
try { await checkInOnce(root); failures=0; } catch { failures=Math.min(failures+1,10); }
|
|
13
|
+
try { await syncSessionTitlesOnce(root, { codexHome: process.env.CODEX_HOME || join(home, '.codex') }); } catch { /* Retain the source cursor and retry; never log titles or credentials. */ }
|
|
12
14
|
if (!stopped) timer=setTimeout(cycle,retryDelay(failures));
|
|
13
15
|
}
|
|
14
16
|
await cycle();
|
package/lib/agent-telemetry.mjs
CHANGED
|
@@ -30,6 +30,7 @@ export function paths(home) {
|
|
|
30
30
|
root,
|
|
31
31
|
data: join(root, "data"),
|
|
32
32
|
state: join(root, "state"),
|
|
33
|
+
executionHealth: join(root, "state", "codex-execution-health.json"),
|
|
33
34
|
config: join(root, "collector.yaml"),
|
|
34
35
|
compose: join(root, "compose.yaml"),
|
|
35
36
|
manifest: join(root, "install.json"),
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2
|
+
import { once } from "node:events";
|
|
3
|
+
import { createAiExecutionReporter, captureCodexExecutionJsonl } from "@akilium/instrumentation";
|
|
4
|
+
|
|
5
|
+
/** Stream Codex JSONL through unchanged while forwarding only its allowlisted execution metadata. */
|
|
6
|
+
export async function captureExecutionJsonl({ input, output, sourceVersion, endpoint, token, fetch }) {
|
|
7
|
+
const reporter = createAiExecutionReporter({ endpoint, token, fetch });
|
|
8
|
+
const decoder = new StringDecoder("utf8");
|
|
9
|
+
async function* events() {
|
|
10
|
+
let pending = "";
|
|
11
|
+
const parse = (line) => {
|
|
12
|
+
try { return JSON.parse(line); }
|
|
13
|
+
catch { return line; }
|
|
14
|
+
};
|
|
15
|
+
for await (const chunk of input) {
|
|
16
|
+
if (!output.write(chunk)) await once(output, "drain");
|
|
17
|
+
pending += decoder.write(chunk);
|
|
18
|
+
let newline;
|
|
19
|
+
while ((newline = pending.indexOf("\n")) !== -1) {
|
|
20
|
+
let line = pending.slice(0, newline);
|
|
21
|
+
pending = pending.slice(newline + 1);
|
|
22
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
23
|
+
yield parse(line);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
pending += decoder.end();
|
|
27
|
+
if (pending.length) yield parse(pending);
|
|
28
|
+
}
|
|
29
|
+
return await captureCodexExecutionJsonl(events(), sourceVersion, reporter);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function safeExecutionHealth(diagnostics, checkedAt = new Date().toISOString()) {
|
|
33
|
+
return {
|
|
34
|
+
checkedAt,
|
|
35
|
+
supported: diagnostics.supported,
|
|
36
|
+
commandExecutions: diagnostics.commandExecutions,
|
|
37
|
+
missingThread: diagnostics.missingThread,
|
|
38
|
+
invalidItems: diagnostics.invalidItems,
|
|
39
|
+
reportsAccepted: diagnostics.reportsAccepted,
|
|
40
|
+
reportsUnavailable: diagnostics.reportsUnavailable,
|
|
41
|
+
reportsRejected: diagnostics.reportsRejected,
|
|
42
|
+
turnIdsUnavailable: diagnostics.turnIdsUnavailable,
|
|
43
|
+
requestIdsUnavailable: diagnostics.requestIdsUnavailable,
|
|
44
|
+
sourceTimestampsUnavailable: diagnostics.sourceTimestampsUnavailable,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function formatExecutionHealth(health) {
|
|
49
|
+
if (!health || typeof health !== "object" || typeof health.checkedAt !== "string" ||
|
|
50
|
+
!Number.isFinite(Date.parse(health.checkedAt)) || typeof health.supported !== "boolean" ||
|
|
51
|
+
["commandExecutions", "reportsAccepted", "reportsUnavailable", "reportsRejected"].some(key =>
|
|
52
|
+
!Number.isSafeInteger(health[key]) || health[key] < 0) ||
|
|
53
|
+
["turnIdsUnavailable", "requestIdsUnavailable", "sourceTimestampsUnavailable"].some(key =>
|
|
54
|
+
typeof health[key] !== "boolean")) return "Execution capture: no local run recorded";
|
|
55
|
+
const runtime = health.supported ? "supported" : "unsupported runtime";
|
|
56
|
+
const delivery = health.reportsUnavailable > 0 ? `${health.reportsUnavailable} unavailable` :
|
|
57
|
+
health.reportsRejected > 0 ? `${health.reportsRejected} rejected` : `${health.reportsAccepted} accepted`;
|
|
58
|
+
const limitations = [health.turnIdsUnavailable && "turn IDs", health.requestIdsUnavailable && "request IDs",
|
|
59
|
+
health.sourceTimestampsUnavailable && "source timing"].filter(Boolean).join(", ");
|
|
60
|
+
return `Execution capture: ${runtime}; ${health.commandExecutions} commands, ${delivery}; unavailable fields: ${limitations || "none"}; checked ${health.checkedAt}`;
|
|
61
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { createReadStream, existsSync, lstatSync } from 'node:fs';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { atomicWrite, readJson } from './agent-telemetry.mjs';
|
|
7
|
+
|
|
8
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
9
|
+
export const sessionKeyHash = (sourceId, threadId) => hash(`sha256:${hash(`${sourceId}:${threadId}`)}`);
|
|
10
|
+
const privateFile = file => { const s = lstatSync(file); return s.isFile() && !s.isSymbolicLink() && (s.mode & 0o077) === 0; };
|
|
11
|
+
|
|
12
|
+
/** Read saved names only. Never open a rollout/transcript or infer a title from a prompt. */
|
|
13
|
+
export async function readSessionTitles(file, sourceId, targets) {
|
|
14
|
+
if (!existsSync(file)) return [];
|
|
15
|
+
const stat = lstatSync(file);
|
|
16
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024 * 1024) throw new Error('Codex title index unavailable');
|
|
17
|
+
const wanted = new Set(targets), found = new Map();
|
|
18
|
+
const stream = createReadStream(file, { encoding: 'utf8', highWaterMark: 16_384 });
|
|
19
|
+
const lines = createInterface({ input: stream, crlfDelay: Infinity });
|
|
20
|
+
let bytes = 0;
|
|
21
|
+
try {
|
|
22
|
+
for await (const line of lines) {
|
|
23
|
+
bytes += Buffer.byteLength(line) + 1;
|
|
24
|
+
if (bytes > 64 * 1024 * 1024) throw new Error('Codex title index exceeds limit');
|
|
25
|
+
if (line.length > 16_384) continue;
|
|
26
|
+
let entry; try { entry = JSON.parse(line); } catch { continue; }
|
|
27
|
+
if (typeof entry.id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(entry.id) ||
|
|
28
|
+
typeof entry.thread_name !== 'string' || !entry.thread_name.trim() || entry.thread_name.trim().length > 240 ||
|
|
29
|
+
/[\u0000-\u001f\u007f]/.test(entry.thread_name) || typeof entry.updated_at !== 'string' ||
|
|
30
|
+
!/^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(entry.updated_at) || !Number.isFinite(Date.parse(entry.updated_at))) continue;
|
|
31
|
+
const key = sessionKeyHash(sourceId, entry.id);
|
|
32
|
+
if (!wanted.has(key)) continue;
|
|
33
|
+
const previous = found.get(key);
|
|
34
|
+
if (!previous || Date.parse(entry.updated_at) > Date.parse(previous.sourceUpdatedAt)) {
|
|
35
|
+
found.set(key, { sessionKeyHash: key, title: entry.thread_name.trim(), sourceUpdatedAt: new Date(entry.updated_at).toISOString() });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
} finally { lines.close(); stream.destroy(); }
|
|
39
|
+
return [...found.values()];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function syncSessionTitlesOnce(root, { request = fetch, codexHome = process.env.CODEX_HOME || join(homedir(), '.codex') } = {}) {
|
|
43
|
+
const file = join(root, 'session-title-enrollment.json');
|
|
44
|
+
if (!existsSync(file)) return 'not_enrolled';
|
|
45
|
+
if (!privateFile(file)) throw new Error('Session title credential must be private');
|
|
46
|
+
const installationFile = join(root, 'telemetry-installation.json');
|
|
47
|
+
if (!existsSync(installationFile) || !privateFile(installationFile)) return 'not_ready';
|
|
48
|
+
const installation = readJson(installationFile);
|
|
49
|
+
const binding = readJson(file), manifest = readJson(join(root, 'install.json'));
|
|
50
|
+
if (!manifest?.deviceLink || manifest.deviceLinkPending || manifest.deviceLink.sourceId !== binding.sourceId ||
|
|
51
|
+
manifest.deviceLink.generation !== binding.generation || installation?.sourceId !== binding.sourceId || installation?.generation !== binding.generation || !installation?.capabilities?.includes('session') ||
|
|
52
|
+
manifest.akilaSessionCapture?.sourceId !== binding.sourceId) return 'not_ready';
|
|
53
|
+
if (!/^[A-Za-z0-9_-]{32,128}$/.test(binding.token ?? '') || !/^[0-9a-f-]{36}$/i.test(binding.sourceId ?? '')) throw new Error('Invalid session title enrollment');
|
|
54
|
+
const url = new URL(binding.endpoint);
|
|
55
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname))) ||
|
|
56
|
+
url.username || url.password || url.search || url.hash || !url.pathname.endsWith('/functions/v1/ai-session-evidence')) throw new Error('Invalid session title endpoint');
|
|
57
|
+
const send = async (suffix, body) => {
|
|
58
|
+
let response;
|
|
59
|
+
try { response = await request(`${url}${suffix}`, { method: 'POST', redirect: 'error', headers: {
|
|
60
|
+
authorization: `Bearer ${binding.token}`, 'content-type': 'application/json',
|
|
61
|
+
}, body: JSON.stringify(body), signal: AbortSignal.timeout(10_000) }); } catch { throw new Error('Session title service unavailable'); }
|
|
62
|
+
if (!response.ok) throw new Error('Session title synchronization unavailable');
|
|
63
|
+
try { return await response.json(); } catch { throw new Error('Invalid title service response'); }
|
|
64
|
+
};
|
|
65
|
+
// Cursor writes must never replace a credential rotated by concurrent reconnect.
|
|
66
|
+
// A cursor from an older enrollment is harmless: its fingerprint will not match.
|
|
67
|
+
const fingerprint = hash(JSON.stringify([binding.sourceId, binding.generation, binding.token, binding.endpoint]));
|
|
68
|
+
const cursorFile = join(root, 'session-title-cursor.json');
|
|
69
|
+
let cursor;
|
|
70
|
+
if (existsSync(cursorFile)) {
|
|
71
|
+
if (!privateFile(cursorFile)) throw new Error('Session title cursor must be private');
|
|
72
|
+
cursor = readJson(cursorFile);
|
|
73
|
+
}
|
|
74
|
+
const afterSessionId = cursor?.fingerprint === fingerprint ? cursor.afterSessionId : null;
|
|
75
|
+
if (!(afterSessionId === null || typeof afterSessionId === 'string' && /^[0-9a-f-]{36}$/i.test(afterSessionId))) throw new Error('Invalid session title cursor');
|
|
76
|
+
const page = await send('/titles/targets', { afterSessionId });
|
|
77
|
+
if (!Array.isArray(page.targets) || page.targets.length > 200 || page.targets.some(x => typeof x !== 'string' || !/^[0-9a-f]{64}$/.test(x)) ||
|
|
78
|
+
!(page.continuation === null || typeof page.continuation === 'string' && /^[0-9a-f-]{36}$/i.test(page.continuation))) throw new Error('Invalid title targets');
|
|
79
|
+
const titles = page.targets.length ? await readSessionTitles(join(codexHome, 'session_index.jsonl'), binding.sourceId, page.targets) : [];
|
|
80
|
+
for (let i = 0; i < titles.length; i += 50) await send('/titles', { contractVersion: '1.0.0', titles: titles.slice(i, i + 50) });
|
|
81
|
+
atomicWrite(cursorFile, JSON.stringify({ fingerprint, afterSessionId: page.continuation }) + '\n');
|
|
82
|
+
return 'synchronized';
|
|
83
|
+
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@akilium/telemetry-collector",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.9",
|
|
4
4
|
"description": "Akilium local OpenTelemetry Collector installer and diagnostic CLI",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"engines": {
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22"
|
|
8
|
+
},
|
|
7
9
|
"license": "MIT",
|
|
8
|
-
"repository": {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/Akilium/akila-platform.git",
|
|
13
|
+
"directory": "packages/telemetry-collector"
|
|
14
|
+
},
|
|
15
|
+
"bin": {
|
|
16
|
+
"akilium-telemetry": "./bin/akilium-telemetry.mjs"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"bin",
|
|
20
|
+
"lib",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@akilium/instrumentation": "0.1.9"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"pretest": "pnpm --filter @akilium/instrumentation build",
|
|
31
|
+
"test": "node --test test/*.test.mjs"
|
|
32
|
+
}
|
|
33
|
+
}
|