@akilium/telemetry-collector 0.1.10 → 0.1.11

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.
Files changed (32) hide show
  1. package/README.md +22 -1
  2. package/bin/akilium-telemetry.mjs +0 -0
  3. package/dist/instrumentation/src/client.d.ts +77 -0
  4. package/dist/instrumentation/src/client.js +237 -0
  5. package/dist/instrumentation/src/codex-cli.d.ts +20 -0
  6. package/dist/instrumentation/src/codex-cli.js +92 -0
  7. package/dist/instrumentation/src/codex-execution.d.ts +27 -0
  8. package/dist/instrumentation/src/codex-execution.js +123 -0
  9. package/dist/instrumentation/src/index.d.ts +11 -0
  10. package/dist/instrumentation/src/index.js +11 -0
  11. package/dist/instrumentation/src/persisted-file.d.ts +18 -0
  12. package/dist/instrumentation/src/persisted-file.js +65 -0
  13. package/dist/instrumentation/src/posting-wrappers.d.ts +49 -0
  14. package/dist/instrumentation/src/posting-wrappers.js +76 -0
  15. package/dist/instrumentation/src/wrappers.d.ts +68 -0
  16. package/dist/instrumentation/src/wrappers.js +76 -0
  17. package/dist/integration-contracts/src/action-lineage.d.ts +120 -0
  18. package/dist/integration-contracts/src/action-lineage.js +208 -0
  19. package/dist/integration-contracts/src/activity-classification.d.ts +251 -0
  20. package/dist/integration-contracts/src/activity-classification.js +406 -0
  21. package/dist/integration-contracts/src/ai-execution.d.ts +62 -0
  22. package/dist/integration-contracts/src/ai-execution.js +244 -0
  23. package/dist/integration-contracts/src/ai-session.d.ts +282 -0
  24. package/dist/integration-contracts/src/ai-session.js +192 -0
  25. package/dist/integration-contracts/src/artifact-lineage.d.ts +140 -0
  26. package/dist/integration-contracts/src/artifact-lineage.js +236 -0
  27. package/dist/integration-contracts/src/lineage-validation.d.ts +14 -0
  28. package/dist/integration-contracts/src/lineage-validation.js +64 -0
  29. package/dist/integration-contracts/src/posting-lineage.d.ts +105 -0
  30. package/dist/integration-contracts/src/posting-lineage.js +147 -0
  31. package/lib/execution-capture.mjs +1 -1
  32. package/package.json +16 -25
package/README.md CHANGED
@@ -4,9 +4,30 @@ Platform-owned installer for the local OpenTelemetry Collector. The package pres
4
4
 
5
5
  This package migrates the reviewed operations installer into the Akila platform monorepo. A rendered local config does not establish hosted acceptance or artifact linkage.
6
6
 
7
+ ## Instrumentation SDK
8
+
9
+ The package also exports the instrumentation SDK and its TypeScript declarations
10
+ at `@akilium/telemetry-collector/instrumentation`. Install the combined package
11
+ and update existing SDK imports from `@akilium/instrumentation`:
12
+
13
+ ```sh
14
+ npm install @akilium/telemetry-collector
15
+ ```
16
+
17
+ ```js
18
+ import { createInstrumentation } from "@akilium/telemetry-collector/instrumentation";
19
+ ```
20
+
21
+ The SDK reporting API and receiver contracts remain unchanged. The combined
22
+ package requires Node.js `>=22.13` for both the CLI and SDK entry points.
23
+ Previously published `@akilium/instrumentation` versions remain available, but
24
+ new releases are distributed through the combined package; no temporary
25
+ compatibility release is planned. Existing installations can continue using
26
+ their pinned published version while migrating their dependency and import.
27
+
7
28
  ## Supported paths and migration
8
29
 
9
- Node.js 22 or newer is required for the CLI. Native installation supports macOS launchd and Linux user systemd with pinned Collector Contrib `0.161.0`; Docker installation uses the matching image and local loopback ports 4317 and 4318. The Codex JSONL action adapter remains version-limited to CLI `0.160.0`. The separate execution instrumentation adapter supports Codex CLI `0.166.0` `exec --json` command-item metadata only. It uses native thread/item IDs and status; turn IDs, request IDs, and source timestamps are unavailable. The background OpenTelemetry Collector remains completion-only and does not imply interactive-session execution coverage.
30
+ Node.js `>=22.13` is required for the CLI. Native installation supports macOS launchd and Linux user systemd with pinned Collector Contrib `0.161.0`; Docker installation uses the matching image and local loopback ports 4317 and 4318. The Codex JSONL action adapter remains version-limited to CLI `0.160.0`. The separate execution instrumentation adapter supports Codex CLI `0.166.0` `exec --json` command-item metadata only. It uses native thread/item IDs and status; turn IDs, request IDs, and source timestamps are unavailable. The background OpenTelemetry Collector remains completion-only and does not imply interactive-session execution coverage.
10
31
 
11
32
  Before changing an existing operations-managed installation, run `akilium-telemetry migrate`. It writes a mode-0700 backup folder under the collector state directory, with mode-0600 copies of the manifest, configuration, existing Akila forwarding overlay and environment file, service definition, binary, and agent settings. Existing collector and Compose files are retained on reinstall; custom pipeline files are never rewritten by `set-destination`. Run `akilium-telemetry rollback` to restore the backup, or `upgrade` to install the pinned Collector version while retaining custom Compose content. `uninstall` stops the managed service and removes only managed agent telemetry settings; local archives, state, and forwarding files remain for review.
12
33
 
