@theokit/presenter 0.3.0 → 0.4.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/chunk-Z4QWC7IK.js +7 -0
- package/dist/chunk-Z4QWC7IK.js.map +1 -0
- package/dist/chunk-schema-PuUWBfl_.d.ts +131 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/wire/index.d.ts +78 -0
- package/dist/wire/index.js +331 -0
- package/dist/wire/index.js.map +1 -0
- package/package.json +9 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
declare const fixedChunkSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
4
|
+
type: z.ZodLiteral<"start">;
|
|
5
|
+
messageId: z.ZodOptional<z.ZodString>;
|
|
6
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
7
|
+
type: z.ZodLiteral<"text-start">;
|
|
8
|
+
id: z.ZodString;
|
|
9
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
10
|
+
type: z.ZodLiteral<"text-delta">;
|
|
11
|
+
id: z.ZodString;
|
|
12
|
+
delta: z.ZodString;
|
|
13
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
14
|
+
type: z.ZodLiteral<"text-end">;
|
|
15
|
+
id: z.ZodString;
|
|
16
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
17
|
+
type: z.ZodLiteral<"reasoning-start">;
|
|
18
|
+
id: z.ZodString;
|
|
19
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
20
|
+
type: z.ZodLiteral<"reasoning-delta">;
|
|
21
|
+
id: z.ZodString;
|
|
22
|
+
delta: z.ZodString;
|
|
23
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
24
|
+
type: z.ZodLiteral<"reasoning-end">;
|
|
25
|
+
id: z.ZodString;
|
|
26
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
27
|
+
type: z.ZodLiteral<"tool-input-available">;
|
|
28
|
+
toolCallId: z.ZodString;
|
|
29
|
+
toolName: z.ZodString;
|
|
30
|
+
input: z.ZodUnknown;
|
|
31
|
+
dynamic: z.ZodOptional<z.ZodBoolean>;
|
|
32
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
33
|
+
type: z.ZodLiteral<"tool-output-available">;
|
|
34
|
+
toolCallId: z.ZodString;
|
|
35
|
+
output: z.ZodUnknown;
|
|
36
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
37
|
+
type: z.ZodLiteral<"tool-output-error">;
|
|
38
|
+
toolCallId: z.ZodString;
|
|
39
|
+
errorText: z.ZodString;
|
|
40
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
41
|
+
type: z.ZodLiteral<"tool-approval-request">;
|
|
42
|
+
approvalId: z.ZodString;
|
|
43
|
+
toolCallId: z.ZodString;
|
|
44
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
45
|
+
type: z.ZodLiteral<"error">;
|
|
46
|
+
errorText: z.ZodOptional<z.ZodString>;
|
|
47
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
48
|
+
type: z.ZodLiteral<"finish">;
|
|
49
|
+
messageMetadata: z.ZodOptional<z.ZodUnknown>;
|
|
50
|
+
}, z.core.$strip>], "type">;
|
|
51
|
+
declare const wireChunkSchema: z.ZodUnion<readonly [z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
52
|
+
type: z.ZodLiteral<"start">;
|
|
53
|
+
messageId: z.ZodOptional<z.ZodString>;
|
|
54
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
55
|
+
type: z.ZodLiteral<"text-start">;
|
|
56
|
+
id: z.ZodString;
|
|
57
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
58
|
+
type: z.ZodLiteral<"text-delta">;
|
|
59
|
+
id: z.ZodString;
|
|
60
|
+
delta: z.ZodString;
|
|
61
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
62
|
+
type: z.ZodLiteral<"text-end">;
|
|
63
|
+
id: z.ZodString;
|
|
64
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
65
|
+
type: z.ZodLiteral<"reasoning-start">;
|
|
66
|
+
id: z.ZodString;
|
|
67
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
68
|
+
type: z.ZodLiteral<"reasoning-delta">;
|
|
69
|
+
id: z.ZodString;
|
|
70
|
+
delta: z.ZodString;
|
|
71
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
72
|
+
type: z.ZodLiteral<"reasoning-end">;
|
|
73
|
+
id: z.ZodString;
|
|
74
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
75
|
+
type: z.ZodLiteral<"tool-input-available">;
|
|
76
|
+
toolCallId: z.ZodString;
|
|
77
|
+
toolName: z.ZodString;
|
|
78
|
+
input: z.ZodUnknown;
|
|
79
|
+
dynamic: z.ZodOptional<z.ZodBoolean>;
|
|
80
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
81
|
+
type: z.ZodLiteral<"tool-output-available">;
|
|
82
|
+
toolCallId: z.ZodString;
|
|
83
|
+
output: z.ZodUnknown;
|
|
84
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
85
|
+
type: z.ZodLiteral<"tool-output-error">;
|
|
86
|
+
toolCallId: z.ZodString;
|
|
87
|
+
errorText: z.ZodString;
|
|
88
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
89
|
+
type: z.ZodLiteral<"tool-approval-request">;
|
|
90
|
+
approvalId: z.ZodString;
|
|
91
|
+
toolCallId: z.ZodString;
|
|
92
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
93
|
+
type: z.ZodLiteral<"error">;
|
|
94
|
+
errorText: z.ZodOptional<z.ZodString>;
|
|
95
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
96
|
+
type: z.ZodLiteral<"finish">;
|
|
97
|
+
messageMetadata: z.ZodOptional<z.ZodUnknown>;
|
|
98
|
+
}, z.core.$strip>], "type">, z.ZodObject<{
|
|
99
|
+
type: z.ZodCustom<`data-${string}`, `data-${string}`>;
|
|
100
|
+
data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
101
|
+
transient: z.ZodOptional<z.ZodBoolean>;
|
|
102
|
+
}, z.core.$strip>]>;
|
|
103
|
+
/**
|
|
104
|
+
* A `data-*` transport part, declared as a type rather than inferred.
|
|
105
|
+
*
|
|
106
|
+
* `z.infer` over the `z.custom` discriminant does not narrow: a `switch (chunk.type)` on the union
|
|
107
|
+
* kept degrading every fixed variant's fields to `unknown`. Declaring the member explicitly gives
|
|
108
|
+
* TypeScript the literal template it needs to exclude this arm. The runtime contract still comes
|
|
109
|
+
* from `dataPartSchema` — the split is between what validates (zod) and what narrows (this type),
|
|
110
|
+
* not two competing sources of truth.
|
|
111
|
+
*/
|
|
112
|
+
interface WireDataPart {
|
|
113
|
+
readonly type: `data-${string}`;
|
|
114
|
+
readonly data: Record<string, unknown>;
|
|
115
|
+
readonly transient?: boolean;
|
|
116
|
+
}
|
|
117
|
+
/** A validated frame of the wire. The fixed arms are derived from the schema (`G3`). */
|
|
118
|
+
type WireChunk = z.infer<typeof fixedChunkSchema> | WireDataPart;
|
|
119
|
+
/**
|
|
120
|
+
* The literal discriminators this package speaks, in declaration order.
|
|
121
|
+
*
|
|
122
|
+
* `scripts/check-wire-parity.mjs` diffs this list against the `ai` union to notice a variant that
|
|
123
|
+
* appeared upstream and that we have not mirrored. It is exported (rather than derived at the call
|
|
124
|
+
* site) so the gate and the schema cannot drift apart — a gate comparing a stale list is a gate
|
|
125
|
+
* whose verdict means nothing.
|
|
126
|
+
*/
|
|
127
|
+
declare const WIRE_CHUNK_TYPES: readonly string[];
|
|
128
|
+
/** `data-*` parts are matched by shape, not by an enumerated name — the family is open by design. */
|
|
129
|
+
declare const WIRE_DATA_PART_PREFIX = "data-";
|
|
130
|
+
|
|
131
|
+
export { type WireChunk as W, WIRE_CHUNK_TYPES as a, WIRE_DATA_PART_PREFIX as b, type WireDataPart as c, wireChunkSchema as w };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { InteractionUpdate } from '@theokit/sdk';
|
|
2
|
-
import {
|
|
2
|
+
import { W as WireChunk } from './chunk-schema-PuUWBfl_.js';
|
|
3
|
+
import 'zod';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* `AgentOutputEvent` — the canonical, normalized agent-output event (M49).
|
|
@@ -154,6 +155,11 @@ declare function fromSdkMessage(msg: SdkMessage): AgentOutputEvent[];
|
|
|
154
155
|
*/
|
|
155
156
|
declare function fromInteractionUpdate(update: InteractionUpdate): AgentOutputEvent[];
|
|
156
157
|
|
|
158
|
+
/**
|
|
159
|
+
* The frame type is TheoKit's own since the `remover-dependencia-ai` plan; it is structurally the
|
|
160
|
+
* ai-sdk `UIMessageChunk`, so the emitted wire is unchanged and an ai-sdk client still reads it.
|
|
161
|
+
*/
|
|
162
|
+
type UIMessageChunk = WireChunk;
|
|
157
163
|
/**
|
|
158
164
|
* `UIMessageStreamPresenter` (M49) — the web surface: the canonical {@link AgentOutputEvent} → the Vercel
|
|
159
165
|
* ai-sdk `UIMessageStream` (`UIMessageChunk`), consumed by `useChat` / assistant-ui.
|
package/dist/index.js
CHANGED
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","../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;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,wCAA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,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"]}
|
|
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"],"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,M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B,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"]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { W as WireChunk } from '../chunk-schema-PuUWBfl_.js';
|
|
2
|
+
export { a as WIRE_CHUNK_TYPES, b as WIRE_DATA_PART_PREFIX, c as WireDataPart, w as wireChunkSchema } from '../chunk-schema-PuUWBfl_.js';
|
|
3
|
+
import 'zod';
|
|
4
|
+
|
|
5
|
+
/** A failure the SERVER reported inside the stream (theokit#136) — never swallowed. */
|
|
6
|
+
declare class WireStreamError extends Error {
|
|
7
|
+
readonly name = "WireStreamError";
|
|
8
|
+
}
|
|
9
|
+
/** A frame that never terminated. Typed so a caller can tell it from a protocol error. */
|
|
10
|
+
declare class WireFrameTooLargeError extends Error {
|
|
11
|
+
readonly name = "WireFrameTooLargeError";
|
|
12
|
+
}
|
|
13
|
+
interface ParseWireStreamOptions {
|
|
14
|
+
readonly maxFrameBytes?: number;
|
|
15
|
+
/** Where discarded frames are reported. Defaults to a no-op: a library must not own the console. */
|
|
16
|
+
readonly onWarn?: (message: string) => void;
|
|
17
|
+
}
|
|
18
|
+
declare function parseWireStream(bytes: ReadableStream<Uint8Array>, options?: ParseWireStreamOptions): ReadableStream<WireChunk>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The public shape of a reconstructed message and of a transport, owned by TheoKit.
|
|
22
|
+
*
|
|
23
|
+
* These mirror `ai`'s `UIMessage` / `ChatTransport` structurally — measured: the ai-sdk declarations
|
|
24
|
+
* carry no brands (`index.d.ts:1798` and `:5350`; every `unique symbol` in that file sits at 3149+,
|
|
25
|
+
* after both), so a faithful mirror is assignment-compatible and a consumer that still types against
|
|
26
|
+
* `ai` keeps compiling.
|
|
27
|
+
*
|
|
28
|
+
* The compatibility we OWE is one-directional: our concrete transports must satisfy
|
|
29
|
+
* `ChatTransport`. Demanding equivalence in both directions would be unachievable by construction —
|
|
30
|
+
* we deliberately mirror only the subset TheoKit speaks, so our type has fewer members.
|
|
31
|
+
*/
|
|
32
|
+
type WireMessageRole = 'system' | 'user' | 'assistant';
|
|
33
|
+
/** A reconstructed part. Open by design: the `data-*` family and future part kinds ride here. */
|
|
34
|
+
interface WireMessagePart {
|
|
35
|
+
readonly type: string;
|
|
36
|
+
readonly [key: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
interface WireMessage<METADATA = unknown> {
|
|
39
|
+
id: string;
|
|
40
|
+
role: WireMessageRole;
|
|
41
|
+
metadata?: METADATA;
|
|
42
|
+
parts: WireMessagePart[];
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The transport seam. Supersedes the use of `ai`'s `ChatTransport` as our published interface
|
|
46
|
+
* (ADR-0050 D1 said "do NOT invent a parallel interface" — this plan reverses that deliberately).
|
|
47
|
+
*/
|
|
48
|
+
interface WireTransport<M extends WireMessage = WireMessage> {
|
|
49
|
+
sendMessages(options: WireSendOptions<M>): Promise<ReadableStream<WireChunk>>;
|
|
50
|
+
reconnectToStream(options: WireReconnectOptions): Promise<ReadableStream<WireChunk> | null>;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* `headers` is typed rather than swallowed by the index signature.
|
|
54
|
+
*
|
|
55
|
+
* The catch-all `[key: string]: unknown` widens every named field to `unknown` for a consumer that
|
|
56
|
+
* spreads it, which broke `HttpTransport`'s header merge at compile time. Naming the fields the
|
|
57
|
+
* transports actually read keeps them typed; the index signature stays for the per-request extras
|
|
58
|
+
* the request-context work (ADR-0052) passes through.
|
|
59
|
+
*/
|
|
60
|
+
type WireHeaders = Record<string, string> | Headers;
|
|
61
|
+
interface WireSendOptions<M extends WireMessage = WireMessage> {
|
|
62
|
+
readonly chatId: string;
|
|
63
|
+
readonly messages: M[];
|
|
64
|
+
readonly abortSignal?: AbortSignal;
|
|
65
|
+
readonly headers?: WireHeaders;
|
|
66
|
+
readonly body?: unknown;
|
|
67
|
+
readonly metadata?: unknown;
|
|
68
|
+
readonly [key: string]: unknown;
|
|
69
|
+
}
|
|
70
|
+
interface WireReconnectOptions {
|
|
71
|
+
readonly chatId: string;
|
|
72
|
+
readonly headers?: WireHeaders;
|
|
73
|
+
readonly [key: string]: unknown;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
declare function readMessageStream(chunks: ReadableStream<WireChunk>): AsyncGenerator<WireMessage>;
|
|
77
|
+
|
|
78
|
+
export { type ParseWireStreamOptions, WireChunk, WireFrameTooLargeError, type WireHeaders, type WireMessage, type WireMessagePart, type WireMessageRole, type WireReconnectOptions, type WireSendOptions, WireStreamError, type WireTransport, parseWireStream, readMessageStream };
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "../chunk-Z4QWC7IK.js";
|
|
4
|
+
|
|
5
|
+
// src/wire/chunk-schema.ts
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
var dataPartSchema = z.object({
|
|
8
|
+
type: z.custom((v) => typeof v === "string" && /^data-[a-z][a-z0-9-]*$/.test(v)),
|
|
9
|
+
data: z.record(z.string(), z.unknown()),
|
|
10
|
+
transient: z.boolean().optional()
|
|
11
|
+
});
|
|
12
|
+
var fixedChunkSchema = z.discriminatedUnion("type", [
|
|
13
|
+
z.object({
|
|
14
|
+
type: z.literal("start"),
|
|
15
|
+
messageId: z.string().optional()
|
|
16
|
+
}),
|
|
17
|
+
z.object({
|
|
18
|
+
type: z.literal("text-start"),
|
|
19
|
+
id: z.string()
|
|
20
|
+
}),
|
|
21
|
+
z.object({
|
|
22
|
+
type: z.literal("text-delta"),
|
|
23
|
+
id: z.string(),
|
|
24
|
+
delta: z.string()
|
|
25
|
+
}),
|
|
26
|
+
z.object({
|
|
27
|
+
type: z.literal("text-end"),
|
|
28
|
+
id: z.string()
|
|
29
|
+
}),
|
|
30
|
+
z.object({
|
|
31
|
+
type: z.literal("reasoning-start"),
|
|
32
|
+
id: z.string()
|
|
33
|
+
}),
|
|
34
|
+
z.object({
|
|
35
|
+
type: z.literal("reasoning-delta"),
|
|
36
|
+
id: z.string(),
|
|
37
|
+
delta: z.string()
|
|
38
|
+
}),
|
|
39
|
+
z.object({
|
|
40
|
+
type: z.literal("reasoning-end"),
|
|
41
|
+
id: z.string()
|
|
42
|
+
}),
|
|
43
|
+
z.object({
|
|
44
|
+
type: z.literal("tool-input-available"),
|
|
45
|
+
toolCallId: z.string(),
|
|
46
|
+
toolName: z.string(),
|
|
47
|
+
input: z.unknown(),
|
|
48
|
+
dynamic: z.boolean().optional()
|
|
49
|
+
}),
|
|
50
|
+
z.object({
|
|
51
|
+
type: z.literal("tool-output-available"),
|
|
52
|
+
toolCallId: z.string(),
|
|
53
|
+
output: z.unknown()
|
|
54
|
+
}),
|
|
55
|
+
z.object({
|
|
56
|
+
type: z.literal("tool-output-error"),
|
|
57
|
+
toolCallId: z.string(),
|
|
58
|
+
errorText: z.string()
|
|
59
|
+
}),
|
|
60
|
+
// HITL — the standalone gate keyed by its own id, distinct from the tool-call id.
|
|
61
|
+
z.object({
|
|
62
|
+
type: z.literal("tool-approval-request"),
|
|
63
|
+
approvalId: z.string(),
|
|
64
|
+
toolCallId: z.string()
|
|
65
|
+
}),
|
|
66
|
+
// `errorText` is optional: a malformed error frame must still be RECOGNISED as an error so the
|
|
67
|
+
// reader can reject. Requiring the field would push it into the discard path and turn a real
|
|
68
|
+
// provider failure into silence — theokit#136 through a side door.
|
|
69
|
+
z.object({
|
|
70
|
+
type: z.literal("error"),
|
|
71
|
+
errorText: z.string().optional()
|
|
72
|
+
}),
|
|
73
|
+
z.object({
|
|
74
|
+
type: z.literal("finish"),
|
|
75
|
+
messageMetadata: z.unknown().optional()
|
|
76
|
+
})
|
|
77
|
+
]);
|
|
78
|
+
var wireChunkSchema = z.union([
|
|
79
|
+
fixedChunkSchema,
|
|
80
|
+
dataPartSchema
|
|
81
|
+
]);
|
|
82
|
+
var WIRE_CHUNK_TYPES = [
|
|
83
|
+
"start",
|
|
84
|
+
"text-start",
|
|
85
|
+
"text-delta",
|
|
86
|
+
"text-end",
|
|
87
|
+
"reasoning-start",
|
|
88
|
+
"reasoning-delta",
|
|
89
|
+
"reasoning-end",
|
|
90
|
+
"tool-input-available",
|
|
91
|
+
"tool-output-available",
|
|
92
|
+
"tool-output-error",
|
|
93
|
+
"tool-approval-request",
|
|
94
|
+
"error",
|
|
95
|
+
"finish"
|
|
96
|
+
];
|
|
97
|
+
var WIRE_DATA_PART_PREFIX = "data-";
|
|
98
|
+
|
|
99
|
+
// src/wire/parse-wire-stream.ts
|
|
100
|
+
var DONE_SENTINEL = "[DONE]";
|
|
101
|
+
var DEFAULT_MAX_FRAME_BYTES = 1e6;
|
|
102
|
+
var WireStreamError = class extends Error {
|
|
103
|
+
static {
|
|
104
|
+
__name(this, "WireStreamError");
|
|
105
|
+
}
|
|
106
|
+
name = "WireStreamError";
|
|
107
|
+
};
|
|
108
|
+
var WireFrameTooLargeError = class extends Error {
|
|
109
|
+
static {
|
|
110
|
+
__name(this, "WireFrameTooLargeError");
|
|
111
|
+
}
|
|
112
|
+
name = "WireFrameTooLargeError";
|
|
113
|
+
};
|
|
114
|
+
function normalizeEol(text) {
|
|
115
|
+
return text.replace(/\r\n|\r/g, "\n");
|
|
116
|
+
}
|
|
117
|
+
__name(normalizeEol, "normalizeEol");
|
|
118
|
+
function joinDataLines(event) {
|
|
119
|
+
const out = [];
|
|
120
|
+
for (const line of event.split("\n")) {
|
|
121
|
+
if (line.startsWith(":")) continue;
|
|
122
|
+
if (!line.startsWith("data:")) continue;
|
|
123
|
+
out.push(line.slice("data:".length).replace(/^ /, ""));
|
|
124
|
+
}
|
|
125
|
+
return out.join("\n");
|
|
126
|
+
}
|
|
127
|
+
__name(joinDataLines, "joinDataLines");
|
|
128
|
+
function parseWireStream(bytes, options = {}) {
|
|
129
|
+
const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
|
|
130
|
+
const warn = options.onWarn ?? (() => void 0);
|
|
131
|
+
const decoder = new TextDecoderStream();
|
|
132
|
+
const reader = bytes.pipeThrough(decoder).getReader();
|
|
133
|
+
let buffer = "";
|
|
134
|
+
const drain = /* @__PURE__ */ __name((controller) => {
|
|
135
|
+
let emitted = 0;
|
|
136
|
+
let cut = buffer.indexOf("\n\n");
|
|
137
|
+
while (cut !== -1) {
|
|
138
|
+
const event = buffer.slice(0, cut);
|
|
139
|
+
buffer = buffer.slice(cut + 2);
|
|
140
|
+
cut = buffer.indexOf("\n\n");
|
|
141
|
+
const payload = joinDataLines(event);
|
|
142
|
+
if (payload === "" || payload === DONE_SENTINEL) continue;
|
|
143
|
+
let raw;
|
|
144
|
+
try {
|
|
145
|
+
raw = JSON.parse(payload);
|
|
146
|
+
} catch {
|
|
147
|
+
warn(`wire: frame com JSON inv\xE1lido descartado (${payload.slice(0, 60)})`);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (typeof raw === "object" && raw !== null && raw.type === "error") {
|
|
151
|
+
const text = raw.errorText;
|
|
152
|
+
controller.enqueue({
|
|
153
|
+
type: "error",
|
|
154
|
+
...typeof text === "string" && text.length > 0 ? {
|
|
155
|
+
errorText: text
|
|
156
|
+
} : {}
|
|
157
|
+
});
|
|
158
|
+
emitted += 1;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const parsed = wireChunkSchema.safeParse(raw);
|
|
162
|
+
if (parsed.success) {
|
|
163
|
+
controller.enqueue(parsed.data);
|
|
164
|
+
emitted += 1;
|
|
165
|
+
} else {
|
|
166
|
+
warn(`wire: variante desconhecida ou inv\xE1lida descartada (${String(raw.type)})`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return emitted;
|
|
170
|
+
}, "drain");
|
|
171
|
+
return new ReadableStream({
|
|
172
|
+
/**
|
|
173
|
+
* Loop until this pull produces at least one chunk or the source ends.
|
|
174
|
+
*
|
|
175
|
+
* A `pull` that returns having enqueued nothing is NOT reliably re-invoked by the controller,
|
|
176
|
+
* so a frame that yields no chunk (the `[DONE]` sentinel, a comment, a discarded variant) would
|
|
177
|
+
* hang the consumer on its next `read()`. Measured: the `[DONE]` test timed out at exactly this
|
|
178
|
+
* point. Looping here makes progress a property of the parser, not of the scheduler.
|
|
179
|
+
*/
|
|
180
|
+
async pull(controller) {
|
|
181
|
+
for (; ; ) {
|
|
182
|
+
const { done, value } = await reader.read();
|
|
183
|
+
if (done) {
|
|
184
|
+
controller.close();
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
buffer += normalizeEol(value);
|
|
188
|
+
if (buffer.length > maxFrameBytes) {
|
|
189
|
+
throw new WireFrameTooLargeError(`wire: frame excedeu ${maxFrameBytes} bytes sem terminador; abortando em vez de acumular`);
|
|
190
|
+
}
|
|
191
|
+
if (drain(controller) > 0) return;
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
async cancel(reason) {
|
|
195
|
+
await reader.cancel(reason);
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
__name(parseWireStream, "parseWireStream");
|
|
200
|
+
|
|
201
|
+
// src/wire/read-message-stream.ts
|
|
202
|
+
function snapshot(message) {
|
|
203
|
+
return structuredClone(message);
|
|
204
|
+
}
|
|
205
|
+
__name(snapshot, "snapshot");
|
|
206
|
+
function open(messageId) {
|
|
207
|
+
return {
|
|
208
|
+
message: {
|
|
209
|
+
id: messageId ?? "",
|
|
210
|
+
role: "assistant",
|
|
211
|
+
parts: []
|
|
212
|
+
},
|
|
213
|
+
blocks: /* @__PURE__ */ new Map(),
|
|
214
|
+
tools: /* @__PURE__ */ new Map()
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
__name(open, "open");
|
|
218
|
+
function raiseStreamError(chunk) {
|
|
219
|
+
const text = chunk.errorText;
|
|
220
|
+
throw new WireStreamError(typeof text === "string" && text.length > 0 ? text : "agent stream failed without a message");
|
|
221
|
+
}
|
|
222
|
+
__name(raiseStreamError, "raiseStreamError");
|
|
223
|
+
async function* readMessageStream(chunks) {
|
|
224
|
+
let state = null;
|
|
225
|
+
for await (const chunk of chunks) {
|
|
226
|
+
if (chunk.type === "error") raiseStreamError(chunk);
|
|
227
|
+
if (chunk.type === "start") {
|
|
228
|
+
if (state !== null) yield snapshot(state.message);
|
|
229
|
+
const messageId = chunk.messageId;
|
|
230
|
+
state = open(messageId);
|
|
231
|
+
if (messageId !== void 0) yield snapshot(state.message);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
if (chunk.type === "finish") continue;
|
|
235
|
+
state ??= open(void 0);
|
|
236
|
+
if (applyChunk(state, chunk)) yield snapshot(state.message);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
__name(readMessageStream, "readMessageStream");
|
|
240
|
+
function applyChunk(state, chunk) {
|
|
241
|
+
const parts = state.message.parts;
|
|
242
|
+
switch (chunk.type) {
|
|
243
|
+
case "text-start":
|
|
244
|
+
case "reasoning-start":
|
|
245
|
+
case "text-delta":
|
|
246
|
+
case "reasoning-delta":
|
|
247
|
+
case "text-end":
|
|
248
|
+
case "reasoning-end":
|
|
249
|
+
return applyBlock(state, parts, chunk);
|
|
250
|
+
case "tool-input-available":
|
|
251
|
+
case "tool-output-available":
|
|
252
|
+
case "tool-output-error":
|
|
253
|
+
return applyTool(state, parts, chunk);
|
|
254
|
+
default:
|
|
255
|
+
return applyDataPart(parts, chunk);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
__name(applyChunk, "applyChunk");
|
|
259
|
+
function applyBlock(state, parts, chunk) {
|
|
260
|
+
const id = chunk.id;
|
|
261
|
+
if (chunk.type === "text-start" || chunk.type === "reasoning-start") {
|
|
262
|
+
state.blocks.set(id, parts.length);
|
|
263
|
+
const kind = chunk.type === "text-start" ? "text" : "reasoning";
|
|
264
|
+
parts.push({
|
|
265
|
+
type: kind,
|
|
266
|
+
text: "",
|
|
267
|
+
state: "streaming"
|
|
268
|
+
});
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
const at = state.blocks.get(id);
|
|
272
|
+
if (at === void 0) return false;
|
|
273
|
+
if (chunk.type === "text-end" || chunk.type === "reasoning-end") {
|
|
274
|
+
parts[at].state = "done";
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
const part = parts[at];
|
|
278
|
+
part.text = (typeof part.text === "string" ? part.text : "") + chunk.delta;
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
__name(applyBlock, "applyBlock");
|
|
282
|
+
function applyTool(state, parts, chunk) {
|
|
283
|
+
const c = chunk;
|
|
284
|
+
if (chunk.type === "tool-input-available") {
|
|
285
|
+
state.tools.set(c.toolCallId, parts.length);
|
|
286
|
+
parts.push({
|
|
287
|
+
type: "dynamic-tool",
|
|
288
|
+
toolName: c.toolName,
|
|
289
|
+
toolCallId: c.toolCallId,
|
|
290
|
+
state: "input-available",
|
|
291
|
+
input: c.input
|
|
292
|
+
});
|
|
293
|
+
return true;
|
|
294
|
+
}
|
|
295
|
+
const at = state.tools.get(c.toolCallId);
|
|
296
|
+
if (at === void 0) return false;
|
|
297
|
+
if (chunk.type === "tool-output-error") {
|
|
298
|
+
Object.assign(parts[at], {
|
|
299
|
+
state: "output-error",
|
|
300
|
+
errorText: c.errorText
|
|
301
|
+
});
|
|
302
|
+
return true;
|
|
303
|
+
}
|
|
304
|
+
Object.assign(parts[at], {
|
|
305
|
+
state: "output-available",
|
|
306
|
+
output: c.output
|
|
307
|
+
});
|
|
308
|
+
return true;
|
|
309
|
+
}
|
|
310
|
+
__name(applyTool, "applyTool");
|
|
311
|
+
function applyDataPart(parts, chunk) {
|
|
312
|
+
if (!chunk.type.startsWith("data-")) return false;
|
|
313
|
+
const part = chunk;
|
|
314
|
+
if (part.transient === true) return false;
|
|
315
|
+
parts.push({
|
|
316
|
+
type: part.type,
|
|
317
|
+
data: part.data
|
|
318
|
+
});
|
|
319
|
+
return true;
|
|
320
|
+
}
|
|
321
|
+
__name(applyDataPart, "applyDataPart");
|
|
322
|
+
export {
|
|
323
|
+
WIRE_CHUNK_TYPES,
|
|
324
|
+
WIRE_DATA_PART_PREFIX,
|
|
325
|
+
WireFrameTooLargeError,
|
|
326
|
+
WireStreamError,
|
|
327
|
+
parseWireStream,
|
|
328
|
+
readMessageStream,
|
|
329
|
+
wireChunkSchema
|
|
330
|
+
};
|
|
331
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/wire/chunk-schema.ts","../../src/wire/parse-wire-stream.ts","../../src/wire/read-message-stream.ts"],"mappings":";;;;;AAAA,SAASA,SAAS;AA6ClB,IAAMC,iBAAiBD,EAAEE,OAAO;EAC9BC,MAAMH,EAAEI,OACN,CAACC,MAAM,OAAOA,MAAM,YAAY,yBAAyBC,KAAKD,CAAAA,CAAAA;EAEhEE,MAAMP,EAAEQ,OAAOR,EAAES,OAAM,GAAIT,EAAEU,QAAO,CAAA;EACpCC,WAAWX,EAAEY,QAAO,EAAGC,SAAQ;AACjC,CAAA;AAEA,IAAMC,mBAAmBd,EAAEe,mBAAmB,QAAQ;EACpDf,EAAEE,OAAO;IAAEC,MAAMH,EAAEgB,QAAQ,OAAA;IAAUC,WAAWjB,EAAES,OAAM,EAAGI,SAAQ;EAAG,CAAA;EAEtEb,EAAEE,OAAO;IAAEC,MAAMH,EAAEgB,QAAQ,YAAA;IAAeE,IAAIlB,EAAES,OAAM;EAAG,CAAA;EACzDT,EAAEE,OAAO;IAAEC,MAAMH,EAAEgB,QAAQ,YAAA;IAAeE,IAAIlB,EAAES,OAAM;IAAIU,OAAOnB,EAAES,OAAM;EAAG,CAAA;EAC5ET,EAAEE,OAAO;IAAEC,MAAMH,EAAEgB,QAAQ,UAAA;IAAaE,IAAIlB,EAAES,OAAM;EAAG,CAAA;EAEvDT,EAAEE,OAAO;IAAEC,MAAMH,EAAEgB,QAAQ,iBAAA;IAAoBE,IAAIlB,EAAES,OAAM;EAAG,CAAA;EAC9DT,EAAEE,O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OAAOnB;AACb,MAAImB,KAAKU,cAAc,KAAM,QAAO;AACpClC,QAAMqB,KAAK;IAAER,MAAMW,KAAKX;IAAMsB,MAAMX,KAAKW;EAAK,CAAA;AAC9C,SAAO;AACT;AANSjB;","names":["z","dataPartSchema","object","type","custom","v","test","data","record","string","unknown","transient","boolean","optional","fixedChunkSchema","discriminatedUnion","literal","messageId","id","delta","toolCallId","toolName","input","dynamic","output","errorText","approvalId","messageMetadata","wireChunkSchema","union","WIRE_CHUNK_TYPES","WIRE_DATA_PART_PREFIX","DONE_SENTINEL","DEFAULT_MAX_FRAME_BYTES","WireStreamError","Error","name","WireFrameTooLargeError","normalizeEol","text","replace","joinDataLines","event","out","line","split","startsWith","push","slice","length","join","parseWireStream","bytes","options","maxFrameBytes","warn","onWarn","undefined","decoder","TextDecoderStream","reader","pipeThrough","getReader","buffer","drain","controller","emitted","cut","indexOf","payload","raw","JSON","parse","type","errorText","enqueue","parsed","wireChunkSchema","safeParse","success","data","String","ReadableStream","pull","done","value","read","close","cancel","reason","snapshot","message","structuredClone","open","messageId","id","role","parts","blocks","Map","tools","raiseStreamError","chunk","text","errorText","WireStreamError","length","readMessageStream","chunks","state","type","undefined","applyChunk","applyBlock","applyTool","applyDataPart","set","kind","push","at","get","part","delta","c","toolCallId","toolName","input","Object","assign","output","startsWith","transient","data"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/presenter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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,
|
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
".": {
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"import": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./wire": {
|
|
15
|
+
"types": "./dist/wire/index.d.ts",
|
|
16
|
+
"import": "./dist/wire/index.js"
|
|
13
17
|
}
|
|
14
18
|
},
|
|
15
19
|
"files": [
|
|
@@ -19,14 +23,15 @@
|
|
|
19
23
|
],
|
|
20
24
|
"peerDependencies": {
|
|
21
25
|
"@theokit/sdk": ">=3.5.0",
|
|
22
|
-
"
|
|
26
|
+
"zod": "^4.0.0"
|
|
23
27
|
},
|
|
24
28
|
"devDependencies": {
|
|
25
29
|
"@theokit/sdk": "^3.5.0",
|
|
26
|
-
"ai": "
|
|
30
|
+
"ai": "7.0.14",
|
|
27
31
|
"tsup": "^8.5.1",
|
|
28
32
|
"typescript": "^5.9.3",
|
|
29
|
-
"vitest": "^3.2.6"
|
|
33
|
+
"vitest": "^3.2.6",
|
|
34
|
+
"zod": "^4.4.3"
|
|
30
35
|
},
|
|
31
36
|
"license": "MIT",
|
|
32
37
|
"engines": {
|