@nanobpm/agentic 0.5.0 → 0.7.0

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.
@@ -0,0 +1,490 @@
1
+ /**
2
+ * The transcript EVENT vocabulary + the single derive() fold (ADR 0056, #251).
3
+ *
4
+ * This is the "event-sourced session" layer over the S6 transcript store ({@link ./store.ts}). The
5
+ * store is already append-only and offset-keyed — chunks are appended, never mutated — which is half of
6
+ * the event-sourced-session pattern. The gap it left is that chunks are opaque `TEXT`: every richer
7
+ * view (structured message history, tool cards, per-turn boundaries, token accounting) had to re-parse
8
+ * the raw frame bytes ad hoc, a DRIFT SURFACE (two parsers of the same bytes), which our "Derivation
9
+ * Over Duplication" doctrine forbids.
10
+ *
11
+ * This module closes that gap: the append-only log of TYPED events is the single source of truth, and
12
+ * every higher-level view is a DERIVATION of that one log via a single {@link deriveView} fold — "the
13
+ * log IS the state, so divergence is structurally impossible". A raw terminal chunk is retained
14
+ * verbatim as a `stream-chunk` event (byte-level replay fidelity is preserved); a producer that emits a
15
+ * structured, marker-tagged JSON envelope is decoded into the authoritative typed events (message /
16
+ * tool-call / tool-result / turn / step / lifecycle) the derived views fold over.
17
+ *
18
+ * THE ONE PARSER. {@link parseTranscriptEvent} is the SINGLE place a stored chunk is classified into a
19
+ * typed event; every consumer (cockpit, search, token accounting, export) reads the derived view, not
20
+ * the raw bytes. A drift-guard test (`events.drift.test.ts`) asserts the event marker — and therefore
21
+ * the raw→event parse — appears in exactly this module, so a second parser cannot creep in.
22
+ *
23
+ * MERGE-EXTENSIBLE. The vocabulary is a small core ({@link CORE_TRANSCRIPT_VOCAB}) authors extend in the
24
+ * same schema with {@link mergeTranscriptVocab}, so a new event kind is an additive merge, never a fork
25
+ * of the parser. A downstream app (e.g. nano-workforce#559) registers its own `permission` kind this
26
+ * way without editing this package.
27
+ *
28
+ * BROWSER-SAFE. This module is imported by cockpit code that runs in the BROWSER (the cockpit derive),
29
+ * so it takes no hard dependency on Node's `Buffer` or any Node-only API — {@link utf8ByteLength} uses
30
+ * the Web/Node standard `TextEncoder`. It is pure and side-effect-free: no I/O, and it never touches the
31
+ * engine or a BPMN flow (ADR 0056: app-tier only, advisory).
32
+ */
33
+
34
+ /**
35
+ * Runtime-safe UTF-8 byte length. The one canonical UTF-8 byte-length implementation the transcript
36
+ * plane derives from. Implemented with `TextEncoder` (a Web/Node standard) rather than Node's `Buffer`,
37
+ * so the single derive fold is portable across the browser (where `Buffer` is not available) and Node.
38
+ */
39
+ let cachedTextEncoder: TextEncoder | undefined;
40
+ export function utf8ByteLength(text: string): number {
41
+ // Cache one TextEncoder in the hot path (folding many stream-chunk events) to avoid allocating a new
42
+ // encoder — and the GC pressure it creates — on every call.
43
+ cachedTextEncoder ??= new TextEncoder();
44
+ return cachedTextEncoder.encode(text).length;
45
+ }
46
+
47
+ /**
48
+ * The reserved marker field that distinguishes a structured transcript-event envelope from raw
49
+ * terminal bytes. A stored chunk is decoded as a typed event ONLY when it is a JSON object carrying
50
+ * this field set to the schema version — otherwise it is retained verbatim as a raw `stream-chunk`, so
51
+ * a raw ANSI frame that happens to be valid JSON is never mis-classified. Namespaced so it cannot
52
+ * collide with a producer's own payload keys. This is the canonical single source of truth for the
53
+ * whole package family — consumers (e.g. the cockpit) import this identifier, never a private copy.
54
+ */
55
+ export const TRANSCRIPT_EVENT_MARKER = "nwfTranscriptEvent" as const;
56
+
57
+ /** The current transcript-event envelope schema version (the value {@link TRANSCRIPT_EVENT_MARKER} carries). */
58
+ export const TRANSCRIPT_EVENT_VERSION = 1 as const;
59
+
60
+ /** The core, closed set of typed transcript-event kinds. Downstream apps register extra *envelope*
61
+ * kinds via {@link mergeTranscriptVocab}, but those decoders must still return one of these core
62
+ * variants — this union itself does not grow for TypeScript consumers. */
63
+ export type TranscriptEventKind =
64
+ | "stream-chunk"
65
+ | "message"
66
+ | "tool-call"
67
+ | "tool-result"
68
+ | "turn"
69
+ | "step"
70
+ | "lifecycle";
71
+
72
+ /** The message roles the derived history distinguishes (assistant is authoritative for derivation). */
73
+ export type TranscriptRole = "assistant" | "user" | "system" | "tool";
74
+
75
+ /** Fields every typed event carries: the store offset it was decoded from. */
76
+ interface TranscriptEventBase {
77
+ readonly offset: number;
78
+ }
79
+
80
+ /** A raw terminal chunk retained verbatim for byte-level replay fidelity (the default classification). */
81
+ export interface StreamChunkEvent extends TranscriptEventBase {
82
+ readonly kind: "stream-chunk";
83
+ /** The exact stored bytes — unmodified, so raw-byte replay stays faithful. */
84
+ readonly chunk: string;
85
+ }
86
+
87
+ /** An assistant/user/system message — authoritative for the derived message history. */
88
+ export interface MessageEvent extends TranscriptEventBase {
89
+ readonly kind: "message";
90
+ readonly role: TranscriptRole;
91
+ readonly text: string;
92
+ }
93
+
94
+ /** A tool invocation the agent issued. */
95
+ export interface ToolCallEvent extends TranscriptEventBase {
96
+ readonly kind: "tool-call";
97
+ readonly name: string;
98
+ /** A stable id linking this call to its {@link ToolResultEvent}, when the producer supplies one. */
99
+ readonly callId?: string;
100
+ readonly args?: unknown;
101
+ }
102
+
103
+ /** A tool result, paired back to its {@link ToolCallEvent} by `callId` (else the most recent open call). */
104
+ export interface ToolResultEvent extends TranscriptEventBase {
105
+ readonly kind: "tool-result";
106
+ readonly callId?: string;
107
+ readonly ok: boolean;
108
+ readonly content?: string;
109
+ }
110
+
111
+ /** A turn boundary — the start of a new request/response cycle. */
112
+ export interface TurnEvent extends TranscriptEventBase {
113
+ readonly kind: "turn";
114
+ /** The producer's turn index, when supplied (else derived positionally). */
115
+ readonly index?: number;
116
+ }
117
+
118
+ /** A step boundary within a turn (a tool loop iteration, a sub-agent hop, …). */
119
+ export interface StepEvent extends TranscriptEventBase {
120
+ readonly kind: "step";
121
+ readonly label?: string;
122
+ }
123
+
124
+ /** A session lifecycle transition (open → completed, or an explicit exit). */
125
+ export interface LifecycleEvent extends TranscriptEventBase {
126
+ readonly kind: "lifecycle";
127
+ readonly phase: "open" | "completed" | "exited";
128
+ }
129
+
130
+ /** The core, closed typed transcript-event union. Merging vocab lets an app decode custom *envelope*
131
+ * kinds, but each decoder returns one of these variants — the union itself does not grow for consumers. */
132
+ export type TranscriptEvent =
133
+ | StreamChunkEvent
134
+ | MessageEvent
135
+ | ToolCallEvent
136
+ | ToolResultEvent
137
+ | TurnEvent
138
+ | StepEvent
139
+ | LifecycleEvent;
140
+
141
+ /** A stored chunk as the store/read path exposes it (mirrors `TranscriptChunk`). */
142
+ export interface StoredChunk {
143
+ readonly offset: number;
144
+ readonly chunk: string;
145
+ }
146
+
147
+ /**
148
+ * A decoder for one event kind: given the parsed envelope body and the chunk offset, it returns the
149
+ * typed event (or `undefined` to reject a malformed envelope, which then falls back to `stream-chunk`).
150
+ * A vocabulary is the map kind → decoder; {@link mergeTranscriptVocab} extends it additively.
151
+ */
152
+ export type TranscriptEventDecoder = (body: Record<string, unknown>, offset: number) => TranscriptEvent | undefined;
153
+
154
+ /** A transcript-event vocabulary: the ONE registry of kind → decoder the single parser consults. */
155
+ export type TranscriptVocab = Readonly<Record<string, TranscriptEventDecoder>>;
156
+
157
+ function str(body: Record<string, unknown>, key: string): string | undefined {
158
+ const v = body[key];
159
+ return typeof v === "string" ? v : undefined;
160
+ }
161
+
162
+ function num(body: Record<string, unknown>, key: string): number | undefined {
163
+ const v = body[key];
164
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
165
+ }
166
+
167
+ const ROLES: readonly TranscriptRole[] = ["assistant", "user", "system", "tool"];
168
+
169
+ /** Narrow an arbitrary string to a known {@link TranscriptRole}, defaulting to `assistant`. */
170
+ function toRole(value: string | undefined): TranscriptRole {
171
+ return ROLES.find((role) => role === value) ?? "assistant";
172
+ }
173
+
174
+ /** A structural guard: a non-null, non-array object is a plain record of unknown values. */
175
+ function isRecord(value: unknown): value is Record<string, unknown> {
176
+ return value !== null && typeof value === "object" && !Array.isArray(value);
177
+ }
178
+
179
+ /**
180
+ * The opinionated core vocabulary — the built-in event kinds every consumer understands out of the
181
+ * box. Authors extend it in the SAME schema via {@link mergeTranscriptVocab}; they never fork the
182
+ * parser. (`stream-chunk` is not decoded here — it is the fallback the parser applies to any chunk
183
+ * that is not a well-formed typed envelope, so raw fidelity needs no decoder.)
184
+ */
185
+ export const CORE_TRANSCRIPT_VOCAB: TranscriptVocab = Object.freeze(Object.assign(Object.create(null), {
186
+ message: (body, offset) => {
187
+ const text = str(body, "text");
188
+ if (text === undefined) return undefined;
189
+ const roleRaw = str(body, "role");
190
+ return { kind: "message", offset, role: toRole(roleRaw), text };
191
+ },
192
+ "tool-call": (body, offset) => {
193
+ const name = str(body, "name");
194
+ if (name === undefined) return undefined;
195
+ const event: ToolCallEvent = { kind: "tool-call", offset, name };
196
+ const callId = str(body, "callId");
197
+ return {
198
+ ...event,
199
+ ...(callId !== undefined ? { callId } : {}),
200
+ ...("args" in body ? { args: body.args } : {}),
201
+ };
202
+ },
203
+ "tool-result": (body, offset) => {
204
+ const ok = typeof body.ok === "boolean" ? body.ok : true;
205
+ const event: ToolResultEvent = { kind: "tool-result", offset, ok };
206
+ const callId = str(body, "callId");
207
+ const content = str(body, "content");
208
+ return {
209
+ ...event,
210
+ ...(callId !== undefined ? { callId } : {}),
211
+ ...(content !== undefined ? { content } : {}),
212
+ };
213
+ },
214
+ turn: (body, offset) => {
215
+ const index = num(body, "index");
216
+ return index !== undefined ? { kind: "turn", offset, index } : { kind: "turn", offset };
217
+ },
218
+ step: (body, offset) => {
219
+ const label = str(body, "label");
220
+ return label !== undefined ? { kind: "step", offset, label } : { kind: "step", offset };
221
+ },
222
+ lifecycle: (body, offset) => {
223
+ const phase = str(body, "phase");
224
+ if (phase !== "open" && phase !== "completed" && phase !== "exited") return undefined;
225
+ return { kind: "lifecycle", offset, phase };
226
+ },
227
+ } satisfies TranscriptVocab));
228
+
229
+ /** The core event kinds the parser decodes from an envelope (every kind except the raw `stream-chunk`
230
+ * fallback). Kept as a runtime list so the drift-guard can assert the single fold handles them all. */
231
+ export const CORE_TRANSCRIPT_EVENT_KINDS: readonly Exclude<TranscriptEventKind, "stream-chunk">[] = Object.freeze([
232
+ "message",
233
+ "tool-call",
234
+ "tool-result",
235
+ "turn",
236
+ "step",
237
+ "lifecycle",
238
+ ]);
239
+
240
+ /**
241
+ * Extend a vocabulary additively: later entries win on a key clash, so an author can either register a
242
+ * brand-new kind or deliberately override a core decoder. Returns a NEW frozen, NULL-PROTOTYPE vocab —
243
+ * neither input is mutated — so the core stays canonical AND `kind in vocab` / `Object.keys(vocab)`
244
+ * only ever see own decoders (an inherited "toString"/"constructor" key can never masquerade as one).
245
+ * This is the EXTENSION POINT a downstream app uses to add its own kind (e.g. nano-workforce#559's
246
+ * `permission`) without editing this package: one schema, extended by merge, never a second parser.
247
+ */
248
+ export function mergeTranscriptVocab(base: TranscriptVocab, ...extensions: TranscriptVocab[]): TranscriptVocab {
249
+ return Object.freeze(Object.assign(Object.create(null), base, ...extensions));
250
+ }
251
+
252
+ /**
253
+ * THE ONE PARSER. Classify a single stored chunk into a typed {@link TranscriptEvent}.
254
+ *
255
+ * A chunk is decoded as a structured event ONLY when it is a JSON object carrying the
256
+ * {@link TRANSCRIPT_EVENT_MARKER} at the current version AND a `kind` the vocab knows AND its decoder
257
+ * accepts the body. Anything else — raw terminal bytes, non-JSON, a JSON value without the marker, an
258
+ * unknown kind, a decoder rejection — is retained verbatim as a `stream-chunk`, so byte-level replay
259
+ * fidelity is never lost. This is the SINGLE point at which raw bytes become typed events; every view
260
+ * folds over the result of this function, so there is exactly one parser of the log.
261
+ */
262
+ export function parseTranscriptEvent(
263
+ entry: StoredChunk,
264
+ vocab: TranscriptVocab = CORE_TRANSCRIPT_VOCAB,
265
+ ): TranscriptEvent {
266
+ const raw: StreamChunkEvent = { kind: "stream-chunk", offset: entry.offset, chunk: entry.chunk };
267
+ const body = decodeEnvelope(entry.chunk);
268
+ if (body === undefined) return raw;
269
+ const kind = typeof body.kind === "string" ? body.kind : undefined;
270
+ if (kind === undefined) return raw;
271
+ // Own-property + typeof-function guard: `kind` is untrusted, so a bare `vocab[kind]` would resolve
272
+ // inherited members like "constructor"/"toString"/"__proto__" up the prototype chain to a
273
+ // non-decoder function and call it — a crashable (DoS) / invariant-breaking path. Only an OWN
274
+ // decoder function is ever invoked; everything else falls back to the raw stream-chunk.
275
+ const decoder = Object.prototype.hasOwnProperty.call(vocab, kind) ? vocab[kind] : undefined;
276
+ if (typeof decoder !== "function") return raw;
277
+ return decoder(body, entry.offset) ?? raw;
278
+ }
279
+
280
+ /**
281
+ * Decode a chunk into a marker-tagged envelope body, or `undefined` when it is not one. Kept private
282
+ * so `JSON.parse` of a chunk lives in exactly one place (the drift-guard depends on this).
283
+ */
284
+ function decodeEnvelope(chunk: string): Record<string, unknown> | undefined {
285
+ // Cheap reject before the parse: a valid envelope is a JSON object mentioning the marker key.
286
+ const trimmed = chunk.trimStart();
287
+ if (!trimmed.startsWith("{") || !chunk.includes(TRANSCRIPT_EVENT_MARKER)) return undefined;
288
+ let parsed: unknown;
289
+ try {
290
+ parsed = JSON.parse(chunk);
291
+ } catch {
292
+ return undefined;
293
+ }
294
+ if (!isRecord(parsed)) return undefined;
295
+ return parsed[TRANSCRIPT_EVENT_MARKER] === TRANSCRIPT_EVENT_VERSION ? parsed : undefined;
296
+ }
297
+
298
+ /**
299
+ * Encode a typed event into the stored-chunk wire form a structured producer appends. The inverse of
300
+ * {@link parseTranscriptEvent} for every non-raw kind (a `stream-chunk` is stored as its own raw bytes,
301
+ * so it is returned verbatim). Provided so producers and tests speak the one envelope grammar rather
302
+ * than hand-rolling the marker — the derivation-over-duplication rule applied to the write side too.
303
+ */
304
+ export function encodeTranscriptEvent(event: TranscriptEvent): string {
305
+ if (event.kind === "stream-chunk") return event.chunk;
306
+ const { offset: _offset, ...rest } = event;
307
+ return JSON.stringify({ [TRANSCRIPT_EVENT_MARKER]: TRANSCRIPT_EVENT_VERSION, ...rest });
308
+ }
309
+
310
+ /** A derived tool card: a tool-call paired with its result (result absent while the call is pending). */
311
+ export interface DerivedTool {
312
+ readonly name: string;
313
+ readonly callId?: string;
314
+ readonly args?: unknown;
315
+ readonly offset: number;
316
+ readonly result?: { readonly ok: boolean; readonly content?: string; readonly offset: number };
317
+ }
318
+
319
+ /** A derived message in the folded history. */
320
+ export interface DerivedMessage {
321
+ readonly role: TranscriptRole;
322
+ readonly text: string;
323
+ readonly offset: number;
324
+ }
325
+
326
+ /** A derived turn: the messages, tool cards and step count folded within one turn boundary. */
327
+ export interface DerivedTurn {
328
+ readonly index: number;
329
+ readonly startOffset: number;
330
+ readonly messages: readonly DerivedMessage[];
331
+ readonly tools: readonly DerivedTool[];
332
+ readonly steps: number;
333
+ }
334
+
335
+ /** The single derived view every higher-level consumer reads instead of re-parsing raw bytes. */
336
+ export interface DerivedView {
337
+ /** The per-turn structure (a turn is opened implicitly before the first turn event when typed content — a message, tool-call or step — precedes it; raw `stream-chunk`s alone open no turn). */
338
+ readonly turns: readonly DerivedTurn[];
339
+ /** Every message across all turns, in offset order (the flat derived history). */
340
+ readonly messages: readonly DerivedMessage[];
341
+ /** Every tool card across all turns, in offset order. */
342
+ readonly tools: readonly DerivedTool[];
343
+ /** Total retained raw bytes (UTF-8) across `stream-chunk` events — the byte-replay fidelity accounting. */
344
+ readonly rawByteLength: number;
345
+ /** Number of retained raw chunks. */
346
+ readonly rawChunkCount: number;
347
+ /** The session lifecycle as the last lifecycle event reports it (defaults to `open`). */
348
+ readonly lifecycle: "open" | "completed" | "exited";
349
+ /** Number of events folded — every event in the log, including raw `stream-chunk`s. */
350
+ readonly eventCount: number;
351
+ }
352
+
353
+ interface MutableTurn {
354
+ index: number;
355
+ startOffset: number;
356
+ messages: DerivedMessage[];
357
+ tools: DerivedTool[];
358
+ steps: number;
359
+ }
360
+
361
+ /** A pending (result-less) tool call, remembered by where it lives in both the flat `tools` list and its
362
+ * owning turn's `tools` list. Recording those positions at call time lets a later `tool-result` replace the
363
+ * pending card in both lists in O(1), instead of re-scanning every turn/tool per result (which made result
364
+ * pairing O(n²) on long transcripts). Array positions are stable because both lists only ever grow by push
365
+ * and are updated by in-place index assignment — never spliced. */
366
+ interface PendingTool {
367
+ tool: DerivedTool;
368
+ toolsIndex: number;
369
+ turn: MutableTurn;
370
+ turnToolIndex: number;
371
+ }
372
+
373
+ /**
374
+ * THE SINGLE FOLD. Derive every higher-level view from the typed event log — "the log IS the state".
375
+ *
376
+ * Folds the events (assumed in offset order — the store's append order) into per-turn structure, a flat
377
+ * message history, tool cards (each call paired to its result by `callId`, else the most recent open
378
+ * call), raw-byte accounting for replay fidelity, and the session lifecycle. It is a pure reduction of
379
+ * one log: the cockpit, search, token accounting and export all read THIS, so there is never a second
380
+ * parser of the same bytes. Typed content — a message, tool-call or step — that precedes the first
381
+ * explicit `turn` event opens an implicit turn 0, so a producer that never emits turn boundaries still
382
+ * derives a coherent single-turn view. Raw `stream-chunk` events alone open no turn (they only feed the
383
+ * byte-replay accounting), so a log of only chunks derives zero turns.
384
+ */
385
+ export function deriveView(events: Iterable<TranscriptEvent>): DerivedView {
386
+ const turns: MutableTurn[] = [];
387
+ const messages: DerivedMessage[] = [];
388
+ const tools: DerivedTool[] = [];
389
+ const openTools = new Map<string, PendingTool>();
390
+ let anonymousTool: PendingTool | undefined;
391
+ let rawByteLength = 0;
392
+ let rawChunkCount = 0;
393
+ let lifecycle: "open" | "completed" | "exited" = "open";
394
+ let eventCount = 0;
395
+ let current: MutableTurn | undefined;
396
+
397
+ const ensureTurn = (offset: number): MutableTurn => {
398
+ if (current === undefined) {
399
+ current = { index: turns.length, startOffset: offset, messages: [], tools: [], steps: 0 };
400
+ turns.push(current);
401
+ }
402
+ return current;
403
+ };
404
+
405
+ for (const event of events) {
406
+ eventCount++;
407
+ switch (event.kind) {
408
+ case "turn": {
409
+ current = { index: event.index ?? turns.length, startOffset: event.offset, messages: [], tools: [], steps: 0 };
410
+ turns.push(current);
411
+ break;
412
+ }
413
+ case "step": {
414
+ ensureTurn(event.offset).steps++;
415
+ break;
416
+ }
417
+ case "message": {
418
+ const msg: DerivedMessage = { role: event.role, text: event.text, offset: event.offset };
419
+ messages.push(msg);
420
+ ensureTurn(event.offset).messages.push(msg);
421
+ break;
422
+ }
423
+ case "tool-call": {
424
+ const tool: DerivedTool = {
425
+ name: event.name,
426
+ offset: event.offset,
427
+ ...(event.callId !== undefined ? { callId: event.callId } : {}),
428
+ ...(event.args !== undefined ? { args: event.args } : {}),
429
+ };
430
+ const toolsIndex = tools.push(tool) - 1;
431
+ const turn = ensureTurn(event.offset);
432
+ const turnToolIndex = turn.tools.push(tool) - 1;
433
+ const pending: PendingTool = { tool, toolsIndex, turn, turnToolIndex };
434
+ if (event.callId !== undefined) openTools.set(event.callId, pending);
435
+ else anonymousTool = pending;
436
+ break;
437
+ }
438
+ case "tool-result": {
439
+ const pending = event.callId !== undefined ? openTools.get(event.callId) : anonymousTool;
440
+ if (pending !== undefined) {
441
+ const resolved = withResult(pending.tool, event);
442
+ tools[pending.toolsIndex] = resolved;
443
+ pending.turn.tools[pending.turnToolIndex] = resolved;
444
+ if (event.callId !== undefined) openTools.delete(event.callId);
445
+ else anonymousTool = undefined;
446
+ }
447
+ break;
448
+ }
449
+ case "lifecycle": {
450
+ lifecycle = event.phase;
451
+ break;
452
+ }
453
+ case "stream-chunk": {
454
+ rawByteLength += utf8ByteLength(event.chunk);
455
+ rawChunkCount++;
456
+ break;
457
+ }
458
+ }
459
+ }
460
+
461
+ return {
462
+ turns: turns.map((t) => ({ index: t.index, startOffset: t.startOffset, messages: t.messages, tools: t.tools, steps: t.steps })),
463
+ messages,
464
+ tools,
465
+ rawByteLength,
466
+ rawChunkCount,
467
+ lifecycle,
468
+ eventCount,
469
+ };
470
+ }
471
+
472
+ /** Replace a pending tool with its result: a new resolved card that carries the result payload. */
473
+ function withResult(tool: DerivedTool, result: ToolResultEvent): DerivedTool {
474
+ return {
475
+ ...tool,
476
+ result: { ok: result.ok, offset: result.offset, ...(result.content !== undefined ? { content: result.content } : {}) },
477
+ };
478
+ }
479
+
480
+ /**
481
+ * Convenience: parse a run of stored chunks into typed events through {@link parseTranscriptEvent} (the
482
+ * one parser) and fold them with {@link deriveView} in a single call — the entry point a consumer uses
483
+ * to go from stored bytes to a derived view without ever touching a second parser.
484
+ */
485
+ export function deriveViewFromChunks(chunks: Iterable<StoredChunk>, vocab: TranscriptVocab = CORE_TRANSCRIPT_VOCAB): DerivedView {
486
+ function* parsed(): Generator<TranscriptEvent> {
487
+ for (const entry of chunks) yield parseTranscriptEvent(entry, vocab);
488
+ }
489
+ return deriveView(parsed());
490
+ }
@@ -39,3 +39,41 @@ export {
39
39
  TRANSCRIPT_TURN_SCHEMA_SQL,
40
40
  TRANSCRIPT_TURN_TABLE,
41
41
  } from "./schema.ts";
