@akilium/telemetry-collector 0.1.4 → 0.1.7
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 +11 -19
- package/bin/akilium-telemetry.mjs +274 -33
- package/bin/collector-launcher.mjs +4 -1
- package/bin/status-reporter.mjs +14 -0
- package/lib/agent-telemetry.mjs +3 -1
- package/lib/session-capture.mjs +7 -7
- package/lib/status-reporter.mjs +51 -0
- package/package.json +1 -1
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
|
-
|
|
15
|
+
An operator prepares a setup link in **Connections → Telemetry enrollment**. On the intended computer, use the endpoint from that link and paste the invitation at the hidden prompt:
|
|
16
16
|
|
|
17
17
|
```sh
|
|
18
|
-
|
|
18
|
+
akilium-telemetry login --endpoint https://YOUR_PROJECT.supabase.co --name "My laptop" --invite-stdin
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
The CLI
|
|
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
|
-
|
|
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
|
-
|
|
25
|
+
## Codex action attempts
|
|
32
26
|
|
|
33
|
-
|
|
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
|
-
|
|
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
|
|
38
|
+
## Session capture
|
|
47
39
|
|
|
48
|
-
|
|
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
|
-
|
|
42
|
+
Managed setup captures new completions only. It does not offer retained-history import; previously captured evidence remains governed and unchanged.
|
|
51
43
|
|
|
52
|
-
|
|
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.
|
|
@@ -44,7 +44,7 @@ function backupExisting(manifest) {
|
|
|
44
44
|
const folder = join(p.state, `platform-backup-${Date.now()}`);
|
|
45
45
|
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
46
46
|
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];
|
|
47
|
+
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
48
|
const saved = [];
|
|
49
49
|
for (const file of files) {
|
|
50
50
|
if (!existsSync(file)) continue;
|
|
@@ -86,6 +86,24 @@ function startService(mode) {
|
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
// Service managers can report a newly started process as activating for a
|
|
90
|
+
// short time. Wait for readiness before acknowledging the managed delivery.
|
|
91
|
+
async function waitForService(check) {
|
|
92
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
93
|
+
try { if (check()) return; } catch { /* service may still be starting */ }
|
|
94
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
95
|
+
}
|
|
96
|
+
throw new Error("Service did not start");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function waitForCollector(mode) {
|
|
100
|
+
await waitForService(() => mode === "docker"
|
|
101
|
+
? run("docker", ["compose", "-f", p.compose, "ps", "--status", "running", "--services"]).split(/\s+/).includes("collector")
|
|
102
|
+
: mode === "launchd"
|
|
103
|
+
? /state\s*=\s*running/.test(run("launchctl", ["print", `gui/${process.getuid()}/ai.akilium.agent-telemetry`]))
|
|
104
|
+
: run("systemctl", ["--user", "is-active", "akilium-agent-telemetry.service"]) === "active");
|
|
105
|
+
}
|
|
106
|
+
|
|
89
107
|
function launchdPlist() {
|
|
90
108
|
const xml = (value) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
91
109
|
const args = readJson(p.manifest)?.akilaCompletionForwarding
|
|
@@ -205,24 +223,239 @@ async function upgrade() {
|
|
|
205
223
|
await install(manifest.mode === "docker" ? "docker" : "native");
|
|
206
224
|
}
|
|
207
225
|
|
|
208
|
-
function
|
|
226
|
+
async function login() {
|
|
227
|
+
if (!args.includes("--invite-stdin")) throw new Error("Use login --invite-stdin with the setup link provided by your operator");
|
|
228
|
+
if (args.includes("--include-history")) throw new Error("Managed enrollment captures new completions only; retained history is not imported");
|
|
229
|
+
return await managedLogin();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function readInvitation() {
|
|
233
|
+
let value = "";
|
|
234
|
+
if (!process.stdin.isTTY) {
|
|
235
|
+
value = readFileSync(0, "utf8");
|
|
236
|
+
} else {
|
|
237
|
+
process.stderr.write("Paste the invitation and press Enter: ");
|
|
238
|
+
process.stdin.setRawMode(true);
|
|
239
|
+
process.stdin.resume();
|
|
240
|
+
try {
|
|
241
|
+
for await (const chunk of process.stdin) {
|
|
242
|
+
for (const ch of chunk.toString("utf8")) {
|
|
243
|
+
if (ch === "\u0003") throw new Error("Setup cancelled");
|
|
244
|
+
if (ch === "\r" || ch === "\n") return checkedInvitation(value);
|
|
245
|
+
if (ch === "\u007f" || ch === "\b") value = value.slice(0, -1);
|
|
246
|
+
else value += ch;
|
|
247
|
+
if (value.length > 256) throw new Error("Invalid invitation on stdin");
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
} finally {
|
|
251
|
+
process.stdin.setRawMode(false);
|
|
252
|
+
process.stdin.pause();
|
|
253
|
+
process.stderr.write("\n");
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return checkedInvitation(value);
|
|
257
|
+
}
|
|
258
|
+
function checkedInvitation(value) {
|
|
259
|
+
value = value.trim();
|
|
260
|
+
if (!/^[A-Za-z0-9_-]{32,128}$/.test(value)) throw new Error("Invalid invitation on stdin");
|
|
261
|
+
return value;
|
|
262
|
+
}
|
|
263
|
+
function validSecret(value) { return typeof value === "string" && /^[A-Za-z0-9_-]{32,128}$/.test(value); }
|
|
264
|
+
function validateManagedPayload(payload, origin) {
|
|
265
|
+
const id = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
266
|
+
const suffix = { usage: "/functions/v1/codex-usage-ingestion/v1/logs", lineage: "/functions/v1/codex-lineage-otel-ingestion", session: "/functions/v1/ai-session-evidence/enroll" };
|
|
267
|
+
if (!payload || !id.test(payload.installationId) || !id.test(payload.sourceId) || !Number.isSafeInteger(payload.generation) || payload.generation < 1 ||
|
|
268
|
+
!Array.isArray(payload.capabilities) || !payload.capabilities.length || payload.capabilities.length > 3 ||
|
|
269
|
+
new Set(payload.capabilities).size !== payload.capabilities.length || payload.capabilities.some(c => !(c in suffix)) ||
|
|
270
|
+
(payload.capabilities.includes('session') && !payload.capabilities.includes('usage')) ||
|
|
271
|
+
!validSecret(payload.statusCredential?.token) || !validSecret(payload.statusCredential?.challenge) ||
|
|
272
|
+
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");
|
|
273
|
+
for (const c of Object.keys(suffix)) {
|
|
274
|
+
const value = payload[c];
|
|
275
|
+
if (payload.capabilities.includes(c) !== Boolean(value)) throw new Error("Invalid device-link delivery");
|
|
276
|
+
if (value) {
|
|
277
|
+
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");
|
|
278
|
+
const url = new URL(value.endpoint);
|
|
279
|
+
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");
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
async function applyManagedPayload(payload, origin) {
|
|
284
|
+
validateManagedPayload(payload, origin);
|
|
285
|
+
let manifest = readJson(p.manifest);
|
|
286
|
+
const prior = manifest.deviceLink;
|
|
287
|
+
if (prior?.installationId && (prior.installationId !== payload.installationId || prior.sourceId !== payload.sourceId ||
|
|
288
|
+
!Number.isSafeInteger(prior.generation) || payload.generation <= prior.generation))
|
|
289
|
+
throw new Error("Delivery does not match the existing installation");
|
|
290
|
+
const usage = payload.capabilities.includes("usage"), lineage = payload.capabilities.includes("lineage");
|
|
291
|
+
const forwarding = usage || lineage;
|
|
292
|
+
const overlay = join(p.root, "akila-forwarding.yaml"), envFile = join(p.root, "akila-forwarding.env");
|
|
293
|
+
const compose = existsSync(p.compose) ? readFileSync(p.compose, "utf8") : "";
|
|
294
|
+
if (manifest.mode === "docker" && compose && ![renderCompose(p.root),renderCompose(p.root,true)].includes(compose))
|
|
295
|
+
throw new Error("Custom Compose configuration requires review before enrollment");
|
|
296
|
+
if (manifest.mode !== "docker") {
|
|
297
|
+
const service = serviceFile(manifest.mode), existing = existsSync(service) ? readFileSync(service, "utf8") : "";
|
|
298
|
+
if (existing && !(existing.includes("ai.akilium.agent-telemetry") || existing.includes("Description=Akilium local agent telemetry collector")))
|
|
299
|
+
throw new Error("Custom service configuration requires review before enrollment");
|
|
300
|
+
}
|
|
301
|
+
backupExisting(manifest);
|
|
302
|
+
const old = existsSync(envFile) ? readFileSync(envFile, "utf8").split("\n") : [];
|
|
303
|
+
const retained = old.filter(line => line && !/^AKILA_(INGESTION_ENDPOINT|CODEX_TOKEN|LINEAGE_ENDPOINT|LINEAGE_TOKEN)=/.test(line));
|
|
304
|
+
if (usage) retained.push(`AKILA_INGESTION_ENDPOINT=${payload.usage.endpoint}`, `AKILA_CODEX_TOKEN=${payload.usage.token}`);
|
|
305
|
+
if (lineage) retained.push(`AKILA_LINEAGE_ENDPOINT=${payload.lineage.endpoint}`, `AKILA_LINEAGE_TOKEN=${payload.lineage.token}`);
|
|
306
|
+
atomicWrite(envFile, retained.join("\n") + "\n");
|
|
307
|
+
if (forwarding) atomicWrite(overlay, renderAkilaForwarding(option("--mapping", "v1"), lineage, usage));
|
|
308
|
+
manifest.akilaCompletionForwarding = forwarding;
|
|
309
|
+
manifest.akilaLineageForwarding = lineage;
|
|
310
|
+
saveManifest(manifest);
|
|
311
|
+
if (manifest.mode === "docker") atomicWrite(p.compose, renderCompose(p.root,forwarding));
|
|
312
|
+
else atomicWrite(serviceFile(manifest.mode), manifest.mode === "launchd" ? launchdPlist() : systemdUnit(), 0o644);
|
|
313
|
+
const binding = { endpoint: origin, installationId: payload.installationId, sourceId: payload.sourceId, generation: payload.generation,
|
|
314
|
+
token: payload.statusCredential.token, challenge: payload.statusCredential.challenge, expiresAt: payload.statusCredential.expiresAt, capabilities: payload.capabilities };
|
|
315
|
+
atomicWrite(join(p.root,"telemetry-installation.json"),JSON.stringify(binding) + "\n");
|
|
316
|
+
if (payload.session) await enrollSessions(false,payload.session.token,payload.session.endpoint,binding);
|
|
317
|
+
manifest = readJson(p.manifest);
|
|
318
|
+
try {
|
|
319
|
+
if (manifest.mode === "docker") run("docker", ["compose", "-f", p.compose, "config", "--quiet"]);
|
|
320
|
+
else run(p.binary, ["validate", `--config=${p.config}`, ...(forwarding ? [`--config=${overlay}`] : [])]);
|
|
321
|
+
stopService(manifest.mode);
|
|
322
|
+
startService(manifest.mode);
|
|
323
|
+
await waitForCollector(manifest.mode);
|
|
324
|
+
await startStatusReporter();
|
|
325
|
+
} catch { throw new Error("Collector or status service could not start; setup remains pending"); }
|
|
326
|
+
}
|
|
327
|
+
function statusServiceFile() {
|
|
328
|
+
if (platform() === "darwin") return join(home,"Library","LaunchAgents","ai.akilium.telemetry-status.plist");
|
|
329
|
+
if (platform() === "linux") return join(home,".config","systemd","user","akilium-telemetry-status.service");
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
async function startStatusReporter() {
|
|
333
|
+
const worker = fileURLToPath(new URL("./status-reporter.mjs", import.meta.url));
|
|
334
|
+
if (platform() === "darwin") {
|
|
335
|
+
const target = join(home, "Library", "LaunchAgents", "ai.akilium.telemetry-status.plist");
|
|
336
|
+
const xml = value => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
337
|
+
const existing = existsSync(target) ? readFileSync(target,"utf8") : "";
|
|
338
|
+
if (existing && !existing.includes("ai.akilium.telemetry-status")) throw new Error("Status service requires review");
|
|
339
|
+
const args=[process.execPath,worker];
|
|
340
|
+
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);
|
|
341
|
+
run("launchctl",["bootout",`gui/${process.getuid()}`,target],true);
|
|
342
|
+
run("launchctl",["bootstrap",`gui/${process.getuid()}`,target]);
|
|
343
|
+
await waitForService(() => /state\s*=\s*running/.test(run("launchctl",["print",`gui/${process.getuid()}/ai.akilium.telemetry-status`])));
|
|
344
|
+
} else if (platform() === "linux") {
|
|
345
|
+
const target=join(home,".config","systemd","user","akilium-telemetry-status.service");
|
|
346
|
+
if ([process.execPath,worker,home].some(x=>/[\n\r%"\\]/.test(x))) throw new Error("Unsafe status service path");
|
|
347
|
+
const existing=existsSync(target)?readFileSync(target,"utf8"):"";
|
|
348
|
+
if (existing && !existing.includes("Description=Akilium telemetry status reporter")) throw new Error("Status service requires review");
|
|
349
|
+
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);
|
|
350
|
+
run("systemctl",["--user","daemon-reload"]);
|
|
351
|
+
run("systemctl",["--user","enable","--now","akilium-telemetry-status.service"]);
|
|
352
|
+
run("systemctl",["--user","restart","akilium-telemetry-status.service"]);
|
|
353
|
+
await waitForService(() => run("systemctl",["--user","is-active","akilium-telemetry-status.service"]) === "active");
|
|
354
|
+
} else throw new Error("Status service is unavailable on this platform");
|
|
355
|
+
}
|
|
356
|
+
function stopStatusReporter() {
|
|
357
|
+
if (platform() === "darwin") {
|
|
358
|
+
const target=join(home,"Library","LaunchAgents","ai.akilium.telemetry-status.plist");
|
|
359
|
+
if (existsSync(target) && readFileSync(target,"utf8").includes("ai.akilium.telemetry-status")) {
|
|
360
|
+
run("launchctl",["bootout",`gui/${process.getuid()}`,target],true); rmSync(target,{force:true});
|
|
361
|
+
}
|
|
362
|
+
} else if (platform() === "linux") {
|
|
363
|
+
const target=join(home,".config","systemd","user","akilium-telemetry-status.service");
|
|
364
|
+
if (existsSync(target) && readFileSync(target,"utf8").includes("Description=Akilium telemetry status reporter")) {
|
|
365
|
+
run("systemctl",["--user","disable","--now","akilium-telemetry-status.service"],true); rmSync(target,{force:true});
|
|
366
|
+
run("systemctl",["--user","daemon-reload"],true);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
async function managedLogin() {
|
|
371
|
+
let manifest = readJson(p.manifest);
|
|
372
|
+
if (!manifest) throw new Error("Install or migrate the collector first");
|
|
373
|
+
let started = manifest.deviceLinkPending;
|
|
374
|
+
if (started && started.version !== 2) throw new Error("An incompatible device-link request is pending until it expires");
|
|
375
|
+
const endpoint = option("--endpoint", started?.endpoint || manifest.deviceLink?.endpoint);
|
|
376
|
+
if (!endpoint) throw new Error("--endpoint is required the first time you link this collector");
|
|
377
|
+
const base = new URL(endpoint);
|
|
378
|
+
if ((base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname))) || base.username || base.password || base.search || base.hash)
|
|
379
|
+
throw new Error("Device-link endpoint must be a verified HTTPS Supabase URL");
|
|
380
|
+
const origin = base.toString().replace(/\/$/, ""), control = `${origin}/functions/v1/local-telemetry-device-link`;
|
|
381
|
+
if (started && started.endpoint !== origin) throw new Error("A different device-link request is pending");
|
|
382
|
+
if (started && (!started.expiresAt || Date.parse(started.expiresAt) <= Date.now())) {
|
|
383
|
+
delete manifest.deviceLinkPending; saveManifest(manifest); started = null;
|
|
384
|
+
}
|
|
385
|
+
// Back up the prior installation before writing a new request or its proof.
|
|
386
|
+
if (!started) { backupExisting(manifest); manifest = readJson(p.manifest); }
|
|
387
|
+
const post = async (path,value) => {
|
|
388
|
+
let response;
|
|
389
|
+
try { response = await fetch(`${control}${path}`, { method:"POST", headers:{"content-type":"application/json"}, body:JSON.stringify(value), redirect:"error", signal:AbortSignal.timeout(15_000) }); }
|
|
390
|
+
catch { throw new Error("Device-link service is unavailable"); }
|
|
391
|
+
if (!response.ok) throw new Error("Device-link service is unavailable");
|
|
392
|
+
return response.status === 204 ? null : await response.json();
|
|
393
|
+
};
|
|
394
|
+
if (!started || !started.expiresAt || Date.parse(started.expiresAt) <= Date.now()) {
|
|
395
|
+
const machineName = option("--name", process.env.HOSTNAME || "local collector");
|
|
396
|
+
const created = await post("/start", {machineName,collectorVersion:"0.1.4"});
|
|
397
|
+
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)))
|
|
398
|
+
throw new Error("Invalid device-link response");
|
|
399
|
+
started = {...created, endpoint:origin, machineName, version:2, claimed:false};
|
|
400
|
+
manifest.deviceLinkPending = started; saveManifest(manifest);
|
|
401
|
+
}
|
|
402
|
+
if (!started.claimed) {
|
|
403
|
+
const invitation = await readInvitation();
|
|
404
|
+
await post("/v2/claim", {requestId:started.requestId,pollSecret:started.pollSecret,invitation});
|
|
405
|
+
started.claimed = true; manifest.deviceLinkPending = started; saveManifest(manifest);
|
|
406
|
+
}
|
|
407
|
+
if (started.applied) {
|
|
408
|
+
try { await waitForCollector(manifest.mode); await startStatusReporter(); } catch { throw new Error("Collector or status service could not start; setup remains pending"); }
|
|
409
|
+
await post("/v2/acknowledge", {requestId:started.requestId,pollSecret:started.pollSecret,deliveryId:started.applied.deliveryId,generation:started.applied.generation});
|
|
410
|
+
} else {
|
|
411
|
+
console.log(`Akila access code: ${started.code}`);
|
|
412
|
+
console.log("Ask your operator to compare this code and approve this device in Connections.");
|
|
413
|
+
let approved;
|
|
414
|
+
while (Date.now() < Date.parse(started.expiresAt)) {
|
|
415
|
+
await new Promise(resolve => setTimeout(resolve,5000));
|
|
416
|
+
const result = await post("/v2/poll", {requestId:started.requestId,pollSecret:started.pollSecret});
|
|
417
|
+
if (result?.status === "pending") continue;
|
|
418
|
+
if (result?.status === "approved" && result.payload && typeof result.deliveryId === "string") { approved=result; break; }
|
|
419
|
+
throw new Error("Device-link request was denied, revoked, or expired");
|
|
420
|
+
}
|
|
421
|
+
if (!approved) throw new Error("Device-link request expired before approval");
|
|
422
|
+
await applyManagedPayload(approved.payload,origin);
|
|
423
|
+
manifest=readJson(p.manifest); started=manifest.deviceLinkPending;
|
|
424
|
+
started.applied={deliveryId:approved.deliveryId,generation:approved.payload.generation};
|
|
425
|
+
manifest.deviceLinkPending=started; saveManifest(manifest);
|
|
426
|
+
await post("/v2/acknowledge", {requestId:started.requestId,pollSecret:started.pollSecret,deliveryId:started.applied.deliveryId,generation:started.applied.generation});
|
|
427
|
+
}
|
|
428
|
+
manifest=readJson(p.manifest);
|
|
429
|
+
const binding=readJson(join(p.root,"telemetry-installation.json"));
|
|
430
|
+
manifest.deviceLink={endpoint:origin,machineName:started.machineName,installationId:binding.installationId,sourceId:binding.sourceId,generation:binding.generation,linkedAt:new Date().toISOString()};
|
|
431
|
+
delete manifest.deviceLinkPending; saveManifest(manifest);
|
|
432
|
+
console.log("Akila local collector linked. No enrollment credential was displayed.");
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async function rollback() {
|
|
209
436
|
const manifest = readJson(p.manifest);
|
|
210
437
|
if (!manifest?.migrationBackup) throw new Error("No platform migration backup is recorded");
|
|
211
438
|
const folder = manifest.migrationBackup;
|
|
212
439
|
const saved = readJson(join(folder, "index.json"));
|
|
213
440
|
if (!Array.isArray(saved)) throw new Error("Migration backup index is missing");
|
|
214
441
|
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]);
|
|
442
|
+
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
443
|
if (saved.some((entry) => !allowed.has(entry.path) || dirname(entry.backup) !== folder ||
|
|
217
444
|
!existsSync(entry.backup))) throw new Error("Migration backup index is invalid");
|
|
218
445
|
stopService(manifest.mode);
|
|
446
|
+
stopStatusReporter();
|
|
219
447
|
for (const entry of saved) {
|
|
220
448
|
mkdirSync(dirname(entry.path), { recursive: true, mode: 0o700 });
|
|
221
449
|
copyFileSync(entry.backup, entry.path);
|
|
222
450
|
chmodSync(entry.path, entry.mode);
|
|
223
451
|
}
|
|
452
|
+
const savedPaths = new Set(saved.map(entry => entry.path));
|
|
453
|
+
for (const file of [join(p.root, "akila-forwarding.yaml"), join(p.root, "akila-forwarding.env"), join(p.root, "telemetry-installation.json")]) {
|
|
454
|
+
if (!savedPaths.has(file)) rmSync(file, { force: true });
|
|
455
|
+
}
|
|
224
456
|
const restored = readJson(p.manifest);
|
|
225
457
|
if (restored?.mode) startService(restored.mode);
|
|
458
|
+
if (restored?.deviceLink?.installationId && statusServiceFile() && savedPaths.has(statusServiceFile())) await startStatusReporter();
|
|
226
459
|
console.log("Previous collector configuration restored from the protected backup");
|
|
227
460
|
}
|
|
228
461
|
|
|
@@ -233,15 +466,15 @@ function migrate() {
|
|
|
233
466
|
console.log(`Existing configuration backed up at ${folder}; collector and agents were not restarted`);
|
|
234
467
|
}
|
|
235
468
|
|
|
236
|
-
function enroll() {
|
|
469
|
+
function enroll(tokenOverride = null, endpointOverride = null) {
|
|
237
470
|
const manifest = readJson(p.manifest);
|
|
238
471
|
if (!manifest) throw new Error("Install or migrate the collector first");
|
|
239
|
-
const endpoint = option("--endpoint");
|
|
472
|
+
const endpoint = endpointOverride || option("--endpoint");
|
|
240
473
|
const mappingVersion = option("--mapping", "v1");
|
|
241
474
|
if (!["v1", "v2"].includes(mappingVersion)) throw new Error("--mapping must be v1 or v2");
|
|
242
475
|
if (!endpoint) throw new Error("--endpoint is required");
|
|
243
476
|
const url = new URL(endpoint);
|
|
244
|
-
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash ||
|
|
477
|
+
if ((url.protocol !== "https:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) || url.username || url.password || url.search || url.hash ||
|
|
245
478
|
!url.pathname.endsWith("/functions/v1/codex-usage-ingestion/v1/logs")) {
|
|
246
479
|
throw new Error("Enrollment requires a verified HTTPS Codex completion receiver URL");
|
|
247
480
|
}
|
|
@@ -261,7 +494,7 @@ function enroll() {
|
|
|
261
494
|
throw new Error("Native service file has custom content; review it before enrollment");
|
|
262
495
|
}
|
|
263
496
|
}
|
|
264
|
-
const token = readFileSync(0, "utf8").trim();
|
|
497
|
+
const token = tokenOverride || readFileSync(0, "utf8").trim();
|
|
265
498
|
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw new Error("Invalid enrollment token on stdin");
|
|
266
499
|
backupExisting(manifest);
|
|
267
500
|
const previous = existsSync(envFile) ? readFileSync(envFile, "utf8").split("\n") : [];
|
|
@@ -283,13 +516,13 @@ function enroll() {
|
|
|
283
516
|
console.log("Protected completion forwarding configured; restart the collector and check hosted acceptance");
|
|
284
517
|
}
|
|
285
518
|
|
|
286
|
-
function enrollLineage() {
|
|
519
|
+
function enrollLineage(tokenOverride = null, endpointOverride = null) {
|
|
287
520
|
const manifest = readJson(p.manifest);
|
|
288
521
|
if (!manifest) throw new Error("Install or migrate the collector first");
|
|
289
|
-
const endpoint = option("--endpoint");
|
|
522
|
+
const endpoint = endpointOverride || option("--endpoint");
|
|
290
523
|
if (!endpoint) throw new Error("--endpoint is required");
|
|
291
524
|
const url = new URL(endpoint);
|
|
292
|
-
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash ||
|
|
525
|
+
if ((url.protocol !== "https:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) || url.username || url.password || url.search || url.hash ||
|
|
293
526
|
!url.pathname.endsWith("/functions/v1/codex-lineage-otel-ingestion")) {
|
|
294
527
|
throw new Error("Enrollment requires a verified HTTPS Codex lineage OTel receiver URL");
|
|
295
528
|
}
|
|
@@ -298,7 +531,7 @@ function enrollLineage() {
|
|
|
298
531
|
if (!existsSync(envFile) || !existsSync(overlay)) throw new Error("Configure completion forwarding before lineage forwarding");
|
|
299
532
|
const lines = readFileSync(envFile, "utf8").split("\n");
|
|
300
533
|
if (!lines.some((line) => line.startsWith("AKILA_CODEX_TOKEN="))) throw new Error("Completion forwarding enrollment is incomplete");
|
|
301
|
-
const token = readFileSync(0, "utf8").trim();
|
|
534
|
+
const token = tokenOverride || readFileSync(0, "utf8").trim();
|
|
302
535
|
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw new Error("Invalid lineage enrollment token on stdin");
|
|
303
536
|
const oldConfig = readFileSync(overlay, "utf8");
|
|
304
537
|
const mappingVersion = oldConfig.includes('"user.account_id"') ? "v2" : "v1";
|
|
@@ -314,29 +547,29 @@ function enrollLineage() {
|
|
|
314
547
|
if (manifest.mode === "docker") console.log(`Run: docker compose -f "${join(p.root, "compose.yaml")}" up -d --force-recreate collector`);
|
|
315
548
|
}
|
|
316
549
|
|
|
317
|
-
async function enrollSessions(previewOnly = false) {
|
|
550
|
+
async function enrollSessions(previewOnly = false, tokenOverride = null, endpointOverride = null, bindingOverride = null) {
|
|
318
551
|
const manifest = readJson(p.manifest);
|
|
319
552
|
if (!manifest) throw new Error("Install or migrate the collector first");
|
|
320
|
-
const
|
|
321
|
-
if (!existsSync(
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
const endpoint = option("--endpoint");
|
|
325
|
-
if (!endpoint
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
const
|
|
329
|
-
const
|
|
330
|
-
const preview = await configureSessionCapture({ endpoint, token, completionToken, action: "preview" });
|
|
553
|
+
const bindingFile = join(p.root, "telemetry-installation.json");
|
|
554
|
+
if (!bindingOverride && (!existsSync(bindingFile) || (statSync(bindingFile).mode & 0o077) !== 0))
|
|
555
|
+
throw new Error("Protected installation enrollment is required");
|
|
556
|
+
const binding = bindingOverride || readJson(bindingFile);
|
|
557
|
+
const endpoint = endpointOverride || option("--endpoint");
|
|
558
|
+
if (!endpoint || !binding?.endpoint || new URL(binding.endpoint).origin !== new URL(endpoint).origin)
|
|
559
|
+
throw new Error("Session and installation endpoints must use the same project");
|
|
560
|
+
const token = tokenOverride || readFileSync(0, "utf8").trim();
|
|
561
|
+
const installationCredential = binding.token;
|
|
562
|
+
const preview = await configureSessionCapture({ endpoint, token, installationCredential, action: "preview" });
|
|
331
563
|
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
564
|
if (previewOnly) { console.log("Preview only; no capture settings or session data changed."); return; }
|
|
334
|
-
|
|
335
|
-
|
|
565
|
+
// Managed enrollment starts with new completions; reconnect never imports
|
|
566
|
+
// retained history implicitly.
|
|
567
|
+
const includeHistory = false;
|
|
568
|
+
const result = await configureSessionCapture({ endpoint, token, installationCredential, action: "enroll", includeHistory });
|
|
569
|
+
if (binding.sourceId && result.sourceId !== binding.sourceId) throw new Error("Session source does not match this installation");
|
|
336
570
|
manifest.akilaSessionCapture = { endpoint, sourceId: result.sourceId, expiresAt: result.expiresAt, includeHistory };
|
|
337
571
|
saveManifest(manifest);
|
|
338
572
|
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
573
|
}
|
|
341
574
|
|
|
342
575
|
function setDestination() {
|
|
@@ -401,7 +634,15 @@ function status() {
|
|
|
401
634
|
else console.log(`Service: ${run("launchctl", ["list", "ai.akilium.agent-telemetry"], true) ? "loaded" : "inactive"}`);
|
|
402
635
|
if (manifest.akilaSessionCapture) {
|
|
403
636
|
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 (
|
|
637
|
+
} else console.log("Session capture: not enrolled on this installation (approve session capture through Telemetry enrollment)");
|
|
638
|
+
if (manifest.deviceLink?.installationId) {
|
|
639
|
+
const statusFile=join(p.root,"telemetry-installation.json");
|
|
640
|
+
const privateState=existsSync(statusFile) && (statSync(statusFile).mode & 0o077)===0;
|
|
641
|
+
const service=platform()==="darwin" ? (run("launchctl",["list","ai.akilium.telemetry-status"],true) ? "loaded" : "inactive") :
|
|
642
|
+
platform()==="linux" ? (run("systemctl",["--user","is-active","akilium-telemetry-status.service"],true) || "inactive") : "unavailable";
|
|
643
|
+
console.log(`Status reporter: ${service}; local state ${privateState ? "protected" : "unavailable or unprotected"}`);
|
|
644
|
+
if (manifest.deviceLinkPending) console.log("Device setup: awaiting local completion or acknowledgement");
|
|
645
|
+
}
|
|
405
646
|
console.log("Hosted receipt: unknown (inspect Akila connection health)");
|
|
406
647
|
console.log("Normalization: unknown (inspect Akila worker/inbox health)");
|
|
407
648
|
console.log("Artifact linkage: unknown (inspect authorized event and artifact views)");
|
|
@@ -430,6 +671,7 @@ function uninstall() {
|
|
|
430
671
|
const manifest = readJson(p.manifest);
|
|
431
672
|
if (!manifest) throw new Error("Collector is not installed");
|
|
432
673
|
stopService(manifest.mode);
|
|
674
|
+
stopStatusReporter();
|
|
433
675
|
if (manifest.codexManaged && existsSync(p.codex)) {
|
|
434
676
|
const restored = restoreCodexTelemetry(readFileSync(p.codex, "utf8"));
|
|
435
677
|
if (restored !== null) {
|
|
@@ -452,17 +694,16 @@ try {
|
|
|
452
694
|
if (action === "install") await install();
|
|
453
695
|
else if (action === "migrate") migrate();
|
|
454
696
|
else if (action === "upgrade") await upgrade();
|
|
455
|
-
else if (action === "
|
|
697
|
+
else if (action === "login") await login();
|
|
698
|
+
else if (action === "rollback") await rollback();
|
|
456
699
|
else if (action === "enroll") enroll();
|
|
457
700
|
else if (action === "enroll-lineage") enrollLineage();
|
|
458
|
-
else if (action === "enroll-sessions") await enrollSessions();
|
|
459
|
-
else if (action === "preview-sessions") await enrollSessions(true);
|
|
460
701
|
else if (action === "configure") installAgents(readJson(p.manifest) || (() => { throw new Error("Install the collector first"); })());
|
|
461
702
|
else if (action === "set-destination") setDestination();
|
|
462
|
-
else if (action === "status") status();
|
|
703
|
+
else if (action === "status") { status(); if (args.includes("--repair")) { await startStatusReporter(); console.log("Status reporting restarted."); } }
|
|
463
704
|
else if (action === "doctor") await doctor();
|
|
464
705
|
else if (action === "uninstall") uninstall();
|
|
465
|
-
else if (action === "help") console.log("Usage: akilium-telemetry <install|migrate|enroll|enroll-lineage|
|
|
706
|
+
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
707
|
else throw new Error(`Unknown action: ${action}`);
|
|
467
708
|
} catch (error) {
|
|
468
709
|
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
|
-
|
|
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();
|
package/lib/agent-telemetry.mjs
CHANGED
|
@@ -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
|
|
package/lib/session-capture.mjs
CHANGED
|
@@ -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,
|
|
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(
|
|
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,
|
|
16
|
-
} catch { throw new Error('Session receiver unavailable; existing
|
|
17
|
-
if (response.status === 403) throw new Error('Session token belongs to a different source than this laptop.
|
|
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
|
-
|
|
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
|
+
}
|