@tinyweb_dev/agent-framework-llm 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/dist/cache-policy.d.ts +3 -0
  2. package/dist/cache-policy.d.ts.map +1 -0
  3. package/dist/index.cjs +2956 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +23 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +2831 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/llm.cjs +1718 -0
  10. package/dist/llm.cjs.map +1 -0
  11. package/dist/llm.d.ts +284 -0
  12. package/dist/llm.d.ts.map +1 -0
  13. package/dist/llm.js +1692 -0
  14. package/dist/llm.js.map +1 -0
  15. package/dist/protocols/openai-chat.cjs +2443 -0
  16. package/dist/protocols/openai-chat.cjs.map +1 -0
  17. package/dist/protocols/openai-chat.d.ts +357 -0
  18. package/dist/protocols/openai-chat.d.ts.map +1 -0
  19. package/dist/protocols/openai-chat.js +2414 -0
  20. package/dist/protocols/openai-chat.js.map +1 -0
  21. package/dist/protocols/openai-compatible-chat.cjs +2443 -0
  22. package/dist/protocols/openai-compatible-chat.cjs.map +1 -0
  23. package/dist/protocols/openai-compatible-chat.d.ts +77 -0
  24. package/dist/protocols/openai-compatible-chat.d.ts.map +1 -0
  25. package/dist/protocols/openai-compatible-chat.js +2419 -0
  26. package/dist/protocols/openai-compatible-chat.js.map +1 -0
  27. package/dist/protocols/shared.cjs +904 -0
  28. package/dist/protocols/shared.cjs.map +1 -0
  29. package/dist/protocols/shared.d.ts +51 -0
  30. package/dist/protocols/shared.d.ts.map +1 -0
  31. package/dist/protocols/shared.js +857 -0
  32. package/dist/protocols/shared.js.map +1 -0
  33. package/dist/protocols/utils/openai-options.d.ts +15 -0
  34. package/dist/protocols/utils/openai-options.d.ts.map +1 -0
  35. package/dist/protocols/utils/tool-stream.d.ts +78 -0
  36. package/dist/protocols/utils/tool-stream.d.ts.map +1 -0
  37. package/dist/provider.cjs +20 -0
  38. package/dist/provider.cjs.map +1 -0
  39. package/dist/provider.d.ts +19 -0
  40. package/dist/provider.d.ts.map +1 -0
  41. package/dist/provider.js +17 -0
  42. package/dist/provider.js.map +1 -0
  43. package/{src/providers/openai-compatible-profile.ts → dist/providers/openai-compatible-profile.cjs} +12 -12
  44. package/dist/providers/openai-compatible-profile.cjs.map +1 -0
  45. package/dist/providers/openai-compatible-profile.d.ts +52 -0
  46. package/dist/providers/openai-compatible-profile.d.ts.map +1 -0
  47. package/dist/providers/openai-compatible-profile.js +21 -0
  48. package/dist/providers/openai-compatible-profile.js.map +1 -0
  49. package/dist/providers/openai-compatible.cjs +2533 -0
  50. package/dist/providers/openai-compatible.cjs.map +1 -0
  51. package/dist/providers/openai-compatible.d.ts +128 -0
  52. package/dist/providers/openai-compatible.d.ts.map +1 -0
  53. package/dist/providers/openai-compatible.js +2495 -0
  54. package/dist/providers/openai-compatible.js.map +1 -0
  55. package/dist/providers/openai-options.cjs +797 -0
  56. package/dist/providers/openai-options.cjs.map +1 -0
  57. package/dist/providers/openai-options.d.ts +29 -0
  58. package/dist/providers/openai-options.d.ts.map +1 -0
  59. package/dist/providers/openai-options.js +792 -0
  60. package/dist/providers/openai-options.js.map +1 -0
  61. package/dist/providers/openai.cjs +2517 -0
  62. package/dist/providers/openai.cjs.map +1 -0
  63. package/dist/providers/openai.d.ts +87 -0
  64. package/dist/providers/openai.d.ts.map +1 -0
  65. package/dist/providers/openai.js +2489 -0
  66. package/dist/providers/openai.js.map +1 -0
  67. package/dist/route/auth-options.cjs +855 -0
  68. package/dist/route/auth-options.cjs.map +1 -0
  69. package/dist/route/auth-options.d.ts +25 -0
  70. package/dist/route/auth-options.d.ts.map +1 -0
  71. package/dist/route/auth-options.js +852 -0
  72. package/dist/route/auth-options.js.map +1 -0
  73. package/dist/route/auth.cjs +855 -0
  74. package/dist/route/auth.cjs.map +1 -0
  75. package/dist/route/auth.d.ts +51 -0
  76. package/dist/route/auth.d.ts.map +1 -0
  77. package/dist/route/auth.js +836 -0
  78. package/dist/route/auth.js.map +1 -0
  79. package/dist/route/client.cjs +1844 -0
  80. package/dist/route/client.cjs.map +1 -0
  81. package/dist/route/client.d.ts +268 -0
  82. package/dist/route/client.d.ts.map +1 -0
  83. package/dist/route/client.js +1830 -0
  84. package/dist/route/client.js.map +1 -0
  85. package/dist/route/endpoint.cjs +756 -0
  86. package/dist/route/endpoint.cjs.map +1 -0
  87. package/dist/route/endpoint.d.ts +13 -0
  88. package/dist/route/endpoint.d.ts.map +1 -0
  89. package/dist/route/endpoint.js +752 -0
  90. package/dist/route/endpoint.js.map +1 -0
  91. package/dist/route/executor.cjs +1077 -0
  92. package/dist/route/executor.cjs.map +1 -0
  93. package/dist/route/executor.d.ts +13 -0
  94. package/dist/route/executor.d.ts.map +1 -0
  95. package/dist/route/executor.js +1072 -0
  96. package/dist/route/executor.js.map +1 -0
  97. package/dist/route/framing.cjs +773 -0
  98. package/dist/route/framing.cjs.map +1 -0
  99. package/dist/route/framing.d.ts +9 -0
  100. package/dist/route/framing.d.ts.map +1 -0
  101. package/dist/route/framing.js +750 -0
  102. package/dist/route/framing.js.map +1 -0
  103. package/dist/route/overflow-detect.d.ts +18 -0
  104. package/dist/route/overflow-detect.d.ts.map +1 -0
  105. package/dist/route/protocol.cjs +25 -0
  106. package/dist/route/protocol.cjs.map +1 -0
  107. package/dist/route/protocol.d.ts +40 -0
  108. package/dist/route/protocol.d.ts.map +1 -0
  109. package/dist/route/protocol.js +21 -0
  110. package/dist/route/protocol.js.map +1 -0
  111. package/dist/route/transport/http.d.ts +48 -0
  112. package/dist/route/transport/http.d.ts.map +1 -0
  113. package/dist/route/transport/index.cjs +969 -0
  114. package/dist/route/transport/index.cjs.map +1 -0
  115. package/dist/route/transport/index.d.ts +13 -0
  116. package/dist/route/transport/index.d.ts.map +1 -0
  117. package/dist/route/transport/index.js +967 -0
  118. package/dist/route/transport/index.js.map +1 -0
  119. package/dist/schema/errors.d.ts +181 -0
  120. package/dist/schema/errors.d.ts.map +1 -0
  121. package/dist/schema/events.d.ts +3224 -0
  122. package/dist/schema/events.d.ts.map +1 -0
  123. package/dist/schema/ids.d.ts +31 -0
  124. package/dist/schema/ids.d.ts.map +1 -0
  125. package/dist/schema/index.cjs +847 -0
  126. package/dist/schema/index.cjs.map +1 -0
  127. package/dist/schema/index.d.ts +6 -0
  128. package/dist/schema/index.d.ts.map +1 -0
  129. package/dist/schema/index.js +777 -0
  130. package/dist/schema/index.js.map +1 -0
  131. package/dist/schema/messages.d.ts +292 -0
  132. package/dist/schema/messages.d.ts.map +1 -0
  133. package/dist/schema/options.d.ts +123 -0
  134. package/dist/schema/options.d.ts.map +1 -0
  135. package/dist/tool-runtime.cjs +907 -0
  136. package/dist/tool-runtime.cjs.map +1 -0
  137. package/dist/tool-runtime.d.ts +50 -0
  138. package/dist/tool-runtime.d.ts.map +1 -0
  139. package/dist/tool-runtime.js +901 -0
  140. package/dist/tool-runtime.js.map +1 -0
  141. package/dist/tool.cjs +802 -0
  142. package/dist/tool.cjs.map +1 -0
  143. package/dist/tool.d.ts +111 -0
  144. package/dist/tool.d.ts.map +1 -0
  145. package/dist/tool.js +796 -0
  146. package/dist/tool.js.map +1 -0
  147. package/package.json +112 -29
  148. package/src/cache-policy.ts +0 -92
  149. package/src/index.ts +0 -62
  150. package/src/llm.ts +0 -210
  151. package/src/protocols/openai-chat.ts +0 -422
  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 -333
  172. package/src/schema/ids.ts +0 -44
  173. package/src/schema/index.ts +0 -6
  174. package/src/schema/messages.ts +0 -240
  175. package/src/schema/options.ts +0 -231
  176. package/src/tool-runtime.ts +0 -263
  177. package/src/tool.ts +0 -212
