@tinyweb_dev/agent-framework-llm 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/dist/cache-policy.d.ts +3 -0
  2. package/dist/cache-policy.d.ts.map +1 -0
  3. package/dist/index.cjs +2956 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +23 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +2831 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/llm.cjs +1718 -0
  10. package/dist/llm.cjs.map +1 -0
  11. package/dist/llm.d.ts +284 -0
  12. package/dist/llm.d.ts.map +1 -0
  13. package/dist/llm.js +1692 -0
  14. package/dist/llm.js.map +1 -0
  15. package/dist/protocols/openai-chat.cjs +2443 -0
  16. package/dist/protocols/openai-chat.cjs.map +1 -0
  17. package/dist/protocols/openai-chat.d.ts +357 -0
  18. package/dist/protocols/openai-chat.d.ts.map +1 -0
  19. package/dist/protocols/openai-chat.js +2414 -0
  20. package/dist/protocols/openai-chat.js.map +1 -0
  21. package/dist/protocols/openai-compatible-chat.cjs +2443 -0
  22. package/dist/protocols/openai-compatible-chat.cjs.map +1 -0
  23. package/dist/protocols/openai-compatible-chat.d.ts +77 -0
  24. package/dist/protocols/openai-compatible-chat.d.ts.map +1 -0
  25. package/dist/protocols/openai-compatible-chat.js +2419 -0
  26. package/dist/protocols/openai-compatible-chat.js.map +1 -0
  27. package/dist/protocols/shared.cjs +904 -0
  28. package/dist/protocols/shared.cjs.map +1 -0
  29. package/dist/protocols/shared.d.ts +51 -0
  30. package/dist/protocols/shared.d.ts.map +1 -0
  31. package/dist/protocols/shared.js +857 -0
  32. package/dist/protocols/shared.js.map +1 -0
  33. package/dist/protocols/utils/openai-options.d.ts +15 -0
  34. package/dist/protocols/utils/openai-options.d.ts.map +1 -0
  35. package/dist/protocols/utils/tool-stream.d.ts +78 -0
  36. package/dist/protocols/utils/tool-stream.d.ts.map +1 -0
  37. package/dist/provider.cjs +20 -0
  38. package/dist/provider.cjs.map +1 -0
  39. package/dist/provider.d.ts +19 -0
  40. package/dist/provider.d.ts.map +1 -0
  41. package/dist/provider.js +17 -0
  42. package/dist/provider.js.map +1 -0
  43. package/{src/providers/openai-compatible-profile.ts → dist/providers/openai-compatible-profile.cjs} +12 -12
  44. package/dist/providers/openai-compatible-profile.cjs.map +1 -0
  45. package/dist/providers/openai-compatible-profile.d.ts +52 -0
  46. package/dist/providers/openai-compatible-profile.d.ts.map +1 -0
  47. package/dist/providers/openai-compatible-profile.js +21 -0
  48. package/dist/providers/openai-compatible-profile.js.map +1 -0
  49. package/dist/providers/openai-compatible.cjs +2533 -0
  50. package/dist/providers/openai-compatible.cjs.map +1 -0
  51. package/dist/providers/openai-compatible.d.ts +128 -0
  52. package/dist/providers/openai-compatible.d.ts.map +1 -0
  53. package/dist/providers/openai-compatible.js +2495 -0
  54. package/dist/providers/openai-compatible.js.map +1 -0
  55. package/dist/providers/openai-options.cjs +797 -0
  56. package/dist/providers/openai-options.cjs.map +1 -0
  57. package/dist/providers/openai-options.d.ts +29 -0
  58. package/dist/providers/openai-options.d.ts.map +1 -0
  59. package/dist/providers/openai-options.js +792 -0
  60. package/dist/providers/openai-options.js.map +1 -0
  61. package/dist/providers/openai.cjs +2517 -0
  62. package/dist/providers/openai.cjs.map +1 -0
  63. package/dist/providers/openai.d.ts +87 -0
  64. package/dist/providers/openai.d.ts.map +1 -0
  65. package/dist/providers/openai.js +2489 -0
  66. package/dist/providers/openai.js.map +1 -0
  67. package/dist/route/auth-options.cjs +855 -0
  68. package/dist/route/auth-options.cjs.map +1 -0
  69. package/dist/route/auth-options.d.ts +25 -0
  70. package/dist/route/auth-options.d.ts.map +1 -0
  71. package/dist/route/auth-options.js +852 -0
  72. package/dist/route/auth-options.js.map +1 -0
  73. package/dist/route/auth.cjs +855 -0
  74. package/dist/route/auth.cjs.map +1 -0
  75. package/dist/route/auth.d.ts +51 -0
  76. package/dist/route/auth.d.ts.map +1 -0
  77. package/dist/route/auth.js +836 -0
  78. package/dist/route/auth.js.map +1 -0
  79. package/dist/route/client.cjs +1844 -0
  80. package/dist/route/client.cjs.map +1 -0
  81. package/dist/route/client.d.ts +268 -0
  82. package/dist/route/client.d.ts.map +1 -0
  83. package/dist/route/client.js +1830 -0
  84. package/dist/route/client.js.map +1 -0
  85. package/dist/route/endpoint.cjs +756 -0
  86. package/dist/route/endpoint.cjs.map +1 -0
  87. package/dist/route/endpoint.d.ts +13 -0
  88. package/dist/route/endpoint.d.ts.map +1 -0
  89. package/dist/route/endpoint.js +752 -0
  90. package/dist/route/endpoint.js.map +1 -0
  91. package/dist/route/executor.cjs +1077 -0
  92. package/dist/route/executor.cjs.map +1 -0
  93. package/dist/route/executor.d.ts +13 -0
  94. package/dist/route/executor.d.ts.map +1 -0
  95. package/dist/route/executor.js +1072 -0
  96. package/dist/route/executor.js.map +1 -0
  97. package/dist/route/framing.cjs +773 -0
  98. package/dist/route/framing.cjs.map +1 -0
  99. package/dist/route/framing.d.ts +9 -0
  100. package/dist/route/framing.d.ts.map +1 -0
  101. package/dist/route/framing.js +750 -0
  102. package/dist/route/framing.js.map +1 -0
  103. package/dist/route/overflow-detect.d.ts +18 -0
  104. package/dist/route/overflow-detect.d.ts.map +1 -0
  105. package/dist/route/protocol.cjs +25 -0
  106. package/dist/route/protocol.cjs.map +1 -0
  107. package/dist/route/protocol.d.ts +40 -0
  108. package/dist/route/protocol.d.ts.map +1 -0
  109. package/dist/route/protocol.js +21 -0
  110. package/dist/route/protocol.js.map +1 -0
  111. package/dist/route/transport/http.d.ts +48 -0
  112. package/dist/route/transport/http.d.ts.map +1 -0
  113. package/dist/route/transport/index.cjs +969 -0
  114. package/dist/route/transport/index.cjs.map +1 -0
  115. package/dist/route/transport/index.d.ts +13 -0
  116. package/dist/route/transport/index.d.ts.map +1 -0
  117. package/dist/route/transport/index.js +967 -0
  118. package/dist/route/transport/index.js.map +1 -0
  119. package/dist/schema/errors.d.ts +181 -0
  120. package/dist/schema/errors.d.ts.map +1 -0
  121. package/dist/schema/events.d.ts +3224 -0
  122. package/dist/schema/events.d.ts.map +1 -0
  123. package/dist/schema/ids.d.ts +31 -0
  124. package/dist/schema/ids.d.ts.map +1 -0
  125. package/dist/schema/index.cjs +847 -0
  126. package/dist/schema/index.cjs.map +1 -0
  127. package/dist/schema/index.d.ts +6 -0
  128. package/dist/schema/index.d.ts.map +1 -0
  129. package/dist/schema/index.js +777 -0
  130. package/dist/schema/index.js.map +1 -0
  131. package/dist/schema/messages.d.ts +292 -0
  132. package/dist/schema/messages.d.ts.map +1 -0
  133. package/dist/schema/options.d.ts +123 -0
  134. package/dist/schema/options.d.ts.map +1 -0
  135. package/dist/tool-runtime.cjs +907 -0
  136. package/dist/tool-runtime.cjs.map +1 -0
  137. package/dist/tool-runtime.d.ts +50 -0
  138. package/dist/tool-runtime.d.ts.map +1 -0
  139. package/dist/tool-runtime.js +901 -0
  140. package/dist/tool-runtime.js.map +1 -0
  141. package/dist/tool.cjs +802 -0
  142. package/dist/tool.cjs.map +1 -0
  143. package/dist/tool.d.ts +111 -0
  144. package/dist/tool.d.ts.map +1 -0
  145. package/dist/tool.js +796 -0
  146. package/dist/tool.js.map +1 -0
  147. package/package.json +112 -29
  148. package/src/cache-policy.ts +0 -92
  149. package/src/index.ts +0 -62
  150. package/src/llm.ts +0 -210
  151. package/src/protocols/openai-chat.ts +0 -464
  152. package/src/protocols/openai-compatible-chat.ts +0 -29
  153. package/src/protocols/shared.ts +0 -204
  154. package/src/protocols/utils/openai-options.ts +0 -56
  155. package/src/protocols/utils/tool-stream.ts +0 -135
  156. package/src/provider.ts +0 -32
  157. package/src/providers/openai-compatible.ts +0 -69
  158. package/src/providers/openai-options.ts +0 -71
  159. package/src/providers/openai.ts +0 -39
  160. package/src/route/auth-options.ts +0 -48
  161. package/src/route/auth.ts +0 -198
  162. package/src/route/client.ts +0 -459
  163. package/src/route/endpoint.ts +0 -28
  164. package/src/route/executor.ts +0 -396
  165. package/src/route/framing.ts +0 -13
  166. package/src/route/overflow-detect.ts +0 -74
  167. package/src/route/protocol.ts +0 -48
  168. package/src/route/transport/http.ts +0 -123
  169. package/src/route/transport/index.ts +0 -21
  170. package/src/schema/errors.ts +0 -225
  171. package/src/schema/events.ts +0 -335
  172. package/src/schema/ids.ts +0 -44
  173. package/src/schema/index.ts +0 -6
  174. package/src/schema/messages.ts +0 -250
  175. package/src/schema/options.ts +0 -231
  176. package/src/tool-runtime.ts +0 -301
  177. package/src/tool.ts +0 -212
