@akilium/telemetry-collector 0.1.4 → 0.1.8

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
@@ -12,29 +12,21 @@ Before changing an existing operations-managed installation, run `akilium-teleme
12
12
 
13
13
  ## Protected enrollment
14
14
 
15
- Use a source-approved HTTPS completion receiver URL and pass its one-time enrollment token on stdin, for example:
15
+ An operator prepares a setup link in **Connections → Telemetry enrollment**. On a new reporter, install the collector service with `akilium-telemetry install --mode native --agents codex` (or use `--mode docker`). On the intended computer, use the endpoint from the setup link and paste the invitation at the hidden prompt:
16
16
 
17
17
  ```sh
18
- printf '%s' "$AKILA_CODEX_TOKEN" | akilium-telemetry enroll --endpoint https://YOUR_PROJECT.supabase.co/functions/v1/codex-usage-ingestion/v1/logs
18
+ akilium-telemetry login --endpoint https://YOUR_PROJECT.supabase.co --name "My laptop" --invite-stdin
19
19
  ```
20
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.
21
+ The CLI prints a ten-character access code. The operator compares it with the intended person and approves the device and its selected capabilities in Telemetry enrollment. The browser never receives collector credentials; the CLI stores forwarding and installation credentials in protected local files, backs up the installation, starts the selected services and acknowledges delivery after application. Retry the same login before expiry to recover an interrupted apply. Session enrollment captures new completions and does not import retained history.
22
22
 
23
- ## Codex action attempts
24
-
25
- After the source and connection are active, issue a separate action capture token from the Codex connection controls. Read it without echo and enroll it independently:
26
-
27
- ```sh
28
- printf 'Lineage token: '; read -r -s AKILA_LINEAGE_TOKEN; printf '\n'; printf '%s' "$AKILA_LINEAGE_TOKEN" | npx --yes @akilium/telemetry-collector@0.1.2 enroll-lineage --endpoint https://YOUR_PROJECT.supabase.co/functions/v1/codex-lineage-otel-ingestion; unset AKILA_LINEAGE_TOKEN
29
- ```
23
+ Manual session-token setup and the old device-code exchange are retired. The older `enroll` and `enroll-lineage` commands remain available for separately governed unmanaged source credentials, not managed installations.
30
24
 
31
- For Docker, recreate the container after enrollment so the new environment variables are loaded:
25
+ ## Codex action attempts
32
26
 
33
- ```sh
34
- docker compose -f "$HOME/.local/share/akilium-agent-telemetry/compose.yaml" up -d --force-recreate collector
35
- ```
27
+ Select **Action and lineage telemetry** while approving the CLI access code. The same protected local environment receives a separate capability-bound credential; it is never displayed in Connections.
36
28
 
37
- For native installations, stop and relaunch the collector with the updated protected environment. A Docker restart alone keeps the previous environment. 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.
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.
38
30
 
39
31
  ## Operational limits and diagnostics, v1
40
32
 
@@ -43,10 +35,10 @@ The Collector retains local rotated archive files for seven days with up to 20 b
43
35
  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 SDK reports. The Codex OTel action pipeline uses the Collector's persistent file-backed queue and retries for up to one hour. `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.
44
36
 
45
37
 
46
- ## Session capture (0.1.4)
38
+ ## Session capture
47
39
 
48
- Session capture requires an active approved Codex completion source with protected conversation references. In **Connections → Codex telemetry → Session capture**, issue a separate session capture token. Existing usage/action tokens do not enable this capability. The source administrator's controls show enrollment validity, captured sessions/revisions and pending/failed processing.
40
+ Select **session** while approving the local collector’s access code. The installation has an independent session credential bound to its own installation and generation; session capture requires usage capture to be selected as well.
49
41
 
50
- Use the displayed hidden-prompt commands with `npx --yes @akilium/telemetry-collector@0.1.4 preview-sessions --endpoint https://YOUR_PROJECT.supabase.co/functions/v1/ai-session-evidence/enroll` and then `enroll-sessions` at that same endpoint. Both read the token from stdin; never put it in a command argument or URL. Preview reports exact retained sessions/completion revisions, missing-identity records and already captured revisions without changing any data. Add `--include-history` to enrollment only after reviewing that preview if you want retained exact history; default enrollment captures new completions.
42
+ Managed setup captures new completions only. It does not offer retained-history import; previously captured evidence remains governed and unchanged.
51
43
 
52
- Enrollment reuses the existing completion exporter and protected source-qualified canonical metadata. It adds no exporter, does not collect prompts/responses, and does not restart or overwrite the Collector. It stores only public enrollment metadata locally, not the session credential. Token rotation, revocation, expiry or lost source approval stops session capture; issue and enroll a replacement token 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.
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.
@@ -13,6 +13,7 @@ import {
13
13
  readJson, fileBytes,
14
14
  } from "../lib/agent-telemetry.mjs";
15
15
 
16
+ const CLI_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
16
17
  const [action = "help", ...args] = process.argv.slice(2);
17
18
  const home = process.env.AGENT_TELEMETRY_HOME || homedir();
18
19
  const p = paths(home);
@@ -44,7 +45,7 @@ function backupExisting(manifest) {
44
45
  const folder = join(p.state, `platform-backup-${Date.now()}`);
45
46
  mkdirSync(folder, { recursive: true, mode: 0o700 });
46
47
  const files = [p.manifest, p.config, p.compose, p.launchd, p.systemd, p.binary,
47
- join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), p.codex, p.claude];
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);
48
49
  const saved = [];
49
50
  for (const file of files) {
50
51
  if (!existsSync(file)) continue;
@@ -86,6 +87,24 @@ function startService(mode) {
86
87
  }
87
88
  }
88
89
 
