@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,904 @@
1
+ 'use strict';
2
+
3
+ var buffer = require('buffer');
4
+ var effect = require('effect');
5
+ var Sse = require('effect/unstable/encoding/Sse');
6
+ var http = require('effect/unstable/http');
7
+
8
+ function _interopNamespace(e) {
9
+ if (e && e.__esModule) return e;
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () { return e[k]; }
18
+ });
19
+ }
20
+ });
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
+ }
25
+
26
+ var Sse__namespace = /*#__PURE__*/_interopNamespace(Sse);
27
+
28
+ var __defProp = Object.defineProperty;
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, { get: all[name], enumerable: true });
32
+ };
33
+
34
+ // src/protocols/shared.ts
35
+ var shared_exports = {};
36
+ __export(shared_exports, {
37
+ Json: () => Json,
38
+ JsonObject: () => JsonObject,
39
+ ProviderShared: () => shared_exports,
40
+ decodeJson: () => decodeJson,
41
+ encodeJson: () => encodeJson,
42
+ errorText: () => errorText,
43
+ eventError: () => eventError,
44
+ invalidRequest: () => invalidRequest,
45
+ isRecord: () => isRecord2,
46
+ joinText: () => joinText,
47
+ jsonPost: () => jsonPost,
48
+ matchToolChoice: () => matchToolChoice,
49
+ mediaBytes: () => mediaBytes,
50
+ optionalArray: () => optionalArray,
51
+ optionalNull: () => optionalNull,
52
+ parseJson: () => parseJson,
53
+ parseToolInput: () => parseToolInput,
54
+ sseFraming: () => sseFraming,
55
+ subtractTokens: () => subtractTokens,
56
+ sumTokens: () => sumTokens,
57
+ supportsContent: () => supportsContent,
58
+ toolResultText: () => toolResultText,
59
+ totalTokens: () => totalTokens,
60
+ trimBaseUrl: () => trimBaseUrl,
61
+ unsupportedContent: () => unsupportedContent,
62
+ validateWith: () => validateWith
63
+ });
64
+ var ProtocolID = effect.Schema.String;
65
+ var RouteID = effect.Schema.String;
66
+ var ModelID = effect.Schema.String.pipe(effect.Schema.brand("LLM.ModelID"));
67
+ var ProviderID = effect.Schema.String.pipe(effect.Schema.brand("LLM.ProviderID"));
68
+ var ResponseID = effect.Schema.String;
69
+ var ContentBlockID = effect.Schema.String;
70
+ var ToolCallID = effect.Schema.String;
71
+ var ReasoningEfforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
72
+ effect.Schema.Literals(ReasoningEfforts);
73
+ effect.Schema.Literals(["low", "medium", "high"]);
74
+ var MessageRole = effect.Schema.Literals(["user", "assistant", "tool"]);
75
+ var FinishReason = effect.Schema.Literals(["stop", "length", "tool-calls", "content-filter", "error", "unknown"]);
76
+ var JsonSchema = effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown);
77
+ var ProviderMetadata = effect.Schema.Record(effect.Schema.String, effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown));
78
+ var ProviderOptions = effect.Schema.Record(effect.Schema.String, effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown));
79
+ var HttpOptions = class extends effect.Schema.Class("LLM.HttpOptions")({
80
+ body: effect.Schema.optional(JsonSchema),
81
+ headers: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
82
+ query: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String))
83
+ }) {
84
+ };
85
+ ((HttpOptions2) => {
86
+ HttpOptions2.make = (input) => input instanceof HttpOptions2 ? input : new HttpOptions2(input);
87
+ })(HttpOptions || (HttpOptions = {}));
88
+ var GenerationOptions = class extends effect.Schema.Class("LLM.GenerationOptions")({
89
+ maxTokens: effect.Schema.optional(effect.Schema.Number),
90
+ temperature: effect.Schema.optional(effect.Schema.Number),
91
+ topP: effect.Schema.optional(effect.Schema.Number),
92
+ topK: effect.Schema.optional(effect.Schema.Number),
93
+ frequencyPenalty: effect.Schema.optional(effect.Schema.Number),
94
+ presencePenalty: effect.Schema.optional(effect.Schema.Number),
95
+ seed: effect.Schema.optional(effect.Schema.Number),
96
+ stop: effect.Schema.optional(effect.Schema.Array(effect.Schema.String))
97
+ }) {
98
+ };
99
+ ((GenerationOptions2) => {
100
+ GenerationOptions2.make = (input = {}) => input instanceof GenerationOptions2 ? input : new GenerationOptions2(input);
101
+ })(GenerationOptions || (GenerationOptions = {}));
102
+ var ModelLimits = class extends effect.Schema.Class("LLM.ModelLimits")({
103
+ context: effect.Schema.optional(effect.Schema.Number),
104
+ output: effect.Schema.optional(effect.Schema.Number)
105
+ }) {
106
+ };
107
+ ((ModelLimits2) => {
108
+ ModelLimits2.make = (input) => input instanceof ModelLimits2 ? input : new ModelLimits2(input ?? {});
109
+ })(ModelLimits || (ModelLimits = {}));
110
+ var ModelRef = class extends effect.Schema.Class("LLM.ModelRef")({
111
+ id: ModelID,
112
+ provider: ProviderID,
113
+ route: RouteID,
114
+ baseURL: effect.Schema.String,
115
+ /** Provider-specific API key convenience. Provider helpers normalize this into `auth`. */
116
+ apiKey: effect.Schema.optional(effect.Schema.String),
117
+ /** Optional transport auth policy. Opaque because it may contain functions. */
118
+ auth: effect.Schema.optional(effect.Schema.Any),
119
+ headers: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
120
+ /**
121
+ * Query params appended to the request URL by `Endpoint.baseURL`. Used for
122
+ * deployment-level URL-scoped settings such as Azure's `api-version` or any
123
+ * provider that requires a per-request key in the URL. Generic concern, so
124
+ * lives as a typed first-class field instead of `native`.
125
+ */
126
+ queryParams: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
127
+ limits: ModelLimits,
128
+ /** Provider-neutral generation defaults. Request-level values override them. */
129
+ generation: effect.Schema.optional(GenerationOptions),
130
+ /** Provider-owned typed-at-the-facade options for non-portable knobs. */
131
+ providerOptions: effect.Schema.optional(ProviderOptions),
132
+ /** Serializable raw HTTP overlays applied to the final outgoing request. */
133
+ http: effect.Schema.optional(HttpOptions),
134
+ /**
135
+ * Provider-specific opaque options. Reach for this only when the value is
136
+ * genuinely provider-private and does not fit a typed axis (e.g. Bedrock's
137
+ * `aws_credentials` / `aws_region` for SigV4). Anything used by more than
138
+ * one route should grow into a typed field instead.
139
+ */
140
+ native: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
141
+ }) {
142
+ };
143
+ ((ModelRef2) => {
144
+ ModelRef2.input = (model) => ({
145
+ id: model.id,
146
+ provider: model.provider,
147
+ route: model.route,
148
+ baseURL: model.baseURL,
149
+ apiKey: model.apiKey,
150
+ auth: model.auth,
151
+ headers: model.headers,
152
+ queryParams: model.queryParams,
153
+ limits: model.limits,
154
+ generation: model.generation,
155
+ providerOptions: model.providerOptions,
156
+ http: model.http,
157
+ native: model.native
158
+ });
159
+ ModelRef2.update = (model, patch) => {
160
+ if (Object.keys(patch).length === 0) return model;
161
+ return new ModelRef2({
162
+ ...(0, ModelRef2.input)(model),
163
+ ...patch
164
+ });
165
+ };
166
+ })(ModelRef || (ModelRef = {}));
167
+ var CacheHint = class extends effect.Schema.Class("LLM.CacheHint")({
168
+ type: effect.Schema.Literals(["ephemeral", "persistent"]),
169
+ ttlSeconds: effect.Schema.optional(effect.Schema.Number)
170
+ }) {
171
+ };
172
+ var CachePolicyObject = effect.Schema.Struct({
173
+ tools: effect.Schema.optional(effect.Schema.Boolean),
174
+ system: effect.Schema.optional(effect.Schema.Boolean),
175
+ messages: effect.Schema.optional(
176
+ effect.Schema.Union([
177
+ effect.Schema.Literal("latest-user-message"),
178
+ effect.Schema.Literal("latest-assistant"),
179
+ effect.Schema.Struct({ tail: effect.Schema.Number })
180
+ ])
181
+ ),
182
+ ttlSeconds: effect.Schema.optional(effect.Schema.Number)
183
+ });
184
+ var CachePolicy = effect.Schema.Union([effect.Schema.Literal("auto"), effect.Schema.Literal("none"), CachePolicyObject]);
185
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
186
+ var systemPartSchema = effect.Schema.Struct({
187
+ type: effect.Schema.Literal("text"),
188
+ text: effect.Schema.String,
189
+ cache: effect.Schema.optional(CacheHint),
190
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
191
+ }).annotate({ identifier: "LLM.SystemPart" });
192
+ var makeSystemPart = (text) => ({ type: "text", text });
193
+ var SystemPart = Object.assign(systemPartSchema, {
194
+ make: makeSystemPart,
195
+ content: (input) => {
196
+ if (input === void 0) return [];
197
+ return typeof input === "string" ? [makeSystemPart(input)] : Array.isArray(input) ? [...input] : [input];
198
+ }
199
+ });
200
+ var TextPart = effect.Schema.Struct({
201
+ type: effect.Schema.Literal("text"),
202
+ text: effect.Schema.String,
203
+ cache: effect.Schema.optional(CacheHint),
204
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
205
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
206
+ }).annotate({ identifier: "LLM.Content.Text" });
207
+ var MediaPart = effect.Schema.Struct({
208
+ type: effect.Schema.Literal("media"),
209
+ mediaType: effect.Schema.String,
210
+ data: effect.Schema.Union([effect.Schema.String, effect.Schema.Uint8Array]),
211
+ filename: effect.Schema.optional(effect.Schema.String),
212
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
213
+ }).annotate({ identifier: "LLM.Content.Media" });
214
+ var isToolResultValue = (value) => isRecord(value) && (value.type === "text" || value.type === "json" || value.type === "error") && "value" in value;
215
+ var ToolResultValue = Object.assign(
216
+ effect.Schema.Struct({
217
+ type: effect.Schema.Literals(["json", "text", "error"]),
218
+ value: effect.Schema.Unknown,
219
+ /** Optional structured payload (e.g. tool-interrupt metadata). */
220
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
221
+ }).annotate({ identifier: "LLM.ToolResult" }),
222
+ {
223
+ make: (value, type = "json", metadata) => {
224
+ if (isToolResultValue(value)) {
225
+ return metadata ? { ...value, metadata: { ...value.metadata ?? {}, ...metadata } } : value;
226
+ }
227
+ return metadata ? { type, value, metadata } : { type, value };
228
+ }
229
+ }
230
+ );
231
+ var ToolCallPart = Object.assign(
232
+ effect.Schema.Struct({
233
+ type: effect.Schema.Literal("tool-call"),
234
+ id: effect.Schema.String,
235
+ name: effect.Schema.String,
236
+ input: effect.Schema.Unknown,
237
+ providerExecuted: effect.Schema.optional(effect.Schema.Boolean),
238
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
239
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
240
+ }).annotate({ identifier: "LLM.Content.ToolCall" }),
241
+ {
242
+ make: (input) => ({ type: "tool-call", ...input })
243
+ }
244
+ );
245
+ var ToolResultPart = Object.assign(
246
+ effect.Schema.Struct({
247
+ type: effect.Schema.Literal("tool-result"),
248
+ id: effect.Schema.String,
249
+ name: effect.Schema.String,
250
+ result: ToolResultValue,
251
+ providerExecuted: effect.Schema.optional(effect.Schema.Boolean),
252
+ cache: effect.Schema.optional(CacheHint),
253
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
254
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
255
+ }).annotate({ identifier: "LLM.Content.ToolResult" }),
256
+ {
257
+ make: (input) => ({
258
+ type: "tool-result",
259
+ id: input.id,
260
+ name: input.name,
261
+ result: ToolResultValue.make(input.result, input.resultType),
262
+ providerExecuted: input.providerExecuted,
263
+ cache: input.cache,
264
+ metadata: input.metadata,
265
+ providerMetadata: input.providerMetadata
266
+ })
267
+ }
268
+ );
269
+ var ReasoningPart = effect.Schema.Struct({
270
+ type: effect.Schema.Literal("reasoning"),
271
+ text: effect.Schema.String,
272
+ encrypted: effect.Schema.optional(effect.Schema.String),
273
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
274
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
275
+ }).annotate({ identifier: "LLM.Content.Reasoning" });
276
+ var ContentPart = effect.Schema.Union([TextPart, MediaPart, ToolCallPart, ToolResultPart, ReasoningPart]).pipe(
277
+ effect.Schema.toTaggedUnion("type")
278
+ );
279
+ var Message = class extends effect.Schema.Class("LLM.Message")({
280
+ id: effect.Schema.optional(effect.Schema.String),
281
+ role: MessageRole,
282
+ content: effect.Schema.Array(ContentPart),
283
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
284
+ native: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
285
+ }) {
286
+ };
287
+ ((Message2) => {
288
+ Message2.text = (value) => ({ type: "text", text: value });
289
+ Message2.content = (input) => typeof input === "string" ? [(0, Message2.text)(input)] : Array.isArray(input) ? [...input] : [input];
290
+ Message2.make = (input) => {
291
+ if (input instanceof Message2) return input;
292
+ return new Message2({ ...input, content: (0, Message2.content)(input.content) });
293
+ };
294
+ Message2.user = (content2) => (0, Message2.make)({ role: "user", content: content2 });
295
+ Message2.assistant = (content2) => (0, Message2.make)({ role: "assistant", content: content2 });
296
+ Message2.tool = (result) => (0, Message2.make)({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] });
297
+ })(Message || (Message = {}));
298
+ var ToolDefinition = class extends effect.Schema.Class("LLM.ToolDefinition")({
299
+ name: effect.Schema.String,
300
+ description: effect.Schema.String,
301
+ inputSchema: JsonSchema,
302
+ cache: effect.Schema.optional(CacheHint),
303
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
304
+ native: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
305
+ }) {
306
+ };
307
+ ((ToolDefinition2) => {
308
+ ToolDefinition2.make = (input) => input instanceof ToolDefinition2 ? input : new ToolDefinition2(input);
309
+ })(ToolDefinition || (ToolDefinition = {}));
310
+ var ToolChoice = class extends effect.Schema.Class("LLM.ToolChoice")({
311
+ type: effect.Schema.Literals(["auto", "none", "required", "tool"]),
312
+ name: effect.Schema.optional(effect.Schema.String)
313
+ }) {
314
+ };
315
+ ((ToolChoice2) => {
316
+ const isMode = (value) => value === "auto" || value === "none" || value === "required";
317
+ ToolChoice2.named = (value) => new ToolChoice2({ type: "tool", name: value });
318
+ ToolChoice2.make = (input) => {
319
+ if (input instanceof ToolChoice2) return input;
320
+ if (input instanceof ToolDefinition) return (0, ToolChoice2.named)(input.name);
321
+ if (typeof input === "string") return isMode(input) ? new ToolChoice2({ type: input }) : (0, ToolChoice2.named)(input);
322
+ return new ToolChoice2(input);
323
+ };
324
+ })(ToolChoice || (ToolChoice = {}));
325
+ var ResponseFormat = effect.Schema.Union([
326
+ effect.Schema.Struct({ type: effect.Schema.Literal("text") }),
327
+ effect.Schema.Struct({ type: effect.Schema.Literal("json"), schema: JsonSchema }),
328
+ effect.Schema.Struct({ type: effect.Schema.Literal("tool"), tool: ToolDefinition })
329
+ ]).pipe(effect.Schema.toTaggedUnion("type"));
330
+ var LLMRequest = class extends effect.Schema.Class("LLM.Request")({
331
+ id: effect.Schema.optional(effect.Schema.String),
332
+ model: ModelRef,
333
+ system: effect.Schema.Array(SystemPart),
334
+ messages: effect.Schema.Array(Message),
335
+ tools: effect.Schema.Array(ToolDefinition),
336
+ toolChoice: effect.Schema.optional(ToolChoice),
337
+ generation: effect.Schema.optional(GenerationOptions),
338
+ providerOptions: effect.Schema.optional(ProviderOptions),
339
+ http: effect.Schema.optional(HttpOptions),
340
+ responseFormat: effect.Schema.optional(ResponseFormat),
341
+ cache: effect.Schema.optional(CachePolicy),
342
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
343
+ }) {
344
+ };
345
+ ((LLMRequest2) => {
346
+ LLMRequest2.input = (request) => ({
347
+ id: request.id,
348
+ model: request.model,
349
+ system: request.system,
350
+ messages: request.messages,
351
+ tools: request.tools,
352
+ toolChoice: request.toolChoice,
353
+ generation: request.generation,
354
+ providerOptions: request.providerOptions,
355
+ http: request.http,
356
+ responseFormat: request.responseFormat,
357
+ cache: request.cache,
358
+ metadata: request.metadata
359
+ });
360
+ LLMRequest2.update = (request, patch) => {
361
+ if (Object.keys(patch).length === 0) return request;
362
+ return new LLMRequest2({
363
+ ...(0, LLMRequest2.input)(request),
364
+ ...patch,
365
+ model: patch.model ?? request.model
366
+ });
367
+ };
368
+ })(LLMRequest || (LLMRequest = {}));
369
+ var Usage = class extends effect.Schema.Class("LLM.Usage")({
370
+ inputTokens: effect.Schema.optional(effect.Schema.Number),
371
+ outputTokens: effect.Schema.optional(effect.Schema.Number),
372
+ nonCachedInputTokens: effect.Schema.optional(effect.Schema.Number),
373
+ cacheReadInputTokens: effect.Schema.optional(effect.Schema.Number),
374
+ cacheWriteInputTokens: effect.Schema.optional(effect.Schema.Number),
375
+ reasoningTokens: effect.Schema.optional(effect.Schema.Number),
376
+ totalTokens: effect.Schema.optional(effect.Schema.Number),
377
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
378
+ }) {
379
+ /**
380
+ * Visible output tokens — `outputTokens` minus `reasoningTokens`, clamped
381
+ * to zero. The one place subtraction happens in this contract; the clamp
382
+ * means a provider reporting `reasoningTokens > outputTokens` produces a
383
+ * harmless zero rather than a negative that crashes downstream schemas.
384
+ */
385
+ get visibleOutputTokens() {
386
+ return Math.max(0, (this.outputTokens ?? 0) - (this.reasoningTokens ?? 0));
387
+ }
388
+ };
389
+ var RequestStart = effect.Schema.Struct({
390
+ type: effect.Schema.tag("request-start"),
391
+ id: ResponseID,
392
+ model: ModelRef
393
+ }).annotate({ identifier: "LLM.Event.RequestStart" });
394
+ var StepStart = effect.Schema.Struct({
395
+ type: effect.Schema.tag("step-start"),
396
+ index: effect.Schema.Number
397
+ }).annotate({ identifier: "LLM.Event.StepStart" });
398
+ var TextStart = effect.Schema.Struct({
399
+ type: effect.Schema.tag("text-start"),
400
+ id: ContentBlockID,
401
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
402
+ }).annotate({ identifier: "LLM.Event.TextStart" });
403
+ var TextDelta = effect.Schema.Struct({
404
+ type: effect.Schema.tag("text-delta"),
405
+ id: ContentBlockID,
406
+ text: effect.Schema.String
407
+ }).annotate({ identifier: "LLM.Event.TextDelta" });
408
+ var TextEnd = effect.Schema.Struct({
409
+ type: effect.Schema.tag("text-end"),
410
+ id: ContentBlockID,
411
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
412
+ }).annotate({ identifier: "LLM.Event.TextEnd" });
413
+ var ReasoningStart = effect.Schema.Struct({
414
+ type: effect.Schema.tag("reasoning-start"),
415
+ id: ContentBlockID,
416
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
417
+ }).annotate({ identifier: "LLM.Event.ReasoningStart" });
418
+ var ReasoningDelta = effect.Schema.Struct({
419
+ type: effect.Schema.tag("reasoning-delta"),
420
+ id: ContentBlockID,
421
+ text: effect.Schema.String
422
+ }).annotate({ identifier: "LLM.Event.ReasoningDelta" });
423
+ var ReasoningEnd = effect.Schema.Struct({
424
+ type: effect.Schema.tag("reasoning-end"),
425
+ id: ContentBlockID,
426
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
427
+ }).annotate({ identifier: "LLM.Event.ReasoningEnd" });
428
+ var ToolInputStart = effect.Schema.Struct({
429
+ type: effect.Schema.tag("tool-input-start"),
430
+ id: ToolCallID,
431
+ name: effect.Schema.String,
432
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
433
+ }).annotate({ identifier: "LLM.Event.ToolInputStart" });
434
+ var ToolInputDelta = effect.Schema.Struct({
435
+ type: effect.Schema.tag("tool-input-delta"),
436
+ id: ToolCallID,
437
+ name: effect.Schema.String,
438
+ text: effect.Schema.String
439
+ }).annotate({ identifier: "LLM.Event.ToolInputDelta" });
440
+ var ToolInputEnd = effect.Schema.Struct({
441
+ type: effect.Schema.tag("tool-input-end"),
442
+ id: ToolCallID,
443
+ name: effect.Schema.String,
444
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
445
+ }).annotate({ identifier: "LLM.Event.ToolInputEnd" });
446
+ var ToolCall = effect.Schema.Struct({
447
+ type: effect.Schema.tag("tool-call"),
448
+ id: ToolCallID,
449
+ name: effect.Schema.String,
450
+ input: effect.Schema.Unknown,
451
+ providerExecuted: effect.Schema.optional(effect.Schema.Boolean),
452
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
453
+ }).annotate({ identifier: "LLM.Event.ToolCall" });
454
+ var ToolResult = effect.Schema.Struct({
455
+ type: effect.Schema.tag("tool-result"),
456
+ id: ToolCallID,
457
+ name: effect.Schema.String,
458
+ result: ToolResultValue,
459
+ providerExecuted: effect.Schema.optional(effect.Schema.Boolean),
460
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
461
+ }).annotate({ identifier: "LLM.Event.ToolResult" });
462
+ var ToolError = effect.Schema.Struct({
463
+ type: effect.Schema.tag("tool-error"),
464
+ id: ToolCallID,
465
+ name: effect.Schema.String,
466
+ message: effect.Schema.String,
467
+ /** Optional structured payload (e.g. tool-interrupt metadata for approval). */
468
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
469
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
470
+ }).annotate({ identifier: "LLM.Event.ToolError" });
471
+ var StepFinish = effect.Schema.Struct({
472
+ type: effect.Schema.tag("step-finish"),
473
+ index: effect.Schema.Number,
474
+ reason: FinishReason,
475
+ usage: effect.Schema.optional(Usage),
476
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
477
+ }).annotate({ identifier: "LLM.Event.StepFinish" });
478
+ var RequestFinish = effect.Schema.Struct({
479
+ type: effect.Schema.tag("request-finish"),
480
+ reason: FinishReason,
481
+ usage: effect.Schema.optional(Usage),
482
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
483
+ }).annotate({ identifier: "LLM.Event.RequestFinish" });
484
+ var ProviderErrorEvent = effect.Schema.Struct({
485
+ type: effect.Schema.tag("provider-error"),
486
+ message: effect.Schema.String,
487
+ retryable: effect.Schema.optional(effect.Schema.Boolean),
488
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
489
+ }).annotate({ identifier: "LLM.Event.ProviderError" });
490
+ var llmEventTagged = effect.Schema.Union([
491
+ RequestStart,
492
+ StepStart,
493
+ TextStart,
494
+ TextDelta,
495
+ TextEnd,
496
+ ReasoningStart,
497
+ ReasoningDelta,
498
+ ReasoningEnd,
499
+ ToolInputStart,
500
+ ToolInputDelta,
501
+ ToolInputEnd,
502
+ ToolCall,
503
+ ToolResult,
504
+ ToolError,
505
+ StepFinish,
506
+ RequestFinish,
507
+ ProviderErrorEvent
508
+ ]).pipe(effect.Schema.toTaggedUnion("type"));
509
+ var responseID = (value) => ResponseID.make(value);
510
+ var contentBlockID = (value) => ContentBlockID.make(value);
511
+ var toolCallID = (value) => ToolCallID.make(value);
512
+ var LLMEvent = Object.assign(llmEventTagged, {
513
+ requestStart: (input) => RequestStart.make({ ...input, id: responseID(input.id) }),
514
+ stepStart: StepStart.make,
515
+ textStart: (input) => TextStart.make({ ...input, id: contentBlockID(input.id) }),
516
+ textDelta: (input) => TextDelta.make({ ...input, id: contentBlockID(input.id) }),
517
+ textEnd: (input) => TextEnd.make({ ...input, id: contentBlockID(input.id) }),
518
+ reasoningStart: (input) => ReasoningStart.make({ ...input, id: contentBlockID(input.id) }),
519
+ reasoningDelta: (input) => ReasoningDelta.make({ ...input, id: contentBlockID(input.id) }),
520
+ reasoningEnd: (input) => ReasoningEnd.make({ ...input, id: contentBlockID(input.id) }),
521
+ toolInputStart: (input) => ToolInputStart.make({ ...input, id: toolCallID(input.id) }),
522
+ toolInputDelta: (input) => ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
523
+ toolInputEnd: (input) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
524
+ toolCall: (input) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
525
+ toolResult: (input) => ToolResult.make({ ...input, id: toolCallID(input.id) }),
526
+ toolError: (input) => ToolError.make({ ...input, id: toolCallID(input.id) }),
527
+ stepFinish: StepFinish.make,
528
+ requestFinish: RequestFinish.make,
529
+ providerError: ProviderErrorEvent.make,
530
+ is: {
531
+ requestStart: llmEventTagged.guards["request-start"],
532
+ stepStart: llmEventTagged.guards["step-start"],
533
+ textStart: llmEventTagged.guards["text-start"],
534
+ textDelta: llmEventTagged.guards["text-delta"],
535
+ textEnd: llmEventTagged.guards["text-end"],
536
+ reasoningStart: llmEventTagged.guards["reasoning-start"],
537
+ reasoningDelta: llmEventTagged.guards["reasoning-delta"],
538
+ reasoningEnd: llmEventTagged.guards["reasoning-end"],
539
+ toolInputStart: llmEventTagged.guards["tool-input-start"],
540
+ toolInputDelta: llmEventTagged.guards["tool-input-delta"],
541
+ toolInputEnd: llmEventTagged.guards["tool-input-end"],
542
+ toolCall: llmEventTagged.guards["tool-call"],
543
+ toolResult: llmEventTagged.guards["tool-result"],
544
+ toolError: llmEventTagged.guards["tool-error"],
545
+ stepFinish: llmEventTagged.guards["step-finish"],
546
+ requestFinish: llmEventTagged.guards["request-finish"],
547
+ providerError: llmEventTagged.guards["provider-error"]
548
+ }
549
+ });
550
+ (class extends effect.Schema.Class("LLM.PreparedRequest")({
551
+ id: effect.Schema.String,
552
+ route: RouteID,
553
+ protocol: ProtocolID,
554
+ model: ModelRef,
555
+ body: effect.Schema.Unknown,
556
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
557
+ }) {
558
+ });
559
+ var responseText = (events) => events.filter(LLMEvent.is.textDelta).map((event) => event.text).join("");
560
+ var responseReasoning = (events) => events.filter(LLMEvent.is.reasoningDelta).map((event) => event.text).join("");
561
+ var responseUsage = (events) => events.reduce(
562
+ (usage, event) => "usage" in event && event.usage !== void 0 ? event.usage : usage,
563
+ void 0
564
+ );
565
+ var LLMResponse = class extends effect.Schema.Class("LLM.Response")({
566
+ events: effect.Schema.Array(LLMEvent),
567
+ usage: effect.Schema.optional(Usage)
568
+ }) {
569
+ /** Concatenated assistant text assembled from streamed `text-delta` events. */
570
+ get text() {
571
+ return responseText(this.events);
572
+ }
573
+ /** Concatenated reasoning text assembled from streamed `reasoning-delta` events. */
574
+ get reasoning() {
575
+ return responseReasoning(this.events);
576
+ }
577
+ /** Completed tool calls emitted by the provider. */
578
+ get toolCalls() {
579
+ return this.events.filter(LLMEvent.is.toolCall);
580
+ }
581
+ };
582
+ ((LLMResponse2) => {
583
+ LLMResponse2.text = (response) => responseText(response.events);
584
+ LLMResponse2.usage = (response) => response.usage ?? responseUsage(response.events);
585
+ LLMResponse2.toolCalls = (response) => response.events.filter(LLMEvent.is.toolCall);
586
+ LLMResponse2.reasoning = (response) => responseReasoning(response.events);
587
+ })(LLMResponse || (LLMResponse = {}));
588
+ var HttpRequestDetails = class extends effect.Schema.Class("LLM.HttpRequestDetails")({
589
+ method: effect.Schema.String,
590
+ url: effect.Schema.String,
591
+ headers: effect.Schema.Record(effect.Schema.String, effect.Schema.String)
592
+ }) {
593
+ };
594
+ var HttpResponseDetails = class extends effect.Schema.Class("LLM.HttpResponseDetails")({
595
+ status: effect.Schema.Number,
596
+ headers: effect.Schema.Record(effect.Schema.String, effect.Schema.String)
597
+ }) {
598
+ };
599
+ var HttpRateLimitDetails = class extends effect.Schema.Class("LLM.HttpRateLimitDetails")({
600
+ retryAfterMs: effect.Schema.optional(effect.Schema.Number),
601
+ limit: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
602
+ remaining: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
603
+ reset: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String))
604
+ }) {
605
+ };
606
+ var HttpContext = class extends effect.Schema.Class("LLM.HttpContext")({
607
+ request: HttpRequestDetails,
608
+ response: effect.Schema.optional(HttpResponseDetails),
609
+ body: effect.Schema.optional(effect.Schema.String),
610
+ bodyTruncated: effect.Schema.optional(effect.Schema.Boolean),
611
+ requestId: effect.Schema.optional(effect.Schema.String),
612
+ rateLimit: effect.Schema.optional(HttpRateLimitDetails)
613
+ }) {
614
+ };
615
+ var InvalidRequestReason = class extends effect.Schema.Class("LLM.Error.InvalidRequest")({
616
+ _tag: effect.Schema.tag("InvalidRequest"),
617
+ message: effect.Schema.String,
618
+ parameter: effect.Schema.optional(effect.Schema.String),
619
+ providerMetadata: effect.Schema.optional(ProviderMetadata),
620
+ http: effect.Schema.optional(HttpContext)
621
+ }) {
622
+ get retryable() {
623
+ return false;
624
+ }
625
+ };
626
+ var ContextOverflowReason = class extends effect.Schema.Class("LLM.Error.ContextOverflow")({
627
+ _tag: effect.Schema.tag("ContextOverflow"),
628
+ message: effect.Schema.String,
629
+ /** Provider-reported prompt token count when present in the error body. */
630
+ promptTokens: effect.Schema.optional(effect.Schema.Number),
631
+ /** Provider-reported context window size when present in the error body. */
632
+ contextWindow: effect.Schema.optional(effect.Schema.Number),
633
+ providerMetadata: effect.Schema.optional(ProviderMetadata),
634
+ http: effect.Schema.optional(HttpContext)
635
+ }) {
636
+ get retryable() {
637
+ return false;
638
+ }
639
+ };
640
+ var NoRouteReason = class extends effect.Schema.Class("LLM.Error.NoRoute")({
641
+ _tag: effect.Schema.tag("NoRoute"),
642
+ route: RouteID,
643
+ provider: ProviderID,
644
+ model: ModelID
645
+ }) {
646
+ get retryable() {
647
+ return false;
648
+ }
649
+ get message() {
650
+ return `No LLM route for ${this.provider}/${this.model} using ${this.route}`;
651
+ }
652
+ };
653
+ var AuthenticationReason = class extends effect.Schema.Class("LLM.Error.Authentication")({
654
+ _tag: effect.Schema.tag("Authentication"),
655
+ message: effect.Schema.String,
656
+ kind: effect.Schema.Literals(["missing", "invalid", "expired", "insufficient-permissions", "unknown"]),
657
+ providerMetadata: effect.Schema.optional(ProviderMetadata),
658
+ http: effect.Schema.optional(HttpContext)
659
+ }) {
660
+ get retryable() {
661
+ return false;
662
+ }
663
+ };
664
+ var RateLimitReason = class extends effect.Schema.Class("LLM.Error.RateLimit")({
665
+ _tag: effect.Schema.tag("RateLimit"),
666
+ message: effect.Schema.String,
667
+ retryAfterMs: effect.Schema.optional(effect.Schema.Number),
668
+ rateLimit: effect.Schema.optional(HttpRateLimitDetails),
669
+ providerMetadata: effect.Schema.optional(ProviderMetadata),
670
+ http: effect.Schema.optional(HttpContext)
671
+ }) {
672
+ get retryable() {
673
+ return true;
674
+ }
675
+ };
676
+ var QuotaExceededReason = class extends effect.Schema.Class("LLM.Error.QuotaExceeded")({
677
+ _tag: effect.Schema.tag("QuotaExceeded"),
678
+ message: effect.Schema.String,
679
+ providerMetadata: effect.Schema.optional(ProviderMetadata),
680
+ http: effect.Schema.optional(HttpContext)
681
+ }) {
682
+ get retryable() {
683
+ return false;
684
+ }
685
+ };
686
+ var ContentPolicyReason = class extends effect.Schema.Class("LLM.Error.ContentPolicy")({
687
+ _tag: effect.Schema.tag("ContentPolicy"),
688
+ message: effect.Schema.String,
689
+ providerMetadata: effect.Schema.optional(ProviderMetadata),
690
+ http: effect.Schema.optional(HttpContext)
691
+ }) {
692
+ get retryable() {
693
+ return false;
694
+ }
695
+ };
696
+ var ProviderInternalReason = class extends effect.Schema.Class("LLM.Error.ProviderInternal")({
697
+ _tag: effect.Schema.tag("ProviderInternal"),
698
+ message: effect.Schema.String,
699
+ status: effect.Schema.Number,
700
+ retryAfterMs: effect.Schema.optional(effect.Schema.Number),
701
+ providerMetadata: effect.Schema.optional(ProviderMetadata),
702
+ http: effect.Schema.optional(HttpContext)
703
+ }) {
704
+ get retryable() {
705
+ return true;
706
+ }
707
+ };
708
+ var TransportReason = class extends effect.Schema.Class("LLM.Error.Transport")({
709
+ _tag: effect.Schema.tag("Transport"),
710
+ message: effect.Schema.String,
711
+ kind: effect.Schema.optional(effect.Schema.String),
712
+ url: effect.Schema.optional(effect.Schema.String),
713
+ http: effect.Schema.optional(HttpContext)
714
+ }) {
715
+ get retryable() {
716
+ return false;
717
+ }
718
+ };
719
+ var InvalidProviderOutputReason = class extends effect.Schema.Class(
720
+ "LLM.Error.InvalidProviderOutput"
721
+ )({
722
+ _tag: effect.Schema.tag("InvalidProviderOutput"),
723
+ message: effect.Schema.String,
724
+ route: effect.Schema.optional(effect.Schema.String),
725
+ raw: effect.Schema.optional(effect.Schema.String),
726
+ providerMetadata: effect.Schema.optional(ProviderMetadata)
727
+ }) {
728
+ get retryable() {
729
+ return false;
730
+ }
731
+ };
732
+ var UnknownProviderReason = class extends effect.Schema.Class("LLM.Error.UnknownProvider")({
733
+ _tag: effect.Schema.tag("UnknownProvider"),
734
+ message: effect.Schema.String,
735
+ status: effect.Schema.optional(effect.Schema.Number),
736
+ providerMetadata: effect.Schema.optional(ProviderMetadata),
737
+ http: effect.Schema.optional(HttpContext)
738
+ }) {
739
+ get retryable() {
740
+ return false;
741
+ }
742
+ };
743
+ var LLMErrorReason = effect.Schema.Union([
744
+ InvalidRequestReason,
745
+ ContextOverflowReason,
746
+ NoRouteReason,
747
+ AuthenticationReason,
748
+ RateLimitReason,
749
+ QuotaExceededReason,
750
+ ContentPolicyReason,
751
+ ProviderInternalReason,
752
+ TransportReason,
753
+ InvalidProviderOutputReason,
754
+ UnknownProviderReason
755
+ ]).pipe(effect.Schema.toTaggedUnion("_tag"));
756
+ var LLMError = class extends effect.Schema.TaggedErrorClass()("LLM.Error", {
757
+ module: effect.Schema.String,
758
+ method: effect.Schema.String,
759
+ reason: LLMErrorReason
760
+ }) {
761
+ cause = this.reason;
762
+ get retryable() {
763
+ return this.reason.retryable;
764
+ }
765
+ get retryAfterMs() {
766
+ return "retryAfterMs" in this.reason ? this.reason.retryAfterMs : void 0;
767
+ }
768
+ get message() {
769
+ return `${this.module}.${this.method}: ${this.reason.message}`;
770
+ }
771
+ };
772
+ (class extends effect.Schema.TaggedErrorClass()("LLM.ToolFailure", {
773
+ message: effect.Schema.String,
774
+ metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
775
+ }) {
776
+ });
777
+
778
+ // src/protocols/shared.ts
779
+ var Json = effect.Schema.fromJsonString(effect.Schema.Unknown);
780
+ var decodeJson = effect.Schema.decodeUnknownSync(Json);
781
+ var encodeJson = effect.Schema.encodeSync(Json);
782
+ var JsonObject = effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown);
783
+ var optionalArray = (schema) => effect.Schema.optional(effect.Schema.Array(schema));
784
+ var optionalNull = (schema) => effect.Schema.optional(effect.Schema.NullOr(schema));
785
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
786
+ var totalTokens = (inputTokens, outputTokens, total) => {
787
+ if (total !== void 0) return total;
788
+ if (inputTokens === void 0 && outputTokens === void 0) return void 0;
789
+ return (inputTokens ?? 0) + (outputTokens ?? 0);
790
+ };
791
+ var subtractTokens = (total, subtrahend) => {
792
+ if (total === void 0) return void 0;
793
+ if (subtrahend === void 0) return total;
794
+ return Math.max(0, total - subtrahend);
795
+ };
796
+ var sumTokens = (...values) => {
797
+ if (values.every((value) => value === void 0)) return void 0;
798
+ return values.reduce((acc, value) => acc + (value ?? 0), 0);
799
+ };
800
+ var eventError = (route, message, raw) => new LLMError({
801
+ module: "ProviderShared",
802
+ method: "stream",
803
+ reason: new InvalidProviderOutputReason({ route, message, raw })
804
+ });
805
+ var parseJson = (route, input, message) => effect.Effect.try({
806
+ try: () => decodeJson(input),
807
+ catch: () => eventError(route, message, input)
808
+ });
809
+ var joinText = (parts) => parts.map((part) => part.text).join("\n");
810
+ var parseToolInput = (route, name, raw) => parseJson(route, raw || "{}", `Invalid JSON input for ${route} tool call ${name}`);
811
+ var mediaBytes = (part) => typeof part.data === "string" ? part.data : buffer.Buffer.from(part.data).toString("base64");
812
+ var trimBaseUrl = (value) => value.replace(/\/+$/, "");
813
+ var IMAGE_BASE64_FIELDS = /* @__PURE__ */ new Set(["imageBase64", "base64", "data"]);
814
+ var isImageResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.mimeType === "string" && value.mimeType.startsWith("image/");
815
+ var redactImagePayload = (value) => {
816
+ if (Array.isArray(value)) return value.map(redactImagePayload);
817
+ if (!value || typeof value !== "object") return value;
818
+ if (isImageResult(value)) {
819
+ const out2 = {};
820
+ for (const [k, v] of Object.entries(value)) {
821
+ if (IMAGE_BASE64_FIELDS.has(k) && typeof v === "string") {
822
+ out2[k] = `<image elided; ${v.length} chars base64 already shown to user>`;
823
+ continue;
824
+ }
825
+ out2[k] = v;
826
+ }
827
+ return out2;
828
+ }
829
+ const out = {};
830
+ for (const [k, v] of Object.entries(value)) out[k] = redactImagePayload(v);
831
+ return out;
832
+ };
833
+ var toolResultText = (part) => {
834
+ if (part.result.type === "text" || part.result.type === "error") return String(part.result.value);
835
+ return encodeJson(redactImagePayload(part.result.value));
836
+ };
837
+ var errorText = (error) => {
838
+ if (error instanceof Error) return error.message;
839
+ if (typeof error === "string") return error;
840
+ if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") return String(error);
841
+ if (error === null) return "null";
842
+ if (error === void 0) return "undefined";
843
+ return "Unknown stream error";
844
+ };
845
+ var sseFraming = (bytes) => bytes.pipe(
846
+ effect.Stream.decodeText(),
847
+ effect.Stream.pipeThroughChannel(Sse__namespace.decode()),
848
+ effect.Stream.catchTag("Retry", () => effect.Stream.empty),
849
+ effect.Stream.filter((event) => event.data.length > 0 && event.data !== "[DONE]"),
850
+ effect.Stream.map((event) => event.data)
851
+ );
852
+ var invalidRequest = (message) => new LLMError({
853
+ module: "ProviderShared",
854
+ method: "request",
855
+ reason: new InvalidRequestReason({ message })
856
+ });
857
+ var matchToolChoice = (route, toolChoice, cases) => effect.Effect.gen(function* () {
858
+ if (toolChoice.type === "auto") return cases.auto();
859
+ if (toolChoice.type === "none") return cases.none();
860
+ if (toolChoice.type === "required") return cases.required();
861
+ if (!toolChoice.name) return yield* invalidRequest(`${route} tool choice requires a tool name`);
862
+ return cases.tool(toolChoice.name);
863
+ });
864
+ var formatContentTypes = (types) => {
865
+ if (types.length <= 1) return types[0] ?? "";
866
+ if (types.length === 2) return `${types[0]} and ${types[1]}`;
867
+ return `${types.slice(0, -1).join(", ")}, and ${types.at(-1)}`;
868
+ };
869
+ var supportsContent = (part, types) => types.includes(part.type);
870
+ var unsupportedContent = (route, role, types) => invalidRequest(`${route} ${role} messages only support ${formatContentTypes(types)} content for now`);
871
+ var validateWith = (decode2) => (payload) => decode2(payload).pipe(effect.Effect.mapError((error) => invalidRequest(error.message)));
872
+ var jsonPost = (input) => http.HttpClientRequest.post(input.url).pipe(
873
+ http.HttpClientRequest.setHeaders(http.Headers.set(http.Headers.fromInput(input.headers), "content-type", "application/json")),
874
+ http.HttpClientRequest.bodyText(input.body, "application/json")
875
+ );
876
+
877
+ exports.Json = Json;
878
+ exports.JsonObject = JsonObject;
879
+ exports.ProviderShared = shared_exports;
880
+ exports.decodeJson = decodeJson;
881
+ exports.encodeJson = encodeJson;
882
+ exports.errorText = errorText;
883
+ exports.eventError = eventError;
884
+ exports.invalidRequest = invalidRequest;
885
+ exports.isRecord = isRecord2;
886
+ exports.joinText = joinText;
887
+ exports.jsonPost = jsonPost;
888
+ exports.matchToolChoice = matchToolChoice;
889
+ exports.mediaBytes = mediaBytes;
890
+ exports.optionalArray = optionalArray;
891
+ exports.optionalNull = optionalNull;
892
+ exports.parseJson = parseJson;
893
+ exports.parseToolInput = parseToolInput;
894
+ exports.sseFraming = sseFraming;
895
+ exports.subtractTokens = subtractTokens;
896
+ exports.sumTokens = sumTokens;
897
+ exports.supportsContent = supportsContent;
898
+ exports.toolResultText = toolResultText;
899
+ exports.totalTokens = totalTokens;
900
+ exports.trimBaseUrl = trimBaseUrl;
901
+ exports.unsupportedContent = unsupportedContent;
902
+ exports.validateWith = validateWith;
903
+ //# sourceMappingURL=shared.cjs.map
904
+ //# sourceMappingURL=shared.cjs.map