package/dist/index.cjs ADDED
@@ -0,0 +1,2956 @@
1
+ 'use strict';
2
+
3
+ var effect$1 = require('effect');
4
+ var buffer = require('buffer');
5
+ var Sse = require('effect/unstable/encoding/Sse');
6
+ var http = require('effect/unstable/http');
7
+
8
+ function _interopNamespace(e) {
9
+ if (e && e.__esModule) return e;
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () { return e[k]; }
18
+ });
19
+ }
20
+ });
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
+ }
25
+
26
+ var Sse__namespace = /*#__PURE__*/_interopNamespace(Sse);
27
+
28
+ var __defProp = Object.defineProperty;
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, { get: all[name], enumerable: true });
32
+ };
33
+ var ProtocolID = effect$1.Schema.String;
34
+ var RouteID = effect$1.Schema.String;
35
+ var ModelID = effect$1.Schema.String.pipe(effect$1.Schema.brand("LLM.ModelID"));
36
+ var ProviderID = effect$1.Schema.String.pipe(effect$1.Schema.brand("LLM.ProviderID"));
37
+ var ResponseID = effect$1.Schema.String;
38
+ var ContentBlockID = effect$1.Schema.String;
39
+ var ToolCallID = effect$1.Schema.String;
40
+ var ReasoningEfforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
41
+ var ReasoningEffort = effect$1.Schema.Literals(ReasoningEfforts);
42
+ var TextVerbosity = effect$1.Schema.Literals(["low", "medium", "high"]);
43
+ var MessageRole = effect$1.Schema.Literals(["user", "assistant", "tool"]);
44
+ var FinishReason = effect$1.Schema.Literals(["stop", "length", "tool-calls", "content-filter", "error", "unknown"]);
45
+ var JsonSchema = effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown);
46
+ var ProviderMetadata = effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown));
47
+ var isRecord = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
48
+ var mergeJsonRecords = (...items) => {
49
+ const defined = items.filter((item) => item !== void 0);
50
+ if (defined.length === 0) return void 0;
51
+ if (defined.length === 1 && Object.values(defined[0]).every((value2) => value2 !== void 0)) return defined[0];
52
+ const result = {};
53
+ for (const item of defined) {
54
+ for (const [key, value2] of Object.entries(item)) {
55
+ if (value2 === void 0) continue;
56
+ result[key] = isRecord(result[key]) && isRecord(value2) ? mergeJsonRecords(result[key], value2) : value2;
57
+ }
58
+ }
59
+ return Object.keys(result).length === 0 ? void 0 : result;
60
+ };
61
+ var mergeStringRecords = (...items) => {
62
+ const defined = items.filter((item) => item !== void 0);
63
+ if (defined.length === 0) return void 0;
64
+ if (defined.length === 1) return defined[0];
65
+ const result = Object.fromEntries(
66
+ defined.flatMap(
67
+ (item) => Object.entries(item).filter((entry) => entry[1] !== void 0)
68
+ )
69
+ );
70
+ return Object.keys(result).length === 0 ? void 0 : result;
71
+ };
72
+ var ProviderOptions = effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown));
73
+ var mergeProviderOptions = (...items) => {
74
+ const result = {};
75
+ for (const item of items) {
76
+ if (!item) continue;
77
+ for (const [provider3, options2] of Object.entries(item)) {
78
+ const merged = mergeJsonRecords(result[provider3], options2);
79
+ if (merged) result[provider3] = merged;
80
+ }
81
+ }
82
+ return Object.keys(result).length === 0 ? void 0 : result;
83
+ };
84
+ exports.HttpOptions = class HttpOptions extends effect$1.Schema.Class("LLM.HttpOptions")({
85
+ body: effect$1.Schema.optional(JsonSchema),
86
+ headers: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
87
+ query: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String))
88
+ }) {
89
+ };
90
+ ((HttpOptions2) => {
91
+ HttpOptions2.make = (input) => input instanceof HttpOptions2 ? input : new HttpOptions2(input);
92
+ })(exports.HttpOptions || (exports.HttpOptions = {}));
93
+ var mergeHttpOptions = (...items) => {
94
+ const body = mergeJsonRecords(...items.map((item) => item?.body));
95
+ const headers2 = mergeStringRecords(...items.map((item) => item?.headers));
96
+ const query = mergeStringRecords(...items.map((item) => item?.query));
97
+ if (!body && !headers2 && !query) return void 0;
98
+ return new exports.HttpOptions({ body, headers: headers2, query });
99
+ };
100
+ exports.GenerationOptions = class GenerationOptions extends effect$1.Schema.Class("LLM.GenerationOptions")({
101
+ maxTokens: effect$1.Schema.optional(effect$1.Schema.Number),
102
+ temperature: effect$1.Schema.optional(effect$1.Schema.Number),
103
+ topP: effect$1.Schema.optional(effect$1.Schema.Number),
104
+ topK: effect$1.Schema.optional(effect$1.Schema.Number),
105
+ frequencyPenalty: effect$1.Schema.optional(effect$1.Schema.Number),
106
+ presencePenalty: effect$1.Schema.optional(effect$1.Schema.Number),
107
+ seed: effect$1.Schema.optional(effect$1.Schema.Number),
108
+ stop: effect$1.Schema.optional(effect$1.Schema.Array(effect$1.Schema.String))
109
+ }) {
110
+ };
111
+ ((GenerationOptions2) => {
112
+ GenerationOptions2.make = (input = {}) => input instanceof GenerationOptions2 ? input : new GenerationOptions2(input);
113
+ })(exports.GenerationOptions || (exports.GenerationOptions = {}));
114
+ var latestGeneration = (items, key) => items.findLast((item) => item?.[key] !== void 0)?.[key];
115
+ var mergeGenerationOptions = (...items) => {
116
+ const result = new exports.GenerationOptions({
117
+ maxTokens: latestGeneration(items, "maxTokens"),
118
+ temperature: latestGeneration(items, "temperature"),
119
+ topP: latestGeneration(items, "topP"),
120
+ topK: latestGeneration(items, "topK"),
121
+ frequencyPenalty: latestGeneration(items, "frequencyPenalty"),
122
+ presencePenalty: latestGeneration(items, "presencePenalty"),
123
+ seed: latestGeneration(items, "seed"),
124
+ stop: latestGeneration(items, "stop")
125
+ });
126
+ return Object.values(result).some((value2) => value2 !== void 0) ? result : void 0;
127
+ };
128
+ exports.ModelLimits = class ModelLimits extends effect$1.Schema.Class("LLM.ModelLimits")({
129
+ context: effect$1.Schema.optional(effect$1.Schema.Number),
130
+ output: effect$1.Schema.optional(effect$1.Schema.Number)
131
+ }) {
132
+ };
133
+ ((ModelLimits2) => {
134
+ ModelLimits2.make = (input) => input instanceof ModelLimits2 ? input : new ModelLimits2(input ?? {});
135
+ })(exports.ModelLimits || (exports.ModelLimits = {}));
136
+ exports.ModelRef = class ModelRef extends effect$1.Schema.Class("LLM.ModelRef")({
137
+ id: ModelID,
138
+ provider: ProviderID,
139
+ route: RouteID,
140
+ baseURL: effect$1.Schema.String,
141
+ /** Provider-specific API key convenience. Provider helpers normalize this into `auth`. */
142
+ apiKey: effect$1.Schema.optional(effect$1.Schema.String),
143
+ /** Optional transport auth policy. Opaque because it may contain functions. */
144
+ auth: effect$1.Schema.optional(effect$1.Schema.Any),
145
+ headers: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
146
+ /**
147
+ * Query params appended to the request URL by `Endpoint.baseURL`. Used for
148
+ * deployment-level URL-scoped settings such as Azure's `api-version` or any
149
+ * provider that requires a per-request key in the URL. Generic concern, so
150
+ * lives as a typed first-class field instead of `native`.
151
+ */
152
+ queryParams: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
153
+ limits: exports.ModelLimits,
154
+ /** Provider-neutral generation defaults. Request-level values override them. */
155
+ generation: effect$1.Schema.optional(exports.GenerationOptions),
156
+ /** Provider-owned typed-at-the-facade options for non-portable knobs. */
157
+ providerOptions: effect$1.Schema.optional(ProviderOptions),
158
+ /** Serializable raw HTTP overlays applied to the final outgoing request. */
159
+ http: effect$1.Schema.optional(exports.HttpOptions),
160
+ /**
161
+ * Provider-specific opaque options. Reach for this only when the value is
162
+ * genuinely provider-private and does not fit a typed axis (e.g. Bedrock's
163
+ * `aws_credentials` / `aws_region` for SigV4). Anything used by more than
164
+ * one route should grow into a typed field instead.
165
+ */
166
+ native: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
167
+ }) {
168
+ };
169
+ ((ModelRef2) => {
170
+ ModelRef2.input = (model7) => ({
171
+ id: model7.id,
172
+ provider: model7.provider,
173
+ route: model7.route,
174
+ baseURL: model7.baseURL,
175
+ apiKey: model7.apiKey,
176
+ auth: model7.auth,
177
+ headers: model7.headers,
178
+ queryParams: model7.queryParams,
179
+ limits: model7.limits,
180
+ generation: model7.generation,
181
+ providerOptions: model7.providerOptions,
182
+ http: model7.http,
183
+ native: model7.native
184
+ });
185
+ ModelRef2.update = (model7, patch) => {
186
+ if (Object.keys(patch).length === 0) return model7;
187
+ return new ModelRef2({
188
+ ...(0, ModelRef2.input)(model7),
189
+ ...patch
190
+ });
191
+ };
192
+ })(exports.ModelRef || (exports.ModelRef = {}));
193
+ var CacheHint = class extends effect$1.Schema.Class("LLM.CacheHint")({
194
+ type: effect$1.Schema.Literals(["ephemeral", "persistent"]),
195
+ ttlSeconds: effect$1.Schema.optional(effect$1.Schema.Number)
196
+ }) {
197
+ };
198
+ var CachePolicyObject = effect$1.Schema.Struct({
199
+ tools: effect$1.Schema.optional(effect$1.Schema.Boolean),
200
+ system: effect$1.Schema.optional(effect$1.Schema.Boolean),
201
+ messages: effect$1.Schema.optional(
202
+ effect$1.Schema.Union([
203
+ effect$1.Schema.Literal("latest-user-message"),
204
+ effect$1.Schema.Literal("latest-assistant"),
205
+ effect$1.Schema.Struct({ tail: effect$1.Schema.Number })
206
+ ])
207
+ ),
208
+ ttlSeconds: effect$1.Schema.optional(effect$1.Schema.Number)
209
+ });
210
+ var CachePolicy = effect$1.Schema.Union([effect$1.Schema.Literal("auto"), effect$1.Schema.Literal("none"), CachePolicyObject]);
211
+ var isRecord2 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
212
+ var systemPartSchema = effect$1.Schema.Struct({
213
+ type: effect$1.Schema.Literal("text"),
214
+ text: effect$1.Schema.String,
215
+ cache: effect$1.Schema.optional(CacheHint),
216
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
217
+ }).annotate({ identifier: "LLM.SystemPart" });
218
+ var makeSystemPart = (text2) => ({ type: "text", text: text2 });
219
+ var SystemPart = Object.assign(systemPartSchema, {
220
+ make: makeSystemPart,
221
+ content: (input) => {
222
+ if (input === void 0) return [];
223
+ return typeof input === "string" ? [makeSystemPart(input)] : Array.isArray(input) ? [...input] : [input];
224
+ }
225
+ });
226
+ var TextPart = effect$1.Schema.Struct({
227
+ type: effect$1.Schema.Literal("text"),
228
+ text: effect$1.Schema.String,
229
+ cache: effect$1.Schema.optional(CacheHint),
230
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
231
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
232
+ }).annotate({ identifier: "LLM.Content.Text" });
233
+ var MediaPart = effect$1.Schema.Struct({
234
+ type: effect$1.Schema.Literal("media"),
235
+ mediaType: effect$1.Schema.String,
236
+ data: effect$1.Schema.Union([effect$1.Schema.String, effect$1.Schema.Uint8Array]),
237
+ filename: effect$1.Schema.optional(effect$1.Schema.String),
238
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
239
+ }).annotate({ identifier: "LLM.Content.Media" });
240
+ var isToolResultValue = (value2) => isRecord2(value2) && (value2.type === "text" || value2.type === "json" || value2.type === "error") && "value" in value2;
241
+ var ToolResultValue = Object.assign(
242
+ effect$1.Schema.Struct({
243
+ type: effect$1.Schema.Literals(["json", "text", "error"]),
244
+ value: effect$1.Schema.Unknown,
245
+ /** Optional structured payload (e.g. tool-interrupt metadata). */
246
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
247
+ }).annotate({ identifier: "LLM.ToolResult" }),
248
+ {
249
+ make: (value2, type = "json", metadata) => {
250
+ if (isToolResultValue(value2)) {
251
+ return metadata ? { ...value2, metadata: { ...value2.metadata ?? {}, ...metadata } } : value2;
252
+ }
253
+ return metadata ? { type, value: value2, metadata } : { type, value: value2 };
254
+ }
255
+ }
256
+ );
257
+ var ToolCallPart = Object.assign(
258
+ effect$1.Schema.Struct({
259
+ type: effect$1.Schema.Literal("tool-call"),
260
+ id: effect$1.Schema.String,
261
+ name: effect$1.Schema.String,
262
+ input: effect$1.Schema.Unknown,
263
+ providerExecuted: effect$1.Schema.optional(effect$1.Schema.Boolean),
264
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
265
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
266
+ }).annotate({ identifier: "LLM.Content.ToolCall" }),
267
+ {
268
+ make: (input) => ({ type: "tool-call", ...input })
269
+ }
270
+ );
271
+ var ToolResultPart = Object.assign(
272
+ effect$1.Schema.Struct({
273
+ type: effect$1.Schema.Literal("tool-result"),
274
+ id: effect$1.Schema.String,
275
+ name: effect$1.Schema.String,
276
+ result: ToolResultValue,
277
+ providerExecuted: effect$1.Schema.optional(effect$1.Schema.Boolean),
278
+ cache: effect$1.Schema.optional(CacheHint),
279
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
280
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
281
+ }).annotate({ identifier: "LLM.Content.ToolResult" }),
282
+ {
283
+ make: (input) => ({
284
+ type: "tool-result",
285
+ id: input.id,
286
+ name: input.name,
287
+ result: ToolResultValue.make(input.result, input.resultType),
288
+ providerExecuted: input.providerExecuted,
289
+ cache: input.cache,
290
+ metadata: input.metadata,
291
+ providerMetadata: input.providerMetadata
292
+ })
293
+ }
294
+ );
295
+ var ReasoningPart = effect$1.Schema.Struct({
296
+ type: effect$1.Schema.Literal("reasoning"),
297
+ text: effect$1.Schema.String,
298
+ encrypted: effect$1.Schema.optional(effect$1.Schema.String),
299
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
300
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
301
+ }).annotate({ identifier: "LLM.Content.Reasoning" });
302
+ var ContentPart = effect$1.Schema.Union([TextPart, MediaPart, ToolCallPart, ToolResultPart, ReasoningPart]).pipe(
303
+ effect$1.Schema.toTaggedUnion("type")
304
+ );
305
+ exports.Message = class Message extends effect$1.Schema.Class("LLM.Message")({
306
+ id: effect$1.Schema.optional(effect$1.Schema.String),
307
+ role: MessageRole,
308
+ content: effect$1.Schema.Array(ContentPart),
309
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
310
+ native: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
311
+ }) {
312
+ };
313
+ ((Message2) => {
314
+ Message2.text = (value2) => ({ type: "text", text: value2 });
315
+ Message2.content = (input) => typeof input === "string" ? [(0, Message2.text)(input)] : Array.isArray(input) ? [...input] : [input];
316
+ Message2.make = (input) => {
317
+ if (input instanceof Message2) return input;
318
+ return new Message2({ ...input, content: (0, Message2.content)(input.content) });
319
+ };
320
+ Message2.user = (content2) => (0, Message2.make)({ role: "user", content: content2 });
321
+ Message2.assistant = (content2) => (0, Message2.make)({ role: "assistant", content: content2 });
322
+ Message2.tool = (result) => (0, Message2.make)({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] });
323
+ })(exports.Message || (exports.Message = {}));
324
+ exports.ToolDefinition = class ToolDefinition extends effect$1.Schema.Class("LLM.ToolDefinition")({
325
+ name: effect$1.Schema.String,
326
+ description: effect$1.Schema.String,
327
+ inputSchema: JsonSchema,
328
+ cache: effect$1.Schema.optional(CacheHint),
329
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
330
+ native: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
331
+ }) {
332
+ };
333
+ ((ToolDefinition2) => {
334
+ ToolDefinition2.make = (input) => input instanceof ToolDefinition2 ? input : new ToolDefinition2(input);
335
+ })(exports.ToolDefinition || (exports.ToolDefinition = {}));
336
+ exports.ToolChoice = class ToolChoice extends effect$1.Schema.Class("LLM.ToolChoice")({
337
+ type: effect$1.Schema.Literals(["auto", "none", "required", "tool"]),
338
+ name: effect$1.Schema.optional(effect$1.Schema.String)
339
+ }) {
340
+ };
341
+ ((ToolChoice2) => {
342
+ const isMode = (value2) => value2 === "auto" || value2 === "none" || value2 === "required";
343
+ ToolChoice2.named = (value2) => new ToolChoice2({ type: "tool", name: value2 });
344
+ ToolChoice2.make = (input) => {
345
+ if (input instanceof ToolChoice2) return input;
346
+ if (input instanceof exports.ToolDefinition) return (0, ToolChoice2.named)(input.name);
347
+ if (typeof input === "string") return isMode(input) ? new ToolChoice2({ type: input }) : (0, ToolChoice2.named)(input);
348
+ return new ToolChoice2(input);
349
+ };
350
+ })(exports.ToolChoice || (exports.ToolChoice = {}));
351
+ var ResponseFormat = effect$1.Schema.Union([
352
+ effect$1.Schema.Struct({ type: effect$1.Schema.Literal("text") }),
353
+ effect$1.Schema.Struct({ type: effect$1.Schema.Literal("json"), schema: JsonSchema }),
354
+ effect$1.Schema.Struct({ type: effect$1.Schema.Literal("tool"), tool: exports.ToolDefinition })
355
+ ]).pipe(effect$1.Schema.toTaggedUnion("type"));
356
+ exports.LLMRequest = class LLMRequest extends effect$1.Schema.Class("LLM.Request")({
357
+ id: effect$1.Schema.optional(effect$1.Schema.String),
358
+ model: exports.ModelRef,
359
+ system: effect$1.Schema.Array(SystemPart),
360
+ messages: effect$1.Schema.Array(exports.Message),
361
+ tools: effect$1.Schema.Array(exports.ToolDefinition),
362
+ toolChoice: effect$1.Schema.optional(exports.ToolChoice),
363
+ generation: effect$1.Schema.optional(exports.GenerationOptions),
364
+ providerOptions: effect$1.Schema.optional(ProviderOptions),
365
+ http: effect$1.Schema.optional(exports.HttpOptions),
366
+ responseFormat: effect$1.Schema.optional(ResponseFormat),
367
+ cache: effect$1.Schema.optional(CachePolicy),
368
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
369
+ }) {
370
+ };
371
+ ((LLMRequest2) => {
372
+ LLMRequest2.input = (request2) => ({
373
+ id: request2.id,
374
+ model: request2.model,
375
+ system: request2.system,
376
+ messages: request2.messages,
377
+ tools: request2.tools,
378
+ toolChoice: request2.toolChoice,
379
+ generation: request2.generation,
380
+ providerOptions: request2.providerOptions,
381
+ http: request2.http,
382
+ responseFormat: request2.responseFormat,
383
+ cache: request2.cache,
384
+ metadata: request2.metadata
385
+ });
386
+ LLMRequest2.update = (request2, patch) => {
387
+ if (Object.keys(patch).length === 0) return request2;
388
+ return new LLMRequest2({
389
+ ...(0, LLMRequest2.input)(request2),
390
+ ...patch,
391
+ model: patch.model ?? request2.model
392
+ });
393
+ };
394
+ })(exports.LLMRequest || (exports.LLMRequest = {}));
395
+ var Usage = class extends effect$1.Schema.Class("LLM.Usage")({
396
+ inputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
397
+ outputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
398
+ nonCachedInputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
399
+ cacheReadInputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
400
+ cacheWriteInputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
401
+ reasoningTokens: effect$1.Schema.optional(effect$1.Schema.Number),
402
+ totalTokens: effect$1.Schema.optional(effect$1.Schema.Number),
403
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
404
+ }) {
405
+ /**
406
+ * Visible output tokens — `outputTokens` minus `reasoningTokens`, clamped
407
+ * to zero. The one place subtraction happens in this contract; the clamp
408
+ * means a provider reporting `reasoningTokens > outputTokens` produces a
409
+ * harmless zero rather than a negative that crashes downstream schemas.
410
+ */
411
+ get visibleOutputTokens() {
412
+ return Math.max(0, (this.outputTokens ?? 0) - (this.reasoningTokens ?? 0));
413
+ }
414
+ };
415
+ var RequestStart = effect$1.Schema.Struct({
416
+ type: effect$1.Schema.tag("request-start"),
417
+ id: ResponseID,
418
+ model: exports.ModelRef
419
+ }).annotate({ identifier: "LLM.Event.RequestStart" });
420
+ var StepStart = effect$1.Schema.Struct({
421
+ type: effect$1.Schema.tag("step-start"),
422
+ index: effect$1.Schema.Number
423
+ }).annotate({ identifier: "LLM.Event.StepStart" });
424
+ var TextStart = effect$1.Schema.Struct({
425
+ type: effect$1.Schema.tag("text-start"),
426
+ id: ContentBlockID,
427
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
428
+ }).annotate({ identifier: "LLM.Event.TextStart" });
429
+ var TextDelta = effect$1.Schema.Struct({
430
+ type: effect$1.Schema.tag("text-delta"),
431
+ id: ContentBlockID,
432
+ text: effect$1.Schema.String
433
+ }).annotate({ identifier: "LLM.Event.TextDelta" });
434
+ var TextEnd = effect$1.Schema.Struct({
435
+ type: effect$1.Schema.tag("text-end"),
436
+ id: ContentBlockID,
437
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
438
+ }).annotate({ identifier: "LLM.Event.TextEnd" });
439
+ var ReasoningStart = effect$1.Schema.Struct({
440
+ type: effect$1.Schema.tag("reasoning-start"),
441
+ id: ContentBlockID,
442
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
443
+ }).annotate({ identifier: "LLM.Event.ReasoningStart" });
444
+ var ReasoningDelta = effect$1.Schema.Struct({
445
+ type: effect$1.Schema.tag("reasoning-delta"),
446
+ id: ContentBlockID,
447
+ text: effect$1.Schema.String
448
+ }).annotate({ identifier: "LLM.Event.ReasoningDelta" });
449
+ var ReasoningEnd = effect$1.Schema.Struct({
450
+ type: effect$1.Schema.tag("reasoning-end"),
451
+ id: ContentBlockID,
452
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
453
+ }).annotate({ identifier: "LLM.Event.ReasoningEnd" });
454
+ var ToolInputStart = effect$1.Schema.Struct({
455
+ type: effect$1.Schema.tag("tool-input-start"),
456
+ id: ToolCallID,
457
+ name: effect$1.Schema.String,
458
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
459
+ }).annotate({ identifier: "LLM.Event.ToolInputStart" });
460
+ var ToolInputDelta = effect$1.Schema.Struct({
461
+ type: effect$1.Schema.tag("tool-input-delta"),
462
+ id: ToolCallID,
463
+ name: effect$1.Schema.String,
464
+ text: effect$1.Schema.String
465
+ }).annotate({ identifier: "LLM.Event.ToolInputDelta" });
466
+ var ToolInputEnd = effect$1.Schema.Struct({
467
+ type: effect$1.Schema.tag("tool-input-end"),
468
+ id: ToolCallID,
469
+ name: effect$1.Schema.String,
470
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
471
+ }).annotate({ identifier: "LLM.Event.ToolInputEnd" });
472
+ var ToolCall = effect$1.Schema.Struct({
473
+ type: effect$1.Schema.tag("tool-call"),
474
+ id: ToolCallID,
475
+ name: effect$1.Schema.String,
476
+ input: effect$1.Schema.Unknown,
477
+ providerExecuted: effect$1.Schema.optional(effect$1.Schema.Boolean),
478
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
479
+ }).annotate({ identifier: "LLM.Event.ToolCall" });
480
+ var ToolResult = effect$1.Schema.Struct({
481
+ type: effect$1.Schema.tag("tool-result"),
482
+ id: ToolCallID,
483
+ name: effect$1.Schema.String,
484
+ result: ToolResultValue,
485
+ providerExecuted: effect$1.Schema.optional(effect$1.Schema.Boolean),
486
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
487
+ }).annotate({ identifier: "LLM.Event.ToolResult" });
488
+ var ToolError = effect$1.Schema.Struct({
489
+ type: effect$1.Schema.tag("tool-error"),
490
+ id: ToolCallID,
491
+ name: effect$1.Schema.String,
492
+ message: effect$1.Schema.String,
493
+ /** Optional structured payload (e.g. tool-interrupt metadata for approval). */
494
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
495
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
496
+ }).annotate({ identifier: "LLM.Event.ToolError" });
497
+ var StepFinish = effect$1.Schema.Struct({
498
+ type: effect$1.Schema.tag("step-finish"),
499
+ index: effect$1.Schema.Number,
500
+ reason: FinishReason,
501
+ usage: effect$1.Schema.optional(Usage),
502
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
503
+ }).annotate({ identifier: "LLM.Event.StepFinish" });
504
+ var RequestFinish = effect$1.Schema.Struct({
505
+ type: effect$1.Schema.tag("request-finish"),
506
+ reason: FinishReason,
507
+ usage: effect$1.Schema.optional(Usage),
508
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
509
+ }).annotate({ identifier: "LLM.Event.RequestFinish" });
510
+ var ProviderErrorEvent = effect$1.Schema.Struct({
511
+ type: effect$1.Schema.tag("provider-error"),
512
+ message: effect$1.Schema.String,
513
+ retryable: effect$1.Schema.optional(effect$1.Schema.Boolean),
514
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
515
+ }).annotate({ identifier: "LLM.Event.ProviderError" });
516
+ var llmEventTagged = effect$1.Schema.Union([
517
+ RequestStart,
518
+ StepStart,
519
+ TextStart,
520
+ TextDelta,
521
+ TextEnd,
522
+ ReasoningStart,
523
+ ReasoningDelta,
524
+ ReasoningEnd,
525
+ ToolInputStart,
526
+ ToolInputDelta,
527
+ ToolInputEnd,
528
+ ToolCall,
529
+ ToolResult,
530
+ ToolError,
531
+ StepFinish,
532
+ RequestFinish,
533
+ ProviderErrorEvent
534
+ ]).pipe(effect$1.Schema.toTaggedUnion("type"));
535
+ var responseID = (value2) => ResponseID.make(value2);
536
+ var contentBlockID = (value2) => ContentBlockID.make(value2);
537
+ var toolCallID = (value2) => ToolCallID.make(value2);
538
+ var LLMEvent = Object.assign(llmEventTagged, {
539
+ requestStart: (input) => RequestStart.make({ ...input, id: responseID(input.id) }),
540
+ stepStart: StepStart.make,
541
+ textStart: (input) => TextStart.make({ ...input, id: contentBlockID(input.id) }),
542
+ textDelta: (input) => TextDelta.make({ ...input, id: contentBlockID(input.id) }),
543
+ textEnd: (input) => TextEnd.make({ ...input, id: contentBlockID(input.id) }),
544
+ reasoningStart: (input) => ReasoningStart.make({ ...input, id: contentBlockID(input.id) }),
545
+ reasoningDelta: (input) => ReasoningDelta.make({ ...input, id: contentBlockID(input.id) }),
546
+ reasoningEnd: (input) => ReasoningEnd.make({ ...input, id: contentBlockID(input.id) }),
547
+ toolInputStart: (input) => ToolInputStart.make({ ...input, id: toolCallID(input.id) }),
548
+ toolInputDelta: (input) => ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
549
+ toolInputEnd: (input) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
550
+ toolCall: (input) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
551
+ toolResult: (input) => ToolResult.make({ ...input, id: toolCallID(input.id) }),
552
+ toolError: (input) => ToolError.make({ ...input, id: toolCallID(input.id) }),
553
+ stepFinish: StepFinish.make,
554
+ requestFinish: RequestFinish.make,
555
+ providerError: ProviderErrorEvent.make,
556
+ is: {
557
+ requestStart: llmEventTagged.guards["request-start"],
558
+ stepStart: llmEventTagged.guards["step-start"],
559
+ textStart: llmEventTagged.guards["text-start"],
560
+ textDelta: llmEventTagged.guards["text-delta"],
561
+ textEnd: llmEventTagged.guards["text-end"],
562
+ reasoningStart: llmEventTagged.guards["reasoning-start"],
563
+ reasoningDelta: llmEventTagged.guards["reasoning-delta"],
564
+ reasoningEnd: llmEventTagged.guards["reasoning-end"],
565
+ toolInputStart: llmEventTagged.guards["tool-input-start"],
566
+ toolInputDelta: llmEventTagged.guards["tool-input-delta"],
567
+ toolInputEnd: llmEventTagged.guards["tool-input-end"],
568
+ toolCall: llmEventTagged.guards["tool-call"],
569
+ toolResult: llmEventTagged.guards["tool-result"],
570
+ toolError: llmEventTagged.guards["tool-error"],
571
+ stepFinish: llmEventTagged.guards["step-finish"],
572
+ requestFinish: llmEventTagged.guards["request-finish"],
573
+ providerError: llmEventTagged.guards["provider-error"]
574
+ }
575
+ });
576
+ var PreparedRequest = class extends effect$1.Schema.Class("LLM.PreparedRequest")({
577
+ id: effect$1.Schema.String,
578
+ route: RouteID,
579
+ protocol: ProtocolID,
580
+ model: exports.ModelRef,
581
+ body: effect$1.Schema.Unknown,
582
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
583
+ }) {
584
+ };
585
+ var responseText = (events) => events.filter(LLMEvent.is.textDelta).map((event) => event.text).join("");
586
+ var responseReasoning = (events) => events.filter(LLMEvent.is.reasoningDelta).map((event) => event.text).join("");
587
+ var responseUsage = (events) => events.reduce(
588
+ (usage, event) => "usage" in event && event.usage !== void 0 ? event.usage : usage,
589
+ void 0
590
+ );
591
+ exports.LLMResponse = class LLMResponse extends effect$1.Schema.Class("LLM.Response")({
592
+ events: effect$1.Schema.Array(LLMEvent),
593
+ usage: effect$1.Schema.optional(Usage)
594
+ }) {
595
+ /** Concatenated assistant text assembled from streamed `text-delta` events. */
596
+ get text() {
597
+ return responseText(this.events);
598
+ }
599
+ /** Concatenated reasoning text assembled from streamed `reasoning-delta` events. */
600
+ get reasoning() {
601
+ return responseReasoning(this.events);
602
+ }
603
+ /** Completed tool calls emitted by the provider. */
604
+ get toolCalls() {
605
+ return this.events.filter(LLMEvent.is.toolCall);
606
+ }
607
+ };
608
+ ((LLMResponse3) => {
609
+ LLMResponse3.text = (response) => responseText(response.events);
610
+ LLMResponse3.usage = (response) => response.usage ?? responseUsage(response.events);
611
+ LLMResponse3.toolCalls = (response) => response.events.filter(LLMEvent.is.toolCall);
612
+ LLMResponse3.reasoning = (response) => responseReasoning(response.events);
613
+ })(exports.LLMResponse || (exports.LLMResponse = {}));
614
+ var HttpRequestDetails = class extends effect$1.Schema.Class("LLM.HttpRequestDetails")({
615
+ method: effect$1.Schema.String,
616
+ url: effect$1.Schema.String,
617
+ headers: effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)
618
+ }) {
619
+ };
620
+ var HttpResponseDetails = class extends effect$1.Schema.Class("LLM.HttpResponseDetails")({
621
+ status: effect$1.Schema.Number,
622
+ headers: effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)
623
+ }) {
624
+ };
625
+ var HttpRateLimitDetails = class extends effect$1.Schema.Class("LLM.HttpRateLimitDetails")({
626
+ retryAfterMs: effect$1.Schema.optional(effect$1.Schema.Number),
627
+ limit: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
628
+ remaining: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
629
+ reset: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String))
630
+ }) {
631
+ };
632
+ var HttpContext = class extends effect$1.Schema.Class("LLM.HttpContext")({
633
+ request: HttpRequestDetails,
634
+ response: effect$1.Schema.optional(HttpResponseDetails),
635
+ body: effect$1.Schema.optional(effect$1.Schema.String),
636
+ bodyTruncated: effect$1.Schema.optional(effect$1.Schema.Boolean),
637
+ requestId: effect$1.Schema.optional(effect$1.Schema.String),
638
+ rateLimit: effect$1.Schema.optional(HttpRateLimitDetails)
639
+ }) {
640
+ };
641
+ var InvalidRequestReason = class extends effect$1.Schema.Class("LLM.Error.InvalidRequest")({
642
+ _tag: effect$1.Schema.tag("InvalidRequest"),
643
+ message: effect$1.Schema.String,
644
+ parameter: effect$1.Schema.optional(effect$1.Schema.String),
645
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
646
+ http: effect$1.Schema.optional(HttpContext)
647
+ }) {
648
+ get retryable() {
649
+ return false;
650
+ }
651
+ };
652
+ var ContextOverflowReason = class extends effect$1.Schema.Class("LLM.Error.ContextOverflow")({
653
+ _tag: effect$1.Schema.tag("ContextOverflow"),
654
+ message: effect$1.Schema.String,
655
+ /** Provider-reported prompt token count when present in the error body. */
656
+ promptTokens: effect$1.Schema.optional(effect$1.Schema.Number),
657
+ /** Provider-reported context window size when present in the error body. */
658
+ contextWindow: effect$1.Schema.optional(effect$1.Schema.Number),
659
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
660
+ http: effect$1.Schema.optional(HttpContext)
661
+ }) {
662
+ get retryable() {
663
+ return false;
664
+ }
665
+ };
666
+ var NoRouteReason = class extends effect$1.Schema.Class("LLM.Error.NoRoute")({
667
+ _tag: effect$1.Schema.tag("NoRoute"),
668
+ route: RouteID,
669
+ provider: ProviderID,
670
+ model: ModelID
671
+ }) {
672
+ get retryable() {
673
+ return false;
674
+ }
675
+ get message() {
676
+ return `No LLM route for ${this.provider}/${this.model} using ${this.route}`;
677
+ }
678
+ };
679
+ var AuthenticationReason = class extends effect$1.Schema.Class("LLM.Error.Authentication")({
680
+ _tag: effect$1.Schema.tag("Authentication"),
681
+ message: effect$1.Schema.String,
682
+ kind: effect$1.Schema.Literals(["missing", "invalid", "expired", "insufficient-permissions", "unknown"]),
683
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
684
+ http: effect$1.Schema.optional(HttpContext)
685
+ }) {
686
+ get retryable() {
687
+ return false;
688
+ }
689
+ };
690
+ var RateLimitReason = class extends effect$1.Schema.Class("LLM.Error.RateLimit")({
691
+ _tag: effect$1.Schema.tag("RateLimit"),
692
+ message: effect$1.Schema.String,
693
+ retryAfterMs: effect$1.Schema.optional(effect$1.Schema.Number),
694
+ rateLimit: effect$1.Schema.optional(HttpRateLimitDetails),
695
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
696
+ http: effect$1.Schema.optional(HttpContext)
697
+ }) {
698
+ get retryable() {
699
+ return true;
700
+ }
701
+ };
702
+ var QuotaExceededReason = class extends effect$1.Schema.Class("LLM.Error.QuotaExceeded")({
703
+ _tag: effect$1.Schema.tag("QuotaExceeded"),
704
+ message: effect$1.Schema.String,
705
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
706
+ http: effect$1.Schema.optional(HttpContext)
707
+ }) {
708
+ get retryable() {
709
+ return false;
710
+ }
711
+ };
712
+ var ContentPolicyReason = class extends effect$1.Schema.Class("LLM.Error.ContentPolicy")({
713
+ _tag: effect$1.Schema.tag("ContentPolicy"),
714
+ message: effect$1.Schema.String,
715
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
716
+ http: effect$1.Schema.optional(HttpContext)
717
+ }) {
718
+ get retryable() {
719
+ return false;
720
+ }
721
+ };
722
+ var ProviderInternalReason = class extends effect$1.Schema.Class("LLM.Error.ProviderInternal")({
723
+ _tag: effect$1.Schema.tag("ProviderInternal"),
724
+ message: effect$1.Schema.String,
725
+ status: effect$1.Schema.Number,
726
+ retryAfterMs: effect$1.Schema.optional(effect$1.Schema.Number),
727
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
728
+ http: effect$1.Schema.optional(HttpContext)
729
+ }) {
730
+ get retryable() {
731
+ return true;
732
+ }
733
+ };
734
+ var TransportReason = class extends effect$1.Schema.Class("LLM.Error.Transport")({
735
+ _tag: effect$1.Schema.tag("Transport"),
736
+ message: effect$1.Schema.String,
737
+ kind: effect$1.Schema.optional(effect$1.Schema.String),
738
+ url: effect$1.Schema.optional(effect$1.Schema.String),
739
+ http: effect$1.Schema.optional(HttpContext)
740
+ }) {
741
+ get retryable() {
742
+ return false;
743
+ }
744
+ };
745
+ var InvalidProviderOutputReason = class extends effect$1.Schema.Class(
746
+ "LLM.Error.InvalidProviderOutput"
747
+ )({
748
+ _tag: effect$1.Schema.tag("InvalidProviderOutput"),
749
+ message: effect$1.Schema.String,
750
+ route: effect$1.Schema.optional(effect$1.Schema.String),
751
+ raw: effect$1.Schema.optional(effect$1.Schema.String),
752
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
753
+ }) {
754
+ get retryable() {
755
+ return false;
756
+ }
757
+ };
758
+ var UnknownProviderReason = class extends effect$1.Schema.Class("LLM.Error.UnknownProvider")({
759
+ _tag: effect$1.Schema.tag("UnknownProvider"),
760
+ message: effect$1.Schema.String,
761
+ status: effect$1.Schema.optional(effect$1.Schema.Number),
762
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
763
+ http: effect$1.Schema.optional(HttpContext)
764
+ }) {
765
+ get retryable() {
766
+ return false;
767
+ }
768
+ };
769
+ var LLMErrorReason = effect$1.Schema.Union([
770
+ InvalidRequestReason,
771
+ ContextOverflowReason,
772
+ NoRouteReason,
773
+ AuthenticationReason,
774
+ RateLimitReason,
775
+ QuotaExceededReason,
776
+ ContentPolicyReason,
777
+ ProviderInternalReason,
778
+ TransportReason,
779
+ InvalidProviderOutputReason,
780
+ UnknownProviderReason
781
+ ]).pipe(effect$1.Schema.toTaggedUnion("_tag"));
782
+ var LLMError = class extends effect$1.Schema.TaggedErrorClass()("LLM.Error", {
783
+ module: effect$1.Schema.String,
784
+ method: effect$1.Schema.String,
785
+ reason: LLMErrorReason
786
+ }) {
787
+ cause = this.reason;
788
+ get retryable() {
789
+ return this.reason.retryable;
790
+ }
791
+ get retryAfterMs() {
792
+ return "retryAfterMs" in this.reason ? this.reason.retryAfterMs : void 0;
793
+ }
794
+ get message() {
795
+ return `${this.module}.${this.method}: ${this.reason.message}`;
796
+ }
797
+ };
798
+ var ToolFailure = class extends effect$1.Schema.TaggedErrorClass()("LLM.ToolFailure", {
799
+ message: effect$1.Schema.String,
800
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
801
+ }) {
802
+ };
803
+
804
+ // src/tool.ts
805
+ var tool_exports = {};
806
+ __export(tool_exports, {
807
+ Tool: () => tool_exports,
808
+ ToolFailure: () => ToolFailure,
809
+ make: () => make,
810
+ toDefinitions: () => toDefinitions,
811
+ tool: () => tool
812
+ });
813
+ function make(config2) {
814
+ if ("jsonSchema" in config2) {
815
+ return {
816
+ description: config2.description,
817
+ parameters: effect$1.Schema.Unknown,
818
+ success: effect$1.Schema.Unknown,
819
+ execute: config2.execute,
820
+ _decode: effect$1.Effect.succeed,
821
+ _encode: effect$1.Effect.succeed,
822
+ _definition: new exports.ToolDefinition({
823
+ name: "",
824
+ description: config2.description,
825
+ inputSchema: config2.jsonSchema
826
+ })
827
+ };
828
+ }
829
+ return {
830
+ description: config2.description,
831
+ parameters: config2.parameters,
832
+ success: config2.success,
833
+ execute: config2.execute,
834
+ _decode: effect$1.Schema.decodeUnknownEffect(config2.parameters),
835
+ _encode: effect$1.Schema.encodeEffect(config2.success),
836
+ _definition: new exports.ToolDefinition({
837
+ name: "",
838
+ description: config2.description,
839
+ inputSchema: toJsonSchema(config2.parameters)
840
+ })
841
+ };
842
+ }
843
+ var tool = make;
844
+ var toDefinitions = (tools) => Object.entries(tools).map(
845
+ ([name, item]) => new exports.ToolDefinition({
846
+ name,
847
+ description: item._definition.description,
848
+ inputSchema: item._definition.inputSchema
849
+ })
850
+ );
851
+ var toJsonSchema = (schema) => {
852
+ const document = effect$1.Schema.toJsonSchemaDocument(schema);
853
+ const base = Object.keys(document.definitions).length === 0 ? document.schema : { ...document.schema, $defs: document.definitions };
854
+ return normalizeTopLevel(base);
855
+ };
856
+ var normalizeTopLevel = (s) => {
857
+ if (!s || typeof s !== "object") {
858
+ return { type: "object", properties: {}, additionalProperties: false };
859
+ }
860
+ const obj = s;
861
+ if (obj.type === "object") return s;
862
+ if (Array.isArray(obj.anyOf)) {
863
+ const objectVariant = obj.anyOf.find(
864
+ (v) => v != null && typeof v === "object" && v.type === "object"
865
+ );
866
+ if (objectVariant) {
867
+ const { anyOf: _omit, ...rest } = obj;
868
+ return { ...rest, ...objectVariant };
869
+ }
870
+ }
871
+ return { type: "object", properties: {}, additionalProperties: false };
872
+ };
873
+ var hasToolCall = (name) => (state) => state.toolCalls.some((call) => call.name === name);
874
+ var stopWhenAny = (...conditions) => (state) => conditions.some((condition) => condition(state));
875
+ var stepCountIs = (count) => (state) => state.step + 1 >= count;
876
+ var stream = (options2) => {
877
+ const concurrency = options2.concurrency ?? 10;
878
+ const tools = options2.tools;
879
+ const runtimeTools = toDefinitions(tools);
880
+ const runtimeToolNames = new Set(runtimeTools.map((tool2) => tool2.name));
881
+ const initialRequest = runtimeTools.length === 0 ? options2.request : exports.LLMRequest.update(options2.request, {
882
+ tools: [...options2.request.tools.filter((tool2) => !runtimeToolNames.has(tool2.name)), ...runtimeTools]
883
+ });
884
+ const loop = (request2, step2) => effect$1.Stream.unwrap(
885
+ effect$1.Effect.gen(function* () {
886
+ const state = { assistantContent: [], toolCalls: [], finishReason: void 0 };
887
+ const modelStream = options2.stream(request2).pipe(effect$1.Stream.tap((event) => effect$1.Effect.sync(() => accumulate(state, event))));
888
+ const continuation = effect$1.Stream.unwrap(
889
+ effect$1.Effect.gen(function* () {
890
+ if (state.finishReason !== "tool-calls" || state.toolCalls.length === 0) return effect$1.Stream.empty;
891
+ if (options2.toolExecution === "none") return effect$1.Stream.empty;
892
+ const dispatched = yield* effect$1.Effect.forEach(
893
+ state.toolCalls,
894
+ (call) => dispatch(tools, call).pipe(effect$1.Effect.map((result) => [call, result])),
895
+ { concurrency }
896
+ );
897
+ const resultStream = effect$1.Stream.fromIterable(dispatched.flatMap(([call, result]) => emitEvents(call, result)));
898
+ if (dispatched.some(([, result]) => isInterruptResult(result))) return resultStream;
899
+ if (!options2.stopWhen) return resultStream;
900
+ if (options2.stopWhen({ step: step2, request: request2, toolCalls: state.toolCalls })) return resultStream;
901
+ const followUp = dispatched.filter(([, result]) => !isInterruptResult(result));
902
+ if (followUp.length === 0) return resultStream;
903
+ return resultStream.pipe(effect$1.Stream.concat(loop(followUpRequest(request2, state, followUp), step2 + 1)));
904
+ })
905
+ );
906
+ return modelStream.pipe(effect$1.Stream.concat(continuation));
907
+ })
908
+ );
909
+ return loop(initialRequest, 0);
910
+ };
911
+ var accumulate = (state, event) => {
912
+ if (event.type === "text-delta") {
913
+ appendStreamingText(state, "text", event.text, void 0);
914
+ return;
915
+ }
916
+ if (event.type === "reasoning-delta") {
917
+ appendStreamingText(state, "reasoning", event.text, void 0);
918
+ return;
919
+ }
920
+ if (event.type === "reasoning-end") {
921
+ appendStreamingText(state, "reasoning", "", event.providerMetadata);
922
+ return;
923
+ }
924
+ if (event.type === "text-end") {
925
+ appendStreamingText(state, "text", "", event.providerMetadata);
926
+ return;
927
+ }
928
+ if (event.type === "tool-call") {
929
+ const part = ToolCallPart.make({
930
+ id: event.id,
931
+ name: event.name,
932
+ input: event.input,
933
+ providerExecuted: event.providerExecuted,
934
+ providerMetadata: event.providerMetadata
935
+ });
936
+ state.assistantContent.push(part);
937
+ if (!event.providerExecuted) state.toolCalls.push(part);
938
+ return;
939
+ }
940
+ if (event.type === "tool-result" && event.providerExecuted) {
941
+ state.assistantContent.push(
942
+ ToolResultPart.make({
943
+ id: event.id,
944
+ name: event.name,
945
+ result: event.result,
946
+ providerExecuted: true,
947
+ providerMetadata: event.providerMetadata
948
+ })
949
+ );
950
+ return;
951
+ }
952
+ if (event.type === "request-finish") {
953
+ state.finishReason = event.reason;
954
+ }
955
+ };
956
+ var sameProviderMetadata = (left, right) => left === right || JSON.stringify(left) === JSON.stringify(right);
957
+ var mergeProviderMetadata = (left, right) => {
958
+ if (!left) return right;
959
+ if (!right) return left;
960
+ return Object.fromEntries(
961
+ Array.from(/* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])).map((provider3) => [
962
+ provider3,
963
+ { ...left[provider3], ...right[provider3] }
964
+ ])
965
+ );
966
+ };
967
+ var appendStreamingText = (state, type, text2, providerMetadata) => {
968
+ const last = state.assistantContent.at(-1);
969
+ if (last?.type === type && text2.length === 0) {
970
+ state.assistantContent[state.assistantContent.length - 1] = {
971
+ ...last,
972
+ providerMetadata: mergeProviderMetadata(last.providerMetadata, providerMetadata)
973
+ };
974
+ return;
975
+ }
976
+ if (last?.type === type && sameProviderMetadata(last.providerMetadata, providerMetadata)) {
977
+ state.assistantContent[state.assistantContent.length - 1] = { ...last, text: `${last.text}${text2}` };
978
+ return;
979
+ }
980
+ state.assistantContent.push({ type, text: text2, providerMetadata });
981
+ };
982
+ var isInterruptResult = (result) => result.type === "error" && typeof result.metadata === "object" && result.metadata !== null && result.metadata.kind === "tool-interrupt";
983
+ var dispatch = (tools, call) => {
984
+ const tool2 = tools[call.name];
985
+ if (!tool2) return effect$1.Effect.succeed({ type: "error", value: `Unknown tool: ${call.name}` });
986
+ if (!tool2.execute)
987
+ return effect$1.Effect.succeed({ type: "error", value: `Tool has no execute handler: ${call.name}` });
988
+ return decodeAndExecute(tool2, call.input).pipe(
989
+ effect$1.Effect.catchTag(
990
+ "LLM.ToolFailure",
991
+ (failure) => effect$1.Effect.succeed({
992
+ type: "error",
993
+ value: failure.message,
994
+ ...failure.metadata ? { metadata: failure.metadata } : {}
995
+ })
996
+ )
997
+ );
998
+ };
999
+ var decodeAndExecute = (tool2, input) => tool2._decode(input).pipe(
1000
+ effect$1.Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
1001
+ effect$1.Effect.flatMap((decoded) => tool2.execute(decoded)),
1002
+ effect$1.Effect.flatMap(
1003
+ (value2) => tool2._encode(value2).pipe(
1004
+ effect$1.Effect.mapError(
1005
+ (error) => new ToolFailure({
1006
+ message: `Tool returned an invalid value for its success schema: ${error.message}`
1007
+ })
1008
+ )
1009
+ )
1010
+ ),
1011
+ effect$1.Effect.map((encoded) => ({ type: "json", value: encoded }))
1012
+ );
1013
+ var emitEvents = (call, result) => {
1014
+ if (result.type === "error") {
1015
+ if (isInterruptResult(result)) {
1016
+ return [
1017
+ LLMEvent.toolError({
1018
+ id: call.id,
1019
+ name: call.name,
1020
+ message: String(result.value),
1021
+ metadata: result.metadata
1022
+ })
1023
+ ];
1024
+ }
1025
+ return [
1026
+ LLMEvent.toolError({
1027
+ id: call.id,
1028
+ name: call.name,
1029
+ message: String(result.value),
1030
+ metadata: result.metadata
1031
+ }),
1032
+ LLMEvent.toolResult({ id: call.id, name: call.name, result })
1033
+ ];
1034
+ }
1035
+ return [LLMEvent.toolResult({ id: call.id, name: call.name, result })];
1036
+ };
1037
+ var followUpRequest = (request2, state, dispatched) => exports.LLMRequest.update(request2, {
1038
+ messages: [
1039
+ ...request2.messages,
1040
+ exports.Message.assistant(state.assistantContent),
1041
+ ...dispatched.map(([call, result]) => exports.Message.tool({ id: call.id, name: call.name, result }))
1042
+ ]
1043
+ });
1044
+ var ToolRuntime = { stream, stepCountIs };
1045
+
1046
+ // src/route/protocol.ts
1047
+ var protocol_exports = {};
1048
+ __export(protocol_exports, {
1049
+ Protocol: () => protocol_exports,
1050
+ jsonEvent: () => jsonEvent,
1051
+ make: () => make2
1052
+ });
1053
+ var make2 = (input) => input;
1054
+ var jsonEvent = (schema) => effect$1.Schema.fromJsonString(schema);
1055
+
1056
+ // src/route/endpoint.ts
1057
+ var endpoint_exports = {};
1058
+ __export(endpoint_exports, {
1059
+ Endpoint: () => endpoint_exports,
1060
+ path: () => path,
1061
+ render: () => render
1062
+ });
1063
+
1064
+ // src/protocols/shared.ts
1065
+ var shared_exports = {};
1066
+ __export(shared_exports, {
1067
+ Json: () => Json,
1068
+ JsonObject: () => JsonObject,
1069
+ ProviderShared: () => shared_exports,
1070
+ decodeJson: () => decodeJson,
1071
+ encodeJson: () => encodeJson,
1072
+ errorText: () => errorText,
1073
+ eventError: () => eventError,
1074
+ invalidRequest: () => invalidRequest,
1075
+ isRecord: () => isRecord3,
1076
+ joinText: () => joinText,
1077
+ jsonPost: () => jsonPost,
1078
+ matchToolChoice: () => matchToolChoice,
1079
+ mediaBytes: () => mediaBytes,
1080
+ optionalArray: () => optionalArray,
1081
+ optionalNull: () => optionalNull,
1082
+ parseJson: () => parseJson,
1083
+ parseToolInput: () => parseToolInput,
1084
+ sseFraming: () => sseFraming,
1085
+ subtractTokens: () => subtractTokens,
1086
+ sumTokens: () => sumTokens,
1087
+ supportsContent: () => supportsContent,
1088
+ toolResultText: () => toolResultText,
1089
+ totalTokens: () => totalTokens,
1090
+ trimBaseUrl: () => trimBaseUrl,
1091
+ unsupportedContent: () => unsupportedContent,
1092
+ validateWith: () => validateWith
1093
+ });
1094
+ var Json = effect$1.Schema.fromJsonString(effect$1.Schema.Unknown);
1095
+ var decodeJson = effect$1.Schema.decodeUnknownSync(Json);
1096
+ var encodeJson = effect$1.Schema.encodeSync(Json);
1097
+ var JsonObject = effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown);
1098
+ var optionalArray = (schema) => effect$1.Schema.optional(effect$1.Schema.Array(schema));
1099
+ var optionalNull = (schema) => effect$1.Schema.optional(effect$1.Schema.NullOr(schema));
1100
+ var isRecord3 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
1101
+ var totalTokens = (inputTokens, outputTokens, total) => {
1102
+ if (total !== void 0) return total;
1103
+ if (inputTokens === void 0 && outputTokens === void 0) return void 0;
1104
+ return (inputTokens ?? 0) + (outputTokens ?? 0);
1105
+ };
1106
+ var subtractTokens = (total, subtrahend) => {
1107
+ if (total === void 0) return void 0;
1108
+ if (subtrahend === void 0) return total;
1109
+ return Math.max(0, total - subtrahend);
1110
+ };
1111
+ var sumTokens = (...values) => {
1112
+ if (values.every((value2) => value2 === void 0)) return void 0;
1113
+ return values.reduce((acc, value2) => acc + (value2 ?? 0), 0);
1114
+ };
1115
+ var eventError = (route3, message2, raw) => new LLMError({
1116
+ module: "ProviderShared",
1117
+ method: "stream",
1118
+ reason: new InvalidProviderOutputReason({ route: route3, message: message2, raw })
1119
+ });
1120
+ var parseJson = (route3, input, message2) => effect$1.Effect.try({
1121
+ try: () => decodeJson(input),
1122
+ catch: () => eventError(route3, message2, input)
1123
+ });
1124
+ var joinText = (parts) => parts.map((part) => part.text).join("\n");
1125
+ var parseToolInput = (route3, name, raw) => parseJson(route3, raw || "{}", `Invalid JSON input for ${route3} tool call ${name}`);
1126
+ var mediaBytes = (part) => typeof part.data === "string" ? part.data : buffer.Buffer.from(part.data).toString("base64");
1127
+ var trimBaseUrl = (value2) => value2.replace(/\/+$/, "");
1128
+ var IMAGE_BASE64_FIELDS = /* @__PURE__ */ new Set(["imageBase64", "base64", "data"]);
1129
+ var isImageResult = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2) && typeof value2.mimeType === "string" && value2.mimeType.startsWith("image/");
1130
+ var redactImagePayload = (value2) => {
1131
+ if (Array.isArray(value2)) return value2.map(redactImagePayload);
1132
+ if (!value2 || typeof value2 !== "object") return value2;
1133
+ if (isImageResult(value2)) {
1134
+ const out2 = {};
1135
+ for (const [k, v] of Object.entries(value2)) {
1136
+ if (IMAGE_BASE64_FIELDS.has(k) && typeof v === "string") {
1137
+ out2[k] = `<image elided; ${v.length} chars base64 already shown to user>`;
1138
+ continue;
1139
+ }
1140
+ out2[k] = v;
1141
+ }
1142
+ return out2;
1143
+ }
1144
+ const out = {};
1145
+ for (const [k, v] of Object.entries(value2)) out[k] = redactImagePayload(v);
1146
+ return out;
1147
+ };
1148
+ var toolResultText = (part) => {
1149
+ if (part.result.type === "text" || part.result.type === "error") return String(part.result.value);
1150
+ return encodeJson(redactImagePayload(part.result.value));
1151
+ };
1152
+ var errorText = (error) => {
1153
+ if (error instanceof Error) return error.message;
1154
+ if (typeof error === "string") return error;
1155
+ if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") return String(error);
1156
+ if (error === null) return "null";
1157
+ if (error === void 0) return "undefined";
1158
+ return "Unknown stream error";
1159
+ };
1160
+ var sseFraming = (bytes) => bytes.pipe(
1161
+ effect$1.Stream.decodeText(),
1162
+ effect$1.Stream.pipeThroughChannel(Sse__namespace.decode()),
1163
+ effect$1.Stream.catchTag("Retry", () => effect$1.Stream.empty),
1164
+ effect$1.Stream.filter((event) => event.data.length > 0 && event.data !== "[DONE]"),
1165
+ effect$1.Stream.map((event) => event.data)
1166
+ );
1167
+ var invalidRequest = (message2) => new LLMError({
1168
+ module: "ProviderShared",
1169
+ method: "request",
1170
+ reason: new InvalidRequestReason({ message: message2 })
1171
+ });
1172
+ var matchToolChoice = (route3, toolChoice2, cases) => effect$1.Effect.gen(function* () {
1173
+ if (toolChoice2.type === "auto") return cases.auto();
1174
+ if (toolChoice2.type === "none") return cases.none();
1175
+ if (toolChoice2.type === "required") return cases.required();
1176
+ if (!toolChoice2.name) return yield* invalidRequest(`${route3} tool choice requires a tool name`);
1177
+ return cases.tool(toolChoice2.name);
1178
+ });
1179
+ var formatContentTypes = (types) => {
1180
+ if (types.length <= 1) return types[0] ?? "";
1181
+ if (types.length === 2) return `${types[0]} and ${types[1]}`;
1182
+ return `${types.slice(0, -1).join(", ")}, and ${types.at(-1)}`;
1183
+ };
1184
+ var supportsContent = (part, types) => types.includes(part.type);
1185
+ var unsupportedContent = (route3, role, types) => invalidRequest(`${route3} ${role} messages only support ${formatContentTypes(types)} content for now`);
1186
+ var validateWith = (decode2) => (payload) => decode2(payload).pipe(effect$1.Effect.mapError((error) => invalidRequest(error.message)));
1187
+ var jsonPost = (input) => http.HttpClientRequest.post(input.url).pipe(
1188
+ http.HttpClientRequest.setHeaders(http.Headers.set(http.Headers.fromInput(input.headers), "content-type", "application/json")),
1189
+ http.HttpClientRequest.bodyText(input.body, "application/json")
1190
+ );
1191
+
1192
+ // src/route/endpoint.ts
1193
+ var path = (value2) => ({ path: value2 });
1194
+ var renderPart = (part, input) => typeof part === "function" ? part(input) : part;
1195
+ var render = (endpoint, input) => {
1196
+ const url = new URL(`${trimBaseUrl(input.request.model.baseURL)}${renderPart(endpoint.path, input)}`);
1197
+ const params = input.request.model.queryParams;
1198
+ if (params) for (const [key, value2] of Object.entries(params)) url.searchParams.set(key, value2);
1199
+ return url;
1200
+ };
1201
+
1202
+ // src/route/framing.ts
1203
+ var framing_exports = {};
1204
+ __export(framing_exports, {
1205
+ Framing: () => framing_exports,
1206
+ sse: () => sse
1207
+ });
1208
+ var sse = { id: "sse", frame: sseFraming };
1209
+
1210
+ // src/route/auth.ts
1211
+ var auth_exports = {};
1212
+ __export(auth_exports, {
1213
+ Auth: () => auth_exports,
1214
+ MissingCredentialError: () => MissingCredentialError,
1215
+ apiKey: () => apiKey,
1216
+ apiKeyHeader: () => apiKeyHeader,
1217
+ bearer: () => bearer,
1218
+ bearerHeader: () => bearerHeader,
1219
+ config: () => config,
1220
+ custom: () => custom,
1221
+ effect: () => effect,
1222
+ header: () => header,
1223
+ headers: () => headers,
1224
+ isAuth: () => isAuth,
1225
+ none: () => none,
1226
+ optional: () => optional,
1227
+ passthrough: () => passthrough,
1228
+ remove: () => remove,
1229
+ toEffect: () => toEffect,
1230
+ value: () => value
1231
+ });
1232
+ var MissingCredentialError = class extends Error {
1233
+ constructor(source) {
1234
+ super(`Missing auth credential: ${source}`);
1235
+ this.source = source;
1236
+ }
1237
+ _tag = "MissingCredentialError";
1238
+ };
1239
+ var isAuth = (input) => typeof input === "object" && input !== null && "apply" in input && typeof input.apply === "function";
1240
+ var credential = (load) => {
1241
+ const self = {
1242
+ load,
1243
+ orElse: (that) => credential(load.pipe(effect$1.Effect.catch(() => that.load))),
1244
+ bearer: () => fromCredential(self, (secret) => ({ authorization: `Bearer ${secret}` })),
1245
+ header: (name) => fromCredential(self, (secret) => ({ [name]: secret })),
1246
+ pipe: (f) => f(self)
1247
+ };
1248
+ return self;
1249
+ };
1250
+ var auth = (apply) => {
1251
+ const self = {
1252
+ apply,
1253
+ andThen: (that) => auth((input) => apply(input).pipe(effect$1.Effect.flatMap((headers2) => that.apply({ ...input, headers: headers2 })))),
1254
+ orElse: (that) => auth((input) => apply(input).pipe(effect$1.Effect.catch(() => that.apply(input)))),
1255
+ pipe: (f) => f(self)
1256
+ };
1257
+ return self;
1258
+ };
1259
+ var fromCredential = (source, render2) => auth(
1260
+ (input) => source.load.pipe(effect$1.Effect.map((secret) => http.Headers.setAll(input.headers, render2(effect$1.Redacted.value(secret)))))
1261
+ );
1262
+ var secretEffect = (secret, source) => {
1263
+ const redacted = typeof secret === "string" ? effect$1.Redacted.make(secret) : secret;
1264
+ if (effect$1.Redacted.value(redacted) === "") return effect$1.Effect.fail(new MissingCredentialError(source));
1265
+ return effect$1.Effect.succeed(redacted);
1266
+ };
1267
+ var credentialFromSecret = (secret, source) => {
1268
+ if (typeof secret === "string" || effect$1.Redacted.isRedacted(secret)) return credential(secretEffect(secret, source));
1269
+ return credential(
1270
+ effect$1.Effect.gen(function* () {
1271
+ return yield* secretEffect(yield* secret, source);
1272
+ })
1273
+ );
1274
+ };
1275
+ var value = (secret, source = "value") => credentialFromSecret(secret, source);
1276
+ var optional = (secret, source = "optional value") => secret === void 0 ? credential(effect$1.Effect.fail(new MissingCredentialError(source))) : credentialFromSecret(secret, source);
1277
+ var config = (name) => credentialFromSecret(effect$1.Config.redacted(name), name);
1278
+ var effect = (load) => credential(load);
1279
+ var none = auth((input) => effect$1.Effect.succeed(input.headers));
1280
+ var headers = (input) => auth((inputAuth) => effect$1.Effect.succeed(http.Headers.setAll(inputAuth.headers, input)));
1281
+ var remove = (name) => auth((input) => effect$1.Effect.succeed(http.Headers.remove(input.headers, name)));
1282
+ var custom = (apply) => auth(apply);
1283
+ var passthrough = none;
1284
+ var fromModelApiKey = (from) => auth(({ request: request2, headers: headers2 }) => {
1285
+ const key = request2.model.apiKey;
1286
+ if (!key) return effect$1.Effect.succeed(headers2);
1287
+ return effect$1.Effect.succeed(http.Headers.setAll(headers2, from(key)));
1288
+ });
1289
+ var credentialInput = (source) => typeof source === "string" || effect$1.Redacted.isRedacted(source) || effect$1.Config.isConfig(source) ? credentialFromSecret(source, "value") : source;
1290
+ function bearer(source) {
1291
+ if (source === void 0) return fromModelApiKey((key) => ({ authorization: `Bearer ${key}` }));
1292
+ return credentialInput(source).bearer();
1293
+ }
1294
+ var apiKey = bearer;
1295
+ var apiKeyHeader = (name) => fromModelApiKey((key) => ({ [name]: key }));
1296
+ function header(name, source) {
1297
+ if (source === void 0) {
1298
+ return (next) => credentialInput(next).header(name);
1299
+ }
1300
+ return credentialInput(source).header(name);
1301
+ }
1302
+ function bearerHeader(name, source) {
1303
+ const render2 = (input) => fromCredential(credentialInput(input), (secret) => ({ [name]: `Bearer ${secret}` }));
1304
+ if (source === void 0) return render2;
1305
+ return render2(source);
1306
+ }
1307
+ var toLLMError = (error) => {
1308
+ if (error instanceof MissingCredentialError || error instanceof effect$1.Config.ConfigError) {
1309
+ return new LLMError({
1310
+ module: "Auth",
1311
+ method: "apply",
1312
+ reason: error instanceof MissingCredentialError ? new AuthenticationReason({ message: error.message, kind: "missing" }) : new InvalidRequestReason({ message: `Failed to resolve auth config: ${error.message}` })
1313
+ });
1314
+ }
1315
+ return error;
1316
+ };
1317
+ var toEffect = (input) => (authInput) => input.apply(authInput).pipe(effect$1.Effect.mapError(toLLMError));
1318
+
1319
+ // src/route/auth-options.ts
1320
+ var auth_options_exports = {};
1321
+ __export(auth_options_exports, {
1322
+ AuthOptions: () => auth_options_exports,
1323
+ bearer: () => bearer2
1324
+ });
1325
+ var bearer2 = (options2, envVar) => {
1326
+ if ("auth" in options2 && options2.auth) return options2.auth;
1327
+ return (Array.isArray(envVar) ? envVar : [envVar]).reduce(
1328
+ (auth3, name) => auth3.orElse(auth_exports.config(name)),
1329
+ auth_exports.optional("apiKey" in options2 ? options2.apiKey : void 0, "apiKey")
1330
+ ).bearer();
1331
+ };
1332
+
1333
+ // src/route/transport/http.ts
1334
+ var http_exports = {};
1335
+ __export(http_exports, {
1336
+ httpJson: () => httpJson,
1337
+ jsonRequestParts: () => jsonRequestParts
1338
+ });
1339
+ var applyQuery = (url, query) => {
1340
+ if (!query) return url;
1341
+ const next = new URL(url);
1342
+ Object.entries(query).forEach(([key, value2]) => next.searchParams.set(key, value2));
1343
+ return next.toString();
1344
+ };
1345
+ var bodyWithOverlay = (body, request2, encodeBody2) => effect$1.Effect.gen(function* () {
1346
+ if (request2.http?.body === void 0) return { jsonBody: body, bodyText: encodeBody2(body) };
1347
+ if (isRecord3(body)) {
1348
+ const overlaid = mergeJsonRecords(body, request2.http.body) ?? {};
1349
+ return { jsonBody: overlaid, bodyText: encodeJson(overlaid) };
1350
+ }
1351
+ return yield* invalidRequest("http.body can only overlay JSON object request bodies");
1352
+ });
1353
+ var jsonRequestParts = (input) => effect$1.Effect.gen(function* () {
1354
+ const url = applyQuery(
1355
+ render(input.endpoint, { request: input.request, body: input.body }).toString(),
1356
+ input.request.http?.query
1357
+ );
1358
+ const body = yield* bodyWithOverlay(input.body, input.request, input.encodeBody);
1359
+ const headers2 = yield* auth_exports.toEffect(auth_exports.isAuth(input.request.model.auth) ? input.request.model.auth : input.auth)(
1360
+ {
1361
+ request: input.request,
1362
+ method: "POST",
1363
+ url,
1364
+ body: body.bodyText,
1365
+ headers: http.Headers.fromInput({
1366
+ ...input.headers?.({ request: input.request }) ?? {},
1367
+ ...input.request.model.headers,
1368
+ ...input.request.http?.headers
1369
+ })
1370
+ }
1371
+ );
1372
+ return { url, jsonBody: body.jsonBody, bodyText: body.bodyText, headers: headers2 };
1373
+ });
1374
+ var httpJson = (input) => ({
1375
+ id: "http-json",
1376
+ with: (patch) => httpJson({ ...input, ...patch }),
1377
+ prepare: (body, request2) => jsonRequestParts({
1378
+ body,
1379
+ request: request2,
1380
+ endpoint: input.endpoint,
1381
+ auth: input.auth ?? auth_exports.bearer(),
1382
+ encodeBody: input.encodeBody,
1383
+ headers: input.headers
1384
+ }).pipe(
1385
+ effect$1.Effect.map((parts) => ({
1386
+ request: jsonPost({ url: parts.url, body: parts.bodyText, headers: parts.headers }),
1387
+ framing: input.framing
1388
+ }))
1389
+ ),
1390
+ frames: (prepared, request2, runtime) => effect$1.Stream.unwrap(
1391
+ runtime.http.execute(prepared.request).pipe(
1392
+ effect$1.Effect.map(
1393
+ (response) => prepared.framing.frame(
1394
+ response.stream.pipe(
1395
+ effect$1.Stream.mapError(
1396
+ (error) => eventError(
1397
+ `${request2.model.provider}/${request2.model.route}`,
1398
+ `Failed to read ${request2.model.provider}/${request2.model.route} stream`,
1399
+ errorText(error)
1400
+ )
1401
+ )
1402
+ )
1403
+ )
1404
+ )
1405
+ )
1406
+ )
1407
+ });
1408
+
1409
+ // src/route/executor.ts
1410
+ var executor_exports = {};
1411
+ __export(executor_exports, {
1412
+ RequestExecutor: () => executor_exports,
1413
+ Service: () => Service,
1414
+ defaultLayer: () => defaultLayer,
1415
+ layer: () => layer
1416
+ });
1417
+
1418
+ // src/route/overflow-detect.ts
1419
+ var OVERFLOW_PATTERNS = [
1420
+ /prompt is too long/i,
1421
+ // Anthropic
1422
+ /input is too long for requested model/i,
1423
+ // Amazon Bedrock
1424
+ /exceeds the context window/i,
1425
+ // OpenAI
1426
+ /input token count.*exceeds the maximum/i,
1427
+ // Google (Gemini)
1428
+ /maximum prompt length is \d+/i,
1429
+ // xAI (Grok)
1430
+ /reduce the length of the messages/i,
1431
+ // Groq
1432
+ /maximum context length is \d+ tokens/i,
1433
+ // OpenRouter, DeepSeek, vLLM
1434
+ /exceeds the limit of \d+/i,
1435
+ // GitHub Copilot
1436
+ /exceeds the available context size/i,
1437
+ // llama.cpp server
1438
+ /greater than the context length/i,
1439
+ // LM Studio
1440
+ /context window exceeds limit/i,
1441
+ // MiniMax
1442
+ /exceeded model token limit/i,
1443
+ // Kimi, Moonshot
1444
+ /context[_ ]length[_ ]exceeded/i,
1445
+ // Generic OpenAI-style code
1446
+ /request entity too large/i,
1447
+ // HTTP 413
1448
+ /context length is only \d+ tokens/i,
1449
+ // vLLM
1450
+ /input length.*exceeds.*context length/i,
1451
+ // vLLM
1452
+ /prompt too long; exceeded (?:max )?context length/i,
1453
+ // Ollama
1454
+ /too large for model with \d+ maximum context length/i,
1455
+ // Mistral
1456
+ /model_context_window_exceeded/i
1457
+ // z.ai
1458
+ ];
1459
+ var NO_BODY_4XX = /^4(00|13)\s*(status code)?\s*\(no body\)/i;
1460
+ var isOverflowMessage = (message2) => {
1461
+ if (OVERFLOW_PATTERNS.some((p) => p.test(message2))) return true;
1462
+ return NO_BODY_4XX.test(message2);
1463
+ };
1464
+ var isOverflowStatus = (status) => status === 413;
1465
+ var TOKENS_GT_MAX = /(\d{4,})\s*tokens?\s*[>≥]\s*(\d{4,})/i;
1466
+ var PROMPT_LENGTH = /prompt is too long:\s*(\d{4,})\s*tokens?\s*>\s*(\d{4,})\s*maximum/i;
1467
+ var INPUT_LIMIT = /input length\s*(\d{4,}).*context length\s*(\d{4,})/i;
1468
+ var extractOverflowNumbers = (message2) => {
1469
+ const match = PROMPT_LENGTH.exec(message2) ?? INPUT_LIMIT.exec(message2) ?? TOKENS_GT_MAX.exec(message2);
1470
+ if (!match) return void 0;
1471
+ const promptTokens = Number(match[1]);
1472
+ const contextWindow = Number(match[2]);
1473
+ if (!Number.isFinite(promptTokens) || !Number.isFinite(contextWindow)) return void 0;
1474
+ return { promptTokens, contextWindow };
1475
+ };
1476
+ var isOverflowBody = (body) => {
1477
+ if (typeof body !== "object" || body === null) return false;
1478
+ const root = body;
1479
+ const code = root.error?.code ?? root.code;
1480
+ if (typeof code === "string" && /context[_ ]length[_ ]exceeded/i.test(code)) return true;
1481
+ if (typeof code === "string" && /model_context_window_exceeded/i.test(code)) return true;
1482
+ return false;
1483
+ };
1484
+
1485
+ // src/route/executor.ts
1486
+ var Service = class extends effect$1.Context.Service()("@tinyweb-agent/LLM/RequestExecutor") {
1487
+ };
1488
+ var BODY_LIMIT = 16384;
1489
+ var MAX_RETRIES = 2;
1490
+ var BASE_DELAY_MS = 500;
1491
+ var MAX_DELAY_MS = 1e4;
1492
+ var REDACTED = "<redacted>";
1493
+ var SENSITIVE_NAME_SOURCE = "authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|credential|signature|x-amz-signature";
1494
+ var SENSITIVE_NAME = new RegExp(SENSITIVE_NAME_SOURCE, "i");
1495
+ var SHORT_QUERY_NAME = /^(key|sig)$/i;
1496
+ var SENSITIVE_BODY_FIELD = new RegExp(`(?:${SENSITIVE_NAME_SOURCE}|key)`, "i");
1497
+ var REDACT_JSON_FIELD = new RegExp(`("(?:${SENSITIVE_BODY_FIELD.source})"\\s*:\\s*)"[^"]*"`, "gi");
1498
+ var REDACT_QUERY_FIELD = new RegExp(`((?:${SENSITIVE_BODY_FIELD.source})=)[^&\\s"]+`, "gi");
1499
+ var isSensitiveHeaderName = (name) => SENSITIVE_NAME.test(name);
1500
+ var isSensitiveQueryName = (name) => isSensitiveHeaderName(name) || SHORT_QUERY_NAME.test(name);
1501
+ var redactHeaders = (headers2, redactedNames) => Object.fromEntries(
1502
+ Object.entries(http.Headers.redact(headers2, [...redactedNames, SENSITIVE_NAME])).map(([name, value2]) => [
1503
+ name,
1504
+ String(value2)
1505
+ ])
1506
+ );
1507
+ var redactUrl = (value2) => {
1508
+ if (!URL.canParse(value2)) return REDACTED;
1509
+ const url = new URL(value2);
1510
+ url.searchParams.forEach((_, key) => {
1511
+ if (isSensitiveQueryName(key)) url.searchParams.set(key, REDACTED);
1512
+ });
1513
+ return url.toString();
1514
+ };
1515
+ var normalizedHeaders = (headers2) => Object.fromEntries(Object.entries(headers2).map(([key, value2]) => [key.toLowerCase(), value2]));
1516
+ var requestId = (headers2) => {
1517
+ return headers2["x-request-id"] ?? headers2["request-id"] ?? headers2["x-amzn-requestid"] ?? headers2["x-amz-request-id"] ?? headers2["x-goog-request-id"] ?? headers2["cf-ray"];
1518
+ };
1519
+ var retryableStatus = (status) => status === 429 || status === 503 || status === 504 || status === 529;
1520
+ var retryAfterMs = (headers2) => {
1521
+ const millis = Number(headers2["retry-after-ms"]);
1522
+ if (Number.isFinite(millis)) return Math.max(0, millis);
1523
+ const value2 = headers2["retry-after"];
1524
+ if (!value2) return void 0;
1525
+ const seconds = Number(value2);
1526
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
1527
+ const date = Date.parse(value2);
1528
+ if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
1529
+ return void 0;
1530
+ };
1531
+ var addRateLimitValue = (target, key, value2) => {
1532
+ if (key.length > 0) target[key] = value2;
1533
+ };
1534
+ var rateLimitDetails = (headers2, retryAfter) => {
1535
+ const limit = {};
1536
+ const remaining = {};
1537
+ const reset = {};
1538
+ Object.entries(headers2).forEach(([name, value2]) => {
1539
+ const openaiLimit = /^x-ratelimit-limit-(.+)$/.exec(name)?.[1];
1540
+ if (openaiLimit) return addRateLimitValue(limit, openaiLimit, value2);
1541
+ const openaiRemaining = /^x-ratelimit-remaining-(.+)$/.exec(name)?.[1];
1542
+ if (openaiRemaining) return addRateLimitValue(remaining, openaiRemaining, value2);
1543
+ const openaiReset = /^x-ratelimit-reset-(.+)$/.exec(name)?.[1];
1544
+ if (openaiReset) return addRateLimitValue(reset, openaiReset, value2);
1545
+ const anthropic = /^anthropic-ratelimit-(.+)-(limit|remaining|reset)$/.exec(name);
1546
+ if (!anthropic) return;
1547
+ if (anthropic[2] === "limit") return addRateLimitValue(limit, anthropic[1], value2);
1548
+ if (anthropic[2] === "remaining") return addRateLimitValue(remaining, anthropic[1], value2);
1549
+ return addRateLimitValue(reset, anthropic[1], value2);
1550
+ });
1551
+ if (retryAfter === void 0 && Object.keys(limit).length === 0 && Object.keys(remaining).length === 0 && Object.keys(reset).length === 0)
1552
+ return void 0;
1553
+ return new HttpRateLimitDetails({
1554
+ retryAfterMs: retryAfter,
1555
+ limit: Object.keys(limit).length === 0 ? void 0 : limit,
1556
+ remaining: Object.keys(remaining).length === 0 ? void 0 : remaining,
1557
+ reset: Object.keys(reset).length === 0 ? void 0 : reset
1558
+ });
1559
+ };
1560
+ var requestDetails = (request2, redactedNames) => new HttpRequestDetails({
1561
+ method: request2.method,
1562
+ url: redactUrl(request2.url),
1563
+ headers: redactHeaders(request2.headers, redactedNames)
1564
+ });
1565
+ var responseDetails = (response, redactedNames) => new HttpResponseDetails({
1566
+ status: response.status,
1567
+ headers: redactHeaders(response.headers, redactedNames)
1568
+ });
1569
+ var secretValues = (request2) => {
1570
+ const values = /* @__PURE__ */ new Set();
1571
+ const add = (value2) => {
1572
+ if (value2.length < 4) return;
1573
+ values.add(value2);
1574
+ values.add(encodeURIComponent(value2));
1575
+ };
1576
+ Object.entries(request2.headers).forEach(([name, value2]) => {
1577
+ if (!isSensitiveHeaderName(name)) return;
1578
+ add(value2);
1579
+ const bearer3 = /^Bearer\s+(.+)$/i.exec(value2)?.[1];
1580
+ if (bearer3) add(bearer3);
1581
+ });
1582
+ if (!URL.canParse(request2.url)) return values;
1583
+ new URL(request2.url).searchParams.forEach((value2, key) => {
1584
+ if (isSensitiveQueryName(key)) add(value2);
1585
+ });
1586
+ return values;
1587
+ };
1588
+ var redactBody = (body, request2) => Array.from(secretValues(request2)).reduce(
1589
+ (text2, secret) => text2.split(secret).join(REDACTED),
1590
+ body.replace(REDACT_JSON_FIELD, `$1"${REDACTED}"`).replace(REDACT_QUERY_FIELD, `$1${REDACTED}`)
1591
+ );
1592
+ var responseBody = (body, request2) => {
1593
+ if (body === void 0) return {};
1594
+ const redacted = redactBody(body, request2);
1595
+ if (redacted.length <= BODY_LIMIT) return { body: redacted };
1596
+ return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true };
1597
+ };
1598
+ var providerMessage = (status, body) => {
1599
+ if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`;
1600
+ return `Provider request failed with HTTP ${status}`;
1601
+ };
1602
+ var responseHttp = (input) => new HttpContext({
1603
+ request: requestDetails(input.request, input.redactedNames),
1604
+ response: responseDetails(input.response, input.redactedNames),
1605
+ ...input.body,
1606
+ requestId: input.requestId,
1607
+ rateLimit: input.rateLimit
1608
+ });
1609
+ var parseJsonBody = (body) => {
1610
+ if (body.length === 0) return void 0;
1611
+ try {
1612
+ return JSON.parse(body);
1613
+ } catch {
1614
+ return void 0;
1615
+ }
1616
+ };
1617
+ var isOverflow = (status, message2, body) => {
1618
+ if (isOverflowStatus(status)) return true;
1619
+ if (isOverflowMessage(message2)) return true;
1620
+ if (body.length > 0 && isOverflowMessage(body)) return true;
1621
+ return isOverflowBody(parseJsonBody(body));
1622
+ };
1623
+ var overflowReason = (input) => {
1624
+ const numbers = extractOverflowNumbers(input.message) ?? extractOverflowNumbers(input.body);
1625
+ return new ContextOverflowReason({
1626
+ message: input.message,
1627
+ promptTokens: numbers?.promptTokens,
1628
+ contextWindow: numbers?.contextWindow,
1629
+ http: input.http
1630
+ });
1631
+ };
1632
+ var statusReason = (input) => {
1633
+ const body = input.http.body ?? "";
1634
+ if (isOverflow(input.status, input.message, body)) {
1635
+ return overflowReason({ message: input.message, body, http: input.http });
1636
+ }
1637
+ if (/content[-_\s]?policy|content_filter|safety/i.test(body)) {
1638
+ return new ContentPolicyReason({ message: input.message, http: input.http });
1639
+ }
1640
+ if (input.status === 401) {
1641
+ return new AuthenticationReason({ message: input.message, kind: "invalid", http: input.http });
1642
+ }
1643
+ if (input.status === 403) {
1644
+ return new AuthenticationReason({ message: input.message, kind: "insufficient-permissions", http: input.http });
1645
+ }
1646
+ if (input.status === 429) {
1647
+ if (/insufficient[-_\s]?quota|quota[-_\s]?exceeded/i.test(body)) {
1648
+ return new QuotaExceededReason({ message: input.message, http: input.http });
1649
+ }
1650
+ return new RateLimitReason({
1651
+ message: input.message,
1652
+ retryAfterMs: input.retryAfterMs,
1653
+ rateLimit: input.rateLimit,
1654
+ http: input.http
1655
+ });
1656
+ }
1657
+ if (input.status === 400 || input.status === 404 || input.status === 409 || input.status === 422) {
1658
+ return new InvalidRequestReason({ message: input.message, http: input.http });
1659
+ }
1660
+ if (input.status >= 500 || retryableStatus(input.status)) {
1661
+ return new ProviderInternalReason({
1662
+ message: input.message,
1663
+ status: input.status,
1664
+ retryAfterMs: input.retryAfterMs,
1665
+ http: input.http
1666
+ });
1667
+ }
1668
+ return new UnknownProviderReason({ message: input.message, status: input.status, http: input.http });
1669
+ };
1670
+ var statusError = (request2, redactedNames) => (response) => effect$1.Effect.gen(function* () {
1671
+ if (response.status < 400) return response;
1672
+ const body = yield* response.text.pipe(effect$1.Effect.catch(() => effect$1.Effect.void));
1673
+ const headers2 = normalizedHeaders(response.headers);
1674
+ const retryAfter = retryAfterMs(headers2);
1675
+ const rateLimit = rateLimitDetails(headers2, retryAfter);
1676
+ const details = responseBody(body, request2);
1677
+ return yield* new LLMError({
1678
+ module: "RequestExecutor",
1679
+ method: "execute",
1680
+ reason: statusReason({
1681
+ status: response.status,
1682
+ message: providerMessage(response.status, details),
1683
+ retryAfterMs: retryAfter,
1684
+ rateLimit,
1685
+ http: responseHttp({
1686
+ request: request2,
1687
+ response,
1688
+ redactedNames,
1689
+ body: details,
1690
+ requestId: requestId(headers2),
1691
+ rateLimit
1692
+ })
1693
+ })
1694
+ });
1695
+ });
1696
+ var toHttpError = (redactedNames) => (error) => {
1697
+ const transportError = (input) => new LLMError({
1698
+ module: "RequestExecutor",
1699
+ method: "execute",
1700
+ reason: new TransportReason({
1701
+ message: input.message,
1702
+ kind: input.kind,
1703
+ url: input.request ? redactUrl(input.request.url) : void 0,
1704
+ http: input.request ? new HttpContext({ request: requestDetails(input.request, redactedNames) }) : void 0
1705
+ })
1706
+ });
1707
+ if (effect$1.Cause.isTimeoutError(error)) {
1708
+ return transportError({ message: error.message, kind: "Timeout" });
1709
+ }
1710
+ if (!http.HttpClientError.isHttpClientError(error)) {
1711
+ return transportError({ message: "HTTP transport failed" });
1712
+ }
1713
+ const request2 = "request" in error ? error.request : void 0;
1714
+ if (error.reason._tag === "TransportError") {
1715
+ return transportError({
1716
+ message: error.reason.description ?? "HTTP transport failed",
1717
+ kind: error.reason._tag,
1718
+ request: request2
1719
+ });
1720
+ }
1721
+ return transportError({
1722
+ message: `HTTP transport failed: ${error.reason._tag}`,
1723
+ kind: error.reason._tag,
1724
+ request: request2
1725
+ });
1726
+ };
1727
+ var retryDelay = (error, attempt) => {
1728
+ if (error.retryAfterMs !== void 0) return effect$1.Effect.succeed(Math.min(error.retryAfterMs, MAX_DELAY_MS));
1729
+ return effect$1.Random.nextBetween(
1730
+ Math.min(BASE_DELAY_MS * 2 ** attempt * 0.8, MAX_DELAY_MS),
1731
+ Math.min(BASE_DELAY_MS * 2 ** attempt * 1.2, MAX_DELAY_MS)
1732
+ ).pipe(effect$1.Effect.map((delay) => Math.round(delay)));
1733
+ };
1734
+ var retryStatusFailures = (effect2, retries = MAX_RETRIES, attempt = 0) => effect$1.Effect.catchTag(effect2, "LLM.Error", (error) => {
1735
+ if (!error.retryable || retries <= 0) return effect$1.Effect.fail(error);
1736
+ return retryDelay(error, attempt).pipe(
1737
+ effect$1.Effect.flatMap((delay) => effect$1.Effect.sleep(delay)),
1738
+ effect$1.Effect.flatMap(() => retryStatusFailures(effect2, retries - 1, attempt + 1))
1739
+ );
1740
+ });
1741
+ var layer = effect$1.Layer.effect(
1742
+ Service,
1743
+ effect$1.Effect.gen(function* () {
1744
+ const http$1 = yield* http.HttpClient.HttpClient;
1745
+ const executeOnce = (request2) => effect$1.Effect.gen(function* () {
1746
+ const redactedNames = yield* http.Headers.CurrentRedactedNames;
1747
+ return yield* http$1.execute(request2).pipe(effect$1.Effect.mapError(toHttpError(redactedNames)), effect$1.Effect.flatMap(statusError(request2, redactedNames)));
1748
+ });
1749
+ return Service.of({
1750
+ execute: (request2) => retryStatusFailures(executeOnce(request2))
1751
+ });
1752
+ })
1753
+ );
1754
+ var defaultLayer = layer.pipe(effect$1.Layer.provide(http.FetchHttpClient.layer));
1755
+
1756
+ // src/cache-policy.ts
1757
+ var AUTO = {
1758
+ tools: true,
1759
+ system: true,
1760
+ messages: "latest-user-message"
1761
+ };
1762
+ var NONE = {};
1763
+ var resolve = (policy) => {
1764
+ if (policy === void 0 || policy === "auto") return AUTO;
1765
+ if (policy === "none") return NONE;
1766
+ return policy;
1767
+ };
1768
+ var RESPECTS_INLINE_HINTS = /* @__PURE__ */ new Set([]);
1769
+ var makeHint = (ttlSeconds) => ttlSeconds !== void 0 ? new CacheHint({ type: "ephemeral", ttlSeconds }) : new CacheHint({ type: "ephemeral" });
1770
+ var markLastTool = (tools, hint) => {
1771
+ if (tools.length === 0) return tools;
1772
+ const last = tools.length - 1;
1773
+ if (tools[last].cache) return tools;
1774
+ return tools.map((tool2, i) => i === last ? new exports.ToolDefinition({ ...tool2, cache: hint }) : tool2);
1775
+ };
1776
+ var markLastSystem = (system2, hint) => {
1777
+ if (system2.length === 0) return system2;
1778
+ const last = system2.length - 1;
1779
+ if (system2[last].cache) return system2;
1780
+ return system2.map((part, i) => i === last ? { ...part, cache: hint } : part);
1781
+ };
1782
+ var lastIndexOfRole = (messages, role) => messages.findLastIndex((m) => m.role === role);
1783
+ var markMessageAt = (messages, index, hint) => {
1784
+ if (index < 0 || index >= messages.length) return messages;
1785
+ const target = messages[index];
1786
+ if (target.content.length === 0) return messages;
1787
+ const lastTextIndex = target.content.findLastIndex((part) => part.type === "text");
1788
+ const markAt = lastTextIndex >= 0 ? lastTextIndex : target.content.length - 1;
1789
+ const existing = target.content[markAt];
1790
+ if ("cache" in existing && existing.cache) return messages;
1791
+ const nextContent = target.content.map((part, i) => i === markAt ? { ...part, cache: hint } : part);
1792
+ const next = new exports.Message({ ...target, content: nextContent });
1793
+ const result = messages.slice();
1794
+ result[index] = next;
1795
+ return result;
1796
+ };
1797
+ var markMessages = (messages, strategy, hint) => {
1798
+ if (messages.length === 0) return messages;
1799
+ if (strategy === "latest-user-message") return markMessageAt(messages, lastIndexOfRole(messages, "user"), hint);
1800
+ if (strategy === "latest-assistant") return markMessageAt(messages, lastIndexOfRole(messages, "assistant"), hint);
1801
+ const start2 = Math.max(0, messages.length - strategy.tail);
1802
+ let next = messages;
1803
+ for (let i = start2; i < messages.length; i++) next = markMessageAt(next, i, hint);
1804
+ return next;
1805
+ };
1806
+ var applyCachePolicy = (request2) => {
1807
+ if (!RESPECTS_INLINE_HINTS.has(request2.model.route)) return request2;
1808
+ const policy = resolve(request2.cache);
1809
+ if (!policy.tools && !policy.system && !policy.messages) return request2;
1810
+ const hint = makeHint(policy.ttlSeconds);
1811
+ const tools = policy.tools ? markLastTool(request2.tools, hint) : request2.tools;
1812
+ const system2 = policy.system ? markLastSystem(request2.system, hint) : request2.system;
1813
+ const messages = policy.messages ? markMessages(request2.messages, policy.messages, hint) : request2.messages;
1814
+ if (tools === request2.tools && system2 === request2.system && messages === request2.messages) return request2;
1815
+ return exports.LLMRequest.update(request2, { tools, system: system2, messages });
1816
+ };
1817
+
1818
+ // src/route/client.ts
1819
+ var routeRegistry = /* @__PURE__ */ new Map();
1820
+ var register = (route3) => {
1821
+ const existing = routeRegistry.get(route3.id);
1822
+ if (existing && existing !== route3) throw new Error(`Duplicate LLM route id "${route3.id}"`);
1823
+ routeRegistry.set(route3.id, route3);
1824
+ return route3;
1825
+ };
1826
+ var registeredRoute = (id3) => routeRegistry.get(id3);
1827
+ var modelWithDefaults = (route3, defaults, options2) => (input) => {
1828
+ const mapped = options2.mapInput === void 0 ? input : options2.mapInput(input);
1829
+ const provider3 = defaults.provider ?? route3.provider ?? ("provider" in mapped ? mapped.provider : void 0);
1830
+ if (!provider3) throw new Error(`Route.model(${route3.id}) requires a provider`);
1831
+ const baseURL = mapped.baseURL ?? defaults.baseURL ?? route3.defaults.baseURL;
1832
+ if (!baseURL)
1833
+ throw new Error(`Route.model(${route3.id}) requires a baseURL \u2014 supply it via input, defaults, or route defaults`);
1834
+ const generation2 = mergeGenerationOptions(route3.defaults.generation, defaults.generation);
1835
+ const providerOptions = mergeProviderOptions(route3.defaults.providerOptions, defaults.providerOptions);
1836
+ const http = mergeHttpOptions(httpOptions(route3.defaults.http), httpOptions(defaults.http));
1837
+ return modelRef({
1838
+ ...route3.defaults,
1839
+ ...defaults,
1840
+ ...mapped,
1841
+ baseURL,
1842
+ provider: provider3,
1843
+ route: route3.id,
1844
+ limits: mapped.limits ?? defaults.limits ?? route3.defaults.limits,
1845
+ generation: mergeGenerationOptions(generation2, mapped.generation),
1846
+ providerOptions: mergeProviderOptions(providerOptions, mapped.providerOptions),
1847
+ http: mergeHttpOptions(http, httpOptions(mapped.http))
1848
+ });
1849
+ };
1850
+ var mergeRouteDefaults = (base, patch) => ({
1851
+ ...base,
1852
+ ...patch,
1853
+ limits: patch.limits ?? base?.limits,
1854
+ generation: mergeGenerationOptions(generationOptions(base?.generation), generationOptions(patch.generation)),
1855
+ providerOptions: mergeProviderOptions(base?.providerOptions, patch.providerOptions),
1856
+ http: mergeHttpOptions(httpOptions(base?.http), httpOptions(patch.http))
1857
+ });
1858
+ var modelLimits = exports.ModelLimits.make;
1859
+ var generationOptions = (input) => input === void 0 ? void 0 : exports.GenerationOptions.make(input);
1860
+ var httpOptions = (input) => {
1861
+ if (input === void 0) return input;
1862
+ return exports.HttpOptions.make(input);
1863
+ };
1864
+ var modelRef = (input) => new exports.ModelRef({
1865
+ ...input,
1866
+ id: ModelID.make(input.id),
1867
+ provider: ProviderID.make(input.provider),
1868
+ route: RouteID.make(input.route),
1869
+ limits: modelLimits(input.limits),
1870
+ generation: generationOptions(input.generation),
1871
+ http: httpOptions(input.http)
1872
+ });
1873
+ function model(route3, defaults = {}, options2 = {}) {
1874
+ return modelWithDefaults(route3, defaults, options2);
1875
+ }
1876
+ var Service2 = class extends effect$1.Context.Service()("@tinyweb-agent/LLMClient") {
1877
+ };
1878
+ var noRoute = (model7) => new LLMError({
1879
+ module: "LLMClient",
1880
+ method: "resolveRoute",
1881
+ reason: new NoRouteReason({ route: model7.route, provider: model7.provider, model: model7.id })
1882
+ });
1883
+ var resolveRequestOptions = (request2) => exports.LLMRequest.update(request2, {
1884
+ generation: mergeGenerationOptions(request2.model.generation, request2.generation) ?? new exports.GenerationOptions({}),
1885
+ providerOptions: mergeProviderOptions(request2.model.providerOptions, request2.providerOptions),
1886
+ http: mergeHttpOptions(request2.model.http, request2.http)
1887
+ });
1888
+ var streamError = (route3, message2, cause) => {
1889
+ const failed = cause.reasons.find(effect$1.Cause.isFailReason)?.error;
1890
+ if (failed instanceof LLMError) return failed;
1891
+ return eventError(route3, message2, effect$1.Cause.pretty(cause));
1892
+ };
1893
+ function makeFromTransport(input) {
1894
+ const protocol2 = input.protocol;
1895
+ const decodeEventEffect = effect$1.Schema.decodeUnknownEffect(protocol2.stream.event);
1896
+ const decodeEvent = (route3) => (frame) => decodeEventEffect(frame).pipe(
1897
+ effect$1.Effect.mapError(
1898
+ () => eventError(
1899
+ input.id,
1900
+ `Invalid ${route3} stream event`,
1901
+ typeof frame === "string" ? frame : encodeJson(frame)
1902
+ )
1903
+ )
1904
+ );
1905
+ const build = (routeInput) => {
1906
+ const route3 = {
1907
+ id: routeInput.id,
1908
+ provider: routeInput.provider === void 0 ? void 0 : ProviderID.make(routeInput.provider),
1909
+ protocol: protocol2.id,
1910
+ transport: routeInput.transport,
1911
+ defaults: routeInput.defaults ?? {},
1912
+ body: protocol2.body,
1913
+ with: (patch) => {
1914
+ const { id: id3, provider: provider3, transport, ...defaults } = patch;
1915
+ if (!id3 || id3 === routeInput.id) throw new Error(`Route.with(${routeInput.id}) requires a new route id`);
1916
+ return build({
1917
+ ...routeInput,
1918
+ id: id3,
1919
+ provider: provider3 ?? routeInput.provider,
1920
+ transport: transport ?? routeInput.transport,
1921
+ defaults: mergeRouteDefaults(routeInput.defaults, defaults)
1922
+ });
1923
+ },
1924
+ model: (input2) => modelWithDefaults(route3, {}, {})(input2),
1925
+ prepareTransport: routeInput.transport.prepare,
1926
+ streamPrepared: (prepared, request2, runtime) => {
1927
+ const route4 = `${request2.model.provider}/${request2.model.route}`;
1928
+ const events = routeInput.transport.frames(prepared, request2, runtime).pipe(
1929
+ effect$1.Stream.mapEffect(decodeEvent(route4)),
1930
+ protocol2.stream.terminal ? effect$1.Stream.takeUntil(protocol2.stream.terminal) : (stream4) => stream4
1931
+ );
1932
+ return events.pipe(
1933
+ effect$1.Stream.mapAccumEffect(
1934
+ protocol2.stream.initial,
1935
+ protocol2.stream.step,
1936
+ protocol2.stream.onHalt ? { onHalt: protocol2.stream.onHalt } : void 0
1937
+ ),
1938
+ effect$1.Stream.catchCause((cause) => effect$1.Stream.fail(streamError(route4, `Failed to read ${route4} stream`, cause)))
1939
+ );
1940
+ }
1941
+ };
1942
+ return register(route3);
1943
+ };
1944
+ return build(input);
1945
+ }
1946
+ function make3(input) {
1947
+ if ("transport" in input) return makeFromTransport(input);
1948
+ const protocol2 = input.protocol;
1949
+ const encodeBody2 = effect$1.Schema.encodeSync(effect$1.Schema.fromJsonString(protocol2.body.schema));
1950
+ return makeFromTransport({
1951
+ id: input.id,
1952
+ provider: input.provider,
1953
+ protocol: protocol2,
1954
+ transport: http_exports.httpJson({
1955
+ endpoint: input.endpoint,
1956
+ auth: input.auth,
1957
+ framing: input.framing,
1958
+ encodeBody: encodeBody2,
1959
+ headers: input.headers
1960
+ }),
1961
+ defaults: input.defaults
1962
+ });
1963
+ }
1964
+ var compile = effect$1.Effect.fn("LLM.compile")(function* (request2) {
1965
+ const resolved = applyCachePolicy(resolveRequestOptions(request2));
1966
+ const route3 = registeredRoute(resolved.model.route);
1967
+ if (!route3) return yield* noRoute(resolved.model);
1968
+ const body = yield* route3.body.from(resolved).pipe(effect$1.Effect.flatMap(validateWith(effect$1.Schema.decodeUnknownEffect(route3.body.schema))));
1969
+ const prepared = yield* route3.prepareTransport(body, resolved);
1970
+ return {
1971
+ request: resolved,
1972
+ route: route3,
1973
+ body,
1974
+ prepared
1975
+ };
1976
+ });
1977
+ var prepareWith = effect$1.Effect.fn("LLMClient.prepare")(function* (request2) {
1978
+ const compiled = yield* compile(request2);
1979
+ return new PreparedRequest({
1980
+ id: compiled.request.id ?? "request",
1981
+ route: compiled.route.id,
1982
+ protocol: compiled.route.protocol,
1983
+ model: compiled.request.model,
1984
+ body: compiled.body,
1985
+ metadata: { transport: compiled.route.transport.id }
1986
+ });
1987
+ });
1988
+ var streamRequestWith = (runtime) => (request2) => effect$1.Stream.unwrap(
1989
+ effect$1.Effect.gen(function* () {
1990
+ const compiled = yield* compile(request2);
1991
+ return compiled.route.streamPrepared(compiled.prepared, compiled.request, runtime);
1992
+ })
1993
+ );
1994
+ var isToolRunOptions = (input) => "request" in input && "tools" in input;
1995
+ var streamWith = (streamRequest) => ((input) => {
1996
+ if (isToolRunOptions(input)) return stream({ ...input, stream: streamRequest });
1997
+ return streamRequest(input);
1998
+ });
1999
+ var generateWith = (stream4) => effect$1.Effect.fn("LLM.generate")(function* (input) {
2000
+ return new exports.LLMResponse(
2001
+ yield* stream4(input).pipe(
2002
+ effect$1.Stream.runFold(
2003
+ () => ({ events: [], usage: void 0 }),
2004
+ (acc, event) => {
2005
+ acc.events.push(event);
2006
+ if ("usage" in event && event.usage !== void 0) acc.usage = event.usage;
2007
+ return acc;
2008
+ }
2009
+ )
2010
+ )
2011
+ );
2012
+ });
2013
+ var prepare = (request2) => prepareWith(request2);
2014
+ function stream2(input) {
2015
+ return effect$1.Stream.unwrap(
2016
+ effect$1.Effect.gen(function* () {
2017
+ return (yield* Service2).stream(input);
2018
+ })
2019
+ );
2020
+ }
2021
+ function generate(input) {
2022
+ return effect$1.Effect.gen(function* () {
2023
+ return yield* (yield* Service2).generate(input);
2024
+ });
2025
+ }
2026
+ var layer2 = effect$1.Layer.effect(
2027
+ Service2,
2028
+ effect$1.Effect.gen(function* () {
2029
+ const stream4 = streamWith(streamRequestWith({ http: yield* executor_exports.Service }));
2030
+ return Service2.of({ prepare: prepareWith, stream: stream4, generate: generateWith(stream4) });
2031
+ })
2032
+ );
2033
+ var Route = { make: make3, model };
2034
+ var LLMClient = {
2035
+ Service: Service2,
2036
+ layer: layer2,
2037
+ prepare,
2038
+ stream: stream2,
2039
+ generate,
2040
+ stepCountIs,
2041
+ hasToolCall,
2042
+ stopWhenAny
2043
+ };
2044
+
2045
+ // src/protocols/openai-chat.ts
2046
+ var openai_chat_exports = {};
2047
+ __export(openai_chat_exports, {
2048
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
2049
+ OpenAIChat: () => openai_chat_exports,
2050
+ PATH: () => PATH,
2051
+ bodyFields: () => bodyFields,
2052
+ httpTransport: () => httpTransport,
2053
+ model: () => model2,
2054
+ protocol: () => protocol,
2055
+ route: () => route
2056
+ });
2057
+
2058
+ // src/protocols/utils/openai-options.ts
2059
+ var openai_options_exports = {};
2060
+ __export(openai_options_exports, {
2061
+ OpenAIOptions: () => openai_options_exports,
2062
+ OpenAIReasoningEffort: () => OpenAIReasoningEffort,
2063
+ OpenAIReasoningEfforts: () => OpenAIReasoningEfforts,
2064
+ OpenAITextVerbosity: () => OpenAITextVerbosity,
2065
+ encryptedReasoning: () => encryptedReasoning,
2066
+ isReasoningEffort: () => isReasoningEffort,
2067
+ promptCacheKey: () => promptCacheKey,
2068
+ reasoningEffort: () => reasoningEffort,
2069
+ reasoningSummary: () => reasoningSummary,
2070
+ store: () => store,
2071
+ textVerbosity: () => textVerbosity
2072
+ });
2073
+ var OpenAIReasoningEfforts = ReasoningEfforts.filter(
2074
+ (effort) => effort !== "max"
2075
+ );
2076
+ var REASONING_EFFORTS = new Set(ReasoningEfforts);
2077
+ var OPENAI_REASONING_EFFORTS = new Set(OpenAIReasoningEfforts);
2078
+ var TEXT_VERBOSITY = /* @__PURE__ */ new Set(["low", "medium", "high"]);
2079
+ var OpenAIReasoningEffort = effect$1.Schema.Literals(OpenAIReasoningEfforts);
2080
+ var OpenAITextVerbosity = TextVerbosity;
2081
+ var isAnyReasoningEffort = (effort) => typeof effort === "string" && REASONING_EFFORTS.has(effort);
2082
+ var isReasoningEffort = (effort) => typeof effort === "string" && OPENAI_REASONING_EFFORTS.has(effort);
2083
+ var isTextVerbosity = (value2) => typeof value2 === "string" && TEXT_VERBOSITY.has(value2);
2084
+ var options = (request2) => request2.providerOptions?.openai;
2085
+ var store = (request2) => {
2086
+ const value2 = options(request2)?.store;
2087
+ return typeof value2 === "boolean" ? value2 : void 0;
2088
+ };
2089
+ var reasoningEffort = (request2) => {
2090
+ const value2 = options(request2)?.reasoningEffort;
2091
+ return isAnyReasoningEffort(value2) ? value2 : void 0;
2092
+ };
2093
+ var reasoningSummary = (request2) => {
2094
+ return options(request2)?.reasoningSummary === "auto" ? "auto" : void 0;
2095
+ };
2096
+ var encryptedReasoning = (request2) => options(request2)?.includeEncryptedReasoning === true ? true : void 0;
2097
+ var promptCacheKey = (request2) => {
2098
+ const value2 = options(request2)?.promptCacheKey;
2099
+ return typeof value2 === "string" ? value2 : void 0;
2100
+ };
2101
+ var textVerbosity = (request2) => {
2102
+ const value2 = options(request2)?.textVerbosity;
2103
+ return isTextVerbosity(value2) ? value2 : void 0;
2104
+ };
2105
+
2106
+ // src/protocols/utils/tool-stream.ts
2107
+ var tool_stream_exports = {};
2108
+ __export(tool_stream_exports, {
2109
+ ToolStream: () => tool_stream_exports,
2110
+ appendExisting: () => appendExisting,
2111
+ appendOrStart: () => appendOrStart,
2112
+ empty: () => empty,
2113
+ finish: () => finish,
2114
+ finishAll: () => finishAll,
2115
+ finishWithInput: () => finishWithInput,
2116
+ isError: () => isError,
2117
+ start: () => start
2118
+ });
2119
+ var empty = () => ({});
2120
+ var withTool = (tools, key, tool2) => {
2121
+ return { ...tools, [key]: tool2 };
2122
+ };
2123
+ var withoutTool = (tools, key) => {
2124
+ const next = { ...tools };
2125
+ delete next[key];
2126
+ return next;
2127
+ };
2128
+ var inputDelta = (tool2, text2) => LLMEvent.toolInputDelta({
2129
+ id: tool2.id,
2130
+ name: tool2.name,
2131
+ text: text2
2132
+ });
2133
+ var toolCall = (route3, tool2, inputOverride) => parseToolInput(route3, tool2.name, inputOverride ?? tool2.input).pipe(
2134
+ effect$1.Effect.map(
2135
+ (input) => LLMEvent.toolCall({
2136
+ id: tool2.id,
2137
+ name: tool2.name,
2138
+ input,
2139
+ providerExecuted: tool2.providerExecuted ? true : void 0,
2140
+ providerMetadata: tool2.providerMetadata
2141
+ })
2142
+ )
2143
+ );
2144
+ var appendTool = (tools, key, tool2, text2) => ({
2145
+ tools: withTool(tools, key, tool2),
2146
+ tool: tool2,
2147
+ event: text2.length === 0 ? void 0 : inputDelta(tool2, text2)
2148
+ });
2149
+ var isError = (result) => result instanceof LLMError;
2150
+ var start = (tools, key, tool2) => withTool(tools, key, { ...tool2, input: tool2.input ?? "" });
2151
+ var appendOrStart = (route3, tools, key, delta, missingToolMessage) => {
2152
+ const current = tools[key];
2153
+ const id3 = delta.id ?? current?.id;
2154
+ const name = delta.name ?? current?.name;
2155
+ if (!id3 || !name) return eventError(route3, missingToolMessage);
2156
+ const tool2 = {
2157
+ id: id3,
2158
+ name,
2159
+ input: `${current?.input ?? ""}${delta.text}`,
2160
+ providerExecuted: current?.providerExecuted,
2161
+ providerMetadata: current?.providerMetadata
2162
+ };
2163
+ if (current && delta.text.length === 0 && current.id === id3 && current.name === name) return { tools, tool: current };
2164
+ return appendTool(tools, key, tool2, delta.text);
2165
+ };
2166
+ var appendExisting = (route3, tools, key, text2, missingToolMessage) => {
2167
+ const current = tools[key];
2168
+ if (!current) return eventError(route3, missingToolMessage);
2169
+ if (text2.length === 0) return { tools, tool: current };
2170
+ return appendTool(tools, key, { ...current, input: `${current.input}${text2}` }, text2);
2171
+ };
2172
+ var finish = (route3, tools, key) => effect$1.Effect.gen(function* () {
2173
+ const tool2 = tools[key];
2174
+ if (!tool2) return { tools };
2175
+ return { tools: withoutTool(tools, key), event: yield* toolCall(route3, tool2) };
2176
+ });
2177
+ var finishWithInput = (route3, tools, key, input) => effect$1.Effect.gen(function* () {
2178
+ const tool2 = tools[key];
2179
+ if (!tool2) return { tools };
2180
+ return { tools: withoutTool(tools, key), event: yield* toolCall(route3, tool2, input) };
2181
+ });
2182
+ var finishAll = (route3, tools) => effect$1.Effect.gen(function* () {
2183
+ const pending = Object.values(tools).filter(
2184
+ (tool2) => tool2 !== void 0
2185
+ );
2186
+ return {
2187
+ tools: empty(),
2188
+ events: yield* effect$1.Effect.forEach(pending, (tool2) => toolCall(route3, tool2))
2189
+ };
2190
+ });
2191
+
2192
+ // src/protocols/openai-chat.ts
2193
+ var ADAPTER = "openai-chat";
2194
+ var DEFAULT_BASE_URL = "https://api.openai.com/v1";
2195
+ var PATH = "/chat/completions";
2196
+ var OpenAIChatFunction = effect$1.Schema.Struct({
2197
+ name: effect$1.Schema.String,
2198
+ description: effect$1.Schema.String,
2199
+ parameters: JsonObject
2200
+ });
2201
+ var OpenAIChatTool = effect$1.Schema.Struct({
2202
+ type: effect$1.Schema.tag("function"),
2203
+ function: OpenAIChatFunction
2204
+ });
2205
+ var OpenAIChatAssistantToolCall = effect$1.Schema.Struct({
2206
+ id: effect$1.Schema.String,
2207
+ type: effect$1.Schema.tag("function"),
2208
+ function: effect$1.Schema.Struct({
2209
+ name: effect$1.Schema.String,
2210
+ arguments: effect$1.Schema.String
2211
+ })
2212
+ });
2213
+ var OpenAIChatUserContentText = effect$1.Schema.Struct({
2214
+ type: effect$1.Schema.Literal("text"),
2215
+ text: effect$1.Schema.String
2216
+ });
2217
+ var OpenAIChatUserContentImageUrl = effect$1.Schema.Struct({
2218
+ type: effect$1.Schema.Literal("image_url"),
2219
+ image_url: effect$1.Schema.Struct({ url: effect$1.Schema.String })
2220
+ });
2221
+ var OpenAIChatUserContentPart = effect$1.Schema.Union([OpenAIChatUserContentText, OpenAIChatUserContentImageUrl]).pipe(
2222
+ effect$1.Schema.toTaggedUnion("type")
2223
+ );
2224
+ var OpenAIChatUserContent = effect$1.Schema.Union([effect$1.Schema.String, effect$1.Schema.Array(OpenAIChatUserContentPart)]);
2225
+ var OpenAIChatMessage = effect$1.Schema.Union([
2226
+ effect$1.Schema.Struct({ role: effect$1.Schema.Literal("system"), content: effect$1.Schema.String }),
2227
+ effect$1.Schema.Struct({ role: effect$1.Schema.Literal("user"), content: OpenAIChatUserContent }),
2228
+ effect$1.Schema.Struct({
2229
+ role: effect$1.Schema.Literal("assistant"),
2230
+ content: effect$1.Schema.NullOr(effect$1.Schema.String),
2231
+ tool_calls: optionalArray(OpenAIChatAssistantToolCall),
2232
+ reasoning_content: effect$1.Schema.optional(effect$1.Schema.String)
2233
+ }),
2234
+ effect$1.Schema.Struct({ role: effect$1.Schema.Literal("tool"), tool_call_id: effect$1.Schema.String, content: effect$1.Schema.String })
2235
+ ]).pipe(effect$1.Schema.toTaggedUnion("role"));
2236
+ var OpenAIChatToolChoice = effect$1.Schema.Union([
2237
+ effect$1.Schema.Literals(["auto", "none", "required"]),
2238
+ effect$1.Schema.Struct({
2239
+ type: effect$1.Schema.tag("function"),
2240
+ function: effect$1.Schema.Struct({ name: effect$1.Schema.String })
2241
+ })
2242
+ ]);
2243
+ var bodyFields = {
2244
+ model: effect$1.Schema.String,
2245
+ messages: effect$1.Schema.Array(OpenAIChatMessage),
2246
+ tools: optionalArray(OpenAIChatTool),
2247
+ tool_choice: effect$1.Schema.optional(OpenAIChatToolChoice),
2248
+ stream: effect$1.Schema.Literal(true),
2249
+ stream_options: effect$1.Schema.optional(effect$1.Schema.Struct({ include_usage: effect$1.Schema.Boolean })),
2250
+ store: effect$1.Schema.optional(effect$1.Schema.Boolean),
2251
+ reasoning_effort: effect$1.Schema.optional(openai_options_exports.OpenAIReasoningEffort),
2252
+ max_tokens: effect$1.Schema.optional(effect$1.Schema.Number),
2253
+ temperature: effect$1.Schema.optional(effect$1.Schema.Number),
2254
+ top_p: effect$1.Schema.optional(effect$1.Schema.Number),
2255
+ frequency_penalty: effect$1.Schema.optional(effect$1.Schema.Number),
2256
+ presence_penalty: effect$1.Schema.optional(effect$1.Schema.Number),
2257
+ seed: effect$1.Schema.optional(effect$1.Schema.Number),
2258
+ stop: optionalArray(effect$1.Schema.String)
2259
+ };
2260
+ var OpenAIChatBody = effect$1.Schema.Struct(bodyFields);
2261
+ var OpenAIChatUsage = effect$1.Schema.Struct({
2262
+ prompt_tokens: effect$1.Schema.optional(effect$1.Schema.Number),
2263
+ completion_tokens: effect$1.Schema.optional(effect$1.Schema.Number),
2264
+ total_tokens: effect$1.Schema.optional(effect$1.Schema.Number),
2265
+ prompt_tokens_details: optionalNull(
2266
+ effect$1.Schema.Struct({
2267
+ cached_tokens: effect$1.Schema.optional(effect$1.Schema.Number)
2268
+ })
2269
+ ),
2270
+ completion_tokens_details: optionalNull(
2271
+ effect$1.Schema.Struct({
2272
+ reasoning_tokens: effect$1.Schema.optional(effect$1.Schema.Number)
2273
+ })
2274
+ )
2275
+ });
2276
+ var OpenAIChatToolCallDeltaFunction = effect$1.Schema.Struct({
2277
+ name: optionalNull(effect$1.Schema.String),
2278
+ arguments: optionalNull(effect$1.Schema.String)
2279
+ });
2280
+ var OpenAIChatToolCallDelta = effect$1.Schema.Struct({
2281
+ index: effect$1.Schema.Number,
2282
+ id: optionalNull(effect$1.Schema.String),
2283
+ function: optionalNull(OpenAIChatToolCallDeltaFunction)
2284
+ });
2285
+ var OpenAIChatDelta = effect$1.Schema.Struct({
2286
+ content: optionalNull(effect$1.Schema.String),
2287
+ tool_calls: optionalNull(effect$1.Schema.Array(OpenAIChatToolCallDelta))
2288
+ });
2289
+ var OpenAIChatChoice = effect$1.Schema.Struct({
2290
+ delta: optionalNull(OpenAIChatDelta),
2291
+ finish_reason: optionalNull(effect$1.Schema.String)
2292
+ });
2293
+ var OpenAIChatEvent = effect$1.Schema.Struct({
2294
+ choices: effect$1.Schema.Array(OpenAIChatChoice),
2295
+ usage: optionalNull(OpenAIChatUsage)
2296
+ });
2297
+ var invalid = shared_exports.invalidRequest;
2298
+ var lowerTool = (tool2) => ({
2299
+ type: "function",
2300
+ function: {
2301
+ name: tool2.name,
2302
+ description: tool2.description,
2303
+ parameters: tool2.inputSchema
2304
+ }
2305
+ });
2306
+ var lowerToolChoice = (toolChoice2) => shared_exports.matchToolChoice("OpenAI Chat", toolChoice2, {
2307
+ auto: () => "auto",
2308
+ none: () => "none",
2309
+ required: () => "required",
2310
+ tool: (name) => ({ type: "function", function: { name } })
2311
+ });
2312
+ var lowerToolCall = (part) => ({
2313
+ id: part.id,
2314
+ type: "function",
2315
+ function: {
2316
+ name: part.name,
2317
+ arguments: shared_exports.encodeJson(part.input)
2318
+ }
2319
+ });
2320
+ var openAICompatibleReasoningContent = (native) => isRecord3(native) && typeof native.reasoning_content === "string" ? native.reasoning_content : void 0;
2321
+ var mediaToImageUrl = (part) => {
2322
+ const data = part.data;
2323
+ if (typeof data === "string") {
2324
+ if (data.startsWith("http://") || data.startsWith("https://") || data.startsWith("data:") || data.startsWith("file://"))
2325
+ return data;
2326
+ return `data:${part.mediaType};base64,${data}`;
2327
+ }
2328
+ return `data:${part.mediaType};base64,${shared_exports.mediaBytes(part)}`;
2329
+ };
2330
+ var lowerUserMessage = effect$1.Effect.fn("OpenAIChat.lowerUserMessage")(function* (message2) {
2331
+ const parts = [];
2332
+ let hasMedia = false;
2333
+ const textParts = [];
2334
+ for (const part of message2.content) {
2335
+ if (!shared_exports.supportsContent(part, ["text", "media"]))
2336
+ return yield* shared_exports.unsupportedContent("OpenAI Chat", "user", ["text", "media"]);
2337
+ if (part.type === "text") {
2338
+ textParts.push(part);
2339
+ parts.push({ type: "text", text: part.text });
2340
+ continue;
2341
+ }
2342
+ if (!part.mediaType.startsWith("image/"))
2343
+ return yield* shared_exports.invalidRequest(
2344
+ `OpenAI Chat user messages only support image/* media (received ${part.mediaType})`
2345
+ );
2346
+ hasMedia = true;
2347
+ parts.push({ type: "image_url", image_url: { url: mediaToImageUrl(part) } });
2348
+ }
2349
+ if (!hasMedia) return { role: "user", content: shared_exports.joinText(textParts) };
2350
+ return { role: "user", content: parts };
2351
+ });
2352
+ var lowerAssistantMessage = effect$1.Effect.fn("OpenAIChat.lowerAssistantMessage")(function* (message2) {
2353
+ const content = [];
2354
+ const toolCalls = [];
2355
+ for (const part of message2.content) {
2356
+ if (!shared_exports.supportsContent(part, ["text", "tool-call"]))
2357
+ return yield* shared_exports.unsupportedContent("OpenAI Chat", "assistant", ["text", "tool-call"]);
2358
+ if (part.type === "text") {
2359
+ content.push(part);
2360
+ continue;
2361
+ }
2362
+ if (part.type === "tool-call") {
2363
+ toolCalls.push(lowerToolCall(part));
2364
+ continue;
2365
+ }
2366
+ }
2367
+ return {
2368
+ role: "assistant",
2369
+ content: content.length === 0 ? null : shared_exports.joinText(content),
2370
+ tool_calls: toolCalls.length === 0 ? void 0 : toolCalls,
2371
+ reasoning_content: openAICompatibleReasoningContent(message2.native?.openaiCompatible)
2372
+ };
2373
+ });
2374
+ var lowerToolMessages = effect$1.Effect.fn("OpenAIChat.lowerToolMessages")(function* (message2) {
2375
+ const messages = [];
2376
+ for (const part of message2.content) {
2377
+ if (!shared_exports.supportsContent(part, ["tool-result"]))
2378
+ return yield* shared_exports.unsupportedContent("OpenAI Chat", "tool", ["tool-result"]);
2379
+ messages.push({ role: "tool", tool_call_id: part.id, content: shared_exports.toolResultText(part) });
2380
+ }
2381
+ return messages;
2382
+ });
2383
+ var lowerMessage = effect$1.Effect.fn("OpenAIChat.lowerMessage")(function* (message2) {
2384
+ if (message2.role === "user") return [yield* lowerUserMessage(message2)];
2385
+ if (message2.role === "assistant") return [yield* lowerAssistantMessage(message2)];
2386
+ return yield* lowerToolMessages(message2);
2387
+ });
2388
+ var lowerMessages = effect$1.Effect.fn("OpenAIChat.lowerMessages")(function* (request2) {
2389
+ const system2 = request2.system.length === 0 ? [] : [{ role: "system", content: shared_exports.joinText(request2.system) }];
2390
+ return [...system2, ...effect$1.Array.flatten(yield* effect$1.Effect.forEach(request2.messages, lowerMessage))];
2391
+ });
2392
+ var lowerOptions = effect$1.Effect.fn("OpenAIChat.lowerOptions")(function* (request2) {
2393
+ const store2 = openai_options_exports.store(request2);
2394
+ const reasoningEffort2 = openai_options_exports.reasoningEffort(request2);
2395
+ if (reasoningEffort2 && !openai_options_exports.isReasoningEffort(reasoningEffort2))
2396
+ return yield* invalid(`OpenAI Chat does not support reasoning effort ${reasoningEffort2}`);
2397
+ return {
2398
+ ...store2 !== void 0 ? { store: store2 } : {},
2399
+ ...reasoningEffort2 ? { reasoning_effort: reasoningEffort2 } : {}
2400
+ };
2401
+ });
2402
+ var fromRequest = effect$1.Effect.fn("OpenAIChat.fromRequest")(function* (request2) {
2403
+ const generation2 = request2.generation;
2404
+ return {
2405
+ model: request2.model.id,
2406
+ messages: yield* lowerMessages(request2),
2407
+ tools: request2.tools.length === 0 ? void 0 : request2.tools.map(lowerTool),
2408
+ tool_choice: request2.toolChoice ? yield* lowerToolChoice(request2.toolChoice) : void 0,
2409
+ stream: true,
2410
+ stream_options: { include_usage: true },
2411
+ max_tokens: generation2?.maxTokens,
2412
+ temperature: generation2?.temperature,
2413
+ top_p: generation2?.topP,
2414
+ frequency_penalty: generation2?.frequencyPenalty,
2415
+ presence_penalty: generation2?.presencePenalty,
2416
+ seed: generation2?.seed,
2417
+ stop: generation2?.stop,
2418
+ ...yield* lowerOptions(request2)
2419
+ };
2420
+ });
2421
+ var mapFinishReason = (reason) => {
2422
+ if (reason === "stop") return "stop";
2423
+ if (reason === "length") return "length";
2424
+ if (reason === "content_filter") return "content-filter";
2425
+ if (reason === "function_call" || reason === "tool_calls") return "tool-calls";
2426
+ return "unknown";
2427
+ };
2428
+ var mapUsage = (usage) => {
2429
+ if (!usage) return void 0;
2430
+ const cached = usage.prompt_tokens_details?.cached_tokens;
2431
+ const reasoning = usage.completion_tokens_details?.reasoning_tokens;
2432
+ const nonCached = shared_exports.subtractTokens(usage.prompt_tokens, cached);
2433
+ return new Usage({
2434
+ inputTokens: usage.prompt_tokens,
2435
+ outputTokens: usage.completion_tokens,
2436
+ nonCachedInputTokens: nonCached,
2437
+ cacheReadInputTokens: cached,
2438
+ reasoningTokens: reasoning,
2439
+ totalTokens: shared_exports.totalTokens(usage.prompt_tokens, usage.completion_tokens, usage.total_tokens),
2440
+ providerMetadata: { openai: usage }
2441
+ });
2442
+ };
2443
+ var normaliseTextDelta = (prev, incoming) => {
2444
+ if (!incoming) return { emit: "", textAcc: prev };
2445
+ if (incoming === prev) return { emit: "", textAcc: prev };
2446
+ if (prev.length > 0 && incoming.startsWith(prev)) {
2447
+ return { emit: incoming.slice(prev.length), textAcc: incoming };
2448
+ }
2449
+ if (prev.length > 0 && prev.startsWith(incoming)) {
2450
+ return { emit: "", textAcc: prev };
2451
+ }
2452
+ return { emit: incoming, textAcc: prev + incoming };
2453
+ };
2454
+ var step = (state, event) => effect$1.Effect.gen(function* () {
2455
+ const events = [];
2456
+ const usage = mapUsage(event.usage) ?? state.usage;
2457
+ const choice = event.choices[0];
2458
+ const finishReason = choice?.finish_reason ? mapFinishReason(choice.finish_reason) : state.finishReason;
2459
+ const delta = choice?.delta;
2460
+ const toolDeltas = delta?.tool_calls ?? [];
2461
+ let tools = state.tools;
2462
+ let textAcc = state.textAcc;
2463
+ if (delta?.content) {
2464
+ const normalised = normaliseTextDelta(textAcc, delta.content);
2465
+ textAcc = normalised.textAcc;
2466
+ if (normalised.emit) {
2467
+ events.push(LLMEvent.textDelta({ id: "text-0", text: normalised.emit }));
2468
+ }
2469
+ }
2470
+ for (const tool2 of toolDeltas) {
2471
+ const result = tool_stream_exports.appendOrStart(
2472
+ ADAPTER,
2473
+ tools,
2474
+ tool2.index,
2475
+ { id: tool2.id ?? void 0, name: tool2.function?.name ?? void 0, text: tool2.function?.arguments ?? "" },
2476
+ "OpenAI Chat tool call delta is missing id or name"
2477
+ );
2478
+ if (tool_stream_exports.isError(result)) return yield* result;
2479
+ tools = result.tools;
2480
+ if (result.event) events.push(result.event);
2481
+ }
2482
+ const finished = finishReason !== void 0 && state.finishReason === void 0 && Object.keys(tools).length > 0 ? yield* tool_stream_exports.finishAll(ADAPTER, tools) : void 0;
2483
+ return [
2484
+ {
2485
+ tools: finished?.tools ?? tools,
2486
+ toolCallEvents: finished?.events ?? state.toolCallEvents,
2487
+ usage,
2488
+ finishReason,
2489
+ textAcc
2490
+ },
2491
+ events
2492
+ ];
2493
+ });
2494
+ var finishEvents = (state) => {
2495
+ const hasToolCalls = state.toolCallEvents.length > 0;
2496
+ const reason = state.finishReason === "stop" && hasToolCalls ? "tool-calls" : state.finishReason;
2497
+ return [...state.toolCallEvents, ...reason ? [LLMEvent.requestFinish({ reason, usage: state.usage })] : []];
2498
+ };
2499
+ var protocol = protocol_exports.make({
2500
+ id: ADAPTER,
2501
+ body: {
2502
+ schema: OpenAIChatBody,
2503
+ from: fromRequest
2504
+ },
2505
+ stream: {
2506
+ event: protocol_exports.jsonEvent(OpenAIChatEvent),
2507
+ initial: () => ({
2508
+ tools: tool_stream_exports.empty(),
2509
+ toolCallEvents: [],
2510
+ textAcc: ""
2511
+ }),
2512
+ step,
2513
+ onHalt: finishEvents
2514
+ }
2515
+ });
2516
+ var encodeBody = effect$1.Schema.encodeSync(effect$1.Schema.fromJsonString(OpenAIChatBody));
2517
+ var httpTransport = http_exports.httpJson({
2518
+ endpoint: endpoint_exports.path(PATH),
2519
+ auth: auth_exports.bearer(),
2520
+ framing: framing_exports.sse,
2521
+ encodeBody
2522
+ });
2523
+ var route = Route.make({
2524
+ id: ADAPTER,
2525
+ provider: "openai",
2526
+ protocol,
2527
+ transport: httpTransport,
2528
+ defaults: {
2529
+ baseURL: DEFAULT_BASE_URL
2530
+ }
2531
+ });
2532
+ var model2 = route.model;
2533
+
2534
+ // src/protocols/openai-compatible-chat.ts
2535
+ var openai_compatible_chat_exports = {};
2536
+ __export(openai_compatible_chat_exports, {
2537
+ OpenAICompatibleChat: () => openai_compatible_chat_exports,
2538
+ model: () => model3,
2539
+ route: () => route2
2540
+ });
2541
+ var ADAPTER2 = "openai-compatible-chat";
2542
+ var route2 = Route.make({
2543
+ id: ADAPTER2,
2544
+ protocol,
2545
+ endpoint: endpoint_exports.path("/chat/completions"),
2546
+ framing: framing_exports.sse
2547
+ });
2548
+ var model3 = Route.model(route2);
2549
+
2550
+ // src/provider.ts
2551
+ var provider_exports = {};
2552
+ __export(provider_exports, {
2553
+ Provider: () => provider_exports,
2554
+ make: () => make4
2555
+ });
2556
+ var make4 = (definition) => definition;
2557
+
2558
+ // src/providers/openai.ts
2559
+ var openai_exports = {};
2560
+ __export(openai_exports, {
2561
+ OpenAI: () => openai_exports,
2562
+ apis: () => apis,
2563
+ chat: () => chat,
2564
+ id: () => id,
2565
+ model: () => model4,
2566
+ provider: () => provider,
2567
+ routes: () => routes
2568
+ });
2569
+
2570
+ // src/providers/openai-options.ts
2571
+ var openai_options_exports2 = {};
2572
+ __export(openai_options_exports2, {
2573
+ OpenAIProviderOptions: () => openai_options_exports2,
2574
+ gpt5DefaultOptions: () => gpt5DefaultOptions,
2575
+ openAIDefaultOptions: () => openAIDefaultOptions,
2576
+ withOpenAIOptions: () => withOpenAIOptions
2577
+ });
2578
+ var definedEntries = (input) => Object.entries(input).filter((entry) => entry[1] !== void 0);
2579
+ var openAIProviderOptions = (options2) => {
2580
+ const openai = Object.fromEntries(
2581
+ definedEntries({
2582
+ store: options2?.store,
2583
+ promptCacheKey: options2?.promptCacheKey,
2584
+ reasoningEffort: options2?.reasoningEffort,
2585
+ reasoningSummary: options2?.reasoningSummary,
2586
+ includeEncryptedReasoning: options2?.includeEncryptedReasoning,
2587
+ textVerbosity: options2?.textVerbosity
2588
+ })
2589
+ );
2590
+ if (Object.keys(openai).length === 0) return void 0;
2591
+ return { openai };
2592
+ };
2593
+ var gpt5DefaultOptions = (modelID, options2 = {}) => {
2594
+ const id3 = modelID.toLowerCase();
2595
+ if (!id3.includes("gpt-5") || id3.includes("gpt-5-chat") || id3.includes("gpt-5-pro")) return void 0;
2596
+ return openAIProviderOptions({
2597
+ reasoningEffort: "medium",
2598
+ reasoningSummary: "auto",
2599
+ textVerbosity: options2.textVerbosity === true && id3.includes("gpt-5.") && !id3.includes("codex") && !id3.includes("-chat") ? "low" : void 0
2600
+ });
2601
+ };
2602
+ var openAIDefaultOptions = (modelID, options2 = {}) => mergeProviderOptions(openAIProviderOptions({ store: false }), gpt5DefaultOptions(modelID, options2));
2603
+ var withOpenAIOptions = (modelID, options2, defaults = {}) => {
2604
+ return {
2605
+ ...options2,
2606
+ id: modelID,
2607
+ providerOptions: mergeProviderOptions(openAIDefaultOptions(modelID, defaults), options2.providerOptions)
2608
+ };
2609
+ };
2610
+
2611
+ // src/providers/openai.ts
2612
+ var id = ProviderID.make("openai");
2613
+ var routes = [route];
2614
+ var auth2 = (options2) => auth_options_exports.bearer(options2, "OPENAI_API_KEY");
2615
+ var chat = (id3, options2 = {}) => {
2616
+ const { apiKey: _, ...rest } = options2;
2617
+ return model2(withOpenAIOptions(id3, { ...rest, auth: auth2(options2) }));
2618
+ };
2619
+ var provider = provider_exports.make({
2620
+ id,
2621
+ model: chat,
2622
+ apis: { chat }
2623
+ });
2624
+ var model4 = provider.model;
2625
+ var apis = provider.apis;
2626
+
2627
+ // src/providers/openai-compatible.ts
2628
+ var openai_compatible_exports = {};
2629
+ __export(openai_compatible_exports, {
2630
+ OpenAICompatible: () => openai_compatible_exports,
2631
+ baseten: () => baseten,
2632
+ cerebras: () => cerebras,
2633
+ deepinfra: () => deepinfra,
2634
+ deepseek: () => deepseek,
2635
+ fireworks: () => fireworks,
2636
+ groq: () => groq,
2637
+ id: () => id2,
2638
+ lmstudio: () => lmstudio,
2639
+ model: () => model5,
2640
+ ollama: () => ollama,
2641
+ openrouter: () => openrouter,
2642
+ profileModel: () => profileModel,
2643
+ provider: () => provider2,
2644
+ routes: () => routes2,
2645
+ togetherai: () => togetherai,
2646
+ xai: () => xai
2647
+ });
2648
+
2649
+ // src/providers/openai-compatible-profile.ts
2650
+ var profiles = {
2651
+ baseten: { provider: "baseten", baseURL: "https://inference.baseten.co/v1" },
2652
+ cerebras: { provider: "cerebras", baseURL: "https://api.cerebras.ai/v1" },
2653
+ deepinfra: { provider: "deepinfra", baseURL: "https://api.deepinfra.com/v1/openai" },
2654
+ deepseek: { provider: "deepseek", baseURL: "https://api.deepseek.com/v1" },
2655
+ fireworks: { provider: "fireworks", baseURL: "https://api.fireworks.ai/inference/v1" },
2656
+ groq: { provider: "groq", baseURL: "https://api.groq.com/openai/v1" },
2657
+ openrouter: { provider: "openrouter", baseURL: "https://openrouter.ai/api/v1" },
2658
+ togetherai: { provider: "togetherai", baseURL: "https://api.together.xyz/v1" },
2659
+ xai: { provider: "xai", baseURL: "https://api.x.ai/v1" },
2660
+ ollama: { provider: "ollama", baseURL: "http://localhost:11434/v1" },
2661
+ lmstudio: { provider: "lmstudio", baseURL: "http://localhost:1234/v1" }
2662
+ };
2663
+ Object.fromEntries(
2664
+ Object.values(profiles).map((profile) => [profile.provider, profile])
2665
+ );
2666
+
2667
+ // src/providers/openai-compatible.ts
2668
+ var id2 = ProviderID.make("openai-compatible");
2669
+ var routes2 = [route2];
2670
+ var model5 = (id3, options2) => {
2671
+ return model3({
2672
+ ...options2,
2673
+ id: id3,
2674
+ provider: ProviderID.make(options2.provider)
2675
+ });
2676
+ };
2677
+ var profileModel = (profile, id3, options2 = {}) => model3({
2678
+ ...options2,
2679
+ id: id3,
2680
+ provider: profile.provider,
2681
+ baseURL: options2.baseURL ?? profile.baseURL
2682
+ });
2683
+ var define = (profile) => provider_exports.make({
2684
+ id: ProviderID.make(profile.provider),
2685
+ model: (id3, options2 = {}) => profileModel(profile, id3, options2)
2686
+ });
2687
+ var provider2 = provider_exports.make({
2688
+ id: id2,
2689
+ model: (id3, options2) => model5(id3, { ...options2, provider: options2.provider ?? "openai-compatible" })
2690
+ });
2691
+ var baseten = define(profiles.baseten);
2692
+ var cerebras = define(profiles.cerebras);
2693
+ var deepinfra = define(profiles.deepinfra);
2694
+ var deepseek = define(profiles.deepseek);
2695
+ var fireworks = define(profiles.fireworks);
2696
+ var groq = define(profiles.groq);
2697
+ var openrouter = define(profiles.openrouter);
2698
+ var togetherai = define(profiles.togetherai);
2699
+ var xai = define(profiles.xai);
2700
+ var ollama = define(profiles.ollama);
2701
+ var lmstudio = define(profiles.lmstudio);
2702
+
2703
+ // src/llm.ts
2704
+ var llm_exports = {};
2705
+ __export(llm_exports, {
2706
+ GenerateObjectResponse: () => GenerateObjectResponse,
2707
+ LLM: () => llm_exports,
2708
+ assistant: () => assistant,
2709
+ generate: () => generate2,
2710
+ generateObject: () => generateObject,
2711
+ generation: () => generation,
2712
+ hasToolCall: () => hasToolCall,
2713
+ limits: () => limits,
2714
+ message: () => message,
2715
+ model: () => model6,
2716
+ request: () => request,
2717
+ requestInput: () => requestInput,
2718
+ stepCountIs: () => stepCountIs2,
2719
+ stopWhenAny: () => stopWhenAny,
2720
+ stream: () => stream3,
2721
+ system: () => system,
2722
+ text: () => text,
2723
+ toolCall: () => toolCall2,
2724
+ toolChoice: () => toolChoice,
2725
+ toolChoiceName: () => toolChoiceName,
2726
+ toolDefinition: () => toolDefinition,
2727
+ toolMessage: () => toolMessage,
2728
+ toolResult: () => toolResult,
2729
+ updateRequest: () => updateRequest,
2730
+ user: () => user
2731
+ });
2732
+ var limits = modelLimits;
2733
+ var text = exports.Message.text;
2734
+ var system = SystemPart.make;
2735
+ var message = exports.Message.make;
2736
+ var user = exports.Message.user;
2737
+ var assistant = exports.Message.assistant;
2738
+ var model6 = modelRef;
2739
+ var toolDefinition = exports.ToolDefinition.make;
2740
+ var toolCall2 = ToolCallPart.make;
2741
+ var toolResult = ToolResultPart.make;
2742
+ var toolMessage = exports.Message.tool;
2743
+ var toolChoiceName = exports.ToolChoice.named;
2744
+ var toolChoice = exports.ToolChoice.make;
2745
+ var generation = exports.GenerationOptions.make;
2746
+ var generate2 = LLMClient.generate;
2747
+ var stream3 = LLMClient.stream;
2748
+ var stepCountIs2 = LLMClient.stepCountIs;
2749
+ var requestInput = (input) => ({
2750
+ ...exports.LLMRequest.input(input)
2751
+ });
2752
+ var request = (input) => {
2753
+ const {
2754
+ system: requestSystem,
2755
+ prompt,
2756
+ messages,
2757
+ tools,
2758
+ toolChoice: requestToolChoice,
2759
+ generation: requestGeneration,
2760
+ providerOptions: requestProviderOptions,
2761
+ http: requestHttp,
2762
+ ...rest
2763
+ } = input;
2764
+ return new exports.LLMRequest({
2765
+ ...rest,
2766
+ system: SystemPart.content(requestSystem),
2767
+ messages: [...messages?.map(message) ?? [], ...prompt === void 0 ? [] : [user(prompt)]],
2768
+ tools: tools?.map(toolDefinition) ?? [],
2769
+ toolChoice: requestToolChoice ? toolChoice(requestToolChoice) : void 0,
2770
+ generation: requestGeneration === void 0 ? void 0 : generation(requestGeneration),
2771
+ providerOptions: requestProviderOptions,
2772
+ http: requestHttp === void 0 ? void 0 : exports.HttpOptions.make(requestHttp)
2773
+ });
2774
+ };
2775
+ var updateRequest = (input, patch) => request({ ...requestInput(input), ...patch });
2776
+ var GENERATE_OBJECT_TOOL_NAME = "generate_object";
2777
+ var GENERATE_OBJECT_TOOL_DESCRIPTION = "Return the structured result by calling this tool.";
2778
+ var GenerateObjectResponse = class {
2779
+ constructor(object, response) {
2780
+ this.object = object;
2781
+ this.response = response;
2782
+ }
2783
+ get events() {
2784
+ return this.response.events;
2785
+ }
2786
+ get usage() {
2787
+ return this.response.usage;
2788
+ }
2789
+ };
2790
+ var runGenerateObject = effect$1.Effect.fn("LLM.generateObject")(function* (options2, tool2) {
2791
+ const baseRequest = request(options2);
2792
+ const generateRequest = exports.LLMRequest.update(baseRequest, {
2793
+ toolChoice: exports.ToolChoice.named(GENERATE_OBJECT_TOOL_NAME)
2794
+ });
2795
+ const response = yield* LLMClient.generate({
2796
+ request: generateRequest,
2797
+ tools: { [GENERATE_OBJECT_TOOL_NAME]: tool2 },
2798
+ toolExecution: "none"
2799
+ });
2800
+ const call = response.toolCalls.find(
2801
+ (event) => LLMEvent.is.toolCall(event) && event.name === GENERATE_OBJECT_TOOL_NAME
2802
+ );
2803
+ if (!call || !LLMEvent.is.toolCall(call))
2804
+ return yield* new LLMError({
2805
+ module: "LLM",
2806
+ method: "generateObject",
2807
+ reason: new InvalidProviderOutputReason({
2808
+ message: `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool`
2809
+ })
2810
+ });
2811
+ const object = yield* tool2._decode(call.input).pipe(
2812
+ effect$1.Effect.mapError(
2813
+ (error) => new LLMError({
2814
+ module: "LLM",
2815
+ method: "generateObject",
2816
+ reason: new InvalidProviderOutputReason({
2817
+ message: `generateObject: tool input failed schema decode: ${error.message}`
2818
+ })
2819
+ })
2820
+ )
2821
+ );
2822
+ return new GenerateObjectResponse(object, response);
2823
+ });
2824
+ function generateObject(options2) {
2825
+ if ("schema" in options2) {
2826
+ const { schema, ...rest2 } = options2;
2827
+ return runGenerateObject(
2828
+ rest2,
2829
+ make({
2830
+ description: GENERATE_OBJECT_TOOL_DESCRIPTION,
2831
+ parameters: schema,
2832
+ success: effect$1.Schema.Unknown,
2833
+ execute: () => effect$1.Effect.void
2834
+ })
2835
+ );
2836
+ }
2837
+ const { jsonSchema, ...rest } = options2;
2838
+ return runGenerateObject(
2839
+ rest,
2840
+ make({
2841
+ description: GENERATE_OBJECT_TOOL_DESCRIPTION,
2842
+ jsonSchema,
2843
+ execute: () => effect$1.Effect.void
2844
+ })
2845
+ );
2846
+ }
2847
+
2848
+ // src/index.ts
2849
+ var VERSION = "0.0.1";
2850
+
2851
+ exports.Auth = auth_exports;
2852
+ exports.AuthOptions = auth_options_exports;
2853
+ exports.AuthenticationReason = AuthenticationReason;
2854
+ exports.CacheHint = CacheHint;
2855
+ exports.CachePolicy = CachePolicy;
2856
+ exports.CachePolicyObject = CachePolicyObject;
2857
+ exports.ContentBlockID = ContentBlockID;
2858
+ exports.ContentPart = ContentPart;
2859
+ exports.ContentPolicyReason = ContentPolicyReason;
2860
+ exports.ContextOverflowReason = ContextOverflowReason;
2861
+ exports.Endpoint = endpoint_exports;
2862
+ exports.FinishReason = FinishReason;
2863
+ exports.Framing = framing_exports;
2864
+ exports.HttpContext = HttpContext;
2865
+ exports.HttpRateLimitDetails = HttpRateLimitDetails;
2866
+ exports.HttpRequestDetails = HttpRequestDetails;
2867
+ exports.HttpResponseDetails = HttpResponseDetails;
2868
+ exports.HttpTransport = http_exports;
2869
+ exports.InvalidProviderOutputReason = InvalidProviderOutputReason;
2870
+ exports.InvalidRequestReason = InvalidRequestReason;
2871
+ exports.JsonSchema = JsonSchema;
2872
+ exports.LLM = llm_exports;
2873
+ exports.LLMClient = LLMClient;
2874
+ exports.LLMError = LLMError;
2875
+ exports.LLMErrorReason = LLMErrorReason;
2876
+ exports.LLMEvent = LLMEvent;
2877
+ exports.MediaPart = MediaPart;
2878
+ exports.MessageRole = MessageRole;
2879
+ exports.MissingCredentialError = MissingCredentialError;
2880
+ exports.ModelID = ModelID;
2881
+ exports.NoRouteReason = NoRouteReason;
2882
+ exports.OpenAI = openai_exports;
2883
+ exports.OpenAIChat = openai_chat_exports;
2884
+ exports.OpenAICompatible = openai_compatible_exports;
2885
+ exports.OpenAICompatibleChat = openai_compatible_chat_exports;
2886
+ exports.OpenAIProviderOptions = openai_options_exports2;
2887
+ exports.PreparedRequest = PreparedRequest;
2888
+ exports.Protocol = protocol_exports;
2889
+ exports.ProtocolID = ProtocolID;
2890
+ exports.Provider = provider_exports;
2891
+ exports.ProviderErrorEvent = ProviderErrorEvent;
2892
+ exports.ProviderID = ProviderID;
2893
+ exports.ProviderInternalReason = ProviderInternalReason;
2894
+ exports.ProviderMetadata = ProviderMetadata;
2895
+ exports.ProviderOptions = ProviderOptions;
2896
+ exports.ProviderShared = shared_exports;
2897
+ exports.QuotaExceededReason = QuotaExceededReason;
2898
+ exports.RateLimitReason = RateLimitReason;
2899
+ exports.ReasoningDelta = ReasoningDelta;
2900
+ exports.ReasoningEffort = ReasoningEffort;
2901
+ exports.ReasoningEfforts = ReasoningEfforts;
2902
+ exports.ReasoningEnd = ReasoningEnd;
2903
+ exports.ReasoningPart = ReasoningPart;
2904
+ exports.ReasoningStart = ReasoningStart;
2905
+ exports.RequestExecutor = executor_exports;
2906
+ exports.RequestFinish = RequestFinish;
2907
+ exports.RequestStart = RequestStart;
2908
+ exports.ResponseFormat = ResponseFormat;
2909
+ exports.ResponseID = ResponseID;
2910
+ exports.Route = Route;
2911
+ exports.RouteID = RouteID;
2912
+ exports.StepFinish = StepFinish;
2913
+ exports.StepStart = StepStart;
2914
+ exports.SystemPart = SystemPart;
2915
+ exports.TextDelta = TextDelta;
2916
+ exports.TextEnd = TextEnd;
2917
+ exports.TextPart = TextPart;
2918
+ exports.TextStart = TextStart;
2919
+ exports.TextVerbosity = TextVerbosity;
2920
+ exports.Tool = tool_exports;
2921
+ exports.ToolCall = ToolCall;
2922
+ exports.ToolCallID = ToolCallID;
2923
+ exports.ToolCallPart = ToolCallPart;
2924
+ exports.ToolError = ToolError;
2925
+ exports.ToolFailure = ToolFailure;
2926
+ exports.ToolInputDelta = ToolInputDelta;
2927
+ exports.ToolInputEnd = ToolInputEnd;
2928
+ exports.ToolInputStart = ToolInputStart;
2929
+ exports.ToolResult = ToolResult;
2930
+ exports.ToolResultPart = ToolResultPart;
2931
+ exports.ToolResultValue = ToolResultValue;
2932
+ exports.ToolRuntime = ToolRuntime;
2933
+ exports.TransportReason = TransportReason;
2934
+ exports.UnknownProviderReason = UnknownProviderReason;
2935
+ exports.Usage = Usage;
2936
+ exports.VERSION = VERSION;
2937
+ exports.extractOverflowNumbers = extractOverflowNumbers;
2938
+ exports.hasToolCall = hasToolCall;
2939
+ exports.isOverflowBody = isOverflowBody;
2940
+ exports.isOverflowMessage = isOverflowMessage;
2941
+ exports.isOverflowStatus = isOverflowStatus;
2942
+ exports.make = make;
2943
+ exports.mergeGenerationOptions = mergeGenerationOptions;
2944
+ exports.mergeHttpOptions = mergeHttpOptions;
2945
+ exports.mergeJsonRecords = mergeJsonRecords;
2946
+ exports.mergeProviderOptions = mergeProviderOptions;
2947
+ exports.modelLimits = modelLimits;
2948
+ exports.modelRef = modelRef;
2949
+ exports.openAICompatibleProfiles = profiles;
2950
+ exports.runtimeStream = stream;
2951
+ exports.stepCountIs = stepCountIs;
2952
+ exports.stopWhenAny = stopWhenAny;
2953
+ exports.toDefinitions = toDefinitions;
2954
+ exports.tool = tool;
2955
+ //# sourceMappingURL=index.cjs.map
2956
+ //# sourceMappingURL=index.cjs.map