90
+ // Service managers can report a newly started process as activating for a
91
+ // short time. Wait for readiness before acknowledging the managed delivery.
92
+ async function waitForService(check) {
93
+ for (let attempt = 0; attempt < 20; attempt++) {
94
+ try { if (check()) return; } catch { /* service may still be starting */ }
95
+ await new Promise(resolve => setTimeout(resolve, 250));
96
+ }
97
+ throw new Error("Service did not start");
98
+ }
99
+
100
+ async function waitForCollector(mode) {
101
+ await waitForService(() => mode === "docker"
102
+ ? run("docker", ["compose", "-f", p.compose, "ps", "--status", "running", "--services"]).split(/\s+/).includes("collector")
103
+ : mode === "launchd"
104
+ ? /state\s*=\s*running/.test(run("launchctl", ["print", `gui/${process.getuid()}/ai.akilium.agent-telemetry`]))
105
+ : run("systemctl", ["--user", "is-active", "akilium-agent-telemetry.service"]) === "active");
106
+ }
107
+
89
108
  function launchdPlist() {
90
109
  const xml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
91
110
  const args = readJson(p.manifest)?.akilaCompletionForwarding
@@ -205,24 +224,239 @@ async function upgrade() {
205
224
  await install(manifest.mode === "docker" ? "docker" : "native");
206
225
  }
207
226
 
208
- function rollback() {
227
+ async function login() {
228
+ if (!args.includes("--invite-stdin")) throw new Error("Use login --invite-stdin with the setup link provided by your operator");
229
+ if (args.includes("--include-history")) throw new Error("Managed enrollment captures new completions only; retained history is not imported");
230
+ return await managedLogin();
231
+ }
232
+
233
+ async function readInvitation() {
234
+ let value = "";
235
+ if (!process.stdin.isTTY) {
236
+ value = readFileSync(0, "utf8");
237
+ } else {
238
+ process.stderr.write("Paste the invitation and press Enter: ");
239
+ process.stdin.setRawMode(true);
240
+ process.stdin.resume();
241
+ try {
242
+ for await (const chunk of process.stdin) {
243
+ for (const ch of chunk.toString("utf8")) {
244
+ if (ch === "\u0003") throw new Error("Setup cancelled");
245
+ if (ch === "\r" || ch === "\n") return checkedInvitation(value);
246
+ if (ch === "\u007f" || ch === "\b") value = value.slice(0, -1);
247
+ else value += ch;
248
+ if (value.length > 256) throw new Error("Invalid invitation on stdin");
249
+ }
250
+ }
251
+ } finally {
252
+ process.stdin.setRawMode(false);
253
+ process.stdin.pause();
254
+ process.stderr.write("\n");
255
+ }
256
+ }
257
+ return checkedInvitation(value);
258
+ }
259
+ function checkedInvitation(value) {
260
+ value = value.trim();
261
+ if (!/^[A-Za-z0-9_-]{32,128}$/.test(value)) throw new Error("Invalid invitation on stdin");
262
+ return value;
263
+ }
264
+ function validSecret(value) { return typeof value === "string" && /^[A-Za-z0-9_-]{32,128}$/.test(value); }
265
+ function validateManagedPayload(payload, origin) {
266
+ const id = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
267
+ const suffix = { usage: "/functions/v1/codex-usage-ingestion/v1/logs", lineage: "/functions/v1/codex-lineage-otel-ingestion", session: "/functions/v1/ai-session-evidence/enroll" };
268
+ if (!payload || !id.test(payload.installationId) || !id.test(payload.sourceId) || !Number.isSafeInteger(payload.generation) || payload.generation < 1 ||
269
+ !Array.isArray(payload.capabilities) || !payload.capabilities.length || payload.capabilities.length > 3 ||
270
+ new Set(payload.capabilities).size !== payload.capabilities.length || payload.capabilities.some(c => !(c in suffix)) ||
271
+ (payload.capabilities.includes('session') && !payload.capabilities.includes('usage')) ||
272
+ !validSecret(payload.statusCredential?.token) || !validSecret(payload.statusCredential?.challenge) ||
273
+ typeof payload.statusCredential?.expiresAt !== "string" || !Number.isFinite(Date.parse(payload.statusCredential.expiresAt)) || Date.parse(payload.statusCredential.expiresAt) <= Date.now()) throw new Error("Invalid device-link delivery");
274
+ for (const c of Object.keys(suffix)) {
275
+ const value = payload[c];
276
+ if (payload.capabilities.includes(c) !== Boolean(value)) throw new Error("Invalid device-link delivery");
277
+ if (value) {
278
+ if (!validSecret(value.token) || typeof value.endpoint !== "string" || typeof value.expiresAt !== "string" || !Number.isFinite(Date.parse(value.expiresAt)) || Date.parse(value.expiresAt) <= Date.now()) throw new Error("Invalid device-link delivery");
279
+ const url = new URL(value.endpoint);
280
+ if (url.origin !== new URL(origin).origin || url.pathname !== suffix[c] || url.username || url.password || url.search || url.hash) throw new Error("Invalid device-link delivery");
281
+ }
282
+ }
283
+ }
284
+ async function applyManagedPayload(payload, origin) {
285
+ validateManagedPayload(payload, origin);
286
+ let manifest = readJson(p.manifest);
287
+ const prior = manifest.deviceLink;
288
+ if (prior?.installationId && (prior.installationId !== payload.installationId || prior.sourceId !== payload.sourceId ||
289
+ !Number.isSafeInteger(prior.generation) || payload.generation <= prior.generation))
290
+ throw new Error("Delivery does not match the existing installation");
291
+ const usage = payload.capabilities.includes("usage"), lineage = payload.capabilities.includes("lineage");
292
+ const forwarding = usage || lineage;
293
+ const overlay = join(p.root, "akila-forwarding.yaml"), envFile = join(p.root, "akila-forwarding.env");
294
+ const compose = existsSync(p.compose) ? readFileSync(p.compose, "utf8") : "";
295
+ if (manifest.mode === "docker" && compose && ![renderCompose(p.root),renderCompose(p.root,true)].includes(compose))
296
+ throw new Error("Custom Compose configuration requires review before enrollment");
297
+ if (manifest.mode !== "docker") {
298
+ const service = serviceFile(manifest.mode), existing = existsSync(service) ? readFileSync(service, "utf8") : "";
299
+ if (existing && !(existing.includes("ai.akilium.agent-telemetry") || existing.includes("Description=Akilium local agent telemetry collector")))
300
+ throw new Error("Custom service configuration requires review before enrollment");
301
+ }
302
+ backupExisting(manifest);
303
+ const old = existsSync(envFile) ? readFileSync(envFile, "utf8").split("\n") : [];
304
+ const retained = old.filter(line => line && !/^AKILA_(INGESTION_ENDPOINT|CODEX_TOKEN|LINEAGE_ENDPOINT|LINEAGE_TOKEN)=/.test(line));
305
+ if (usage) retained.push(`AKILA_INGESTION_ENDPOINT=${payload.usage.endpoint}`, `AKILA_CODEX_TOKEN=${payload.usage.token}`);
306
+ if (lineage) retained.push(`AKILA_LINEAGE_ENDPOINT=${payload.lineage.endpoint}`, `AKILA_LINEAGE_TOKEN=${payload.lineage.token}`);
307
+ atomicWrite(envFile, retained.join("\n") + "\n");
308
+ if (forwarding) atomicWrite(overlay, renderAkilaForwarding(option("--mapping", "v1"), lineage, usage));
309
+ manifest.akilaCompletionForwarding = forwarding;
310
+ manifest.akilaLineageForwarding = lineage;
311
+ saveManifest(manifest);
312
+ if (manifest.mode === "docker") atomicWrite(p.compose, renderCompose(p.root,forwarding));
313
+ else atomicWrite(serviceFile(manifest.mode), manifest.mode === "launchd" ? launchdPlist() : systemdUnit(), 0o644);
314
+ const binding = { endpoint: origin, installationId: payload.installationId, sourceId: payload.sourceId, generation: payload.generation,
315
+ token: payload.statusCredential.token, challenge: payload.statusCredential.challenge, expiresAt: payload.statusCredential.expiresAt, capabilities: payload.capabilities };
316
+ atomicWrite(join(p.root,"telemetry-installation.json"),JSON.stringify(binding) + "\n");
317
+ if (payload.session) await enrollSessions(false,payload.session.token,payload.session.endpoint,binding);
318
+ manifest = readJson(p.manifest);
319
+ try {
320
+ if (manifest.mode === "docker") run("docker", ["compose", "-f", p.compose, "config", "--quiet"]);
321
+ else run(p.binary, ["validate", `--config=${p.config}`, ...(forwarding ? [`--config=${overlay}`] : [])]);
322
+ stopService(manifest.mode);
323
+ startService(manifest.mode);
324
+ await waitForCollector(manifest.mode);
325
+ await startStatusReporter();
326
+ } catch { throw new Error("Collector or status service could not start; setup remains pending"); }
327
+ }
328
+ function statusServiceFile() {
329
+ if (platform() === "darwin") return join(home,"Library","LaunchAgents","ai.akilium.telemetry-status.plist");
330
+ if (platform() === "linux") return join(home,".config","systemd","user","akilium-telemetry-status.service");
331
+ return null;
332
+ }
333
+ async function startStatusReporter() {
334
+ const worker = fileURLToPath(new URL("./status-reporter.mjs", import.meta.url));
335
+ if (platform() === "darwin") {
336
+ const target = join(home, "Library", "LaunchAgents", "ai.akilium.telemetry-status.plist");
337
+ const xml = value => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
338
+ const existing = existsSync(target) ? readFileSync(target,"utf8") : "";
339
+ if (existing && !existing.includes("ai.akilium.telemetry-status")) throw new Error("Status service requires review");
340
+ const args=[process.execPath,worker];
341
+ atomicWrite(target,`<?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><key>Label</key><string>ai.akilium.telemetry-status</string><key>ProgramArguments</key><array>${args.map(x=>`<string>${xml(x)}</string>`).join("")}</array><key>EnvironmentVariables</key><dict><key>AGENT_TELEMETRY_HOME</key><string>${xml(home)}</string></dict><key>RunAtLoad</key><true/><key>KeepAlive</key><true/></dict></plist>\n`,0o644);
342
+ run("launchctl",["bootout",`gui/${process.getuid()}`,target],true);
343
+ run("launchctl",["bootstrap",`gui/${process.getuid()}`,target]);
344
+ await waitForService(() => /state\s*=\s*running/.test(run("launchctl",["print",`gui/${process.getuid()}/ai.akilium.telemetry-status`])));
345
+ } else if (platform() === "linux") {
346
+ const target=join(home,".config","systemd","user","akilium-telemetry-status.service");
347
+ if ([process.execPath,worker,home].some(x=>/[\n\r%"\\]/.test(x))) throw new Error("Unsafe status service path");
348
+ const existing=existsSync(target)?readFileSync(target,"utf8"):"";
349
+ if (existing && !existing.includes("Description=Akilium telemetry status reporter")) throw new Error("Status service requires review");
350
+ atomicWrite(target,`[Unit]\nDescription=Akilium telemetry status reporter\nAfter=network-online.target\n\n[Service]\nType=simple\nEnvironment="AGENT_TELEMETRY_HOME=${home}"\nExecStart="${process.execPath}" "${worker}"\nRestart=on-failure\nRestartSec=30\nNoNewPrivileges=true\n\n[Install]\nWantedBy=default.target\n`,0o644);
351
+ run("systemctl",["--user","daemon-reload"]);
352
+ run("systemctl",["--user","enable","--now","akilium-telemetry-status.service"]);
353
+ run("systemctl",["--user","restart","akilium-telemetry-status.service"]);
354
+ await waitForService(() => run("systemctl",["--user","is-active","akilium-telemetry-status.service"]) === "active");
355
+ } else throw new Error("Status service is unavailable on this platform");
356
+ }
357
+ function stopStatusReporter() {
358
+ if (platform() === "darwin") {
359
+ const target=join(home,"Library","LaunchAgents","ai.akilium.telemetry-status.plist");
360
+ if (existsSync(target) && readFileSync(target,"utf8").includes("ai.akilium.telemetry-status")) {
361
+ run("launchctl",["bootout",`gui/${process.getuid()}`,target],true); rmSync(target,{force:true});
362
+ }
363
+ } else if (platform() === "linux") {
364
+ const target=join(home,".config","systemd","user","akilium-telemetry-status.service");
365
+ if (existsSync(target) && readFileSync(target,"utf8").includes("Description=Akilium telemetry status reporter")) {
366
+ run("systemctl",["--user","disable","--now","akilium-telemetry-status.service"],true); rmSync(target,{force:true});
367
+ run("systemctl",["--user","daemon-reload"],true);
368
+ }
369
+ }
370
+ }
371
+ async function managedLogin() {
372
+ let manifest = readJson(p.manifest);
373
+ if (!manifest) throw new Error("Install or migrate the collector first");
374
+ let started = manifest.deviceLinkPending;
375
+ if (started && started.version !== 2) throw new Error("An incompatible device-link request is pending until it expires");
376
+ const endpoint = option("--endpoint", started?.endpoint || manifest.deviceLink?.endpoint);
377
+ if (!endpoint) throw new Error("--endpoint is required the first time you link this collector");
378
+ const base = new URL(endpoint);
379
+ if ((base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname))) || base.username || base.password || base.search || base.hash)
380
+ throw new Error("Device-link endpoint must be a verified HTTPS Supabase URL");
381
+ const origin = base.toString().replace(/\/$/, ""), control = `${origin}/functions/v1/local-telemetry-device-link`;
382
+ if (started && started.endpoint !== origin) throw new Error("A different device-link request is pending");
383
+ if (started && (!started.expiresAt || Date.parse(started.expiresAt) <= Date.now())) {
384
+ delete manifest.deviceLinkPending; saveManifest(manifest); started = null;
385
+ }
386
+ // Back up the prior installation before writing a new request or its proof.
387
+ if (!started) { backupExisting(manifest); manifest = readJson(p.manifest); }
388
+ const post = async (path,value) => {
389
+ let response;
390
+ try { response = await fetch(`${control}${path}`, { method:"POST", headers:{"content-type":"application/json"}, body:JSON.stringify(value), redirect:"error", signal:AbortSignal.timeout(15_000) }); }
391
+ catch { throw new Error("Device-link service is unavailable"); }
392
+ if (!response.ok) throw new Error("Device-link service is unavailable");
393
+ return response.status === 204 ? null : await response.json();
394
+ };
395
+ if (!started || !started.expiresAt || Date.parse(started.expiresAt) <= Date.now()) {
396
+ const machineName = option("--name", process.env.HOSTNAME || "local collector");
397
+ const created = await post("/start", {machineName,collectorVersion:CLI_VERSION});
398
+ if (!created || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(created.requestId ?? "") || !/^AKLA-[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}$/.test(created.code ?? "") || !validSecret(created.pollSecret) || !Number.isFinite(Date.parse(created.expiresAt)))
399
+ throw new Error("Invalid device-link response");
400
+ started = {...created, endpoint:origin, machineName, version:2, claimed:false};
401
+ manifest.deviceLinkPending = started; saveManifest(manifest);
402
+ }
403
+ if (!started.claimed) {
404
+ const invitation = await readInvitation();
405
+ await post("/v2/claim", {requestId:started.requestId,pollSecret:started.pollSecret,invitation});
406
+ started.claimed = true; manifest.deviceLinkPending = started; saveManifest(manifest);
407
+ }
408
+ if (started.applied) {
409
+ try { await waitForCollector(manifest.mode); await startStatusReporter(); } catch { throw new Error("Collector or status service could not start; setup remains pending"); }
410
+ await post("/v2/acknowledge", {requestId:started.requestId,pollSecret:started.pollSecret,deliveryId:started.applied.deliveryId,generation:started.applied.generation});
411
+ } else {
412
+ console.log(`Akila access code: ${started.code}`);
413
+ console.log("Ask your operator to compare this code and approve this device in Connections.");
414
+ let approved;
415
+ while (Date.now() < Date.parse(started.expiresAt)) {
416
+ await new Promise(resolve => setTimeout(resolve,5000));
417
+ const result = await post("/v2/poll", {requestId:started.requestId,pollSecret:started.pollSecret});
418
+ if (result?.status === "pending") continue;
419
+ if (result?.status === "approved" && result.payload && typeof result.deliveryId === "string") { approved=result; break; }
420
+ throw new Error("Device-link request was denied, revoked, or expired");
421
+ }
422
+ if (!approved) throw new Error("Device-link request expired before approval");
423
+ await applyManagedPayload(approved.payload,origin);
424
+ manifest=readJson(p.manifest); started=manifest.deviceLinkPending;
425
+ started.applied={deliveryId:approved.deliveryId,generation:approved.payload.generation};
426
+ manifest.deviceLinkPending=started; saveManifest(manifest);
427
+ await post("/v2/acknowledge", {requestId:started.requestId,pollSecret:started.pollSecret,deliveryId:started.applied.deliveryId,generation:started.applied.generation});
428
+ }
429
+ manifest=readJson(p.manifest);
430
+ const binding=readJson(join(p.root,"telemetry-installation.json"));
431
+ manifest.deviceLink={endpoint:origin,machineName:started.machineName,installationId:binding.installationId,sourceId:binding.sourceId,generation:binding.generation,linkedAt:new Date().toISOString()};
432
+ delete manifest.deviceLinkPending; saveManifest(manifest);
433
+ console.log("Akila local collector linked. No enrollment credential was displayed.");
434
+ }
435
+
436
+ async function rollback() {
209
437
  const manifest = readJson(p.manifest);
210
438
  if (!manifest?.migrationBackup) throw new Error("No platform migration backup is recorded");
211
439
  const folder = manifest.migrationBackup;
212
440
  const saved = readJson(join(folder, "index.json"));
213
441
  if (!Array.isArray(saved)) throw new Error("Migration backup index is missing");
214
442
  const allowed = new Set([p.manifest, p.config, p.compose, p.launchd, p.systemd, p.binary,
215
- join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), p.codex, p.claude]);
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));
216
444
  if (saved.some((entry) => !allowed.has(entry.path) || dirname(entry.backup) !== folder ||
217
445
  !existsSync(entry.backup))) throw new Error("Migration backup index is invalid");
218
446
  stopService(manifest.mode);
447
+ stopStatusReporter();
219
448
  for (const entry of saved) {
220
449
  mkdirSync(dirname(entry.path), { recursive: true, mode: 0o700 });
221
450
  copyFileSync(entry.backup, entry.path);
222
451
  chmodSync(entry.path, entry.mode);
223
452
  }
453
+ const savedPaths = new Set(saved.map(entry => entry.path));
454
+ for (const file of [join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), join(p.root, "telemetry-installation.json")]) {
455
+ if (!savedPaths.has(file)) rmSync(file, { force: true });
456
+ }
224
457
  const restored = readJson(p.manifest);
