@spellkave/agent-observability 0.0.0-bootstrap

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/src/reader.ts ADDED
@@ -0,0 +1,122 @@
1
+ // Read/projection API (ADR-0074 S2) — the single consumption path for the
2
+ // playtest judge, progress-explorer, and future inspection layers. Emission
3
+ // and consumption live in ONE package on purpose: the moment they separate,
4
+ // schemas drift apart again (the ADR's stated enforcement mechanism).
5
+ //
6
+ // Readers are TOLERANT by contract: unknown fields are preserved untouched,
7
+ // unparseable or foreign lines are counted and skipped, never thrown on.
8
+ import {
9
+ type AgentRunEvent,
10
+ isAgentRunEvent,
11
+ type RunEndData,
12
+ type TerminalData,
13
+ } from "./events.ts";
14
+
15
+ export interface ParsedRunEvents {
16
+ events: AgentRunEvent[];
17
+ /** Lines that failed JSON.parse or are not agent-run-events/v1. */
18
+ skipped: number;
19
+ }
20
+
21
+ /** Parse a JSONL document into v1 events, tolerantly. */
22
+ export function parseRunEvents(jsonl: string): ParsedRunEvents {
23
+ const events: AgentRunEvent[] = [];
24
+ let skipped = 0;
25
+ for (const line of jsonl.split("\n")) {
26
+ const trimmed = line.trim();
27
+ if (trimmed === "") continue;
28
+ let value: unknown;
29
+ try {
30
+ value = JSON.parse(trimmed);
31
+ } catch {
32
+ skipped += 1;
33
+ continue;
34
+ }
35
+ if (!isAgentRunEvent(value)) {
36
+ skipped += 1;
37
+ continue;
38
+ }
39
+ // Normalise a missing payload; never strip unknown fields.
40
+ if (typeof (value as { data?: unknown }).data !== "object" || value.data === null) {
41
+ (value as { data: Record<string, unknown> }).data = {};
42
+ }
43
+ events.push(value);
44
+ }
45
+ return { events, skipped };
46
+ }
47
+
48
+ // --- Aggregations: the first two the playtest judge actually needs. ---
49
+
50
+ export interface RunTotals {
51
+ run_id: string;
52
+ tool_calls: number;
53
+ /** Tool calls whose payload flagged `is_error: true`. */
54
+ tool_errors: number;
55
+ turns: number;
56
+ input_tokens: number;
57
+ output_tokens: number;
58
+ gap_reports: number;
59
+ }
60
+
61
+ /** Per-run token/tool-call totals. Counts `tool_call` / `turn_end` /
62
+ * `gap_report` events; token fields sum whatever `turn_end` payloads carry
63
+ * (absent fields count 0 — tolerant readers never assume payload fields). */
64
+ export function aggregateRunTotals(events: readonly AgentRunEvent[]): RunTotals {
65
+ const totals: RunTotals = {
66
+ run_id: events[0]?.run_id ?? "",
67
+ tool_calls: 0,
68
+ tool_errors: 0,
69
+ turns: 0,
70
+ input_tokens: 0,
71
+ output_tokens: 0,
72
+ gap_reports: 0,
73
+ };
74
+ for (const event of events) {
75
+ if (event.type === "tool_call") {
76
+ totals.tool_calls += 1;
77
+ if (event.data.is_error === true) totals.tool_errors += 1;
78
+ } else if (event.type === "turn_end") {
79
+ totals.turns += 1;
80
+ totals.input_tokens += numberField(event.data, "input_tokens");
81
+ totals.output_tokens += numberField(event.data, "output_tokens");
82
+ } else if (event.type === "gap_report") {
83
+ totals.gap_reports += 1;
84
+ }
85
+ }
86
+ return totals;
87
+ }
88
+
89
+ export interface TerminalClassification {
90
+ /** The terminal from the `terminal` event (preferred) or `run_end.terminal`. */
91
+ terminal: string | null;
92
+ reason: string | null;
93
+ /** A `run_start` without any `run_end` — the run died or is still live. */
94
+ incomplete: boolean;
95
+ }
96
+
97
+ /** Terminal classification for one run's event stream. */
98
+ export function classifyTerminal(events: readonly AgentRunEvent[]): TerminalClassification {
99
+ let terminal: string | null = null;
100
+ let reason: string | null = null;
101
+ let sawStart = false;
102
+ let sawEnd = false;
103
+ for (const event of events) {
104
+ if (event.type === "run_start") sawStart = true;
105
+ if (event.type === "terminal") {
106
+ const data = event.data as Partial<TerminalData>;
107
+ if (typeof data.terminal === "string") terminal = data.terminal;
108
+ if (typeof data.reason === "string") reason = data.reason;
109
+ }
110
+ if (event.type === "run_end") {
111
+ sawEnd = true;
112
+ const data = event.data as Partial<RunEndData>;
113
+ if (terminal === null && typeof data.terminal === "string") terminal = data.terminal;
114
+ }
115
+ }
116
+ return { terminal, reason, incomplete: sawStart && !sawEnd };
117
+ }
118
+
119
+ function numberField(data: Record<string, unknown>, key: string): number {
120
+ const value = data[key];
121
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
122
+ }
package/src/traces.ts ADDED
@@ -0,0 +1,261 @@
1
+ // Lightweight, dependency-free OTLP/HTTP trace projection for world-actor work.
2
+ // Hosts configure transport; instrumented libraries depend only on the small
3
+ // structural WorldActorTracer interface, not on an OpenTelemetry SDK.
4
+
5
+ export const OTEL_TRACE_SERVICE_NAME = "spellkave-world-actors";
6
+ export const OTEL_TRACE_STREAM_NAME = "world_actor_traces";
7
+
8
+ export type WorldActorSpanStatus = "unset" | "ok" | "error";
9
+
10
+ export interface WorldActorSpan {
11
+ addEvent(name: string, attributes?: Record<string, unknown>): void;
12
+ end(status?: WorldActorSpanStatus): void;
13
+ }
14
+
15
+ export interface WorldActorTracer {
16
+ startSpan(name: string, attributes?: Record<string, unknown>): WorldActorSpan;
17
+ flush(): Promise<void>;
18
+ }
19
+
20
+ interface OtlpAttribute {
21
+ key: string;
22
+ value:
23
+ | { stringValue: string }
24
+ | { intValue: string }
25
+ | { doubleValue: number }
26
+ | { boolValue: boolean };
27
+ }
28
+
29
+ interface OtlpSpan {
30
+ traceId: string;
31
+ spanId: string;
32
+ name: string;
33
+ kind: number;
34
+ startTimeUnixNano: string;
35
+ endTimeUnixNano: string;
36
+ attributes: OtlpAttribute[];
37
+ events: Array<{ timeUnixNano: string; name: string; attributes: OtlpAttribute[] }>;
38
+ status: { code: number };
39
+ }
40
+
41
+ /** Correlation keys a reducer-attempt host may attach. The SDK keeps a
42
+ * matching runtime copy (`REDUCER_ATTEMPT_SAFE_TELEMETRY_ATTRIBUTES`) because
43
+ * it stays free of a runtime dependency on this package; the exporter list
44
+ * below is derived from this one so a new correlation key cannot be forgotten
45
+ * at export. Equality is asserted by
46
+ * `packages/spellkave-sdk/src/__tests__/reducer-attempt-telemetry-allowlist.test.ts`. */
47
+ export const WORLD_ACTOR_CORRELATION_ATTRIBUTE_KEYS = [
48
+ "spellkave.reducer",
49
+ "spellkave.actor_id",
50
+ "spellkave.action_id",
51
+ "spellkave.target_ref",
52
+ "spellkave.correlation_id",
53
+ "spellkave.world_slug",
54
+ "spellkave.cause_kind",
55
+ "spellkave.cause_id",
56
+ ] as const;
57
+
58
+ const SAFE_TRACE_ATTRIBUTE_EXTRAS = [
59
+ "spellkave.subject_id",
60
+ "spellkave.timeout_ms",
61
+ "spellkave.poll_ms",
62
+ "spellkave.success_on_provenance",
63
+ "spellkave.baseline_count",
64
+ "spellkave.provenance_id",
65
+ "spellkave.provenance_status",
66
+ "spellkave.provenance_kind",
67
+ "spellkave.failure_class",
68
+ "spellkave.result_status",
69
+ "spellkave.poll_count",
70
+ "spellkave.invoke_settled",
71
+ "spellkave.invoke_failed",
72
+ "spellkave.lag_warning",
73
+ "spellkave.step",
74
+ "spellkave.error_code",
75
+ "spellkave.retry_count",
76
+ ] as const;
77
+
78
+ export const SAFE_TRACE_ATTRIBUTE_KEYS = new Set<string>([
79
+ ...WORLD_ACTOR_CORRELATION_ATTRIBUTE_KEYS,
80
+ ...SAFE_TRACE_ATTRIBUTE_EXTRAS,
81
+ ]);
82
+
83
+ const SAFE_RESOURCE_ATTRIBUTE_KEYS = new Set([
84
+ "service.name",
85
+ "service.namespace",
86
+ // Deployed revision (`SPELLKAVE_IMAGE_TAG`, sk-0m4.120.13) — a tag, never a path.
87
+ "service.version",
88
+ "service.instance.id",
89
+ // sk-jay0.6.38.13: old semconv key — the collector hygiene key AND the live
90
+ // column (`service_deployment_environment` on `world_actor_traces`).
91
+ "deployment.environment",
92
+ "deployment.environment.name",
93
+ "openobserve.stream",
94
+ "spellkave.world_slug",
95
+ ]);
96
+
97
+ export interface OtlpHttpTracerOptions {
98
+ endpoint: string;
99
+ serviceName?: string;
100
+ headers?: Record<string, string>;
101
+ resourceAttributes?: Record<string, unknown>;
102
+ fetchFn?: typeof fetch;
103
+ now?: () => number;
104
+ batchSize?: number;
105
+ onError?: (error: unknown) => void;
106
+ /** Abort each export request after this deadline; default 10 seconds, as
107
+ * for the log and metrics exporters. A request that never settles would
108
+ * otherwise stay pending for the life of the process and hold `flush`
109
+ * open (sk-jay0.6.15.56.21). */
110
+ requestTimeoutMs?: number;
111
+ }
112
+
113
+ const STATUS_CODE: Record<WorldActorSpanStatus, number> = { unset: 0, ok: 1, error: 2 };
114
+
115
+ function attributes(
116
+ values: Record<string, unknown>,
117
+ allowed: ReadonlySet<string>,
118
+ ): OtlpAttribute[] {
119
+ const out: OtlpAttribute[] = [];
120
+ for (const [key, value] of Object.entries(values)) {
121
+ if (!allowed.has(key)) continue;
122
+ if (value === undefined || value === null) continue;
123
+ if (typeof value === "boolean") out.push({ key, value: { boolValue: value } });
124
+ else if (typeof value === "number" && Number.isFinite(value)) {
125
+ out.push({
126
+ key,
127
+ value: Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value },
128
+ });
129
+ } else if (typeof value === "bigint") out.push({ key, value: { intValue: value.toString() } });
130
+ else out.push({ key, value: { stringValue: String(value).slice(0, 8_000) } });
131
+ }
132
+ return out;
133
+ }
134
+
135
+ function hexId(bytes: number): string {
136
+ const value = new Uint8Array(bytes);
137
+ globalThis.crypto.getRandomValues(value);
138
+ return Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("");
139
+ }
140
+
141
+ function unixNano(now: () => number): string {
142
+ return String(Math.round(now() * 1_000_000));
143
+ }
144
+
145
+ function tracesUrl(endpoint: string): string {
146
+ const base = endpoint.trim().replace(/\/+$/, "");
147
+ return base.endsWith("/v1/traces") ? base : `${base}/v1/traces`;
148
+ }
149
+
150
+ export function createOtlpHttpTracer(options: OtlpHttpTracerOptions): WorldActorTracer {
151
+ const now = options.now ?? Date.now;
152
+ const doFetch = options.fetchFn ?? globalThis.fetch.bind(globalThis);
153
+ const serviceName = options.serviceName ?? OTEL_TRACE_SERVICE_NAME;
154
+ const batchSize = options.batchSize ?? 32;
155
+ const queue: OtlpSpan[] = [];
156
+ const pending = new Set<Promise<void>>();
157
+ const configuredTimeout = options.requestTimeoutMs ?? 10_000;
158
+ const requestTimeoutMs = Number.isFinite(configuredTimeout)
159
+ ? Math.max(1, Math.trunc(configuredTimeout))
160
+ : 10_000;
161
+
162
+ function payload(spans: OtlpSpan[]): unknown {
163
+ return {
164
+ resourceSpans: [
165
+ {
166
+ resource: {
167
+ attributes: attributes(
168
+ {
169
+ "service.name": serviceName,
170
+ "service.namespace": "spellkave",
171
+ "openobserve.stream": OTEL_TRACE_STREAM_NAME,
172
+ ...options.resourceAttributes,
173
+ },
174
+ SAFE_RESOURCE_ATTRIBUTE_KEYS,
175
+ ),
176
+ },
177
+ scopeSpans: [{ scope: { name: "@spellkave/agent-observability" }, spans }],
178
+ },
179
+ ],
180
+ };
181
+ }
182
+
183
+ function ship(spans: OtlpSpan[]): Promise<void> {
184
+ if (spans.length === 0) return Promise.resolve();
185
+ const headers = new Headers(options.headers);
186
+ headers.set("content-type", "application/json");
187
+ headers.set("stream-name", OTEL_TRACE_STREAM_NAME);
188
+ let request: Promise<Response>;
189
+ const controller = new AbortController();
190
+ const timer = setTimeout(() => controller.abort(), requestTimeoutMs);
191
+ timer.unref?.();
192
+ try {
193
+ request = doFetch(tracesUrl(options.endpoint), {
194
+ method: "POST",
195
+ headers,
196
+ body: JSON.stringify(payload(spans)),
197
+ signal: controller.signal,
198
+ });
199
+ } catch (error) {
200
+ clearTimeout(timer);
201
+ options.onError?.(error);
202
+ return Promise.resolve();
203
+ }
204
+ let tracked: Promise<void>;
205
+ tracked = request
206
+ .then((response) => {
207
+ if (!response.ok)
208
+ throw new Error(`OTLP trace export failed: ${response.status} ${response.statusText}`);
209
+ })
210
+ .catch((error) => options.onError?.(error))
211
+ .finally(() => {
212
+ clearTimeout(timer);
213
+ pending.delete(tracked);
214
+ });
215
+ pending.add(tracked);
216
+ return tracked;
217
+ }
218
+
219
+ function flushQueue(): Promise<void> {
220
+ return ship(queue.splice(0, queue.length));
221
+ }
222
+
223
+ return {
224
+ startSpan(name, spanAttributes = {}) {
225
+ const span: OtlpSpan = {
226
+ traceId: hexId(16),
227
+ spanId: hexId(8),
228
+ name,
229
+ kind: 1,
230
+ startTimeUnixNano: unixNano(now),
231
+ endTimeUnixNano: unixNano(now),
232
+ attributes: attributes(spanAttributes, SAFE_TRACE_ATTRIBUTE_KEYS),
233
+ events: [],
234
+ status: { code: STATUS_CODE.unset },
235
+ };
236
+ let ended = false;
237
+ return {
238
+ addEvent(eventName, eventAttributes = {}) {
239
+ if (ended) return;
240
+ span.events.push({
241
+ timeUnixNano: unixNano(now),
242
+ name: eventName,
243
+ attributes: attributes(eventAttributes, SAFE_TRACE_ATTRIBUTE_KEYS),
244
+ });
245
+ },
246
+ end(status = "ok") {
247
+ if (ended) return;
248
+ ended = true;
249
+ span.endTimeUnixNano = unixNano(now);
250
+ span.status = { code: STATUS_CODE[status] };
251
+ queue.push(span);
252
+ if (queue.length >= batchSize) void flushQueue();
253
+ },
254
+ };
255
+ },
256
+ async flush() {
257
+ await flushQueue();
258
+ await Promise.allSettled([...pending]);
259
+ },
260
+ };
261
+ }
@@ -0,0 +1,52 @@
1
+ // Projection of a SpacetimeDB `world_event` TABLE header onto the world-actor
2
+ // OTLP path (sk-jay0.6.31.7). This is NOT `@spellkave/world-events` (the
3
+ // player-facing delivery vocabulary). Wasm reducers cannot post OTLP; a host
4
+ // subscriber forwards visible header scalars through `createOtlpHttpSink`.
5
+
6
+ /** Flatten a SpacetimeDB tagged EventKind to the server `event_kind_path` shape. */
7
+ export function eventKindPath(kind: unknown): string {
8
+ if (typeof kind === "string") return kind;
9
+ if (kind !== null && typeof kind === "object" && "tag" in kind) {
10
+ const tagged = kind as { tag: unknown; value?: unknown };
11
+ const outer = String(tagged.tag);
12
+ const inner = tagged.value;
13
+ if (inner !== null && typeof inner === "object" && "tag" in inner) {
14
+ return `${outer}.${String((inner as { tag: unknown }).tag)}`;
15
+ }
16
+ if (outer === "Autonomy") return "Autonomy.Job";
17
+ return outer;
18
+ }
19
+ return String(kind ?? "");
20
+ }
21
+
22
+ function asId(value: unknown): string {
23
+ if (typeof value === "bigint") return value.toString();
24
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
25
+ if (typeof value === "string") return value;
26
+ return String(value ?? "");
27
+ }
28
+
29
+ function asTick(value: unknown): number | undefined {
30
+ if (typeof value === "bigint") return Number(value);
31
+ if (typeof value === "number" && Number.isFinite(value)) return value;
32
+ if (typeof value === "string" && value.trim() !== "") {
33
+ const parsed = Number(value);
34
+ return Number.isFinite(parsed) ? parsed : undefined;
35
+ }
36
+ return undefined;
37
+ }
38
+
39
+ /** Scalar-only payload admitted across the OTLP disclosure boundary. */
40
+ export function worldTableEventData(
41
+ row: Readonly<Record<string, unknown>>,
42
+ worldSlug?: string,
43
+ ): Record<string, unknown> {
44
+ const data: Record<string, unknown> = {
45
+ event_id: asId(row.id),
46
+ event_kind: eventKindPath(row.kind),
47
+ };
48
+ const tick = asTick(row.tick);
49
+ if (tick !== undefined) data.tick = tick;
50
+ if (worldSlug !== undefined && worldSlug !== "") data.world_slug = worldSlug;
51
+ return data;
52
+ }