@tinyweb_dev/agent-framework-llm 0.2.0 → 0.4.0

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