225
458
  if (restored?.mode) startService(restored.mode);
459
+ if (restored?.deviceLink?.installationId && statusServiceFile() && savedPaths.has(statusServiceFile())) await startStatusReporter();
226
460
  console.log("Previous collector configuration restored from the protected backup");
227
461
  }
228
462
 
@@ -233,15 +467,15 @@ function migrate() {
233
467
  console.log(`Existing configuration backed up at ${folder}; collector and agents were not restarted`);
234
468
  }
235
469
 
236
- function enroll() {
470
+ function enroll(tokenOverride = null, endpointOverride = null) {
237
471
  const manifest = readJson(p.manifest);
238
472
  if (!manifest) throw new Error("Install or migrate the collector first");
239
- const endpoint = option("--endpoint");
473
+ const endpoint = endpointOverride || option("--endpoint");
240
474
  const mappingVersion = option("--mapping", "v1");
241
475
  if (!["v1", "v2"].includes(mappingVersion)) throw new Error("--mapping must be v1 or v2");
242
476
  if (!endpoint) throw new Error("--endpoint is required");
243
477
  const url = new URL(endpoint);
244
- if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash ||
478
+ if ((url.protocol !== "https:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) || url.username || url.password || url.search || url.hash ||
245
479
  !url.pathname.endsWith("/functions/v1/codex-usage-ingestion/v1/logs")) {
246
480
  throw new Error("Enrollment requires a verified HTTPS Codex completion receiver URL");
247
481
  }
@@ -261,7 +495,7 @@ function enroll() {
261
495
  throw new Error("Native service file has custom content; review it before enrollment");
262
496
  }
263
497
  }
264
- const token = readFileSync(0, "utf8").trim();
498
+ const token = tokenOverride || readFileSync(0, "utf8").trim();
265
499
  if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw new Error("Invalid enrollment token on stdin");
266
500
  backupExisting(manifest);
267
501
  const previous = existsSync(envFile) ? readFileSync(envFile, "utf8").split("\n") : [];
@@ -283,13 +517,13 @@ function enroll() {
283
517
  console.log("Protected completion forwarding configured; restart the collector and check hosted acceptance");
284
518
  }
285
519
 
286
- function enrollLineage() {
520
+ function enrollLineage(tokenOverride = null, endpointOverride = null) {
287
521
  const manifest = readJson(p.manifest);
288
522
  if (!manifest) throw new Error("Install or migrate the collector first");
289
- const endpoint = option("--endpoint");
523
+ const endpoint = endpointOverride || option("--endpoint");
290
524
  if (!endpoint) throw new Error("--endpoint is required");
291
525
  const url = new URL(endpoint);
292
- if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash ||
526
+ if ((url.protocol !== "https:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) || url.username || url.password || url.search || url.hash ||
293
527
  !url.pathname.endsWith("/functions/v1/codex-lineage-otel-ingestion")) {
294
528
  throw new Error("Enrollment requires a verified HTTPS Codex lineage OTel receiver URL");
295
529
  }
@@ -298,7 +532,7 @@ function enrollLineage() {
298
532
  if (!existsSync(envFile) || !existsSync(overlay)) throw new Error("Configure completion forwarding before lineage forwarding");
299
533
  const lines = readFileSync(envFile, "utf8").split("\n");
300
534
  if (!lines.some((line) => line.startsWith("AKILA_CODEX_TOKEN="))) throw new Error("Completion forwarding enrollment is incomplete");
301
- const token = readFileSync(0, "utf8").trim();
535
+ const token = tokenOverride || readFileSync(0, "utf8").trim();
302
536
  if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw new Error("Invalid lineage enrollment token on stdin");
303
537
  const oldConfig = readFileSync(overlay, "utf8");
304
538
  const mappingVersion = oldConfig.includes('"user.account_id"') ? "v2" : "v1";
@@ -314,29 +548,29 @@ function enrollLineage() {
314
548
  if (manifest.mode === "docker") console.log(`Run: docker compose -f "${join(p.root, "compose.yaml")}" up -d --force-recreate collector`);
315
549
  }
316
550
 
317
- async function enrollSessions(previewOnly = false) {
551
+ async function enrollSessions(previewOnly = false, tokenOverride = null, endpointOverride = null, bindingOverride = null) {
318
552
  const manifest = readJson(p.manifest);
319
553
  if (!manifest) throw new Error("Install or migrate the collector first");
320
- const envFile = join(p.root, "akila-forwarding.env");
321
- if (!existsSync(envFile) || (statSync(envFile).mode & 0o077) !== 0) throw new Error("Protected completion forwarding enrollment is required");
322
- const lines = readFileSync(envFile, "utf8").split("\n");
323
- if (!lines.some(line => /^AKILA_CODEX_TOKEN=.+/.test(line))) throw new Error("Completion forwarding enrollment is required");
324
- const endpoint = option("--endpoint");
325
- if (!endpoint) throw new Error("--endpoint is required");
326
- const completionEndpoint = lines.find(line => line.startsWith("AKILA_INGESTION_ENDPOINT="))?.slice("AKILA_INGESTION_ENDPOINT=".length);
327
- if (!completionEndpoint || new URL(completionEndpoint).origin !== new URL(endpoint).origin) throw new Error("Session and completion endpoints must use the same project");
328
- const token = readFileSync(0, "utf8").trim();
329
- const completionToken = lines.find(line => line.startsWith("AKILA_CODEX_TOKEN="))?.slice("AKILA_CODEX_TOKEN=".length);
330
- const preview = await configureSessionCapture({ endpoint, token, completionToken, action: "preview" });
554
+ const bindingFile = join(p.root, "telemetry-installation.json");
555
+ if (!bindingOverride && (!existsSync(bindingFile) || (statSync(bindingFile).mode & 0o077) !== 0))
556
+ throw new Error("Protected installation enrollment is required");
557
+ const binding = bindingOverride || readJson(bindingFile);
558
+ const endpoint = endpointOverride || option("--endpoint");
559
+ if (!endpoint || !binding?.endpoint || new URL(binding.endpoint).origin !== new URL(endpoint).origin)
560
+ throw new Error("Session and installation endpoints must use the same project");
561
+ const token = tokenOverride || readFileSync(0, "utf8").trim();
562
+ const installationCredential = binding.token;
563
+ const preview = await configureSessionCapture({ endpoint, token, installationCredential, action: "preview" });
331
564
  console.log(`Retained history: ${preview.eligibleSessions} exact sessions / ${preview.eligibleRecords} completion revisions; ${preview.unresolvedRecords} unresolved; ${preview.capturedRecords} already captured.`);
332
- if (preview.usageCredentialState !== "active") console.log(`Usage credential: ${preview.usageCredentialState}. Renew usage enrollment and restart/recreate the collector to resume new completions.`);
333
565
  if (previewOnly) { console.log("Preview only; no capture settings or session data changed."); return; }
334
- const includeHistory = args.includes("--include-history");
335
- const result = await configureSessionCapture({ endpoint, token, completionToken, action: "enroll", includeHistory });
566
+ // Managed enrollment starts with new completions; reconnect never imports
567
+ // retained history implicitly.
568
+ const includeHistory = false;
569
+ const result = await configureSessionCapture({ endpoint, token, installationCredential, action: "enroll", includeHistory });
570
+ if (binding.sourceId && result.sourceId !== binding.sourceId) throw new Error("Session source does not match this installation");
336
571
  manifest.akilaSessionCapture = { endpoint, sourceId: result.sourceId, expiresAt: result.expiresAt, includeHistory };
337
572
  saveManifest(manifest);
338
573
  console.log(`Session capture enrolled until ${result.expiresAt}. ${includeHistory ? "Exact retained history included." : "New completions only."}`);
339
- console.log("Existing completion forwarding is reused; no collector restart or additional exporter is required. Check Connections for hosted processing health, then refresh Sessions.");
340
574
  }
341
575
 
342
576
  function setDestination() {
@@ -401,7 +635,15 @@ function status() {
401
635
  else console.log(`Service: ${run("launchctl", ["list", "ai.akilium.agent-telemetry"], true) ? "loaded" : "inactive"}`);
402
636
  if (manifest.akilaSessionCapture) {
403
637
  console.log(`Session capture: locally enrolled until ${manifest.akilaSessionCapture.expiresAt}; hosted validity/processing must be checked in Connections`);
404
- } else console.log("Session capture: not enrolled on this installation (use enroll-sessions)");
638
+ } else console.log("Session capture: not enrolled on this installation (approve session capture through Telemetry enrollment)");
639
+ if (manifest.deviceLink?.installationId) {
640
+ const statusFile=join(p.root,"telemetry-installation.json");
641
+ const privateState=existsSync(statusFile) && (statSync(statusFile).mode & 0o077)===0;
642
+ const service=platform()==="darwin" ? (run("launchctl",["list","ai.akilium.telemetry-status"],true) ? "loaded" : "inactive") :
643
+ platform()==="linux" ? (run("systemctl",["--user","is-active","akilium-telemetry-status.service"],true) || "inactive") : "unavailable";
644
+ console.log(`Status reporter: ${service}; local state ${privateState ? "protected" : "unavailable or unprotected"}`);
645
+ if (manifest.deviceLinkPending) console.log("Device setup: awaiting local completion or acknowledgement");
646
+ }
405
647
  console.log("Hosted receipt: unknown (inspect Akila connection health)");
406
648
  console.log("Normalization: unknown (inspect Akila worker/inbox health)");
407
649
  console.log("Artifact linkage: unknown (inspect authorized event and artifact views)");
@@ -430,6 +672,7 @@ function uninstall() {
430
672
  const manifest = readJson(p.manifest);
431
673
  if (!manifest) throw new Error("Collector is not installed");
432
674
  stopService(manifest.mode);
675
+ stopStatusReporter();
433
676
  if (manifest.codexManaged && existsSync(p.codex)) {
434
677
  const restored = restoreCodexTelemetry(readFileSync(p.codex, "utf8"));
435
678
  if (restored !== null) {
@@ -452,17 +695,16 @@ try {
452
695
  if (action === "install") await install();
453
696
  else if (action === "migrate") migrate();
454
697
  else if (action === "upgrade") await upgrade();
455
- else if (action === "rollback") rollback();
698
+ else if (action === "login") await login();
699
+ else if (action === "rollback") await rollback();
456
700
  else if (action === "enroll") enroll();
457
701
  else if (action === "enroll-lineage") enrollLineage();
458
- else if (action === "enroll-sessions") await enrollSessions();
459
- else if (action === "preview-sessions") await enrollSessions(true);
460
702
  else if (action === "configure") installAgents(readJson(p.manifest) || (() => { throw new Error("Install the collector first"); })());
461
703
  else if (action === "set-destination") setDestination();
462
- else if (action === "status") status();
704
+ else if (action === "status") { status(); if (args.includes("--repair")) { await startStatusReporter(); console.log("Status reporting restarted."); } }
463
705
  else if (action === "doctor") await doctor();
464
706
  else if (action === "uninstall") uninstall();
465
- else if (action === "help") console.log("Usage: akilium-telemetry <install|migrate|enroll|enroll-lineage|preview-sessions|enroll-sessions|configure|status|doctor|upgrade|rollback|set-destination|uninstall> [--mode native|docker] [--agents codex,claude] [--endpoint URL|--clear] [--mapping v1|v2] [--include-history]; all enrollment/preview commands read tokens from stdin");
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");
466
708
  else throw new Error(`Unknown action: ${action}`);
467
709
  } catch (error) {
468
710
  if (!quiet) console.error(`agent-telemetry: ${error.message}`);
@@ -13,7 +13,10 @@ for (const line of readFileSync(envFile, "utf8").split("\n")) {
13
13
  const match = /^(AKILA_INGESTION_ENDPOINT|AKILA_CODEX_TOKEN|AKILA_LINEAGE_ENDPOINT|AKILA_LINEAGE_TOKEN)=(.*)$/.exec(line);
14
14
  if (match) env[match[1]] = match[2];
15
15
  }
16
- if (!env.AKILA_INGESTION_ENDPOINT || !env.AKILA_CODEX_TOKEN) throw new Error("Collector enrollment is incomplete");
16
+ const overlay = readFileSync(overlayConfig, "utf8");
17
+ const usage = /^ logs\/akila:$/m.test(overlay), lineage = /^ logs\/akila_lineage:$/m.test(overlay);
18
+ if ((!usage && !lineage) || (usage && (!env.AKILA_INGESTION_ENDPOINT || !env.AKILA_CODEX_TOKEN)) ||
19
+ (lineage && (!env.AKILA_LINEAGE_ENDPOINT || !env.AKILA_LINEAGE_TOKEN))) throw new Error("Collector enrollment is incomplete");
17
20
  const child = spawn(binary, [`--config=${primaryConfig}`, `--config=${overlayConfig}`],
18
21
  { env, stdio: "inherit" });
19
22
  for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => child.kill(signal));
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { join } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { checkInOnce, retryDelay } from '../lib/status-reporter.mjs';
5
+ const home=process.env.AGENT_TELEMETRY_HOME || homedir();
6
+ const root=join(home,'.local','share','akilium-agent-telemetry');
7
+ let stopped=false, failures=0, timer;
8
+ for (const signal of ['SIGINT','SIGTERM']) process.on(signal,()=>{stopped=true; clearTimeout(timer);});
9
+ async function cycle() {
10
+ if (stopped) return;
11
+ try { await checkInOnce(root); failures=0; } catch { failures=Math.min(failures+1,10); }
12
+ if (!stopped) timer=setTimeout(cycle,retryDelay(failures));
13
+ }
14
+ await cycle();
@@ -71,7 +71,8 @@ export function renderCompose(root, akilaForwarding = false) {
71
71
  }
72
72
 
73
73
  /** Completion forwarding remains separate from the independently authenticated action lineage path. */
74
- export function renderAkilaForwarding(mappingVersion = "v1", includeLineage = false) {
74
+ export function renderAkilaForwarding(mappingVersion = "v1", includeLineage = false, includeUsage = true) {
75
+ if (!includeUsage && !includeLineage) throw new Error("Select at least one forwarding capability");
75
76
  if (!["v1", "v2"].includes(mappingVersion)) throw new Error("Unsupported Codex mapping version");
76
77
  const keys = ["event.name", "event.kind", "input_token_count", "output_token_count",
77
78
  "cached_token_count", "cache_write_token_count", "reasoning_token_count", "tool_token_count",
@@ -80,6 +81,7 @@ export function renderAkilaForwarding(mappingVersion = "v1", includeLineage = fa
80
81
  const lineage = includeLineage ? ` filter/codex_tool_result:\n error_mode: ignore\n log_conditions:\n - 'log.attributes["event.name"] != "codex.tool_result" and log.attributes["event.name"] != "akila.activity"'\n transform/codex_tool_result_allowlist:\n error_mode: propagate\n log_statements:\n - keep_keys(log.attributes, ["event.name", "event.timestamp", "call_id", "success", "duration_ms", "activity.call_id", "activity.report_id", "activity.occurred_at", "activity.purpose.category_id", "activity.purpose.category_version", "activity.purpose.category_scope", "activity.purpose.tenant_id", "activity.purpose.team_id", "activity.purpose.declared_at", "activity.purpose.evidence_references", "activity.membership.context_id", "activity.membership.context_kind", "activity.membership.established_at", "activity.output.output_id", "activity.output.kind", "activity.output.lifetime", "activity.output.evidence_reference", "activity.output.no_output_assertion_id", "activity.output.no_output_occurred_at", "activity.output.no_output_origin", "activity.output.no_output_qualification", "activity.output.no_output_evidence_reference", "activity.output.no_output_supersedes_id"])\n - keep_keys(resource.attributes, ["service.name", "service.version"])\n - keep_keys(scope.attributes, [])\n - set(log.body, nil)\n` : "";
81
82
  const lineageExporter = includeLineage ? ` otlphttp/lineage:\n logs_endpoint: \${env:AKILA_LINEAGE_ENDPOINT}\n encoding: json\n compression: none\n headers:\n Authorization: "Bearer \${env:AKILA_LINEAGE_TOKEN}"\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` : "";
82
83
  const lineagePipeline = includeLineage ? ` logs/akila_lineage:\n receivers: [otlp]\n processors: [filter/codex_tool_result, transform/codex_tool_result_allowlist]\n exporters: [otlphttp/lineage]\n` : "";
84
+ if (!includeUsage) return `processors:\n${lineage}exporters:\n${lineageExporter}service:\n pipelines:\n${lineagePipeline}`;
83
85
  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)\n${lineage}exporters:\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}"\n${lineageExporter}service:\n pipelines:\n logs/akila:\n receivers: [otlp]\n processors: [filter/codex_completion, transform/codex_allowlist]\n exporters: [otlphttp/akila]\n${lineagePipeline}`;
84
86
  }
85
87
 
@@ -1,20 +1,20 @@
1
1
  /** No raw identifiers or tokens are persisted or returned by this client. */
2
- export async function configureSessionCapture({ endpoint, token, completionToken, action, includeHistory = false, request = fetch }) {
2
+ export async function configureSessionCapture({ endpoint, token, installationCredential, action, includeHistory = false, request = fetch }) {
3
3
  const url = new URL(endpoint);
4
- if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash ||
4
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname))) || url.username || url.password || url.search || url.hash ||
5
5
  !url.pathname.endsWith('/functions/v1/ai-session-evidence/enroll')) {
6
6
  throw new Error('Session enrollment requires a verified HTTPS session receiver URL');
7
7
  }
8
8
  if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw new Error('Invalid session enrollment token on stdin');
9
- if (!/^[A-Za-z0-9_-]{32,128}$/.test(completionToken ?? '')) throw new Error('Protected usage enrollment is required to match this laptop to its source');
9
+ if (!/^[A-Za-z0-9_-]{32,128}$/.test(installationCredential ?? '')) throw new Error('Protected installation credential is required to match this laptop to its source');
10
10
  if (!['preview', 'enroll'].includes(action) || typeof includeHistory !== 'boolean') throw new Error('Invalid capture options');
11
11
  let response;
12
12
  try {
13
13
  response = await request(url, { method: 'POST', redirect: 'error',
14
14
  headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
15
- body: JSON.stringify({ action, includeHistory, completionToken }), signal: AbortSignal.timeout(15_000) });
16
- } catch { throw new Error('Session receiver unavailable; existing usage capture is unchanged'); }
17
- if (response.status === 403) throw new Error('Session token belongs to a different source than this laptop. Issue the session token from the same Codex source as its usage token');
15
+ body: JSON.stringify({ action, includeHistory, installationCredential }), signal: AbortSignal.timeout(15_000) });
16
+ } catch { throw new Error('Session receiver unavailable; existing capture is unchanged'); }
17
+ if (response.status === 403) throw new Error('Session token belongs to a different source than this laptop. Use the session and installation credentials from the same device enrollment');
18
18
  if (!response.ok) throw new Error(`Session enrollment rejected (HTTP ${response.status}); check token expiry, capability and source approval`);
19
19
  let value;
20
20
  try { value = await response.json(); } catch { throw new Error('Invalid session enrollment response'); }
@@ -27,5 +27,5 @@ export async function configureSessionCapture({ endpoint, token, completionToken
27
27
  return { state: value.state, sourceId: value.sourceId, expiresAt: value.expiresAt,
28
28
  eligibleRecords: value.eligibleRecords, eligibleSessions: value.eligibleSessions,
29
29
  unresolvedRecords: value.unresolvedRecords, capturedRecords: value.capturedRecords,
30
- usageCredentialState: ['active', 'expired', 'revoked'].includes(value.usageCredentialState) ? value.usageCredentialState : 'unknown' };
30
+ bindingState: 'valid' };
31
31
  }
@@ -0,0 +1,51 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ import { atomicWrite, readJson } from './agent-telemetry.mjs';
5
+
6
+ // Never log a request body or token; pending requests stay in the protected file
7
+ // so a lost acknowledgement retries the same ID and cannot refresh health twice.
8
+ export async function checkInOnce(root, { request = fetch, makeId = randomUUID } = {}) {
9
+ const file=join(root,'telemetry-installation.json'), manifestFile=join(root,'install.json');
10
+ if ((statSync(file).mode & 0o077)!==0) throw new Error('Installation state must be private');
11
+ const binding=readJson(file), manifest=readJson(manifestFile);
12
+ if (!binding || !manifest?.deviceLink || manifest.deviceLinkPending || manifest.deviceLink.installationId!==binding.installationId ||
13
+ manifest.deviceLink.generation!==binding.generation || !Array.isArray(binding.capabilities)) throw new Error('Installation is not ready');
14
+ const base=new URL(binding.endpoint);
15
+ if ((base.protocol!=='https:' && !(base.protocol==='http:' && ['localhost','127.0.0.1','[::1]'].includes(base.hostname))) ||
16
+ base.username || base.password || base.search || base.hash || !/^[A-Za-z0-9_-]{32,128}$/.test(binding.token ?? '')) throw new Error('Invalid installation state');
17
+ const control=`${base.toString().replace(/\/$/,'')}/functions/v1/local-telemetry-device-link`;
18
+ const send=async (path,payload)=>{
19
+ try { return await request(`${control}${path}`,{method:'POST',redirect:'error',headers:{authorization:`Bearer ${binding.token}`,'content-type':'application/json'},body:JSON.stringify(payload),signal:AbortSignal.timeout(10_000)}); }
20
+ catch { throw new Error('Status service unavailable'); }
21
+ };
22
+ const save=()=>atomicWrite(file,JSON.stringify(binding)+'\n');
23
+ if (!binding.pendingCheckIn) {
24
+ let challenge=binding.challenge;
25
+ if (!challenge) {
26
+ const response=await send('/v1/status-challenge',{});
27
+ if (!response.ok) throw new Error('Status challenge unavailable');
28
+ const data=await response.json(); challenge=data?.challenge;
29
+ if (typeof challenge!=='string' || !/^[A-Za-z0-9_-]{32,128}$/.test(challenge)) throw new Error('Invalid status challenge');
30
+ }
31
+ const selected=binding.capabilities;
32
+ if (!selected.length || selected.length>3 || new Set(selected).size!==selected.length || selected.some(x=>!['usage','lineage','session'].includes(x))) throw new Error('Invalid installation state');
33
+ const forwarding=join(root,'akila-forwarding.env');
34
+ let env=''; try { if ((statSync(forwarding).mode & 0o077)===0) env=readFileSync(forwarding,'utf8'); } catch { /* no forwarding configured */ }
35
+ const incomplete=(selected.includes('usage') && !/^AKILA_CODEX_TOKEN=.+$/m.test(env)) || (selected.includes('lineage') && !/^AKILA_LINEAGE_TOKEN=.+$/m.test(env)) ||
36
+ (selected.includes('session') && manifest.akilaSessionCapture?.sourceId!==binding.sourceId);
37
+ binding.pendingCheckIn={checkInId:makeId(),challenge,reporterVersion:'0.1.4',tool:'codex',configuredCapabilities:selected,diagnostics:[incomplete?'local_config_incomplete':'local_ok']};
38
+ delete binding.challenge; save();
39
+ }
40
+ const response=await send('/v1/check-in',binding.pendingCheckIn);
41
+ if (response.status===204) { delete binding.pendingCheckIn; save(); return 'accepted'; }
42
+ // The server returns 401 for an expired challenge or revoked status bearer.
43
+ // Reacquire a challenge on the next attempt; a revoked bearer cannot refresh.
44
+ if (response.status===401) { delete binding.pendingCheckIn; save(); }
45
+ throw new Error('Status check-in unavailable');
46
+ }
47
+
48
+ export function retryDelay(failures, random = Math.random) {
49
+ const base=failures ? Math.min(5*60_000,30_000*2**Math.min(failures-1,5)) : 5*60_000;
50
+ return failures ? Math.min(5*60_000,Math.round(base*(0.9+0.2*random()))) : Math.round(base*(0.9+0.2*random()));
51
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akilium/telemetry-collector",
3
- "version": "0.1.4",
3
+ "version": "0.1.8",
4
4
  "description": "Akilium local OpenTelemetry Collector installer and diagnostic CLI",
5
5
  "type": "module",
6
6
  "engines": { "node": ">=22" },