File without changes
@@ -0,0 +1,77 @@
1
+ import { type ActionArtifactResultV1, type ActionArtifactResultV1_1, type ActionCorrelationV1, type ActionExecutionStatus, type ActionLineageEnvelopeV1 } from "../../integration-contracts/src/action-lineage.ts";
2
+ import { type ActivityPurposeReportV1, type ActivityPurposeDeclarationV1, type ActivityWorkContextMembershipV1, type ActivityEphemeralOutputV1, type ActivityNoOutputAssertionV1 } from "../../integration-contracts/src/activity-classification.ts";
3
+ import type { LineageAuthorityV1 } from "../../integration-contracts/src/artifact-lineage.ts";
4
+ import { type PostingActionEnvelopeV1_2 } from "../../integration-contracts/src/posting-lineage.ts";
5
+ export type ReportOutcome = {
6
+ status: "accepted";
7
+ accepted: number;
8
+ duplicates: number;
9
+ } | {
10
+ status: "unavailable" | "rejected";
11
+ httpStatus: number | null;
12
+ };
13
+ export interface InstrumentationOptions {
14
+ /** Complete versioned receiver URL. Use HTTPS outside a local Supabase instance. */
15
+ endpoint: string;
16
+ /** Protected lineage enrollment credential. Never put this in browser code. */
17
+ token: string;
18
+ /** Origins approved on the enrolled source for persisted HTTPS locators. */
19
+ approvedLocatorOrigins?: readonly string[];
20
+ /** Bounded in-memory retry queue; defaults to 128 reports and one hour. */
21
+ maxPendingReports?: number;
22
+ maxReportAgeMs?: number;
23
+ /** Enable only with an enrollment carrying artifact_presentation_v1. */
24
+ artifactPresentationEnabled?: boolean;
25
+ retryBaseMs?: number;
26
+ now?: () => number;
27
+ fetch?: typeof globalThis.fetch;
28
+ /** Public source binding used only for local contract validation; the receiver rebinds it from the enrollment token. */
29
+ activityAuthority?: LineageAuthorityV1;
30
+ activityCapabilities?: readonly string[];
31
+ /** Enable only with an enrollment issued for posting_lineage_v1. */
32
+ postingLineageEnabled?: boolean;
33
+ postingAuthority?: LineageAuthorityV1;
34
+ postingCapabilities?: readonly string[];
35
+ }
36
+ export type PostingReportInput = Omit<PostingActionEnvelopeV1_2, "contractVersion" | "reportId" | "phase">;
37
+ export type ActivityReportInput = Pick<ActivityPurposeReportV1, "actionId" | "attemptId"> & {
38
+ purpose?: ActivityPurposeDeclarationV1 | null;
39
+ membership?: ActivityWorkContextMembershipV1 | null;
40
+ outputs?: ActivityEphemeralOutputV1[];
41
+ noOutput?: ActivityNoOutputAssertionV1 | null;
42
+ };
43
+ export interface ExportStatus {
44
+ queued: number;
45
+ accepted: number;
46
+ duplicates: number;
47
+ rejected: number;
48
+ dropped: number;
49
+ unavailable: number;
50
+ gapPending: boolean;
51
+ gapAccepted: number;
52
+ }
53
+ export interface ActionStart {
54
+ actionId?: string;
55
+ attemptId?: string;
56
+ toolKind: ActionLineageEnvelopeV1["metadata"]["toolKind"];
57
+ correlation?: Partial<ActionCorrelationV1>;
58
+ startedAt?: string;
59
+ }
60
+ export interface ActionSession {
61
+ readonly actionId: string;
62
+ readonly attemptId: string;
63
+ readonly startedAt: string;
64
+ start(): Promise<ReportOutcome>;
65
+ result(artifacts: ActionArtifactResultV1[], status?: ActionExecutionStatus): Promise<ReportOutcome>;
66
+ resultEnhanced(artifacts: ActionArtifactResultV1_1[], status?: ActionExecutionStatus): Promise<ReportOutcome>;
67
+ complete(status: Exclude<ActionExecutionStatus, "in_progress">, exitCode?: number | null): Promise<ReportOutcome>;
68
+ }
69
+ export declare function createInstrumentation(options: InstrumentationOptions): {
70
+ reportEnvelope: (envelope: ActionLineageEnvelopeV1) => Promise<ReportOutcome>;
71
+ reportActivity: (input: ActivityReportInput) => Promise<ReportOutcome>;
72
+ reportPosting: (input: PostingReportInput) => Promise<ReportOutcome>;
73
+ reportCollectionGap: (gapStart: string, gapEnd: string) => Promise<ReportOutcome>;
74
+ action: (input: ActionStart) => ActionSession;
75
+ flush: () => Promise<ExportStatus>;
76
+ status: () => ExportStatus;
77
+ };
@@ -0,0 +1,237 @@
1
+ import { ACTION_LINEAGE_CONTRACT_VERSION, ACTION_LINEAGE_LIMITS, ACTION_LINEAGE_ENHANCED_CONTRACT_VERSION, parseActionLineageEnvelopeV1_1, parseActionCollectionGap, parseActionLineageEnvelope, } from "../../integration-contracts/src/action-lineage.js";
2
+ import { ACTIVITY_CLASSIFICATION_CONTRACT_VERSION, parseActivityPurposeReport, } from "../../integration-contracts/src/activity-classification.js";
3
+ import { bindPostingActionEnvelopeV1_2, POSTING_LINEAGE_CAPABILITY, POSTING_LINEAGE_CONTRACT_VERSION, } from "../../integration-contracts/src/posting-lineage.js";
4
+ const emptyCorrelation = {
5
+ namespace: "explicit-sdk-v1", runId: null, sessionId: null, parentRunId: null,
6
+ toolCallId: null, completionReference: null,
7
+ };
8
+ export function createInstrumentation(options) {
9
+ const url = new URL(options.endpoint);
10
+ if (url.protocol !== "https:" && !(url.protocol === "http:" &&
11
+ ["localhost", "127.0.0.1", "::1"].includes(url.hostname))) {
12
+ throw new Error("Lineage endpoint must use HTTPS");
13
+ }
14
+ if (!/^[A-Za-z0-9_-]{32,128}$/.test(options.token))
15
+ throw new Error("Invalid lineage enrollment token");
16
+ const request = options.fetch ?? globalThis.fetch;
17
+ const maxPending = options.maxPendingReports ?? 128;
18
+ const maxAge = options.maxReportAgeMs ?? 3_600_000;
19
+ const retryBase = options.retryBaseMs ?? 1_000;
20
+ if (!Number.isSafeInteger(maxPending) || maxPending < 0 || maxPending > 10_000 ||
21
+ !Number.isSafeInteger(maxAge) || maxAge < 1_000 || maxAge > 86_400_000 ||
22
+ !Number.isSafeInteger(retryBase) || retryBase < 1 || retryBase > 60_000) {
23
+ throw new Error("Invalid lineage queue limits");
24
+ }
25
+ const now = options.now ?? Date.now;
26
+ const pending = [];
27
+ const counters = { accepted: 0, duplicates: 0, rejected: 0, dropped: 0, unavailable: 0 };
28
+ let pendingGap = null;
29
+ let gapAccepted = 0;
30
+ function queueGap(start, end, reason) {
31
+ const previous = pendingGap;
32
+ const gapStart = Math.min(start, previous ? Date.parse(previous.gapStart) : start);
33
+ const gapEnd = Math.max(end, previous ? Date.parse(previous.gapEnd) : end, gapStart + 1);
34
+ pendingGap = parseActionCollectionGap({ contractVersion: ACTION_LINEAGE_CONTRACT_VERSION,
35
+ kind: "collection_gap", gapId: crypto.randomUUID(),
36
+ gapStart: new Date(gapStart).toISOString(), gapEnd: new Date(gapEnd).toISOString(), reason });
37
+ }
38
+ function expire() {
39
+ for (let i = pending.length - 1; i >= 0; i--) {
40
+ if (now() - pending[i].enqueuedAt >= maxAge) {
41
+ const expired = pending[i];
42
+ pending.splice(i, 1);
43
+ counters.dropped++;
44
+ queueGap(Math.min(expired.sourceAt, expired.enqueuedAt), now(), "queue_expired");
45
+ }
46
+ }
47
+ }
48
+ async function flushGap() {
49
+ const gap = pendingGap;
50
+ if (!gap)
51
+ return;
52
+ const outcome = await send(JSON.stringify(gap));
53
+ if (outcome.status === "accepted" && pendingGap?.gapId === gap.gapId) {
54
+ pendingGap = null;
55
+ gapAccepted += outcome.accepted;
56
+ }
57
+ }
58
+ async function send(body) {
59
+ let response;
60
+ try {
61
+ response = await request(url.toString(), {
62
+ method: "POST", headers: { "content-type": "application/json",
63
+ authorization: `Bearer ${options.token}` },
64
+ body,
65
+ });
66
+ }
67
+ catch {
68
+ return { status: "unavailable", httpStatus: null };
69
+ }
70
+ if (response.status === 202) {
71
+ const ack = await response.json().catch(() => null);
72
+ if (ack?.durable === true && typeof ack.accepted === "number" &&
73
+ typeof ack.duplicates === "number") {
74
+ return { status: "accepted", accepted: ack.accepted, duplicates: ack.duplicates };
75
+ }
76
+ return { status: "unavailable", httpStatus: 202 };
77
+ }
78
+ return { status: response.status >= 500 || response.status === 429 ? "unavailable" : "rejected",
79
+ httpStatus: response.status };
80
+ }
81
+ function count(outcome) {
82
+ if (outcome.status === "accepted") {
83
+ counters.accepted += outcome.accepted;
84
+ counters.duplicates += outcome.duplicates;
85
+ }
86
+ else
87
+ counters[outcome.status]++;
88
+ }
89
+ async function reportEnvelope(envelope) {
90
+ const parsed = parseActionLineageEnvelope(envelope, options.approvedLocatorOrigins);
91
+ return reportPayload(parsed, parsed.occurredAt ? Date.parse(parsed.occurredAt) : now());
92
+ }
93
+ async function reportEnvelopeEnhanced(envelope) {
94
+ if (options.artifactPresentationEnabled !== true)
95
+ throw new Error("Enhanced artifact reporting requires the artifact_presentation_v1 enrollment capability");
96
+ const parsed = parseActionLineageEnvelopeV1_1(envelope, options.approvedLocatorOrigins);
97
+ return reportPayload(parsed, parsed.occurredAt ? Date.parse(parsed.occurredAt) : now());
98
+ }
99
+ async function reportPayload(payload, sourceAt) {
100
+ const body = JSON.stringify(payload);
101
+ if (new TextEncoder().encode(body).byteLength > 65_536)
102
+ throw new Error("Lineage report exceeds receiver limit");
103
+ const outcome = await send(body);
104
+ count(outcome);
105
+ if (outcome.status === "unavailable") {
106
+ expire();
107
+ if (pending.length < maxPending)
108
+ pending.push({ body, enqueuedAt: now(), sourceAt,
109
+ nextRetryAt: now() + retryBase, attempts: 1 });
110
+ else {
111
+ counters.dropped++;
112
+ queueGap(Math.min(sourceAt, now()), now() + 1, "queue_overflow");
113
+ }
114
+ }
115
+ if (outcome.status === "accepted" && pendingGap)
116
+ await flushGap();
117
+ return outcome;
118
+ }
119
+ async function reportActivity(input) {
120
+ if (!options.activityAuthority)
121
+ throw new Error("Activity reporting requires its enrollment-bound source context");
122
+ const payload = parseActivityPurposeReport({
123
+ contractVersion: ACTIVITY_CLASSIFICATION_CONTRACT_VERSION, reportId: crypto.randomUUID(),
124
+ actionId: input.actionId, attemptId: input.attemptId, purpose: input.purpose ?? null,
125
+ membership: input.membership ?? null, outputs: input.outputs ?? [], noOutput: input.noOutput ?? null,
126
+ }, { authority: options.activityAuthority, capabilities: options.activityCapabilities ?? [] });
127
+ const occurrence = input.purpose?.declaredAt ?? input.membership?.establishedAt ?? input.outputs?.[0]?.occurredAt ?? input.noOutput?.occurredAt;
128
+ return reportPayload(payload, occurrence ? Date.parse(occurrence) : now());
129
+ }
130
+ async function reportPosting(input) {
131
+ if (options.postingLineageEnabled !== true || !options.postingAuthority) {
132
+ throw new Error("Posting reporting requires a posting_lineage_v1 enrollment and its source binding");
133
+ }
134
+ const payload = bindPostingActionEnvelopeV1_2({ ...input, contractVersion: POSTING_LINEAGE_CONTRACT_VERSION,
135
+ reportId: crypto.randomUUID(), phase: "artifact_result" }, {
136
+ authority: options.postingAuthority,
137
+ capabilities: options.postingCapabilities ?? ["artifact_lineage_v1", POSTING_LINEAGE_CAPABILITY],
138
+ });
139
+ const occurredAt = input.occurredAt ?? input.completedAt ?? input.startedAt;
140
+ return reportPayload(payload.envelope, occurredAt ? Date.parse(occurredAt) : now());
141
+ }
142
+ async function flush() {
143
+ expire();
144
+ // A bounded pass; retries preserve the original immutable report ID and payload.
145
+ const countAtStart = pending.length;
146
+ for (let i = 0; i < countAtStart; i++) {
147
+ const entry = pending.shift();
148
+ if (!entry)
149
+ break;
150
+ if (now() < entry.nextRetryAt) {
151
+ pending.push(entry);
152
+ continue;
153
+ }
154
+ const outcome = await send(entry.body);
155
+ count(outcome);
156
+ if (outcome.status === "unavailable") {
157
+ entry.attempts++;
158
+ entry.nextRetryAt = now() + Math.min(60_000, retryBase * 2 ** Math.min(entry.attempts - 1, 16));
159
+ pending.push(entry);
160
+ }
161
+ }
162
+ expire();
163
+ await flushGap();
164
+ return status();
165
+ }
166
+ function status() {
167
+ expire();
168
+ return { queued: pending.length, ...counters, gapPending: pendingGap !== null, gapAccepted };
169
+ }
170
+ async function reportCollectionGap(gapStart, gapEnd) {
171
+ const gap = parseActionCollectionGap({ contractVersion: ACTION_LINEAGE_CONTRACT_VERSION,
172
+ kind: "collection_gap", gapId: crypto.randomUUID(), gapStart, gapEnd, reason: "operator_reported" });
173
+ const outcome = await send(JSON.stringify(gap));
174
+ if (outcome.status === "accepted")
175
+ gapAccepted += outcome.accepted;
176
+ else if (outcome.status === "unavailable") {
177
+ queueGap(Date.parse(gap.gapStart), Date.parse(gap.gapEnd), "operator_reported");
178
+ }
179
+ return outcome;
180
+ }
181
+ function action(input) {
182
+ const actionId = input.actionId ?? crypto.randomUUID();
183
+ const attemptId = input.attemptId ?? crypto.randomUUID();
184
+ const startedAt = input.startedAt ?? new Date(now()).toISOString();
185
+ const correlation = { ...emptyCorrelation, ...input.correlation,
186
+ namespace: "explicit-sdk-v1" };
187
+ function report(phase, status, artifacts, exitCode = null) {
188
+ const occurredAt = new Date(now()).toISOString();
189
+ return reportEnvelope({ contractVersion: ACTION_LINEAGE_CONTRACT_VERSION,
190
+ reportId: crypto.randomUUID(), actionId, attemptId, phase, executionStatus: status,
191
+ startedAt, completedAt: phase === "started" ? null : occurredAt, occurredAt,
192
+ correlation, adapter: { name: "explicit_sdk", version: "1.0.0", sourceVersion: null },
193
+ metadata: { toolKind: input.toolKind, exitCode,
194
+ errorCode: status === "failed" ? "tool_failed" : status === "cancelled" ? "cancelled" : null },
195
+ artifacts });
196
+ }
197
+ function reportEnhanced(artifacts, status = "succeeded") {
198
+ const occurredAt = new Date(now()).toISOString();
199
+ return reportEnvelopeEnhanced({ contractVersion: ACTION_LINEAGE_ENHANCED_CONTRACT_VERSION,
200
+ reportId: crypto.randomUUID(), actionId, attemptId, phase: "artifact_result", executionStatus: status,
201
+ startedAt, completedAt: occurredAt, occurredAt, correlation,
202
+ adapter: { name: "explicit_sdk", version: "1.1.0", sourceVersion: null },
203
+ metadata: { toolKind: input.toolKind, exitCode: null,
204
+ errorCode: status === "failed" ? "tool_failed" : status === "cancelled" ? "cancelled" : null }, artifacts });
205
+ }
206
+ return { actionId, attemptId, startedAt,
207
+ start: () => report("started", "in_progress", []),
208
+ result: async (artifacts, status = "succeeded") => {
209
+ if (artifacts.length <= ACTION_LINEAGE_LIMITS.maxArtifacts)
210
+ return report("artifact_result", status, artifacts);
211
+ let outcome = { status: "accepted", accepted: 0, duplicates: 0 };
212
+ for (let index = 0; index < artifacts.length; index += ACTION_LINEAGE_LIMITS.maxArtifacts) {
213
+ const next = await report("artifact_result", status, artifacts.slice(index, index + ACTION_LINEAGE_LIMITS.maxArtifacts));
214
+ if (next.status !== "accepted")
215
+ outcome = next;
216
+ else if (outcome.status === "accepted")
217
+ outcome = { status: "accepted", accepted: outcome.accepted + next.accepted, duplicates: outcome.duplicates + next.duplicates };
218
+ }
219
+ return outcome;
220
+ },
221
+ resultEnhanced: async (artifacts, status = "succeeded") => {
222
+ if (artifacts.length <= ACTION_LINEAGE_LIMITS.maxArtifacts)
223
+ return reportEnhanced(artifacts, status);
224
+ let outcome = { status: "accepted", accepted: 0, duplicates: 0 };
225
+ for (let index = 0; index < artifacts.length; index += ACTION_LINEAGE_LIMITS.maxArtifacts) {
226
+ const next = await reportEnhanced(artifacts.slice(index, index + ACTION_LINEAGE_LIMITS.maxArtifacts), status);
227
+ if (next.status !== "accepted")
228
+ outcome = next;
229
+ else if (outcome.status === "accepted")
230
+ outcome = { status: "accepted", accepted: outcome.accepted + next.accepted, duplicates: outcome.duplicates + next.duplicates };
231
+ }
232
+ return outcome;
233
+ },
234
+ complete: (status, exitCode = null) => report("completed", status, [], exitCode) };
235
+ }
236
+ return { reportEnvelope, reportActivity, reportPosting, reportCollectionGap, action, flush, status };
237
+ }
@@ -0,0 +1,20 @@
1
+ import { type ActionLineageEnvelopeV1 } from "../../integration-contracts/src/action-lineage.ts";
2
+ import type { ReportOutcome } from "./client.ts";
3
+ export declare const SUPPORTED_CODEX_CLI_VERSION: "0.160.0";
4
+ export interface CodexCliDiagnostics {
5
+ supported: boolean;
6
+ commandsStarted: number;
7
+ commandsCompleted: number;
8
+ missingStart: number;
9
+ missingTerminal: number;
10
+ invalidItems: number;
11
+ reportsAccepted: number;
12
+ reportsUnavailable: number;
13
+ reportsRejected: number;
14
+ }
15
+ interface Reporter {
16
+ reportEnvelope(envelope: ActionLineageEnvelopeV1): Promise<ReportOutcome>;
17
+ }
18
+ /** Consumes only the version-matched JSONL event structure. Content fields are never read. */
19
+ export declare function captureCodexCliJsonl(events: Iterable<unknown> | AsyncIterable<unknown>, sourceVersion: string, reporter: Reporter): Promise<CodexCliDiagnostics>;
20
+ export {};
@@ -0,0 +1,92 @@
1
+ import { ACTION_LINEAGE_CONTRACT_VERSION } from "../../integration-contracts/src/action-lineage.js";
2
+ export const SUPPORTED_CODEX_CLI_VERSION = "0.160.0";
3
+ /** Consumes only the version-matched JSONL event structure. Content fields are never read. */
4
+ export async function captureCodexCliJsonl(events, sourceVersion, reporter) {
5
+ const diagnostics = { supported: sourceVersion === SUPPORTED_CODEX_CLI_VERSION,
6
+ commandsStarted: 0, commandsCompleted: 0, missingStart: 0, missingTerminal: 0,
7
+ invalidItems: 0, reportsAccepted: 0, reportsUnavailable: 0, reportsRejected: 0 };
8
+ if (!diagnostics.supported)
9
+ return diagnostics;
10
+ const pending = new Map();
11
+ let threadId = null;
12
+ const sourceId = (value) => typeof value === "string" &&
13
+ /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : null;
14
+ async function report(phase, ids, status, exitCode) {
15
+ const envelope = {
16
+ contractVersion: ACTION_LINEAGE_CONTRACT_VERSION, reportId: crypto.randomUUID(),
17
+ actionId: ids.actionId, attemptId: ids.attemptId, phase, executionStatus: status,
18
+ // The CLI fixture carries no source clock. Receipt time must not stand in for occurrence.
19
+ startedAt: null, completedAt: null, occurredAt: null,
20
+ correlation: { namespace: "codex-cli-jsonl-v1", runId: threadId, sessionId: null,
21
+ parentRunId: null, toolCallId: null, completionReference: null },
22
+ adapter: { name: "codex_exec_jsonl", version: "1.0.0", sourceVersion: SUPPORTED_CODEX_CLI_VERSION },
23
+ metadata: { toolKind: "command", exitCode, errorCode: status === "failed" ? "tool_failed" :
24
+ status === "unknown" ? "unknown" : null }, artifacts: [],
25
+ };
26
+ try {
27
+ const outcome = await reporter.reportEnvelope(envelope);
28
+ if (outcome.status === "accepted")
29
+ diagnostics.reportsAccepted++;
30
+ else if (outcome.status === "unavailable")
31
+ diagnostics.reportsUnavailable++;
32
+ else
33
+ diagnostics.reportsRejected++;
34
+ }
35
+ catch {
36
+ diagnostics.reportsUnavailable++;
37
+ }
38
+ }
39
+ for await (const raw of events) {
40
+ if (typeof raw !== "object" || raw === null) {
41
+ diagnostics.invalidItems++;
42
+ continue;
43
+ }
44
+ const event = raw;
45
+ if (event.type === "thread.started") {
46
+ threadId = sourceId(event.thread_id);
47
+ if (threadId === null)
48
+ diagnostics.invalidItems++;
49
+ continue;
50
+ }
51
+ if (event.type !== "item.started" && event.type !== "item.completed")
52
+ continue;
53
+ if (typeof event.item !== "object" || event.item === null) {
54
+ diagnostics.invalidItems++;
55
+ continue;
56
+ }
57
+ const item = event.item;
58
+ if (item.type !== "command_execution")
59
+ continue;
60
+ const itemId = sourceId(item.id);
61
+ if (!itemId || !threadId) {
62
+ diagnostics.invalidItems++;
63
+ continue;
64
+ }
65
+ if (event.type === "item.started") {
66
+ if (item.status !== "in_progress" || pending.has(itemId)) {
67
+ diagnostics.invalidItems++;
68
+ continue;
69
+ }
70
+ const ids = { actionId: crypto.randomUUID(), attemptId: crypto.randomUUID() };
71
+ pending.set(itemId, ids);
72
+ diagnostics.commandsStarted++;
73
+ await report("started", ids, "in_progress", null);
74
+ continue;
75
+ }
76
+ if (item.status !== "completed" && item.status !== "failed") {
77
+ diagnostics.invalidItems++;
78
+ continue;
79
+ }
80
+ const ids = pending.get(itemId) ?? { actionId: crypto.randomUUID(), attemptId: crypto.randomUUID() };
81
+ if (!pending.has(itemId))
82
+ diagnostics.missingStart++;
83
+ pending.delete(itemId);
84
+ diagnostics.commandsCompleted++;
85
+ const exitCode = typeof item.exit_code === "number" && Number.isSafeInteger(item.exit_code) &&
86
+ item.exit_code >= -255 && item.exit_code <= 65535 ? item.exit_code : null;
87
+ const status = exitCode === null ? "unknown" : exitCode === 0 ? "succeeded" : "failed";
88
+ await report("completed", ids, status, exitCode);
89
+ }
90
+ diagnostics.missingTerminal = pending.size;
91
+ return diagnostics;
92
+ }
@@ -0,0 +1,27 @@
1
+ import { type AiExecutionEvidencePacketV1 } from "../../integration-contracts/src/ai-execution.ts";
2
+ import type { ReportOutcome } from "./client.ts";
3
+ export declare const SUPPORTED_CODEX_EXECUTION_VERSION: "0.166.0";
4
+ export declare const CODEX_EXECUTION_MAPPING_VERSION: "codex-execution-cli-0.166.0";
5
+ export interface CodexExecutionDiagnostics {
6
+ supported: boolean;
7
+ commandExecutions: number;
8
+ missingThread: number;
9
+ invalidItems: number;
10
+ reportsAccepted: number;
11
+ reportsUnavailable: number;
12
+ reportsRejected: number;
13
+ turnIdsUnavailable: boolean;
14
+ requestIdsUnavailable: boolean;
15
+ sourceTimestampsUnavailable: boolean;
16
+ }
17
+ interface Reporter {
18
+ reportExecutionPacket(packet: AiExecutionEvidencePacketV1): Promise<ReportOutcome>;
19
+ }
20
+ export declare function createAiExecutionReporter(options: {
21
+ endpoint: string;
22
+ token: string;
23
+ fetch?: typeof globalThis.fetch;
24
+ }): Reporter;
25
+ /** Maps only the installed-version JSONL fields present in the sanitized fixture. */
26
+ export declare function captureCodexExecutionJsonl(events: Iterable<unknown> | AsyncIterable<unknown>, sourceVersion: string, reporter: Reporter): Promise<CodexExecutionDiagnostics>;
27
+ export {};
@@ -0,0 +1,123 @@
1
+ import { AI_EXECUTION_EVIDENCE_CONTRACT_VERSION, parseAiExecutionEvidencePacket, } from "../../integration-contracts/src/ai-execution.js";
2
+ export const SUPPORTED_CODEX_EXECUTION_VERSION = "0.166.0";
3
+ export const CODEX_EXECUTION_MAPPING_VERSION = "codex-execution-cli-0.166.0";
4
+ const NAMESPACE = "codex-cli-exec-jsonl-0.166.0";
5
+ export function createAiExecutionReporter(options) {
6
+ const url = new URL(options.endpoint);
7
+ if ((url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "::1"].includes(url.hostname))) ||
8
+ url.username || url.password || url.search || url.hash || !url.pathname.endsWith("/functions/v1/ai-execution-evidence")) {
9
+ throw new Error("Execution endpoint must use the verified HTTPS receiver URL");
10
+ }
11
+ if (!/^[A-Za-z0-9_-]{32,128}$/.test(options.token))
12
+ throw new Error("Invalid execution enrollment token");
13
+ const request = options.fetch ?? globalThis.fetch;
14
+ return {
15
+ reportExecutionPacket: async (packet) => {
16
+ const body = JSON.stringify(parseAiExecutionEvidencePacket(packet));
17
+ if (new TextEncoder().encode(body).byteLength > 65_536)
18
+ return { status: "rejected", httpStatus: 413 };
19
+ let response;
20
+ try {
21
+ response = await request(url.toString(), { method: "POST", redirect: "error",
22
+ headers: { authorization: `Bearer ${options.token}`, "content-type": "application/json" }, body,
23
+ signal: AbortSignal.timeout(5_000) });
24
+ }
25
+ catch {
26
+ return { status: "unavailable", httpStatus: null };
27
+ }
28
+ if (response.status === 202) {
29
+ const receipt = await response.json().catch(() => null);
30
+ return receipt && typeof receipt.receiptId === "string" &&
31
+ ["accepted", "binding_pending", "processed"].includes(String(receipt.state)) &&
32
+ typeof receipt.receivedAt === "string"
33
+ ? { status: "accepted", accepted: 1, duplicates: 0 }
34
+ : { status: "unavailable", httpStatus: 202 };
35
+ }
36
+ return { status: response.status >= 500 || response.status === 429 ? "unavailable" : "rejected",
37
+ httpStatus: response.status };
38
+ },
39
+ };
40
+ }
41
+ function normalizedVersion(value) {
42
+ const match = /^(?:codex-cli\s+)?(\d+\.\d+\.\d+)$/.exec(value.trim());
43
+ return match?.[1] ?? null;
44
+ }
45
+ async function digest(value) {
46
+ const bytes = new TextEncoder().encode(value);
47
+ const result = await crypto.subtle.digest("SHA-256", bytes);
48
+ return [...new Uint8Array(result)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
49
+ }
50
+ /** Maps only the installed-version JSONL fields present in the sanitized fixture. */
51
+ export async function captureCodexExecutionJsonl(events, sourceVersion, reporter) {
52
+ const supported = normalizedVersion(sourceVersion) === SUPPORTED_CODEX_EXECUTION_VERSION;
53
+ const diagnostics = {
54
+ supported, commandExecutions: 0, missingThread: 0, invalidItems: 0,
55
+ reportsAccepted: 0, reportsUnavailable: 0, reportsRejected: 0,
56
+ turnIdsUnavailable: true, requestIdsUnavailable: true, sourceTimestampsUnavailable: true,
57
+ };
58
+ if (!supported) {
59
+ // The caller may be teeing a live JSONL stream. Drain it without parsing or
60
+ // forwarding so an unsupported adapter never consumes the originating output.
61
+ for await (const _event of events) { /* pass-through is owned by the caller */ }
62
+ return diagnostics;
63
+ }
64
+ let threadId = null;
65
+ const validId = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
66
+ const pendingReports = [];
67
+ for await (const raw of events) {
68
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
69
+ diagnostics.invalidItems++;
70
+ continue;
71
+ }
72
+ const event = raw;
73
+ if (event.type === "thread.started") {
74
+ threadId = validId(event.thread_id) ? event.thread_id : null;
75
+ if (threadId === null)
76
+ diagnostics.invalidItems++;
77
+ continue;
78
+ }
79
+ if (event.type !== "item.completed" || typeof event.item !== "object" || event.item === null || Array.isArray(event.item))
80
+ continue;
81
+ const item = event.item;
82
+ if (item.type !== "command_execution")
83
+ continue;
84
+ if (!validId(item.id)) {
85
+ diagnostics.invalidItems++;
86
+ continue;
87
+ }
88
+ if (!threadId) {
89
+ diagnostics.missingThread++;
90
+ continue;
91
+ }
92
+ const identity = `${NAMESPACE}:${threadId}:${item.id}`;
93
+ const exitCode = typeof item.exit_code === "number" && Number.isSafeInteger(item.exit_code)
94
+ ? item.exit_code : null;
95
+ const status = item.status === "failed" || (exitCode !== null && exitCode !== 0)
96
+ ? "failed" : item.status === "completed" && exitCode === 0 ? "succeeded" : "unknown";
97
+ const packet = parseAiExecutionEvidencePacket({
98
+ contractVersion: AI_EXECUTION_EVIDENCE_CONTRACT_VERSION,
99
+ reportId: crypto.randomUUID(),
100
+ mappingVersion: CODEX_EXECUTION_MAPPING_VERSION,
101
+ namespace: NAMESPACE,
102
+ protectedSessionKey: await digest(`${NAMESPACE}:session:${threadId}`),
103
+ executions: [{
104
+ executionKey: await digest(`${identity}:execution`),
105
+ kind: "tool_execution",
106
+ operation: "command_execution",
107
+ status,
108
+ factReferences: [],
109
+ }],
110
+ });
111
+ diagnostics.commandExecutions++;
112
+ pendingReports.push(Promise.resolve().then(() => reporter.reportExecutionPacket(packet)).then((outcome) => {
113
+ if (outcome.status === "accepted")
114
+ diagnostics.reportsAccepted++;
115
+ else if (outcome.status === "unavailable")
116
+ diagnostics.reportsUnavailable++;
117
+ else
118
+ diagnostics.reportsRejected++;
119
+ }).catch(() => { diagnostics.reportsUnavailable++; }));
120
+ }
121
+ await Promise.all(pendingReports);
122
+ return diagnostics;
123
+ }
@@ -0,0 +1,11 @@
1
+ export { ACTION_LINEAGE_CONTRACT_VERSION, ACTION_LINEAGE_ENHANCED_CONTRACT_VERSION, ACTION_LINEAGE_PRESENTATION_CAPABILITY, ACTION_LINEAGE_LIMITS, parseActionLineageEnvelope, parseActionCollectionGap, type ActionLineageEnvelopeV1, type ActionCollectionGapV1, type ActionArtifactResultV1, type ActionArtifactResultV1_1, type ActionArtifactPresentationV1, type PersistedOutputVerificationV1, type ActionCorrelationV1, type ActionExecutionStatus, } from "../../integration-contracts/src/action-lineage.ts";
2
+ export { ARTIFACT_LINEAGE_CONTRACT_VERSION, parseArtifactIdentity, parseArtifactRevision, type ArtifactIdentityV1, type ArtifactRelationship, type ArtifactRevisionV1, } from "../../integration-contracts/src/artifact-lineage.ts";
3
+ export { createInstrumentation, type InstrumentationOptions, type ActionSession, type ReportOutcome, type ActionStart, type ExportStatus, type ActivityReportInput, type PostingReportInput } from "./client.ts";
4
+ export { ACTIVITY_CLASSIFICATION_CONTRACT_VERSION, ACTIVITY_PURPOSE_CAPABILITY, ACTIVITY_OUTPUT_CAPABILITY, parseActivityPurposeReport, parseActivityPurposeJson, type ActivityPurposeReportV1, type ActivityPurposeDeclarationV1, type ActivityWorkContextMembershipV1, type ActivityEphemeralOutputV1, type ActivityNoOutputAssertionV1, type ActivityCategoryReferenceV1, } from "../../integration-contracts/src/activity-classification.ts";
5
+ export { commitReference, pullRequestReference, linearTicketReference, persistedResultReference, wrapCommitTool, wrapPullRequestTool, wrapLinearTicketTool, wrapPersistedResultTool, StructuredToolFailure, type StructuredResult, type StructuredToolClient, type WrapperOptions, persistedResultReferenceEnhanced } from "./wrappers.ts";
6
+ export { captureCodexCliJsonl, SUPPORTED_CODEX_CLI_VERSION, type CodexCliDiagnostics } from "./codex-cli.ts";
7
+ export { captureCodexExecutionJsonl, createAiExecutionReporter, SUPPORTED_CODEX_EXECUTION_VERSION, CODEX_EXECUTION_MAPPING_VERSION, type CodexExecutionDiagnostics } from "./codex-execution.ts";
8
+ export { savePersistedFile, PersistedFileSaveError, type PersistedFileSaveInput } from "./persisted-file.ts";
9
+ export { postingReference, linearCommentReference, githubConversationCommentReference, githubInlineReviewCommentReference, slackMessageReference, wrapPostingTool, PostingToolFailure, type PostingToolClient, type PostingStructuredResult, type PostingActionReference, type PostingWrapperOptions } from "./posting-wrappers.ts";
10
+ export { POSTING_LINEAGE_CONTRACT_VERSION, POSTING_LINEAGE_CAPABILITY, parsePostingIdentityV1_2, parsePostingParentContextV1_2, parsePostingActionResultV1_2, parsePostingActionEnvelopeV1_2, type PostingIdentityV1_2, type PostingParentContextV1_2, type PostingActionResultV1_2, type PostingActionEnvelopeV1_2, } from "../../integration-contracts/src/posting-lineage.ts";
11
+ export { AI_SESSION_EVIDENCE_CONTRACT_VERSION, AI_SESSION_EVIDENCE_CAPABILITY, AI_SESSION_EVIDENCE_LIMITS, parseAiSessionEvidencePacket, buildAiSessionEvidencePacket, buildAiSessionMembershipPacket, type AiSessionEvidencePacketV1, type AiSessionReferenceV1, type AiSessionEvidenceReferenceV1, type AiSessionReceiptV1, } from "../../integration-contracts/src/ai-session.ts";
@@ -0,0 +1,11 @@
1
+ export { ACTION_LINEAGE_CONTRACT_VERSION, ACTION_LINEAGE_ENHANCED_CONTRACT_VERSION, ACTION_LINEAGE_PRESENTATION_CAPABILITY, ACTION_LINEAGE_LIMITS, parseActionLineageEnvelope, parseActionCollectionGap, } from "../../integration-contracts/src/action-lineage.js";
2
+ export { ARTIFACT_LINEAGE_CONTRACT_VERSION, parseArtifactIdentity, parseArtifactRevision, } from "../../integration-contracts/src/artifact-lineage.js";
3
+ export { createInstrumentation } from "./client.js";
4
+ export { ACTIVITY_CLASSIFICATION_CONTRACT_VERSION, ACTIVITY_PURPOSE_CAPABILITY, ACTIVITY_OUTPUT_CAPABILITY, parseActivityPurposeReport, parseActivityPurposeJson, } from "../../integration-contracts/src/activity-classification.js";
5
+ export { commitReference, pullRequestReference, linearTicketReference, persistedResultReference, wrapCommitTool, wrapPullRequestTool, wrapLinearTicketTool, wrapPersistedResultTool, StructuredToolFailure, persistedResultReferenceEnhanced } from "./wrappers.js";
6
+ export { captureCodexCliJsonl, SUPPORTED_CODEX_CLI_VERSION } from "./codex-cli.js";
7
+ export { captureCodexExecutionJsonl, createAiExecutionReporter, SUPPORTED_CODEX_EXECUTION_VERSION, CODEX_EXECUTION_MAPPING_VERSION } from "./codex-execution.js";
8
+ export { savePersistedFile, PersistedFileSaveError } from "./persisted-file.js";
9
+ export { postingReference, linearCommentReference, githubConversationCommentReference, githubInlineReviewCommentReference, slackMessageReference, wrapPostingTool, PostingToolFailure } from "./posting-wrappers.js";
10
+ export { POSTING_LINEAGE_CONTRACT_VERSION, POSTING_LINEAGE_CAPABILITY, parsePostingIdentityV1_2, parsePostingParentContextV1_2, parsePostingActionResultV1_2, parsePostingActionEnvelopeV1_2, } from "../../integration-contracts/src/posting-lineage.js";
11
+ export { AI_SESSION_EVIDENCE_CONTRACT_VERSION, AI_SESSION_EVIDENCE_CAPABILITY, AI_SESSION_EVIDENCE_LIMITS, parseAiSessionEvidencePacket, buildAiSessionEvidencePacket, buildAiSessionMembershipPacket, } from "../../integration-contracts/src/ai-session.js";