42
+
43
+ /**
44
+ * The transcript EVENT vocabulary + the single derive() fold (ADR 0056, #251) — the canonical,
45
+ * merge-extensible typed event grammar every Urban app consumes and extends (rather than forking).
46
+ * The marker + version constants and {@link parseTranscriptEvent} are the single source of truth the
47
+ * whole package family (e.g. the cockpit's structured-stream detection) imports from here.
48
+ */
49
+ export {
50
+ CORE_TRANSCRIPT_EVENT_KINDS,
51
+ CORE_TRANSCRIPT_VOCAB,
52
+ TRANSCRIPT_EVENT_MARKER,
53
+ TRANSCRIPT_EVENT_VERSION,
54
+ deriveView,
55
+ deriveViewFromChunks,
56
+ encodeTranscriptEvent,
57
+ mergeTranscriptVocab,
58
+ parseTranscriptEvent,
59
+ utf8ByteLength,
60
+ } from "./events.ts";
61
+ export type {
62
+ DerivedMessage,
63
+ DerivedTool,
64
+ DerivedTurn,
65
+ DerivedView,
66
+ LifecycleEvent,
67
+ MessageEvent,
68
+ StepEvent,
69
+ StoredChunk,
70
+ StreamChunkEvent,
71
+ ToolCallEvent,
72
+ ToolResultEvent,
73
+ TranscriptEvent,
74
+ TranscriptEventDecoder,
75
+ TranscriptEventKind,
76
+ TranscriptRole,
77
+ TranscriptVocab,
78
+ TurnEvent,
79
+ } from "./events.ts";