@theokit/presenter 0.2.0 → 0.3.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.
package/dist/index.d.ts CHANGED
@@ -214,4 +214,61 @@ declare class UIMessageStreamPresenter implements Presenter<UIMessageChunk> {
214
214
  markSeen(callId: string): void;
215
215
  }
216
216
 
217
- export { AGENT_OUTPUT_EVENT_TYPES, type AgentErrorEvent, type AgentFinishEvent, type AgentOutputEvent, type AgentOutputEventType, type AgentPartialToolCallEvent, type AgentReasoningEvent, type AgentStatusEvent, type AgentTextEvent, type AgentToolCallEvent, type AgentToolResultEvent, type Presenter, PresenterRegistry, type SdkMessage, type TurnMetadata, UIMessageStreamPresenter, type UIMessageStreamPresenterOptions, UnknownPresenterError, fromInteractionUpdate, fromSdkMessage, isErrorEvent, isFinishEvent, isPartialToolCallEvent, isReasoningEvent, isStatusEvent, isTextEvent, isToolCallEvent, isToolResultEvent };
217
+ /**
218
+ * `TerminalPresenter` (M50) — the terminal surface: the canonical {@link AgentOutputEvent} → plain rows
219
+ * ready for a TTY. Peer of the web `UIMessageStreamPresenter`, sourced from the SAME canonical event, so a
220
+ * terminal agent (exec / CLI / TUI) never re-translates the SDK.
221
+ *
222
+ * Returns DATA (`TerminalRow[]`), never a pre-painted string blob: the row carries its `kind` so an Ink /
223
+ * blessed / raw-TTY renderer decides styling (SRP — format here, render there). ANSI is opt-in via
224
+ * `{ ansi: true }` for consumers that write straight to a stream.
225
+ *
226
+ * @public
227
+ */
228
+ interface TerminalRow {
229
+ /** Semantic kind — the renderer maps it to a style. */
230
+ readonly kind: 'text' | 'reasoning' | 'tool' | 'tool-result' | 'tool-error' | 'error' | 'status' | 'finish';
231
+ /** The line content (already one-line-safe; no trailing newline). */
232
+ readonly text: string;
233
+ }
234
+ interface TerminalPresenterOptions {
235
+ /** Wrap rows in ANSI colors (default `false` — the renderer usually styles). */
236
+ readonly ansi?: boolean;
237
+ /** Max width for inlined tool input/result previews (default 88). */
238
+ readonly maxPreview?: number;
239
+ }
240
+ declare class TerminalPresenter implements Presenter<TerminalRow> {
241
+ #private;
242
+ readonly surface = "terminal";
243
+ constructor(options?: TerminalPresenterOptions);
244
+ present(event: AgentOutputEvent): TerminalRow[];
245
+ }
246
+
247
+ /**
248
+ * `JsonPresenter` (M51) — the API / programmatic surface: the canonical {@link AgentOutputEvent} → a
249
+ * stable, machine-readable JSON record. Third peer of the web (`UIMessageStreamPresenter`) and terminal
250
+ * (`TerminalPresenter`) surfaces, proving the contract generalizes: ONE canonical event, N surfaces.
251
+ *
252
+ * Consumers (a `--json` CLI, a webhook, a log sink) read FIELDS, never regex over rendered UI strings.
253
+ * The record keeps the canonical discriminant under `type` and is namespaced with `agent.` so it can be
254
+ * multiplexed onto a shared JSONL stream without colliding with a host's own event names.
255
+ *
256
+ * @public
257
+ */
258
+ interface JsonRecord {
259
+ /** Namespaced canonical discriminant, e.g. `agent.text` / `agent.tool-call`. */
260
+ readonly type: string;
261
+ readonly [key: string]: unknown;
262
+ }
263
+ interface JsonPresenterOptions {
264
+ /** Prefix for the `type` field (default `"agent."`). Pass `""` for bare discriminants. */
265
+ readonly namespace?: string;
266
+ }
267
+ declare class JsonPresenter implements Presenter<JsonRecord> {
268
+ #private;
269
+ readonly surface = "json";
270
+ constructor(options?: JsonPresenterOptions);
271
+ present(event: AgentOutputEvent): JsonRecord[];
272
+ }
273
+
274
+ export { AGENT_OUTPUT_EVENT_TYPES, type AgentErrorEvent, type AgentFinishEvent, type AgentOutputEvent, type AgentOutputEventType, type AgentPartialToolCallEvent, type AgentReasoningEvent, type AgentStatusEvent, type AgentTextEvent, type AgentToolCallEvent, type AgentToolResultEvent, JsonPresenter, type JsonPresenterOptions, type JsonRecord, type Presenter, PresenterRegistry, type SdkMessage, TerminalPresenter, type TerminalPresenterOptions, type TerminalRow, type TurnMetadata, UIMessageStreamPresenter, type UIMessageStreamPresenterOptions, UnknownPresenterError, fromInteractionUpdate, fromSdkMessage, isErrorEvent, isFinishEvent, isPartialToolCallEvent, isReasoningEvent, isStatusEvent, isTextEvent, isToolCallEvent, isToolResultEvent };
package/dist/index.js CHANGED
@@ -405,9 +405,125 @@ var UIMessageStreamPresenter = class {
405
405
  return out;
406
406
  }
407
407
  };
