@rulvar/bridge-ai-sdk 1.0.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,37 @@
1
+ import { LanguageModelV4 } from "@ai-sdk/provider";
2
+ import { ModelCaps, ProviderAdapter, WireError } from "@rulvar/core";
3
+
4
+ //#region src/bridge.d.ts
5
+ interface BridgeAiSdkOptions {
6
+ /**
7
+ * Adapter id (the left segment of ModelRef). Defaults to the wrapped
8
+ * model's `provider` string; pass an explicit id to register several
9
+ * bridged models of the same provider side by side.
10
+ */
11
+ id?: string;
12
+ /**
13
+ * Provider family for provider-raw retention and projection (docs/04,
14
+ * section 2.3). Defaults to the wrapped model's `provider` string, so
15
+ * two bridged models of one provider share retained blocks.
16
+ */
17
+ provider?: string;
18
+ /** Per-model capability overrides merged over the conservative defaults. */
19
+ caps?: (model: string) => ModelCaps | Partial<ModelCaps>;
20
+ }
21
+ /**
22
+ * Wraps a Vercel AI SDK LanguageModelV4 as a ProviderAdapter (docs/04,
23
+ * section 7). The bridge MUST check specificationVersion at runtime and
24
+ * fail with a typed ConfigError on mismatch. The published interface names
25
+ * the version V4; the wire literal carried by @ai-sdk/provider ^4 is 'v4'.
26
+ */
27
+ declare function bridgeAiSdk(model: LanguageModelV4, options?: BridgeAiSdkOptions): ProviderAdapter;
28
+ /**
29
+ * Projects a thrown value from the wrapped model into a typed WireError.
30
+ * APICallError carries the provider's status and headers: 429 surfaces as
31
+ * a retryable rate-limit with retryAfterMs; 5xx and status-less network
32
+ * failures are retryable transport; other statuses are terminal transport
33
+ * (docs/04, section 2.2).
34
+ */
35
+ declare function aiSdkErrorToWire(error: unknown): WireError;
36
+ //#endregion
37
+ export { type BridgeAiSdkOptions, aiSdkErrorToWire, bridgeAiSdk };
package/dist/index.js ADDED
@@ -0,0 +1,651 @@
1
+ import { APICallError } from "@ai-sdk/provider";
2
+ import { ConfigError, createCanonicalIdMinter } from "@rulvar/core";
3
+ //#region src/bridge.ts
4
+ /**
5
+ * @rulvar/bridge-ai-sdk (M9-T01): wraps any Vercel AI SDK LanguageModelV4
6
+ * as a ProviderAdapter for the long tail of providers (Google, Bedrock,
7
+ * Vertex) without coupling the core to the ai-sdk release cycle.
8
+ *
9
+ * Owning spec: docs/04-model-layer-spec.md, section "@rulvar/bridge-ai-sdk".
10
+ * This is documented as the highest-churn package in the set: it tracks the
11
+ * @ai-sdk/provider major line (^4, pinned in docs/13, section "Dependency
12
+ * baseline pins") and checks specificationVersion at runtime so a transitive
13
+ * provider-package major cannot mis-wire silently.
14
+ */
15
+ /**
16
+ * Conservative capability set for a model the bridge cannot introspect:
17
+ * the LanguageModelV4 interface exposes no capability discovery, so the
18
+ * defaults mirror the openaiCompatible factory posture (docs/04, section
19
+ * 6) except structuredOutput, where responseFormat json IS the V4-native
20
+ * mechanism every ai-sdk provider accepts. Callers SHOULD supply caps for
21
+ * anything beyond this.
22
+ */
23
+ const CONSERVATIVE_BRIDGE_CAPS = {
24
+ structuredOutput: "native",
25
+ supportsTemperature: true,
26
+ supportsParallelTools: false,
27
+ reasoningEfforts: [],
28
+ contextWindow: 8192,
29
+ maxOutputTokens: 4096
30
+ };
31
+ /**
32
+ * Canonical effort to V4 reasoning effort. Canonical 'max' has no V4
33
+ * equivalent and downmaps to 'xhigh' (the documented lossy downmap pattern
34
+ * of docs/04, section 3.3); the downmap is recorded in providerMetadata.
35
+ * Identity always keeps the requested canonical effort.
36
+ */
37
+ const EFFORT_TO_V4 = {
38
+ low: "low",
39
+ medium: "medium",
40
+ high: "high",
41
+ xhigh: "xhigh",
42
+ max: "xhigh"
43
+ };
44
+ /**
45
+ * Keys of the bridge's providerOptions namespace that would contradict a
46
+ * canonical ChatRequest field. Canonical fields always win; a namespaced
47
+ * option silently contradicting one is a typed ConfigError (docs/04,
48
+ * section 1.8).
49
+ */
50
+ const CANONICAL_CONFLICT_KEYS = [
51
+ "prompt",
52
+ "maxOutputTokens",
53
+ "stopSequences",
54
+ "responseFormat",
55
+ "tools",
56
+ "toolChoice",
57
+ "reasoning",
58
+ "abortSignal"
59
+ ];
60
+ /** Transport knobs the bridge lifts from its namespace into V4 call options. */
61
+ const LIFTED_OPTION_KEYS = [
62
+ "temperature",
63
+ "topP",
64
+ "topK",
65
+ "seed",
66
+ "presencePenalty",
67
+ "frequencyPenalty",
68
+ "headers"
69
+ ];
70
+ /**
71
+ * Bijective map between engine-minted CanonicalIds and the wrapped
72
+ * provider's wire tool-call ids (docs/04, section 1.2). V4 accepts
73
+ * arbitrary strings as toolCallId, so a canonical id minted outside this
74
+ * provider is used verbatim as its own wire id.
75
+ */
76
+ var BridgeIdMap = class {
77
+ toWire = /* @__PURE__ */ new Map();
78
+ toCanonical = /* @__PURE__ */ new Map();
79
+ mint;
80
+ constructor(mint) {
81
+ this.mint = mint;
82
+ }
83
+ canonicalFor(wireId) {
84
+ const existing = this.toCanonical.get(wireId);
85
+ if (existing !== void 0) return existing;
86
+ const canonical = this.mint();
87
+ this.toCanonical.set(wireId, canonical);
88
+ this.toWire.set(canonical, wireId);
89
+ return canonical;
90
+ }
91
+ wireFor(canonicalId) {
92
+ const existing = this.toWire.get(canonicalId);
93
+ if (existing !== void 0) return existing;
94
+ this.toWire.set(canonicalId, canonicalId);
95
+ this.toCanonical.set(canonicalId, canonicalId);
96
+ return canonicalId;
97
+ }
98
+ };
99
+ /**
100
+ * Wraps a Vercel AI SDK LanguageModelV4 as a ProviderAdapter (docs/04,
101
+ * section 7). The bridge MUST check specificationVersion at runtime and
102
+ * fail with a typed ConfigError on mismatch. The published interface names
103
+ * the version V4; the wire literal carried by @ai-sdk/provider ^4 is 'v4'.
104
+ */
105
+ function bridgeAiSdk(model, options = {}) {
106
+ const version = model.specificationVersion;
107
+ if (version !== "v4") throw new ConfigError(`bridgeAiSdk requires a LanguageModelV4 (specificationVersion 'v4'); received ${JSON.stringify(version)}. A mismatched @ai-sdk/provider major cannot be bridged (docs/04, section 7).`, { data: { received: typeof version === "string" ? version : null } });
108
+ const id = options.id ?? model.provider;
109
+ if (id === void 0 || id === "") throw new ConfigError("bridgeAiSdk requires a non-empty adapter id (model.provider was empty)");
110
+ const family = options.provider ?? model.provider;
111
+ const ids = new BridgeIdMap(createCanonicalIdMinter());
112
+ return {
113
+ id,
114
+ provider: family,
115
+ caps(wireModel) {
116
+ const overrides = options.caps?.(wireModel);
117
+ return overrides === void 0 ? CONSERVATIVE_BRIDGE_CAPS : {
118
+ ...CONSERVATIVE_BRIDGE_CAPS,
119
+ ...overrides
120
+ };
121
+ },
122
+ async *stream(req, signal) {
123
+ if (req.model !== model.modelId) throw new ConfigError(`bridgeAiSdk adapter '${id}' wraps model '${model.modelId}' but was asked for '${req.model}'; register one bridgeAiSdk adapter per wrapped model`);
124
+ const built = buildCallOptions(req, {
125
+ adapterId: id,
126
+ family,
127
+ ids,
128
+ signal
129
+ });
130
+ let result;
131
+ try {
132
+ result = await model.doStream(built.callOptions);
133
+ } catch (thrown) {
134
+ if (signal?.aborted === true) return;
135
+ yield {
136
+ type: "error",
137
+ error: aiSdkErrorToWire(thrown)
138
+ };
139
+ return;
140
+ }
141
+ const mapper = new StreamMapper(id, ids, built.effortDownmapped);
142
+ try {
143
+ for await (const part of iterateStream(result.stream)) {
144
+ for (const event of mapper.map(part)) yield event;
145
+ if (mapper.terminal) return;
146
+ }
147
+ } catch (thrown) {
148
+ if (signal?.aborted === true) return;
149
+ yield {
150
+ type: "error",
151
+ error: aiSdkErrorToWire(thrown)
152
+ };
153
+ return;
154
+ }
155
+ if (!mapper.terminal) yield {
156
+ type: "error",
157
+ error: {
158
+ code: "agent",
159
+ message: `bridged model '${model.modelId}' ended its stream without a finish part`,
160
+ retryable: true,
161
+ data: { kind: "transport" }
162
+ }
163
+ };
164
+ }
165
+ };
166
+ }
167
+ async function* iterateStream(stream) {
168
+ const reader = stream.getReader();
169
+ try {
170
+ while (true) {
171
+ const { done, value } = await reader.read();
172
+ if (done) return;
173
+ yield value;
174
+ }
175
+ } finally {
176
+ reader.releaseLock();
177
+ }
178
+ }
179
+ function buildCallOptions(req, context) {
180
+ const callOptions = { prompt: mapMessages(req.messages, context) };
181
+ if (req.maxOutputTokens !== void 0) callOptions.maxOutputTokens = req.maxOutputTokens;
182
+ if (req.stopSequences !== void 0) callOptions.stopSequences = req.stopSequences;
183
+ if (req.tools !== void 0 && req.tools.length > 0) callOptions.tools = req.tools.map((tool) => ({
184
+ type: "function",
185
+ name: tool.name,
186
+ description: tool.description,
187
+ inputSchema: tool.parameters
188
+ }));
189
+ if (req.toolChoice !== void 0) callOptions.toolChoice = mapToolChoice(req.toolChoice);
190
+ if (req.schema !== void 0) callOptions.responseFormat = {
191
+ type: "json",
192
+ schema: req.schema
193
+ };
194
+ let effortDownmapped = false;
195
+ if (req.effort !== void 0) {
196
+ callOptions.reasoning = EFFORT_TO_V4[req.effort];
197
+ effortDownmapped = req.effort === "max";
198
+ }
199
+ if (context.signal !== void 0) callOptions.abortSignal = context.signal;
200
+ applyNamespacedOptions(req, callOptions, context.adapterId);
201
+ return {
202
+ callOptions,
203
+ effortDownmapped
204
+ };
205
+ }
206
+ function applyNamespacedOptions(req, callOptions, adapterId) {
207
+ const ns = req.providerOptions?.[adapterId];
208
+ if (ns === void 0) return;
209
+ for (const key of CANONICAL_CONFLICT_KEYS) if (key in ns) throw new ConfigError(`providerOptions.${adapterId}.${key} contradicts a canonical ChatRequest field; canonical fields always win (docs/04, section 1.8)`);
210
+ for (const key of LIFTED_OPTION_KEYS) if (ns[key] !== void 0) callOptions[key] = ns[key];
211
+ if (ns.providerOptions !== void 0) callOptions.providerOptions = ns.providerOptions;
212
+ }
213
+ function mapToolChoice(choice) {
214
+ if (choice === "auto") return { type: "auto" };
215
+ if (choice === "none") return { type: "none" };
216
+ if (choice === "required") return { type: "required" };
217
+ return {
218
+ type: "tool",
219
+ toolName: choice.name
220
+ };
221
+ }
222
+ function mapMessages(messages, context) {
223
+ const prompt = [];
224
+ for (const message of messages) {
225
+ if (message.role === "system") {
226
+ const text = message.parts.map((part) => part.type === "text" ? part.text : "").join("");
227
+ prompt.push({
228
+ role: "system",
229
+ content: text
230
+ });
231
+ continue;
232
+ }
233
+ if (message.role === "user") {
234
+ const content = [];
235
+ for (const part of message.parts) if (part.type === "text") content.push({
236
+ type: "text",
237
+ text: part.text
238
+ });
239
+ else if (part.type === "image") content.push({
240
+ type: "file",
241
+ mediaType: part.mediaType,
242
+ data: toFileData(part.data)
243
+ });
244
+ prompt.push({
245
+ role: "user",
246
+ content
247
+ });
248
+ continue;
249
+ }
250
+ if (message.role === "assistant") {
251
+ const content = [];
252
+ for (const part of message.parts) if (part.type === "text") content.push({
253
+ type: "text",
254
+ text: part.text
255
+ });
256
+ else if (part.type === "tool-call") content.push({
257
+ type: "tool-call",
258
+ toolCallId: context.ids.wireFor(part.id),
259
+ toolName: part.name,
260
+ input: part.args
261
+ });
262
+ else if (part.type === "provider-raw" && part.provider === context.family) {
263
+ const reinserted = reinsertRetained(part.block);
264
+ if (reinserted !== void 0) content.push(reinserted);
265
+ }
266
+ prompt.push({
267
+ role: "assistant",
268
+ content
269
+ });
270
+ continue;
271
+ }
272
+ const content = [];
273
+ for (const part of message.parts) if (part.type === "tool-result") content.push({
274
+ type: "tool-result",
275
+ toolCallId: context.ids.wireFor(part.id),
276
+ toolName: part.name,
277
+ output: part.isError === true ? {
278
+ type: "error-text",
279
+ value: stringifyResult(part.result)
280
+ } : {
281
+ type: "json",
282
+ value: part.result
283
+ }
284
+ });
285
+ prompt.push({
286
+ role: "tool",
287
+ content
288
+ });
289
+ }
290
+ return prompt;
291
+ }
292
+ /**
293
+ * Transforms a retained stream part (shipped through finish
294
+ * providerMetadata retainedParts and lifted into a provider-raw part by
295
+ * the runtime, docs/04, section 2.3) back into its V4 prompt-part shape.
296
+ * Response-side providerMetadata becomes prompt-side providerOptions.
297
+ */
298
+ function reinsertRetained(block) {
299
+ if (typeof block !== "object" || block === null) return;
300
+ const record = block;
301
+ const meta = record.providerMetadata;
302
+ const withMeta = meta === void 0 ? {} : { providerOptions: meta };
303
+ switch (record.type) {
304
+ case "reasoning": return {
305
+ type: "reasoning",
306
+ text: record.text,
307
+ ...withMeta
308
+ };
309
+ case "custom": return {
310
+ type: "custom",
311
+ kind: record.kind,
312
+ ...withMeta
313
+ };
314
+ case "file": return {
315
+ type: "file",
316
+ mediaType: record.mediaType,
317
+ data: record.data,
318
+ ...withMeta
319
+ };
320
+ case "reasoning-file": return {
321
+ type: "reasoning-file",
322
+ mediaType: record.mediaType,
323
+ data: record.data,
324
+ ...withMeta
325
+ };
326
+ case "tool-call": return {
327
+ type: "tool-call",
328
+ toolCallId: record.toolCallId,
329
+ toolName: record.toolName,
330
+ input: record.input,
331
+ providerExecuted: true,
332
+ ...withMeta
333
+ };
334
+ case "tool-result": return {
335
+ type: "tool-result",
336
+ toolCallId: record.toolCallId,
337
+ toolName: record.toolName,
338
+ output: {
339
+ type: "json",
340
+ value: record.result
341
+ },
342
+ ...withMeta
343
+ };
344
+ default: return;
345
+ }
346
+ }
347
+ function toFileData(data) {
348
+ if (typeof data === "string" && (/^https?:/i.test(data) || data.startsWith("data:"))) return {
349
+ type: "url",
350
+ url: new URL(data)
351
+ };
352
+ return {
353
+ type: "data",
354
+ data
355
+ };
356
+ }
357
+ function stringifyResult(result) {
358
+ return typeof result === "string" ? result : JSON.stringify(result) ?? "null";
359
+ }
360
+ /**
361
+ * Maps the V4 stream-part vocabulary onto ChatEvents, assembling tool
362
+ * arguments, normalizing usage under the Usage invariant, and collecting
363
+ * the turn's retention payload (reasoning parts with their signatures,
364
+ * custom blocks, generated files, provider-executed tool exchanges) for
365
+ * finish providerMetadata retainedParts.
366
+ */
367
+ var StreamMapper = class {
368
+ terminal = false;
369
+ adapterId;
370
+ ids;
371
+ effortDownmapped;
372
+ toolNames = /* @__PURE__ */ new Map();
373
+ startedToolWireIds = /* @__PURE__ */ new Set();
374
+ providerExecutedWireIds = /* @__PURE__ */ new Set();
375
+ reasoning = /* @__PURE__ */ new Map();
376
+ retained = [];
377
+ warnings = [];
378
+ response;
379
+ constructor(adapterId, ids, effortDownmapped) {
380
+ this.adapterId = adapterId;
381
+ this.ids = ids;
382
+ this.effortDownmapped = effortDownmapped;
383
+ }
384
+ map(part) {
385
+ switch (part.type) {
386
+ case "stream-start":
387
+ this.warnings = part.warnings;
388
+ return [];
389
+ case "response-metadata": {
390
+ const response = {};
391
+ if (part.id !== void 0) response.id = part.id;
392
+ if (part.modelId !== void 0) response.modelId = part.modelId;
393
+ if (part.timestamp !== void 0) response.timestamp = part.timestamp.toISOString();
394
+ if (Object.keys(response).length > 0) this.response = response;
395
+ return [];
396
+ }
397
+ case "text-start":
398
+ case "text-end": return [];
399
+ case "text-delta": return [{
400
+ type: "text-delta",
401
+ text: part.delta
402
+ }];
403
+ case "reasoning-start":
404
+ this.reasoning.set(part.id, {
405
+ text: "",
406
+ ...part.providerMetadata === void 0 ? {} : { providerMetadata: { ...part.providerMetadata } }
407
+ });
408
+ return [];
409
+ case "reasoning-delta": {
410
+ const acc = this.reasoning.get(part.id) ?? { text: "" };
411
+ acc.text += part.delta;
412
+ this.mergeReasoningMeta(acc, part.providerMetadata);
413
+ this.reasoning.set(part.id, acc);
414
+ return [{
415
+ type: "reasoning-delta",
416
+ text: part.delta
417
+ }];
418
+ }
419
+ case "reasoning-end": {
420
+ const acc = this.reasoning.get(part.id);
421
+ if (acc !== void 0) {
422
+ this.mergeReasoningMeta(acc, part.providerMetadata);
423
+ this.retained.push({
424
+ type: "reasoning",
425
+ text: acc.text,
426
+ ...acc.providerMetadata === void 0 ? {} : { providerMetadata: acc.providerMetadata }
427
+ });
428
+ this.reasoning.delete(part.id);
429
+ }
430
+ return [];
431
+ }
432
+ case "tool-input-start":
433
+ if (part.providerExecuted === true) {
434
+ this.providerExecutedWireIds.add(part.id);
435
+ return [];
436
+ }
437
+ this.toolNames.set(part.id, part.toolName);
438
+ this.startedToolWireIds.add(part.id);
439
+ return [{
440
+ type: "tool-call-start",
441
+ id: this.ids.canonicalFor(part.id),
442
+ name: part.toolName
443
+ }];
444
+ case "tool-input-delta":
445
+ if (this.providerExecutedWireIds.has(part.id)) return [];
446
+ return [{
447
+ type: "tool-call-delta",
448
+ id: this.ids.canonicalFor(part.id),
449
+ argsTextDelta: part.delta
450
+ }];
451
+ case "tool-input-end": return [];
452
+ case "tool-call": {
453
+ if (part.providerExecuted === true) {
454
+ this.providerExecutedWireIds.add(part.toolCallId);
455
+ const parsed = parseToolArgs(part.input);
456
+ this.retained.push({
457
+ type: "tool-call",
458
+ toolCallId: part.toolCallId,
459
+ toolName: part.toolName,
460
+ input: parsed.ok ? parsed.value : part.input,
461
+ providerExecuted: true,
462
+ ...part.providerMetadata === void 0 ? {} : { providerMetadata: part.providerMetadata }
463
+ });
464
+ return [];
465
+ }
466
+ const events = [];
467
+ const canonical = this.ids.canonicalFor(part.toolCallId);
468
+ if (!this.startedToolWireIds.has(part.toolCallId)) events.push({
469
+ type: "tool-call-start",
470
+ id: canonical,
471
+ name: part.toolName
472
+ });
473
+ const parsed = parseToolArgs(part.input);
474
+ if (parsed.ok) events.push({
475
+ type: "tool-call-end",
476
+ id: canonical,
477
+ args: parsed.value
478
+ });
479
+ else {
480
+ this.terminal = true;
481
+ events.push({
482
+ type: "error",
483
+ error: {
484
+ code: "agent",
485
+ message: `bridged tool call '${part.toolName}' carried arguments that are not valid JSON`,
486
+ retryable: true,
487
+ data: { kind: "transport" }
488
+ }
489
+ });
490
+ }
491
+ return events;
492
+ }
493
+ case "tool-result":
494
+ this.retained.push({
495
+ type: "tool-result",
496
+ toolCallId: part.toolCallId,
497
+ toolName: part.toolName,
498
+ result: part.result,
499
+ ...part.isError === void 0 ? {} : { isError: part.isError },
500
+ ...part.providerMetadata === void 0 ? {} : { providerMetadata: part.providerMetadata }
501
+ });
502
+ return [];
503
+ case "tool-approval-request":
504
+ this.terminal = true;
505
+ return [{
506
+ type: "error",
507
+ error: {
508
+ code: "agent",
509
+ message: "the bridged provider requested approval for a provider-executed tool call; provider-executed tool approval flows are not supported through bridgeAiSdk",
510
+ retryable: false,
511
+ data: { kind: "terminal" }
512
+ }
513
+ }];
514
+ case "custom":
515
+ case "file":
516
+ case "reasoning-file":
517
+ this.retained.push(part);
518
+ return [];
519
+ case "source":
520
+ case "raw": return [];
521
+ case "finish":
522
+ this.terminal = true;
523
+ return this.mapFinish(part);
524
+ case "error":
525
+ this.terminal = true;
526
+ return [{
527
+ type: "error",
528
+ error: aiSdkErrorToWire(part.error)
529
+ }];
530
+ default: return [];
531
+ }
532
+ }
533
+ mergeReasoningMeta(acc, meta) {
534
+ if (meta === void 0) return;
535
+ acc.providerMetadata = {
536
+ ...acc.providerMetadata,
537
+ ...meta
538
+ };
539
+ }
540
+ mapFinish(part) {
541
+ if (part.finishReason.unified === "error") return [{
542
+ type: "error",
543
+ error: {
544
+ code: "agent",
545
+ message: part.finishReason.raw === void 0 ? "bridged provider reported an error finish" : `bridged provider reported an error finish (${part.finishReason.raw})`,
546
+ retryable: true,
547
+ data: { kind: "transport" }
548
+ }
549
+ }];
550
+ const finish = mapFinishReason(part.finishReason, this.adapterId);
551
+ const usage = mapUsage(part.usage);
552
+ const bag = {};
553
+ if (this.retained.length > 0) bag.retainedParts = this.retained;
554
+ if (this.warnings.length > 0) bag.warnings = this.warnings;
555
+ if (this.response !== void 0) bag.response = this.response;
556
+ if (part.providerMetadata !== void 0) bag.upstream = part.providerMetadata;
557
+ if (this.effortDownmapped) bag.effortDownmap = "max->xhigh";
558
+ if (part.finishReason.unified === "other" && part.finishReason.raw !== void 0) bag.finishRaw = part.finishReason.raw;
559
+ return [{
560
+ type: "finish",
561
+ finish,
562
+ usage,
563
+ ...Object.keys(bag).length === 0 ? {} : { providerMetadata: { [this.adapterId]: bag } }
564
+ }];
565
+ }
566
+ };
567
+ function mapFinishReason(reason, adapterId) {
568
+ switch (reason.unified) {
569
+ case "tool-calls": return { reason: "tool-calls" };
570
+ case "length": return { reason: "max-tokens" };
571
+ case "content-filter": return {
572
+ reason: "refusal",
573
+ refusal: {
574
+ provider: adapterId,
575
+ stopDetails: { type: reason.raw ?? "content-filter" }
576
+ }
577
+ };
578
+ default: return { reason: "stop" };
579
+ }
580
+ }
581
+ /**
582
+ * Normalizes V4 nested usage to the flat Usage under the Usage invariant:
583
+ * inputTokens is the FULL prompt including cache reads and writes
584
+ * (docs/04, section 1.6). When the provider's total disagrees with the
585
+ * component sum, the larger value wins so the invariant holds by
586
+ * construction.
587
+ */
588
+ function mapUsage(usage) {
589
+ const cacheRead = usage.inputTokens.cacheRead ?? 0;
590
+ const cacheWrite = usage.inputTokens.cacheWrite ?? 0;
591
+ const derivedInput = (usage.inputTokens.noCache ?? 0) + cacheRead + cacheWrite;
592
+ const inputTokens = Math.max(usage.inputTokens.total ?? 0, derivedInput);
593
+ const derivedOutput = (usage.outputTokens.text ?? 0) + (usage.outputTokens.reasoning ?? 0);
594
+ return {
595
+ inputTokens,
596
+ outputTokens: Math.max(usage.outputTokens.total ?? 0, derivedOutput),
597
+ cacheReadTokens: cacheRead,
598
+ cacheWriteTokens: cacheWrite,
599
+ ...usage.outputTokens.reasoning === void 0 ? {} : { reasoningTokens: usage.outputTokens.reasoning }
600
+ };
601
+ }
602
+ function parseToolArgs(input) {
603
+ if (input === "") return {
604
+ ok: true,
605
+ value: {}
606
+ };
607
+ try {
608
+ return {
609
+ ok: true,
610
+ value: JSON.parse(input)
611
+ };
612
+ } catch {
613
+ return { ok: false };
614
+ }
615
+ }
616
+ /**
617
+ * Projects a thrown value from the wrapped model into a typed WireError.
618
+ * APICallError carries the provider's status and headers: 429 surfaces as
619
+ * a retryable rate-limit with retryAfterMs; 5xx and status-less network
620
+ * failures are retryable transport; other statuses are terminal transport
621
+ * (docs/04, section 2.2).
622
+ */
623
+ function aiSdkErrorToWire(error) {
624
+ const record = error;
625
+ const status = typeof record.statusCode === "number" ? record.statusCode : typeof record.status === "number" ? record.status : void 0;
626
+ const message = typeof record.message === "string" ? record.message : String(error);
627
+ if (status === 429) {
628
+ const retryAfter = record.responseHeaders?.["retry-after"];
629
+ return {
630
+ code: "agent",
631
+ message,
632
+ retryable: true,
633
+ data: {
634
+ kind: "rate-limit",
635
+ ...retryAfter === void 0 || Number.isNaN(Number(retryAfter)) ? {} : { retryAfterMs: Number(retryAfter) * 1e3 },
636
+ status: 429
637
+ }
638
+ };
639
+ }
640
+ return {
641
+ code: "agent",
642
+ message,
643
+ retryable: APICallError.isInstance(error) ? error.isRetryable : status === void 0 || status >= 500,
644
+ data: {
645
+ kind: "transport",
646
+ ...status === void 0 ? {} : { status }
647
+ }
648
+ };
649
+ }
650
+ //#endregion
651
+ export { aiSdkErrorToWire, bridgeAiSdk };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@rulvar/bridge-ai-sdk",
3
+ "version": "1.0.0",
4
+ "description": "rulvar bridge adapter wrapping any Vercel AI SDK LanguageModelV4 as a ProviderAdapter.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "engines": {
8
+ "node": ">=22.12.0"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "sideEffects": false,
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "dependencies": {
25
+ "@ai-sdk/provider": "^4.0.0",
26
+ "@rulvar/core": "1.0.0"
27
+ },
28
+ "devDependencies": {
29
+ "@ai-sdk/google": "^4.0.0",
30
+ "@types/node": "^22.20.0",
31
+ "tsdown": "^0.22.3",
32
+ "typescript": "~6.0.3"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/o-stepper/rulvar.git",
37
+ "directory": "packages/bridge-ai-sdk"
38
+ },
39
+ "homepage": "https://rulvar.com",
40
+ "bugs": {
41
+ "url": "https://github.com/o-stepper/rulvar/issues"
42
+ },
43
+ "scripts": {
44
+ "build": "tsdown",
45
+ "typecheck": "tsc --noEmit",
46
+ "lint": "eslint .",
47
+ "pack-check": "publint --pack pnpm && attw --pack . --profile esm-only"
48
+ }
49
+ }