@silverprotocol/vercel-ai 0.3.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Loqu, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # @silverprotocol/vercel-ai
2
+
3
+ AgJSON normalizer for the **Vercel AI SDK** —
4
+ [`ai`](https://github.com/vercel/ai) (`streamText` fullStream
5
+ `TextStreamPart` → `AgEvent[]`). It **sits on top of your `streamText`
6
+ call** and translates the stream parts it yields into framework-neutral
7
+ AgJSON; it doesn't replace the SDK you already use.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @silverprotocol/vercel-ai ai
13
+ ```
14
+
15
+ `@silverprotocol/core` is a required peer (pulled in automatically). `ai` is
16
+ the Vercel AI SDK itself — you need it to *produce* the stream parts. (The
17
+ normalizer guards `TextStreamPart`s structurally, so if you only feed it
18
+ already-captured parts it's just a type-level peer.)
19
+
20
+ <!-- compat:begin -->
21
+ <!-- generated by scripts/render-compat.mjs — do NOT edit by hand.
22
+ Facts live in package.json#peerDependencies + sdk-surface.json#verified;
23
+ edit those, then re-run `node scripts/render-compat.mjs`. -->
24
+ ## Upstream compatibility
25
+
26
+ Supported peer range: `ai` `>=6.0.0 <8` (npm-enforced, optional — this package never imports the SDK).
27
+
28
+ Wire shapes outside the verified set never crash the normalizer, and the
29
+ fixture-drift gate (`scripts/check-fixture-drift.mjs`) turns every newly-appeared
30
+ upstream field into a tracked triage disposition rather than an unnoticed drop —
31
+ carried losslessly where a carry channel exists (see `sdk-surface.json` for this
32
+ facet's per-field dispositions, including its disclosed `silently-dropped` gaps).
33
+
34
+ | `ai` | verified | with | evidence |
35
+ | --- | --- | --- | --- |
36
+ | `7.0.31` | 2026-07-20 | 0.3.3 | LIVE conformance capture: echo-gpt56 corpus (gpt-4o-mini via @ai-sdk/openai, official @ai-sdk/mcp Streamable-HTTP client against the harness mock) — landed as a standing replay seed; full two-step tool loop normalized (tool.start/args/assembled/done -> text step -> turn.done), zero unparsed/frame carries; deterministic replay green across the corpus. Census dispositions seeded from the capture (disclosed drops: tool-input-start.toolMetadata.clientName, dynamic flag on input-start) |
37
+ | `7.0.26` | 2026-07-20 | 0.3.3 | full drive switch + 20-test fixture suite replaying REAL mock-captured fullStream sequences at ai@7.0.26 (text/reasoning/two-step tool with id-correlation R1, per-step message model R3, three error arms R4, abort ordering R5, content-filter mapping, forward-compat frame carries) incl. Reducer folds; D1 burn-down contract finals empirically verified; live conformance capture pending |
38
+ <!-- compat:end -->
39
+
40
+ ## Usage
41
+
42
+ ```ts
43
+ import { streamText } from "ai";
44
+ import { openai } from "@ai-sdk/openai";
45
+ import { createVercelNormalizer } from "@silverprotocol/vercel-ai";
46
+
47
+ // Call streamText as usual — this package normalizes what it emits.
48
+ const result = streamText({
49
+ model: openai("gpt-5.6"),
50
+ tools: { echo: echoTool },
51
+ prompt: "call the echo tool",
52
+ });
53
+
54
+ const n = createVercelNormalizer();
55
+ const agEvents = [];
56
+ // fullStream is the typed TextStreamPart stream (on ai v7 it is aliased to
57
+ // `result.stream` — both names work across the supported range).
58
+ for await (const native of result.fullStream)
59
+ agEvents.push(...n.push(native)); // one TextStreamPart → 0+ AgEvents
60
+ agEvents.push(...n.flush()); // seal anything still open
61
+ ```
62
+
63
+ `push()` returns the `AgEvent[]` synthesized from each native
64
+ `TextStreamPart`; `flush()` drains buffered end-of-stream state. Any
65
+ async/sync iterable of `TextStreamPart`s works — a live `streamText` run, or
66
+ parts you captured earlier.
67
+
68
+ Then fold the resulting `AgEvent`s into messages and turns with
69
+ `@silverprotocol/core`'s `reduce()` — the same client code regardless of which
70
+ framework produced the stream.
71
+
72
+ Spec: [silverprotocol.io/AgJSON](https://silverprotocol.io/AgJSON) — canonical
73
+ in [silverprotocol/AgJSON](https://github.com/silverprotocol/AgJSON); wire
74
+ version `1.0.0-draft.1`.
@@ -0,0 +1,66 @@
1
+ /**
2
+ * `@silverprotocol/vercel-ai` — AgJSON normalizer for the Vercel AI SDK.
3
+ *
4
+ * Normalizes the `streamText` result's `fullStream` (v7: also `result.stream`)
5
+ * — the `TextStreamPart` union — into AgJSON events. fullStream is the
6
+ * in-process analog of the other three facets' inputs and the only Vercel
7
+ * surface carrying typed usage (`finish-step.usage` / `finish.totalUsage`).
8
+ *
9
+ * DESIGN: docs/plans/2026-07-14-vercel-ai-facet-brief.md (private workspace)
10
+ * — event mapping table + D1 decision sheet. Every wire shape below was
11
+ * captured from REAL ai@7.0.26 fullStream output (keyless MockLanguageModelV3
12
+ * runs, 2026-07-20), which corrected the survey in three places:
13
+ * - `text-delta`/`reasoning-delta` carry `text`; `tool-input-delta` carries
14
+ * `delta` (asymmetric on the real wire);
15
+ * - `start-step` carries NO response id — `{request, warnings}` only. The
16
+ * step's response identity (`id`, `modelId`) surfaces at
17
+ * `finish-step.response`, so message ids are minted synthetically at open
18
+ * (`msg_<turnId>_s<k>`) and the response identity lands as a
19
+ * `message.metadata` event at close;
20
+ * - fullStream `finishReason` is a flat string with a sibling
21
+ * `rawFinishReason` (the `{unified, raw}` object form exists only on the
22
+ * model-spec chunk grammar).
23
+ *
24
+ * Anchoring (D1-final): one `streamText` invocation = ONE turn (threadId fixed
25
+ * `"vercel"`; no wire thread id — openai-facet precedent). One message PER
26
+ * STEP: opened at `start-step`, sealed at `finish-step` with that step's
27
+ * `usage`; `turn.done.usage` = `finish.totalUsage` VERBATIM (never summed,
28
+ * `cumulative` absent). `step.start`/`step.done` ride as fold-neutral live
29
+ * markers.
30
+ *
31
+ * Errors have three arms (all empirically captured):
32
+ * A. in-band `error` part with a later `finish` — non-terminal advisory
33
+ * `error` event, then the turn closes via `turn.error` (finishReason
34
+ * `"error"`) or `turn.done` (provider recovered and finished normally);
35
+ * B. in-band `error` part and the stream just ENDS (doStream rejection:
36
+ * `[start, error]`, no finish) — `flush()` self-seals the turn as
37
+ * `turn.error` with the stashed message;
38
+ * C. a raw throw out of `for await (fullStream)` (transport failure) — the
39
+ * HOST wraps iteration and pushes a `{type: VERCEL_HOST_ERROR, message}`
40
+ * sentinel (OpenAIHostError pattern), which closes message + turn.
41
+ *
42
+ * Lossless posture (Tenet 6): `push()` never throws. Unknown part types ride
43
+ * `ext.vercel.frame{kind, frame}` (v7 adds `custom`, `reasoning-file`,
44
+ * `tool-approval-*`; also v0-DEFERRED: `source`, `file`, `raw` — carried, not
45
+ * yet mapped to first-class blocks). Guard failures ride
46
+ * `ext.vercel.unparsed{native}`. `ai` is an OPTIONAL peer, never imported.
47
+ */
48
+ import type { AgEvent, JsonValue, Normalizer } from "@silverprotocol/core";
49
+ /** Sentinel `type` the HOST pushes when `for await (fullStream)` itself throws
50
+ * (transport failure — bypasses even streamText's `onError`). Wrap iteration:
51
+ * `try { for await (const p of stream) out.push(...n.push(p)) } catch (e) {
52
+ * out.push(...n.push({ type: VERCEL_HOST_ERROR, message: String(e) })) }` */
53
+ export declare const VERCEL_HOST_ERROR = "__host_error__";
54
+ /** The one invariant every `TextStreamPart` shares: a string `type` discriminant. */
55
+ export interface VercelStreamPart {
56
+ type: string;
57
+ [k: string]: unknown;
58
+ }
59
+ /**
60
+ * Stateful-per-invoke normalizer for one `streamText` run's fullStream.
61
+ * `push(part)` → 0+ AgEvents; `flush()` seals anything still open.
62
+ */
63
+ export declare function createVercelNormalizer(): Normalizer;
64
+ export default createVercelNormalizer;
65
+ export type { AgEvent, JsonValue };
66
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,KAAK,EAAE,OAAO,EAA2B,SAAS,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAKpG;;;iFAGiF;AACjF,eAAO,MAAM,iBAAiB,mBAAmB,CAAC;AAIlD,qFAAqF;AACrF,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CACtB;AA0FD;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,UAAU,CA0TnD;AAED,eAAe,sBAAsB,CAAC;AACtC,YAAY,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,462 @@
1
+ /**
2
+ * `@silverprotocol/vercel-ai` — AgJSON normalizer for the Vercel AI SDK.
3
+ *
4
+ * Normalizes the `streamText` result's `fullStream` (v7: also `result.stream`)
5
+ * — the `TextStreamPart` union — into AgJSON events. fullStream is the
6
+ * in-process analog of the other three facets' inputs and the only Vercel
7
+ * surface carrying typed usage (`finish-step.usage` / `finish.totalUsage`).
8
+ *
9
+ * DESIGN: docs/plans/2026-07-14-vercel-ai-facet-brief.md (private workspace)
10
+ * — event mapping table + D1 decision sheet. Every wire shape below was
11
+ * captured from REAL ai@7.0.26 fullStream output (keyless MockLanguageModelV3
12
+ * runs, 2026-07-20), which corrected the survey in three places:
13
+ * - `text-delta`/`reasoning-delta` carry `text`; `tool-input-delta` carries
14
+ * `delta` (asymmetric on the real wire);
15
+ * - `start-step` carries NO response id — `{request, warnings}` only. The
16
+ * step's response identity (`id`, `modelId`) surfaces at
17
+ * `finish-step.response`, so message ids are minted synthetically at open
18
+ * (`msg_<turnId>_s<k>`) and the response identity lands as a
19
+ * `message.metadata` event at close;
20
+ * - fullStream `finishReason` is a flat string with a sibling
21
+ * `rawFinishReason` (the `{unified, raw}` object form exists only on the
22
+ * model-spec chunk grammar).
23
+ *
24
+ * Anchoring (D1-final): one `streamText` invocation = ONE turn (threadId fixed
25
+ * `"vercel"`; no wire thread id — openai-facet precedent). One message PER
26
+ * STEP: opened at `start-step`, sealed at `finish-step` with that step's
27
+ * `usage`; `turn.done.usage` = `finish.totalUsage` VERBATIM (never summed,
28
+ * `cumulative` absent). `step.start`/`step.done` ride as fold-neutral live
29
+ * markers.
30
+ *
31
+ * Errors have three arms (all empirically captured):
32
+ * A. in-band `error` part with a later `finish` — non-terminal advisory
33
+ * `error` event, then the turn closes via `turn.error` (finishReason
34
+ * `"error"`) or `turn.done` (provider recovered and finished normally);
35
+ * B. in-band `error` part and the stream just ENDS (doStream rejection:
36
+ * `[start, error]`, no finish) — `flush()` self-seals the turn as
37
+ * `turn.error` with the stashed message;
38
+ * C. a raw throw out of `for await (fullStream)` (transport failure) — the
39
+ * HOST wraps iteration and pushes a `{type: VERCEL_HOST_ERROR, message}`
40
+ * sentinel (OpenAIHostError pattern), which closes message + turn.
41
+ *
42
+ * Lossless posture (Tenet 6): `push()` never throws. Unknown part types ride
43
+ * `ext.vercel.frame{kind, frame}` (v7 adds `custom`, `reasoning-file`,
44
+ * `tool-approval-*`; also v0-DEFERRED: `source`, `file`, `raw` — carried, not
45
+ * yet mapped to first-class blocks). Guard failures ride
46
+ * `ext.vercel.unparsed{native}`. `ai` is an OPTIONAL peer, never imported.
47
+ */
48
+ import { StreamAssembler, toJsonValue } from "@silverprotocol/core";
49
+ // ─── host-boundary sentinel (error arm C) ────────────────────────────────────
50
+ /** Sentinel `type` the HOST pushes when `for await (fullStream)` itself throws
51
+ * (transport failure — bypasses even streamText's `onError`). Wrap iteration:
52
+ * `try { for await (const p of stream) out.push(...n.push(p)) } catch (e) {
53
+ * out.push(...n.push({ type: VERCEL_HOST_ERROR, message: String(e) })) }` */
54
+ export const VERCEL_HOST_ERROR = "__host_error__";
55
+ /** JSON-materialize ANY input without ever throwing (Tenet 6). */
56
+ function safeJson(v) {
57
+ if (v === undefined)
58
+ return null;
59
+ try {
60
+ return toJsonValue(v);
61
+ }
62
+ catch {
63
+ return String(v);
64
+ }
65
+ }
66
+ /** True for a non-null, non-array object carrying a string `type` (guard idiom
67
+ * shared with the OpenAI facet — envelope-only; arm payloads are validated by
68
+ * the drive switch per-arm, widen-don't-cast). */
69
+ function isVercelStreamPart(v) {
70
+ return (typeof v === "object" &&
71
+ v !== null &&
72
+ !Array.isArray(v) &&
73
+ typeof v.type === "string");
74
+ }
75
+ const str = (v) => (typeof v === "string" ? v : undefined);
76
+ const num = (v) => (typeof v === "number" ? v : undefined);
77
+ const rec = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
78
+ /** Render any error-ish value to a message string, never throwing. */
79
+ function errText(v) {
80
+ if (v instanceof Error)
81
+ return v.message;
82
+ if (typeof v === "string")
83
+ return v;
84
+ try {
85
+ return JSON.stringify(v) ?? String(v);
86
+ }
87
+ catch {
88
+ return String(v);
89
+ }
90
+ }
91
+ // ─── wire → AgJSON value mapping ─────────────────────────────────────────────
92
+ /** fullStream `LanguageModelUsage` (flat tokens + detail bags — verified
93
+ * ai@7.0.26) → AgUsage. `cumulative` deliberately ABSENT (D1: totalUsage is
94
+ * carried verbatim on turn.done; per-step usage rides message.end). */
95
+ function mapUsage(v) {
96
+ const u = rec(v);
97
+ if (u === undefined)
98
+ return undefined;
99
+ const inDet = rec(u["inputTokenDetails"]);
100
+ const outDet = rec(u["outputTokenDetails"]);
101
+ const out = {
102
+ ...(num(u["inputTokens"]) !== undefined ? { inputTokens: num(u["inputTokens"]) } : {}),
103
+ ...(num(u["outputTokens"]) !== undefined ? { outputTokens: num(u["outputTokens"]) } : {}),
104
+ ...(num(u["totalTokens"]) !== undefined ? { totalTokens: num(u["totalTokens"]) } : {}),
105
+ ...(num(inDet?.["cacheReadTokens"]) !== undefined
106
+ ? { cacheReadTokens: num(inDet?.["cacheReadTokens"]) }
107
+ : {}),
108
+ ...(num(inDet?.["cacheWriteTokens"]) !== undefined
109
+ ? { cacheWriteTokens: num(inDet?.["cacheWriteTokens"]) }
110
+ : {}),
111
+ ...(num(outDet?.["reasoningTokens"]) !== undefined
112
+ ? { reasoningTokens: num(outDet?.["reasoningTokens"]) }
113
+ : {}),
114
+ };
115
+ return Object.keys(out).length > 0 ? out : undefined;
116
+ }
117
+ /** fullStream finishReason strings → AgFinishReason. `"error"` never reaches
118
+ * this map — it routes to `turn.error` in the `finish` arm. */
119
+ function mapFinishReason(v) {
120
+ switch (str(v)) {
121
+ case "stop":
122
+ return "stop";
123
+ case "tool-calls":
124
+ return "tool_call";
125
+ case "length":
126
+ return "token_limit";
127
+ case "content-filter":
128
+ return "safety_blocked";
129
+ case "other":
130
+ return "other";
131
+ default:
132
+ return "unknown";
133
+ }
134
+ }
135
+ // ─── factory ──────────────────────────────────────────────────────────────────
136
+ const THREAD_ID = "vercel";
137
+ /**
138
+ * Stateful-per-invoke normalizer for one `streamText` run's fullStream.
139
+ * `push(part)` → 0+ AgEvents; `flush()` seals anything still open.
140
+ */
141
+ export function createVercelNormalizer() {
142
+ const a = new StreamAssembler();
143
+ let turnCounter = 0;
144
+ let turnId; // current open turn
145
+ let turnClosed = false;
146
+ let stepIndex = 0;
147
+ let stepId; // current open step marker id
148
+ let msgId; // current open message id
149
+ const openTextIds = new Set();
150
+ const openReasoningIds = new Set();
151
+ const pendingToolIds = new Set(); // tool-input-start seen, tool-call not yet
152
+ let stashedError; // last in-band error message (arms A/B)
153
+ /** Mint + open the run's turn if not already open (defensive: arms other
154
+ * than `start` can arrive first on a hostile/truncated wire). */
155
+ function ensureTurn() {
156
+ if (turnId === undefined || turnClosed) {
157
+ turnId = `turn_vercel_${++turnCounter}`;
158
+ turnClosed = false;
159
+ a.openTurn(turnId, THREAD_ID);
160
+ }
161
+ return turnId;
162
+ }
163
+ /** Ensure an open message (defensive for content arriving before start-step). */
164
+ function ensureMessage() {
165
+ if (msgId === undefined) {
166
+ const t = ensureTurn();
167
+ stepIndex += 1;
168
+ stepId = `step_${stepIndex}`;
169
+ a.emit({ type: "step.start", id: stepId, turnId: t });
170
+ msgId = `msg_${t}_s${stepIndex}`;
171
+ a.openMessage({ id: msgId, role: "assistant", turnId: t, threadId: THREAD_ID, stepId });
172
+ }
173
+ return msgId;
174
+ }
175
+ /** Close any open text/reasoning streams (abort/host-error paths). */
176
+ function endOpenStreams() {
177
+ if (msgId === undefined)
178
+ return;
179
+ for (const id of openTextIds)
180
+ a.textEnd(id, msgId);
181
+ openTextIds.clear();
182
+ for (const id of openReasoningIds)
183
+ a.reasoningEnd(id, msgId);
184
+ openReasoningIds.clear();
185
+ }
186
+ /** messageEnd BEFORE any turn-terminal event (D1/R5 ordering rule). */
187
+ function closeOpenMessage(usage) {
188
+ if (msgId === undefined)
189
+ return;
190
+ endOpenStreams();
191
+ a.closeMessage(msgId, usage);
192
+ if (stepId !== undefined)
193
+ a.emit({ type: "step.done", id: stepId });
194
+ msgId = undefined;
195
+ stepId = undefined;
196
+ }
197
+ function drive(part) {
198
+ switch (part.type) {
199
+ case "start": {
200
+ ensureTurn();
201
+ return;
202
+ }
203
+ case "start-step": {
204
+ const t = ensureTurn();
205
+ // Seal a dangling previous step defensively (the real wire always
206
+ // closes via finish-step first — verified tool-two-step capture).
207
+ if (msgId !== undefined)
208
+ closeOpenMessage();
209
+ stepIndex += 1;
210
+ stepId = `step_${stepIndex}`;
211
+ a.emit({ type: "step.start", id: stepId, turnId: t });
212
+ msgId = `msg_${t}_s${stepIndex}`;
213
+ a.openMessage({ id: msgId, role: "assistant", turnId: t, threadId: THREAD_ID, stepId });
214
+ const warnings = part["warnings"];
215
+ if (Array.isArray(warnings) && warnings.length > 0) {
216
+ a.emitExt(THREAD_ID, "warnings", { stepId, warnings: safeJson(warnings) });
217
+ }
218
+ return;
219
+ }
220
+ case "text-start": {
221
+ const id = str(part["id"]);
222
+ if (id === undefined)
223
+ break;
224
+ openTextIds.add(id);
225
+ a.textStart(id, ensureMessage());
226
+ return;
227
+ }
228
+ case "text-delta": {
229
+ const id = str(part["id"]);
230
+ const text = str(part["text"]); // fullStream field is `text` (verified)
231
+ if (id === undefined || text === undefined)
232
+ break;
233
+ a.textDelta(id, ensureMessage(), text, { cumulative: false });
234
+ return;
235
+ }
236
+ case "text-end": {
237
+ const id = str(part["id"]);
238
+ if (id === undefined)
239
+ break;
240
+ openTextIds.delete(id);
241
+ a.textEnd(id, ensureMessage());
242
+ return;
243
+ }
244
+ case "reasoning-start": {
245
+ const id = str(part["id"]);
246
+ if (id === undefined)
247
+ break;
248
+ openReasoningIds.add(id);
249
+ a.reasoningStart(id, ensureMessage());
250
+ return;
251
+ }
252
+ case "reasoning-delta": {
253
+ const id = str(part["id"]);
254
+ const text = str(part["text"]); // `text` here too (verified)
255
+ if (id === undefined || text === undefined)
256
+ break;
257
+ a.reasoningDelta(id, ensureMessage(), text, { cumulative: false });
258
+ return;
259
+ }
260
+ case "reasoning-end": {
261
+ const id = str(part["id"]);
262
+ if (id === undefined)
263
+ break;
264
+ openReasoningIds.delete(id);
265
+ a.reasoningEnd(id, ensureMessage());
266
+ return;
267
+ }
268
+ case "tool-input-start": {
269
+ // fullStream keys the streamed-input lifecycle by `id` ≡ the eventual
270
+ // `tool-call.toolCallId` (R1, verified live).
271
+ const id = str(part["id"]);
272
+ const name = str(part["toolName"]);
273
+ if (id === undefined || name === undefined)
274
+ break;
275
+ pendingToolIds.add(id);
276
+ a.toolStart({
277
+ toolCallId: id,
278
+ name,
279
+ messageId: ensureMessage(),
280
+ ...(typeof part["dynamic"] === "boolean" ? { dynamic: part["dynamic"] } : {}),
281
+ ...(str(part["title"]) !== undefined ? { title: str(part["title"]) } : {}),
282
+ ...(typeof part["providerExecuted"] === "boolean"
283
+ ? { providerExecuted: part["providerExecuted"] }
284
+ : {}),
285
+ });
286
+ return;
287
+ }
288
+ case "tool-input-delta": {
289
+ const id = str(part["id"]);
290
+ const delta = str(part["delta"]); // `delta` for tool input (verified)
291
+ if (id === undefined || delta === undefined)
292
+ break;
293
+ a.toolArgsDelta(id, delta, { cumulative: false });
294
+ return;
295
+ }
296
+ case "tool-input-end": {
297
+ // Redundant on this seam — `tool-call` is the single authoritative
298
+ // assembled-input source (mapping table §1).
299
+ return;
300
+ }
301
+ case "tool-call": {
302
+ const toolCallId = str(part["toolCallId"]);
303
+ const name = str(part["toolName"]);
304
+ if (toolCallId === undefined || name === undefined)
305
+ break;
306
+ const input = safeJson(part["input"] ?? {}); // parsed OBJECT on this wire (verified)
307
+ if (!pendingToolIds.has(toolCallId)) {
308
+ // Non-streamed call: synthesize the start+delta pair so the tool
309
+ // lifecycle stays well-formed (openai-facet built-in-tool precedent).
310
+ a.toolStart({
311
+ toolCallId,
312
+ name,
313
+ messageId: ensureMessage(),
314
+ ...(typeof part["dynamic"] === "boolean" ? { dynamic: part["dynamic"] } : {}),
315
+ });
316
+ a.toolArgsDelta(toolCallId, JSON.stringify(input), { cumulative: false });
317
+ }
318
+ pendingToolIds.delete(toolCallId);
319
+ a.toolArgsAssembled(toolCallId, input);
320
+ if (part["invalid"] === true) {
321
+ a.emitExt(THREAD_ID, "invalid-tool-call", {
322
+ toolCallId,
323
+ error: errText(part["error"]),
324
+ });
325
+ }
326
+ return;
327
+ }
328
+ case "tool-result": {
329
+ const toolCallId = str(part["toolCallId"]);
330
+ if (toolCallId === undefined)
331
+ break;
332
+ const output = safeJson(part["output"]);
333
+ const preliminary = part["preliminary"] === true;
334
+ a.toolDone({
335
+ toolCallId,
336
+ outcome: "ok",
337
+ structuredContent: output,
338
+ content: [
339
+ { type: "text", text: typeof output === "string" ? output : JSON.stringify(output) },
340
+ ],
341
+ ...(preliminary ? { more: true, preliminary: true } : {}),
342
+ ...(typeof part["dynamic"] === "boolean" ? { dynamic: part["dynamic"] } : {}),
343
+ });
344
+ return;
345
+ }
346
+ case "tool-error": {
347
+ const toolCallId = str(part["toolCallId"]);
348
+ if (toolCallId === undefined)
349
+ break;
350
+ const message = errText(part["error"]);
351
+ a.toolDone({
352
+ toolCallId,
353
+ outcome: "error",
354
+ isError: true,
355
+ errorText: message,
356
+ content: [{ type: "text", text: message }],
357
+ });
358
+ return;
359
+ }
360
+ case "finish-step": {
361
+ const response = rec(part["response"]);
362
+ if (msgId !== undefined && response !== undefined) {
363
+ // The step's response identity only surfaces HERE (verified) —
364
+ // land it as message metadata before sealing.
365
+ const metadata = {};
366
+ const responseId = str(response["id"]);
367
+ const modelId = str(response["modelId"]);
368
+ const rawFinish = str(part["rawFinishReason"]);
369
+ if (responseId !== undefined)
370
+ metadata["responseId"] = responseId;
371
+ if (modelId !== undefined)
372
+ metadata["model"] = modelId;
373
+ if (rawFinish !== undefined)
374
+ metadata["rawFinishReason"] = rawFinish;
375
+ if (Object.keys(metadata).length > 0) {
376
+ a.emit({ type: "message.metadata", messageId: msgId, metadata });
377
+ }
378
+ }
379
+ closeOpenMessage(mapUsage(part["usage"]));
380
+ return;
381
+ }
382
+ case "finish": {
383
+ const t = ensureTurn();
384
+ closeOpenMessage(); // defensive; the real wire closes via finish-step first
385
+ if (str(part["finishReason"]) === "error") {
386
+ a.closeTurnError(t, { message: stashedError ?? "provider error" });
387
+ }
388
+ else {
389
+ const usage = mapUsage(part["totalUsage"]);
390
+ a.closeTurnDone(t, {
391
+ outcome: { type: "success" },
392
+ finishReason: mapFinishReason(part["finishReason"]),
393
+ ...(usage !== undefined ? { usage } : {}),
394
+ });
395
+ }
396
+ turnClosed = true;
397
+ stashedError = undefined;
398
+ return;
399
+ }
400
+ case "error": {
401
+ // Non-terminal advisory (arm A); stashed for arm B's flush self-seal.
402
+ stashedError = errText(part["error"]);
403
+ a.emit({ type: "error", message: stashedError });
404
+ return;
405
+ }
406
+ case VERCEL_HOST_ERROR: {
407
+ // Arm C: transport failure thrown out of the iterator; host sentinel.
408
+ const t = ensureTurn();
409
+ stashedError = str(part["message"]) ?? "host iteration error";
410
+ a.emit({ type: "error", message: stashedError });
411
+ closeOpenMessage();
412
+ a.closeTurnError(t, { message: stashedError });
413
+ turnClosed = true;
414
+ stashedError = undefined;
415
+ return;
416
+ }
417
+ case "abort": {
418
+ const t = ensureTurn();
419
+ closeOpenMessage(); // messageEnd BEFORE turn.abort (R5 ordering rule)
420
+ const reason = str(part["reason"]);
421
+ a.emit({ type: "turn.abort", turnId: t, ...(reason !== undefined ? { reason } : {}) });
422
+ turnClosed = true;
423
+ return;
424
+ }
425
+ default:
426
+ break; // → tolerant frame carry below
427
+ }
428
+ // Tolerant default arm (R2): unknown part types AND known types with
429
+ // malformed payloads ride the lossless vendor channel.
430
+ a.emitExt(THREAD_ID, "frame", { kind: part.type, frame: safeJson(part) });
431
+ }
432
+ return {
433
+ push(native) {
434
+ if (!isVercelStreamPart(native)) {
435
+ a.emitExt(THREAD_ID, "unparsed", { native: safeJson(native) });
436
+ return a.drain();
437
+ }
438
+ drive(native);
439
+ return a.drain();
440
+ },
441
+ flush() {
442
+ if (turnId !== undefined && !turnClosed) {
443
+ if (stashedError !== undefined) {
444
+ // Arm B: in-band error and the stream just ended (doStream
445
+ // rejection — verified: [start, error] then EOF). Self-seal.
446
+ closeOpenMessage();
447
+ a.closeTurnError(turnId, { message: stashedError });
448
+ turnClosed = true;
449
+ stashedError = undefined;
450
+ }
451
+ else {
452
+ // Truncated stream with no error signal: seal the message; the
453
+ // engine's flush (INV-FLUSH) aborts the still-open turn.
454
+ closeOpenMessage();
455
+ }
456
+ }
457
+ return a.flush();
458
+ },
459
+ };
460
+ }
461
+ export default createVercelNormalizer;
462
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAGH,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEpE,gFAAgF;AAEhF;;;iFAGiF;AACjF,MAAM,CAAC,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAUlD,kEAAkE;AAClE,SAAS,QAAQ,CAAC,CAAU;IAC1B,IAAI,CAAC,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IACjC,IAAI,CAAC;QACH,OAAO,WAAW,CAAC,CAAC,CAAC,CAAC;IACxB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;IACnB,CAAC;AACH,CAAC;AAED;;mDAEmD;AACnD,SAAS,kBAAkB,CAAC,CAAU;IACpC,OAAO,CACL,OAAO,CAAC,KAAK,QAAQ;QACrB,CAAC,KAAK,IAAI;QACV,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;QACjB,OAAQ,CAAwB,CAAC,IAAI,KAAK,QAAQ,CACnD,CAAC;AACJ,CAAC;AAED,MAAM,GAAG,GAAG,CAAC,CAAU,EAAsB,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AACxF,MAAM,GAAG,GAAG,CAAC,CAAU,EAAsB,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AACxF,MA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0,0 +1,49 @@
1
+ {
2
+ "name": "@silverprotocol/vercel-ai",
3
+ "version": "0.3.3",
4
+ "description": "AgJSON normalizer for the Vercel AI SDK (fullStream TextStreamPart → AgEvent[]).",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/silverprotocol/typescript-sdk.git",
9
+ "directory": "packages/vercel-ai"
10
+ },
11
+ "homepage": "https://github.com/silverprotocol/typescript-sdk#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/silverprotocol/typescript-sdk/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "type": "module",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "files": [
28
+ "dist",
29
+ "src",
30
+ "!src/**/*.test.ts",
31
+ "!dist/**/*.test.*"
32
+ ],
33
+ "dependencies": {
34
+ "@silverprotocol/core": "0.3.3"
35
+ },
36
+ "peerDependencies": {
37
+ "ai": ">=6.0.0 <8"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "ai": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "scripts": {
45
+ "build": "tsc -b --force",
46
+ "test": "vitest run",
47
+ "typecheck": "tsc -p tsconfig.json --noEmit"
48
+ }
49
+ }
package/src/index.ts ADDED
@@ -0,0 +1,477 @@
1
+ /**
2
+ * `@silverprotocol/vercel-ai` — AgJSON normalizer for the Vercel AI SDK.
3
+ *
4
+ * Normalizes the `streamText` result's `fullStream` (v7: also `result.stream`)
5
+ * — the `TextStreamPart` union — into AgJSON events. fullStream is the
6
+ * in-process analog of the other three facets' inputs and the only Vercel
7
+ * surface carrying typed usage (`finish-step.usage` / `finish.totalUsage`).
8
+ *
9
+ * DESIGN: docs/plans/2026-07-14-vercel-ai-facet-brief.md (private workspace)
10
+ * — event mapping table + D1 decision sheet. Every wire shape below was
11
+ * captured from REAL ai@7.0.26 fullStream output (keyless MockLanguageModelV3
12
+ * runs, 2026-07-20), which corrected the survey in three places:
13
+ * - `text-delta`/`reasoning-delta` carry `text`; `tool-input-delta` carries
14
+ * `delta` (asymmetric on the real wire);
15
+ * - `start-step` carries NO response id — `{request, warnings}` only. The
16
+ * step's response identity (`id`, `modelId`) surfaces at
17
+ * `finish-step.response`, so message ids are minted synthetically at open
18
+ * (`msg_<turnId>_s<k>`) and the response identity lands as a
19
+ * `message.metadata` event at close;
20
+ * - fullStream `finishReason` is a flat string with a sibling
21
+ * `rawFinishReason` (the `{unified, raw}` object form exists only on the
22
+ * model-spec chunk grammar).
23
+ *
24
+ * Anchoring (D1-final): one `streamText` invocation = ONE turn (threadId fixed
25
+ * `"vercel"`; no wire thread id — openai-facet precedent). One message PER
26
+ * STEP: opened at `start-step`, sealed at `finish-step` with that step's
27
+ * `usage`; `turn.done.usage` = `finish.totalUsage` VERBATIM (never summed,
28
+ * `cumulative` absent). `step.start`/`step.done` ride as fold-neutral live
29
+ * markers.
30
+ *
31
+ * Errors have three arms (all empirically captured):
32
+ * A. in-band `error` part with a later `finish` — non-terminal advisory
33
+ * `error` event, then the turn closes via `turn.error` (finishReason
34
+ * `"error"`) or `turn.done` (provider recovered and finished normally);
35
+ * B. in-band `error` part and the stream just ENDS (doStream rejection:
36
+ * `[start, error]`, no finish) — `flush()` self-seals the turn as
37
+ * `turn.error` with the stashed message;
38
+ * C. a raw throw out of `for await (fullStream)` (transport failure) — the
39
+ * HOST wraps iteration and pushes a `{type: VERCEL_HOST_ERROR, message}`
40
+ * sentinel (OpenAIHostError pattern), which closes message + turn.
41
+ *
42
+ * Lossless posture (Tenet 6): `push()` never throws. Unknown part types ride
43
+ * `ext.vercel.frame{kind, frame}` (v7 adds `custom`, `reasoning-file`,
44
+ * `tool-approval-*`; also v0-DEFERRED: `source`, `file`, `raw` — carried, not
45
+ * yet mapped to first-class blocks). Guard failures ride
46
+ * `ext.vercel.unparsed{native}`. `ai` is an OPTIONAL peer, never imported.
47
+ */
48
+
49
+ import type { AgEvent, AgFinishReason, AgUsage, JsonValue, Normalizer } from "@silverprotocol/core";
50
+ import { StreamAssembler, toJsonValue } from "@silverprotocol/core";
51
+
52
+ // ─── host-boundary sentinel (error arm C) ────────────────────────────────────
53
+
54
+ /** Sentinel `type` the HOST pushes when `for await (fullStream)` itself throws
55
+ * (transport failure — bypasses even streamText's `onError`). Wrap iteration:
56
+ * `try { for await (const p of stream) out.push(...n.push(p)) } catch (e) {
57
+ * out.push(...n.push({ type: VERCEL_HOST_ERROR, message: String(e) })) }` */
58
+ export const VERCEL_HOST_ERROR = "__host_error__";
59
+
60
+ // ─── input contract — structural projection of the fullStream envelope ───────
61
+
62
+ /** The one invariant every `TextStreamPart` shares: a string `type` discriminant. */
63
+ export interface VercelStreamPart {
64
+ type: string;
65
+ [k: string]: unknown;
66
+ }
67
+
68
+ /** JSON-materialize ANY input without ever throwing (Tenet 6). */
69
+ function safeJson(v: unknown): JsonValue {
70
+ if (v === undefined) return null;
71
+ try {
72
+ return toJsonValue(v);
73
+ } catch {
74
+ return String(v);
75
+ }
76
+ }
77
+
78
+ /** True for a non-null, non-array object carrying a string `type` (guard idiom
79
+ * shared with the OpenAI facet — envelope-only; arm payloads are validated by
80
+ * the drive switch per-arm, widen-don't-cast). */
81
+ function isVercelStreamPart(v: unknown): v is VercelStreamPart {
82
+ return (
83
+ typeof v === "object" &&
84
+ v !== null &&
85
+ !Array.isArray(v) &&
86
+ typeof (v as { type?: unknown }).type === "string"
87
+ );
88
+ }
89
+
90
+ const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
91
+ const num = (v: unknown): number | undefined => (typeof v === "number" ? v : undefined);
92
+ const rec = (v: unknown): { [k: string]: unknown } | undefined =>
93
+ typeof v === "object" && v !== null && !Array.isArray(v) ? (v as { [k: string]: unknown }) : undefined;
94
+
95
+ /** Render any error-ish value to a message string, never throwing. */
96
+ function errText(v: unknown): string {
97
+ if (v instanceof Error) return v.message;
98
+ if (typeof v === "string") return v;
99
+ try {
100
+ return JSON.stringify(v) ?? String(v);
101
+ } catch {
102
+ return String(v);
103
+ }
104
+ }
105
+
106
+ // ─── wire → AgJSON value mapping ─────────────────────────────────────────────
107
+
108
+ /** fullStream `LanguageModelUsage` (flat tokens + detail bags — verified
109
+ * ai@7.0.26) → AgUsage. `cumulative` deliberately ABSENT (D1: totalUsage is
110
+ * carried verbatim on turn.done; per-step usage rides message.end). */
111
+ function mapUsage(v: unknown): AgUsage | undefined {
112
+ const u = rec(v);
113
+ if (u === undefined) return undefined;
114
+ const inDet = rec(u["inputTokenDetails"]);
115
+ const outDet = rec(u["outputTokenDetails"]);
116
+ const out: AgUsage = {
117
+ ...(num(u["inputTokens"]) !== undefined ? { inputTokens: num(u["inputTokens"]) } : {}),
118
+ ...(num(u["outputTokens"]) !== undefined ? { outputTokens: num(u["outputTokens"]) } : {}),
119
+ ...(num(u["totalTokens"]) !== undefined ? { totalTokens: num(u["totalTokens"]) } : {}),
120
+ ...(num(inDet?.["cacheReadTokens"]) !== undefined
121
+ ? { cacheReadTokens: num(inDet?.["cacheReadTokens"]) }
122
+ : {}),
123
+ ...(num(inDet?.["cacheWriteTokens"]) !== undefined
124
+ ? { cacheWriteTokens: num(inDet?.["cacheWriteTokens"]) }
125
+ : {}),
126
+ ...(num(outDet?.["reasoningTokens"]) !== undefined
127
+ ? { reasoningTokens: num(outDet?.["reasoningTokens"]) }
128
+ : {}),
129
+ };
130
+ return Object.keys(out).length > 0 ? out : undefined;
131
+ }
132
+
133
+ /** fullStream finishReason strings → AgFinishReason. `"error"` never reaches
134
+ * this map — it routes to `turn.error` in the `finish` arm. */
135
+ function mapFinishReason(v: unknown): AgFinishReason {
136
+ switch (str(v)) {
137
+ case "stop":
138
+ return "stop";
139
+ case "tool-calls":
140
+ return "tool_call";
141
+ case "length":
142
+ return "token_limit";
143
+ case "content-filter":
144
+ return "safety_blocked";
145
+ case "other":
146
+ return "other";
147
+ default:
148
+ return "unknown";
149
+ }
150
+ }
151
+
152
+ // ─── factory ──────────────────────────────────────────────────────────────────
153
+
154
+ const THREAD_ID = "vercel";
155
+
156
+ /**
157
+ * Stateful-per-invoke normalizer for one `streamText` run's fullStream.
158
+ * `push(part)` → 0+ AgEvents; `flush()` seals anything still open.
159
+ */
160
+ export function createVercelNormalizer(): Normalizer {
161
+ const a = new StreamAssembler();
162
+
163
+ let turnCounter = 0;
164
+ let turnId: string | undefined; // current open turn
165
+ let turnClosed = false;
166
+ let stepIndex = 0;
167
+ let stepId: string | undefined; // current open step marker id
168
+ let msgId: string | undefined; // current open message id
169
+ const openTextIds = new Set<string>();
170
+ const openReasoningIds = new Set<string>();
171
+ const pendingToolIds = new Set<string>(); // tool-input-start seen, tool-call not yet
172
+ let stashedError: string | undefined; // last in-band error message (arms A/B)
173
+
174
+ /** Mint + open the run's turn if not already open (defensive: arms other
175
+ * than `start` can arrive first on a hostile/truncated wire). */
176
+ function ensureTurn(): string {
177
+ if (turnId === undefined || turnClosed) {
178
+ turnId = `turn_vercel_${++turnCounter}`;
179
+ turnClosed = false;
180
+ a.openTurn(turnId, THREAD_ID);
181
+ }
182
+ return turnId;
183
+ }
184
+
185
+ /** Ensure an open message (defensive for content arriving before start-step). */
186
+ function ensureMessage(): string {
187
+ if (msgId === undefined) {
188
+ const t = ensureTurn();
189
+ stepIndex += 1;
190
+ stepId = `step_${stepIndex}`;
191
+ a.emit({ type: "step.start", id: stepId, turnId: t });
192
+ msgId = `msg_${t}_s${stepIndex}`;
193
+ a.openMessage({ id: msgId, role: "assistant", turnId: t, threadId: THREAD_ID, stepId });
194
+ }
195
+ return msgId;
196
+ }
197
+
198
+ /** Close any open text/reasoning streams (abort/host-error paths). */
199
+ function endOpenStreams(): void {
200
+ if (msgId === undefined) return;
201
+ for (const id of openTextIds) a.textEnd(id, msgId);
202
+ openTextIds.clear();
203
+ for (const id of openReasoningIds) a.reasoningEnd(id, msgId);
204
+ openReasoningIds.clear();
205
+ }
206
+
207
+ /** messageEnd BEFORE any turn-terminal event (D1/R5 ordering rule). */
208
+ function closeOpenMessage(usage?: AgUsage): void {
209
+ if (msgId === undefined) return;
210
+ endOpenStreams();
211
+ a.closeMessage(msgId, usage);
212
+ if (stepId !== undefined) a.emit({ type: "step.done", id: stepId });
213
+ msgId = undefined;
214
+ stepId = undefined;
215
+ }
216
+
217
+ function drive(part: VercelStreamPart): void {
218
+ switch (part.type) {
219
+ case "start": {
220
+ ensureTurn();
221
+ return;
222
+ }
223
+
224
+ case "start-step": {
225
+ const t = ensureTurn();
226
+ // Seal a dangling previous step defensively (the real wire always
227
+ // closes via finish-step first — verified tool-two-step capture).
228
+ if (msgId !== undefined) closeOpenMessage();
229
+ stepIndex += 1;
230
+ stepId = `step_${stepIndex}`;
231
+ a.emit({ type: "step.start", id: stepId, turnId: t });
232
+ msgId = `msg_${t}_s${stepIndex}`;
233
+ a.openMessage({ id: msgId, role: "assistant", turnId: t, threadId: THREAD_ID, stepId });
234
+ const warnings = part["warnings"];
235
+ if (Array.isArray(warnings) && warnings.length > 0) {
236
+ a.emitExt(THREAD_ID, "warnings", { stepId, warnings: safeJson(warnings) });
237
+ }
238
+ return;
239
+ }
240
+
241
+ case "text-start": {
242
+ const id = str(part["id"]);
243
+ if (id === undefined) break;
244
+ openTextIds.add(id);
245
+ a.textStart(id, ensureMessage());
246
+ return;
247
+ }
248
+ case "text-delta": {
249
+ const id = str(part["id"]);
250
+ const text = str(part["text"]); // fullStream field is `text` (verified)
251
+ if (id === undefined || text === undefined) break;
252
+ a.textDelta(id, ensureMessage(), text, { cumulative: false });
253
+ return;
254
+ }
255
+ case "text-end": {
256
+ const id = str(part["id"]);
257
+ if (id === undefined) break;
258
+ openTextIds.delete(id);
259
+ a.textEnd(id, ensureMessage());
260
+ return;
261
+ }
262
+
263
+ case "reasoning-start": {
264
+ const id = str(part["id"]);
265
+ if (id === undefined) break;
266
+ openReasoningIds.add(id);
267
+ a.reasoningStart(id, ensureMessage());
268
+ return;
269
+ }
270
+ case "reasoning-delta": {
271
+ const id = str(part["id"]);
272
+ const text = str(part["text"]); // `text` here too (verified)
273
+ if (id === undefined || text === undefined) break;
274
+ a.reasoningDelta(id, ensureMessage(), text, { cumulative: false });
275
+ return;
276
+ }
277
+ case "reasoning-end": {
278
+ const id = str(part["id"]);
279
+ if (id === undefined) break;
280
+ openReasoningIds.delete(id);
281
+ a.reasoningEnd(id, ensureMessage());
282
+ return;
283
+ }
284
+
285
+ case "tool-input-start": {
286
+ // fullStream keys the streamed-input lifecycle by `id` ≡ the eventual
287
+ // `tool-call.toolCallId` (R1, verified live).
288
+ const id = str(part["id"]);
289
+ const name = str(part["toolName"]);
290
+ if (id === undefined || name === undefined) break;
291
+ pendingToolIds.add(id);
292
+ a.toolStart({
293
+ toolCallId: id,
294
+ name,
295
+ messageId: ensureMessage(),
296
+ ...(typeof part["dynamic"] === "boolean" ? { dynamic: part["dynamic"] } : {}),
297
+ ...(str(part["title"]) !== undefined ? { title: str(part["title"]) } : {}),
298
+ ...(typeof part["providerExecuted"] === "boolean"
299
+ ? { providerExecuted: part["providerExecuted"] }
300
+ : {}),
301
+ });
302
+ return;
303
+ }
304
+ case "tool-input-delta": {
305
+ const id = str(part["id"]);
306
+ const delta = str(part["delta"]); // `delta` for tool input (verified)
307
+ if (id === undefined || delta === undefined) break;
308
+ a.toolArgsDelta(id, delta, { cumulative: false });
309
+ return;
310
+ }
311
+ case "tool-input-end": {
312
+ // Redundant on this seam — `tool-call` is the single authoritative
313
+ // assembled-input source (mapping table §1).
314
+ return;
315
+ }
316
+ case "tool-call": {
317
+ const toolCallId = str(part["toolCallId"]);
318
+ const name = str(part["toolName"]);
319
+ if (toolCallId === undefined || name === undefined) break;
320
+ const input = safeJson(part["input"] ?? {}); // parsed OBJECT on this wire (verified)
321
+ if (!pendingToolIds.has(toolCallId)) {
322
+ // Non-streamed call: synthesize the start+delta pair so the tool
323
+ // lifecycle stays well-formed (openai-facet built-in-tool precedent).
324
+ a.toolStart({
325
+ toolCallId,
326
+ name,
327
+ messageId: ensureMessage(),
328
+ ...(typeof part["dynamic"] === "boolean" ? { dynamic: part["dynamic"] } : {}),
329
+ });
330
+ a.toolArgsDelta(toolCallId, JSON.stringify(input), { cumulative: false });
331
+ }
332
+ pendingToolIds.delete(toolCallId);
333
+ a.toolArgsAssembled(toolCallId, input);
334
+ if (part["invalid"] === true) {
335
+ a.emitExt(THREAD_ID, "invalid-tool-call", {
336
+ toolCallId,
337
+ error: errText(part["error"]),
338
+ });
339
+ }
340
+ return;
341
+ }
342
+ case "tool-result": {
343
+ const toolCallId = str(part["toolCallId"]);
344
+ if (toolCallId === undefined) break;
345
+ const output = safeJson(part["output"]);
346
+ const preliminary = part["preliminary"] === true;
347
+ a.toolDone({
348
+ toolCallId,
349
+ outcome: "ok",
350
+ structuredContent: output,
351
+ content: [
352
+ { type: "text", text: typeof output === "string" ? output : JSON.stringify(output) },
353
+ ],
354
+ ...(preliminary ? { more: true, preliminary: true } : {}),
355
+ ...(typeof part["dynamic"] === "boolean" ? { dynamic: part["dynamic"] } : {}),
356
+ });
357
+ return;
358
+ }
359
+ case "tool-error": {
360
+ const toolCallId = str(part["toolCallId"]);
361
+ if (toolCallId === undefined) break;
362
+ const message = errText(part["error"]);
363
+ a.toolDone({
364
+ toolCallId,
365
+ outcome: "error",
366
+ isError: true,
367
+ errorText: message,
368
+ content: [{ type: "text", text: message }],
369
+ });
370
+ return;
371
+ }
372
+
373
+ case "finish-step": {
374
+ const response = rec(part["response"]);
375
+ if (msgId !== undefined && response !== undefined) {
376
+ // The step's response identity only surfaces HERE (verified) —
377
+ // land it as message metadata before sealing.
378
+ const metadata: { [k: string]: JsonValue } = {};
379
+ const responseId = str(response["id"]);
380
+ const modelId = str(response["modelId"]);
381
+ const rawFinish = str(part["rawFinishReason"]);
382
+ if (responseId !== undefined) metadata["responseId"] = responseId;
383
+ if (modelId !== undefined) metadata["model"] = modelId;
384
+ if (rawFinish !== undefined) metadata["rawFinishReason"] = rawFinish;
385
+ if (Object.keys(metadata).length > 0) {
386
+ a.emit({ type: "message.metadata", messageId: msgId, metadata });
387
+ }
388
+ }
389
+ closeOpenMessage(mapUsage(part["usage"]));
390
+ return;
391
+ }
392
+
393
+ case "finish": {
394
+ const t = ensureTurn();
395
+ closeOpenMessage(); // defensive; the real wire closes via finish-step first
396
+ if (str(part["finishReason"]) === "error") {
397
+ a.closeTurnError(t, { message: stashedError ?? "provider error" });
398
+ } else {
399
+ const usage = mapUsage(part["totalUsage"]);
400
+ a.closeTurnDone(t, {
401
+ outcome: { type: "success" },
402
+ finishReason: mapFinishReason(part["finishReason"]),
403
+ ...(usage !== undefined ? { usage } : {}),
404
+ });
405
+ }
406
+ turnClosed = true;
407
+ stashedError = undefined;
408
+ return;
409
+ }
410
+
411
+ case "error": {
412
+ // Non-terminal advisory (arm A); stashed for arm B's flush self-seal.
413
+ stashedError = errText(part["error"]);
414
+ a.emit({ type: "error", message: stashedError });
415
+ return;
416
+ }
417
+
418
+ case VERCEL_HOST_ERROR: {
419
+ // Arm C: transport failure thrown out of the iterator; host sentinel.
420
+ const t = ensureTurn();
421
+ stashedError = str(part["message"]) ?? "host iteration error";
422
+ a.emit({ type: "error", message: stashedError });
423
+ closeOpenMessage();
424
+ a.closeTurnError(t, { message: stashedError });
425
+ turnClosed = true;
426
+ stashedError = undefined;
427
+ return;
428
+ }
429
+
430
+ case "abort": {
431
+ const t = ensureTurn();
432
+ closeOpenMessage(); // messageEnd BEFORE turn.abort (R5 ordering rule)
433
+ const reason = str(part["reason"]);
434
+ a.emit({ type: "turn.abort", turnId: t, ...(reason !== undefined ? { reason } : {}) });
435
+ turnClosed = true;
436
+ return;
437
+ }
438
+
439
+ default:
440
+ break; // → tolerant frame carry below
441
+ }
442
+ // Tolerant default arm (R2): unknown part types AND known types with
443
+ // malformed payloads ride the lossless vendor channel.
444
+ a.emitExt(THREAD_ID, "frame", { kind: part.type, frame: safeJson(part) });
445
+ }
446
+
447
+ return {
448
+ push(native: unknown): AgEvent[] {
449
+ if (!isVercelStreamPart(native)) {
450
+ a.emitExt(THREAD_ID, "unparsed", { native: safeJson(native) });
451
+ return a.drain();
452
+ }
453
+ drive(native);
454
+ return a.drain();
455
+ },
456
+ flush(): AgEvent[] {
457
+ if (turnId !== undefined && !turnClosed) {
458
+ if (stashedError !== undefined) {
459
+ // Arm B: in-band error and the stream just ended (doStream
460
+ // rejection — verified: [start, error] then EOF). Self-seal.
461
+ closeOpenMessage();
462
+ a.closeTurnError(turnId, { message: stashedError });
463
+ turnClosed = true;
464
+ stashedError = undefined;
465
+ } else {
466
+ // Truncated stream with no error signal: seal the message; the
467
+ // engine's flush (INV-FLUSH) aborts the still-open turn.
468
+ closeOpenMessage();
469
+ }
470
+ }
471
+ return a.flush();
472
+ },
473
+ };
474
+ }
475
+
476
+ export default createVercelNormalizer;
477
+ export type { AgEvent, JsonValue };