408
+
409
+ // src/presenters/terminal.ts
410
+ var ANSI = {
411
+ text: "",
412
+ reasoning: "\x1B[2m",
413
+ tool: "\x1B[36m",
414
+ "tool-result": "\x1B[2m",
415
+ "tool-error": "\x1B[31m",
416
+ error: "\x1B[31m",
417
+ status: "\x1B[35m",
418
+ finish: "\x1B[2m"
419
+ };
420
+ var RESET = "\x1B[0m";
421
+ function preview(value, max) {
422
+ const raw = typeof value === "string" ? value : safeJson(value);
423
+ const flat = raw.replace(/\s+/g, " ").trim();
424
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
425
+ }
426
+ __name(preview, "preview");
427
+ function safeJson(value) {
428
+ if (value === void 0 || value === null) return "";
429
+ try {
430
+ return JSON.stringify(value);
431
+ } catch {
432
+ return typeof value === "bigint" ? value.toString() : "";
433
+ }
434
+ }
435
+ __name(safeJson, "safeJson");
436
+ function suffix(open, value, close) {
437
+ return value === void 0 ? "" : open + value + close;
438
+ }
439
+ __name(suffix, "suffix");
440
+ var TerminalPresenter = class {
441
+ static {
442
+ __name(this, "TerminalPresenter");
443
+ }
444
+ surface = "terminal";
445
+ #ansi;
446
+ #max;
447
+ constructor(options = {}) {
448
+ this.#ansi = options.ansi ?? false;
449
+ this.#max = options.maxPreview ?? 88;
450
+ }
451
+ present(event) {
452
+ switch (event.type) {
453
+ case "text":
454
+ return event.text.length > 0 ? [
455
+ this.#row("text", event.text)
456
+ ] : [];
457
+ case "reasoning":
458
+ return event.text.length > 0 ? [
459
+ this.#row("reasoning", `\xB7 ${event.text}`)
460
+ ] : [];
461
+ case "tool-call":
462
+ return [
463
+ this.#row("tool", `\u23FA ${event.name}(${preview(event.input, this.#max)})`)
464
+ ];
465
+ case "tool-result":
466
+ return [
467
+ this.#toolResult(event.isError === true, preview(event.result, this.#max))
468
+ ];
469
+ case "error":
470
+ return [
471
+ this.#row("error", `\u2716 ${event.message}${suffix(" (", event.code, ")")}`)
472
+ ];
473
+ case "status":
474
+ return [
475
+ this.#row("status", `\u25CF ${event.status}${suffix(" \u2014 ", event.detail, "")}`)
476
+ ];
477
+ case "finish":
478
+ return [
479
+ this.#row("finish", this.#finishText(event.reason, event.usage?.totalTokens))
480
+ ];
481
+ // `partial-tool-call` streams incremental args — the committed `tool-call` renders them.
482
+ default:
483
+ return [];
484
+ }
485
+ }
486
+ #toolResult(isError, body) {
487
+ return this.#row(isError ? "tool-error" : "tool-result", ` \u23BF ${body}`);
488
+ }
489
+ #finishText(reason, tokens) {
490
+ const r = suffix(" ", reason, "");
491
+ const t = tokens === void 0 ? "" : ` \xB7 ${tokens} tokens`;
492
+ return `<<${r}${t} >>`;
493
+ }
494
+ #row(kind, text) {
495
+ return {
496
+ kind,
497
+ text: this.#ansi && ANSI[kind] !== "" ? `${ANSI[kind]}${text}${RESET}` : text
498
+ };
499
+ }
500
+ };
501
+
502
+ // src/presenters/json.ts
503
+ var JsonPresenter = class {
504
+ static {
505
+ __name(this, "JsonPresenter");
506
+ }
507
+ surface = "json";
508
+ #ns;
509
+ constructor(options = {}) {
510
+ this.#ns = options.namespace ?? "agent.";
511
+ }
512
+ present(event) {
513
+ const { type, ...payload } = event;
514
+ return [
515
+ {
516
+ type: `${this.#ns}${type}`,
517
+ ...payload
518
+ }
519
+ ];
520
+ }
521
+ };
408
522
  export {
409
523
  AGENT_OUTPUT_EVENT_TYPES,
524
+ JsonPresenter,
410
525
  PresenterRegistry,
526
+ TerminalPresenter,
411
527
  UIMessageStreamPresenter,
412
528
  UnknownPresenterError,
413
529
  fromInteractionUpdate,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent-output-event.ts","../src/presenter.ts","../src/source/from-sdk.ts","../src/presenters/ui-message-stream.ts"],"sourcesContent":["/**\n * `AgentOutputEvent` — the canonical, normalized agent-output event (M49).\n *\n * This is the **narrow waist** of theokit's presentation layer: ONE normalized event that every SOURCE\n * (the SDK's `SDKMessage` / `InteractionUpdate`) is translated INTO, and that every `Presenter`\n * (web `UIMessageStream`, terminal ANSI, JSON API) is translated OUT of. Without it you get N×M\n * translators — the current duplication where the web path and the terminal path each re-translate the\n * SDK independently and drift. The variants are derived from the SDK's own event discriminants (source\n * side), NOT from any single surface's wire format, so no surface leaks into the contract.\n *\n * @public\n */\nexport type AgentOutputEvent =\n | AgentTextEvent\n | AgentReasoningEvent\n | AgentToolCallEvent\n | AgentPartialToolCallEvent\n | AgentToolResultEvent\n | AgentErrorEvent\n | AgentFinishEvent\n | AgentStatusEvent\n\n/** Assistant text output (streamed or whole). */\nexport interface AgentTextEvent {\n readonly type: 'text'\n readonly text: string\n}\n\n/** Model reasoning / thinking content (distinct from user-visible text). */\nexport interface AgentReasoningEvent {\n readonly type: 'reasoning'\n readonly text: string\n}\n\n/** A tool invocation with its (committed) input — the args the model decided on. */\nexport interface AgentToolCallEvent {\n readonly type: 'tool-call'\n readonly callId: string\n readonly name: string\n readonly input: unknown\n}\n\n/**\n * Incremental tool input as the model streams the args (theokit-sdk#70) — a DISTINCT lifecycle point\n * from `tool-call` (args committed). Consumers that stream tool-input render the progressive args; those\n * that don't may ignore it. Never duplicates `tool-call`.\n */\nexport interface AgentPartialToolCallEvent {\n readonly type: 'partial-tool-call'\n readonly callId: string\n readonly name: string\n readonly input: unknown\n}\n\n/** The result of a tool invocation, keyed by the same `callId`. `isError` marks a failed tool. */\nexport interface AgentToolResultEvent {\n readonly type: 'tool-result'\n readonly callId: string\n readonly name: string\n readonly result: unknown\n readonly isError?: boolean\n}\n\n/** A run-level error (typed message + optional code). */\nexport interface AgentErrorEvent {\n readonly type: 'error'\n readonly message: string\n readonly code?: string\n}\n\n/** Terminal event of a turn: the run finished. `usage` carries token accounting when available. */\nexport interface AgentFinishEvent {\n readonly type: 'finish'\n readonly reason?: string\n readonly usage?: { readonly totalTokens?: number }\n}\n\n/** A lifecycle status transition (e.g. goal `active` → `completed`), surface-agnostic. */\nexport interface AgentStatusEvent {\n readonly type: 'status'\n readonly status: string\n readonly detail?: string\n}\n\n/** The stable set of variant discriminants — useful for exhaustiveness and registry keys. */\nexport const AGENT_OUTPUT_EVENT_TYPES = [\n 'text',\n 'reasoning',\n 'tool-call',\n 'partial-tool-call',\n 'tool-result',\n 'error',\n 'finish',\n 'status',\n] as const\n\nexport type AgentOutputEventType = (typeof AGENT_OUTPUT_EVENT_TYPES)[number]\n\n// --- type guards (discriminate a canonical event without a manual `switch`) ---\n\nexport const isTextEvent = (e: AgentOutputEvent): e is AgentTextEvent => e.type === 'text'\nexport const isReasoningEvent = (e: AgentOutputEvent): e is AgentReasoningEvent =>\n e.type === 'reasoning'\nexport const isToolCallEvent = (e: AgentOutputEvent): e is AgentToolCallEvent =>\n e.type === 'tool-call'\nexport const isPartialToolCallEvent = (e: AgentOutputEvent): e is AgentPartialToolCallEvent =>\n e.type === 'partial-tool-call'\nexport const isToolResultEvent = (e: AgentOutputEvent): e is AgentToolResultEvent =>\n e.type === 'tool-result'\nexport const isErrorEvent = (e: AgentOutputEvent): e is AgentErrorEvent => e.type === 'error'\nexport const isFinishEvent = (e: AgentOutputEvent): e is AgentFinishEvent => e.type === 'finish'\nexport const isStatusEvent = (e: AgentOutputEvent): e is AgentStatusEvent => e.type === 'status'\n","import type { AgentOutputEvent } from './agent-output-event.js'\n\n/**\n * `Presenter<TOut>` — the Strategy that turns the canonical {@link AgentOutputEvent} into ONE surface's\n * output (M49). Web (`UIMessageStream`), terminal (ANSI), and JSON API are peer implementations; each\n * consumes the SAME canonical event, so a source is translated once and every surface reuses it.\n *\n * The contract is **per-event, driven by the caller**: the host loops the event stream and calls\n * `present(event)` for each, so it can INTERLEAVE a presenter's pure-output chunks with framework chunks\n * (HITL approval, checkpoints, done-metadata — `@theokit/agents`) in true model order (ADR-4). Optional\n * `start()` / `finish()` bracket the stream for stateful surfaces (the web stream's `start` framing and\n * its open-block close + `finish`). A stateful presenter (web) holds its open-block state internally and\n * is therefore instantiated **per stream**; stateless presenters (terminal/json) may be singletons.\n *\n * @public\n */\nexport interface Presenter<TOut> {\n /** Stable surface key (`\"ui-message-stream\" | \"terminal\" | \"json\" | …`) — the registry resolves by it. */\n readonly surface: string\n /** Optional opening framing emitted once before any event (e.g. the web stream's `{ type: 'start' }`). */\n start?(): TOut[]\n /** Translate one canonical event into zero or more surface chunks (may maintain internal stream state). */\n present(event: AgentOutputEvent): TOut[]\n /** Optional closing framing emitted once after the last event (e.g. close the open block + `finish`). */\n finish?(): TOut[]\n}\n\n/** Thrown when a surface key is resolved but no presenter is registered for it (fail-fast, typed). */\nexport class UnknownPresenterError extends Error {\n override readonly name = 'UnknownPresenterError'\n constructor(surface: string, known: readonly string[]) {\n super(\n `No presenter registered for surface \"${surface}\". Known: ${known.join(', ') || '(none)'}.`,\n )\n }\n}\n\n/**\n * A registry of presenters keyed by surface. Lets a single agent run be driven through any registered\n * surface without the caller hard-wiring a concrete presenter (Open/Closed — add a surface by registering,\n * not by editing a switch).\n *\n * @public\n */\nexport class PresenterRegistry {\n readonly #presenters = new Map<string, Presenter<unknown>>()\n\n /** Register (or replace) the presenter for its surface. Returns `this` for fluent wiring. */\n register(presenter: Presenter<unknown>): this {\n this.#presenters.set(presenter.surface, presenter)\n return this\n }\n\n /** Whether a presenter is registered for `surface`. */\n has(surface: string): boolean {\n return this.#presenters.has(surface)\n }\n\n /** The registered surface keys. */\n surfaces(): string[] {\n return [...this.#presenters.keys()]\n }\n\n /** Resolve the presenter for `surface`, or throw {@link UnknownPresenterError} (never returns undefined). */\n resolve<TOut>(surface: string): Presenter<TOut> {\n const p = this.#presenters.get(surface)\n if (p === undefined) throw new UnknownPresenterError(surface, this.surfaces())\n return p as Presenter<TOut>\n }\n}\n","import type { InteractionUpdate } from '@theokit/sdk'\n\nimport type { AgentOutputEvent } from '../agent-output-event.js'\n\n/**\n * `fromSdk` (M49) — the SINGLE source translator: `@theokit/sdk` output → the canonical\n * {@link AgentOutputEvent}. Every presenter (web / terminal / json) consumes the result, so the SDK is\n * parsed ONCE instead of each surface re-translating it (the duplication this layer removes).\n *\n * Ported faithfully from `@theokit/agents/bridge/event-translator.ts` (the proven web-path logic), but\n * emitting the NARROW pure-output event: framework concerns (run-lifecycle, HITL approval, checkpoints,\n * devtools artifacts) are NOT SDK output and are layered by `@theokit/agents` on top (ADR-4), so they are\n * intentionally NOT produced here.\n */\n\n/** Minimal SDK message shape — duck-typed to avoid a hard import of every SDK message subtype. */\nexport interface SdkMessage {\n readonly type: string\n readonly [key: string]: unknown\n}\n\n/** Safely coerce an unknown value to a string, else the fallback. */\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback\n}\n\n/**\n * Serialize a tool's `result` for the canonical `tool-result.result`. String passthrough; null/undefined →\n * fallback; otherwise JSON. `JSON.stringify` throws on BigInt / circular refs — preserve a BigInt's real\n * value, else fall back (never `[object Object]`). Mirrors event-translator's `serializeToolOutput` (#41).\n */\nfunction serializeToolResult(value: unknown, fallback: string): string {\n if (typeof value === 'string') return value\n if (value === undefined || value === null) return fallback\n try {\n return JSON.stringify(value)\n } catch {\n return typeof value === 'bigint' ? value.toString() : fallback\n }\n}\n\nfunction fromAssistant(msg: SdkMessage): AgentOutputEvent[] {\n const events: AgentOutputEvent[] = []\n const content = (msg.message as { content?: unknown } | undefined)?.content\n if (!Array.isArray(content)) return events\n for (const block of content) {\n const b = block as { type: string; text?: string; name?: string; input?: unknown; id?: string }\n if (b.type === 'text' && b.text) events.push({ type: 'text', text: b.text })\n if (b.type === 'tool_use') {\n events.push({\n type: 'tool-call',\n callId: b.id ?? `tc-${Date.now()}`,\n name: b.name ?? 'unknown',\n input: b.input ?? {},\n })\n }\n }\n return events\n}\n\nfunction fromToolUse(msg: SdkMessage): AgentOutputEvent[] {\n const status = msg.status as string\n const callId = asString(msg.call_id, `tc-${Date.now()}`)\n const name = asString(msg.name, 'unknown')\n if (status === 'completed') {\n return [\n {\n type: 'tool-result',\n callId,\n name,\n result: serializeToolResult(msg.result, ''),\n isError: false,\n },\n ]\n }\n if (status === 'error') {\n return [\n {\n type: 'tool-result',\n callId,\n name,\n result: serializeToolResult(msg.result, 'Tool failed'),\n isError: true,\n },\n ]\n }\n if (status === 'running') {\n // Tool start — emit the committed call so the UI shows the running card. The SDK carries args in\n // `args` (theokit#58; `input`/`arguments` were never the field); keep the others as defensive fallbacks.\n return [\n { type: 'tool-call', callId, name, input: msg.args ?? msg.input ?? msg.arguments ?? {} },\n ]\n }\n return []\n}\n\nfunction fromStatus(msg: SdkMessage): AgentOutputEvent[] {\n // SDKStatusMessage: UPPERCASE cloud-run lifecycle. FINISHED/CANCELLED → finish (terminal-clean);\n // ERROR/EXPIRED → error (terminal-failure, fail-loud). CREATING/RUNNING → in-progress (no output).\n const s = msg.status as string\n if (s === 'FINISHED' || s === 'CANCELLED') return [{ type: 'finish', reason: s.toLowerCase() }]\n if (s === 'ERROR' || s === 'EXPIRED') {\n return [{ type: 'error', message: asString(msg.message, 'Agent error'), code: 'AGENT_ERROR' }]\n }\n return []\n}\n\n/** Translate ONE buffered SDK message (`run.stream()`) to zero or more canonical output events. */\nexport function fromSdkMessage(msg: SdkMessage): AgentOutputEvent[] {\n switch (msg.type) {\n case 'assistant':\n return fromAssistant(msg)\n case 'tool_call':\n return fromToolUse(msg)\n case 'thinking':\n return [{ type: 'reasoning', text: asString(msg.text, '') }]\n case 'status':\n return fromStatus(msg)\n // `system` / run-lifecycle is framework framing, not pure output — intentionally skipped (ADR-4).\n default:\n return []\n }\n}\n\n/**\n * Translate ONE real-time `onDelta` {@link InteractionUpdate} to zero or more canonical output events, in\n * arrival order — the chronological path that keeps text / tool / thinking interleaved in true model order.\n * `partial-tool-call` is surfaced distinctly (theokit-sdk#70); it never duplicates `tool-call`.\n */\nexport function fromInteractionUpdate(update: InteractionUpdate): AgentOutputEvent[] {\n switch (update.type) {\n case 'text-delta':\n return update.text ? [{ type: 'text', text: update.text }] : []\n case 'thinking-delta':\n return update.text ? [{ type: 'reasoning', text: update.text }] : []\n case 'tool-call-started':\n return [\n {\n type: 'tool-call',\n callId: update.callId,\n name: update.toolCall.name,\n input: update.toolCall.args ?? {},\n },\n ]\n case 'partial-tool-call':\n return [\n {\n type: 'partial-tool-call',\n callId: update.callId,\n name: update.toolCall.name,\n input: update.toolCall.args ?? {},\n },\n ]\n case 'tool-call-completed':\n return [\n {\n type: 'tool-result',\n callId: update.callId,\n name: update.toolCall.name,\n result: serializeToolResult(update.toolCall.result, ''),\n isError: false,\n },\n ]\n default:\n return []\n }\n}\n","import type { UIMessageChunk } from 'ai'\n\nimport type { AgentOutputEvent } from '../agent-output-event.js'\nimport type { Presenter } from '../presenter.js'\n\n/**\n * `UIMessageStreamPresenter` (M49) — the web surface: the canonical {@link AgentOutputEvent} → the Vercel\n * ai-sdk `UIMessageStream` (`UIMessageChunk`), consumed by `useChat` / assistant-ui.\n *\n * Ported faithfully from `@theokit/agents/bridge/ui-message-stream-translator.ts` (the M1 web path) with\n * ZERO behavior change for the pure-output events. Framework chunks (HITL `tool-approval-request`,\n * `data-checkpoint`) are NOT emitted here — they ride on `@theokit/agents` framework events and are\n * composed by the agents web handler around this presenter (ADR-4).\n *\n * STATEFUL (open-block state machine) → instantiate ONE per stream. The host brackets the stream with\n * {@link start} / {@link finish} and drives {@link present} per event, interleaving framework chunks.\n *\n * Chunk sequences (unchanged):\n * text run: start → text-start{id} → text-delta{id,delta}* → text-end{id} → finish\n * reasoning run: start → reasoning-start{id} → reasoning-delta{id,delta}* → reasoning-end{id} → finish\n * tool run: start → tool-input-available{callId,name,input} → tool-output-available{callId,output} → finish\n *\n * @public\n */\nexport interface TurnMetadata {\n readonly usage?: {\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly totalTokens?: number\n }\n readonly durationMs?: number\n readonly cost?: number\n}\n\nexport interface UIMessageStreamPresenterOptions {\n /** A single shared id for every text block — injected for deterministic tests (D3). */\n readonly textId: string\n}\n\nexport class UIMessageStreamPresenter implements Presenter<UIMessageChunk> {\n readonly surface = 'ui-message-stream'\n readonly #textId: string\n #openBlock: 'text' | 'reasoning' | null = null\n #reasoningId: string | null = null\n readonly #seen = new Set<string>()\n\n constructor(options: UIMessageStreamPresenterOptions) {\n this.#textId = options.textId\n }\n\n /** Emit the opening `start` chunk (exactly once, before any event). */\n start(): UIMessageChunk[] {\n return [{ type: 'start' }]\n }\n\n present(event: AgentOutputEvent): UIMessageChunk[] {\n switch (event.type) {\n case 'text':\n return this.#emitTextDelta(event.text)\n case 'reasoning':\n return this.#emitReasoningDelta(event.text)\n case 'tool-call':\n return [\n ...this.#closeOpenBlock(),\n ...this.#emitToolCall(event.callId, event.name, event.input),\n ]\n case 'tool-result':\n return [\n ...this.#closeOpenBlock(),\n ...this.#emitToolResult(event.callId, event.name, event.result, event.isError ?? false),\n ]\n case 'error':\n // Surface the failure as an ai-sdk error chunk (fail-clear); the host stops and calls finish().\n return [{ type: 'error', errorText: event.message }]\n // `partial-tool-call` streams incremental args — the current web path emits no chunk for it\n // (args are shown on the committed `tool-call`); `finish` / `status` are handled by finish()/host.\n default:\n return []\n }\n }\n\n /**\n * Close any open text/reasoning block and emit the terminal `finish` chunk. When `metadata` is given\n * (a clean run's turn totals from the framework `done`), it rides `messageMetadata`; otherwise the\n * finish is bare (error/abort turns), byte-identical to the original translator.\n */\n finish(metadata?: TurnMetadata): UIMessageChunk[] {\n const out = this.#closeOpenBlock()\n out.push(metadata ? { type: 'finish', messageMetadata: metadata } : { type: 'finish' })\n return out\n }\n\n /**\n * Close any open text/reasoning block WITHOUT finishing the stream. The host calls this before\n * interleaving a framework chunk (HITL approval / checkpoint) that must not appear inside an open text\n * block — mirroring the original translator's `closeOpenBlock` before those chunks. Idempotent.\n */\n closeBlock(): UIMessageChunk[] {\n return this.#closeOpenBlock()\n }\n\n /**\n * Whether a `callId` has already been introduced (a `tool-call` or a synthesized `tool-input`). The host\n * uses this so a framework `approval_required` reuses the EC-1 synthesize-input-first rule exactly once.\n */\n hasSeen(callId: string): boolean {\n return this.#seen.has(callId)\n }\n\n /** Mark a `callId` as introduced (the host synthesized its `tool-input` for a framework chunk). */\n markSeen(callId: string): void {\n this.#seen.add(callId)\n }\n\n // --- internal open-block state machine (verbatim from the original translator) ---\n\n #closeOpenBlock(): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (this.#openBlock === 'text') {\n out.push({ type: 'text-end', id: this.#textId })\n } else if (this.#openBlock === 'reasoning' && this.#reasoningId) {\n out.push({ type: 'reasoning-end', id: this.#reasoningId })\n }\n this.#openBlock = null\n this.#reasoningId = null\n return out\n }\n\n #emitTextDelta(content: string): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (this.#openBlock !== 'text') {\n out.push(...this.#closeOpenBlock(), { type: 'text-start', id: this.#textId })\n this.#openBlock = 'text'\n }\n out.push({ type: 'text-delta', id: this.#textId, delta: content })\n return out\n }\n\n #emitReasoningDelta(content: string): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n let reasoningId = this.#openBlock === 'reasoning' ? this.#reasoningId : null\n if (reasoningId === null) {\n out.push(...this.#closeOpenBlock())\n reasoningId = crypto.randomUUID()\n this.#reasoningId = reasoningId\n out.push({ type: 'reasoning-start', id: reasoningId })\n this.#openBlock = 'reasoning'\n }\n out.push({ type: 'reasoning-delta', id: reasoningId, delta: content })\n return out\n }\n\n #emitToolCall(callId: string, name: string, input: unknown): UIMessageChunk[] {\n this.#seen.add(callId)\n return [\n { type: 'tool-input-available', toolCallId: callId, toolName: name, input, dynamic: true },\n ]\n }\n\n #emitToolResult(\n callId: string,\n name: string,\n result: unknown,\n isError: boolean,\n ): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (!this.#seen.has(callId)) {\n this.#seen.add(callId)\n out.push({\n type: 'tool-input-available',\n toolCallId: callId,\n toolName: name,\n input: {},\n dynamic: true,\n })\n }\n // The canonical tool-result carries a serialized string `result` (from `fromSdk`).\n const output = typeof result === 'string' ? result : ''\n if (isError) {\n out.push({ type: 'tool-output-error', toolCallId: callId, errorText: output })\n } else {\n out.push({ type: 'tool-output-available', toolCallId: callId, output })\n }\n return out\n }\n}\n"],"mappings":";;;;AAqFO,IAAMA,2BAA2B;EACtC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAOK,IAAMC,cAAc,wBAACC,MAA6CA,EAAEC,SAAS,QAAzD;AACpB,IAAMC,mBAAmB,wBAACF,MAC/BA,EAAEC,SAAS,aADmB;AAEzB,IAAME,kBAAkB,wBAACH,MAC9BA,EAAEC,SAAS,aADkB;AAExB,IAAMG,yBAAyB,wBAACJ,MACrCA,EAAEC,SAAS,qBADyB;AAE/B,IAAMI,oBAAoB,wBAACL,MAChCA,EAAEC,SAAS,eADoB;AAE1B,IAAMK,eAAe,wBAACN,MAA8CA,EAAEC,SAAS,SAA1D;AACrB,IAAMM,gBAAgB,wBAACP,MAA+CA,EAAEC,SAAS,UAA3D;AACtB,IAAMO,gBAAgB,wBAACR,MAA+CA,EAAEC,SAAS,UAA3D;;;ACnFtB,IAAMQ,wBAAN,cAAoCC,MAAAA;EAD3C,OAC2CA;;;EACvBC,OAAO;EACzB,YAAYC,SAAiBC,OAA0B;AACrD,UACE,wCAAwCD,OAAAA,aAAoBC,MAAMC,KAAK,IAAA,KAAS,QAAA,GAAW;EAE/F;AACF;AASO,IAAMC,oBAAN,MAAMA;EAjBb,OAiBaA;;;EACF,cAAc,oBAAIC,IAAAA;;EAG3BC,SAASC,WAAqC;AAC5C,SAAK,YAAYC,IAAID,UAAUN,SAASM,SAAAA;AACxC,WAAO;EACT;;EAGAE,IAAIR,SAA0B;AAC5B,WAAO,KAAK,YAAYQ,IAAIR,OAAAA;EAC9B;;EAGAS,WAAqB;AACnB,WAAO;SAAI,KAAK,YAAYC,KAAI;;EAClC;;EAGAC,QAAcX,SAAkC;AAC9C,UAAMY,IAAI,KAAK,YAAYC,IAAIb,O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,UAAIC,KAAK;QAAEd,MAAM;QAAmBqB,IAAIG;MAAY,CAAA;AACpD,WAAK,aAAa;IACpB;AACAX,QAAIC,KAAK;MAAEd,MAAM;MAAmBqB,IAAIG;MAAaD,OAAOD;IAAQ,CAAA;AACpE,WAAOT;EACT;EAEA,cAAcT,QAAgBC,MAAcC,OAAc;AACxD,SAAK,MAAMc,IAAIhB,MAAAA;AACf,WAAO;MACL;QAAEJ,MAAM;QAAwB2B,YAAYvB;QAAQwB,UAAUvB;QAAMC;QAAOuB,SAAS;MAAK;;EAE7F;EAEA,gBACEzB,QACAC,MACAE,QACAC,SAAgB;AAEhB,UAAMK,MAAwB,CAAA;AAC9B,QAAI,CAAC,KAAK,MAAMK,IAAId,MAAAA,GAAS;AAC3B,WAAK,MAAMgB,IAAIhB,MAAAA;AACfS,UAAIC,KAAK;QACPd,MAAM;QACN2B,YAAYvB;QACZwB,UAAUvB;QACVC,OAAO,CAAC;QACRuB,SAAS;MACX,CAAA;IACF;AAEA,UAAMC,SAAS,OAAOvB,WAAW,WAAWA,SAAS;AACrD,QAAIC,SAAS;AACXK,UAAIC,KAAK;QAAEd,MAAM;QAAqB2B,YAAYvB;QAAQK,WAAWqB;MAAO,CAAA;IAC9E,OAAO;AACLjB,UAAIC,KAAK;QAAEd,MAAM;QAAyB2B,YAAYvB;QAAQ0B;MAAO,CAAA;IACvE;AACA,WAAOjB;EACT;AACF;","names":["AGENT_OUTPUT_EVENT_TYPES","isTextEvent","e","type","isReasoningEvent","isToolCallEvent","isPartialToolCallEvent","isToolResultEvent","isErrorEvent","isFinishEvent","isStatusEvent","UnknownPresenterError","Error","name","surface","known","join","PresenterRegistry","Map","register","presenter","set","has","surfaces","keys","resolve","p","get","undefined","asString","value","fallback","serializeToolResult","undefined","JSON","stringify","toString","fromAssistant","msg","events","content","message","Array","isArray","block","b","type","text","push","callId","id","Date","now","name","input","fromToolUse","status","call_id","result","isError","args","arguments","fromStatus","s","reason","toLowerCase","code","fromSdkMessage","fromInteractionUpdate","update","toolCall","UIMessageStreamPresenter","surface","Set","options","textId","start","type","present","event","text","callId","name","input","result","isError","errorText","message","finish","metadata","out","push","messageMetadata","closeBlock","hasSeen","has","markSeen","add","id","content","delta","reasoningId","crypto","randomUUID","toolCallId","toolName","dynamic","output"]}
1
+ {"version":3,"sources":["../src/agent-output-event.ts","../src/presenter.ts","../src/source/from-sdk.ts","../src/presenters/ui-message-stream.ts","../src/presenters/terminal.ts","../src/presenters/json.ts"],"sourcesContent":["/**\n * `AgentOutputEvent` — the canonical, normalized agent-output event (M49).\n *\n * This is the **narrow waist** of theokit's presentation layer: ONE normalized event that every SOURCE\n * (the SDK's `SDKMessage` / `InteractionUpdate`) is translated INTO, and that every `Presenter`\n * (web `UIMessageStream`, terminal ANSI, JSON API) is translated OUT of. Without it you get N×M\n * translators — the current duplication where the web path and the terminal path each re-translate the\n * SDK independently and drift. The variants are derived from the SDK's own event discriminants (source\n * side), NOT from any single surface's wire format, so no surface leaks into the contract.\n *\n * @public\n */\nexport type AgentOutputEvent =\n | AgentTextEvent\n | AgentReasoningEvent\n | AgentToolCallEvent\n | AgentPartialToolCallEvent\n | AgentToolResultEvent\n | AgentErrorEvent\n | AgentFinishEvent\n | AgentStatusEvent\n\n/** Assistant text output (streamed or whole). */\nexport interface AgentTextEvent {\n readonly type: 'text'\n readonly text: string\n}\n\n/** Model reasoning / thinking content (distinct from user-visible text). */\nexport interface AgentReasoningEvent {\n readonly type: 'reasoning'\n readonly text: string\n}\n\n/** A tool invocation with its (committed) input — the args the model decided on. */\nexport interface AgentToolCallEvent {\n readonly type: 'tool-call'\n readonly callId: string\n readonly name: string\n readonly input: unknown\n}\n\n/**\n * Incremental tool input as the model streams the args (theokit-sdk#70) — a DISTINCT lifecycle point\n * from `tool-call` (args committed). Consumers that stream tool-input render the progressive args; those\n * that don't may ignore it. Never duplicates `tool-call`.\n */\nexport interface AgentPartialToolCallEvent {\n readonly type: 'partial-tool-call'\n readonly callId: string\n readonly name: string\n readonly input: unknown\n}\n\n/** The result of a tool invocation, keyed by the same `callId`. `isError` marks a failed tool. */\nexport interface AgentToolResultEvent {\n readonly type: 'tool-result'\n readonly callId: string\n readonly name: string\n readonly result: unknown\n readonly isError?: boolean\n}\n\n/** A run-level error (typed message + optional code). */\nexport interface AgentErrorEvent {\n readonly type: 'error'\n readonly message: string\n readonly code?: string\n}\n\n/** Terminal event of a turn: the run finished. `usage` carries token accounting when available. */\nexport interface AgentFinishEvent {\n readonly type: 'finish'\n readonly reason?: string\n readonly usage?: { readonly totalTokens?: number }\n}\n\n/** A lifecycle status transition (e.g. goal `active` → `completed`), surface-agnostic. */\nexport interface AgentStatusEvent {\n readonly type: 'status'\n readonly status: string\n readonly detail?: string\n}\n\n/** The stable set of variant discriminants — useful for exhaustiveness and registry keys. */\nexport const AGENT_OUTPUT_EVENT_TYPES = [\n 'text',\n 'reasoning',\n 'tool-call',\n 'partial-tool-call',\n 'tool-result',\n 'error',\n 'finish',\n 'status',\n] as const\n\nexport type AgentOutputEventType = (typeof AGENT_OUTPUT_EVENT_TYPES)[number]\n\n// --- type guards (discriminate a canonical event without a manual `switch`) ---\n\nexport const isTextEvent = (e: AgentOutputEvent): e is AgentTextEvent => e.type === 'text'\nexport const isReasoningEvent = (e: AgentOutputEvent): e is AgentReasoningEvent =>\n e.type === 'reasoning'\nexport const isToolCallEvent = (e: AgentOutputEvent): e is AgentToolCallEvent =>\n e.type === 'tool-call'\nexport const isPartialToolCallEvent = (e: AgentOutputEvent): e is AgentPartialToolCallEvent =>\n e.type === 'partial-tool-call'\nexport const isToolResultEvent = (e: AgentOutputEvent): e is AgentToolResultEvent =>\n e.type === 'tool-result'\nexport const isErrorEvent = (e: AgentOutputEvent): e is AgentErrorEvent => e.type === 'error'\nexport const isFinishEvent = (e: AgentOutputEvent): e is AgentFinishEvent => e.type === 'finish'\nexport const isStatusEvent = (e: AgentOutputEvent): e is AgentStatusEvent => e.type === 'status'\n","import type { AgentOutputEvent } from './agent-output-event.js'\n\n/**\n * `Presenter<TOut>` — the Strategy that turns the canonical {@link AgentOutputEvent} into ONE surface's\n * output (M49). Web (`UIMessageStream`), terminal (ANSI), and JSON API are peer implementations; each\n * consumes the SAME canonical event, so a source is translated once and every surface reuses it.\n *\n * The contract is **per-event, driven by the caller**: the host loops the event stream and calls\n * `present(event)` for each, so it can INTERLEAVE a presenter's pure-output chunks with framework chunks\n * (HITL approval, checkpoints, done-metadata — `@theokit/agents`) in true model order (ADR-4). Optional\n * `start()` / `finish()` bracket the stream for stateful surfaces (the web stream's `start` framing and\n * its open-block close + `finish`). A stateful presenter (web) holds its open-block state internally and\n * is therefore instantiated **per stream**; stateless presenters (terminal/json) may be singletons.\n *\n * @public\n */\nexport interface Presenter<TOut> {\n /** Stable surface key (`\"ui-message-stream\" | \"terminal\" | \"json\" | …`) — the registry resolves by it. */\n readonly surface: string\n /** Optional opening framing emitted once before any event (e.g. the web stream's `{ type: 'start' }`). */\n start?(): TOut[]\n /** Translate one canonical event into zero or more surface chunks (may maintain internal stream state). */\n present(event: AgentOutputEvent): TOut[]\n /** Optional closing framing emitted once after the last event (e.g. close the open block + `finish`). */\n finish?(): TOut[]\n}\n\n/** Thrown when a surface key is resolved but no presenter is registered for it (fail-fast, typed). */\nexport class UnknownPresenterError extends Error {\n override readonly name = 'UnknownPresenterError'\n constructor(surface: string, known: readonly string[]) {\n super(\n `No presenter registered for surface \"${surface}\". Known: ${known.join(', ') || '(none)'}.`,\n )\n }\n}\n\n/**\n * A registry of presenters keyed by surface. Lets a single agent run be driven through any registered\n * surface without the caller hard-wiring a concrete presenter (Open/Closed — add a surface by registering,\n * not by editing a switch).\n *\n * @public\n */\nexport class PresenterRegistry {\n readonly #presenters = new Map<string, Presenter<unknown>>()\n\n /** Register (or replace) the presenter for its surface. Returns `this` for fluent wiring. */\n register(presenter: Presenter<unknown>): this {\n this.#presenters.set(presenter.surface, presenter)\n return this\n }\n\n /** Whether a presenter is registered for `surface`. */\n has(surface: string): boolean {\n return this.#presenters.has(surface)\n }\n\n /** The registered surface keys. */\n surfaces(): string[] {\n return [...this.#presenters.keys()]\n }\n\n /** Resolve the presenter for `surface`, or throw {@link UnknownPresenterError} (never returns undefined). */\n resolve<TOut>(surface: string): Presenter<TOut> {\n const p = this.#presenters.get(surface)\n if (p === undefined) throw new UnknownPresenterError(surface, this.surfaces())\n return p as Presenter<TOut>\n }\n}\n","import type { InteractionUpdate } from '@theokit/sdk'\n\nimport type { AgentOutputEvent } from '../agent-output-event.js'\n\n/**\n * `fromSdk` (M49) — the SINGLE source translator: `@theokit/sdk` output → the canonical\n * {@link AgentOutputEvent}. Every presenter (web / terminal / json) consumes the result, so the SDK is\n * parsed ONCE instead of each surface re-translating it (the duplication this layer removes).\n *\n * Ported faithfully from `@theokit/agents/bridge/event-translator.ts` (the proven web-path logic), but\n * emitting the NARROW pure-output event: framework concerns (run-lifecycle, HITL approval, checkpoints,\n * devtools artifacts) are NOT SDK output and are layered by `@theokit/agents` on top (ADR-4), so they are\n * intentionally NOT produced here.\n */\n\n/** Minimal SDK message shape — duck-typed to avoid a hard import of every SDK message subtype. */\nexport interface SdkMessage {\n readonly type: string\n readonly [key: string]: unknown\n}\n\n/** Safely coerce an unknown value to a string, else the fallback. */\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback\n}\n\n/**\n * Serialize a tool's `result` for the canonical `tool-result.result`. String passthrough; null/undefined →\n * fallback; otherwise JSON. `JSON.stringify` throws on BigInt / circular refs — preserve a BigInt's real\n * value, else fall back (never `[object Object]`). Mirrors event-translator's `serializeToolOutput` (#41).\n */\nfunction serializeToolResult(value: unknown, fallback: string): string {\n if (typeof value === 'string') return value\n if (value === undefined || value === null) return fallback\n try {\n return JSON.stringify(value)\n } catch {\n return typeof value === 'bigint' ? value.toString() : fallback\n }\n}\n\nfunction fromAssistant(msg: SdkMessage): AgentOutputEvent[] {\n const events: AgentOutputEvent[] = []\n const content = (msg.message as { content?: unknown } | undefined)?.content\n if (!Array.isArray(content)) return events\n for (const block of content) {\n const b = block as { type: string; text?: string; name?: string; input?: unknown; id?: string }\n if (b.type === 'text' && b.text) events.push({ type: 'text', text: b.text })\n if (b.type === 'tool_use') {\n events.push({\n type: 'tool-call',\n callId: b.id ?? `tc-${Date.now()}`,\n name: b.name ?? 'unknown',\n input: b.input ?? {},\n })\n }\n }\n return events\n}\n\nfunction fromToolUse(msg: SdkMessage): AgentOutputEvent[] {\n const status = msg.status as string\n const callId = asString(msg.call_id, `tc-${Date.now()}`)\n const name = asString(msg.name, 'unknown')\n if (status === 'completed') {\n return [\n {\n type: 'tool-result',\n callId,\n name,\n result: serializeToolResult(msg.result, ''),\n isError: false,\n },\n ]\n }\n if (status === 'error') {\n return [\n {\n type: 'tool-result',\n callId,\n name,\n result: serializeToolResult(msg.result, 'Tool failed'),\n isError: true,\n },\n ]\n }\n if (status === 'running') {\n // Tool start — emit the committed call so the UI shows the running card. The SDK carries args in\n // `args` (theokit#58; `input`/`arguments` were never the field); keep the others as defensive fallbacks.\n return [\n { type: 'tool-call', callId, name, input: msg.args ?? msg.input ?? msg.arguments ?? {} },\n ]\n }\n return []\n}\n\nfunction fromStatus(msg: SdkMessage): AgentOutputEvent[] {\n // SDKStatusMessage: UPPERCASE cloud-run lifecycle. FINISHED/CANCELLED → finish (terminal-clean);\n // ERROR/EXPIRED → error (terminal-failure, fail-loud). CREATING/RUNNING → in-progress (no output).\n const s = msg.status as string\n if (s === 'FINISHED' || s === 'CANCELLED') return [{ type: 'finish', reason: s.toLowerCase() }]\n if (s === 'ERROR' || s === 'EXPIRED') {\n return [{ type: 'error', message: asString(msg.message, 'Agent error'), code: 'AGENT_ERROR' }]\n }\n return []\n}\n\n/** Translate ONE buffered SDK message (`run.stream()`) to zero or more canonical output events. */\nexport function fromSdkMessage(msg: SdkMessage): AgentOutputEvent[] {\n switch (msg.type) {\n case 'assistant':\n return fromAssistant(msg)\n case 'tool_call':\n return fromToolUse(msg)\n case 'thinking':\n return [{ type: 'reasoning', text: asString(msg.text, '') }]\n case 'status':\n return fromStatus(msg)\n // `system` / run-lifecycle is framework framing, not pure output — intentionally skipped (ADR-4).\n default:\n return []\n }\n}\n\n/**\n * Translate ONE real-time `onDelta` {@link InteractionUpdate} to zero or more canonical output events, in\n * arrival order — the chronological path that keeps text / tool / thinking interleaved in true model order.\n * `partial-tool-call` is surfaced distinctly (theokit-sdk#70); it never duplicates `tool-call`.\n */\nexport function fromInteractionUpdate(update: InteractionUpdate): AgentOutputEvent[] {\n switch (update.type) {\n case 'text-delta':\n return update.text ? [{ type: 'text', text: update.text }] : []\n case 'thinking-delta':\n return update.text ? [{ type: 'reasoning', text: update.text }] : []\n case 'tool-call-started':\n return [\n {\n type: 'tool-call',\n callId: update.callId,\n name: update.toolCall.name,\n input: update.toolCall.args ?? {},\n },\n ]\n case 'partial-tool-call':\n return [\n {\n type: 'partial-tool-call',\n callId: update.callId,\n name: update.toolCall.name,\n input: update.toolCall.args ?? {},\n },\n ]\n case 'tool-call-completed':\n return [\n {\n type: 'tool-result',\n callId: update.callId,\n name: update.toolCall.name,\n result: serializeToolResult(update.toolCall.result, ''),\n isError: false,\n },\n ]\n default:\n return []\n }\n}\n","import type { UIMessageChunk } from 'ai'\n\nimport type { AgentOutputEvent } from '../agent-output-event.js'\nimport type { Presenter } from '../presenter.js'\n\n/**\n * `UIMessageStreamPresenter` (M49) — the web surface: the canonical {@link AgentOutputEvent} → the Vercel\n * ai-sdk `UIMessageStream` (`UIMessageChunk`), consumed by `useChat` / assistant-ui.\n *\n * Ported faithfully from `@theokit/agents/bridge/ui-message-stream-translator.ts` (the M1 web path) with\n * ZERO behavior change for the pure-output events. Framework chunks (HITL `tool-approval-request`,\n * `data-checkpoint`) are NOT emitted here — they ride on `@theokit/agents` framework events and are\n * composed by the agents web handler around this presenter (ADR-4).\n *\n * STATEFUL (open-block state machine) → instantiate ONE per stream. The host brackets the stream with\n * {@link start} / {@link finish} and drives {@link present} per event, interleaving framework chunks.\n *\n * Chunk sequences (unchanged):\n * text run: start → text-start{id} → text-delta{id,delta}* → text-end{id} → finish\n * reasoning run: start → reasoning-start{id} → reasoning-delta{id,delta}* → reasoning-end{id} → finish\n * tool run: start → tool-input-available{callId,name,input} → tool-output-available{callId,output} → finish\n *\n * @public\n */\nexport interface TurnMetadata {\n readonly usage?: {\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly totalTokens?: number\n }\n readonly durationMs?: number\n readonly cost?: number\n}\n\nexport interface UIMessageStreamPresenterOptions {\n /** A single shared id for every text block — injected for deterministic tests (D3). */\n readonly textId: string\n}\n\nexport class UIMessageStreamPresenter implements Presenter<UIMessageChunk> {\n readonly surface = 'ui-message-stream'\n readonly #textId: string\n #openBlock: 'text' | 'reasoning' | null = null\n #reasoningId: string | null = null\n readonly #seen = new Set<string>()\n\n constructor(options: UIMessageStreamPresenterOptions) {\n this.#textId = options.textId\n }\n\n /** Emit the opening `start` chunk (exactly once, before any event). */\n start(): UIMessageChunk[] {\n return [{ type: 'start' }]\n }\n\n present(event: AgentOutputEvent): UIMessageChunk[] {\n switch (event.type) {\n case 'text':\n return this.#emitTextDelta(event.text)\n case 'reasoning':\n return this.#emitReasoningDelta(event.text)\n case 'tool-call':\n return [\n ...this.#closeOpenBlock(),\n ...this.#emitToolCall(event.callId, event.name, event.input),\n ]\n case 'tool-result':\n return [\n ...this.#closeOpenBlock(),\n ...this.#emitToolResult(event.callId, event.name, event.result, event.isError ?? false),\n ]\n case 'error':\n // Surface the failure as an ai-sdk error chunk (fail-clear); the host stops and calls finish().\n return [{ type: 'error', errorText: event.message }]\n // `partial-tool-call` streams incremental args — the current web path emits no chunk for it\n // (args are shown on the committed `tool-call`); `finish` / `status` are handled by finish()/host.\n default:\n return []\n }\n }\n\n /**\n * Close any open text/reasoning block and emit the terminal `finish` chunk. When `metadata` is given\n * (a clean run's turn totals from the framework `done`), it rides `messageMetadata`; otherwise the\n * finish is bare (error/abort turns), byte-identical to the original translator.\n */\n finish(metadata?: TurnMetadata): UIMessageChunk[] {\n const out = this.#closeOpenBlock()\n out.push(metadata ? { type: 'finish', messageMetadata: metadata } : { type: 'finish' })\n return out\n }\n\n /**\n * Close any open text/reasoning block WITHOUT finishing the stream. The host calls this before\n * interleaving a framework chunk (HITL approval / checkpoint) that must not appear inside an open text\n * block — mirroring the original translator's `closeOpenBlock` before those chunks. Idempotent.\n */\n closeBlock(): UIMessageChunk[] {\n return this.#closeOpenBlock()\n }\n\n /**\n * Whether a `callId` has already been introduced (a `tool-call` or a synthesized `tool-input`). The host\n * uses this so a framework `approval_required` reuses the EC-1 synthesize-input-first rule exactly once.\n */\n hasSeen(callId: string): boolean {\n return this.#seen.has(callId)\n }\n\n /** Mark a `callId` as introduced (the host synthesized its `tool-input` for a framework chunk). */\n markSeen(callId: string): void {\n this.#seen.add(callId)\n }\n\n // --- internal open-block state machine (verbatim from the original translator) ---\n\n #closeOpenBlock(): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (this.#openBlock === 'text') {\n out.push({ type: 'text-end', id: this.#textId })\n } else if (this.#openBlock === 'reasoning' && this.#reasoningId) {\n out.push({ type: 'reasoning-end', id: this.#reasoningId })\n }\n this.#openBlock = null\n this.#reasoningId = null\n return out\n }\n\n #emitTextDelta(content: string): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (this.#openBlock !== 'text') {\n out.push(...this.#closeOpenBlock(), { type: 'text-start', id: this.#textId })\n this.#openBlock = 'text'\n }\n out.push({ type: 'text-delta', id: this.#textId, delta: content })\n return out\n }\n\n #emitReasoningDelta(content: string): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n let reasoningId = this.#openBlock === 'reasoning' ? this.#reasoningId : null\n if (reasoningId === null) {\n out.push(...this.#closeOpenBlock())\n reasoningId = crypto.randomUUID()\n this.#reasoningId = reasoningId\n out.push({ type: 'reasoning-start', id: reasoningId })\n this.#openBlock = 'reasoning'\n }\n out.push({ type: 'reasoning-delta', id: reasoningId, delta: content })\n return out\n }\n\n #emitToolCall(callId: string, name: string, input: unknown): UIMessageChunk[] {\n this.#seen.add(callId)\n return [\n { type: 'tool-input-available', toolCallId: callId, toolName: name, input, dynamic: true },\n ]\n }\n\n #emitToolResult(\n callId: string,\n name: string,\n result: unknown,\n isError: boolean,\n ): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (!this.#seen.has(callId)) {\n this.#seen.add(callId)\n out.push({\n type: 'tool-input-available',\n toolCallId: callId,\n toolName: name,\n input: {},\n dynamic: true,\n })\n }\n // The canonical tool-result carries a serialized string `result` (from `fromSdk`).\n const output = typeof result === 'string' ? result : ''\n if (isError) {\n out.push({ type: 'tool-output-error', toolCallId: callId, errorText: output })\n } else {\n out.push({ type: 'tool-output-available', toolCallId: callId, output })\n }\n return out\n }\n}\n","import type { AgentOutputEvent } from '../agent-output-event.js'\nimport type { Presenter } from '../presenter.js'\n\n/**\n * `TerminalPresenter` (M50) — the terminal surface: the canonical {@link AgentOutputEvent} → plain rows\n * ready for a TTY. Peer of the web `UIMessageStreamPresenter`, sourced from the SAME canonical event, so a\n * terminal agent (exec / CLI / TUI) never re-translates the SDK.\n *\n * Returns DATA (`TerminalRow[]`), never a pre-painted string blob: the row carries its `kind` so an Ink /\n * blessed / raw-TTY renderer decides styling (SRP — format here, render there). ANSI is opt-in via\n * `{ ansi: true }` for consumers that write straight to a stream.\n *\n * @public\n */\nexport interface TerminalRow {\n /** Semantic kind — the renderer maps it to a style. */\n readonly kind:\n | 'text'\n | 'reasoning'\n | 'tool'\n | 'tool-result'\n | 'tool-error'\n | 'error'\n | 'status'\n | 'finish'\n /** The line content (already one-line-safe; no trailing newline). */\n readonly text: string\n}\n\nexport interface TerminalPresenterOptions {\n /** Wrap rows in ANSI colors (default `false` — the renderer usually styles). */\n readonly ansi?: boolean\n /** Max width for inlined tool input/result previews (default 88). */\n readonly maxPreview?: number\n}\n\nconst ANSI: Record<TerminalRow['kind'], string> = {\n text: '',\n reasoning: '\\x1b[2m', // dim\n tool: '\\x1b[36m', // cyan\n 'tool-result': '\\x1b[2m',\n 'tool-error': '\\x1b[31m', // red\n error: '\\x1b[31m',\n status: '\\x1b[35m', // magenta\n finish: '\\x1b[2m',\n}\nconst RESET = '\\x1b[0m'\n\n/** One-line, width-capped preview of an arbitrary value (tool input/result). */\nfunction preview(value: unknown, max: number): string {\n const raw = typeof value === 'string' ? value : safeJson(value)\n const flat = raw.replace(/\\s+/g, ' ').trim()\n return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat\n}\n\nfunction safeJson(value: unknown): string {\n if (value === undefined || value === null) return ''\n try {\n return JSON.stringify(value)\n } catch {\n return typeof value === 'bigint' ? value.toString() : ''\n }\n}\n\n/** Build an optional ` (code)` / ` — detail` suffix without nesting template literals. */\nfunction suffix(open: string, value: string | undefined, close: string): string {\n return value === undefined ? '' : open + value + close\n}\n\nexport class TerminalPresenter implements Presenter<TerminalRow> {\n readonly surface = 'terminal'\n readonly #ansi: boolean\n readonly #max: number\n\n constructor(options: TerminalPresenterOptions = {}) {\n this.#ansi = options.ansi ?? false\n this.#max = options.maxPreview ?? 88\n }\n\n present(event: AgentOutputEvent): TerminalRow[] {\n switch (event.type) {\n case 'text':\n return event.text.length > 0 ? [this.#row('text', event.text)] : []\n case 'reasoning':\n return event.text.length > 0 ? [this.#row('reasoning', `\\u00b7 ${event.text}`)] : []\n case 'tool-call':\n return [this.#row('tool', `\\u23fa ${event.name}(${preview(event.input, this.#max)})`)]\n case 'tool-result':\n return [this.#toolResult(event.isError === true, preview(event.result, this.#max))]\n case 'error':\n return [this.#row('error', `\\u2716 ${event.message}${suffix(' (', event.code, ')')}`)]\n case 'status':\n return [\n this.#row('status', `\\u25cf ${event.status}${suffix(' \\u2014 ', event.detail, '')}`),\n ]\n case 'finish':\n return [this.#row('finish', this.#finishText(event.reason, event.usage?.totalTokens))]\n // `partial-tool-call` streams incremental args — the committed `tool-call` renders them.\n default:\n return []\n }\n }\n\n #toolResult(isError: boolean, body: string): TerminalRow {\n return this.#row(isError ? 'tool-error' : 'tool-result', ` \\u23bf ${body}`)\n }\n\n #finishText(reason: string | undefined, tokens: number | undefined): string {\n const r = suffix(' ', reason, '')\n const t = tokens === undefined ? '' : ` \\u00b7 ${tokens} tokens`\n return `<<${r}${t} >>`\n }\n\n #row(kind: TerminalRow['kind'], text: string): TerminalRow {\n return { kind, text: this.#ansi && ANSI[kind] !== '' ? `${ANSI[kind]}${text}${RESET}` : text }\n }\n}\n","import type { AgentOutputEvent } from '../agent-output-event.js'\nimport type { Presenter } from '../presenter.js'\n\n/**\n * `JsonPresenter` (M51) — the API / programmatic surface: the canonical {@link AgentOutputEvent} → a\n * stable, machine-readable JSON record. Third peer of the web (`UIMessageStreamPresenter`) and terminal\n * (`TerminalPresenter`) surfaces, proving the contract generalizes: ONE canonical event, N surfaces.\n *\n * Consumers (a `--json` CLI, a webhook, a log sink) read FIELDS, never regex over rendered UI strings.\n * The record keeps the canonical discriminant under `type` and is namespaced with `agent.` so it can be\n * multiplexed onto a shared JSONL stream without colliding with a host's own event names.\n *\n * @public\n */\nexport interface JsonRecord {\n /** Namespaced canonical discriminant, e.g. `agent.text` / `agent.tool-call`. */\n readonly type: string\n readonly [key: string]: unknown\n}\n\nexport interface JsonPresenterOptions {\n /** Prefix for the `type` field (default `\"agent.\"`). Pass `\"\"` for bare discriminants. */\n readonly namespace?: string\n}\n\nexport class JsonPresenter implements Presenter<JsonRecord> {\n readonly surface = 'json'\n readonly #ns: string\n\n constructor(options: JsonPresenterOptions = {}) {\n this.#ns = options.namespace ?? 'agent.'\n }\n\n present(event: AgentOutputEvent): JsonRecord[] {\n // The canonical event IS already a flat, typed record — the JSON surface only namespaces the\n // discriminant and passes the payload through verbatim (no lossy re-shaping).\n const { type, ...payload } = event\n return [{ type: `${this.#ns}${type}`, ...payload }]\n }\n}\n"],"mappings":";;;;AAqFO,IAAMA,2BAA2B;EACtC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAOK,IAAMC,cAAc,wBAACC,MAA6CA,EAAEC,SAAS,QAAzD;A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,QAA0B;AAChE,UAAMC,IAAIvB,OAAO,KAAKkB,QAAQ,EAAA;AAC9B,UAAMM,IAAIF,WAAW1B,SAAY,KAAK,SAAW0B,MAAAA;AACjD,WAAO,KAAKC,CAAAA,GAAIC,CAAAA;EAClB;EAEA,KAAKC,MAA2B9C,MAAY;AAC1C,WAAO;MAAE8C;MAAM9C,MAAM,KAAK,SAASD,KAAK+C,IAAAA,MAAU,KAAK,GAAG/C,KAAK+C,IAAAA,CAAK,GAAG9C,IAAAA,GAAOM,KAAAA,KAAUN;IAAK;EAC/F;AACF;;;AC3FO,IAAM+C,gBAAN,MAAMA;EAAb,OAAaA;;;EACFC,UAAU;EACV;EAET,YAAYC,UAAgC,CAAC,GAAG;AAC9C,SAAK,MAAMA,QAAQC,aAAa;EAClC;EAEAC,QAAQC,OAAuC;AAG7C,UAAM,EAAEC,MAAM,GAAGC,QAAAA,IAAYF;AAC7B,WAAO;MAAC;QAAEC,MAAM,GAAG,KAAK,GAAG,GAAGA,IAAAA;QAAQ,GAAGC;MAAQ;;EACnD;AACF;","names":["AGENT_OUTPUT_EVENT_TYPES","isTextEvent","e","type","isReasoningEvent","isToolCallEvent","isPartialToolCallEvent","isToolResultEvent","isErrorEvent","isFinishEvent","isStatusEvent","UnknownPresenterError","Error","name","surface","known","join","PresenterRegistry","Map","register","presenter","set","has","surfaces","keys","resolve","p","get","undefined","asString","value","fallback","serializeToolResult","undefined","JSON","stringify","toString","fromAssistant","msg","events","content","message","Array","isArray","block","b","type","text","push","callId","id","Date","now","name","input","fromToolUse","status","call_id","result","isError","args","arguments","fromStatus","s","reason","toLowerCase","code","fromSdkMessage","fromInteractionUpdate","update","toolCall","UIMessageStreamPresenter","surface","Set","options","textId","start","type","present","event","text","callId","name","input","result","isError","errorText","message","finish","metadata","out","push","messageMetadata","closeBlock","hasSeen","has","markSeen","add","id","content","delta","reasoningId","crypto","randomUUID","toolCallId","toolName","dynamic","output","ANSI","text","reasoning","tool","error","status","finish","RESET","preview","value","max","raw","safeJson","flat","replace","trim","length","slice","undefined","JSON","stringify","toString","suffix","open","close","TerminalPresenter","surface","options","ansi","maxPreview","present","event","type","name","input","isError","result","message","code","detail","reason","usage","totalTokens","body","tokens","r","t","kind","JsonPresenter","surface","options","namespace","present","event","type","payload"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/presenter",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "TheoKit's presentation layer — the canonical AgentOutputEvent + Presenter Strategy that turns @theokit/sdk agent output into any surface (web UIMessageStream, terminal ANSI, JSON API) from ONE normalized event.",
5
5
  "type": "module",
6
6
  "sideEffects": false,