@@ -0,0 +1,1844 @@
1
+ 'use strict';
2
+
3
+ var effect$1 = require('effect');
4
+ var http = require('effect/unstable/http');
5
+ require('buffer');
6
+ require('effect/unstable/encoding/Sse');
7
+
8
+ var __defProp = Object.defineProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+
14
+ // src/route/executor.ts
15
+ var executor_exports = {};
16
+ __export(executor_exports, {
17
+ RequestExecutor: () => executor_exports,
18
+ Service: () => Service,
19
+ defaultLayer: () => defaultLayer,
20
+ layer: () => layer
21
+ });
22
+ var ProtocolID = effect$1.Schema.String;
23
+ var RouteID = effect$1.Schema.String;
24
+ var ModelID = effect$1.Schema.String.pipe(effect$1.Schema.brand("LLM.ModelID"));
25
+ var ProviderID = effect$1.Schema.String.pipe(effect$1.Schema.brand("LLM.ProviderID"));
26
+ var ResponseID = effect$1.Schema.String;
27
+ var ContentBlockID = effect$1.Schema.String;
28
+ var ToolCallID = effect$1.Schema.String;
29
+ var ReasoningEfforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
30
+ effect$1.Schema.Literals(ReasoningEfforts);
31
+ effect$1.Schema.Literals(["low", "medium", "high"]);
32
+ var MessageRole = effect$1.Schema.Literals(["user", "assistant", "tool"]);
33
+ var FinishReason = effect$1.Schema.Literals(["stop", "length", "tool-calls", "content-filter", "error", "unknown"]);
34
+ var JsonSchema = effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown);
35
+ var ProviderMetadata = effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown));
36
+ var isRecord = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
37
+ var mergeJsonRecords = (...items) => {
38
+ const defined = items.filter((item) => item !== void 0);
39
+ if (defined.length === 0) return void 0;
40
+ if (defined.length === 1 && Object.values(defined[0]).every((value2) => value2 !== void 0)) return defined[0];
41
+ const result = {};
42
+ for (const item of defined) {
43
+ for (const [key, value2] of Object.entries(item)) {
44
+ if (value2 === void 0) continue;
45
+ result[key] = isRecord(result[key]) && isRecord(value2) ? mergeJsonRecords(result[key], value2) : value2;
46
+ }
47
+ }
48
+ return Object.keys(result).length === 0 ? void 0 : result;
49
+ };
50
+ var mergeStringRecords = (...items) => {
51
+ const defined = items.filter((item) => item !== void 0);
52
+ if (defined.length === 0) return void 0;
53
+ if (defined.length === 1) return defined[0];
54
+ const result = Object.fromEntries(
55
+ defined.flatMap(
56
+ (item) => Object.entries(item).filter((entry) => entry[1] !== void 0)
57
+ )
58
+ );
59
+ return Object.keys(result).length === 0 ? void 0 : result;
60
+ };
61
+ var ProviderOptions = effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown));
62
+ var mergeProviderOptions = (...items) => {
63
+ const result = {};
64
+ for (const item of items) {
65
+ if (!item) continue;
66
+ for (const [provider, options] of Object.entries(item)) {
67
+ const merged = mergeJsonRecords(result[provider], options);
68
+ if (merged) result[provider] = merged;
69
+ }
70
+ }
71
+ return Object.keys(result).length === 0 ? void 0 : result;
72
+ };
73
+ var HttpOptions = class extends effect$1.Schema.Class("LLM.HttpOptions")({
74
+ body: effect$1.Schema.optional(JsonSchema),
75
+ headers: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
76
+ query: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String))
77
+ }) {
78
+ };
79
+ ((HttpOptions2) => {
80
+ HttpOptions2.make = (input) => input instanceof HttpOptions2 ? input : new HttpOptions2(input);
81
+ })(HttpOptions || (HttpOptions = {}));
82
+ var mergeHttpOptions = (...items) => {
83
+ const body = mergeJsonRecords(...items.map((item) => item?.body));
84
+ const headers2 = mergeStringRecords(...items.map((item) => item?.headers));
85
+ const query = mergeStringRecords(...items.map((item) => item?.query));
86
+ if (!body && !headers2 && !query) return void 0;
87
+ return new HttpOptions({ body, headers: headers2, query });
88
+ };
89
+ var GenerationOptions = class extends effect$1.Schema.Class("LLM.GenerationOptions")({
90
+ maxTokens: effect$1.Schema.optional(effect$1.Schema.Number),
91
+ temperature: effect$1.Schema.optional(effect$1.Schema.Number),
92
+ topP: effect$1.Schema.optional(effect$1.Schema.Number),
93
+ topK: effect$1.Schema.optional(effect$1.Schema.Number),
94
+ frequencyPenalty: effect$1.Schema.optional(effect$1.Schema.Number),
95
+ presencePenalty: effect$1.Schema.optional(effect$1.Schema.Number),
96
+ seed: effect$1.Schema.optional(effect$1.Schema.Number),
97
+ stop: effect$1.Schema.optional(effect$1.Schema.Array(effect$1.Schema.String))
98
+ }) {
99
+ };
100
+ ((GenerationOptions2) => {
101
+ GenerationOptions2.make = (input = {}) => input instanceof GenerationOptions2 ? input : new GenerationOptions2(input);
102
+ })(GenerationOptions || (GenerationOptions = {}));
103
+ var latestGeneration = (items, key) => items.findLast((item) => item?.[key] !== void 0)?.[key];
104
+ var mergeGenerationOptions = (...items) => {
105
+ const result = new GenerationOptions({
106
+ maxTokens: latestGeneration(items, "maxTokens"),
107
+ temperature: latestGeneration(items, "temperature"),
108
+ topP: latestGeneration(items, "topP"),
109
+ topK: latestGeneration(items, "topK"),
110
+ frequencyPenalty: latestGeneration(items, "frequencyPenalty"),
111
+ presencePenalty: latestGeneration(items, "presencePenalty"),
112
+ seed: latestGeneration(items, "seed"),
113
+ stop: latestGeneration(items, "stop")
114
+ });
115
+ return Object.values(result).some((value2) => value2 !== void 0) ? result : void 0;
116
+ };
117
+ var ModelLimits = class extends effect$1.Schema.Class("LLM.ModelLimits")({
118
+ context: effect$1.Schema.optional(effect$1.Schema.Number),
119
+ output: effect$1.Schema.optional(effect$1.Schema.Number)
120
+ }) {
121
+ };
122
+ ((ModelLimits2) => {
123
+ ModelLimits2.make = (input) => input instanceof ModelLimits2 ? input : new ModelLimits2(input ?? {});
124
+ })(ModelLimits || (ModelLimits = {}));
125
+ var ModelRef = class extends effect$1.Schema.Class("LLM.ModelRef")({
126
+ id: ModelID,
127
+ provider: ProviderID,
128
+ route: RouteID,
129
+ baseURL: effect$1.Schema.String,
130
+ /** Provider-specific API key convenience. Provider helpers normalize this into `auth`. */
131
+ apiKey: effect$1.Schema.optional(effect$1.Schema.String),
132
+ /** Optional transport auth policy. Opaque because it may contain functions. */
133
+ auth: effect$1.Schema.optional(effect$1.Schema.Any),
134
+ headers: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
135
+ /**
136
+ * Query params appended to the request URL by `Endpoint.baseURL`. Used for
137
+ * deployment-level URL-scoped settings such as Azure's `api-version` or any
138
+ * provider that requires a per-request key in the URL. Generic concern, so
139
+ * lives as a typed first-class field instead of `native`.
140
+ */
141
+ queryParams: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
142
+ limits: ModelLimits,
143
+ /** Provider-neutral generation defaults. Request-level values override them. */
144
+ generation: effect$1.Schema.optional(GenerationOptions),
145
+ /** Provider-owned typed-at-the-facade options for non-portable knobs. */
146
+ providerOptions: effect$1.Schema.optional(ProviderOptions),
147
+ /** Serializable raw HTTP overlays applied to the final outgoing request. */
148
+ http: effect$1.Schema.optional(HttpOptions),
149
+ /**
150
+ * Provider-specific opaque options. Reach for this only when the value is
151
+ * genuinely provider-private and does not fit a typed axis (e.g. Bedrock's
152
+ * `aws_credentials` / `aws_region` for SigV4). Anything used by more than
153
+ * one route should grow into a typed field instead.
154
+ */
155
+ native: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
156
+ }) {
157
+ };
158
+ ((ModelRef2) => {
159
+ ModelRef2.input = (model2) => ({
160
+ id: model2.id,
161
+ provider: model2.provider,
162
+ route: model2.route,
163
+ baseURL: model2.baseURL,
164
+ apiKey: model2.apiKey,
165
+ auth: model2.auth,
166
+ headers: model2.headers,
167
+ queryParams: model2.queryParams,
168
+ limits: model2.limits,
169
+ generation: model2.generation,
170
+ providerOptions: model2.providerOptions,
171
+ http: model2.http,
172
+ native: model2.native
173
+ });
174
+ ModelRef2.update = (model2, patch) => {
175
+ if (Object.keys(patch).length === 0) return model2;
176
+ return new ModelRef2({
177
+ ...(0, ModelRef2.input)(model2),
178
+ ...patch
179
+ });
180
+ };
181
+ })(ModelRef || (ModelRef = {}));
182
+ var CacheHint = class extends effect$1.Schema.Class("LLM.CacheHint")({
183
+ type: effect$1.Schema.Literals(["ephemeral", "persistent"]),
184
+ ttlSeconds: effect$1.Schema.optional(effect$1.Schema.Number)
185
+ }) {
186
+ };
187
+ var CachePolicyObject = effect$1.Schema.Struct({
188
+ tools: effect$1.Schema.optional(effect$1.Schema.Boolean),
189
+ system: effect$1.Schema.optional(effect$1.Schema.Boolean),
190
+ messages: effect$1.Schema.optional(
191
+ effect$1.Schema.Union([
192
+ effect$1.Schema.Literal("latest-user-message"),
193
+ effect$1.Schema.Literal("latest-assistant"),
194
+ effect$1.Schema.Struct({ tail: effect$1.Schema.Number })
195
+ ])
196
+ ),
197
+ ttlSeconds: effect$1.Schema.optional(effect$1.Schema.Number)
198
+ });
199
+ var CachePolicy = effect$1.Schema.Union([effect$1.Schema.Literal("auto"), effect$1.Schema.Literal("none"), CachePolicyObject]);
200
+ var isRecord2 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
201
+ var systemPartSchema = effect$1.Schema.Struct({
202
+ type: effect$1.Schema.Literal("text"),
203
+ text: effect$1.Schema.String,
204
+ cache: effect$1.Schema.optional(CacheHint),
205
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
206
+ }).annotate({ identifier: "LLM.SystemPart" });
207
+ var makeSystemPart = (text) => ({ type: "text", text });
208
+ var SystemPart = Object.assign(systemPartSchema, {
209
+ make: makeSystemPart,
210
+ content: (input) => {
211
+ if (input === void 0) return [];
212
+ return typeof input === "string" ? [makeSystemPart(input)] : Array.isArray(input) ? [...input] : [input];
213
+ }
214
+ });
215
+ var TextPart = effect$1.Schema.Struct({
216
+ type: effect$1.Schema.Literal("text"),
217
+ text: effect$1.Schema.String,
218
+ cache: effect$1.Schema.optional(CacheHint),
219
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
220
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
221
+ }).annotate({ identifier: "LLM.Content.Text" });
222
+ var MediaPart = effect$1.Schema.Struct({
223
+ type: effect$1.Schema.Literal("media"),
224
+ mediaType: effect$1.Schema.String,
225
+ data: effect$1.Schema.Union([effect$1.Schema.String, effect$1.Schema.Uint8Array]),
226
+ filename: effect$1.Schema.optional(effect$1.Schema.String),
227
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
228
+ }).annotate({ identifier: "LLM.Content.Media" });
229
+ var isToolResultValue = (value2) => isRecord2(value2) && (value2.type === "text" || value2.type === "json" || value2.type === "error") && "value" in value2;
230
+ var ToolResultValue = Object.assign(
231
+ effect$1.Schema.Struct({
232
+ type: effect$1.Schema.Literals(["json", "text", "error"]),
233
+ value: effect$1.Schema.Unknown,
234
+ /** Optional structured payload (e.g. tool-interrupt metadata). */
235
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
236
+ }).annotate({ identifier: "LLM.ToolResult" }),
237
+ {
238
+ make: (value2, type = "json", metadata) => {
239
+ if (isToolResultValue(value2)) {
240
+ return metadata ? { ...value2, metadata: { ...value2.metadata ?? {}, ...metadata } } : value2;
241
+ }
242
+ return metadata ? { type, value: value2, metadata } : { type, value: value2 };
243
+ }
244
+ }
245
+ );
246
+ var ToolCallPart = Object.assign(
247
+ effect$1.Schema.Struct({
248
+ type: effect$1.Schema.Literal("tool-call"),
249
+ id: effect$1.Schema.String,
250
+ name: effect$1.Schema.String,
251
+ input: effect$1.Schema.Unknown,
252
+ providerExecuted: effect$1.Schema.optional(effect$1.Schema.Boolean),
253
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
254
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
255
+ }).annotate({ identifier: "LLM.Content.ToolCall" }),
256
+ {
257
+ make: (input) => ({ type: "tool-call", ...input })
258
+ }
259
+ );
260
+ var ToolResultPart = Object.assign(
261
+ effect$1.Schema.Struct({
262
+ type: effect$1.Schema.Literal("tool-result"),
263
+ id: effect$1.Schema.String,
264
+ name: effect$1.Schema.String,
265
+ result: ToolResultValue,
266
+ providerExecuted: effect$1.Schema.optional(effect$1.Schema.Boolean),
267
+ cache: effect$1.Schema.optional(CacheHint),
268
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
269
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
270
+ }).annotate({ identifier: "LLM.Content.ToolResult" }),
271
+ {
272
+ make: (input) => ({
273
+ type: "tool-result",
274
+ id: input.id,
275
+ name: input.name,
276
+ result: ToolResultValue.make(input.result, input.resultType),
277
+ providerExecuted: input.providerExecuted,
278
+ cache: input.cache,
279
+ metadata: input.metadata,
280
+ providerMetadata: input.providerMetadata
281
+ })
282
+ }
283
+ );
284
+ var ReasoningPart = effect$1.Schema.Struct({
285
+ type: effect$1.Schema.Literal("reasoning"),
286
+ text: effect$1.Schema.String,
287
+ encrypted: effect$1.Schema.optional(effect$1.Schema.String),
288
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
289
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
290
+ }).annotate({ identifier: "LLM.Content.Reasoning" });
291
+ var ContentPart = effect$1.Schema.Union([TextPart, MediaPart, ToolCallPart, ToolResultPart, ReasoningPart]).pipe(
292
+ effect$1.Schema.toTaggedUnion("type")
293
+ );
294
+ var Message = class extends effect$1.Schema.Class("LLM.Message")({
295
+ id: effect$1.Schema.optional(effect$1.Schema.String),
296
+ role: MessageRole,
297
+ content: effect$1.Schema.Array(ContentPart),
298
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
299
+ native: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
300
+ }) {
301
+ };
302
+ ((Message2) => {
303
+ Message2.text = (value2) => ({ type: "text", text: value2 });
304
+ Message2.content = (input) => typeof input === "string" ? [(0, Message2.text)(input)] : Array.isArray(input) ? [...input] : [input];
305
+ Message2.make = (input) => {
306
+ if (input instanceof Message2) return input;
307
+ return new Message2({ ...input, content: (0, Message2.content)(input.content) });
308
+ };
309
+ Message2.user = (content2) => (0, Message2.make)({ role: "user", content: content2 });
310
+ Message2.assistant = (content2) => (0, Message2.make)({ role: "assistant", content: content2 });
311
+ Message2.tool = (result) => (0, Message2.make)({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] });
312
+ })(Message || (Message = {}));
313
+ var ToolDefinition = class extends effect$1.Schema.Class("LLM.ToolDefinition")({
314
+ name: effect$1.Schema.String,
315
+ description: effect$1.Schema.String,
316
+ inputSchema: JsonSchema,
317
+ cache: effect$1.Schema.optional(CacheHint),
318
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
319
+ native: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
320
+ }) {
321
+ };
322
+ ((ToolDefinition2) => {
323
+ ToolDefinition2.make = (input) => input instanceof ToolDefinition2 ? input : new ToolDefinition2(input);
324
+ })(ToolDefinition || (ToolDefinition = {}));
325
+ var ToolChoice = class extends effect$1.Schema.Class("LLM.ToolChoice")({
326
+ type: effect$1.Schema.Literals(["auto", "none", "required", "tool"]),
327
+ name: effect$1.Schema.optional(effect$1.Schema.String)
328
+ }) {
329
+ };
330
+ ((ToolChoice2) => {
331
+ const isMode = (value2) => value2 === "auto" || value2 === "none" || value2 === "required";
332
+ ToolChoice2.named = (value2) => new ToolChoice2({ type: "tool", name: value2 });
333
+ ToolChoice2.make = (input) => {
334
+ if (input instanceof ToolChoice2) return input;
335
+ if (input instanceof ToolDefinition) return (0, ToolChoice2.named)(input.name);
336
+ if (typeof input === "string") return isMode(input) ? new ToolChoice2({ type: input }) : (0, ToolChoice2.named)(input);
337
+ return new ToolChoice2(input);
338
+ };
339
+ })(ToolChoice || (ToolChoice = {}));
340
+ var ResponseFormat = effect$1.Schema.Union([
341
+ effect$1.Schema.Struct({ type: effect$1.Schema.Literal("text") }),
342
+ effect$1.Schema.Struct({ type: effect$1.Schema.Literal("json"), schema: JsonSchema }),
343
+ effect$1.Schema.Struct({ type: effect$1.Schema.Literal("tool"), tool: ToolDefinition })
344
+ ]).pipe(effect$1.Schema.toTaggedUnion("type"));
345
+ var LLMRequest = class extends effect$1.Schema.Class("LLM.Request")({
346
+ id: effect$1.Schema.optional(effect$1.Schema.String),
347
+ model: ModelRef,
348
+ system: effect$1.Schema.Array(SystemPart),
349
+ messages: effect$1.Schema.Array(Message),
350
+ tools: effect$1.Schema.Array(ToolDefinition),
351
+ toolChoice: effect$1.Schema.optional(ToolChoice),
352
+ generation: effect$1.Schema.optional(GenerationOptions),
353
+ providerOptions: effect$1.Schema.optional(ProviderOptions),
354
+ http: effect$1.Schema.optional(HttpOptions),
355
+ responseFormat: effect$1.Schema.optional(ResponseFormat),
356
+ cache: effect$1.Schema.optional(CachePolicy),
357
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
358
+ }) {
359
+ };
360
+ ((LLMRequest2) => {
361
+ LLMRequest2.input = (request) => ({
362
+ id: request.id,
363
+ model: request.model,
364
+ system: request.system,
365
+ messages: request.messages,
366
+ tools: request.tools,
367
+ toolChoice: request.toolChoice,
368
+ generation: request.generation,
369
+ providerOptions: request.providerOptions,
370
+ http: request.http,
371
+ responseFormat: request.responseFormat,
372
+ cache: request.cache,
373
+ metadata: request.metadata
374
+ });
375
+ LLMRequest2.update = (request, patch) => {
376
+ if (Object.keys(patch).length === 0) return request;
377
+ return new LLMRequest2({
378
+ ...(0, LLMRequest2.input)(request),
379
+ ...patch,
380
+ model: patch.model ?? request.model
381
+ });
382
+ };
383
+ })(LLMRequest || (LLMRequest = {}));
384
+ var Usage = class extends effect$1.Schema.Class("LLM.Usage")({
385
+ inputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
386
+ outputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
387
+ nonCachedInputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
388
+ cacheReadInputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
389
+ cacheWriteInputTokens: effect$1.Schema.optional(effect$1.Schema.Number),
390
+ reasoningTokens: effect$1.Schema.optional(effect$1.Schema.Number),
391
+ totalTokens: effect$1.Schema.optional(effect$1.Schema.Number),
392
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
393
+ }) {
394
+ /**
395
+ * Visible output tokens — `outputTokens` minus `reasoningTokens`, clamped
396
+ * to zero. The one place subtraction happens in this contract; the clamp
397
+ * means a provider reporting `reasoningTokens > outputTokens` produces a
398
+ * harmless zero rather than a negative that crashes downstream schemas.
399
+ */
400
+ get visibleOutputTokens() {
401
+ return Math.max(0, (this.outputTokens ?? 0) - (this.reasoningTokens ?? 0));
402
+ }
403
+ };
404
+ var RequestStart = effect$1.Schema.Struct({
405
+ type: effect$1.Schema.tag("request-start"),
406
+ id: ResponseID,
407
+ model: ModelRef
408
+ }).annotate({ identifier: "LLM.Event.RequestStart" });
409
+ var StepStart = effect$1.Schema.Struct({
410
+ type: effect$1.Schema.tag("step-start"),
411
+ index: effect$1.Schema.Number
412
+ }).annotate({ identifier: "LLM.Event.StepStart" });
413
+ var TextStart = effect$1.Schema.Struct({
414
+ type: effect$1.Schema.tag("text-start"),
415
+ id: ContentBlockID,
416
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
417
+ }).annotate({ identifier: "LLM.Event.TextStart" });
418
+ var TextDelta = effect$1.Schema.Struct({
419
+ type: effect$1.Schema.tag("text-delta"),
420
+ id: ContentBlockID,
421
+ text: effect$1.Schema.String
422
+ }).annotate({ identifier: "LLM.Event.TextDelta" });
423
+ var TextEnd = effect$1.Schema.Struct({
424
+ type: effect$1.Schema.tag("text-end"),
425
+ id: ContentBlockID,
426
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
427
+ }).annotate({ identifier: "LLM.Event.TextEnd" });
428
+ var ReasoningStart = effect$1.Schema.Struct({
429
+ type: effect$1.Schema.tag("reasoning-start"),
430
+ id: ContentBlockID,
431
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
432
+ }).annotate({ identifier: "LLM.Event.ReasoningStart" });
433
+ var ReasoningDelta = effect$1.Schema.Struct({
434
+ type: effect$1.Schema.tag("reasoning-delta"),
435
+ id: ContentBlockID,
436
+ text: effect$1.Schema.String
437
+ }).annotate({ identifier: "LLM.Event.ReasoningDelta" });
438
+ var ReasoningEnd = effect$1.Schema.Struct({
439
+ type: effect$1.Schema.tag("reasoning-end"),
440
+ id: ContentBlockID,
441
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
442
+ }).annotate({ identifier: "LLM.Event.ReasoningEnd" });
443
+ var ToolInputStart = effect$1.Schema.Struct({
444
+ type: effect$1.Schema.tag("tool-input-start"),
445
+ id: ToolCallID,
446
+ name: effect$1.Schema.String,
447
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
448
+ }).annotate({ identifier: "LLM.Event.ToolInputStart" });
449
+ var ToolInputDelta = effect$1.Schema.Struct({
450
+ type: effect$1.Schema.tag("tool-input-delta"),
451
+ id: ToolCallID,
452
+ name: effect$1.Schema.String,
453
+ text: effect$1.Schema.String
454
+ }).annotate({ identifier: "LLM.Event.ToolInputDelta" });
455
+ var ToolInputEnd = effect$1.Schema.Struct({
456
+ type: effect$1.Schema.tag("tool-input-end"),
457
+ id: ToolCallID,
458
+ name: effect$1.Schema.String,
459
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
460
+ }).annotate({ identifier: "LLM.Event.ToolInputEnd" });
461
+ var ToolCall = effect$1.Schema.Struct({
462
+ type: effect$1.Schema.tag("tool-call"),
463
+ id: ToolCallID,
464
+ name: effect$1.Schema.String,
465
+ input: effect$1.Schema.Unknown,
466
+ providerExecuted: effect$1.Schema.optional(effect$1.Schema.Boolean),
467
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
468
+ }).annotate({ identifier: "LLM.Event.ToolCall" });
469
+ var ToolResult = effect$1.Schema.Struct({
470
+ type: effect$1.Schema.tag("tool-result"),
471
+ id: ToolCallID,
472
+ name: effect$1.Schema.String,
473
+ result: ToolResultValue,
474
+ providerExecuted: effect$1.Schema.optional(effect$1.Schema.Boolean),
475
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
476
+ }).annotate({ identifier: "LLM.Event.ToolResult" });
477
+ var ToolError = effect$1.Schema.Struct({
478
+ type: effect$1.Schema.tag("tool-error"),
479
+ id: ToolCallID,
480
+ name: effect$1.Schema.String,
481
+ message: effect$1.Schema.String,
482
+ /** Optional structured payload (e.g. tool-interrupt metadata for approval). */
483
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown)),
484
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
485
+ }).annotate({ identifier: "LLM.Event.ToolError" });
486
+ var StepFinish = effect$1.Schema.Struct({
487
+ type: effect$1.Schema.tag("step-finish"),
488
+ index: effect$1.Schema.Number,
489
+ reason: FinishReason,
490
+ usage: effect$1.Schema.optional(Usage),
491
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
492
+ }).annotate({ identifier: "LLM.Event.StepFinish" });
493
+ var RequestFinish = effect$1.Schema.Struct({
494
+ type: effect$1.Schema.tag("request-finish"),
495
+ reason: FinishReason,
496
+ usage: effect$1.Schema.optional(Usage),
497
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
498
+ }).annotate({ identifier: "LLM.Event.RequestFinish" });
499
+ var ProviderErrorEvent = effect$1.Schema.Struct({
500
+ type: effect$1.Schema.tag("provider-error"),
501
+ message: effect$1.Schema.String,
502
+ retryable: effect$1.Schema.optional(effect$1.Schema.Boolean),
503
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
504
+ }).annotate({ identifier: "LLM.Event.ProviderError" });
505
+ var llmEventTagged = effect$1.Schema.Union([
506
+ RequestStart,
507
+ StepStart,
508
+ TextStart,
509
+ TextDelta,
510
+ TextEnd,
511
+ ReasoningStart,
512
+ ReasoningDelta,
513
+ ReasoningEnd,
514
+ ToolInputStart,
515
+ ToolInputDelta,
516
+ ToolInputEnd,
517
+ ToolCall,
518
+ ToolResult,
519
+ ToolError,
520
+ StepFinish,
521
+ RequestFinish,
522
+ ProviderErrorEvent
523
+ ]).pipe(effect$1.Schema.toTaggedUnion("type"));
524
+ var responseID = (value2) => ResponseID.make(value2);
525
+ var contentBlockID = (value2) => ContentBlockID.make(value2);
526
+ var toolCallID = (value2) => ToolCallID.make(value2);
527
+ var LLMEvent = Object.assign(llmEventTagged, {
528
+ requestStart: (input) => RequestStart.make({ ...input, id: responseID(input.id) }),
529
+ stepStart: StepStart.make,
530
+ textStart: (input) => TextStart.make({ ...input, id: contentBlockID(input.id) }),
531
+ textDelta: (input) => TextDelta.make({ ...input, id: contentBlockID(input.id) }),
532
+ textEnd: (input) => TextEnd.make({ ...input, id: contentBlockID(input.id) }),
533
+ reasoningStart: (input) => ReasoningStart.make({ ...input, id: contentBlockID(input.id) }),
534
+ reasoningDelta: (input) => ReasoningDelta.make({ ...input, id: contentBlockID(input.id) }),
535
+ reasoningEnd: (input) => ReasoningEnd.make({ ...input, id: contentBlockID(input.id) }),
536
+ toolInputStart: (input) => ToolInputStart.make({ ...input, id: toolCallID(input.id) }),
537
+ toolInputDelta: (input) => ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
538
+ toolInputEnd: (input) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
539
+ toolCall: (input) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
540
+ toolResult: (input) => ToolResult.make({ ...input, id: toolCallID(input.id) }),
541
+ toolError: (input) => ToolError.make({ ...input, id: toolCallID(input.id) }),
542
+ stepFinish: StepFinish.make,
543
+ requestFinish: RequestFinish.make,
544
+ providerError: ProviderErrorEvent.make,
545
+ is: {
546
+ requestStart: llmEventTagged.guards["request-start"],
547
+ stepStart: llmEventTagged.guards["step-start"],
548
+ textStart: llmEventTagged.guards["text-start"],
549
+ textDelta: llmEventTagged.guards["text-delta"],
550
+ textEnd: llmEventTagged.guards["text-end"],
551
+ reasoningStart: llmEventTagged.guards["reasoning-start"],
552
+ reasoningDelta: llmEventTagged.guards["reasoning-delta"],
553
+ reasoningEnd: llmEventTagged.guards["reasoning-end"],
554
+ toolInputStart: llmEventTagged.guards["tool-input-start"],
555
+ toolInputDelta: llmEventTagged.guards["tool-input-delta"],
556
+ toolInputEnd: llmEventTagged.guards["tool-input-end"],
557
+ toolCall: llmEventTagged.guards["tool-call"],
558
+ toolResult: llmEventTagged.guards["tool-result"],
559
+ toolError: llmEventTagged.guards["tool-error"],
560
+ stepFinish: llmEventTagged.guards["step-finish"],
561
+ requestFinish: llmEventTagged.guards["request-finish"],
562
+ providerError: llmEventTagged.guards["provider-error"]
563
+ }
564
+ });
565
+ var PreparedRequest = class extends effect$1.Schema.Class("LLM.PreparedRequest")({
566
+ id: effect$1.Schema.String,
567
+ route: RouteID,
568
+ protocol: ProtocolID,
569
+ model: ModelRef,
570
+ body: effect$1.Schema.Unknown,
571
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
572
+ }) {
573
+ };
574
+ var responseText = (events) => events.filter(LLMEvent.is.textDelta).map((event) => event.text).join("");
575
+ var responseReasoning = (events) => events.filter(LLMEvent.is.reasoningDelta).map((event) => event.text).join("");
576
+ var responseUsage = (events) => events.reduce(
577
+ (usage, event) => "usage" in event && event.usage !== void 0 ? event.usage : usage,
578
+ void 0
579
+ );
580
+ var LLMResponse = class extends effect$1.Schema.Class("LLM.Response")({
581
+ events: effect$1.Schema.Array(LLMEvent),
582
+ usage: effect$1.Schema.optional(Usage)
583
+ }) {
584
+ /** Concatenated assistant text assembled from streamed `text-delta` events. */
585
+ get text() {
586
+ return responseText(this.events);
587
+ }
588
+ /** Concatenated reasoning text assembled from streamed `reasoning-delta` events. */
589
+ get reasoning() {
590
+ return responseReasoning(this.events);
591
+ }
592
+ /** Completed tool calls emitted by the provider. */
593
+ get toolCalls() {
594
+ return this.events.filter(LLMEvent.is.toolCall);
595
+ }
596
+ };
597
+ ((LLMResponse2) => {
598
+ LLMResponse2.text = (response) => responseText(response.events);
599
+ LLMResponse2.usage = (response) => response.usage ?? responseUsage(response.events);
600
+ LLMResponse2.toolCalls = (response) => response.events.filter(LLMEvent.is.toolCall);
601
+ LLMResponse2.reasoning = (response) => responseReasoning(response.events);
602
+ })(LLMResponse || (LLMResponse = {}));
603
+ var HttpRequestDetails = class extends effect$1.Schema.Class("LLM.HttpRequestDetails")({
604
+ method: effect$1.Schema.String,
605
+ url: effect$1.Schema.String,
606
+ headers: effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)
607
+ }) {
608
+ };
609
+ var HttpResponseDetails = class extends effect$1.Schema.Class("LLM.HttpResponseDetails")({
610
+ status: effect$1.Schema.Number,
611
+ headers: effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)
612
+ }) {
613
+ };
614
+ var HttpRateLimitDetails = class extends effect$1.Schema.Class("LLM.HttpRateLimitDetails")({
615
+ retryAfterMs: effect$1.Schema.optional(effect$1.Schema.Number),
616
+ limit: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
617
+ remaining: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String)),
618
+ reset: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.String))
619
+ }) {
620
+ };
621
+ var HttpContext = class extends effect$1.Schema.Class("LLM.HttpContext")({
622
+ request: HttpRequestDetails,
623
+ response: effect$1.Schema.optional(HttpResponseDetails),
624
+ body: effect$1.Schema.optional(effect$1.Schema.String),
625
+ bodyTruncated: effect$1.Schema.optional(effect$1.Schema.Boolean),
626
+ requestId: effect$1.Schema.optional(effect$1.Schema.String),
627
+ rateLimit: effect$1.Schema.optional(HttpRateLimitDetails)
628
+ }) {
629
+ };
630
+ var InvalidRequestReason = class extends effect$1.Schema.Class("LLM.Error.InvalidRequest")({
631
+ _tag: effect$1.Schema.tag("InvalidRequest"),
632
+ message: effect$1.Schema.String,
633
+ parameter: effect$1.Schema.optional(effect$1.Schema.String),
634
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
635
+ http: effect$1.Schema.optional(HttpContext)
636
+ }) {
637
+ get retryable() {
638
+ return false;
639
+ }
640
+ };
641
+ var ContextOverflowReason = class extends effect$1.Schema.Class("LLM.Error.ContextOverflow")({
642
+ _tag: effect$1.Schema.tag("ContextOverflow"),
643
+ message: effect$1.Schema.String,
644
+ /** Provider-reported prompt token count when present in the error body. */
645
+ promptTokens: effect$1.Schema.optional(effect$1.Schema.Number),
646
+ /** Provider-reported context window size when present in the error body. */
647
+ contextWindow: effect$1.Schema.optional(effect$1.Schema.Number),
648
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
649
+ http: effect$1.Schema.optional(HttpContext)
650
+ }) {
651
+ get retryable() {
652
+ return false;
653
+ }
654
+ };
655
+ var NoRouteReason = class extends effect$1.Schema.Class("LLM.Error.NoRoute")({
656
+ _tag: effect$1.Schema.tag("NoRoute"),
657
+ route: RouteID,
658
+ provider: ProviderID,
659
+ model: ModelID
660
+ }) {
661
+ get retryable() {
662
+ return false;
663
+ }
664
+ get message() {
665
+ return `No LLM route for ${this.provider}/${this.model} using ${this.route}`;
666
+ }
667
+ };
668
+ var AuthenticationReason = class extends effect$1.Schema.Class("LLM.Error.Authentication")({
669
+ _tag: effect$1.Schema.tag("Authentication"),
670
+ message: effect$1.Schema.String,
671
+ kind: effect$1.Schema.Literals(["missing", "invalid", "expired", "insufficient-permissions", "unknown"]),
672
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
673
+ http: effect$1.Schema.optional(HttpContext)
674
+ }) {
675
+ get retryable() {
676
+ return false;
677
+ }
678
+ };
679
+ var RateLimitReason = class extends effect$1.Schema.Class("LLM.Error.RateLimit")({
680
+ _tag: effect$1.Schema.tag("RateLimit"),
681
+ message: effect$1.Schema.String,
682
+ retryAfterMs: effect$1.Schema.optional(effect$1.Schema.Number),
683
+ rateLimit: effect$1.Schema.optional(HttpRateLimitDetails),
684
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
685
+ http: effect$1.Schema.optional(HttpContext)
686
+ }) {
687
+ get retryable() {
688
+ return true;
689
+ }
690
+ };
691
+ var QuotaExceededReason = class extends effect$1.Schema.Class("LLM.Error.QuotaExceeded")({
692
+ _tag: effect$1.Schema.tag("QuotaExceeded"),
693
+ message: effect$1.Schema.String,
694
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
695
+ http: effect$1.Schema.optional(HttpContext)
696
+ }) {
697
+ get retryable() {
698
+ return false;
699
+ }
700
+ };
701
+ var ContentPolicyReason = class extends effect$1.Schema.Class("LLM.Error.ContentPolicy")({
702
+ _tag: effect$1.Schema.tag("ContentPolicy"),
703
+ message: effect$1.Schema.String,
704
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
705
+ http: effect$1.Schema.optional(HttpContext)
706
+ }) {
707
+ get retryable() {
708
+ return false;
709
+ }
710
+ };
711
+ var ProviderInternalReason = class extends effect$1.Schema.Class("LLM.Error.ProviderInternal")({
712
+ _tag: effect$1.Schema.tag("ProviderInternal"),
713
+ message: effect$1.Schema.String,
714
+ status: effect$1.Schema.Number,
715
+ retryAfterMs: effect$1.Schema.optional(effect$1.Schema.Number),
716
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
717
+ http: effect$1.Schema.optional(HttpContext)
718
+ }) {
719
+ get retryable() {
720
+ return true;
721
+ }
722
+ };
723
+ var TransportReason = class extends effect$1.Schema.Class("LLM.Error.Transport")({
724
+ _tag: effect$1.Schema.tag("Transport"),
725
+ message: effect$1.Schema.String,
726
+ kind: effect$1.Schema.optional(effect$1.Schema.String),
727
+ url: effect$1.Schema.optional(effect$1.Schema.String),
728
+ http: effect$1.Schema.optional(HttpContext)
729
+ }) {
730
+ get retryable() {
731
+ return false;
732
+ }
733
+ };
734
+ var InvalidProviderOutputReason = class extends effect$1.Schema.Class(
735
+ "LLM.Error.InvalidProviderOutput"
736
+ )({
737
+ _tag: effect$1.Schema.tag("InvalidProviderOutput"),
738
+ message: effect$1.Schema.String,
739
+ route: effect$1.Schema.optional(effect$1.Schema.String),
740
+ raw: effect$1.Schema.optional(effect$1.Schema.String),
741
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata)
742
+ }) {
743
+ get retryable() {
744
+ return false;
745
+ }
746
+ };
747
+ var UnknownProviderReason = class extends effect$1.Schema.Class("LLM.Error.UnknownProvider")({
748
+ _tag: effect$1.Schema.tag("UnknownProvider"),
749
+ message: effect$1.Schema.String,
750
+ status: effect$1.Schema.optional(effect$1.Schema.Number),
751
+ providerMetadata: effect$1.Schema.optional(ProviderMetadata),
752
+ http: effect$1.Schema.optional(HttpContext)
753
+ }) {
754
+ get retryable() {
755
+ return false;
756
+ }
757
+ };
758
+ var LLMErrorReason = effect$1.Schema.Union([
759
+ InvalidRequestReason,
760
+ ContextOverflowReason,
761
+ NoRouteReason,
762
+ AuthenticationReason,
763
+ RateLimitReason,
764
+ QuotaExceededReason,
765
+ ContentPolicyReason,
766
+ ProviderInternalReason,
767
+ TransportReason,
768
+ InvalidProviderOutputReason,
769
+ UnknownProviderReason
770
+ ]).pipe(effect$1.Schema.toTaggedUnion("_tag"));
771
+ var LLMError = class extends effect$1.Schema.TaggedErrorClass()("LLM.Error", {
772
+ module: effect$1.Schema.String,
773
+ method: effect$1.Schema.String,
774
+ reason: LLMErrorReason
775
+ }) {
776
+ cause = this.reason;
777
+ get retryable() {
778
+ return this.reason.retryable;
779
+ }
780
+ get retryAfterMs() {
781
+ return "retryAfterMs" in this.reason ? this.reason.retryAfterMs : void 0;
782
+ }
783
+ get message() {
784
+ return `${this.module}.${this.method}: ${this.reason.message}`;
785
+ }
786
+ };
787
+ var ToolFailure = class extends effect$1.Schema.TaggedErrorClass()("LLM.ToolFailure", {
788
+ message: effect$1.Schema.String,
789
+ metadata: effect$1.Schema.optional(effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown))
790
+ }) {
791
+ };
792
+
793
+ // src/route/overflow-detect.ts
794
+ var OVERFLOW_PATTERNS = [
795
+ /prompt is too long/i,
796
+ // Anthropic
797
+ /input is too long for requested model/i,
798
+ // Amazon Bedrock
799
+ /exceeds the context window/i,
800
+ // OpenAI
801
+ /input token count.*exceeds the maximum/i,
802
+ // Google (Gemini)
803
+ /maximum prompt length is \d+/i,
804
+ // xAI (Grok)
805
+ /reduce the length of the messages/i,
806
+ // Groq
807
+ /maximum context length is \d+ tokens/i,
808
+ // OpenRouter, DeepSeek, vLLM
809
+ /exceeds the limit of \d+/i,
810
+ // GitHub Copilot
811
+ /exceeds the available context size/i,
812
+ // llama.cpp server
813
+ /greater than the context length/i,
814
+ // LM Studio
815
+ /context window exceeds limit/i,
816
+ // MiniMax
817
+ /exceeded model token limit/i,
818
+ // Kimi, Moonshot
819
+ /context[_ ]length[_ ]exceeded/i,
820
+ // Generic OpenAI-style code
821
+ /request entity too large/i,
822
+ // HTTP 413
823
+ /context length is only \d+ tokens/i,
824
+ // vLLM
825
+ /input length.*exceeds.*context length/i,
826
+ // vLLM
827
+ /prompt too long; exceeded (?:max )?context length/i,
828
+ // Ollama
829
+ /too large for model with \d+ maximum context length/i,
830
+ // Mistral
831
+ /model_context_window_exceeded/i
832
+ // z.ai
833
+ ];
834
+ var NO_BODY_4XX = /^4(00|13)\s*(status code)?\s*\(no body\)/i;
835
+ var isOverflowMessage = (message) => {
836
+ if (OVERFLOW_PATTERNS.some((p) => p.test(message))) return true;
837
+ return NO_BODY_4XX.test(message);
838
+ };
839
+ var isOverflowStatus = (status) => status === 413;
840
+ var TOKENS_GT_MAX = /(\d{4,})\s*tokens?\s*[>≥]\s*(\d{4,})/i;
841
+ var PROMPT_LENGTH = /prompt is too long:\s*(\d{4,})\s*tokens?\s*>\s*(\d{4,})\s*maximum/i;
842
+ var INPUT_LIMIT = /input length\s*(\d{4,}).*context length\s*(\d{4,})/i;
843
+ var extractOverflowNumbers = (message) => {
844
+ const match = PROMPT_LENGTH.exec(message) ?? INPUT_LIMIT.exec(message) ?? TOKENS_GT_MAX.exec(message);
845
+ if (!match) return void 0;
846
+ const promptTokens = Number(match[1]);
847
+ const contextWindow = Number(match[2]);
848
+ if (!Number.isFinite(promptTokens) || !Number.isFinite(contextWindow)) return void 0;
849
+ return { promptTokens, contextWindow };
850
+ };
851
+ var isOverflowBody = (body) => {
852
+ if (typeof body !== "object" || body === null) return false;
853
+ const root = body;
854
+ const code = root.error?.code ?? root.code;
855
+ if (typeof code === "string" && /context[_ ]length[_ ]exceeded/i.test(code)) return true;
856
+ if (typeof code === "string" && /model_context_window_exceeded/i.test(code)) return true;
857
+ return false;
858
+ };
859
+
860
+ // src/route/executor.ts
861
+ var Service = class extends effect$1.Context.Service()("@tinyweb-agent/LLM/RequestExecutor") {
862
+ };
863
+ var BODY_LIMIT = 16384;
864
+ var MAX_RETRIES = 2;
865
+ var BASE_DELAY_MS = 500;
866
+ var MAX_DELAY_MS = 1e4;
867
+ var REDACTED = "<redacted>";
868
+ var SENSITIVE_NAME_SOURCE = "authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|credential|signature|x-amz-signature";
869
+ var SENSITIVE_NAME = new RegExp(SENSITIVE_NAME_SOURCE, "i");
870
+ var SHORT_QUERY_NAME = /^(key|sig)$/i;
871
+ var SENSITIVE_BODY_FIELD = new RegExp(`(?:${SENSITIVE_NAME_SOURCE}|key)`, "i");
872
+ var REDACT_JSON_FIELD = new RegExp(`("(?:${SENSITIVE_BODY_FIELD.source})"\\s*:\\s*)"[^"]*"`, "gi");
873
+ var REDACT_QUERY_FIELD = new RegExp(`((?:${SENSITIVE_BODY_FIELD.source})=)[^&\\s"]+`, "gi");
874
+ var isSensitiveHeaderName = (name) => SENSITIVE_NAME.test(name);
875
+ var isSensitiveQueryName = (name) => isSensitiveHeaderName(name) || SHORT_QUERY_NAME.test(name);
876
+ var redactHeaders = (headers2, redactedNames) => Object.fromEntries(
877
+ Object.entries(http.Headers.redact(headers2, [...redactedNames, SENSITIVE_NAME])).map(([name, value2]) => [
878
+ name,
879
+ String(value2)
880
+ ])
881
+ );
882
+ var redactUrl = (value2) => {
883
+ if (!URL.canParse(value2)) return REDACTED;
884
+ const url = new URL(value2);
885
+ url.searchParams.forEach((_, key) => {
886
+ if (isSensitiveQueryName(key)) url.searchParams.set(key, REDACTED);
887
+ });
888
+ return url.toString();
889
+ };
890
+ var normalizedHeaders = (headers2) => Object.fromEntries(Object.entries(headers2).map(([key, value2]) => [key.toLowerCase(), value2]));
891
+ var requestId = (headers2) => {
892
+ 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"];
893
+ };
894
+ var retryableStatus = (status) => status === 429 || status === 503 || status === 504 || status === 529;
895
+ var retryAfterMs = (headers2) => {
896
+ const millis = Number(headers2["retry-after-ms"]);
897
+ if (Number.isFinite(millis)) return Math.max(0, millis);
898
+ const value2 = headers2["retry-after"];
899
+ if (!value2) return void 0;
900
+ const seconds = Number(value2);
901
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
902
+ const date = Date.parse(value2);
903
+ if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
904
+ return void 0;
905
+ };
906
+ var addRateLimitValue = (target, key, value2) => {
907
+ if (key.length > 0) target[key] = value2;
908
+ };
909
+ var rateLimitDetails = (headers2, retryAfter) => {
910
+ const limit = {};
911
+ const remaining = {};
912
+ const reset = {};
913
+ Object.entries(headers2).forEach(([name, value2]) => {
914
+ const openaiLimit = /^x-ratelimit-limit-(.+)$/.exec(name)?.[1];
915
+ if (openaiLimit) return addRateLimitValue(limit, openaiLimit, value2);
916
+ const openaiRemaining = /^x-ratelimit-remaining-(.+)$/.exec(name)?.[1];
917
+ if (openaiRemaining) return addRateLimitValue(remaining, openaiRemaining, value2);
918
+ const openaiReset = /^x-ratelimit-reset-(.+)$/.exec(name)?.[1];
919
+ if (openaiReset) return addRateLimitValue(reset, openaiReset, value2);
920
+ const anthropic = /^anthropic-ratelimit-(.+)-(limit|remaining|reset)$/.exec(name);
921
+ if (!anthropic) return;
922
+ if (anthropic[2] === "limit") return addRateLimitValue(limit, anthropic[1], value2);
923
+ if (anthropic[2] === "remaining") return addRateLimitValue(remaining, anthropic[1], value2);
924
+ return addRateLimitValue(reset, anthropic[1], value2);
925
+ });
926
+ if (retryAfter === void 0 && Object.keys(limit).length === 0 && Object.keys(remaining).length === 0 && Object.keys(reset).length === 0)
927
+ return void 0;
928
+ return new HttpRateLimitDetails({
929
+ retryAfterMs: retryAfter,
930
+ limit: Object.keys(limit).length === 0 ? void 0 : limit,
931
+ remaining: Object.keys(remaining).length === 0 ? void 0 : remaining,
932
+ reset: Object.keys(reset).length === 0 ? void 0 : reset
933
+ });
934
+ };
935
+ var requestDetails = (request, redactedNames) => new HttpRequestDetails({
936
+ method: request.method,
937
+ url: redactUrl(request.url),
938
+ headers: redactHeaders(request.headers, redactedNames)
939
+ });
940
+ var responseDetails = (response, redactedNames) => new HttpResponseDetails({
941
+ status: response.status,
942
+ headers: redactHeaders(response.headers, redactedNames)
943
+ });
944
+ var secretValues = (request) => {
945
+ const values = /* @__PURE__ */ new Set();
946
+ const add = (value2) => {
947
+ if (value2.length < 4) return;
948
+ values.add(value2);
949
+ values.add(encodeURIComponent(value2));
950
+ };
951
+ Object.entries(request.headers).forEach(([name, value2]) => {
952
+ if (!isSensitiveHeaderName(name)) return;
953
+ add(value2);
954
+ const bearer2 = /^Bearer\s+(.+)$/i.exec(value2)?.[1];
955
+ if (bearer2) add(bearer2);
956
+ });
957
+ if (!URL.canParse(request.url)) return values;
958
+ new URL(request.url).searchParams.forEach((value2, key) => {
959
+ if (isSensitiveQueryName(key)) add(value2);
960
+ });
961
+ return values;
962
+ };
963
+ var redactBody = (body, request) => Array.from(secretValues(request)).reduce(
964
+ (text, secret) => text.split(secret).join(REDACTED),
965
+ body.replace(REDACT_JSON_FIELD, `$1"${REDACTED}"`).replace(REDACT_QUERY_FIELD, `$1${REDACTED}`)
966
+ );
967
+ var responseBody = (body, request) => {
968
+ if (body === void 0) return {};
969
+ const redacted = redactBody(body, request);
970
+ if (redacted.length <= BODY_LIMIT) return { body: redacted };
971
+ return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true };
972
+ };
973
+ var providerMessage = (status, body) => {
974
+ if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`;
975
+ return `Provider request failed with HTTP ${status}`;
976
+ };
977
+ var responseHttp = (input) => new HttpContext({
978
+ request: requestDetails(input.request, input.redactedNames),
979
+ response: responseDetails(input.response, input.redactedNames),
980
+ ...input.body,
981
+ requestId: input.requestId,
982
+ rateLimit: input.rateLimit
983
+ });
984
+ var parseJsonBody = (body) => {
985
+ if (body.length === 0) return void 0;
986
+ try {
987
+ return JSON.parse(body);
988
+ } catch {
989
+ return void 0;
990
+ }
991
+ };
992
+ var isOverflow = (status, message, body) => {
993
+ if (isOverflowStatus(status)) return true;
994
+ if (isOverflowMessage(message)) return true;
995
+ if (body.length > 0 && isOverflowMessage(body)) return true;
996
+ return isOverflowBody(parseJsonBody(body));
997
+ };
998
+ var overflowReason = (input) => {
999
+ const numbers = extractOverflowNumbers(input.message) ?? extractOverflowNumbers(input.body);
1000
+ return new ContextOverflowReason({
1001
+ message: input.message,
1002
+ promptTokens: numbers?.promptTokens,
1003
+ contextWindow: numbers?.contextWindow,
1004
+ http: input.http
1005
+ });
1006
+ };
1007
+ var statusReason = (input) => {
1008
+ const body = input.http.body ?? "";
1009
+ if (isOverflow(input.status, input.message, body)) {
1010
+ return overflowReason({ message: input.message, body, http: input.http });
1011
+ }
1012
+ if (/content[-_\s]?policy|content_filter|safety/i.test(body)) {
1013
+ return new ContentPolicyReason({ message: input.message, http: input.http });
1014
+ }
1015
+ if (input.status === 401) {
1016
+ return new AuthenticationReason({ message: input.message, kind: "invalid", http: input.http });
1017
+ }
1018
+ if (input.status === 403) {
1019
+ return new AuthenticationReason({ message: input.message, kind: "insufficient-permissions", http: input.http });
1020
+ }
1021
+ if (input.status === 429) {
1022
+ if (/insufficient[-_\s]?quota|quota[-_\s]?exceeded/i.test(body)) {
1023
+ return new QuotaExceededReason({ message: input.message, http: input.http });
1024
+ }
1025
+ return new RateLimitReason({
1026
+ message: input.message,
1027
+ retryAfterMs: input.retryAfterMs,
1028
+ rateLimit: input.rateLimit,
1029
+ http: input.http
1030
+ });
1031
+ }
1032
+ if (input.status === 400 || input.status === 404 || input.status === 409 || input.status === 422) {
1033
+ return new InvalidRequestReason({ message: input.message, http: input.http });
1034
+ }
1035
+ if (input.status >= 500 || retryableStatus(input.status)) {
1036
+ return new ProviderInternalReason({
1037
+ message: input.message,
1038
+ status: input.status,
1039
+ retryAfterMs: input.retryAfterMs,
1040
+ http: input.http
1041
+ });
1042
+ }
1043
+ return new UnknownProviderReason({ message: input.message, status: input.status, http: input.http });
1044
+ };
1045
+ var statusError = (request, redactedNames) => (response) => effect$1.Effect.gen(function* () {
1046
+ if (response.status < 400) return response;
1047
+ const body = yield* response.text.pipe(effect$1.Effect.catch(() => effect$1.Effect.void));
1048
+ const headers2 = normalizedHeaders(response.headers);
1049
+ const retryAfter = retryAfterMs(headers2);
1050
+ const rateLimit = rateLimitDetails(headers2, retryAfter);
1051
+ const details = responseBody(body, request);
1052
+ return yield* new LLMError({
1053
+ module: "RequestExecutor",
1054
+ method: "execute",
1055
+ reason: statusReason({
1056
+ status: response.status,
1057
+ message: providerMessage(response.status, details),
1058
+ retryAfterMs: retryAfter,
1059
+ rateLimit,
1060
+ http: responseHttp({
1061
+ request,
1062
+ response,
1063
+ redactedNames,
1064
+ body: details,
1065
+ requestId: requestId(headers2),
1066
+ rateLimit
1067
+ })
1068
+ })
1069
+ });
1070
+ });
1071
+ var toHttpError = (redactedNames) => (error) => {
1072
+ const transportError = (input) => new LLMError({
1073
+ module: "RequestExecutor",
1074
+ method: "execute",
1075
+ reason: new TransportReason({
1076
+ message: input.message,
1077
+ kind: input.kind,
1078
+ url: input.request ? redactUrl(input.request.url) : void 0,
1079
+ http: input.request ? new HttpContext({ request: requestDetails(input.request, redactedNames) }) : void 0
1080
+ })
1081
+ });
1082
+ if (effect$1.Cause.isTimeoutError(error)) {
1083
+ return transportError({ message: error.message, kind: "Timeout" });
1084
+ }
1085
+ if (!http.HttpClientError.isHttpClientError(error)) {
1086
+ return transportError({ message: "HTTP transport failed" });
1087
+ }
1088
+ const request = "request" in error ? error.request : void 0;
1089
+ if (error.reason._tag === "TransportError") {
1090
+ return transportError({
1091
+ message: error.reason.description ?? "HTTP transport failed",
1092
+ kind: error.reason._tag,
1093
+ request
1094
+ });
1095
+ }
1096
+ return transportError({
1097
+ message: `HTTP transport failed: ${error.reason._tag}`,
1098
+ kind: error.reason._tag,
1099
+ request
1100
+ });
1101
+ };
1102
+ var retryDelay = (error, attempt) => {
1103
+ if (error.retryAfterMs !== void 0) return effect$1.Effect.succeed(Math.min(error.retryAfterMs, MAX_DELAY_MS));
1104
+ return effect$1.Random.nextBetween(
1105
+ Math.min(BASE_DELAY_MS * 2 ** attempt * 0.8, MAX_DELAY_MS),
1106
+ Math.min(BASE_DELAY_MS * 2 ** attempt * 1.2, MAX_DELAY_MS)
1107
+ ).pipe(effect$1.Effect.map((delay) => Math.round(delay)));
1108
+ };
1109
+ var retryStatusFailures = (effect2, retries = MAX_RETRIES, attempt = 0) => effect$1.Effect.catchTag(effect2, "LLM.Error", (error) => {
1110
+ if (!error.retryable || retries <= 0) return effect$1.Effect.fail(error);
1111
+ return retryDelay(error, attempt).pipe(
1112
+ effect$1.Effect.flatMap((delay) => effect$1.Effect.sleep(delay)),
1113
+ effect$1.Effect.flatMap(() => retryStatusFailures(effect2, retries - 1, attempt + 1))
1114
+ );
1115
+ });
1116
+ var layer = effect$1.Layer.effect(
1117
+ Service,
1118
+ effect$1.Effect.gen(function* () {
1119
+ const http$1 = yield* http.HttpClient.HttpClient;
1120
+ const executeOnce = (request) => effect$1.Effect.gen(function* () {
1121
+ const redactedNames = yield* http.Headers.CurrentRedactedNames;
1122
+ return yield* http$1.execute(request).pipe(effect$1.Effect.mapError(toHttpError(redactedNames)), effect$1.Effect.flatMap(statusError(request, redactedNames)));
1123
+ });
1124
+ return Service.of({
1125
+ execute: (request) => retryStatusFailures(executeOnce(request))
1126
+ });
1127
+ })
1128
+ );
1129
+ var defaultLayer = layer.pipe(effect$1.Layer.provide(http.FetchHttpClient.layer));
1130
+
1131
+ // src/route/transport/http.ts
1132
+ var http_exports = {};
1133
+ __export(http_exports, {
1134
+ httpJson: () => httpJson,
1135
+ jsonRequestParts: () => jsonRequestParts
1136
+ });
1137
+
1138
+ // src/route/auth.ts
1139
+ var auth_exports = {};
1140
+ __export(auth_exports, {
1141
+ Auth: () => auth_exports,
1142
+ MissingCredentialError: () => MissingCredentialError,
1143
+ apiKey: () => apiKey,
1144
+ apiKeyHeader: () => apiKeyHeader,
1145
+ bearer: () => bearer,
1146
+ bearerHeader: () => bearerHeader,
1147
+ config: () => config,
1148
+ custom: () => custom,
1149
+ effect: () => effect,
1150
+ header: () => header,
1151
+ headers: () => headers,
1152
+ isAuth: () => isAuth,
1153
+ none: () => none,
1154
+ optional: () => optional,
1155
+ passthrough: () => passthrough,
1156
+ remove: () => remove,
1157
+ toEffect: () => toEffect,
1158
+ value: () => value
1159
+ });
1160
+ var MissingCredentialError = class extends Error {
1161
+ constructor(source) {
1162
+ super(`Missing auth credential: ${source}`);
1163
+ this.source = source;
1164
+ }
1165
+ _tag = "MissingCredentialError";
1166
+ };
1167
+ var isAuth = (input) => typeof input === "object" && input !== null && "apply" in input && typeof input.apply === "function";
1168
+ var credential = (load) => {
1169
+ const self = {
1170
+ load,
1171
+ orElse: (that) => credential(load.pipe(effect$1.Effect.catch(() => that.load))),
1172
+ bearer: () => fromCredential(self, (secret) => ({ authorization: `Bearer ${secret}` })),
1173
+ header: (name) => fromCredential(self, (secret) => ({ [name]: secret })),
1174
+ pipe: (f) => f(self)
1175
+ };
1176
+ return self;
1177
+ };
1178
+ var auth = (apply) => {
1179
+ const self = {
1180
+ apply,
1181
+ andThen: (that) => auth((input) => apply(input).pipe(effect$1.Effect.flatMap((headers2) => that.apply({ ...input, headers: headers2 })))),
1182
+ orElse: (that) => auth((input) => apply(input).pipe(effect$1.Effect.catch(() => that.apply(input)))),
1183
+ pipe: (f) => f(self)
1184
+ };
1185
+ return self;
1186
+ };
1187
+ var fromCredential = (source, render2) => auth(
1188
+ (input) => source.load.pipe(effect$1.Effect.map((secret) => http.Headers.setAll(input.headers, render2(effect$1.Redacted.value(secret)))))
1189
+ );
1190
+ var secretEffect = (secret, source) => {
1191
+ const redacted = typeof secret === "string" ? effect$1.Redacted.make(secret) : secret;
1192
+ if (effect$1.Redacted.value(redacted) === "") return effect$1.Effect.fail(new MissingCredentialError(source));
1193
+ return effect$1.Effect.succeed(redacted);
1194
+ };
1195
+ var credentialFromSecret = (secret, source) => {
1196
+ if (typeof secret === "string" || effect$1.Redacted.isRedacted(secret)) return credential(secretEffect(secret, source));
1197
+ return credential(
1198
+ effect$1.Effect.gen(function* () {
1199
+ return yield* secretEffect(yield* secret, source);
1200
+ })
1201
+ );
1202
+ };
1203
+ var value = (secret, source = "value") => credentialFromSecret(secret, source);
1204
+ var optional = (secret, source = "optional value") => secret === void 0 ? credential(effect$1.Effect.fail(new MissingCredentialError(source))) : credentialFromSecret(secret, source);
1205
+ var config = (name) => credentialFromSecret(effect$1.Config.redacted(name), name);
1206
+ var effect = (load) => credential(load);
1207
+ var none = auth((input) => effect$1.Effect.succeed(input.headers));
1208
+ var headers = (input) => auth((inputAuth) => effect$1.Effect.succeed(http.Headers.setAll(inputAuth.headers, input)));
1209
+ var remove = (name) => auth((input) => effect$1.Effect.succeed(http.Headers.remove(input.headers, name)));
1210
+ var custom = (apply) => auth(apply);
1211
+ var passthrough = none;
1212
+ var fromModelApiKey = (from) => auth(({ request, headers: headers2 }) => {
1213
+ const key = request.model.apiKey;
1214
+ if (!key) return effect$1.Effect.succeed(headers2);
1215
+ return effect$1.Effect.succeed(http.Headers.setAll(headers2, from(key)));
1216
+ });
1217
+ var credentialInput = (source) => typeof source === "string" || effect$1.Redacted.isRedacted(source) || effect$1.Config.isConfig(source) ? credentialFromSecret(source, "value") : source;
1218
+ function bearer(source) {
1219
+ if (source === void 0) return fromModelApiKey((key) => ({ authorization: `Bearer ${key}` }));
1220
+ return credentialInput(source).bearer();
1221
+ }
1222
+ var apiKey = bearer;
1223
+ var apiKeyHeader = (name) => fromModelApiKey((key) => ({ [name]: key }));
1224
+ function header(name, source) {
1225
+ if (source === void 0) {
1226
+ return (next) => credentialInput(next).header(name);
1227
+ }
1228
+ return credentialInput(source).header(name);
1229
+ }
1230
+ function bearerHeader(name, source) {
1231
+ const render2 = (input) => fromCredential(credentialInput(input), (secret) => ({ [name]: `Bearer ${secret}` }));
1232
+ if (source === void 0) return render2;
1233
+ return render2(source);
1234
+ }
1235
+ var toLLMError = (error) => {
1236
+ if (error instanceof MissingCredentialError || error instanceof effect$1.Config.ConfigError) {
1237
+ return new LLMError({
1238
+ module: "Auth",
1239
+ method: "apply",
1240
+ reason: error instanceof MissingCredentialError ? new AuthenticationReason({ message: error.message, kind: "missing" }) : new InvalidRequestReason({ message: `Failed to resolve auth config: ${error.message}` })
1241
+ });
1242
+ }
1243
+ return error;
1244
+ };
1245
+ var toEffect = (input) => (authInput) => input.apply(authInput).pipe(effect$1.Effect.mapError(toLLMError));
1246
+ var Json = effect$1.Schema.fromJsonString(effect$1.Schema.Unknown);
1247
+ effect$1.Schema.decodeUnknownSync(Json);
1248
+ var encodeJson = effect$1.Schema.encodeSync(Json);
1249
+ effect$1.Schema.Record(effect$1.Schema.String, effect$1.Schema.Unknown);
1250
+ var isRecord3 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
1251
+ var eventError = (route, message, raw) => new LLMError({
1252
+ module: "ProviderShared",
1253
+ method: "stream",
1254
+ reason: new InvalidProviderOutputReason({ route, message, raw })
1255
+ });
1256
+ var trimBaseUrl = (value2) => value2.replace(/\/+$/, "");
1257
+ var errorText = (error) => {
1258
+ if (error instanceof Error) return error.message;
1259
+ if (typeof error === "string") return error;
1260
+ if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") return String(error);
1261
+ if (error === null) return "null";
1262
+ if (error === void 0) return "undefined";
1263
+ return "Unknown stream error";
1264
+ };
1265
+ var invalidRequest = (message) => new LLMError({
1266
+ module: "ProviderShared",
1267
+ method: "request",
1268
+ reason: new InvalidRequestReason({ message })
1269
+ });
1270
+ var validateWith = (decode2) => (payload) => decode2(payload).pipe(effect$1.Effect.mapError((error) => invalidRequest(error.message)));
1271
+ var jsonPost = (input) => http.HttpClientRequest.post(input.url).pipe(
1272
+ http.HttpClientRequest.setHeaders(http.Headers.set(http.Headers.fromInput(input.headers), "content-type", "application/json")),
1273
+ http.HttpClientRequest.bodyText(input.body, "application/json")
1274
+ );
1275
+
1276
+ // src/route/endpoint.ts
1277
+ var renderPart = (part, input) => typeof part === "function" ? part(input) : part;
1278
+ var render = (endpoint, input) => {
1279
+ const url = new URL(`${trimBaseUrl(input.request.model.baseURL)}${renderPart(endpoint.path, input)}`);
1280
+ const params = input.request.model.queryParams;
1281
+ if (params) for (const [key, value2] of Object.entries(params)) url.searchParams.set(key, value2);
1282
+ return url;
1283
+ };
1284
+
1285
+ // src/route/transport/http.ts
1286
+ var applyQuery = (url, query) => {
1287
+ if (!query) return url;
1288
+ const next = new URL(url);
1289
+ Object.entries(query).forEach(([key, value2]) => next.searchParams.set(key, value2));
1290
+ return next.toString();
1291
+ };
1292
+ var bodyWithOverlay = (body, request, encodeBody) => effect$1.Effect.gen(function* () {
1293
+ if (request.http?.body === void 0) return { jsonBody: body, bodyText: encodeBody(body) };
1294
+ if (isRecord3(body)) {
1295
+ const overlaid = mergeJsonRecords(body, request.http.body) ?? {};
1296
+ return { jsonBody: overlaid, bodyText: encodeJson(overlaid) };
1297
+ }
1298
+ return yield* invalidRequest("http.body can only overlay JSON object request bodies");
1299
+ });
1300
+ var jsonRequestParts = (input) => effect$1.Effect.gen(function* () {
1301
+ const url = applyQuery(
1302
+ render(input.endpoint, { request: input.request, body: input.body }).toString(),
1303
+ input.request.http?.query
1304
+ );
1305
+ const body = yield* bodyWithOverlay(input.body, input.request, input.encodeBody);
1306
+ const headers2 = yield* auth_exports.toEffect(auth_exports.isAuth(input.request.model.auth) ? input.request.model.auth : input.auth)(
1307
+ {
1308
+ request: input.request,
1309
+ method: "POST",
1310
+ url,
1311
+ body: body.bodyText,
1312
+ headers: http.Headers.fromInput({
1313
+ ...input.headers?.({ request: input.request }) ?? {},
1314
+ ...input.request.model.headers,
1315
+ ...input.request.http?.headers
1316
+ })
1317
+ }
1318
+ );
1319
+ return { url, jsonBody: body.jsonBody, bodyText: body.bodyText, headers: headers2 };
1320
+ });
1321
+ var httpJson = (input) => ({
1322
+ id: "http-json",
1323
+ with: (patch) => httpJson({ ...input, ...patch }),
1324
+ prepare: (body, request) => jsonRequestParts({
1325
+ body,
1326
+ request,
1327
+ endpoint: input.endpoint,
1328
+ auth: input.auth ?? auth_exports.bearer(),
1329
+ encodeBody: input.encodeBody,
1330
+ headers: input.headers
1331
+ }).pipe(
1332
+ effect$1.Effect.map((parts) => ({
1333
+ request: jsonPost({ url: parts.url, body: parts.bodyText, headers: parts.headers }),
1334
+ framing: input.framing
1335
+ }))
1336
+ ),
1337
+ frames: (prepared, request, runtime) => effect$1.Stream.unwrap(
1338
+ runtime.http.execute(prepared.request).pipe(
1339
+ effect$1.Effect.map(
1340
+ (response) => prepared.framing.frame(
1341
+ response.stream.pipe(
1342
+ effect$1.Stream.mapError(
1343
+ (error) => eventError(
1344
+ `${request.model.provider}/${request.model.route}`,
1345
+ `Failed to read ${request.model.provider}/${request.model.route} stream`,
1346
+ errorText(error)
1347
+ )
1348
+ )
1349
+ )
1350
+ )
1351
+ )
1352
+ )
1353
+ )
1354
+ });
1355
+
1356
+ // src/cache-policy.ts
1357
+ var AUTO = {
1358
+ tools: true,
1359
+ system: true,
1360
+ messages: "latest-user-message"
1361
+ };
1362
+ var NONE = {};
1363
+ var resolve = (policy) => {
1364
+ if (policy === void 0 || policy === "auto") return AUTO;
1365
+ if (policy === "none") return NONE;
1366
+ return policy;
1367
+ };
1368
+ var RESPECTS_INLINE_HINTS = /* @__PURE__ */ new Set([]);
1369
+ var makeHint = (ttlSeconds) => ttlSeconds !== void 0 ? new CacheHint({ type: "ephemeral", ttlSeconds }) : new CacheHint({ type: "ephemeral" });
1370
+ var markLastTool = (tools, hint) => {
1371
+ if (tools.length === 0) return tools;
1372
+ const last = tools.length - 1;
1373
+ if (tools[last].cache) return tools;
1374
+ return tools.map((tool, i) => i === last ? new ToolDefinition({ ...tool, cache: hint }) : tool);
1375
+ };
1376
+ var markLastSystem = (system, hint) => {
1377
+ if (system.length === 0) return system;
1378
+ const last = system.length - 1;
1379
+ if (system[last].cache) return system;
1380
+ return system.map((part, i) => i === last ? { ...part, cache: hint } : part);
1381
+ };
1382
+ var lastIndexOfRole = (messages, role) => messages.findLastIndex((m) => m.role === role);
1383
+ var markMessageAt = (messages, index, hint) => {
1384
+ if (index < 0 || index >= messages.length) return messages;
1385
+ const target = messages[index];
1386
+ if (target.content.length === 0) return messages;
1387
+ const lastTextIndex = target.content.findLastIndex((part) => part.type === "text");
1388
+ const markAt = lastTextIndex >= 0 ? lastTextIndex : target.content.length - 1;
1389
+ const existing = target.content[markAt];
1390
+ if ("cache" in existing && existing.cache) return messages;
1391
+ const nextContent = target.content.map((part, i) => i === markAt ? { ...part, cache: hint } : part);
1392
+ const next = new Message({ ...target, content: nextContent });
1393
+ const result = messages.slice();
1394
+ result[index] = next;
1395
+ return result;
1396
+ };
1397
+ var markMessages = (messages, strategy, hint) => {
1398
+ if (messages.length === 0) return messages;
1399
+ if (strategy === "latest-user-message") return markMessageAt(messages, lastIndexOfRole(messages, "user"), hint);
1400
+ if (strategy === "latest-assistant") return markMessageAt(messages, lastIndexOfRole(messages, "assistant"), hint);
1401
+ const start = Math.max(0, messages.length - strategy.tail);
1402
+ let next = messages;
1403
+ for (let i = start; i < messages.length; i++) next = markMessageAt(next, i, hint);
1404
+ return next;
1405
+ };
1406
+ var applyCachePolicy = (request) => {
1407
+ if (!RESPECTS_INLINE_HINTS.has(request.model.route)) return request;
1408
+ const policy = resolve(request.cache);
1409
+ if (!policy.tools && !policy.system && !policy.messages) return request;
1410
+ const hint = makeHint(policy.ttlSeconds);
1411
+ const tools = policy.tools ? markLastTool(request.tools, hint) : request.tools;
1412
+ const system = policy.system ? markLastSystem(request.system, hint) : request.system;
1413
+ const messages = policy.messages ? markMessages(request.messages, policy.messages, hint) : request.messages;
1414
+ if (tools === request.tools && system === request.system && messages === request.messages) return request;
1415
+ return LLMRequest.update(request, { tools, system, messages });
1416
+ };
1417
+ var toDefinitions = (tools) => Object.entries(tools).map(
1418
+ ([name, item]) => new ToolDefinition({
1419
+ name,
1420
+ description: item._definition.description,
1421
+ inputSchema: item._definition.inputSchema
1422
+ })
1423
+ );
1424
+
1425
+ // src/tool-runtime.ts
1426
+ var hasToolCall = (name) => (state) => state.toolCalls.some((call) => call.name === name);
1427
+ var stopWhenAny = (...conditions) => (state) => conditions.some((condition) => condition(state));
1428
+ var stepCountIs = (count) => (state) => state.step + 1 >= count;
1429
+ var stream = (options) => {
1430
+ const concurrency = options.concurrency ?? 10;
1431
+ const tools = options.tools;
1432
+ const runtimeTools = toDefinitions(tools);
1433
+ const runtimeToolNames = new Set(runtimeTools.map((tool) => tool.name));
1434
+ const initialRequest = runtimeTools.length === 0 ? options.request : LLMRequest.update(options.request, {
1435
+ tools: [...options.request.tools.filter((tool) => !runtimeToolNames.has(tool.name)), ...runtimeTools]
1436
+ });
1437
+ const loop = (request, step) => effect$1.Stream.unwrap(
1438
+ effect$1.Effect.gen(function* () {
1439
+ const state = { assistantContent: [], toolCalls: [], finishReason: void 0 };
1440
+ const modelStream = options.stream(request).pipe(effect$1.Stream.tap((event) => effect$1.Effect.sync(() => accumulate(state, event))));
1441
+ const continuation = effect$1.Stream.unwrap(
1442
+ effect$1.Effect.gen(function* () {
1443
+ if (state.finishReason !== "tool-calls" || state.toolCalls.length === 0) return effect$1.Stream.empty;
1444
+ if (options.toolExecution === "none") return effect$1.Stream.empty;
1445
+ const dispatched = yield* effect$1.Effect.forEach(
1446
+ state.toolCalls,
1447
+ (call) => dispatch(tools, call).pipe(effect$1.Effect.map((result) => [call, result])),
1448
+ { concurrency }
1449
+ );
1450
+ const resultStream = effect$1.Stream.fromIterable(dispatched.flatMap(([call, result]) => emitEvents(call, result)));
1451
+ if (dispatched.some(([, result]) => isInterruptResult(result))) return resultStream;
1452
+ if (!options.stopWhen) return resultStream;
1453
+ if (options.stopWhen({ step, request, toolCalls: state.toolCalls })) return resultStream;
1454
+ const followUp = dispatched.filter(([, result]) => !isInterruptResult(result));
1455
+ if (followUp.length === 0) return resultStream;
1456
+ return resultStream.pipe(effect$1.Stream.concat(loop(followUpRequest(request, state, followUp), step + 1)));
1457
+ })
1458
+ );
1459
+ return modelStream.pipe(effect$1.Stream.concat(continuation));
1460
+ })
1461
+ );
1462
+ return loop(initialRequest, 0);
1463
+ };
1464
+ var accumulate = (state, event) => {
1465
+ if (event.type === "text-delta") {
1466
+ appendStreamingText(state, "text", event.text, void 0);
1467
+ return;
1468
+ }
1469
+ if (event.type === "reasoning-delta") {
1470
+ appendStreamingText(state, "reasoning", event.text, void 0);
1471
+ return;
1472
+ }
1473
+ if (event.type === "reasoning-end") {
1474
+ appendStreamingText(state, "reasoning", "", event.providerMetadata);
1475
+ return;
1476
+ }
1477
+ if (event.type === "text-end") {
1478
+ appendStreamingText(state, "text", "", event.providerMetadata);
1479
+ return;
1480
+ }
1481
+ if (event.type === "tool-call") {
1482
+ const part = ToolCallPart.make({
1483
+ id: event.id,
1484
+ name: event.name,
1485
+ input: event.input,
1486
+ providerExecuted: event.providerExecuted,
1487
+ providerMetadata: event.providerMetadata
1488
+ });
1489
+ state.assistantContent.push(part);
1490
+ if (!event.providerExecuted) state.toolCalls.push(part);
1491
+ return;
1492
+ }
1493
+ if (event.type === "tool-result" && event.providerExecuted) {
1494
+ state.assistantContent.push(
1495
+ ToolResultPart.make({
1496
+ id: event.id,
1497
+ name: event.name,
1498
+ result: event.result,
1499
+ providerExecuted: true,
1500
+ providerMetadata: event.providerMetadata
1501
+ })
1502
+ );
1503
+ return;
1504
+ }
1505
+ if (event.type === "request-finish") {
1506
+ state.finishReason = event.reason;
1507
+ }
1508
+ };
1509
+ var sameProviderMetadata = (left, right) => left === right || JSON.stringify(left) === JSON.stringify(right);
1510
+ var mergeProviderMetadata = (left, right) => {
1511
+ if (!left) return right;
1512
+ if (!right) return left;
1513
+ return Object.fromEntries(
1514
+ Array.from(/* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])).map((provider) => [
1515
+ provider,
1516
+ { ...left[provider], ...right[provider] }
1517
+ ])
1518
+ );
1519
+ };
1520
+ var appendStreamingText = (state, type, text, providerMetadata) => {
1521
+ const last = state.assistantContent.at(-1);
1522
+ if (last?.type === type && text.length === 0) {
1523
+ state.assistantContent[state.assistantContent.length - 1] = {
1524
+ ...last,
1525
+ providerMetadata: mergeProviderMetadata(last.providerMetadata, providerMetadata)
1526
+ };
1527
+ return;
1528
+ }
1529
+ if (last?.type === type && sameProviderMetadata(last.providerMetadata, providerMetadata)) {
1530
+ state.assistantContent[state.assistantContent.length - 1] = { ...last, text: `${last.text}${text}` };
1531
+ return;
1532
+ }
1533
+ state.assistantContent.push({ type, text, providerMetadata });
1534
+ };
1535
+ var isInterruptResult = (result) => result.type === "error" && typeof result.metadata === "object" && result.metadata !== null && result.metadata.kind === "tool-interrupt";
1536
+ var dispatch = (tools, call) => {
1537
+ const tool = tools[call.name];
1538
+ if (!tool) return effect$1.Effect.succeed({ type: "error", value: `Unknown tool: ${call.name}` });
1539
+ if (!tool.execute)
1540
+ return effect$1.Effect.succeed({ type: "error", value: `Tool has no execute handler: ${call.name}` });
1541
+ return decodeAndExecute(tool, call.input).pipe(
1542
+ effect$1.Effect.catchTag(
1543
+ "LLM.ToolFailure",
1544
+ (failure) => effect$1.Effect.succeed({
1545
+ type: "error",
1546
+ value: failure.message,
1547
+ ...failure.metadata ? { metadata: failure.metadata } : {}
1548
+ })
1549
+ )
1550
+ );
1551
+ };
1552
+ var decodeAndExecute = (tool, input) => tool._decode(input).pipe(
1553
+ effect$1.Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
1554
+ effect$1.Effect.flatMap((decoded) => tool.execute(decoded)),
1555
+ effect$1.Effect.flatMap(
1556
+ (value2) => tool._encode(value2).pipe(
1557
+ effect$1.Effect.mapError(
1558
+ (error) => new ToolFailure({
1559
+ message: `Tool returned an invalid value for its success schema: ${error.message}`
1560
+ })
1561
+ )
1562
+ )
1563
+ ),
1564
+ effect$1.Effect.map((encoded) => ({ type: "json", value: encoded }))
1565
+ );
1566
+ var emitEvents = (call, result) => {
1567
+ if (result.type === "error") {
1568
+ if (isInterruptResult(result)) {
1569
+ return [
1570
+ LLMEvent.toolError({
1571
+ id: call.id,
1572
+ name: call.name,
1573
+ message: String(result.value),
1574
+ metadata: result.metadata
1575
+ })
1576
+ ];
1577
+ }
1578
+ return [
1579
+ LLMEvent.toolError({
1580
+ id: call.id,
1581
+ name: call.name,
1582
+ message: String(result.value),
1583
+ metadata: result.metadata
1584
+ }),
1585
+ LLMEvent.toolResult({ id: call.id, name: call.name, result })
1586
+ ];
1587
+ }
1588
+ return [LLMEvent.toolResult({ id: call.id, name: call.name, result })];
1589
+ };
1590
+ var followUpRequest = (request, state, dispatched) => LLMRequest.update(request, {
1591
+ messages: [
1592
+ ...request.messages,
1593
+ Message.assistant(state.assistantContent),
1594
+ ...dispatched.map(([call, result]) => Message.tool({ id: call.id, name: call.name, result }))
1595
+ ]
1596
+ });
1597
+
1598
+ // src/route/client.ts
1599
+ var routeRegistry = /* @__PURE__ */ new Map();
1600
+ var register = (route) => {
1601
+ const existing = routeRegistry.get(route.id);
1602
+ if (existing && existing !== route) throw new Error(`Duplicate LLM route id "${route.id}"`);
1603
+ routeRegistry.set(route.id, route);
1604
+ return route;
1605
+ };
1606
+ var registeredRoute = (id) => routeRegistry.get(id);
1607
+ var modelWithDefaults = (route, defaults, options) => (input) => {
1608
+ const mapped = options.mapInput === void 0 ? input : options.mapInput(input);
1609
+ const provider = defaults.provider ?? route.provider ?? ("provider" in mapped ? mapped.provider : void 0);
1610
+ if (!provider) throw new Error(`Route.model(${route.id}) requires a provider`);
1611
+ const baseURL = mapped.baseURL ?? defaults.baseURL ?? route.defaults.baseURL;
1612
+ if (!baseURL)
1613
+ throw new Error(`Route.model(${route.id}) requires a baseURL \u2014 supply it via input, defaults, or route defaults`);
1614
+ const generation = mergeGenerationOptions(route.defaults.generation, defaults.generation);
1615
+ const providerOptions = mergeProviderOptions(route.defaults.providerOptions, defaults.providerOptions);
1616
+ const http = mergeHttpOptions(httpOptions(route.defaults.http), httpOptions(defaults.http));
1617
+ return modelRef({
1618
+ ...route.defaults,
1619
+ ...defaults,
1620
+ ...mapped,
1621
+ baseURL,
1622
+ provider,
1623
+ route: route.id,
1624
+ limits: mapped.limits ?? defaults.limits ?? route.defaults.limits,
1625
+ generation: mergeGenerationOptions(generation, mapped.generation),
1626
+ providerOptions: mergeProviderOptions(providerOptions, mapped.providerOptions),
1627
+ http: mergeHttpOptions(http, httpOptions(mapped.http))
1628
+ });
1629
+ };
1630
+ var mergeRouteDefaults = (base, patch) => ({
1631
+ ...base,
1632
+ ...patch,
1633
+ limits: patch.limits ?? base?.limits,
1634
+ generation: mergeGenerationOptions(generationOptions(base?.generation), generationOptions(patch.generation)),
1635
+ providerOptions: mergeProviderOptions(base?.providerOptions, patch.providerOptions),
1636
+ http: mergeHttpOptions(httpOptions(base?.http), httpOptions(patch.http))
1637
+ });
1638
+ var modelLimits = ModelLimits.make;
1639
+ var generationOptions = (input) => input === void 0 ? void 0 : GenerationOptions.make(input);
1640
+ var httpOptions = (input) => {
1641
+ if (input === void 0) return input;
1642
+ return HttpOptions.make(input);
1643
+ };
1644
+ var modelRef = (input) => new ModelRef({
1645
+ ...input,
1646
+ id: ModelID.make(input.id),
1647
+ provider: ProviderID.make(input.provider),
1648
+ route: RouteID.make(input.route),
1649
+ limits: modelLimits(input.limits),
1650
+ generation: generationOptions(input.generation),
1651
+ http: httpOptions(input.http)
1652
+ });
1653
+ function model(route, defaults = {}, options = {}) {
1654
+ return modelWithDefaults(route, defaults, options);
1655
+ }
1656
+ var Service2 = class extends effect$1.Context.Service()("@tinyweb-agent/LLMClient") {
1657
+ };
1658
+ var noRoute = (model2) => new LLMError({
1659
+ module: "LLMClient",
1660
+ method: "resolveRoute",
1661
+ reason: new NoRouteReason({ route: model2.route, provider: model2.provider, model: model2.id })
1662
+ });
1663
+ var resolveRequestOptions = (request) => LLMRequest.update(request, {
1664
+ generation: mergeGenerationOptions(request.model.generation, request.generation) ?? new GenerationOptions({}),
1665
+ providerOptions: mergeProviderOptions(request.model.providerOptions, request.providerOptions),
1666
+ http: mergeHttpOptions(request.model.http, request.http)
1667
+ });
1668
+ var streamError = (route, message, cause) => {
1669
+ const failed = cause.reasons.find(effect$1.Cause.isFailReason)?.error;
1670
+ if (failed instanceof LLMError) return failed;
1671
+ return eventError(route, message, effect$1.Cause.pretty(cause));
1672
+ };
1673
+ function makeFromTransport(input) {
1674
+ const protocol = input.protocol;
1675
+ const decodeEventEffect = effect$1.Schema.decodeUnknownEffect(protocol.stream.event);
1676
+ const decodeEvent = (route) => (frame) => decodeEventEffect(frame).pipe(
1677
+ effect$1.Effect.mapError(
1678
+ () => eventError(
1679
+ input.id,
1680
+ `Invalid ${route} stream event`,
1681
+ typeof frame === "string" ? frame : encodeJson(frame)
1682
+ )
1683
+ )
1684
+ );
1685
+ const build = (routeInput) => {
1686
+ const route = {
1687
+ id: routeInput.id,
1688
+ provider: routeInput.provider === void 0 ? void 0 : ProviderID.make(routeInput.provider),
1689
+ protocol: protocol.id,
1690
+ transport: routeInput.transport,
1691
+ defaults: routeInput.defaults ?? {},
1692
+ body: protocol.body,
1693
+ with: (patch) => {
1694
+ const { id, provider, transport, ...defaults } = patch;
1695
+ if (!id || id === routeInput.id) throw new Error(`Route.with(${routeInput.id}) requires a new route id`);
1696
+ return build({
1697
+ ...routeInput,
1698
+ id,
1699
+ provider: provider ?? routeInput.provider,
1700
+ transport: transport ?? routeInput.transport,
1701
+ defaults: mergeRouteDefaults(routeInput.defaults, defaults)
1702
+ });
1703
+ },
1704
+ model: (input2) => modelWithDefaults(route, {}, {})(input2),
1705
+ prepareTransport: routeInput.transport.prepare,
1706
+ streamPrepared: (prepared, request, runtime) => {
1707
+ const route2 = `${request.model.provider}/${request.model.route}`;
1708
+ const events = routeInput.transport.frames(prepared, request, runtime).pipe(
1709
+ effect$1.Stream.mapEffect(decodeEvent(route2)),
1710
+ protocol.stream.terminal ? effect$1.Stream.takeUntil(protocol.stream.terminal) : (stream3) => stream3
1711
+ );
1712
+ return events.pipe(
1713
+ effect$1.Stream.mapAccumEffect(
1714
+ protocol.stream.initial,
1715
+ protocol.stream.step,
1716
+ protocol.stream.onHalt ? { onHalt: protocol.stream.onHalt } : void 0
1717
+ ),
1718
+ effect$1.Stream.catchCause((cause) => effect$1.Stream.fail(streamError(route2, `Failed to read ${route2} stream`, cause)))
1719
+ );
1720
+ }
1721
+ };
1722
+ return register(route);
1723
+ };
1724
+ return build(input);
1725
+ }
1726
+ function make(input) {
1727
+ if ("transport" in input) return makeFromTransport(input);
1728
+ const protocol = input.protocol;
1729
+ const encodeBody = effect$1.Schema.encodeSync(effect$1.Schema.fromJsonString(protocol.body.schema));
1730
+ return makeFromTransport({
1731
+ id: input.id,
1732
+ provider: input.provider,
1733
+ protocol,
1734
+ transport: http_exports.httpJson({
1735
+ endpoint: input.endpoint,
1736
+ auth: input.auth,
1737
+ framing: input.framing,
1738
+ encodeBody,
1739
+ headers: input.headers
1740
+ }),
1741
+ defaults: input.defaults
1742
+ });
1743
+ }
1744
+ var compile = effect$1.Effect.fn("LLM.compile")(function* (request) {
1745
+ const resolved = applyCachePolicy(resolveRequestOptions(request));
1746
+ const route = registeredRoute(resolved.model.route);
1747
+ if (!route) return yield* noRoute(resolved.model);
1748
+ const body = yield* route.body.from(resolved).pipe(effect$1.Effect.flatMap(validateWith(effect$1.Schema.decodeUnknownEffect(route.body.schema))));
1749
+ const prepared = yield* route.prepareTransport(body, resolved);
1750
+ return {
1751
+ request: resolved,
1752
+ route,
1753
+ body,
1754
+ prepared
1755
+ };
1756
+ });
1757
+ var prepareWith = effect$1.Effect.fn("LLMClient.prepare")(function* (request) {
1758
+ const compiled = yield* compile(request);
1759
+ return new PreparedRequest({
1760
+ id: compiled.request.id ?? "request",
1761
+ route: compiled.route.id,
1762
+ protocol: compiled.route.protocol,
1763
+ model: compiled.request.model,
1764
+ body: compiled.body,
1765
+ metadata: { transport: compiled.route.transport.id }
1766
+ });
1767
+ });
1768
+ var streamRequestWith = (runtime) => (request) => effect$1.Stream.unwrap(
1769
+ effect$1.Effect.gen(function* () {
1770
+ const compiled = yield* compile(request);
1771
+ return compiled.route.streamPrepared(compiled.prepared, compiled.request, runtime);
1772
+ })
1773
+ );
1774
+ var isToolRunOptions = (input) => "request" in input && "tools" in input;
1775
+ var streamWith = (streamRequest2) => ((input) => {
1776
+ if (isToolRunOptions(input)) return stream({ ...input, stream: streamRequest2 });
1777
+ return streamRequest2(input);
1778
+ });
1779
+ var generateWith = (stream3) => effect$1.Effect.fn("LLM.generate")(function* (input) {
1780
+ return new LLMResponse(
1781
+ yield* stream3(input).pipe(
1782
+ effect$1.Stream.runFold(
1783
+ () => ({ events: [], usage: void 0 }),
1784
+ (acc, event) => {
1785
+ acc.events.push(event);
1786
+ if ("usage" in event && event.usage !== void 0) acc.usage = event.usage;
1787
+ return acc;
1788
+ }
1789
+ )
1790
+ )
1791
+ );
1792
+ });
1793
+ var prepare = (request) => prepareWith(request);
1794
+ function stream2(input) {
1795
+ return effect$1.Stream.unwrap(
1796
+ effect$1.Effect.gen(function* () {
1797
+ return (yield* Service2).stream(input);
1798
+ })
1799
+ );
1800
+ }
1801
+ function generate(input) {
1802
+ return effect$1.Effect.gen(function* () {
1803
+ return yield* (yield* Service2).generate(input);
1804
+ });
1805
+ }
1806
+ var streamRequest = (request) => effect$1.Stream.unwrap(
1807
+ effect$1.Effect.gen(function* () {
1808
+ return (yield* Service2).stream(request);
1809
+ })
1810
+ );
1811
+ var layer2 = effect$1.Layer.effect(
1812
+ Service2,
1813
+ effect$1.Effect.gen(function* () {
1814
+ const stream3 = streamWith(streamRequestWith({ http: yield* executor_exports.Service }));
1815
+ return Service2.of({ prepare: prepareWith, stream: stream3, generate: generateWith(stream3) });
1816
+ })
1817
+ );
1818
+ var Route = { make, model };
1819
+ var LLMClient = {
1820
+ Service: Service2,
1821
+ layer: layer2,
1822
+ prepare,
1823
+ stream: stream2,
1824
+ generate,
1825
+ stepCountIs,
1826
+ hasToolCall,
1827
+ stopWhenAny
1828
+ };
1829
+
1830
+ exports.LLMClient = LLMClient;
1831
+ exports.Route = Route;
1832
+ exports.Service = Service2;
1833
+ exports.generate = generate;
1834
+ exports.generationOptions = generationOptions;
1835
+ exports.httpOptions = httpOptions;
1836
+ exports.layer = layer2;
1837
+ exports.make = make;
1838
+ exports.modelLimits = modelLimits;
1839
+ exports.modelRef = modelRef;
1840
+ exports.prepare = prepare;
1841
+ exports.stream = stream2;
1842
+ exports.streamRequest = streamRequest;
1843
+ //# sourceMappingURL=client.cjs.map
1844
+ //# sourceMappingURL=client.cjs.map