@luketandjung/ariadne 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +3672 -0
- package/dist/index.d.ts +8504 -0
- package/dist/index.js +3638 -0
- package/package.json +35 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3638 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __export = (target, all) => {
|
|
4
|
+
for (var name in all)
|
|
5
|
+
__defProp(target, name, {
|
|
6
|
+
get: all[name],
|
|
7
|
+
enumerable: true,
|
|
8
|
+
configurable: true,
|
|
9
|
+
set: (newValue) => all[name] = () => newValue
|
|
10
|
+
});
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// packages/ariadne/src/AiError.ts
|
|
14
|
+
var exports_AiError = {};
|
|
15
|
+
__export(exports_AiError, {
|
|
16
|
+
isAiError: () => isAiError,
|
|
17
|
+
UnknownError: () => UnknownError,
|
|
18
|
+
TypeId: () => TypeId,
|
|
19
|
+
MalformedOutput: () => MalformedOutput,
|
|
20
|
+
MalformedInput: () => MalformedInput,
|
|
21
|
+
HttpResponseError: () => HttpResponseError,
|
|
22
|
+
HttpResponseDetails: () => HttpResponseDetails,
|
|
23
|
+
HttpRequestError: () => HttpRequestError,
|
|
24
|
+
HttpRequestDetails: () => HttpRequestDetails,
|
|
25
|
+
AiError: () => AiError
|
|
26
|
+
});
|
|
27
|
+
import * as Effect from "effect/Effect";
|
|
28
|
+
import * as Inspectable from "effect/Inspectable";
|
|
29
|
+
import * as Predicate from "effect/Predicate";
|
|
30
|
+
import * as Schema from "effect/Schema";
|
|
31
|
+
var TypeId = "~@effect/ai/AiError";
|
|
32
|
+
var isAiError = (u) => Predicate.hasProperty(u, TypeId);
|
|
33
|
+
var HttpRequestDetails = Schema.Struct({
|
|
34
|
+
method: Schema.Literal("GET", "POST", "PATCH", "PUT", "DELETE", "HEAD", "OPTIONS"),
|
|
35
|
+
url: Schema.String,
|
|
36
|
+
urlParams: Schema.Array(Schema.Tuple(Schema.String, Schema.String)),
|
|
37
|
+
hash: Schema.Option(Schema.String),
|
|
38
|
+
headers: Schema.Record({ key: Schema.String, value: Schema.String })
|
|
39
|
+
}).annotations({ identifier: "HttpRequestDetails" });
|
|
40
|
+
|
|
41
|
+
class HttpRequestError extends Schema.TaggedError("@effect/ai/AiError/HttpRequestError")("HttpRequestError", {
|
|
42
|
+
module: Schema.String,
|
|
43
|
+
method: Schema.String,
|
|
44
|
+
reason: Schema.Literal("Transport", "Encode", "InvalidUrl"),
|
|
45
|
+
request: HttpRequestDetails,
|
|
46
|
+
description: Schema.optional(Schema.String),
|
|
47
|
+
cause: Schema.optional(Schema.Defect)
|
|
48
|
+
}) {
|
|
49
|
+
[TypeId] = TypeId;
|
|
50
|
+
static fromRequestError({
|
|
51
|
+
error,
|
|
52
|
+
...params
|
|
53
|
+
}) {
|
|
54
|
+
return new HttpRequestError({
|
|
55
|
+
...params,
|
|
56
|
+
cause: error,
|
|
57
|
+
description: error.description,
|
|
58
|
+
reason: error.reason,
|
|
59
|
+
request: {
|
|
60
|
+
hash: error.request.hash,
|
|
61
|
+
headers: Inspectable.redact(error.request.headers),
|
|
62
|
+
method: error.request.method,
|
|
63
|
+
url: error.request.url,
|
|
64
|
+
urlParams: error.request.urlParams
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
get message() {
|
|
69
|
+
const methodAndUrl = `${this.request.method} ${this.request.url}`;
|
|
70
|
+
let baseMessage = this.description ? `${this.reason}: ${this.description}` : `${this.reason}: An HTTP request error occurred.`;
|
|
71
|
+
baseMessage += ` (${methodAndUrl})`;
|
|
72
|
+
let suggestion = "";
|
|
73
|
+
switch (this.reason) {
|
|
74
|
+
case "Encode": {
|
|
75
|
+
suggestion += "Check that the request body data is properly formatted and matches the expected content type.";
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
case "InvalidUrl": {
|
|
79
|
+
suggestion += "Verify that the URL format is correct and that all required parameters have been provided.";
|
|
80
|
+
suggestion += " Check for any special characters that may need encoding.";
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
case "Transport": {
|
|
84
|
+
suggestion += "Check your network connection and verify that the requested URL is accessible.";
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
baseMessage += `
|
|
89
|
+
|
|
90
|
+
Suggestion: ${suggestion}`;
|
|
91
|
+
return baseMessage;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
var HttpResponseDetails = Schema.Struct({
|
|
95
|
+
status: Schema.Number,
|
|
96
|
+
headers: Schema.Record({ key: Schema.String, value: Schema.String })
|
|
97
|
+
}).annotations({ identifier: "HttpResponseDetails" });
|
|
98
|
+
|
|
99
|
+
class HttpResponseError extends Schema.TaggedError("@effect/ai/AiError/HttpResponseError")("HttpResponseError", {
|
|
100
|
+
module: Schema.String,
|
|
101
|
+
method: Schema.String,
|
|
102
|
+
request: HttpRequestDetails,
|
|
103
|
+
response: HttpResponseDetails,
|
|
104
|
+
body: Schema.optional(Schema.String),
|
|
105
|
+
reason: Schema.Literal("StatusCode", "Decode", "EmptyBody"),
|
|
106
|
+
description: Schema.optional(Schema.String)
|
|
107
|
+
}) {
|
|
108
|
+
[TypeId] = TypeId;
|
|
109
|
+
static fromResponseError({
|
|
110
|
+
error,
|
|
111
|
+
...params
|
|
112
|
+
}) {
|
|
113
|
+
let body = Effect.void;
|
|
114
|
+
const contentType = error.response.headers["content-type"] ?? "";
|
|
115
|
+
if (contentType.includes("application/json")) {
|
|
116
|
+
body = error.response.json;
|
|
117
|
+
} else if (contentType.includes("text/") || contentType.includes("urlencoded")) {
|
|
118
|
+
body = error.response.text;
|
|
119
|
+
}
|
|
120
|
+
return Effect.flatMap(Effect.merge(body), (body2) => new HttpResponseError({
|
|
121
|
+
...params,
|
|
122
|
+
description: error.description,
|
|
123
|
+
reason: error.reason,
|
|
124
|
+
request: {
|
|
125
|
+
hash: error.request.hash,
|
|
126
|
+
headers: Inspectable.redact(error.request.headers),
|
|
127
|
+
method: error.request.method,
|
|
128
|
+
url: error.request.url,
|
|
129
|
+
urlParams: error.request.urlParams
|
|
130
|
+
},
|
|
131
|
+
response: {
|
|
132
|
+
headers: Inspectable.redact(error.response.headers),
|
|
133
|
+
status: error.response.status
|
|
134
|
+
},
|
|
135
|
+
body: Inspectable.format(body2)
|
|
136
|
+
}));
|
|
137
|
+
}
|
|
138
|
+
get message() {
|
|
139
|
+
const methodUrlStatus = `${this.response.status} ${this.request.method} ${this.request.url}`;
|
|
140
|
+
let baseMessage = this.description ? `${this.reason}: ${this.description}` : `${this.reason}: An HTTP response error occurred.`;
|
|
141
|
+
baseMessage += ` (${methodUrlStatus})`;
|
|
142
|
+
let suggestion = "";
|
|
143
|
+
switch (this.reason) {
|
|
144
|
+
case "Decode": {
|
|
145
|
+
suggestion += "The response format does not match what is expected. " + "Verify API version compatibility, check response content-type, " + "and/or examine if the endpoint schema has changed.";
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
case "EmptyBody": {
|
|
149
|
+
suggestion += "The response body was empty. This may indicate a server " + "issue, API version mismatch, or the endpoint may have changed its response format.";
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
case "StatusCode": {
|
|
153
|
+
suggestion += getStatusCodeSuggestion(this.response.status);
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
baseMessage += `
|
|
158
|
+
|
|
159
|
+
${suggestion}`;
|
|
160
|
+
if (Predicate.isNotUndefined(this.body)) {
|
|
161
|
+
baseMessage += `
|
|
162
|
+
|
|
163
|
+
Response Body: ${this.body}`;
|
|
164
|
+
}
|
|
165
|
+
return baseMessage;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
class MalformedInput extends Schema.TaggedError("@effect/ai/AiError/MalformedInput")("MalformedInput", {
|
|
170
|
+
module: Schema.String,
|
|
171
|
+
method: Schema.String,
|
|
172
|
+
description: Schema.optional(Schema.String),
|
|
173
|
+
cause: Schema.optional(Schema.Defect)
|
|
174
|
+
}) {
|
|
175
|
+
[TypeId] = TypeId;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
class MalformedOutput extends Schema.TaggedError("@effect/ai/AiError/MalformedOutput")("MalformedOutput", {
|
|
179
|
+
module: Schema.String,
|
|
180
|
+
method: Schema.String,
|
|
181
|
+
description: Schema.optional(Schema.String),
|
|
182
|
+
cause: Schema.optional(Schema.Defect)
|
|
183
|
+
}) {
|
|
184
|
+
[TypeId] = TypeId;
|
|
185
|
+
static fromParseError({
|
|
186
|
+
error,
|
|
187
|
+
...params
|
|
188
|
+
}) {
|
|
189
|
+
return new MalformedOutput({
|
|
190
|
+
...params,
|
|
191
|
+
cause: error
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
class UnknownError extends Schema.TaggedError("@effect/ai/UnknownError")("UnknownError", {
|
|
197
|
+
module: Schema.String,
|
|
198
|
+
method: Schema.String,
|
|
199
|
+
description: Schema.optional(Schema.String),
|
|
200
|
+
cause: Schema.optional(Schema.Defect)
|
|
201
|
+
}) {
|
|
202
|
+
[TypeId] = TypeId;
|
|
203
|
+
get message() {
|
|
204
|
+
const moduleMethod = `${this.module}.${this.method}`;
|
|
205
|
+
return Predicate.isUndefined(this.description) ? `${moduleMethod}: An error occurred` : `${moduleMethod}: ${this.description}`;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
var AiError = Schema.Union(HttpRequestError, HttpResponseError, MalformedInput, MalformedOutput, UnknownError);
|
|
209
|
+
var getStatusCodeSuggestion = (statusCode) => {
|
|
210
|
+
if (statusCode >= 400 && statusCode < 500) {
|
|
211
|
+
switch (statusCode) {
|
|
212
|
+
case 400:
|
|
213
|
+
return "Bad Request - Check request parameters, headers, and body format against API documentation.";
|
|
214
|
+
case 401:
|
|
215
|
+
return "Unauthorized - Verify API key, authentication credentials, or token expiration.";
|
|
216
|
+
case 403:
|
|
217
|
+
return "Forbidden - Check API permissions, usage limits, or resource access rights.";
|
|
218
|
+
case 404:
|
|
219
|
+
return "Not Found - Verify the endpoint URL, API version, and resource identifiers.";
|
|
220
|
+
case 408:
|
|
221
|
+
return "Request Timeout - Consider increasing timeout duration or implementing retry logic.";
|
|
222
|
+
case 422:
|
|
223
|
+
return "Unprocessable Entity - Check request data validation, required fields, and data formats.";
|
|
224
|
+
case 429:
|
|
225
|
+
return "Rate Limited - Implement exponential backoff or reduce request frequency.";
|
|
226
|
+
default:
|
|
227
|
+
return "Client error - Review request format, parameters, and API documentation.";
|
|
228
|
+
}
|
|
229
|
+
} else if (statusCode >= 500) {
|
|
230
|
+
return "Server error - This is likely temporary. Implement retry logic with exponential backoff.";
|
|
231
|
+
} else {
|
|
232
|
+
return "Check API documentation for this status code.";
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
// packages/ariadne/src/AgentRunner.ts
|
|
236
|
+
var exports_AgentRunner = {};
|
|
237
|
+
__export(exports_AgentRunner, {
|
|
238
|
+
defaultConfig: () => defaultConfig,
|
|
239
|
+
ReAct: () => ReAct,
|
|
240
|
+
Config: () => Config
|
|
241
|
+
});
|
|
242
|
+
import * as Context6 from "effect/Context";
|
|
243
|
+
import * as Effect6 from "effect/Effect";
|
|
244
|
+
import * as Layer3 from "effect/Layer";
|
|
245
|
+
import * as Ref from "effect/Ref";
|
|
246
|
+
import * as Stream2 from "effect/Stream";
|
|
247
|
+
|
|
248
|
+
// packages/ariadne/src/LanguageModel.ts
|
|
249
|
+
var exports_LanguageModel = {};
|
|
250
|
+
__export(exports_LanguageModel, {
|
|
251
|
+
streamText: () => streamText,
|
|
252
|
+
streamObject: () => streamObject,
|
|
253
|
+
make: () => make6,
|
|
254
|
+
generateText: () => generateText,
|
|
255
|
+
generateObject: () => generateObject,
|
|
256
|
+
LanguageModel: () => LanguageModel,
|
|
257
|
+
GenerateTextResponse: () => GenerateTextResponse,
|
|
258
|
+
GenerateObjectResponse: () => GenerateObjectResponse
|
|
259
|
+
});
|
|
260
|
+
import * as Chunk from "effect/Chunk";
|
|
261
|
+
import * as Context5 from "effect/Context";
|
|
262
|
+
import * as Effect5 from "effect/Effect";
|
|
263
|
+
import * as Mailbox from "effect/Mailbox";
|
|
264
|
+
import * as Option3 from "effect/Option";
|
|
265
|
+
import * as ParseResult4 from "effect/ParseResult";
|
|
266
|
+
import * as Predicate8 from "effect/Predicate";
|
|
267
|
+
import * as Schema6 from "effect/Schema";
|
|
268
|
+
import * as Stream from "effect/Stream";
|
|
269
|
+
|
|
270
|
+
// packages/ariadne/src/IdGenerator.ts
|
|
271
|
+
var exports_IdGenerator = {};
|
|
272
|
+
__export(exports_IdGenerator, {
|
|
273
|
+
make: () => make,
|
|
274
|
+
layer: () => layer,
|
|
275
|
+
defaultIdGenerator: () => defaultIdGenerator,
|
|
276
|
+
IdGenerator: () => IdGenerator
|
|
277
|
+
});
|
|
278
|
+
import * as Cause from "effect/Cause";
|
|
279
|
+
import * as Context from "effect/Context";
|
|
280
|
+
import * as Effect2 from "effect/Effect";
|
|
281
|
+
import * as Layer from "effect/Layer";
|
|
282
|
+
import * as Predicate2 from "effect/Predicate";
|
|
283
|
+
import * as Random from "effect/Random";
|
|
284
|
+
|
|
285
|
+
class IdGenerator extends Context.Tag("@effect/ai/IdGenerator")() {
|
|
286
|
+
}
|
|
287
|
+
var DEFAULT_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
288
|
+
var DEFAULT_SEPARATOR = "_";
|
|
289
|
+
var DEFAULT_SIZE = 16;
|
|
290
|
+
var makeGenerator = ({
|
|
291
|
+
alphabet = DEFAULT_ALPHABET,
|
|
292
|
+
prefix,
|
|
293
|
+
separator = DEFAULT_SEPARATOR,
|
|
294
|
+
size = DEFAULT_SIZE
|
|
295
|
+
}) => {
|
|
296
|
+
const alphabetLength = alphabet.length;
|
|
297
|
+
return Effect2.fnUntraced(function* () {
|
|
298
|
+
const chars = new Array(size);
|
|
299
|
+
for (let i = 0;i < size; i++) {
|
|
300
|
+
chars[i] = alphabet[(yield* Random.next) * alphabetLength | 0];
|
|
301
|
+
}
|
|
302
|
+
const identifier = chars.join("");
|
|
303
|
+
if (Predicate2.isUndefined(prefix)) {
|
|
304
|
+
return identifier;
|
|
305
|
+
}
|
|
306
|
+
return `${prefix}${separator}${identifier}`;
|
|
307
|
+
});
|
|
308
|
+
};
|
|
309
|
+
var defaultIdGenerator = {
|
|
310
|
+
generateId: makeGenerator({ prefix: "id" })
|
|
311
|
+
};
|
|
312
|
+
var make = Effect2.fnUntraced(function* ({
|
|
313
|
+
alphabet = DEFAULT_ALPHABET,
|
|
314
|
+
prefix,
|
|
315
|
+
separator = DEFAULT_SEPARATOR,
|
|
316
|
+
size = DEFAULT_SIZE
|
|
317
|
+
}) {
|
|
318
|
+
if (alphabet.includes(separator)) {
|
|
319
|
+
const message = `The separator "${separator}" must not be part of the alphabet "${alphabet}".`;
|
|
320
|
+
return yield* new Cause.IllegalArgumentException(message);
|
|
321
|
+
}
|
|
322
|
+
const generateId = makeGenerator({ alphabet, prefix, separator, size });
|
|
323
|
+
return {
|
|
324
|
+
generateId
|
|
325
|
+
};
|
|
326
|
+
});
|
|
327
|
+
var layer = (options) => Layer.effect(IdGenerator, make(options));
|
|
328
|
+
|
|
329
|
+
// packages/ariadne/src/Prompt.ts
|
|
330
|
+
var exports_Prompt = {};
|
|
331
|
+
__export(exports_Prompt, {
|
|
332
|
+
userMessage: () => userMessage,
|
|
333
|
+
toolResultPart: () => toolResultPart,
|
|
334
|
+
toolMessage: () => toolMessage,
|
|
335
|
+
toolCallPart: () => toolCallPart,
|
|
336
|
+
textPart: () => textPart,
|
|
337
|
+
systemMessage: () => systemMessage,
|
|
338
|
+
setSystem: () => setSystem,
|
|
339
|
+
reasoningPart: () => reasoningPart,
|
|
340
|
+
prependSystem: () => prependSystem,
|
|
341
|
+
merge: () => merge2,
|
|
342
|
+
makePart: () => makePart,
|
|
343
|
+
makeMessage: () => makeMessage,
|
|
344
|
+
make: () => make2,
|
|
345
|
+
isPrompt: () => isPrompt,
|
|
346
|
+
isPart: () => isPart,
|
|
347
|
+
isMessage: () => isMessage,
|
|
348
|
+
fromResponseParts: () => fromResponseParts,
|
|
349
|
+
fromMessages: () => fromMessages,
|
|
350
|
+
filePart: () => filePart,
|
|
351
|
+
empty: () => empty,
|
|
352
|
+
assistantMessage: () => assistantMessage,
|
|
353
|
+
appendSystem: () => appendSystem,
|
|
354
|
+
UserMessage: () => UserMessage,
|
|
355
|
+
TypeId: () => TypeId2,
|
|
356
|
+
ToolResultPart: () => ToolResultPart,
|
|
357
|
+
ToolMessage: () => ToolMessage,
|
|
358
|
+
ToolCallPart: () => ToolCallPart,
|
|
359
|
+
TextPart: () => TextPart,
|
|
360
|
+
SystemMessage: () => SystemMessage,
|
|
361
|
+
ReasoningPart: () => ReasoningPart,
|
|
362
|
+
ProviderOptions: () => ProviderOptions,
|
|
363
|
+
PromptFromSelf: () => PromptFromSelf,
|
|
364
|
+
Prompt: () => Prompt,
|
|
365
|
+
PartTypeId: () => PartTypeId,
|
|
366
|
+
MessageTypeId: () => MessageTypeId,
|
|
367
|
+
MessageContentFromString: () => MessageContentFromString,
|
|
368
|
+
Message: () => Message,
|
|
369
|
+
FromJson: () => FromJson,
|
|
370
|
+
FilePart: () => FilePart,
|
|
371
|
+
AssistantMessage: () => AssistantMessage
|
|
372
|
+
});
|
|
373
|
+
import * as Arbitrary from "effect/Arbitrary";
|
|
374
|
+
import * as Arr from "effect/Array";
|
|
375
|
+
import { constFalse, dual } from "effect/Function";
|
|
376
|
+
import * as ParseResult from "effect/ParseResult";
|
|
377
|
+
import { pipeArguments } from "effect/Pipeable";
|
|
378
|
+
import * as Predicate3 from "effect/Predicate";
|
|
379
|
+
import * as Schema2 from "effect/Schema";
|
|
380
|
+
var constEmptyObject = () => ({});
|
|
381
|
+
var ProviderOptions = Schema2.Record({
|
|
382
|
+
key: Schema2.String,
|
|
383
|
+
value: Schema2.UndefinedOr(Schema2.Record({
|
|
384
|
+
key: Schema2.String,
|
|
385
|
+
value: Schema2.Unknown
|
|
386
|
+
}))
|
|
387
|
+
});
|
|
388
|
+
var PartTypeId = "~effect/ai/Prompt/Part";
|
|
389
|
+
var isPart = (u) => Predicate3.hasProperty(u, PartTypeId);
|
|
390
|
+
var makePart = (type, params) => ({
|
|
391
|
+
...params,
|
|
392
|
+
[PartTypeId]: PartTypeId,
|
|
393
|
+
type,
|
|
394
|
+
options: params.options ?? {}
|
|
395
|
+
});
|
|
396
|
+
var TextPart = Schema2.Struct({
|
|
397
|
+
type: Schema2.Literal("text"),
|
|
398
|
+
text: Schema2.String,
|
|
399
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
400
|
+
default: constEmptyObject
|
|
401
|
+
})
|
|
402
|
+
}).pipe(Schema2.attachPropertySignature(PartTypeId, PartTypeId), Schema2.annotations({ identifier: "TextPart" }));
|
|
403
|
+
var textPart = (params) => makePart("text", params);
|
|
404
|
+
var ReasoningPart = Schema2.Struct({
|
|
405
|
+
type: Schema2.Literal("reasoning"),
|
|
406
|
+
text: Schema2.String,
|
|
407
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
408
|
+
default: constEmptyObject
|
|
409
|
+
})
|
|
410
|
+
}).pipe(Schema2.attachPropertySignature(PartTypeId, PartTypeId), Schema2.annotations({ identifier: "ReasoningPart" }));
|
|
411
|
+
var reasoningPart = (params) => makePart("reasoning", params);
|
|
412
|
+
var FilePart = Schema2.Struct({
|
|
413
|
+
type: Schema2.Literal("file"),
|
|
414
|
+
mediaType: Schema2.String,
|
|
415
|
+
fileName: Schema2.optional(Schema2.String),
|
|
416
|
+
data: Schema2.Union(Schema2.String, Schema2.Uint8ArrayFromSelf, Schema2.URLFromSelf),
|
|
417
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
418
|
+
default: constEmptyObject
|
|
419
|
+
})
|
|
420
|
+
}).pipe(Schema2.attachPropertySignature(PartTypeId, PartTypeId), Schema2.annotations({ identifier: "FilePart" }));
|
|
421
|
+
var filePart = (params) => makePart("file", params);
|
|
422
|
+
var ToolCallPart = Schema2.Struct({
|
|
423
|
+
type: Schema2.Literal("tool-call"),
|
|
424
|
+
id: Schema2.String,
|
|
425
|
+
name: Schema2.String,
|
|
426
|
+
params: Schema2.Unknown,
|
|
427
|
+
providerExecuted: Schema2.optionalWith(Schema2.Boolean, {
|
|
428
|
+
default: constFalse
|
|
429
|
+
}),
|
|
430
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
431
|
+
default: constEmptyObject
|
|
432
|
+
})
|
|
433
|
+
}).pipe(Schema2.attachPropertySignature(PartTypeId, PartTypeId), Schema2.annotations({ identifier: "ToolCallPart" }));
|
|
434
|
+
var toolCallPart = (params) => makePart("tool-call", params);
|
|
435
|
+
var ToolResultPart = Schema2.Struct({
|
|
436
|
+
type: Schema2.Literal("tool-result"),
|
|
437
|
+
id: Schema2.String,
|
|
438
|
+
name: Schema2.String,
|
|
439
|
+
isFailure: Schema2.Boolean,
|
|
440
|
+
result: Schema2.Unknown,
|
|
441
|
+
providerExecuted: Schema2.Boolean,
|
|
442
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
443
|
+
default: constEmptyObject
|
|
444
|
+
})
|
|
445
|
+
}).pipe(Schema2.attachPropertySignature(PartTypeId, PartTypeId), Schema2.annotations({ identifier: "ToolResultPart" }));
|
|
446
|
+
var toolResultPart = (params) => makePart("tool-result", params);
|
|
447
|
+
var MessageTypeId = "~effect/ai/Prompt/Message";
|
|
448
|
+
var isMessage = (u) => Predicate3.hasProperty(u, MessageTypeId);
|
|
449
|
+
var makeMessage = (role, params) => ({
|
|
450
|
+
...params,
|
|
451
|
+
[MessageTypeId]: MessageTypeId,
|
|
452
|
+
role,
|
|
453
|
+
options: params.options ?? {}
|
|
454
|
+
});
|
|
455
|
+
var MessageContentFromString = Schema2.transform(Schema2.String, Schema2.NonEmptyArray(Schema2.typeSchema(TextPart)), {
|
|
456
|
+
strict: true,
|
|
457
|
+
decode: (text) => Arr.of(makePart("text", { text })),
|
|
458
|
+
encode: (content) => content[0].text
|
|
459
|
+
});
|
|
460
|
+
var SystemMessage = Schema2.Struct({
|
|
461
|
+
role: Schema2.Literal("system"),
|
|
462
|
+
content: Schema2.String,
|
|
463
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
464
|
+
default: constEmptyObject
|
|
465
|
+
})
|
|
466
|
+
}).pipe(Schema2.attachPropertySignature(MessageTypeId, MessageTypeId), Schema2.annotations({ identifier: "SystemMessage" }));
|
|
467
|
+
var systemMessage = (params) => makeMessage("system", params);
|
|
468
|
+
var UserMessage = Schema2.Struct({
|
|
469
|
+
role: Schema2.Literal("user"),
|
|
470
|
+
content: Schema2.Union(MessageContentFromString, Schema2.Array(Schema2.Union(TextPart, FilePart))),
|
|
471
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
472
|
+
default: constEmptyObject
|
|
473
|
+
})
|
|
474
|
+
}).pipe(Schema2.attachPropertySignature(MessageTypeId, MessageTypeId), Schema2.annotations({ identifier: "UserMessage" }));
|
|
475
|
+
var userMessage = (params) => makeMessage("user", params);
|
|
476
|
+
var AssistantMessage = Schema2.Struct({
|
|
477
|
+
role: Schema2.Literal("assistant"),
|
|
478
|
+
content: Schema2.Union(MessageContentFromString, Schema2.Array(Schema2.Union(TextPart, FilePart, ReasoningPart, ToolCallPart, ToolResultPart))),
|
|
479
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
480
|
+
default: constEmptyObject
|
|
481
|
+
})
|
|
482
|
+
}).pipe(Schema2.attachPropertySignature(MessageTypeId, MessageTypeId), Schema2.annotations({ identifier: "AssistantMessage" }));
|
|
483
|
+
var assistantMessage = (params) => makeMessage("assistant", params);
|
|
484
|
+
var ToolMessage = Schema2.Struct({
|
|
485
|
+
role: Schema2.Literal("tool"),
|
|
486
|
+
content: Schema2.Array(ToolResultPart),
|
|
487
|
+
options: Schema2.optionalWith(ProviderOptions, {
|
|
488
|
+
default: constEmptyObject
|
|
489
|
+
})
|
|
490
|
+
}).pipe(Schema2.attachPropertySignature(MessageTypeId, MessageTypeId), Schema2.annotations({ identifier: "ToolMessage" }));
|
|
491
|
+
var toolMessage = (params) => makeMessage("tool", params);
|
|
492
|
+
var Message = Schema2.Union(SystemMessage, UserMessage, AssistantMessage, ToolMessage);
|
|
493
|
+
var TypeId2 = "~@effect/ai/Prompt";
|
|
494
|
+
var isPrompt = (u) => Predicate3.hasProperty(u, TypeId2);
|
|
495
|
+
|
|
496
|
+
class PromptFromSelf extends Schema2.declare((u) => isPrompt(u), {
|
|
497
|
+
typeConstructor: { _tag: "effect/ai/Prompt" },
|
|
498
|
+
identifier: "PromptFromSelf",
|
|
499
|
+
description: "a Prompt instance",
|
|
500
|
+
arbitrary: () => (fc) => fc.array(Arbitrary.makeLazy(Message)(fc)).map(makePrompt)
|
|
501
|
+
}) {
|
|
502
|
+
}
|
|
503
|
+
var Prompt = Schema2.transformOrFail(Schema2.Struct({ content: Schema2.Array(Schema2.encodedSchema(Message)) }), PromptFromSelf, {
|
|
504
|
+
strict: true,
|
|
505
|
+
decode: (i, _, ast) => decodePrompt(i, ast),
|
|
506
|
+
encode: (a, _, ast) => encodePrompt(a, ast)
|
|
507
|
+
}).annotations({ identifier: "Prompt" });
|
|
508
|
+
var decodeMessages = ParseResult.decodeEither(Schema2.Array(Message));
|
|
509
|
+
var encodeMessages = ParseResult.encodeEither(Schema2.Array(Message));
|
|
510
|
+
var decodePrompt = (input, ast) => ParseResult.mapBoth(decodeMessages(input.content), {
|
|
511
|
+
onFailure: () => new ParseResult.Type(ast, input, `Unable to decode ${JSON.stringify(input)} into a Prompt`),
|
|
512
|
+
onSuccess: makePrompt
|
|
513
|
+
});
|
|
514
|
+
var encodePrompt = (input, ast) => ParseResult.mapBoth(encodeMessages(input.content), {
|
|
515
|
+
onFailure: () => new ParseResult.Type(ast, input, `Failed to encode Prompt`),
|
|
516
|
+
onSuccess: (messages) => ({ content: messages })
|
|
517
|
+
});
|
|
518
|
+
var FromJson = Schema2.parseJson(Prompt);
|
|
519
|
+
var Proto = {
|
|
520
|
+
[TypeId2]: TypeId2,
|
|
521
|
+
pipe() {
|
|
522
|
+
return pipeArguments(this, arguments);
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
var makePrompt = (content) => Object.assign(Object.create(Proto), {
|
|
526
|
+
content
|
|
527
|
+
});
|
|
528
|
+
var decodeMessagesSync = Schema2.decodeSync(Schema2.Array(Message));
|
|
529
|
+
var empty = makePrompt([]);
|
|
530
|
+
var make2 = (input) => {
|
|
531
|
+
if (Predicate3.isString(input)) {
|
|
532
|
+
const part = makePart("text", { text: input });
|
|
533
|
+
const message = makeMessage("user", { content: [part] });
|
|
534
|
+
return makePrompt([message]);
|
|
535
|
+
}
|
|
536
|
+
if (Predicate3.isIterable(input)) {
|
|
537
|
+
return makePrompt(decodeMessagesSync(Arr.fromIterable(input), {
|
|
538
|
+
errors: "all"
|
|
539
|
+
}));
|
|
540
|
+
}
|
|
541
|
+
return input;
|
|
542
|
+
};
|
|
543
|
+
var fromMessages = (messages) => makePrompt(messages);
|
|
544
|
+
var fromResponseParts = (parts) => {
|
|
545
|
+
if (parts.length === 0) {
|
|
546
|
+
return empty;
|
|
547
|
+
}
|
|
548
|
+
const assistantParts = [];
|
|
549
|
+
const toolParts = [];
|
|
550
|
+
const activeTextDeltas = new Map;
|
|
551
|
+
const activeReasoningDeltas = new Map;
|
|
552
|
+
for (const part of parts) {
|
|
553
|
+
switch (part.type) {
|
|
554
|
+
case "text": {
|
|
555
|
+
assistantParts.push(makePart("text", { text: part.text }));
|
|
556
|
+
break;
|
|
557
|
+
}
|
|
558
|
+
case "text-start": {
|
|
559
|
+
activeTextDeltas.set(part.id, { text: "" });
|
|
560
|
+
break;
|
|
561
|
+
}
|
|
562
|
+
case "text-delta": {
|
|
563
|
+
if (activeTextDeltas.has(part.id)) {
|
|
564
|
+
activeTextDeltas.get(part.id).text += part.delta;
|
|
565
|
+
}
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
case "text-end": {
|
|
569
|
+
if (activeTextDeltas.has(part.id)) {
|
|
570
|
+
assistantParts.push(makePart("text", activeTextDeltas.get(part.id)));
|
|
571
|
+
}
|
|
572
|
+
break;
|
|
573
|
+
}
|
|
574
|
+
case "reasoning": {
|
|
575
|
+
assistantParts.push(makePart("reasoning", { text: part.text }));
|
|
576
|
+
break;
|
|
577
|
+
}
|
|
578
|
+
case "reasoning-start": {
|
|
579
|
+
activeReasoningDeltas.set(part.id, { text: "" });
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
case "reasoning-delta": {
|
|
583
|
+
if (activeReasoningDeltas.has(part.id)) {
|
|
584
|
+
activeReasoningDeltas.get(part.id).text += part.delta;
|
|
585
|
+
}
|
|
586
|
+
break;
|
|
587
|
+
}
|
|
588
|
+
case "reasoning-end": {
|
|
589
|
+
if (activeReasoningDeltas.has(part.id)) {
|
|
590
|
+
assistantParts.push(makePart("reasoning", activeReasoningDeltas.get(part.id)));
|
|
591
|
+
}
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
case "tool-call": {
|
|
595
|
+
assistantParts.push(makePart("tool-call", {
|
|
596
|
+
id: part.id,
|
|
597
|
+
name: part.providerName ?? part.name,
|
|
598
|
+
params: part.params,
|
|
599
|
+
providerExecuted: part.providerExecuted ?? false
|
|
600
|
+
}));
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
case "tool-result": {
|
|
604
|
+
const toolPart = makePart("tool-result", {
|
|
605
|
+
id: part.id,
|
|
606
|
+
name: part.providerName ?? part.name,
|
|
607
|
+
isFailure: part.isFailure,
|
|
608
|
+
result: part.encodedResult,
|
|
609
|
+
providerExecuted: part.providerExecuted ?? false
|
|
610
|
+
});
|
|
611
|
+
if (part.providerExecuted) {
|
|
612
|
+
assistantParts.push(toolPart);
|
|
613
|
+
} else {
|
|
614
|
+
toolParts.push(toolPart);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
if (assistantParts.length === 0 && toolParts.length === 0) {
|
|
620
|
+
return empty;
|
|
621
|
+
}
|
|
622
|
+
const messages = [];
|
|
623
|
+
if (assistantParts.length > 0) {
|
|
624
|
+
messages.push(makeMessage("assistant", { content: assistantParts }));
|
|
625
|
+
}
|
|
626
|
+
if (toolParts.length > 0) {
|
|
627
|
+
messages.push(makeMessage("tool", { content: toolParts }));
|
|
628
|
+
}
|
|
629
|
+
return makePrompt(messages);
|
|
630
|
+
};
|
|
631
|
+
var merge2 = dual(2, (self, input) => {
|
|
632
|
+
const other = make2(input);
|
|
633
|
+
if (self.content.length === 0) {
|
|
634
|
+
return other;
|
|
635
|
+
}
|
|
636
|
+
if (other.content.length === 0) {
|
|
637
|
+
return self;
|
|
638
|
+
}
|
|
639
|
+
return fromMessages([...self.content, ...other.content]);
|
|
640
|
+
});
|
|
641
|
+
var setSystem = dual(2, (self, content) => {
|
|
642
|
+
const messages = [makeMessage("system", { content })];
|
|
643
|
+
for (const message of self.content) {
|
|
644
|
+
if (message.role !== "system") {
|
|
645
|
+
messages.push(message);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return makePrompt(messages);
|
|
649
|
+
});
|
|
650
|
+
var prependSystem = dual(2, (self, content) => {
|
|
651
|
+
let system = undefined;
|
|
652
|
+
for (const message of self.content) {
|
|
653
|
+
if (message.role === "system") {
|
|
654
|
+
system = makeMessage("system", {
|
|
655
|
+
content: content + message.content
|
|
656
|
+
});
|
|
657
|
+
break;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
if (Predicate3.isUndefined(system)) {
|
|
661
|
+
system = makeMessage("system", { content });
|
|
662
|
+
}
|
|
663
|
+
return makePrompt([system, ...self.content]);
|
|
664
|
+
});
|
|
665
|
+
var appendSystem = dual(2, (self, content) => {
|
|
666
|
+
let system = undefined;
|
|
667
|
+
for (const message of self.content) {
|
|
668
|
+
if (message.role === "system") {
|
|
669
|
+
system = makeMessage("system", {
|
|
670
|
+
content: message.content + content
|
|
671
|
+
});
|
|
672
|
+
break;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
if (Predicate3.isUndefined(system)) {
|
|
676
|
+
system = makeMessage("system", { content });
|
|
677
|
+
}
|
|
678
|
+
return makePrompt([system, ...self.content]);
|
|
679
|
+
});
|
|
680
|
+
|
|
681
|
+
// packages/ariadne/src/Response.ts
|
|
682
|
+
var exports_Response = {};
|
|
683
|
+
__export(exports_Response, {
|
|
684
|
+
urlSourcePart: () => urlSourcePart,
|
|
685
|
+
toolResultPart: () => toolResultPart2,
|
|
686
|
+
toolParamsStartPart: () => toolParamsStartPart,
|
|
687
|
+
toolParamsEndPart: () => toolParamsEndPart,
|
|
688
|
+
toolParamsDeltaPart: () => toolParamsDeltaPart,
|
|
689
|
+
toolCallPart: () => toolCallPart2,
|
|
690
|
+
textStartPart: () => textStartPart,
|
|
691
|
+
textPart: () => textPart2,
|
|
692
|
+
textEndPart: () => textEndPart,
|
|
693
|
+
textDeltaPart: () => textDeltaPart,
|
|
694
|
+
responseMetadataPart: () => responseMetadataPart,
|
|
695
|
+
reasoningStartPart: () => reasoningStartPart,
|
|
696
|
+
reasoningPart: () => reasoningPart2,
|
|
697
|
+
reasoningEndPart: () => reasoningEndPart,
|
|
698
|
+
reasoningDeltaPart: () => reasoningDeltaPart,
|
|
699
|
+
objectDonePart: () => objectDonePart,
|
|
700
|
+
objectDeltaPart: () => objectDeltaPart,
|
|
701
|
+
makePart: () => makePart2,
|
|
702
|
+
isPart: () => isPart2,
|
|
703
|
+
finishPart: () => finishPart,
|
|
704
|
+
filePart: () => filePart2,
|
|
705
|
+
errorPart: () => errorPart,
|
|
706
|
+
documentSourcePart: () => documentSourcePart,
|
|
707
|
+
Usage: () => Usage,
|
|
708
|
+
UrlSourcePart: () => UrlSourcePart,
|
|
709
|
+
ToolResultPart: () => ToolResultPart2,
|
|
710
|
+
ToolParamsStartPart: () => ToolParamsStartPart,
|
|
711
|
+
ToolParamsEndPart: () => ToolParamsEndPart,
|
|
712
|
+
ToolParamsDeltaPart: () => ToolParamsDeltaPart,
|
|
713
|
+
ToolCallPart: () => ToolCallPart2,
|
|
714
|
+
TextStartPart: () => TextStartPart,
|
|
715
|
+
TextPart: () => TextPart2,
|
|
716
|
+
TextEndPart: () => TextEndPart,
|
|
717
|
+
TextDeltaPart: () => TextDeltaPart,
|
|
718
|
+
StreamPart: () => StreamPart,
|
|
719
|
+
ResponseMetadataPart: () => ResponseMetadataPart,
|
|
720
|
+
ReasoningStartPart: () => ReasoningStartPart,
|
|
721
|
+
ReasoningPart: () => ReasoningPart2,
|
|
722
|
+
ReasoningEndPart: () => ReasoningEndPart,
|
|
723
|
+
ReasoningDeltaPart: () => ReasoningDeltaPart,
|
|
724
|
+
ProviderMetadata: () => ProviderMetadata,
|
|
725
|
+
PartTypeId: () => PartTypeId2,
|
|
726
|
+
Part: () => Part,
|
|
727
|
+
ObjectDonePart: () => ObjectDonePart,
|
|
728
|
+
ObjectDeltaPart: () => ObjectDeltaPart,
|
|
729
|
+
FinishReason: () => FinishReason,
|
|
730
|
+
FinishPart: () => FinishPart,
|
|
731
|
+
FilePart: () => FilePart2,
|
|
732
|
+
ErrorPart: () => ErrorPart,
|
|
733
|
+
DocumentSourcePart: () => DocumentSourcePart,
|
|
734
|
+
AllParts: () => AllParts
|
|
735
|
+
});
|
|
736
|
+
import * as Effect3 from "effect/Effect";
|
|
737
|
+
import { constFalse as constFalse2 } from "effect/Function";
|
|
738
|
+
import * as ParseResult2 from "effect/ParseResult";
|
|
739
|
+
import * as Predicate4 from "effect/Predicate";
|
|
740
|
+
import * as Schema3 from "effect/Schema";
|
|
741
|
+
var constEmptyObject2 = () => ({});
|
|
742
|
+
var PartTypeId2 = "~effect/ai/Content/Part";
|
|
743
|
+
var isPart2 = (u) => Predicate4.hasProperty(u, PartTypeId2);
|
|
744
|
+
var AllParts = (toolkit) => {
|
|
745
|
+
const toolCalls = [];
|
|
746
|
+
const toolCallResults = [];
|
|
747
|
+
for (const tool of Object.values(toolkit.tools)) {
|
|
748
|
+
toolCalls.push(ToolCallPart2(tool.name, tool.parametersSchema));
|
|
749
|
+
toolCallResults.push(ToolResultPart2(tool.name, tool.successSchema, tool.failureSchema));
|
|
750
|
+
}
|
|
751
|
+
return Schema3.Union(TextPart2, TextStartPart, TextDeltaPart, TextEndPart, ReasoningPart2, ReasoningStartPart, ReasoningDeltaPart, ReasoningEndPart, ToolParamsStartPart, ToolParamsDeltaPart, ToolParamsEndPart, FilePart2, DocumentSourcePart, UrlSourcePart, ResponseMetadataPart, FinishPart, ErrorPart, ...toolCalls, ...toolCallResults);
|
|
752
|
+
};
|
|
753
|
+
var Part = (toolkit) => {
|
|
754
|
+
const toolCalls = [];
|
|
755
|
+
const toolCallResults = [];
|
|
756
|
+
for (const tool of Object.values(toolkit.tools)) {
|
|
757
|
+
toolCalls.push(ToolCallPart2(tool.name, tool.parametersSchema));
|
|
758
|
+
toolCallResults.push(ToolResultPart2(tool.name, tool.successSchema, tool.failureSchema));
|
|
759
|
+
}
|
|
760
|
+
return Schema3.Union(TextPart2, ReasoningPart2, FilePart2, DocumentSourcePart, UrlSourcePart, ResponseMetadataPart, FinishPart, ...toolCalls, ...toolCallResults);
|
|
761
|
+
};
|
|
762
|
+
var StreamPart = (toolkit) => {
|
|
763
|
+
const toolCalls = [];
|
|
764
|
+
const toolCallResults = [];
|
|
765
|
+
for (const tool of Object.values(toolkit.tools)) {
|
|
766
|
+
toolCalls.push(ToolCallPart2(tool.name, tool.parametersSchema));
|
|
767
|
+
toolCallResults.push(ToolResultPart2(tool.name, tool.successSchema, tool.failureSchema));
|
|
768
|
+
}
|
|
769
|
+
return Schema3.Union(TextStartPart, TextDeltaPart, TextEndPart, ReasoningStartPart, ReasoningDeltaPart, ReasoningEndPart, ToolParamsStartPart, ToolParamsDeltaPart, ToolParamsEndPart, FilePart2, DocumentSourcePart, UrlSourcePart, ResponseMetadataPart, FinishPart, ErrorPart, ...toolCalls, ...toolCallResults);
|
|
770
|
+
};
|
|
771
|
+
var ProviderMetadata = Schema3.Record({
|
|
772
|
+
key: Schema3.String,
|
|
773
|
+
value: Schema3.UndefinedOr(Schema3.Record({
|
|
774
|
+
key: Schema3.String,
|
|
775
|
+
value: Schema3.Unknown
|
|
776
|
+
}))
|
|
777
|
+
});
|
|
778
|
+
var makePart2 = (type, params) => ({
|
|
779
|
+
...params,
|
|
780
|
+
[PartTypeId2]: PartTypeId2,
|
|
781
|
+
type,
|
|
782
|
+
metadata: params.metadata ?? {}
|
|
783
|
+
});
|
|
784
|
+
var TextPart2 = Schema3.Struct({
|
|
785
|
+
type: Schema3.Literal("text"),
|
|
786
|
+
text: Schema3.String,
|
|
787
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
788
|
+
default: constEmptyObject2
|
|
789
|
+
})
|
|
790
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "TextPart" }));
|
|
791
|
+
var textPart2 = (params) => makePart2("text", params);
|
|
792
|
+
var TextStartPart = Schema3.Struct({
|
|
793
|
+
type: Schema3.Literal("text-start"),
|
|
794
|
+
id: Schema3.String,
|
|
795
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
796
|
+
default: constEmptyObject2
|
|
797
|
+
})
|
|
798
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "TextStartPart" }));
|
|
799
|
+
var textStartPart = (params) => makePart2("text-start", params);
|
|
800
|
+
var TextDeltaPart = Schema3.Struct({
|
|
801
|
+
type: Schema3.Literal("text-delta"),
|
|
802
|
+
id: Schema3.String,
|
|
803
|
+
delta: Schema3.String,
|
|
804
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
805
|
+
default: constEmptyObject2
|
|
806
|
+
})
|
|
807
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "TextDeltaPart" }));
|
|
808
|
+
var textDeltaPart = (params) => makePart2("text-delta", params);
|
|
809
|
+
var TextEndPart = Schema3.Struct({
|
|
810
|
+
type: Schema3.Literal("text-end"),
|
|
811
|
+
id: Schema3.String,
|
|
812
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
813
|
+
default: constEmptyObject2
|
|
814
|
+
})
|
|
815
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "TextEndPart" }));
|
|
816
|
+
var textEndPart = (params) => makePart2("text-end", params);
|
|
817
|
+
var ReasoningPart2 = Schema3.Struct({
|
|
818
|
+
type: Schema3.Literal("reasoning"),
|
|
819
|
+
text: Schema3.String,
|
|
820
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
821
|
+
default: constEmptyObject2
|
|
822
|
+
})
|
|
823
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ReasoningPart" }));
|
|
824
|
+
var reasoningPart2 = (params) => makePart2("reasoning", params);
|
|
825
|
+
var ReasoningStartPart = Schema3.Struct({
|
|
826
|
+
type: Schema3.Literal("reasoning-start"),
|
|
827
|
+
id: Schema3.String,
|
|
828
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
829
|
+
default: constEmptyObject2
|
|
830
|
+
})
|
|
831
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ReasoningStartPart" }));
|
|
832
|
+
var reasoningStartPart = (params) => makePart2("reasoning-start", params);
|
|
833
|
+
var ReasoningDeltaPart = Schema3.Struct({
|
|
834
|
+
type: Schema3.Literal("reasoning-delta"),
|
|
835
|
+
id: Schema3.String,
|
|
836
|
+
delta: Schema3.String,
|
|
837
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
838
|
+
default: constEmptyObject2
|
|
839
|
+
})
|
|
840
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ReasoningDeltaPart" }));
|
|
841
|
+
var reasoningDeltaPart = (params) => makePart2("reasoning-delta", params);
|
|
842
|
+
var ReasoningEndPart = Schema3.Struct({
|
|
843
|
+
type: Schema3.Literal("reasoning-end"),
|
|
844
|
+
id: Schema3.String,
|
|
845
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
846
|
+
default: constEmptyObject2
|
|
847
|
+
})
|
|
848
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ReasoningEndPart" }));
|
|
849
|
+
var reasoningEndPart = (params) => makePart2("reasoning-end", params);
|
|
850
|
+
var ToolParamsStartPart = Schema3.Struct({
|
|
851
|
+
type: Schema3.Literal("tool-params-start"),
|
|
852
|
+
id: Schema3.String,
|
|
853
|
+
name: Schema3.String,
|
|
854
|
+
providerName: Schema3.optional(Schema3.String),
|
|
855
|
+
providerExecuted: Schema3.optionalWith(Schema3.Boolean, {
|
|
856
|
+
default: constFalse2
|
|
857
|
+
}),
|
|
858
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
859
|
+
default: constEmptyObject2
|
|
860
|
+
})
|
|
861
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ToolParamsStartPart" }));
|
|
862
|
+
var toolParamsStartPart = (params) => makePart2("tool-params-start", params);
|
|
863
|
+
var ToolParamsDeltaPart = Schema3.Struct({
|
|
864
|
+
type: Schema3.Literal("tool-params-delta"),
|
|
865
|
+
id: Schema3.String,
|
|
866
|
+
delta: Schema3.String,
|
|
867
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
868
|
+
default: constEmptyObject2
|
|
869
|
+
})
|
|
870
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ToolParamsDeltaPart" }));
|
|
871
|
+
var toolParamsDeltaPart = (params) => makePart2("tool-params-delta", params);
|
|
872
|
+
var ToolParamsEndPart = Schema3.Struct({
|
|
873
|
+
type: Schema3.Literal("tool-params-end"),
|
|
874
|
+
id: Schema3.String,
|
|
875
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
876
|
+
default: constEmptyObject2
|
|
877
|
+
})
|
|
878
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ToolParamsEndPart" }));
|
|
879
|
+
var toolParamsEndPart = (params) => makePart2("tool-params-end", params);
|
|
880
|
+
var ToolCallPart2 = (name, params) => Schema3.Struct({
|
|
881
|
+
type: Schema3.Literal("tool-call"),
|
|
882
|
+
id: Schema3.String,
|
|
883
|
+
name: Schema3.Literal(name),
|
|
884
|
+
params,
|
|
885
|
+
providerName: Schema3.optional(Schema3.String),
|
|
886
|
+
providerExecuted: Schema3.optionalWith(Schema3.Boolean, {
|
|
887
|
+
default: constFalse2
|
|
888
|
+
}),
|
|
889
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
890
|
+
default: constEmptyObject2
|
|
891
|
+
})
|
|
892
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ToolCallPart" }));
|
|
893
|
+
var toolCallPart2 = (params) => makePart2("tool-call", params);
|
|
894
|
+
var ToolResultPart2 = (name, success, failure) => {
|
|
895
|
+
const Base = Schema3.Struct({
|
|
896
|
+
id: Schema3.String,
|
|
897
|
+
type: Schema3.Literal("tool-result"),
|
|
898
|
+
providerName: Schema3.optional(Schema3.String),
|
|
899
|
+
isFailure: Schema3.Boolean
|
|
900
|
+
});
|
|
901
|
+
const ResultSchema = Schema3.Union(success, failure);
|
|
902
|
+
const Encoded = Schema3.Struct({
|
|
903
|
+
...Base.fields,
|
|
904
|
+
name: Schema3.String,
|
|
905
|
+
result: Schema3.encodedSchema(ResultSchema),
|
|
906
|
+
providerExecuted: Schema3.optional(Schema3.Boolean),
|
|
907
|
+
metadata: Schema3.optional(ProviderMetadata)
|
|
908
|
+
});
|
|
909
|
+
const Decoded = Schema3.Struct({
|
|
910
|
+
...Base.fields,
|
|
911
|
+
[PartTypeId2]: Schema3.Literal(PartTypeId2),
|
|
912
|
+
name: Schema3.Literal(name),
|
|
913
|
+
result: Schema3.typeSchema(ResultSchema),
|
|
914
|
+
encodedResult: Schema3.encodedSchema(ResultSchema),
|
|
915
|
+
providerExecuted: Schema3.Boolean,
|
|
916
|
+
metadata: ProviderMetadata
|
|
917
|
+
});
|
|
918
|
+
const decodeResult = ParseResult2.decode(ResultSchema);
|
|
919
|
+
const encodeResult = ParseResult2.encode(ResultSchema);
|
|
920
|
+
return Schema3.transformOrFail(Encoded, Decoded, {
|
|
921
|
+
strict: true,
|
|
922
|
+
decode: Effect3.fnUntraced(function* (encoded) {
|
|
923
|
+
const decoded = yield* decodeResult(encoded.result);
|
|
924
|
+
const providerExecuted = encoded.providerExecuted ?? false;
|
|
925
|
+
return {
|
|
926
|
+
...encoded,
|
|
927
|
+
[PartTypeId2]: PartTypeId2,
|
|
928
|
+
name: encoded.name,
|
|
929
|
+
result: decoded,
|
|
930
|
+
encodedResult: encoded.result,
|
|
931
|
+
metadata: encoded.metadata ?? {},
|
|
932
|
+
providerExecuted
|
|
933
|
+
};
|
|
934
|
+
}),
|
|
935
|
+
encode: Effect3.fnUntraced(function* (decoded) {
|
|
936
|
+
const encoded = yield* encodeResult(decoded.result);
|
|
937
|
+
return {
|
|
938
|
+
...decoded,
|
|
939
|
+
result: encoded,
|
|
940
|
+
...decoded.metadata ?? {},
|
|
941
|
+
...decoded.providerName ? { providerName: decoded.providerName } : {},
|
|
942
|
+
...decoded.providerExecuted ? { providerExecuted: true } : {}
|
|
943
|
+
};
|
|
944
|
+
})
|
|
945
|
+
}).annotations({ identifier: `ToolResultPart(${name})` });
|
|
946
|
+
};
|
|
947
|
+
var toolResultPart2 = (params) => makePart2("tool-result", params);
|
|
948
|
+
var FilePart2 = Schema3.Struct({
|
|
949
|
+
type: Schema3.Literal("file"),
|
|
950
|
+
mediaType: Schema3.String,
|
|
951
|
+
data: Schema3.Uint8ArrayFromBase64,
|
|
952
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
953
|
+
default: constEmptyObject2
|
|
954
|
+
})
|
|
955
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "FilePart" }));
|
|
956
|
+
var filePart2 = (params) => makePart2("file", params);
|
|
957
|
+
var DocumentSourcePart = Schema3.Struct({
|
|
958
|
+
type: Schema3.Literal("source"),
|
|
959
|
+
sourceType: Schema3.Literal("document"),
|
|
960
|
+
id: Schema3.String,
|
|
961
|
+
mediaType: Schema3.String,
|
|
962
|
+
title: Schema3.String,
|
|
963
|
+
fileName: Schema3.optional(Schema3.String),
|
|
964
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
965
|
+
default: constEmptyObject2
|
|
966
|
+
})
|
|
967
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "DocumentSourcePart" }));
|
|
968
|
+
var documentSourcePart = (params) => makePart2("source", { ...params, sourceType: "document" });
|
|
969
|
+
var UrlSourcePart = Schema3.Struct({
|
|
970
|
+
type: Schema3.Literal("source"),
|
|
971
|
+
sourceType: Schema3.Literal("url"),
|
|
972
|
+
id: Schema3.String,
|
|
973
|
+
url: Schema3.URL,
|
|
974
|
+
title: Schema3.String,
|
|
975
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
976
|
+
default: constEmptyObject2
|
|
977
|
+
})
|
|
978
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "UrlSourcePart" }));
|
|
979
|
+
var urlSourcePart = (params) => makePart2("source", { ...params, sourceType: "url" });
|
|
980
|
+
var ResponseMetadataPart = Schema3.Struct({
|
|
981
|
+
type: Schema3.Literal("response-metadata"),
|
|
982
|
+
id: Schema3.optionalWith(Schema3.String, { as: "Option" }),
|
|
983
|
+
modelId: Schema3.optionalWith(Schema3.String, { as: "Option" }),
|
|
984
|
+
timestamp: Schema3.optionalWith(Schema3.DateTimeUtc, { as: "Option" }),
|
|
985
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
986
|
+
default: constEmptyObject2
|
|
987
|
+
})
|
|
988
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ResponseMetadataPart" }));
|
|
989
|
+
var responseMetadataPart = (params) => makePart2("response-metadata", params);
|
|
990
|
+
var FinishReason = Schema3.Literal("stop", "length", "content-filter", "tool-calls", "error", "pause", "other", "unknown");
|
|
991
|
+
|
|
992
|
+
class Usage extends Schema3.Class("@effect/ai/AiResponse/Usage")({
|
|
993
|
+
inputTokens: Schema3.UndefinedOr(Schema3.Number),
|
|
994
|
+
outputTokens: Schema3.UndefinedOr(Schema3.Number),
|
|
995
|
+
totalTokens: Schema3.UndefinedOr(Schema3.Number),
|
|
996
|
+
reasoningTokens: Schema3.optional(Schema3.Number),
|
|
997
|
+
cachedInputTokens: Schema3.optional(Schema3.Number)
|
|
998
|
+
}) {
|
|
999
|
+
}
|
|
1000
|
+
var FinishPart = Schema3.Struct({
|
|
1001
|
+
type: Schema3.Literal("finish"),
|
|
1002
|
+
reason: FinishReason,
|
|
1003
|
+
usage: Usage,
|
|
1004
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
1005
|
+
default: constEmptyObject2
|
|
1006
|
+
})
|
|
1007
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "FinishPart" }));
|
|
1008
|
+
var finishPart = (params) => makePart2("finish", params);
|
|
1009
|
+
var ErrorPart = Schema3.Struct({
|
|
1010
|
+
type: Schema3.Literal("error"),
|
|
1011
|
+
error: Schema3.Unknown,
|
|
1012
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
1013
|
+
default: constEmptyObject2
|
|
1014
|
+
})
|
|
1015
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ErrorPart" }));
|
|
1016
|
+
var errorPart = (params) => makePart2("error", params);
|
|
1017
|
+
var ObjectDeltaPart = Schema3.Struct({
|
|
1018
|
+
type: Schema3.Literal("object-delta"),
|
|
1019
|
+
id: Schema3.String,
|
|
1020
|
+
delta: Schema3.String,
|
|
1021
|
+
accumulated: Schema3.String,
|
|
1022
|
+
partial: Schema3.Unknown,
|
|
1023
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
1024
|
+
default: constEmptyObject2
|
|
1025
|
+
})
|
|
1026
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ObjectDeltaPart" }));
|
|
1027
|
+
var objectDeltaPart = (params) => makePart2("object-delta", params);
|
|
1028
|
+
var ObjectDonePart = Schema3.Struct({
|
|
1029
|
+
type: Schema3.Literal("object-done"),
|
|
1030
|
+
id: Schema3.String,
|
|
1031
|
+
value: Schema3.Unknown,
|
|
1032
|
+
raw: Schema3.String,
|
|
1033
|
+
metadata: Schema3.optionalWith(ProviderMetadata, {
|
|
1034
|
+
default: constEmptyObject2
|
|
1035
|
+
})
|
|
1036
|
+
}).pipe(Schema3.attachPropertySignature(PartTypeId2, PartTypeId2), Schema3.annotations({ identifier: "ObjectDonePart" }));
|
|
1037
|
+
var objectDonePart = (params) => makePart2("object-done", params);
|
|
1038
|
+
|
|
1039
|
+
// packages/ariadne/src/Telemetry.ts
|
|
1040
|
+
var exports_Telemetry = {};
|
|
1041
|
+
__export(exports_Telemetry, {
|
|
1042
|
+
addSpanAttributes: () => addSpanAttributes,
|
|
1043
|
+
addGenAIAnnotations: () => addGenAIAnnotations,
|
|
1044
|
+
CurrentSpanTransformer: () => CurrentSpanTransformer
|
|
1045
|
+
});
|
|
1046
|
+
import * as Context2 from "effect/Context";
|
|
1047
|
+
import { dual as dual2 } from "effect/Function";
|
|
1048
|
+
import * as Predicate5 from "effect/Predicate";
|
|
1049
|
+
import * as String5 from "effect/String";
|
|
1050
|
+
var addSpanAttributes = (keyPrefix, transformKey) => (span, attributes) => {
|
|
1051
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
1052
|
+
if (Predicate5.isNotNullable(value)) {
|
|
1053
|
+
span.attribute(`${keyPrefix}.${transformKey(key)}`, value);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
var addSpanBaseAttributes = addSpanAttributes("gen_ai", String5.camelToSnake);
|
|
1058
|
+
var addSpanOperationAttributes = addSpanAttributes("gen_ai.operation", String5.camelToSnake);
|
|
1059
|
+
var addSpanRequestAttributes = addSpanAttributes("gen_ai.request", String5.camelToSnake);
|
|
1060
|
+
var addSpanResponseAttributes = addSpanAttributes("gen_ai.response", String5.camelToSnake);
|
|
1061
|
+
var addSpanTokenAttributes = addSpanAttributes("gen_ai.token", String5.camelToSnake);
|
|
1062
|
+
var addSpanUsageAttributes = addSpanAttributes("gen_ai.usage", String5.camelToSnake);
|
|
1063
|
+
var addGenAIAnnotations = dual2(2, (span, options) => {
|
|
1064
|
+
addSpanBaseAttributes(span, { system: options.system });
|
|
1065
|
+
if (Predicate5.isNotNullable(options.operation))
|
|
1066
|
+
addSpanOperationAttributes(span, options.operation);
|
|
1067
|
+
if (Predicate5.isNotNullable(options.request))
|
|
1068
|
+
addSpanRequestAttributes(span, options.request);
|
|
1069
|
+
if (Predicate5.isNotNullable(options.response))
|
|
1070
|
+
addSpanResponseAttributes(span, options.response);
|
|
1071
|
+
if (Predicate5.isNotNullable(options.token))
|
|
1072
|
+
addSpanTokenAttributes(span, options.token);
|
|
1073
|
+
if (Predicate5.isNotNullable(options.usage))
|
|
1074
|
+
addSpanUsageAttributes(span, options.usage);
|
|
1075
|
+
});
|
|
1076
|
+
|
|
1077
|
+
class CurrentSpanTransformer extends Context2.Tag("@effect/ai/Telemetry/CurrentSpanTransformer")() {
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
// packages/ariadne/src/Toolkit.ts
|
|
1081
|
+
var exports_Toolkit = {};
|
|
1082
|
+
__export(exports_Toolkit, {
|
|
1083
|
+
merge: () => merge5,
|
|
1084
|
+
make: () => make4,
|
|
1085
|
+
empty: () => empty3,
|
|
1086
|
+
TypeId: () => TypeId4
|
|
1087
|
+
});
|
|
1088
|
+
import * as Context4 from "effect/Context";
|
|
1089
|
+
import * as Effect4 from "effect/Effect";
|
|
1090
|
+
import { CommitPrototype } from "effect/Effectable";
|
|
1091
|
+
import { identity as identity2 } from "effect/Function";
|
|
1092
|
+
import { BaseProto as InspectableProto } from "effect/Inspectable";
|
|
1093
|
+
import * as Layer2 from "effect/Layer";
|
|
1094
|
+
import * as ParseResult3 from "effect/ParseResult";
|
|
1095
|
+
import { pipeArguments as pipeArguments3 } from "effect/Pipeable";
|
|
1096
|
+
import * as Predicate7 from "effect/Predicate";
|
|
1097
|
+
import * as Schema5 from "effect/Schema";
|
|
1098
|
+
|
|
1099
|
+
// packages/ariadne/src/Tool.ts
|
|
1100
|
+
var exports_Tool = {};
|
|
1101
|
+
__export(exports_Tool, {
|
|
1102
|
+
unsafeSecureJsonParse: () => unsafeSecureJsonParse,
|
|
1103
|
+
providerDefined: () => providerDefined,
|
|
1104
|
+
make: () => make3,
|
|
1105
|
+
isUserDefined: () => isUserDefined,
|
|
1106
|
+
isProviderDefined: () => isProviderDefined,
|
|
1107
|
+
getJsonSchemaFromSchemaAst: () => getJsonSchemaFromSchemaAst,
|
|
1108
|
+
getJsonSchema: () => getJsonSchema,
|
|
1109
|
+
getDescriptionFromSchemaAst: () => getDescriptionFromSchemaAst,
|
|
1110
|
+
getDescription: () => getDescription,
|
|
1111
|
+
fromTaggedRequest: () => fromTaggedRequest,
|
|
1112
|
+
TypeId: () => TypeId3,
|
|
1113
|
+
Title: () => Title,
|
|
1114
|
+
Readonly: () => Readonly,
|
|
1115
|
+
ProviderDefinedTypeId: () => ProviderDefinedTypeId,
|
|
1116
|
+
OpenWorld: () => OpenWorld,
|
|
1117
|
+
Idempotent: () => Idempotent,
|
|
1118
|
+
Destructive: () => Destructive
|
|
1119
|
+
});
|
|
1120
|
+
import * as Context3 from "effect/Context";
|
|
1121
|
+
import { constFalse as constFalse3, constTrue, identity } from "effect/Function";
|
|
1122
|
+
import * as JsonSchema from "effect/JSONSchema";
|
|
1123
|
+
import * as Option2 from "effect/Option";
|
|
1124
|
+
import { pipeArguments as pipeArguments2 } from "effect/Pipeable";
|
|
1125
|
+
import * as Predicate6 from "effect/Predicate";
|
|
1126
|
+
import * as Schema4 from "effect/Schema";
|
|
1127
|
+
import * as AST from "effect/SchemaAST";
|
|
1128
|
+
var TypeId3 = "~@effect/ai/Tool";
|
|
1129
|
+
var ProviderDefinedTypeId = "~@effect/ai/Tool/ProviderDefined";
|
|
1130
|
+
var isUserDefined = (u) => Predicate6.hasProperty(u, TypeId3) && !isProviderDefined(u);
|
|
1131
|
+
var isProviderDefined = (u) => Predicate6.hasProperty(u, ProviderDefinedTypeId);
|
|
1132
|
+
var Proto2 = {
|
|
1133
|
+
[TypeId3]: { _Requirements: identity },
|
|
1134
|
+
pipe() {
|
|
1135
|
+
return pipeArguments2(this, arguments);
|
|
1136
|
+
},
|
|
1137
|
+
addDependency() {
|
|
1138
|
+
return userDefinedProto({ ...this });
|
|
1139
|
+
},
|
|
1140
|
+
setParameters(parametersSchema) {
|
|
1141
|
+
return userDefinedProto({
|
|
1142
|
+
...this,
|
|
1143
|
+
parametersSchema: Schema4.isSchema(parametersSchema) ? parametersSchema : Schema4.Struct(parametersSchema)
|
|
1144
|
+
});
|
|
1145
|
+
},
|
|
1146
|
+
setSuccess(successSchema) {
|
|
1147
|
+
return userDefinedProto({
|
|
1148
|
+
...this,
|
|
1149
|
+
successSchema
|
|
1150
|
+
});
|
|
1151
|
+
},
|
|
1152
|
+
setFailure(failureSchema) {
|
|
1153
|
+
return userDefinedProto({
|
|
1154
|
+
...this,
|
|
1155
|
+
failureSchema
|
|
1156
|
+
});
|
|
1157
|
+
},
|
|
1158
|
+
annotate(tag, value) {
|
|
1159
|
+
return userDefinedProto({
|
|
1160
|
+
...this,
|
|
1161
|
+
annotations: Context3.add(this.annotations, tag, value)
|
|
1162
|
+
});
|
|
1163
|
+
},
|
|
1164
|
+
annotateContext(context) {
|
|
1165
|
+
return userDefinedProto({
|
|
1166
|
+
...this,
|
|
1167
|
+
annotations: Context3.merge(this.annotations, context)
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
var ProviderDefinedProto = {
|
|
1172
|
+
...Proto2,
|
|
1173
|
+
[ProviderDefinedTypeId]: ProviderDefinedTypeId
|
|
1174
|
+
};
|
|
1175
|
+
var userDefinedProto = (options) => {
|
|
1176
|
+
const self = Object.assign(Object.create(Proto2), options);
|
|
1177
|
+
self.id = `@effect/ai/Tool/${options.name}`;
|
|
1178
|
+
return self;
|
|
1179
|
+
};
|
|
1180
|
+
var providerDefinedProto = (options) => Object.assign(Object.create(ProviderDefinedProto), options);
|
|
1181
|
+
var constEmptyStruct = Schema4.Struct({});
|
|
1182
|
+
var make3 = (name, options) => {
|
|
1183
|
+
const successSchema = options?.success ?? Schema4.Void;
|
|
1184
|
+
const failureSchema = options?.failure ?? Schema4.Never;
|
|
1185
|
+
return userDefinedProto({
|
|
1186
|
+
name,
|
|
1187
|
+
description: options?.description,
|
|
1188
|
+
parametersSchema: options?.parameters ? Schema4.Struct(options?.parameters) : constEmptyStruct,
|
|
1189
|
+
successSchema,
|
|
1190
|
+
failureSchema,
|
|
1191
|
+
failureMode: options?.failureMode ?? "error",
|
|
1192
|
+
annotations: Context3.empty()
|
|
1193
|
+
});
|
|
1194
|
+
};
|
|
1195
|
+
var providerDefined = (options) => (args) => {
|
|
1196
|
+
const failureMode = "failureMode" in args ? args.failureMode : undefined;
|
|
1197
|
+
const successSchema = options?.success ?? Schema4.Void;
|
|
1198
|
+
const failureSchema = options?.failure ?? Schema4.Never;
|
|
1199
|
+
return providerDefinedProto({
|
|
1200
|
+
id: options.id,
|
|
1201
|
+
name: options.toolkitName,
|
|
1202
|
+
providerName: options.providerName,
|
|
1203
|
+
args,
|
|
1204
|
+
argsSchema: Schema4.Struct(options.args),
|
|
1205
|
+
requiresHandler: options.requiresHandler ?? false,
|
|
1206
|
+
parametersSchema: options?.parameters ? Schema4.Struct(options?.parameters) : constEmptyStruct,
|
|
1207
|
+
successSchema,
|
|
1208
|
+
failureSchema,
|
|
1209
|
+
failureMode: failureMode ?? "error"
|
|
1210
|
+
});
|
|
1211
|
+
};
|
|
1212
|
+
var fromTaggedRequest = (schema) => userDefinedProto({
|
|
1213
|
+
name: schema._tag,
|
|
1214
|
+
description: Option2.getOrUndefined(AST.getDescriptionAnnotation(schema.ast.to)),
|
|
1215
|
+
parametersSchema: schema,
|
|
1216
|
+
successSchema: schema.success,
|
|
1217
|
+
failureSchema: schema.failure,
|
|
1218
|
+
failureMode: "error",
|
|
1219
|
+
annotations: Context3.empty()
|
|
1220
|
+
});
|
|
1221
|
+
var getDescription = (tool) => {
|
|
1222
|
+
if (Predicate6.isNotUndefined(tool.description)) {
|
|
1223
|
+
return tool.description;
|
|
1224
|
+
}
|
|
1225
|
+
return getDescriptionFromSchemaAst(tool.parametersSchema.ast);
|
|
1226
|
+
};
|
|
1227
|
+
var getDescriptionFromSchemaAst = (ast) => {
|
|
1228
|
+
const annotations3 = ast._tag === "Transformation" ? {
|
|
1229
|
+
...ast.to.annotations,
|
|
1230
|
+
...ast.annotations
|
|
1231
|
+
} : ast.annotations;
|
|
1232
|
+
return AST.DescriptionAnnotationId in annotations3 ? annotations3[AST.DescriptionAnnotationId] : undefined;
|
|
1233
|
+
};
|
|
1234
|
+
var getJsonSchema = (tool) => getJsonSchemaFromSchemaAst(tool.parametersSchema.ast);
|
|
1235
|
+
var getJsonSchemaFromSchemaAst = (ast) => {
|
|
1236
|
+
const props = AST.getPropertySignatures(ast);
|
|
1237
|
+
if (props.length === 0) {
|
|
1238
|
+
return {
|
|
1239
|
+
type: "object",
|
|
1240
|
+
properties: {},
|
|
1241
|
+
required: [],
|
|
1242
|
+
additionalProperties: false
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
const $defs = {};
|
|
1246
|
+
const schema = JsonSchema.fromAST(ast, {
|
|
1247
|
+
definitions: $defs,
|
|
1248
|
+
topLevelReferenceStrategy: "skip"
|
|
1249
|
+
});
|
|
1250
|
+
if (Object.keys($defs).length === 0)
|
|
1251
|
+
return schema;
|
|
1252
|
+
schema.$defs = $defs;
|
|
1253
|
+
return schema;
|
|
1254
|
+
};
|
|
1255
|
+
|
|
1256
|
+
class Title extends Context3.Tag("@effect/ai/Tool/Title")() {
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
class Readonly extends Context3.Reference()("@effect/ai/Tool/Readonly", {
|
|
1260
|
+
defaultValue: constFalse3
|
|
1261
|
+
}) {
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
class Destructive extends Context3.Reference()("@effect/ai/Tool/Destructive", {
|
|
1265
|
+
defaultValue: constTrue
|
|
1266
|
+
}) {
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
class Idempotent extends Context3.Reference()("@effect/ai/Tool/Idempotent", {
|
|
1270
|
+
defaultValue: constFalse3
|
|
1271
|
+
}) {
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
class OpenWorld extends Context3.Reference()("@effect/ai/Tool/OpenWorld", {
|
|
1275
|
+
defaultValue: constTrue
|
|
1276
|
+
}) {
|
|
1277
|
+
}
|
|
1278
|
+
var suspectProtoRx = /"__proto__"\s*:/;
|
|
1279
|
+
var suspectConstructorRx = /"constructor"\s*:/;
|
|
1280
|
+
function _parse(text) {
|
|
1281
|
+
const obj = JSON.parse(text);
|
|
1282
|
+
if (obj === null || typeof obj !== "object") {
|
|
1283
|
+
return obj;
|
|
1284
|
+
}
|
|
1285
|
+
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
|
|
1286
|
+
return obj;
|
|
1287
|
+
}
|
|
1288
|
+
return filter(obj);
|
|
1289
|
+
}
|
|
1290
|
+
function filter(obj) {
|
|
1291
|
+
let next2 = [obj];
|
|
1292
|
+
while (next2.length) {
|
|
1293
|
+
const nodes = next2;
|
|
1294
|
+
next2 = [];
|
|
1295
|
+
for (const node of nodes) {
|
|
1296
|
+
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
|
|
1297
|
+
throw new SyntaxError("Object contains forbidden prototype property");
|
|
1298
|
+
}
|
|
1299
|
+
if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
|
|
1300
|
+
throw new SyntaxError("Object contains forbidden prototype property");
|
|
1301
|
+
}
|
|
1302
|
+
for (const key in node) {
|
|
1303
|
+
const value = node[key];
|
|
1304
|
+
if (value && typeof value === "object") {
|
|
1305
|
+
next2.push(value);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
return obj;
|
|
1311
|
+
}
|
|
1312
|
+
var unsafeSecureJsonParse = (text) => {
|
|
1313
|
+
const { stackTraceLimit } = Error;
|
|
1314
|
+
Error.stackTraceLimit = 0;
|
|
1315
|
+
try {
|
|
1316
|
+
return _parse(text);
|
|
1317
|
+
} finally {
|
|
1318
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
1319
|
+
}
|
|
1320
|
+
};
|
|
1321
|
+
|
|
1322
|
+
// packages/ariadne/src/Toolkit.ts
|
|
1323
|
+
var TypeId4 = "~@effect/ai/Toolkit";
|
|
1324
|
+
var Proto3 = {
|
|
1325
|
+
...CommitPrototype,
|
|
1326
|
+
...InspectableProto,
|
|
1327
|
+
of: identity2,
|
|
1328
|
+
toContext(build) {
|
|
1329
|
+
return Effect4.gen(this, function* () {
|
|
1330
|
+
const context2 = yield* Effect4.context();
|
|
1331
|
+
const handlers = Effect4.isEffect(build) ? yield* build : build;
|
|
1332
|
+
const contextMap = new Map;
|
|
1333
|
+
for (const [name, handler] of Object.entries(handlers)) {
|
|
1334
|
+
const tool = this.tools[name];
|
|
1335
|
+
contextMap.set(tool.id, { handler, context: context2 });
|
|
1336
|
+
}
|
|
1337
|
+
return Context4.unsafeMake(contextMap);
|
|
1338
|
+
});
|
|
1339
|
+
},
|
|
1340
|
+
toLayer(build) {
|
|
1341
|
+
return Layer2.scopedContext(this.toContext(build));
|
|
1342
|
+
},
|
|
1343
|
+
commit() {
|
|
1344
|
+
return Effect4.gen(this, function* () {
|
|
1345
|
+
const tools = this.tools;
|
|
1346
|
+
const context2 = yield* Effect4.context();
|
|
1347
|
+
const schemasCache = new WeakMap;
|
|
1348
|
+
const getSchemas = (tool) => {
|
|
1349
|
+
let schemas = schemasCache.get(tool);
|
|
1350
|
+
if (Predicate7.isUndefined(schemas)) {
|
|
1351
|
+
const handler = context2.unsafeMap.get(tool.id);
|
|
1352
|
+
const decodeParameters = Schema5.decodeUnknown(tool.parametersSchema);
|
|
1353
|
+
const resultSchema = Schema5.Union(tool.successSchema, tool.failureSchema);
|
|
1354
|
+
const validateResult = Schema5.validate(resultSchema);
|
|
1355
|
+
const encodeResult = Schema5.encodeUnknown(resultSchema);
|
|
1356
|
+
schemas = {
|
|
1357
|
+
context: handler.context,
|
|
1358
|
+
handler: handler.handler,
|
|
1359
|
+
decodeParameters,
|
|
1360
|
+
validateResult,
|
|
1361
|
+
encodeResult
|
|
1362
|
+
};
|
|
1363
|
+
schemasCache.set(tool, schemas);
|
|
1364
|
+
}
|
|
1365
|
+
return schemas;
|
|
1366
|
+
};
|
|
1367
|
+
const handle = Effect4.fn("Toolkit.handle", {
|
|
1368
|
+
captureStackTrace: false
|
|
1369
|
+
})(function* (name, params) {
|
|
1370
|
+
yield* Effect4.annotateCurrentSpan({
|
|
1371
|
+
tool: name,
|
|
1372
|
+
parameters: params
|
|
1373
|
+
});
|
|
1374
|
+
const tool = tools[name];
|
|
1375
|
+
if (Predicate7.isUndefined(tool)) {
|
|
1376
|
+
const toolNames = Object.keys(tools).join(",");
|
|
1377
|
+
return yield* new MalformedOutput({
|
|
1378
|
+
module: "Toolkit",
|
|
1379
|
+
method: `${name}.handle`,
|
|
1380
|
+
description: `Failed to find tool with name '${name}' in toolkit - available tools: ${toolNames}`
|
|
1381
|
+
});
|
|
1382
|
+
}
|
|
1383
|
+
const schemas = getSchemas(tool);
|
|
1384
|
+
const decodedParams = yield* Effect4.mapError(schemas.decodeParameters(params), (cause) => new MalformedOutput({
|
|
1385
|
+
module: "Toolkit",
|
|
1386
|
+
method: `${name}.handle`,
|
|
1387
|
+
description: `Failed to decode tool call parameters for tool '${name}' from:
|
|
1388
|
+
'${JSON.stringify(params, undefined, 2)}'`,
|
|
1389
|
+
cause
|
|
1390
|
+
}));
|
|
1391
|
+
const { isFailure, result } = yield* schemas.handler(decodedParams).pipe(Effect4.map((result2) => ({ result: result2, isFailure: false })), Effect4.catchAll((error) => tool.failureMode === "error" ? Effect4.fail(error) : Effect4.succeed({
|
|
1392
|
+
result: error,
|
|
1393
|
+
isFailure: true
|
|
1394
|
+
})), Effect4.tap(({ result: result2 }) => schemas.validateResult(result2)), Effect4.mapInputContext((input) => Context4.merge(schemas.context, input)), Effect4.mapError((cause) => ParseResult3.isParseError(cause) ? new MalformedInput({
|
|
1395
|
+
module: "Toolkit",
|
|
1396
|
+
method: `${name}.handle`,
|
|
1397
|
+
description: `Failed to validate tool call result for tool '${name}'`,
|
|
1398
|
+
cause
|
|
1399
|
+
}) : cause));
|
|
1400
|
+
const encodedResult = yield* Effect4.mapError(schemas.encodeResult(result), (cause) => new MalformedInput({
|
|
1401
|
+
module: "Toolkit",
|
|
1402
|
+
method: `${name}.handle`,
|
|
1403
|
+
description: `Failed to encode tool call result for tool '${name}'`,
|
|
1404
|
+
cause
|
|
1405
|
+
}));
|
|
1406
|
+
return {
|
|
1407
|
+
isFailure,
|
|
1408
|
+
result,
|
|
1409
|
+
encodedResult
|
|
1410
|
+
};
|
|
1411
|
+
});
|
|
1412
|
+
return {
|
|
1413
|
+
tools,
|
|
1414
|
+
handle
|
|
1415
|
+
};
|
|
1416
|
+
});
|
|
1417
|
+
},
|
|
1418
|
+
toJSON() {
|
|
1419
|
+
return {
|
|
1420
|
+
_id: "@effect/ai/Toolkit",
|
|
1421
|
+
tools: Array.from(Object.values(this.tools)).map((tool) => tool.name)
|
|
1422
|
+
};
|
|
1423
|
+
},
|
|
1424
|
+
pipe() {
|
|
1425
|
+
return pipeArguments3(this, arguments);
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
var makeProto = (tools) => Object.assign(() => {}, Proto3, { tools });
|
|
1429
|
+
var resolveInput = (...tools) => {
|
|
1430
|
+
const output = {};
|
|
1431
|
+
for (const tool of tools) {
|
|
1432
|
+
const value = Schema5.isSchema(tool) ? fromTaggedRequest(tool) : tool;
|
|
1433
|
+
output[tool.name] = value;
|
|
1434
|
+
}
|
|
1435
|
+
return output;
|
|
1436
|
+
};
|
|
1437
|
+
var empty3 = makeProto({});
|
|
1438
|
+
var make4 = (...tools) => makeProto(resolveInput(...tools));
|
|
1439
|
+
var merge5 = (...toolkits) => {
|
|
1440
|
+
const tools = {};
|
|
1441
|
+
for (const toolkit of toolkits) {
|
|
1442
|
+
for (const [name, tool] of Object.entries(toolkit.tools)) {
|
|
1443
|
+
tools[name] = tool;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
return makeProto(tools);
|
|
1447
|
+
};
|
|
1448
|
+
|
|
1449
|
+
// packages/ariadne/src/LanguageModel.ts
|
|
1450
|
+
class LanguageModel extends Context5.Tag("@effect/ai/LanguageModel")() {
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
class GenerateTextResponse {
|
|
1454
|
+
content;
|
|
1455
|
+
constructor(content) {
|
|
1456
|
+
this.content = content;
|
|
1457
|
+
}
|
|
1458
|
+
get text() {
|
|
1459
|
+
const text = [];
|
|
1460
|
+
for (const part of this.content) {
|
|
1461
|
+
if (part.type === "text") {
|
|
1462
|
+
text.push(part.text);
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
return text.join("");
|
|
1466
|
+
}
|
|
1467
|
+
get reasoning() {
|
|
1468
|
+
return this.content.filter((part) => part.type === "reasoning");
|
|
1469
|
+
}
|
|
1470
|
+
get reasoningText() {
|
|
1471
|
+
const text = [];
|
|
1472
|
+
for (const part of this.content) {
|
|
1473
|
+
if (part.type === "reasoning") {
|
|
1474
|
+
text.push(part.text);
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
return text.length === 0 ? undefined : text.join("");
|
|
1478
|
+
}
|
|
1479
|
+
get toolCalls() {
|
|
1480
|
+
return this.content.filter((part) => part.type === "tool-call");
|
|
1481
|
+
}
|
|
1482
|
+
get toolResults() {
|
|
1483
|
+
return this.content.filter((part) => part.type === "tool-result");
|
|
1484
|
+
}
|
|
1485
|
+
get finishReason() {
|
|
1486
|
+
const finishPart2 = this.content.find((part) => part.type === "finish");
|
|
1487
|
+
return Predicate8.isUndefined(finishPart2) ? "unknown" : finishPart2.reason;
|
|
1488
|
+
}
|
|
1489
|
+
get usage() {
|
|
1490
|
+
const finishPart2 = this.content.find((part) => part.type === "finish");
|
|
1491
|
+
if (Predicate8.isUndefined(finishPart2)) {
|
|
1492
|
+
return new Usage({
|
|
1493
|
+
inputTokens: undefined,
|
|
1494
|
+
outputTokens: undefined,
|
|
1495
|
+
totalTokens: undefined,
|
|
1496
|
+
reasoningTokens: undefined,
|
|
1497
|
+
cachedInputTokens: undefined
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
return finishPart2.usage;
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
class GenerateObjectResponse extends GenerateTextResponse {
|
|
1505
|
+
value;
|
|
1506
|
+
constructor(value, content) {
|
|
1507
|
+
super(content);
|
|
1508
|
+
this.value = value;
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
var make6 = Effect5.fnUntraced(function* (params) {
|
|
1512
|
+
const parentSpanTransformer = yield* Effect5.serviceOption(CurrentSpanTransformer);
|
|
1513
|
+
const getSpanTransformer = Effect5.serviceOption(CurrentSpanTransformer).pipe(Effect5.map(Option3.orElse(() => parentSpanTransformer)));
|
|
1514
|
+
const idGenerator = yield* Effect5.serviceOption(IdGenerator).pipe(Effect5.map(Option3.getOrElse(() => defaultIdGenerator)));
|
|
1515
|
+
const generateText = (options) => Effect5.useSpan("LanguageModel.generateText", {
|
|
1516
|
+
captureStackTrace: false,
|
|
1517
|
+
attributes: {
|
|
1518
|
+
concurrency: options.concurrency,
|
|
1519
|
+
toolChoice: options.toolChoice
|
|
1520
|
+
}
|
|
1521
|
+
}, Effect5.fnUntraced(function* (span) {
|
|
1522
|
+
const spanTransformer = yield* getSpanTransformer;
|
|
1523
|
+
const providerOptions = {
|
|
1524
|
+
prompt: make2(options.prompt),
|
|
1525
|
+
tools: [],
|
|
1526
|
+
toolChoice: "none",
|
|
1527
|
+
responseFormat: { type: "text" },
|
|
1528
|
+
mcpServers: options.mcpServers ?? [],
|
|
1529
|
+
span
|
|
1530
|
+
};
|
|
1531
|
+
const content = yield* generateContent(options, providerOptions);
|
|
1532
|
+
applySpanTransformer(spanTransformer, content, providerOptions);
|
|
1533
|
+
return new GenerateTextResponse(content);
|
|
1534
|
+
}, Effect5.catchTag("ParseError", (error) => MalformedOutput.fromParseError({
|
|
1535
|
+
module: "LanguageModel",
|
|
1536
|
+
method: "generateText",
|
|
1537
|
+
error
|
|
1538
|
+
})), (effect2, span) => Effect5.withParentSpan(effect2, span), Effect5.provideService(IdGenerator, idGenerator)));
|
|
1539
|
+
const generateObject = (options) => {
|
|
1540
|
+
const schema = options.schema;
|
|
1541
|
+
const objectName = getObjectName(options.objectName, schema);
|
|
1542
|
+
return Effect5.useSpan("LanguageModel.generateObject", {
|
|
1543
|
+
captureStackTrace: false,
|
|
1544
|
+
attributes: {
|
|
1545
|
+
objectName,
|
|
1546
|
+
concurrency: options.concurrency,
|
|
1547
|
+
toolChoice: options.toolChoice
|
|
1548
|
+
}
|
|
1549
|
+
}, Effect5.fnUntraced(function* (span) {
|
|
1550
|
+
const spanTransformer = yield* getSpanTransformer;
|
|
1551
|
+
const providerOptions = {
|
|
1552
|
+
prompt: make2(options.prompt),
|
|
1553
|
+
tools: [],
|
|
1554
|
+
toolChoice: "none",
|
|
1555
|
+
responseFormat: {
|
|
1556
|
+
type: "json",
|
|
1557
|
+
objectName,
|
|
1558
|
+
schema
|
|
1559
|
+
},
|
|
1560
|
+
mcpServers: options.mcpServers ?? [],
|
|
1561
|
+
span
|
|
1562
|
+
};
|
|
1563
|
+
const content = yield* generateContent(options, providerOptions);
|
|
1564
|
+
applySpanTransformer(spanTransformer, content, providerOptions);
|
|
1565
|
+
const finishPart2 = content.find((part) => part.type === "finish");
|
|
1566
|
+
const finishReason = finishPart2?.reason ?? "unknown";
|
|
1567
|
+
if (finishReason === "tool-calls") {
|
|
1568
|
+
return new GenerateObjectResponse(undefined, content);
|
|
1569
|
+
}
|
|
1570
|
+
const value = yield* resolveStructuredOutput(content, schema);
|
|
1571
|
+
return new GenerateObjectResponse(value, content);
|
|
1572
|
+
}, Effect5.catchTag("ParseError", (error) => MalformedOutput.fromParseError({
|
|
1573
|
+
module: "LanguageModel",
|
|
1574
|
+
method: "generateText",
|
|
1575
|
+
error
|
|
1576
|
+
})), (effect2, span) => Effect5.withParentSpan(effect2, span), Effect5.provideService(IdGenerator, idGenerator)));
|
|
1577
|
+
};
|
|
1578
|
+
const streamText = Effect5.fnUntraced(function* (options) {
|
|
1579
|
+
const span = yield* Effect5.makeSpanScoped("LanguageModel.streamText", {
|
|
1580
|
+
captureStackTrace: false,
|
|
1581
|
+
attributes: {
|
|
1582
|
+
concurrency: options.concurrency,
|
|
1583
|
+
toolChoice: options.toolChoice
|
|
1584
|
+
}
|
|
1585
|
+
});
|
|
1586
|
+
const providerOptions = {
|
|
1587
|
+
prompt: make2(options.prompt),
|
|
1588
|
+
tools: [],
|
|
1589
|
+
toolChoice: "none",
|
|
1590
|
+
responseFormat: { type: "text" },
|
|
1591
|
+
mcpServers: options.mcpServers ?? [],
|
|
1592
|
+
span
|
|
1593
|
+
};
|
|
1594
|
+
const stream = yield* streamContent(options, providerOptions);
|
|
1595
|
+
const spanTransformer = yield* getSpanTransformer;
|
|
1596
|
+
if (Option3.isNone(spanTransformer)) {
|
|
1597
|
+
return stream;
|
|
1598
|
+
}
|
|
1599
|
+
let content = [];
|
|
1600
|
+
return stream.pipe(Stream.mapChunks((chunk) => {
|
|
1601
|
+
content = [...content, ...chunk];
|
|
1602
|
+
return chunk;
|
|
1603
|
+
}), Stream.ensuring(Effect5.sync(() => {
|
|
1604
|
+
spanTransformer.value({
|
|
1605
|
+
...providerOptions,
|
|
1606
|
+
response: content
|
|
1607
|
+
});
|
|
1608
|
+
})));
|
|
1609
|
+
}, Stream.unwrapScoped, Stream.mapError((error) => ParseResult4.isParseError(error) ? MalformedOutput.fromParseError({
|
|
1610
|
+
module: "LanguageModel",
|
|
1611
|
+
method: "streamText",
|
|
1612
|
+
error
|
|
1613
|
+
}) : error), Stream.provideService(IdGenerator, idGenerator));
|
|
1614
|
+
const generateContent = Effect5.fnUntraced(function* (options, providerOptions) {
|
|
1615
|
+
const toolChoice = options.toolChoice ?? "auto";
|
|
1616
|
+
if (Predicate8.isUndefined(options.toolkit)) {
|
|
1617
|
+
const ResponseSchema2 = Schema6.mutable(Schema6.Array(Part(empty3)));
|
|
1618
|
+
const rawContent2 = yield* params.generateText(providerOptions);
|
|
1619
|
+
const content2 = yield* Schema6.decodeUnknown(ResponseSchema2)(rawContent2);
|
|
1620
|
+
return content2;
|
|
1621
|
+
}
|
|
1622
|
+
const toolkit = yield* resolveToolkit(options.toolkit);
|
|
1623
|
+
if (Object.values(toolkit.tools).length === 0) {
|
|
1624
|
+
const ResponseSchema2 = Schema6.mutable(Schema6.Array(Part(empty3)));
|
|
1625
|
+
const rawContent2 = yield* params.generateText(providerOptions);
|
|
1626
|
+
const content2 = yield* Schema6.decodeUnknown(ResponseSchema2)(rawContent2);
|
|
1627
|
+
return content2;
|
|
1628
|
+
}
|
|
1629
|
+
const tools = typeof toolChoice === "object" && "oneOf" in toolChoice ? Object.values(toolkit.tools).filter((tool) => toolChoice.oneOf.includes(tool.name)) : Object.values(toolkit.tools);
|
|
1630
|
+
providerOptions.tools = tools;
|
|
1631
|
+
providerOptions.toolChoice = toolChoice;
|
|
1632
|
+
const ResponseSchema = Schema6.mutable(Schema6.Array(Part(toolkit)));
|
|
1633
|
+
if (options.disableToolCallResolution === true) {
|
|
1634
|
+
const rawContent2 = yield* params.generateText(providerOptions);
|
|
1635
|
+
const content2 = yield* Schema6.decodeUnknown(ResponseSchema)(rawContent2);
|
|
1636
|
+
return content2;
|
|
1637
|
+
}
|
|
1638
|
+
const rawContent = yield* params.generateText(providerOptions);
|
|
1639
|
+
const toolResults = yield* resolveToolCalls(rawContent, toolkit, options.concurrency);
|
|
1640
|
+
const content = yield* Schema6.decodeUnknown(ResponseSchema)(rawContent);
|
|
1641
|
+
return [...content, ...toolResults];
|
|
1642
|
+
});
|
|
1643
|
+
const streamContent = Effect5.fnUntraced(function* (options, providerOptions) {
|
|
1644
|
+
const toolChoice = options.toolChoice ?? "auto";
|
|
1645
|
+
if (Predicate8.isUndefined(options.toolkit)) {
|
|
1646
|
+
const schema = Schema6.ChunkFromSelf(StreamPart(empty3));
|
|
1647
|
+
const decode4 = Schema6.decode(schema);
|
|
1648
|
+
return params.streamText(providerOptions).pipe(Stream.mapChunksEffect(decode4));
|
|
1649
|
+
}
|
|
1650
|
+
const toolkit = Effect5.isEffect(options.toolkit) ? yield* options.toolkit : options.toolkit;
|
|
1651
|
+
if (Object.values(toolkit.tools).length === 0) {
|
|
1652
|
+
const schema = Schema6.ChunkFromSelf(StreamPart(empty3));
|
|
1653
|
+
const decode4 = Schema6.decode(schema);
|
|
1654
|
+
return params.streamText(providerOptions).pipe(Stream.mapChunksEffect(decode4));
|
|
1655
|
+
}
|
|
1656
|
+
const tools = typeof toolChoice === "object" && "oneOf" in toolChoice ? Object.values(toolkit.tools).filter((tool) => toolChoice.oneOf.includes(tool.name)) : Object.values(toolkit.tools);
|
|
1657
|
+
providerOptions.tools = tools;
|
|
1658
|
+
providerOptions.toolChoice = toolChoice;
|
|
1659
|
+
if (options.disableToolCallResolution === true) {
|
|
1660
|
+
const schema = Schema6.ChunkFromSelf(StreamPart(toolkit));
|
|
1661
|
+
const decode4 = Schema6.decode(schema);
|
|
1662
|
+
return params.streamText(providerOptions).pipe(Stream.mapChunksEffect(decode4));
|
|
1663
|
+
}
|
|
1664
|
+
const mailbox = yield* Mailbox.make();
|
|
1665
|
+
const ResponseSchema = Schema6.Array(StreamPart(toolkit));
|
|
1666
|
+
const decode3 = Schema6.decode(ResponseSchema);
|
|
1667
|
+
yield* params.streamText(providerOptions).pipe(Stream.runForEachChunk(Effect5.fnUntraced(function* (chunk) {
|
|
1668
|
+
const rawContent = Chunk.toArray(chunk);
|
|
1669
|
+
const content = yield* decode3(rawContent);
|
|
1670
|
+
yield* mailbox.offerAll(content);
|
|
1671
|
+
const toolResults = yield* resolveToolCalls(rawContent, toolkit, options.concurrency);
|
|
1672
|
+
yield* mailbox.offerAll(toolResults);
|
|
1673
|
+
})), Mailbox.into(mailbox), Effect5.forkScoped);
|
|
1674
|
+
return Mailbox.toStream(mailbox);
|
|
1675
|
+
});
|
|
1676
|
+
const streamObject = (options) => {
|
|
1677
|
+
const schema = options.schema;
|
|
1678
|
+
const objectName = getObjectName(options.objectName, schema);
|
|
1679
|
+
const tryParsePartial = (json) => {
|
|
1680
|
+
try {
|
|
1681
|
+
return JSON.parse(json);
|
|
1682
|
+
} catch {
|
|
1683
|
+
try {
|
|
1684
|
+
const trimmed = json.trim();
|
|
1685
|
+
let closed = trimmed;
|
|
1686
|
+
const openBraces = (trimmed.match(/\{/g) || []).length - (trimmed.match(/\}/g) || []).length;
|
|
1687
|
+
const openBrackets = (trimmed.match(/\[/g) || []).length - (trimmed.match(/\]/g) || []).length;
|
|
1688
|
+
for (let i = 0;i < openBrackets; i++)
|
|
1689
|
+
closed += "]";
|
|
1690
|
+
for (let i = 0;i < openBraces; i++)
|
|
1691
|
+
closed += "}";
|
|
1692
|
+
return JSON.parse(closed);
|
|
1693
|
+
} catch {
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
};
|
|
1698
|
+
return Effect5.fnUntraced(function* () {
|
|
1699
|
+
const span = yield* Effect5.makeSpanScoped("LanguageModel.streamObject", {
|
|
1700
|
+
captureStackTrace: false,
|
|
1701
|
+
attributes: { objectName }
|
|
1702
|
+
});
|
|
1703
|
+
const providerOptions = {
|
|
1704
|
+
prompt: make2(options.prompt),
|
|
1705
|
+
tools: [],
|
|
1706
|
+
toolChoice: "none",
|
|
1707
|
+
responseFormat: { type: "json", objectName, schema },
|
|
1708
|
+
mcpServers: options.mcpServers ?? [],
|
|
1709
|
+
span
|
|
1710
|
+
};
|
|
1711
|
+
const decodeSchema = Schema6.ChunkFromSelf(StreamPart(empty3));
|
|
1712
|
+
const decode3 = Schema6.decode(decodeSchema);
|
|
1713
|
+
const decodedStream = params.streamText(providerOptions).pipe(Stream.mapChunksEffect(decode3));
|
|
1714
|
+
const objectId = yield* idGenerator.generateId();
|
|
1715
|
+
let accumulated = "";
|
|
1716
|
+
return decodedStream.pipe(Stream.mapEffect(Effect5.fnUntraced(function* (part) {
|
|
1717
|
+
if (part.type === "text-delta") {
|
|
1718
|
+
accumulated += part.delta;
|
|
1719
|
+
const partial = tryParsePartial(accumulated);
|
|
1720
|
+
return objectDeltaPart({
|
|
1721
|
+
id: objectId,
|
|
1722
|
+
delta: part.delta,
|
|
1723
|
+
accumulated,
|
|
1724
|
+
partial
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
if (part.type === "finish") {
|
|
1728
|
+
const decodeJson = Schema6.decode(Schema6.parseJson(schema));
|
|
1729
|
+
const value = yield* Effect5.mapError(decodeJson(accumulated), (cause) => new MalformedOutput({
|
|
1730
|
+
module: "LanguageModel",
|
|
1731
|
+
method: "streamObject",
|
|
1732
|
+
description: "Generated object failed to conform to provided schema",
|
|
1733
|
+
cause
|
|
1734
|
+
}));
|
|
1735
|
+
return objectDonePart({
|
|
1736
|
+
id: objectId,
|
|
1737
|
+
value,
|
|
1738
|
+
raw: accumulated
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
if (part.type === "response-metadata") {
|
|
1742
|
+
return responseMetadataPart({
|
|
1743
|
+
id: part.id,
|
|
1744
|
+
modelId: part.modelId,
|
|
1745
|
+
timestamp: part.timestamp
|
|
1746
|
+
});
|
|
1747
|
+
}
|
|
1748
|
+
if (part.type === "error") {
|
|
1749
|
+
return errorPart({
|
|
1750
|
+
error: part.error
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
return;
|
|
1754
|
+
})), Stream.filter((part) => part !== undefined));
|
|
1755
|
+
}, Stream.unwrapScoped, Stream.mapError((error) => ParseResult4.isParseError(error) ? MalformedOutput.fromParseError({
|
|
1756
|
+
module: "LanguageModel",
|
|
1757
|
+
method: "streamObject",
|
|
1758
|
+
error
|
|
1759
|
+
}) : error), Stream.provideService(IdGenerator, idGenerator))();
|
|
1760
|
+
};
|
|
1761
|
+
return {
|
|
1762
|
+
generateText,
|
|
1763
|
+
generateObject,
|
|
1764
|
+
streamText,
|
|
1765
|
+
streamObject
|
|
1766
|
+
};
|
|
1767
|
+
});
|
|
1768
|
+
var generateText = Effect5.serviceFunctionEffect(LanguageModel, (model) => model.generateText);
|
|
1769
|
+
var generateObject = Effect5.serviceFunctionEffect(LanguageModel, (model) => model.generateObject);
|
|
1770
|
+
var streamText = (options) => Stream.unwrap(LanguageModel.pipe(Effect5.map((model) => model.streamText(options))));
|
|
1771
|
+
var streamObject = (options) => Stream.unwrap(LanguageModel.pipe(Effect5.map((model) => model.streamObject(options))));
|
|
1772
|
+
var resolveToolCalls = (content, toolkit, concurrency) => {
|
|
1773
|
+
const toolNames = [];
|
|
1774
|
+
const toolCalls = [];
|
|
1775
|
+
for (const part of content) {
|
|
1776
|
+
if (part.type === "tool-call") {
|
|
1777
|
+
toolNames.push(part.name);
|
|
1778
|
+
if (part.providerExecuted === true) {
|
|
1779
|
+
continue;
|
|
1780
|
+
}
|
|
1781
|
+
toolCalls.push(part);
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
return Effect5.forEach(toolCalls, (toolCall) => {
|
|
1785
|
+
return toolkit.handle(toolCall.name, toolCall.params).pipe(Effect5.map(({ encodedResult, isFailure, result }) => makePart2("tool-result", {
|
|
1786
|
+
id: toolCall.id,
|
|
1787
|
+
name: toolCall.name,
|
|
1788
|
+
result,
|
|
1789
|
+
encodedResult,
|
|
1790
|
+
isFailure,
|
|
1791
|
+
providerExecuted: false,
|
|
1792
|
+
...toolCall.providerName !== undefined ? { providerName: toolCall.providerName } : {}
|
|
1793
|
+
})));
|
|
1794
|
+
}, { concurrency });
|
|
1795
|
+
};
|
|
1796
|
+
var resolveToolkit = (toolkit) => Effect5.isEffect(toolkit) ? toolkit : Effect5.succeed(toolkit);
|
|
1797
|
+
var getObjectName = (objectName, schema) => Predicate8.isNotUndefined(objectName) ? objectName : ("_tag" in schema) ? schema._tag : ("identifier" in schema) ? schema.identifier : "generateObject";
|
|
1798
|
+
var resolveStructuredOutput = Effect5.fnUntraced(function* (response, ResultSchema) {
|
|
1799
|
+
const text = [];
|
|
1800
|
+
for (const part of response) {
|
|
1801
|
+
if (part.type === "text") {
|
|
1802
|
+
text.push(part.text);
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
if (text.length === 0) {
|
|
1806
|
+
return yield* new MalformedOutput({
|
|
1807
|
+
module: "LanguageModel",
|
|
1808
|
+
method: "generateObject",
|
|
1809
|
+
description: "No object was generated by the large language model"
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
const decode3 = Schema6.decode(Schema6.parseJson(ResultSchema));
|
|
1813
|
+
return yield* Effect5.mapError(decode3(text.join("")), (cause) => new MalformedOutput({
|
|
1814
|
+
module: "LanguageModel",
|
|
1815
|
+
method: "generateObject",
|
|
1816
|
+
description: "Generated object failed to conform to provided schema",
|
|
1817
|
+
cause
|
|
1818
|
+
}));
|
|
1819
|
+
});
|
|
1820
|
+
var applySpanTransformer = (transformer, response, options) => {
|
|
1821
|
+
if (Option3.isSome(transformer)) {
|
|
1822
|
+
transformer.value({ ...options, response });
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
|
|
1826
|
+
// packages/ariadne/src/AgentRunner.ts
|
|
1827
|
+
class Config extends Context6.Tag("ariadne/AgentRunner/Config")() {
|
|
1828
|
+
static getOrUndefined = Effect6.map(Effect6.context(), (context3) => context3.unsafeMap.get(Config.key));
|
|
1829
|
+
}
|
|
1830
|
+
var defaultConfig = Layer3.succeed(Config, {
|
|
1831
|
+
maxTurns: 10
|
|
1832
|
+
});
|
|
1833
|
+
var ReAct = Layer3.effect(LanguageModel, Effect6.gen(function* () {
|
|
1834
|
+
const underlying = yield* LanguageModel;
|
|
1835
|
+
const config = yield* Config.getOrUndefined;
|
|
1836
|
+
const maxTurns = config?.maxTurns ?? 10;
|
|
1837
|
+
const shouldTerminate = (finishReason) => finishReason === "stop" || finishReason === "length" || finishReason === "content-filter" || finishReason === "error" || finishReason === "unknown";
|
|
1838
|
+
const excludeFinishParts = (content) => content.filter((p) => p.type !== "finish");
|
|
1839
|
+
const generateText2 = (options) => Effect6.gen(function* () {
|
|
1840
|
+
const history = yield* Ref.make(make2(options.prompt));
|
|
1841
|
+
let turns = 0;
|
|
1842
|
+
let allContent = [];
|
|
1843
|
+
while (turns < maxTurns) {
|
|
1844
|
+
turns++;
|
|
1845
|
+
const currentPrompt = yield* Ref.get(history);
|
|
1846
|
+
const response = yield* underlying.generateText({
|
|
1847
|
+
...options,
|
|
1848
|
+
prompt: currentPrompt
|
|
1849
|
+
});
|
|
1850
|
+
if (shouldTerminate(response.finishReason)) {
|
|
1851
|
+
allContent = [...allContent, ...response.content];
|
|
1852
|
+
return new GenerateTextResponse(allContent);
|
|
1853
|
+
}
|
|
1854
|
+
allContent = [
|
|
1855
|
+
...allContent,
|
|
1856
|
+
...excludeFinishParts(response.content)
|
|
1857
|
+
];
|
|
1858
|
+
const newPrompt = merge2(currentPrompt, fromResponseParts(response.content));
|
|
1859
|
+
yield* Ref.set(history, newPrompt);
|
|
1860
|
+
}
|
|
1861
|
+
return new GenerateTextResponse(allContent);
|
|
1862
|
+
});
|
|
1863
|
+
const generateObject2 = (options) => Effect6.gen(function* () {
|
|
1864
|
+
const history = yield* Ref.make(make2(options.prompt));
|
|
1865
|
+
let turns = 0;
|
|
1866
|
+
let allContent = [];
|
|
1867
|
+
let finalValue;
|
|
1868
|
+
while (turns < maxTurns) {
|
|
1869
|
+
turns++;
|
|
1870
|
+
const currentPrompt = yield* Ref.get(history);
|
|
1871
|
+
const response = yield* underlying.generateObject({
|
|
1872
|
+
...options,
|
|
1873
|
+
prompt: currentPrompt
|
|
1874
|
+
});
|
|
1875
|
+
finalValue = response.value;
|
|
1876
|
+
if (shouldTerminate(response.finishReason)) {
|
|
1877
|
+
allContent = [...allContent, ...response.content];
|
|
1878
|
+
return new GenerateObjectResponse(finalValue, allContent);
|
|
1879
|
+
}
|
|
1880
|
+
allContent = [
|
|
1881
|
+
...allContent,
|
|
1882
|
+
...excludeFinishParts(response.content)
|
|
1883
|
+
];
|
|
1884
|
+
const newPrompt = merge2(currentPrompt, fromResponseParts(response.content));
|
|
1885
|
+
yield* Ref.set(history, newPrompt);
|
|
1886
|
+
}
|
|
1887
|
+
return new GenerateObjectResponse(finalValue, allContent);
|
|
1888
|
+
});
|
|
1889
|
+
const streamText2 = (options) => {
|
|
1890
|
+
const history = Ref.unsafeMake(make2(options.prompt));
|
|
1891
|
+
let turns = 0;
|
|
1892
|
+
const runTurn = () => Stream2.unwrap(Effect6.gen(function* () {
|
|
1893
|
+
if (turns >= maxTurns) {
|
|
1894
|
+
return Stream2.empty;
|
|
1895
|
+
}
|
|
1896
|
+
turns++;
|
|
1897
|
+
const currentPrompt = yield* Ref.get(history);
|
|
1898
|
+
let accumulatedParts = [];
|
|
1899
|
+
let finishReason = "unknown";
|
|
1900
|
+
const innerStream = underlying.streamText({
|
|
1901
|
+
...options,
|
|
1902
|
+
prompt: currentPrompt
|
|
1903
|
+
}).pipe(Stream2.tap((part) => Effect6.sync(() => {
|
|
1904
|
+
accumulatedParts.push(part);
|
|
1905
|
+
if (part.type === "finish") {
|
|
1906
|
+
finishReason = part.reason;
|
|
1907
|
+
}
|
|
1908
|
+
})));
|
|
1909
|
+
const continueOrEnd = Effect6.gen(function* () {
|
|
1910
|
+
if (!shouldTerminate(finishReason)) {
|
|
1911
|
+
const currentPrompt2 = yield* Ref.get(history);
|
|
1912
|
+
const newPrompt = merge2(currentPrompt2, fromResponseParts(accumulatedParts));
|
|
1913
|
+
yield* Ref.set(history, newPrompt);
|
|
1914
|
+
return runTurn();
|
|
1915
|
+
}
|
|
1916
|
+
return Stream2.empty;
|
|
1917
|
+
});
|
|
1918
|
+
return Stream2.concat(innerStream, Stream2.unwrap(continueOrEnd));
|
|
1919
|
+
}));
|
|
1920
|
+
return runTurn();
|
|
1921
|
+
};
|
|
1922
|
+
const streamObject2 = (options) => underlying.streamObject(options);
|
|
1923
|
+
return {
|
|
1924
|
+
generateText: generateText2,
|
|
1925
|
+
generateObject: generateObject2,
|
|
1926
|
+
streamText: streamText2,
|
|
1927
|
+
streamObject: streamObject2
|
|
1928
|
+
};
|
|
1929
|
+
}));
|
|
1930
|
+
// packages/ariadne/src/Chat.ts
|
|
1931
|
+
var exports_Chat = {};
|
|
1932
|
+
__export(exports_Chat, {
|
|
1933
|
+
makePersisted: () => makePersisted,
|
|
1934
|
+
layerPersisted: () => layerPersisted,
|
|
1935
|
+
fromPrompt: () => fromPrompt,
|
|
1936
|
+
fromJson: () => fromJson,
|
|
1937
|
+
fromExport: () => fromExport,
|
|
1938
|
+
empty: () => empty6,
|
|
1939
|
+
Persistence: () => Persistence,
|
|
1940
|
+
ChatNotFoundError: () => ChatNotFoundError,
|
|
1941
|
+
Chat: () => Chat
|
|
1942
|
+
});
|
|
1943
|
+
import { BackingPersistence } from "@effect/experimental/Persistence";
|
|
1944
|
+
import * as Channel from "effect/Channel";
|
|
1945
|
+
import * as Chunk2 from "effect/Chunk";
|
|
1946
|
+
import * as Context7 from "effect/Context";
|
|
1947
|
+
import * as Duration from "effect/Duration";
|
|
1948
|
+
import * as Effect7 from "effect/Effect";
|
|
1949
|
+
import * as Layer4 from "effect/Layer";
|
|
1950
|
+
import * as Option4 from "effect/Option";
|
|
1951
|
+
import * as Predicate9 from "effect/Predicate";
|
|
1952
|
+
import * as Ref2 from "effect/Ref";
|
|
1953
|
+
import * as Schema7 from "effect/Schema";
|
|
1954
|
+
import * as Stream3 from "effect/Stream";
|
|
1955
|
+
class Chat extends Context7.Tag("@effect/ai/Chat")() {
|
|
1956
|
+
}
|
|
1957
|
+
var empty6 = Effect7.gen(function* () {
|
|
1958
|
+
const history = yield* Ref2.make(empty);
|
|
1959
|
+
const context4 = yield* Effect7.context();
|
|
1960
|
+
const semaphore = yield* Effect7.makeSemaphore(1);
|
|
1961
|
+
const provideContext = (effect3) => Effect7.mapInputContext(effect3, (input) => Context7.merge(context4, input));
|
|
1962
|
+
const provideContextStream = (stream) => Stream3.mapInputContext(stream, (input) => Context7.merge(context4, input));
|
|
1963
|
+
const encodeHistory = Schema7.encode(Prompt);
|
|
1964
|
+
const encodeHistoryJson = Schema7.encode(FromJson);
|
|
1965
|
+
return Chat.of({
|
|
1966
|
+
history,
|
|
1967
|
+
export: Ref2.get(history).pipe(Effect7.flatMap(encodeHistory), Effect7.catchTag("ParseError", (error) => MalformedOutput.fromParseError({
|
|
1968
|
+
module: "Chat",
|
|
1969
|
+
method: "exportJson",
|
|
1970
|
+
description: "Failed to encode chat history",
|
|
1971
|
+
error
|
|
1972
|
+
})), Effect7.withSpan("Chat.export")),
|
|
1973
|
+
exportJson: Ref2.get(history).pipe(Effect7.flatMap(encodeHistoryJson), Effect7.catchTag("ParseError", (error) => MalformedOutput.fromParseError({
|
|
1974
|
+
module: "Chat",
|
|
1975
|
+
method: "exportJson",
|
|
1976
|
+
description: "Failed to encode chat history into JSON",
|
|
1977
|
+
error
|
|
1978
|
+
})), Effect7.withSpan("Chat.exportJson")),
|
|
1979
|
+
generateText: Effect7.fnUntraced(function* (options) {
|
|
1980
|
+
const newPrompt = make2(options.prompt);
|
|
1981
|
+
const oldPrompt = yield* Ref2.get(history);
|
|
1982
|
+
const prompt = merge2(oldPrompt, newPrompt);
|
|
1983
|
+
const response = yield* generateText({
|
|
1984
|
+
...options,
|
|
1985
|
+
prompt
|
|
1986
|
+
});
|
|
1987
|
+
const newHistory = merge2(prompt, fromResponseParts(response.content));
|
|
1988
|
+
yield* Ref2.set(history, newHistory);
|
|
1989
|
+
return response;
|
|
1990
|
+
}, provideContext, semaphore.withPermits(1), Effect7.withSpan("Chat.generateText", { captureStackTrace: false })),
|
|
1991
|
+
streamText: Effect7.fnUntraced(function* (options) {
|
|
1992
|
+
let parts = Chunk2.empty();
|
|
1993
|
+
return Stream3.fromChannel(Channel.acquireUseRelease(semaphore.take(1).pipe(Effect7.zipRight(Ref2.get(history)), Effect7.map((history2) => merge2(history2, make2(options.prompt)))), (prompt) => streamText({ ...options, prompt }).pipe(Stream3.mapChunks((chunk) => {
|
|
1994
|
+
parts = Chunk2.appendAll(parts, chunk);
|
|
1995
|
+
return chunk;
|
|
1996
|
+
}), Stream3.toChannel), (prompt) => Effect7.zipRight(Ref2.set(history, merge2(prompt, fromResponseParts(Array.from(parts)))), semaphore.release(1)))).pipe(provideContextStream, Stream3.withSpan("Chat.streamText", {
|
|
1997
|
+
captureStackTrace: false
|
|
1998
|
+
}));
|
|
1999
|
+
}, Stream3.unwrap),
|
|
2000
|
+
generateObject: Effect7.fnUntraced(function* (options) {
|
|
2001
|
+
const newPrompt = make2(options.prompt);
|
|
2002
|
+
const oldPrompt = yield* Ref2.get(history);
|
|
2003
|
+
const prompt = merge2(oldPrompt, newPrompt);
|
|
2004
|
+
const response = yield* generateObject({
|
|
2005
|
+
...options,
|
|
2006
|
+
prompt
|
|
2007
|
+
});
|
|
2008
|
+
const newHistory = merge2(prompt, fromResponseParts(response.content));
|
|
2009
|
+
yield* Ref2.set(history, newHistory);
|
|
2010
|
+
return response;
|
|
2011
|
+
}, provideContext, semaphore.withPermits(1), (effect3, options) => Effect7.withSpan(effect3, "Chat.generateObject", {
|
|
2012
|
+
attributes: {
|
|
2013
|
+
objectName: "objectName" in options ? options.objectName : ("_tag" in options.schema) ? options.schema._tag : options.schema.identifier ?? "generateObject"
|
|
2014
|
+
},
|
|
2015
|
+
captureStackTrace: false
|
|
2016
|
+
}))
|
|
2017
|
+
});
|
|
2018
|
+
});
|
|
2019
|
+
var fromPrompt = Effect7.fnUntraced(function* (prompt) {
|
|
2020
|
+
const chat = yield* empty6;
|
|
2021
|
+
yield* Ref2.set(chat.history, make2(prompt));
|
|
2022
|
+
return chat;
|
|
2023
|
+
});
|
|
2024
|
+
var decodeUnknown4 = Schema7.decodeUnknown(Prompt);
|
|
2025
|
+
var fromExport = (data) => Effect7.flatMap(decodeUnknown4(data), fromPrompt);
|
|
2026
|
+
var decodeHistoryJson = Schema7.decodeUnknown(FromJson);
|
|
2027
|
+
var fromJson = (data) => Effect7.flatMap(decodeHistoryJson(data), fromPrompt);
|
|
2028
|
+
|
|
2029
|
+
class ChatNotFoundError extends Schema7.TaggedError("@effect/ai/Chat/ChatNotFoundError")("ChatNotFoundError", { chatId: Schema7.String }) {
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
class Persistence extends Context7.Tag("@effect/ai/Chat/Persisted")() {
|
|
2033
|
+
}
|
|
2034
|
+
var makePersisted = Effect7.fnUntraced(function* (options) {
|
|
2035
|
+
const persistence = yield* BackingPersistence;
|
|
2036
|
+
const store = yield* persistence.make(options.storeId);
|
|
2037
|
+
const toPersisted = Effect7.fnUntraced(function* (chatId, chat, ttl) {
|
|
2038
|
+
const idGenerator = yield* Effect7.serviceOption(IdGenerator).pipe(Effect7.map(Option4.getOrElse(() => defaultIdGenerator)));
|
|
2039
|
+
const saveChat = Effect7.fnUntraced(function* (prevHistory) {
|
|
2040
|
+
const history = yield* Ref2.get(chat.history);
|
|
2041
|
+
const lastMessage = prevHistory.content[prevHistory.content.length - 1];
|
|
2042
|
+
let messageId = undefined;
|
|
2043
|
+
if (Predicate9.isNotUndefined(lastMessage) && lastMessage.role === "assistant") {
|
|
2044
|
+
messageId = lastMessage.options[Persistence.key]?.messageId;
|
|
2045
|
+
}
|
|
2046
|
+
if (Predicate9.isUndefined(messageId)) {
|
|
2047
|
+
messageId = yield* idGenerator.generateId();
|
|
2048
|
+
}
|
|
2049
|
+
for (let i = prevHistory.content.length;i < history.content.length; i++) {
|
|
2050
|
+
const message = history.content[i];
|
|
2051
|
+
message.options[Persistence.key] = { messageId };
|
|
2052
|
+
}
|
|
2053
|
+
yield* Ref2.set(chat.history, history);
|
|
2054
|
+
const json = yield* chat.exportJson;
|
|
2055
|
+
yield* store.set(chatId, json, ttl);
|
|
2056
|
+
}, Effect7.catchTag("PersistenceError", (error) => {
|
|
2057
|
+
if (error.reason === "ParseError")
|
|
2058
|
+
return Effect7.die(error);
|
|
2059
|
+
return Effect7.fail(error);
|
|
2060
|
+
}));
|
|
2061
|
+
const persisted = {
|
|
2062
|
+
...chat,
|
|
2063
|
+
id: chatId,
|
|
2064
|
+
save: Effect7.flatMap(Ref2.get(chat.history), saveChat),
|
|
2065
|
+
generateText: Effect7.fnUntraced(function* (options2) {
|
|
2066
|
+
const history = yield* Ref2.get(chat.history);
|
|
2067
|
+
return yield* chat.generateText(options2).pipe(Effect7.ensuring(Effect7.orDie(saveChat(history))));
|
|
2068
|
+
}),
|
|
2069
|
+
generateObject: Effect7.fnUntraced(function* (options2) {
|
|
2070
|
+
const history = yield* Ref2.get(chat.history);
|
|
2071
|
+
return yield* chat.generateObject(options2).pipe(Effect7.ensuring(Effect7.orDie(saveChat(history))));
|
|
2072
|
+
}),
|
|
2073
|
+
streamText: Effect7.fnUntraced(function* (options2) {
|
|
2074
|
+
const history = yield* Ref2.get(chat.history);
|
|
2075
|
+
const stream = chat.streamText(options2).pipe(Stream3.ensuring(Effect7.orDie(saveChat(history))));
|
|
2076
|
+
return stream;
|
|
2077
|
+
}, Stream3.unwrap)
|
|
2078
|
+
};
|
|
2079
|
+
return persisted;
|
|
2080
|
+
});
|
|
2081
|
+
const createChat = Effect7.fnUntraced(function* (chatId, ttl) {
|
|
2082
|
+
const chat = yield* empty6;
|
|
2083
|
+
const history = yield* chat.exportJson;
|
|
2084
|
+
yield* store.set(chatId, history, ttl);
|
|
2085
|
+
return yield* toPersisted(chatId, chat, ttl);
|
|
2086
|
+
}, Effect7.catchTag("PersistenceError", (error) => {
|
|
2087
|
+
if (error.reason === "ParseError")
|
|
2088
|
+
return Effect7.die(error);
|
|
2089
|
+
return Effect7.fail(error);
|
|
2090
|
+
}));
|
|
2091
|
+
const getChat = Effect7.fnUntraced(function* (chatId, ttl) {
|
|
2092
|
+
const chat = yield* empty6;
|
|
2093
|
+
yield* store.get(chatId).pipe(Effect7.flatMap(Effect7.transposeMapOption(decodeHistoryJson)), Effect7.flatten, Effect7.catchTag("NoSuchElementException", () => new ChatNotFoundError({ chatId })), Effect7.flatMap((history) => Ref2.set(chat.history, history)));
|
|
2094
|
+
return yield* toPersisted(chatId, chat, ttl);
|
|
2095
|
+
}, Effect7.catchTags({
|
|
2096
|
+
ParseError: (error) => Effect7.die(error),
|
|
2097
|
+
PersistenceError: (error) => {
|
|
2098
|
+
if (error.reason === "ParseError")
|
|
2099
|
+
return Effect7.die(error);
|
|
2100
|
+
return Effect7.fail(error);
|
|
2101
|
+
}
|
|
2102
|
+
}));
|
|
2103
|
+
const makeTTL = (timeToLive) => Option4.fromNullable(timeToLive).pipe(Option4.map(Duration.decode));
|
|
2104
|
+
const get3 = Effect7.fn("PersistedChat.get")(function* (chatId, options2) {
|
|
2105
|
+
const ttl = makeTTL(options2?.timeToLive);
|
|
2106
|
+
return yield* getChat(chatId, ttl);
|
|
2107
|
+
});
|
|
2108
|
+
const getOrCreate = Effect7.fn("PersistedChat.getOrCreate")(function* (chatId, options2) {
|
|
2109
|
+
const ttl = makeTTL(options2?.timeToLive);
|
|
2110
|
+
return yield* getChat(chatId, ttl).pipe(Effect7.catchTag("ChatNotFoundError", () => createChat(chatId, ttl)));
|
|
2111
|
+
});
|
|
2112
|
+
return Persistence.of({
|
|
2113
|
+
get: get3,
|
|
2114
|
+
getOrCreate
|
|
2115
|
+
});
|
|
2116
|
+
});
|
|
2117
|
+
var layerPersisted = (options) => Layer4.scoped(Persistence, makePersisted(options));
|
|
2118
|
+
// packages/ariadne/src/EmbeddingModel.ts
|
|
2119
|
+
var exports_EmbeddingModel = {};
|
|
2120
|
+
__export(exports_EmbeddingModel, {
|
|
2121
|
+
makeDataLoader: () => makeDataLoader,
|
|
2122
|
+
make: () => make9,
|
|
2123
|
+
EmbeddingModel: () => EmbeddingModel
|
|
2124
|
+
});
|
|
2125
|
+
import { dataLoader } from "@effect/experimental/RequestResolver";
|
|
2126
|
+
import * as Context8 from "effect/Context";
|
|
2127
|
+
import * as Effect8 from "effect/Effect";
|
|
2128
|
+
import { identity as identity3 } from "effect/Function";
|
|
2129
|
+
import * as Option5 from "effect/Option";
|
|
2130
|
+
import * as Request from "effect/Request";
|
|
2131
|
+
import * as RequestResolver from "effect/RequestResolver";
|
|
2132
|
+
import * as Schema8 from "effect/Schema";
|
|
2133
|
+
class EmbeddingModel extends Context8.Tag("@effect/ai/EmbeddingModel")() {
|
|
2134
|
+
}
|
|
2135
|
+
|
|
2136
|
+
class EmbeddingRequest extends Schema8.TaggedRequest("@effect/ai/EmbeddingModel/Request")("EmbeddingRequest", {
|
|
2137
|
+
failure: AiError,
|
|
2138
|
+
success: Schema8.mutable(Schema8.Array(Schema8.Number)),
|
|
2139
|
+
payload: { input: Schema8.String }
|
|
2140
|
+
}) {
|
|
2141
|
+
}
|
|
2142
|
+
var makeBatchedResolver = (embedMany) => RequestResolver.makeBatched((requests) => embedMany(requests.map((request2) => request2.input)).pipe(Effect8.flatMap(Effect8.forEach(({ embeddings, index }) => Request.succeed(requests[index], embeddings), { discard: true })), Effect8.catchAll((error) => Effect8.forEach(requests, (request2) => Request.fail(request2, error), { discard: true }))));
|
|
2143
|
+
var make9 = (options) => Effect8.gen(function* () {
|
|
2144
|
+
const cache = yield* Option5.fromNullable(options.cache).pipe(Effect8.flatMap((config) => Request.makeCache(config)), Effect8.optionFromOptional);
|
|
2145
|
+
const resolver = makeBatchedResolver(options.embedMany).pipe(options.maxBatchSize ? RequestResolver.batchN(options.maxBatchSize) : identity3);
|
|
2146
|
+
const embed = (input) => {
|
|
2147
|
+
const request2 = Effect8.request(new EmbeddingRequest({ input }), resolver);
|
|
2148
|
+
return Option5.match(cache, {
|
|
2149
|
+
onNone: () => request2,
|
|
2150
|
+
onSome: (cache2) => request2.pipe(Effect8.withRequestCaching(true), Effect8.withRequestCache(cache2))
|
|
2151
|
+
});
|
|
2152
|
+
};
|
|
2153
|
+
const embedMany = (inputs, options2) => Effect8.forEach(inputs, embed, {
|
|
2154
|
+
batching: true,
|
|
2155
|
+
concurrency: options2?.concurrency
|
|
2156
|
+
});
|
|
2157
|
+
return EmbeddingModel.of({
|
|
2158
|
+
embed: (input) => embed(input).pipe(Effect8.withSpan("EmbeddingModel.embed", {
|
|
2159
|
+
captureStackTrace: false
|
|
2160
|
+
})),
|
|
2161
|
+
embedMany: (inputs) => embedMany(inputs).pipe(Effect8.withSpan("EmbeddingModel.embedMany", {
|
|
2162
|
+
captureStackTrace: false
|
|
2163
|
+
}))
|
|
2164
|
+
});
|
|
2165
|
+
});
|
|
2166
|
+
var makeDataLoader = (options) => Effect8.gen(function* () {
|
|
2167
|
+
const resolver = makeBatchedResolver(options.embedMany);
|
|
2168
|
+
const resolverDelayed = yield* dataLoader(resolver, {
|
|
2169
|
+
window: options.window,
|
|
2170
|
+
maxBatchSize: options.maxBatchSize
|
|
2171
|
+
});
|
|
2172
|
+
function embed(input) {
|
|
2173
|
+
return Effect8.request(new EmbeddingRequest({ input }), resolverDelayed).pipe(Effect8.withSpan("EmbeddingModel.embed", {
|
|
2174
|
+
captureStackTrace: false
|
|
2175
|
+
}));
|
|
2176
|
+
}
|
|
2177
|
+
function embedMany(inputs, options2) {
|
|
2178
|
+
return Effect8.forEach(inputs, embed, {
|
|
2179
|
+
batching: true,
|
|
2180
|
+
concurrency: options2?.concurrency
|
|
2181
|
+
}).pipe(Effect8.withSpan("EmbeddingModel.embedMany", {
|
|
2182
|
+
captureStackTrace: false
|
|
2183
|
+
}));
|
|
2184
|
+
}
|
|
2185
|
+
return EmbeddingModel.of({
|
|
2186
|
+
embed,
|
|
2187
|
+
embedMany
|
|
2188
|
+
});
|
|
2189
|
+
});
|
|
2190
|
+
// packages/ariadne/src/McpRegistry.ts
|
|
2191
|
+
var exports_McpRegistry = {};
|
|
2192
|
+
__export(exports_McpRegistry, {
|
|
2193
|
+
url: () => url,
|
|
2194
|
+
toApiFormat: () => toApiFormat,
|
|
2195
|
+
marketplace: () => marketplace,
|
|
2196
|
+
make: () => make10,
|
|
2197
|
+
isUrl: () => isUrl,
|
|
2198
|
+
isMarketplace: () => isMarketplace
|
|
2199
|
+
});
|
|
2200
|
+
var url = (url2) => ({ _tag: "url", url: url2 });
|
|
2201
|
+
var marketplace = (id) => ({
|
|
2202
|
+
_tag: "marketplace",
|
|
2203
|
+
id
|
|
2204
|
+
});
|
|
2205
|
+
var make10 = (servers) => Array.from(servers);
|
|
2206
|
+
var toApiFormat = (servers) => servers.map((server) => server._tag === "url" ? server.url : server.id);
|
|
2207
|
+
var isUrl = (server) => server._tag === "url";
|
|
2208
|
+
var isMarketplace = (server) => server._tag === "marketplace";
|
|
2209
|
+
// packages/ariadne/src/McpSchema.ts
|
|
2210
|
+
var exports_McpSchema = {};
|
|
2211
|
+
__export(exports_McpSchema, {
|
|
2212
|
+
param: () => param,
|
|
2213
|
+
Unsubscribe: () => Unsubscribe,
|
|
2214
|
+
ToolListChangedNotification: () => ToolListChangedNotification,
|
|
2215
|
+
ToolAnnotations: () => ToolAnnotations,
|
|
2216
|
+
Tool: () => Tool,
|
|
2217
|
+
TextResourceContents: () => TextResourceContents,
|
|
2218
|
+
TextContent: () => TextContent,
|
|
2219
|
+
Subscribe: () => Subscribe,
|
|
2220
|
+
SetLevel: () => SetLevel,
|
|
2221
|
+
ServerRequestRpcs: () => ServerRequestRpcs,
|
|
2222
|
+
ServerNotificationRpcs: () => ServerNotificationRpcs,
|
|
2223
|
+
ServerCapabilities: () => ServerCapabilities,
|
|
2224
|
+
SamplingMessage: () => SamplingMessage,
|
|
2225
|
+
RootsListChangedNotification: () => RootsListChangedNotification,
|
|
2226
|
+
Root: () => Root,
|
|
2227
|
+
Role: () => Role,
|
|
2228
|
+
ResultMeta: () => ResultMeta,
|
|
2229
|
+
ResourceUpdatedNotification: () => ResourceUpdatedNotification,
|
|
2230
|
+
ResourceTemplate: () => ResourceTemplate,
|
|
2231
|
+
ResourceReference: () => ResourceReference,
|
|
2232
|
+
ResourceListChangedNotification: () => ResourceListChangedNotification,
|
|
2233
|
+
ResourceLink: () => ResourceLink,
|
|
2234
|
+
ResourceContents: () => ResourceContents,
|
|
2235
|
+
Resource: () => Resource,
|
|
2236
|
+
RequestMeta: () => RequestMeta,
|
|
2237
|
+
RequestId: () => RequestId,
|
|
2238
|
+
ReadResourceResult: () => ReadResourceResult,
|
|
2239
|
+
ReadResource: () => ReadResource,
|
|
2240
|
+
PromptReference: () => PromptReference,
|
|
2241
|
+
PromptMessage: () => PromptMessage,
|
|
2242
|
+
PromptListChangedNotification: () => PromptListChangedNotification,
|
|
2243
|
+
PromptArgument: () => PromptArgument,
|
|
2244
|
+
Prompt: () => Prompt2,
|
|
2245
|
+
ProgressToken: () => ProgressToken,
|
|
2246
|
+
ProgressNotification: () => ProgressNotification,
|
|
2247
|
+
Ping: () => Ping,
|
|
2248
|
+
ParseError: () => ParseError,
|
|
2249
|
+
ParamAnnotation: () => ParamAnnotation,
|
|
2250
|
+
PaginatedResultMeta: () => PaginatedResultMeta,
|
|
2251
|
+
PaginatedRequestMeta: () => PaginatedRequestMeta,
|
|
2252
|
+
PARSE_ERROR_CODE: () => PARSE_ERROR_CODE,
|
|
2253
|
+
NotificationMeta: () => NotificationMeta,
|
|
2254
|
+
ModelPreferences: () => ModelPreferences,
|
|
2255
|
+
ModelHint: () => ModelHint,
|
|
2256
|
+
MethodNotFound: () => MethodNotFound,
|
|
2257
|
+
McpServerClientMiddleware: () => McpServerClientMiddleware,
|
|
2258
|
+
McpServerClient: () => McpServerClient,
|
|
2259
|
+
McpError: () => McpError,
|
|
2260
|
+
METHOD_NOT_FOUND_ERROR_CODE: () => METHOD_NOT_FOUND_ERROR_CODE,
|
|
2261
|
+
LoggingMessageNotification: () => LoggingMessageNotification,
|
|
2262
|
+
LoggingLevel: () => LoggingLevel,
|
|
2263
|
+
ListToolsResult: () => ListToolsResult,
|
|
2264
|
+
ListTools: () => ListTools,
|
|
2265
|
+
ListRootsResult: () => ListRootsResult,
|
|
2266
|
+
ListRoots: () => ListRoots,
|
|
2267
|
+
ListResourcesResult: () => ListResourcesResult,
|
|
2268
|
+
ListResources: () => ListResources,
|
|
2269
|
+
ListResourceTemplatesResult: () => ListResourceTemplatesResult,
|
|
2270
|
+
ListResourceTemplates: () => ListResourceTemplates,
|
|
2271
|
+
ListPromptsResult: () => ListPromptsResult,
|
|
2272
|
+
ListPrompts: () => ListPrompts,
|
|
2273
|
+
InvalidRequest: () => InvalidRequest,
|
|
2274
|
+
InvalidParams: () => InvalidParams,
|
|
2275
|
+
InternalError: () => InternalError,
|
|
2276
|
+
InitializedNotification: () => InitializedNotification,
|
|
2277
|
+
InitializeResult: () => InitializeResult,
|
|
2278
|
+
Initialize: () => Initialize,
|
|
2279
|
+
Implementation: () => Implementation,
|
|
2280
|
+
ImageContent: () => ImageContent,
|
|
2281
|
+
INVALID_REQUEST_ERROR_CODE: () => INVALID_REQUEST_ERROR_CODE,
|
|
2282
|
+
INVALID_PARAMS_ERROR_CODE: () => INVALID_PARAMS_ERROR_CODE,
|
|
2283
|
+
INTERNAL_ERROR_CODE: () => INTERNAL_ERROR_CODE,
|
|
2284
|
+
GetPromptResult: () => GetPromptResult,
|
|
2285
|
+
GetPrompt: () => GetPrompt,
|
|
2286
|
+
EmbeddedResource: () => EmbeddedResource,
|
|
2287
|
+
ElicitationDeclined: () => ElicitationDeclined,
|
|
2288
|
+
ElicitResult: () => ElicitResult,
|
|
2289
|
+
ElicitDeclineResult: () => ElicitDeclineResult,
|
|
2290
|
+
ElicitAcceptResult: () => ElicitAcceptResult,
|
|
2291
|
+
Elicit: () => Elicit,
|
|
2292
|
+
Cursor: () => Cursor,
|
|
2293
|
+
CreateMessageResult: () => CreateMessageResult,
|
|
2294
|
+
CreateMessage: () => CreateMessage,
|
|
2295
|
+
ContentBlock: () => ContentBlock,
|
|
2296
|
+
CompleteResult: () => CompleteResult,
|
|
2297
|
+
Complete: () => Complete,
|
|
2298
|
+
ClientRpcs: () => ClientRpcs,
|
|
2299
|
+
ClientRequestRpcs: () => ClientRequestRpcs,
|
|
2300
|
+
ClientNotificationRpcs: () => ClientNotificationRpcs,
|
|
2301
|
+
ClientCapabilities: () => ClientCapabilities,
|
|
2302
|
+
CancelledNotification: () => CancelledNotification,
|
|
2303
|
+
CallToolResult: () => CallToolResult,
|
|
2304
|
+
CallTool: () => CallTool,
|
|
2305
|
+
BlobResourceContents: () => BlobResourceContents,
|
|
2306
|
+
AudioContent: () => AudioContent,
|
|
2307
|
+
Annotations: () => Annotations
|
|
2308
|
+
});
|
|
2309
|
+
import * as Rpc from "@effect/rpc/Rpc";
|
|
2310
|
+
import * as RpcGroup from "@effect/rpc/RpcGroup";
|
|
2311
|
+
import * as RpcMiddleware from "@effect/rpc/RpcMiddleware";
|
|
2312
|
+
import * as Context9 from "effect/Context";
|
|
2313
|
+
import * as Schema9 from "effect/Schema";
|
|
2314
|
+
var RequestId = Schema9.Union(Schema9.String, Schema9.Number);
|
|
2315
|
+
var ProgressToken = Schema9.Union(Schema9.String, Schema9.Number);
|
|
2316
|
+
|
|
2317
|
+
class RequestMeta extends Schema9.Struct({
|
|
2318
|
+
_meta: Schema9.optional(Schema9.Struct({
|
|
2319
|
+
progressToken: Schema9.optional(ProgressToken)
|
|
2320
|
+
}))
|
|
2321
|
+
}) {
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
class ResultMeta extends Schema9.Struct({
|
|
2325
|
+
_meta: Schema9.optional(Schema9.Record({ key: Schema9.String, value: Schema9.Unknown }))
|
|
2326
|
+
}) {
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
class NotificationMeta extends Schema9.Struct({
|
|
2330
|
+
_meta: Schema9.optional(Schema9.Record({ key: Schema9.String, value: Schema9.Unknown }))
|
|
2331
|
+
}) {
|
|
2332
|
+
}
|
|
2333
|
+
var Cursor = Schema9.String;
|
|
2334
|
+
|
|
2335
|
+
class PaginatedRequestMeta extends Schema9.Struct({
|
|
2336
|
+
...RequestMeta.fields,
|
|
2337
|
+
cursor: Schema9.optional(Cursor)
|
|
2338
|
+
}) {
|
|
2339
|
+
}
|
|
2340
|
+
|
|
2341
|
+
class PaginatedResultMeta extends Schema9.Struct({
|
|
2342
|
+
...ResultMeta.fields,
|
|
2343
|
+
nextCursor: Schema9.optional(Cursor)
|
|
2344
|
+
}) {
|
|
2345
|
+
}
|
|
2346
|
+
var Role = Schema9.Literal("user", "assistant");
|
|
2347
|
+
|
|
2348
|
+
class Annotations extends Schema9.Struct({
|
|
2349
|
+
audience: Schema9.optional(Schema9.Array(Role)),
|
|
2350
|
+
priority: Schema9.optional(Schema9.Number.pipe(Schema9.between(0, 1)))
|
|
2351
|
+
}) {
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
class Implementation extends Schema9.Struct({
|
|
2355
|
+
name: Schema9.String,
|
|
2356
|
+
title: Schema9.optional(Schema9.String),
|
|
2357
|
+
version: Schema9.String
|
|
2358
|
+
}) {
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
class ClientCapabilities extends Schema9.Class("@effect/ai/McpSchema/ClientCapabilities")({
|
|
2362
|
+
experimental: Schema9.optional(Schema9.Record({
|
|
2363
|
+
key: Schema9.String,
|
|
2364
|
+
value: Schema9.Struct({})
|
|
2365
|
+
})),
|
|
2366
|
+
roots: Schema9.optional(Schema9.Struct({
|
|
2367
|
+
listChanged: Schema9.optional(Schema9.Boolean)
|
|
2368
|
+
})),
|
|
2369
|
+
sampling: Schema9.optional(Schema9.Struct({})),
|
|
2370
|
+
elicitation: Schema9.optional(Schema9.Struct({}))
|
|
2371
|
+
}) {
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
class ServerCapabilities extends Schema9.Struct({
|
|
2375
|
+
experimental: Schema9.optional(Schema9.Record({
|
|
2376
|
+
key: Schema9.String,
|
|
2377
|
+
value: Schema9.Struct({})
|
|
2378
|
+
})),
|
|
2379
|
+
logging: Schema9.optional(Schema9.Struct({})),
|
|
2380
|
+
completions: Schema9.optional(Schema9.Struct({})),
|
|
2381
|
+
prompts: Schema9.optional(Schema9.Struct({
|
|
2382
|
+
listChanged: Schema9.optional(Schema9.Boolean)
|
|
2383
|
+
})),
|
|
2384
|
+
resources: Schema9.optional(Schema9.Struct({
|
|
2385
|
+
subscribe: Schema9.optional(Schema9.Boolean),
|
|
2386
|
+
listChanged: Schema9.optional(Schema9.Boolean)
|
|
2387
|
+
})),
|
|
2388
|
+
tools: Schema9.optional(Schema9.Struct({
|
|
2389
|
+
listChanged: Schema9.optional(Schema9.Boolean)
|
|
2390
|
+
}))
|
|
2391
|
+
}) {
|
|
2392
|
+
}
|
|
2393
|
+
|
|
2394
|
+
class McpError extends Schema9.Class("@effect/ai/McpSchema/McpError")({
|
|
2395
|
+
code: Schema9.Number,
|
|
2396
|
+
message: Schema9.String,
|
|
2397
|
+
data: Schema9.optional(Schema9.Unknown)
|
|
2398
|
+
}) {
|
|
2399
|
+
}
|
|
2400
|
+
var INVALID_REQUEST_ERROR_CODE = -32600;
|
|
2401
|
+
var METHOD_NOT_FOUND_ERROR_CODE = -32601;
|
|
2402
|
+
var INVALID_PARAMS_ERROR_CODE = -32602;
|
|
2403
|
+
var INTERNAL_ERROR_CODE = -32603;
|
|
2404
|
+
var PARSE_ERROR_CODE = -32700;
|
|
2405
|
+
|
|
2406
|
+
class ParseError extends Schema9.TaggedError()("ParseError", {
|
|
2407
|
+
...McpError.fields,
|
|
2408
|
+
code: Schema9.tag(PARSE_ERROR_CODE)
|
|
2409
|
+
}) {
|
|
2410
|
+
}
|
|
2411
|
+
|
|
2412
|
+
class InvalidRequest extends Schema9.TaggedError()("InvalidRequest", {
|
|
2413
|
+
...McpError.fields,
|
|
2414
|
+
code: Schema9.tag(INVALID_REQUEST_ERROR_CODE)
|
|
2415
|
+
}) {
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
class MethodNotFound extends Schema9.TaggedError()("MethodNotFound", {
|
|
2419
|
+
...McpError.fields,
|
|
2420
|
+
code: Schema9.tag(METHOD_NOT_FOUND_ERROR_CODE)
|
|
2421
|
+
}) {
|
|
2422
|
+
}
|
|
2423
|
+
|
|
2424
|
+
class InvalidParams extends Schema9.TaggedError()("InvalidParams", {
|
|
2425
|
+
...McpError.fields,
|
|
2426
|
+
code: Schema9.tag(INVALID_PARAMS_ERROR_CODE)
|
|
2427
|
+
}) {
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
class InternalError extends Schema9.TaggedError()("InternalError", {
|
|
2431
|
+
...McpError.fields,
|
|
2432
|
+
code: Schema9.tag(INTERNAL_ERROR_CODE)
|
|
2433
|
+
}) {
|
|
2434
|
+
static notImplemented = new InternalError({
|
|
2435
|
+
message: "Not implemented"
|
|
2436
|
+
});
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
class Ping extends Rpc.make("ping", {
|
|
2440
|
+
success: Schema9.Struct({}),
|
|
2441
|
+
error: McpError,
|
|
2442
|
+
payload: Schema9.UndefinedOr(RequestMeta)
|
|
2443
|
+
}) {
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
class InitializeResult extends Schema9.Class("@effect/ai/McpSchema/InitializeResult")({
|
|
2447
|
+
...ResultMeta.fields,
|
|
2448
|
+
protocolVersion: Schema9.String,
|
|
2449
|
+
capabilities: ServerCapabilities,
|
|
2450
|
+
serverInfo: Implementation,
|
|
2451
|
+
instructions: Schema9.optional(Schema9.String)
|
|
2452
|
+
}) {
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
class Initialize extends Rpc.make("initialize", {
|
|
2456
|
+
success: InitializeResult,
|
|
2457
|
+
error: McpError,
|
|
2458
|
+
payload: {
|
|
2459
|
+
...RequestMeta.fields,
|
|
2460
|
+
protocolVersion: Schema9.String,
|
|
2461
|
+
capabilities: ClientCapabilities,
|
|
2462
|
+
clientInfo: Implementation
|
|
2463
|
+
}
|
|
2464
|
+
}) {
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
class InitializedNotification extends Rpc.make("notifications/initialized", {
|
|
2468
|
+
payload: Schema9.UndefinedOr(NotificationMeta)
|
|
2469
|
+
}) {
|
|
2470
|
+
}
|
|
2471
|
+
|
|
2472
|
+
class CancelledNotification extends Rpc.make("notifications/cancelled", {
|
|
2473
|
+
payload: {
|
|
2474
|
+
...NotificationMeta.fields,
|
|
2475
|
+
requestId: RequestId,
|
|
2476
|
+
reason: Schema9.optional(Schema9.String)
|
|
2477
|
+
}
|
|
2478
|
+
}) {
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
class ProgressNotification extends Rpc.make("notifications/progress", {
|
|
2482
|
+
payload: {
|
|
2483
|
+
...NotificationMeta.fields,
|
|
2484
|
+
progressToken: ProgressToken,
|
|
2485
|
+
progress: Schema9.optional(Schema9.Number),
|
|
2486
|
+
total: Schema9.optional(Schema9.Number),
|
|
2487
|
+
message: Schema9.optional(Schema9.String)
|
|
2488
|
+
}
|
|
2489
|
+
}) {
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
class Resource extends Schema9.Class("@effect/ai/McpSchema/Resource")({
|
|
2493
|
+
uri: Schema9.String,
|
|
2494
|
+
name: Schema9.String,
|
|
2495
|
+
title: Schema9.optional(Schema9.String),
|
|
2496
|
+
description: Schema9.optional(Schema9.String),
|
|
2497
|
+
mimeType: Schema9.optional(Schema9.String),
|
|
2498
|
+
annotations: Schema9.optional(Annotations),
|
|
2499
|
+
size: Schema9.optional(Schema9.Number)
|
|
2500
|
+
}) {
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
class ResourceTemplate extends Schema9.Class("@effect/ai/McpSchema/ResourceTemplate")({
|
|
2504
|
+
uriTemplate: Schema9.String,
|
|
2505
|
+
name: Schema9.String,
|
|
2506
|
+
title: Schema9.optional(Schema9.String),
|
|
2507
|
+
description: Schema9.optional(Schema9.String),
|
|
2508
|
+
mimeType: Schema9.optional(Schema9.String),
|
|
2509
|
+
annotations: Schema9.optional(Annotations)
|
|
2510
|
+
}) {
|
|
2511
|
+
}
|
|
2512
|
+
|
|
2513
|
+
class ResourceContents extends Schema9.Struct({
|
|
2514
|
+
uri: Schema9.String,
|
|
2515
|
+
mimeType: Schema9.optional(Schema9.String)
|
|
2516
|
+
}) {
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2519
|
+
class TextResourceContents extends Schema9.Struct({
|
|
2520
|
+
...ResourceContents.fields,
|
|
2521
|
+
text: Schema9.String
|
|
2522
|
+
}) {
|
|
2523
|
+
}
|
|
2524
|
+
|
|
2525
|
+
class BlobResourceContents extends Schema9.Struct({
|
|
2526
|
+
...ResourceContents.fields,
|
|
2527
|
+
blob: Schema9.Uint8ArrayFromBase64
|
|
2528
|
+
}) {
|
|
2529
|
+
}
|
|
2530
|
+
|
|
2531
|
+
class ListResourcesResult extends Schema9.Class("@effect/ai/McpSchema/ListResourcesResult")({
|
|
2532
|
+
...PaginatedResultMeta.fields,
|
|
2533
|
+
resources: Schema9.Array(Resource)
|
|
2534
|
+
}) {
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
class ListResources extends Rpc.make("resources/list", {
|
|
2538
|
+
success: ListResourcesResult,
|
|
2539
|
+
error: McpError,
|
|
2540
|
+
payload: Schema9.UndefinedOr(PaginatedRequestMeta)
|
|
2541
|
+
}) {
|
|
2542
|
+
}
|
|
2543
|
+
|
|
2544
|
+
class ListResourceTemplatesResult extends Schema9.Class("@effect/ai/McpSchema/ListResourceTemplatesResult")({
|
|
2545
|
+
...PaginatedResultMeta.fields,
|
|
2546
|
+
resourceTemplates: Schema9.Array(ResourceTemplate)
|
|
2547
|
+
}) {
|
|
2548
|
+
}
|
|
2549
|
+
|
|
2550
|
+
class ListResourceTemplates extends Rpc.make("resources/templates/list", {
|
|
2551
|
+
success: ListResourceTemplatesResult,
|
|
2552
|
+
error: McpError,
|
|
2553
|
+
payload: Schema9.UndefinedOr(PaginatedRequestMeta)
|
|
2554
|
+
}) {
|
|
2555
|
+
}
|
|
2556
|
+
|
|
2557
|
+
class ReadResourceResult extends Schema9.Struct({
|
|
2558
|
+
...ResultMeta.fields,
|
|
2559
|
+
contents: Schema9.Array(Schema9.Union(TextResourceContents, BlobResourceContents))
|
|
2560
|
+
}) {
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
class ReadResource extends Rpc.make("resources/read", {
|
|
2564
|
+
success: ReadResourceResult,
|
|
2565
|
+
error: McpError,
|
|
2566
|
+
payload: {
|
|
2567
|
+
...RequestMeta.fields,
|
|
2568
|
+
uri: Schema9.String
|
|
2569
|
+
}
|
|
2570
|
+
}) {
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2573
|
+
class ResourceListChangedNotification extends Rpc.make("notifications/resources/list_changed", {
|
|
2574
|
+
payload: Schema9.UndefinedOr(NotificationMeta)
|
|
2575
|
+
}) {
|
|
2576
|
+
}
|
|
2577
|
+
|
|
2578
|
+
class Subscribe extends Rpc.make("resources/subscribe", {
|
|
2579
|
+
error: McpError,
|
|
2580
|
+
payload: {
|
|
2581
|
+
...RequestMeta.fields,
|
|
2582
|
+
uri: Schema9.String
|
|
2583
|
+
}
|
|
2584
|
+
}) {
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
class Unsubscribe extends Rpc.make("resources/unsubscribe", {
|
|
2588
|
+
error: McpError,
|
|
2589
|
+
payload: {
|
|
2590
|
+
...RequestMeta.fields,
|
|
2591
|
+
uri: Schema9.String
|
|
2592
|
+
}
|
|
2593
|
+
}) {
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2596
|
+
class ResourceUpdatedNotification extends Rpc.make("notifications/resources/updated", {
|
|
2597
|
+
payload: {
|
|
2598
|
+
...NotificationMeta.fields,
|
|
2599
|
+
uri: Schema9.String
|
|
2600
|
+
}
|
|
2601
|
+
}) {
|
|
2602
|
+
}
|
|
2603
|
+
|
|
2604
|
+
class PromptArgument extends Schema9.Struct({
|
|
2605
|
+
name: Schema9.String,
|
|
2606
|
+
title: Schema9.optional(Schema9.String),
|
|
2607
|
+
description: Schema9.optional(Schema9.String),
|
|
2608
|
+
required: Schema9.optional(Schema9.Boolean)
|
|
2609
|
+
}) {
|
|
2610
|
+
}
|
|
2611
|
+
|
|
2612
|
+
class Prompt2 extends Schema9.Class("@effect/ai/McpSchema/Prompt")({
|
|
2613
|
+
name: Schema9.String,
|
|
2614
|
+
title: Schema9.optional(Schema9.String),
|
|
2615
|
+
description: Schema9.optional(Schema9.String),
|
|
2616
|
+
arguments: Schema9.optional(Schema9.Array(PromptArgument))
|
|
2617
|
+
}) {
|
|
2618
|
+
}
|
|
2619
|
+
|
|
2620
|
+
class TextContent extends Schema9.Struct({
|
|
2621
|
+
type: Schema9.tag("text"),
|
|
2622
|
+
text: Schema9.String,
|
|
2623
|
+
annotations: Schema9.optional(Annotations)
|
|
2624
|
+
}) {
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
class ImageContent extends Schema9.Struct({
|
|
2628
|
+
type: Schema9.tag("image"),
|
|
2629
|
+
data: Schema9.Uint8ArrayFromBase64,
|
|
2630
|
+
mimeType: Schema9.String,
|
|
2631
|
+
annotations: Schema9.optional(Annotations)
|
|
2632
|
+
}) {
|
|
2633
|
+
}
|
|
2634
|
+
|
|
2635
|
+
class AudioContent extends Schema9.Struct({
|
|
2636
|
+
type: Schema9.tag("audio"),
|
|
2637
|
+
data: Schema9.Uint8ArrayFromBase64,
|
|
2638
|
+
mimeType: Schema9.String,
|
|
2639
|
+
annotations: Schema9.optional(Annotations)
|
|
2640
|
+
}) {
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2643
|
+
class EmbeddedResource extends Schema9.Struct({
|
|
2644
|
+
type: Schema9.tag("resource"),
|
|
2645
|
+
resource: Schema9.Union(TextResourceContents, BlobResourceContents),
|
|
2646
|
+
annotations: Schema9.optional(Annotations)
|
|
2647
|
+
}) {
|
|
2648
|
+
}
|
|
2649
|
+
|
|
2650
|
+
class ResourceLink extends Schema9.Struct({
|
|
2651
|
+
...Resource.fields,
|
|
2652
|
+
type: Schema9.tag("resource_link")
|
|
2653
|
+
}) {
|
|
2654
|
+
}
|
|
2655
|
+
|
|
2656
|
+
class ContentBlock extends Schema9.Union(TextContent, ImageContent, AudioContent, EmbeddedResource, ResourceLink) {
|
|
2657
|
+
}
|
|
2658
|
+
|
|
2659
|
+
class PromptMessage extends Schema9.Struct({
|
|
2660
|
+
role: Role,
|
|
2661
|
+
content: ContentBlock
|
|
2662
|
+
}) {
|
|
2663
|
+
}
|
|
2664
|
+
|
|
2665
|
+
class ListPromptsResult extends Schema9.Class("@effect/ai/McpSchema/ListPromptsResult")({
|
|
2666
|
+
...PaginatedResultMeta.fields,
|
|
2667
|
+
prompts: Schema9.Array(Prompt2)
|
|
2668
|
+
}) {
|
|
2669
|
+
}
|
|
2670
|
+
|
|
2671
|
+
class ListPrompts extends Rpc.make("prompts/list", {
|
|
2672
|
+
success: ListPromptsResult,
|
|
2673
|
+
error: McpError,
|
|
2674
|
+
payload: Schema9.UndefinedOr(PaginatedRequestMeta)
|
|
2675
|
+
}) {
|
|
2676
|
+
}
|
|
2677
|
+
|
|
2678
|
+
class GetPromptResult extends Schema9.Class("@effect/ai/McpSchema/GetPromptResult")({
|
|
2679
|
+
...ResultMeta.fields,
|
|
2680
|
+
messages: Schema9.Array(PromptMessage),
|
|
2681
|
+
description: Schema9.optional(Schema9.String)
|
|
2682
|
+
}) {
|
|
2683
|
+
}
|
|
2684
|
+
|
|
2685
|
+
class GetPrompt extends Rpc.make("prompts/get", {
|
|
2686
|
+
success: GetPromptResult,
|
|
2687
|
+
error: McpError,
|
|
2688
|
+
payload: {
|
|
2689
|
+
...RequestMeta.fields,
|
|
2690
|
+
name: Schema9.String,
|
|
2691
|
+
title: Schema9.optional(Schema9.String),
|
|
2692
|
+
arguments: Schema9.optional(Schema9.Record({
|
|
2693
|
+
key: Schema9.String,
|
|
2694
|
+
value: Schema9.String
|
|
2695
|
+
}))
|
|
2696
|
+
}
|
|
2697
|
+
}) {
|
|
2698
|
+
}
|
|
2699
|
+
|
|
2700
|
+
class PromptListChangedNotification extends Rpc.make("notifications/prompts/list_changed", {
|
|
2701
|
+
payload: Schema9.UndefinedOr(NotificationMeta)
|
|
2702
|
+
}) {
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
class ToolAnnotations extends Schema9.Class("@effect/ai/McpSchema/ToolAnnotations")({
|
|
2706
|
+
title: Schema9.optional(Schema9.String),
|
|
2707
|
+
readOnlyHint: Schema9.optionalWith(Schema9.Boolean, { default: () => false }),
|
|
2708
|
+
destructiveHint: Schema9.optionalWith(Schema9.Boolean, {
|
|
2709
|
+
default: () => true
|
|
2710
|
+
}),
|
|
2711
|
+
idempotentHint: Schema9.optionalWith(Schema9.Boolean, {
|
|
2712
|
+
default: () => false
|
|
2713
|
+
}),
|
|
2714
|
+
openWorldHint: Schema9.optionalWith(Schema9.Boolean, { default: () => true })
|
|
2715
|
+
}) {
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
class Tool extends Schema9.Class("@effect/ai/McpSchema/Tool")({
|
|
2719
|
+
name: Schema9.String,
|
|
2720
|
+
title: Schema9.optional(Schema9.String),
|
|
2721
|
+
description: Schema9.optional(Schema9.String),
|
|
2722
|
+
inputSchema: Schema9.Unknown,
|
|
2723
|
+
annotations: Schema9.optional(ToolAnnotations)
|
|
2724
|
+
}) {
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2727
|
+
class ListToolsResult extends Schema9.Class("@effect/ai/McpSchema/ListToolsResult")({
|
|
2728
|
+
...PaginatedResultMeta.fields,
|
|
2729
|
+
tools: Schema9.Array(Tool)
|
|
2730
|
+
}) {
|
|
2731
|
+
}
|
|
2732
|
+
|
|
2733
|
+
class ListTools extends Rpc.make("tools/list", {
|
|
2734
|
+
success: ListToolsResult,
|
|
2735
|
+
error: McpError,
|
|
2736
|
+
payload: Schema9.UndefinedOr(PaginatedRequestMeta)
|
|
2737
|
+
}) {
|
|
2738
|
+
}
|
|
2739
|
+
|
|
2740
|
+
class CallToolResult extends Schema9.Class("@effect/ai/McpSchema/CallToolResult")({
|
|
2741
|
+
...ResultMeta.fields,
|
|
2742
|
+
content: Schema9.Array(ContentBlock),
|
|
2743
|
+
structuredContent: Schema9.optional(Schema9.Unknown),
|
|
2744
|
+
isError: Schema9.optional(Schema9.Boolean)
|
|
2745
|
+
}) {
|
|
2746
|
+
}
|
|
2747
|
+
|
|
2748
|
+
class CallTool extends Rpc.make("tools/call", {
|
|
2749
|
+
success: CallToolResult,
|
|
2750
|
+
error: McpError,
|
|
2751
|
+
payload: {
|
|
2752
|
+
...RequestMeta.fields,
|
|
2753
|
+
name: Schema9.String,
|
|
2754
|
+
arguments: Schema9.Record({
|
|
2755
|
+
key: Schema9.String,
|
|
2756
|
+
value: Schema9.Unknown
|
|
2757
|
+
})
|
|
2758
|
+
}
|
|
2759
|
+
}) {
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2762
|
+
class ToolListChangedNotification extends Rpc.make("notifications/tools/list_changed", {
|
|
2763
|
+
payload: Schema9.UndefinedOr(NotificationMeta)
|
|
2764
|
+
}) {
|
|
2765
|
+
}
|
|
2766
|
+
var LoggingLevel = Schema9.Literal("debug", "info", "notice", "warning", "error", "critical", "alert", "emergency");
|
|
2767
|
+
|
|
2768
|
+
class SetLevel extends Rpc.make("logging/setLevel", {
|
|
2769
|
+
payload: {
|
|
2770
|
+
...RequestMeta.fields,
|
|
2771
|
+
level: LoggingLevel
|
|
2772
|
+
},
|
|
2773
|
+
error: McpError
|
|
2774
|
+
}) {
|
|
2775
|
+
}
|
|
2776
|
+
|
|
2777
|
+
class LoggingMessageNotification extends Rpc.make("notifications/message", {
|
|
2778
|
+
payload: Schema9.Struct({
|
|
2779
|
+
...NotificationMeta.fields,
|
|
2780
|
+
level: LoggingLevel,
|
|
2781
|
+
logger: Schema9.optional(Schema9.String),
|
|
2782
|
+
data: Schema9.Unknown
|
|
2783
|
+
})
|
|
2784
|
+
}) {
|
|
2785
|
+
}
|
|
2786
|
+
|
|
2787
|
+
class SamplingMessage extends Schema9.Struct({
|
|
2788
|
+
role: Role,
|
|
2789
|
+
content: Schema9.Union(TextContent, ImageContent, AudioContent)
|
|
2790
|
+
}) {
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
class ModelHint extends Schema9.Struct({
|
|
2794
|
+
name: Schema9.optional(Schema9.String)
|
|
2795
|
+
}) {
|
|
2796
|
+
}
|
|
2797
|
+
|
|
2798
|
+
class ModelPreferences extends Schema9.Class("@effect/ai/McpSchema/ModelPreferences")({
|
|
2799
|
+
hints: Schema9.optional(Schema9.Array(ModelHint)),
|
|
2800
|
+
costPriority: Schema9.optional(Schema9.Number.pipe(Schema9.between(0, 1))),
|
|
2801
|
+
speedPriority: Schema9.optional(Schema9.Number.pipe(Schema9.between(0, 1))),
|
|
2802
|
+
intelligencePriority: Schema9.optional(Schema9.Number.pipe(Schema9.between(0, 1)))
|
|
2803
|
+
}) {
|
|
2804
|
+
}
|
|
2805
|
+
|
|
2806
|
+
class CreateMessageResult extends Schema9.Class("@effect/ai/McpSchema/CreateMessageResult")({
|
|
2807
|
+
model: Schema9.String,
|
|
2808
|
+
stopReason: Schema9.optional(Schema9.String)
|
|
2809
|
+
}) {
|
|
2810
|
+
}
|
|
2811
|
+
|
|
2812
|
+
class CreateMessage extends Rpc.make("sampling/createMessage", {
|
|
2813
|
+
success: CreateMessageResult,
|
|
2814
|
+
error: McpError,
|
|
2815
|
+
payload: {
|
|
2816
|
+
messages: Schema9.Array(SamplingMessage),
|
|
2817
|
+
modelPreferences: Schema9.optional(ModelPreferences),
|
|
2818
|
+
systemPrompt: Schema9.optional(Schema9.String),
|
|
2819
|
+
includeContext: Schema9.optional(Schema9.Literal("none", "thisServer", "allServers")),
|
|
2820
|
+
temperature: Schema9.optional(Schema9.Number),
|
|
2821
|
+
maxTokens: Schema9.Number,
|
|
2822
|
+
stopSequences: Schema9.optional(Schema9.Array(Schema9.String)),
|
|
2823
|
+
metadata: Schema9.Unknown
|
|
2824
|
+
}
|
|
2825
|
+
}) {
|
|
2826
|
+
}
|
|
2827
|
+
|
|
2828
|
+
class ResourceReference extends Schema9.Struct({
|
|
2829
|
+
type: Schema9.tag("ref/resource"),
|
|
2830
|
+
uri: Schema9.String
|
|
2831
|
+
}) {
|
|
2832
|
+
}
|
|
2833
|
+
|
|
2834
|
+
class PromptReference extends Schema9.Struct({
|
|
2835
|
+
type: Schema9.tag("ref/prompt"),
|
|
2836
|
+
name: Schema9.String,
|
|
2837
|
+
title: Schema9.optional(Schema9.String)
|
|
2838
|
+
}) {
|
|
2839
|
+
}
|
|
2840
|
+
|
|
2841
|
+
class CompleteResult extends Schema9.Class("@effect/ai/McpSchema/CompleteResult")({
|
|
2842
|
+
completion: Schema9.Struct({
|
|
2843
|
+
values: Schema9.Array(Schema9.String),
|
|
2844
|
+
total: Schema9.optional(Schema9.Number),
|
|
2845
|
+
hasMore: Schema9.optional(Schema9.Boolean)
|
|
2846
|
+
})
|
|
2847
|
+
}) {
|
|
2848
|
+
static empty = CompleteResult.make({
|
|
2849
|
+
completion: {
|
|
2850
|
+
values: [],
|
|
2851
|
+
total: 0,
|
|
2852
|
+
hasMore: false
|
|
2853
|
+
}
|
|
2854
|
+
});
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
class Complete extends Rpc.make("completion/complete", {
|
|
2858
|
+
success: CompleteResult,
|
|
2859
|
+
error: McpError,
|
|
2860
|
+
payload: Schema9.Struct({
|
|
2861
|
+
ref: Schema9.Union(PromptReference, ResourceReference),
|
|
2862
|
+
argument: Schema9.Struct({
|
|
2863
|
+
name: Schema9.String,
|
|
2864
|
+
value: Schema9.String
|
|
2865
|
+
}),
|
|
2866
|
+
context: Schema9.optionalWith(Schema9.Struct({
|
|
2867
|
+
arguments: Schema9.optionalWith(Schema9.Record({
|
|
2868
|
+
key: Schema9.String,
|
|
2869
|
+
value: Schema9.String
|
|
2870
|
+
}), { default: () => ({}) })
|
|
2871
|
+
}), { default: () => ({ arguments: {} }) })
|
|
2872
|
+
})
|
|
2873
|
+
}) {
|
|
2874
|
+
}
|
|
2875
|
+
|
|
2876
|
+
class Root extends Schema9.Class("@effect/ai/McpSchema/Root")({
|
|
2877
|
+
uri: Schema9.String,
|
|
2878
|
+
name: Schema9.optional(Schema9.String)
|
|
2879
|
+
}) {
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
class ListRootsResult extends Schema9.Class("@effect/ai/McpSchema/ListRootsResult")({
|
|
2883
|
+
roots: Schema9.Array(Root)
|
|
2884
|
+
}) {
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
class ListRoots extends Rpc.make("roots/list", {
|
|
2888
|
+
success: ListRootsResult,
|
|
2889
|
+
error: McpError,
|
|
2890
|
+
payload: Schema9.UndefinedOr(RequestMeta)
|
|
2891
|
+
}) {
|
|
2892
|
+
}
|
|
2893
|
+
|
|
2894
|
+
class RootsListChangedNotification extends Rpc.make("notifications/roots/list_changed", {
|
|
2895
|
+
payload: Schema9.UndefinedOr(NotificationMeta)
|
|
2896
|
+
}) {
|
|
2897
|
+
}
|
|
2898
|
+
|
|
2899
|
+
class ElicitAcceptResult extends Schema9.Class("@effect/ai/McpSchema/ElicitAcceptResult")({
|
|
2900
|
+
...ResultMeta.fields,
|
|
2901
|
+
action: Schema9.Literal("accept"),
|
|
2902
|
+
content: Schema9.Unknown
|
|
2903
|
+
}) {
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
class ElicitDeclineResult extends Schema9.Class("@effect/ai/McpSchema/ElicitDeclineResult")({
|
|
2907
|
+
...ResultMeta.fields,
|
|
2908
|
+
action: Schema9.Literal("cancel", "decline")
|
|
2909
|
+
}) {
|
|
2910
|
+
}
|
|
2911
|
+
var ElicitResult = Schema9.Union(ElicitAcceptResult, ElicitDeclineResult);
|
|
2912
|
+
|
|
2913
|
+
class Elicit extends Rpc.make("elicitation/create", {
|
|
2914
|
+
success: ElicitResult,
|
|
2915
|
+
error: McpError,
|
|
2916
|
+
payload: {
|
|
2917
|
+
message: Schema9.String,
|
|
2918
|
+
requestedSchema: Schema9.Unknown
|
|
2919
|
+
}
|
|
2920
|
+
}) {
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
class ElicitationDeclined extends Schema9.TaggedError("@effect/ai/McpSchema/ElicitationDeclined")("ElicitationDeclined", {
|
|
2924
|
+
request: Elicit.payloadSchema,
|
|
2925
|
+
cause: Schema9.optional(Schema9.Defect)
|
|
2926
|
+
}) {
|
|
2927
|
+
}
|
|
2928
|
+
|
|
2929
|
+
class McpServerClient extends Context9.Tag("@effect/ai/McpSchema/McpServerClient")() {
|
|
2930
|
+
}
|
|
2931
|
+
|
|
2932
|
+
class McpServerClientMiddleware extends RpcMiddleware.Tag()("@effect/ai/McpSchema/McpServerClientMiddleware", {
|
|
2933
|
+
provides: McpServerClient
|
|
2934
|
+
}) {
|
|
2935
|
+
}
|
|
2936
|
+
|
|
2937
|
+
class ClientRequestRpcs extends RpcGroup.make(Ping, Initialize, Complete, SetLevel, GetPrompt, ListPrompts, ListResources, ListResourceTemplates, ReadResource, Subscribe, Unsubscribe, CallTool, ListTools).middleware(McpServerClientMiddleware) {
|
|
2938
|
+
}
|
|
2939
|
+
|
|
2940
|
+
class ClientNotificationRpcs extends RpcGroup.make(CancelledNotification, ProgressNotification, InitializedNotification, RootsListChangedNotification) {
|
|
2941
|
+
}
|
|
2942
|
+
|
|
2943
|
+
class ClientRpcs extends ClientRequestRpcs.merge(ClientNotificationRpcs) {
|
|
2944
|
+
}
|
|
2945
|
+
|
|
2946
|
+
class ServerRequestRpcs extends RpcGroup.make(Ping, CreateMessage, ListRoots, Elicit) {
|
|
2947
|
+
}
|
|
2948
|
+
|
|
2949
|
+
class ServerNotificationRpcs extends RpcGroup.make(CancelledNotification, ProgressNotification, LoggingMessageNotification, ResourceUpdatedNotification, ResourceListChangedNotification, ToolListChangedNotification, PromptListChangedNotification) {
|
|
2950
|
+
}
|
|
2951
|
+
var ParamAnnotation = Symbol.for("@effect/ai/McpSchema/ParamNameId");
|
|
2952
|
+
var param = (id, schema) => schema.annotations({
|
|
2953
|
+
[ParamAnnotation]: id
|
|
2954
|
+
});
|
|
2955
|
+
// packages/ariadne/src/McpServer.ts
|
|
2956
|
+
var exports_McpServer = {};
|
|
2957
|
+
__export(exports_McpServer, {
|
|
2958
|
+
toolkit: () => toolkit,
|
|
2959
|
+
run: () => run,
|
|
2960
|
+
resource: () => resource,
|
|
2961
|
+
registerToolkit: () => registerToolkit,
|
|
2962
|
+
registerResource: () => registerResource,
|
|
2963
|
+
registerPrompt: () => registerPrompt,
|
|
2964
|
+
prompt: () => prompt,
|
|
2965
|
+
layerStdio: () => layerStdio,
|
|
2966
|
+
layerHttpRouter: () => layerHttpRouter,
|
|
2967
|
+
layerHttp: () => layerHttp,
|
|
2968
|
+
layer: () => layer2,
|
|
2969
|
+
elicit: () => elicit,
|
|
2970
|
+
McpServer: () => McpServer
|
|
2971
|
+
});
|
|
2972
|
+
import * as Headers from "@effect/platform/Headers";
|
|
2973
|
+
import * as RpcClient from "@effect/rpc/RpcClient";
|
|
2974
|
+
import * as RpcSerialization from "@effect/rpc/RpcSerialization";
|
|
2975
|
+
import * as RpcServer from "@effect/rpc/RpcServer";
|
|
2976
|
+
import * as Arr2 from "effect/Array";
|
|
2977
|
+
import * as Cause2 from "effect/Cause";
|
|
2978
|
+
import * as Context10 from "effect/Context";
|
|
2979
|
+
import * as Effect9 from "effect/Effect";
|
|
2980
|
+
import * as Exit from "effect/Exit";
|
|
2981
|
+
import * as JsonSchema2 from "effect/JSONSchema";
|
|
2982
|
+
import * as Layer5 from "effect/Layer";
|
|
2983
|
+
import * as Logger from "effect/Logger";
|
|
2984
|
+
import * as Mailbox2 from "effect/Mailbox";
|
|
2985
|
+
import * as Option6 from "effect/Option";
|
|
2986
|
+
import * as RcMap from "effect/RcMap";
|
|
2987
|
+
import * as Schema10 from "effect/Schema";
|
|
2988
|
+
import * as AST2 from "effect/SchemaAST";
|
|
2989
|
+
import * as FindMyWay from "find-my-way-ts";
|
|
2990
|
+
class McpServer extends Context10.Tag("@effect/ai/McpServer")() {
|
|
2991
|
+
static make = Effect9.gen(function* () {
|
|
2992
|
+
const matcher = makeUriMatcher();
|
|
2993
|
+
const tools = Arr2.empty();
|
|
2994
|
+
const toolMap = new Map;
|
|
2995
|
+
const resources = [];
|
|
2996
|
+
const resourceTemplates = [];
|
|
2997
|
+
const prompts = [];
|
|
2998
|
+
const promptMap = new Map;
|
|
2999
|
+
const completionsMap = new Map;
|
|
3000
|
+
const notificationsMailbox = yield* Mailbox2.make();
|
|
3001
|
+
const listChangedHandles = new Map;
|
|
3002
|
+
const notifications = yield* RpcClient.makeNoSerialization(ServerNotificationRpcs, {
|
|
3003
|
+
spanPrefix: "McpServer/Notifications",
|
|
3004
|
+
onFromClient(options) {
|
|
3005
|
+
const message = options.message;
|
|
3006
|
+
if (message._tag !== "Request") {
|
|
3007
|
+
return Effect9.void;
|
|
3008
|
+
}
|
|
3009
|
+
if (message.tag.includes("list_changed")) {
|
|
3010
|
+
if (!listChangedHandles.has(message.tag)) {
|
|
3011
|
+
listChangedHandles.set(message.tag, setTimeout(() => {
|
|
3012
|
+
notificationsMailbox.unsafeOffer(message);
|
|
3013
|
+
listChangedHandles.delete(message.tag);
|
|
3014
|
+
}, 0));
|
|
3015
|
+
}
|
|
3016
|
+
} else {
|
|
3017
|
+
notificationsMailbox.unsafeOffer(message);
|
|
3018
|
+
}
|
|
3019
|
+
return notifications.write({
|
|
3020
|
+
clientId: 0,
|
|
3021
|
+
requestId: message.id,
|
|
3022
|
+
_tag: "Exit",
|
|
3023
|
+
exit: Exit.void
|
|
3024
|
+
});
|
|
3025
|
+
}
|
|
3026
|
+
});
|
|
3027
|
+
return McpServer.of({
|
|
3028
|
+
notifications: notifications.client,
|
|
3029
|
+
notificationsMailbox,
|
|
3030
|
+
initializedClients: new Set,
|
|
3031
|
+
get tools() {
|
|
3032
|
+
return tools;
|
|
3033
|
+
},
|
|
3034
|
+
addTool: (options) => Effect9.suspend(() => {
|
|
3035
|
+
tools.push(options.tool);
|
|
3036
|
+
toolMap.set(options.tool.name, options.handle);
|
|
3037
|
+
return notifications.client["notifications/tools/list_changed"]({});
|
|
3038
|
+
}),
|
|
3039
|
+
callTool: (request2) => Effect9.suspend(() => {
|
|
3040
|
+
const handle = toolMap.get(request2.name);
|
|
3041
|
+
if (!handle) {
|
|
3042
|
+
return Effect9.fail(new InvalidParams({
|
|
3043
|
+
message: `Tool '${request2.name}' not found`
|
|
3044
|
+
}));
|
|
3045
|
+
}
|
|
3046
|
+
return handle(request2.arguments);
|
|
3047
|
+
}),
|
|
3048
|
+
get resources() {
|
|
3049
|
+
return resources;
|
|
3050
|
+
},
|
|
3051
|
+
get resourceTemplates() {
|
|
3052
|
+
return resourceTemplates;
|
|
3053
|
+
},
|
|
3054
|
+
addResource: (resource, effect3) => Effect9.suspend(() => {
|
|
3055
|
+
resources.push(resource);
|
|
3056
|
+
matcher.add(resource.uri, { _tag: "Resource", effect: effect3 });
|
|
3057
|
+
return notifications.client["notifications/resources/list_changed"]({});
|
|
3058
|
+
}),
|
|
3059
|
+
addResourceTemplate: ({
|
|
3060
|
+
completions,
|
|
3061
|
+
handle,
|
|
3062
|
+
routerPath,
|
|
3063
|
+
template
|
|
3064
|
+
}) => Effect9.suspend(() => {
|
|
3065
|
+
resourceTemplates.push(template);
|
|
3066
|
+
matcher.add(routerPath, {
|
|
3067
|
+
_tag: "ResourceTemplate",
|
|
3068
|
+
handle
|
|
3069
|
+
});
|
|
3070
|
+
for (const [param2, handle2] of Object.entries(completions)) {
|
|
3071
|
+
completionsMap.set(`ref/resource/${template.uriTemplate}/${param2}`, handle2);
|
|
3072
|
+
}
|
|
3073
|
+
return notifications.client["notifications/resources/list_changed"]({});
|
|
3074
|
+
}),
|
|
3075
|
+
findResource: (uri) => Effect9.suspend(() => {
|
|
3076
|
+
const match3 = matcher.find(uri);
|
|
3077
|
+
if (!match3) {
|
|
3078
|
+
return Effect9.succeed({ contents: [] });
|
|
3079
|
+
} else if (match3.handler._tag === "Resource") {
|
|
3080
|
+
return match3.handler.effect;
|
|
3081
|
+
}
|
|
3082
|
+
const params = [];
|
|
3083
|
+
for (const key of Object.keys(match3.params)) {
|
|
3084
|
+
params[Number(key)] = match3.params[key];
|
|
3085
|
+
}
|
|
3086
|
+
return match3.handler.handle(uri, params);
|
|
3087
|
+
}),
|
|
3088
|
+
get prompts() {
|
|
3089
|
+
return prompts;
|
|
3090
|
+
},
|
|
3091
|
+
addPrompt: (options) => Effect9.suspend(() => {
|
|
3092
|
+
prompts.push(options.prompt);
|
|
3093
|
+
promptMap.set(options.prompt.name, options.handle);
|
|
3094
|
+
for (const [param2, handle] of Object.entries(options.completions)) {
|
|
3095
|
+
completionsMap.set(`ref/prompt/${options.prompt.name}/${param2}`, handle);
|
|
3096
|
+
}
|
|
3097
|
+
return notifications.client["notifications/prompts/list_changed"]({});
|
|
3098
|
+
}),
|
|
3099
|
+
getPromptResult: Effect9.fnUntraced(function* ({
|
|
3100
|
+
arguments: params,
|
|
3101
|
+
name
|
|
3102
|
+
}) {
|
|
3103
|
+
const handler = promptMap.get(name);
|
|
3104
|
+
if (!handler) {
|
|
3105
|
+
return yield* new InvalidParams({
|
|
3106
|
+
message: `Prompt '${name}' not found`
|
|
3107
|
+
});
|
|
3108
|
+
}
|
|
3109
|
+
return yield* handler(params ?? {});
|
|
3110
|
+
}),
|
|
3111
|
+
completion: Effect9.fnUntraced(function* (complete) {
|
|
3112
|
+
const ref = complete.ref;
|
|
3113
|
+
const key = ref.type === "ref/resource" ? `ref/resource/${ref.uri}/${complete.argument.name}` : `ref/prompt/${ref.name}/${complete.argument.name}`;
|
|
3114
|
+
const handler = completionsMap.get(key);
|
|
3115
|
+
return handler ? yield* handler(complete.argument.value) : CompleteResult.empty;
|
|
3116
|
+
})
|
|
3117
|
+
});
|
|
3118
|
+
});
|
|
3119
|
+
static layer = Layer5.scoped(McpServer, McpServer.make);
|
|
3120
|
+
}
|
|
3121
|
+
var LATEST_PROTOCOL_VERSION = "2025-06-18";
|
|
3122
|
+
var SUPPORTED_PROTOCOL_VERSIONS = [
|
|
3123
|
+
LATEST_PROTOCOL_VERSION,
|
|
3124
|
+
"2025-03-26",
|
|
3125
|
+
"2024-11-05",
|
|
3126
|
+
"2024-10-07"
|
|
3127
|
+
];
|
|
3128
|
+
var run = Effect9.fnUntraced(function* (options) {
|
|
3129
|
+
const protocol = yield* RpcServer.Protocol;
|
|
3130
|
+
const handlers = yield* Layer5.build(layerHandlers(options));
|
|
3131
|
+
const server = yield* McpServer;
|
|
3132
|
+
const clients = yield* RcMap.make({
|
|
3133
|
+
lookup: Effect9.fnUntraced(function* (clientId) {
|
|
3134
|
+
let write;
|
|
3135
|
+
const client = yield* RpcClient.make(ServerRequestRpcs, {
|
|
3136
|
+
spanPrefix: "McpServer/Client"
|
|
3137
|
+
}).pipe(Effect9.provideServiceEffect(RpcClient.Protocol, RpcClient.Protocol.make(Effect9.fnUntraced(function* (writeResponse) {
|
|
3138
|
+
write = writeResponse;
|
|
3139
|
+
return {
|
|
3140
|
+
send(request2, _transferables) {
|
|
3141
|
+
return protocol.send(clientId, {
|
|
3142
|
+
...request2,
|
|
3143
|
+
headers: undefined,
|
|
3144
|
+
traceId: undefined,
|
|
3145
|
+
spanId: undefined,
|
|
3146
|
+
sampled: undefined
|
|
3147
|
+
});
|
|
3148
|
+
},
|
|
3149
|
+
supportsAck: true,
|
|
3150
|
+
supportsTransferables: false
|
|
3151
|
+
};
|
|
3152
|
+
}))));
|
|
3153
|
+
return { client, write };
|
|
3154
|
+
}),
|
|
3155
|
+
idleTimeToLive: 1e4
|
|
3156
|
+
});
|
|
3157
|
+
const clientMiddleware = McpServerClientMiddleware.of(({ clientId }) => Effect9.sync(() => McpServerClient.of({
|
|
3158
|
+
clientId,
|
|
3159
|
+
getClient: RcMap.get(clients, clientId).pipe(Effect9.map(({ client }) => client))
|
|
3160
|
+
})));
|
|
3161
|
+
const patchedProtocol = RpcServer.Protocol.of({
|
|
3162
|
+
...protocol,
|
|
3163
|
+
run: (f) => protocol.run((clientId, request_) => {
|
|
3164
|
+
const request2 = request_;
|
|
3165
|
+
switch (request2._tag) {
|
|
3166
|
+
case "Request": {
|
|
3167
|
+
if (ClientNotificationRpcs.requests.has(request2.tag)) {
|
|
3168
|
+
if (request2.tag === "notifications/cancelled") {
|
|
3169
|
+
return f(clientId, {
|
|
3170
|
+
_tag: "Interrupt",
|
|
3171
|
+
requestId: String(request2.payload.requestId)
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
const handler = handlers.unsafeMap.get(request2.tag);
|
|
3175
|
+
return handler ? handler.handler(request2.payload, {
|
|
3176
|
+
clientId,
|
|
3177
|
+
headers: Headers.fromInput(request2.headers)
|
|
3178
|
+
}) : Effect9.void;
|
|
3179
|
+
}
|
|
3180
|
+
return f(clientId, request2);
|
|
3181
|
+
}
|
|
3182
|
+
case "Ping":
|
|
3183
|
+
case "Ack":
|
|
3184
|
+
case "Interrupt":
|
|
3185
|
+
case "Eof":
|
|
3186
|
+
return f(clientId, request2);
|
|
3187
|
+
case "Pong":
|
|
3188
|
+
case "Exit":
|
|
3189
|
+
case "Chunk":
|
|
3190
|
+
case "ClientProtocolError":
|
|
3191
|
+
case "Defect":
|
|
3192
|
+
return RcMap.get(clients, clientId).pipe(Effect9.flatMap(({ write }) => write(request2)), Effect9.scoped);
|
|
3193
|
+
}
|
|
3194
|
+
})
|
|
3195
|
+
});
|
|
3196
|
+
const encodeNotification = Schema10.encode(Schema10.Union(...Array.from(ServerNotificationRpcs.requests.values(), (rpc) => rpc.payloadSchema)));
|
|
3197
|
+
yield* server.notificationsMailbox.take.pipe(Effect9.flatMap(Effect9.fnUntraced(function* (request2) {
|
|
3198
|
+
const encoded = yield* encodeNotification(request2.payload);
|
|
3199
|
+
const message = {
|
|
3200
|
+
_tag: "Request",
|
|
3201
|
+
tag: request2.tag,
|
|
3202
|
+
payload: encoded
|
|
3203
|
+
};
|
|
3204
|
+
const clientIds = yield* patchedProtocol.clientIds;
|
|
3205
|
+
for (const clientId of server.initializedClients) {
|
|
3206
|
+
if (!clientIds.has(clientId)) {
|
|
3207
|
+
server.initializedClients.delete(clientId);
|
|
3208
|
+
continue;
|
|
3209
|
+
}
|
|
3210
|
+
yield* patchedProtocol.send(clientId, message);
|
|
3211
|
+
}
|
|
3212
|
+
})), Effect9.catchAllCause(() => Effect9.void), Effect9.forever, Effect9.forkScoped);
|
|
3213
|
+
return yield* RpcServer.make(ClientRpcs, {
|
|
3214
|
+
spanPrefix: "McpServer",
|
|
3215
|
+
disableFatalDefects: true
|
|
3216
|
+
}).pipe(Effect9.provideService(RpcServer.Protocol, patchedProtocol), Effect9.provideService(McpServerClientMiddleware, clientMiddleware), Effect9.provide(handlers));
|
|
3217
|
+
}, Effect9.scoped);
|
|
3218
|
+
var layer2 = (options) => Layer5.scopedDiscard(Effect9.forkScoped(run(options))).pipe(Layer5.provideMerge(McpServer.layer));
|
|
3219
|
+
var layerStdio = (options) => layer2(options).pipe(Layer5.provide(RpcServer.layerProtocolStdio({
|
|
3220
|
+
stdin: options.stdin,
|
|
3221
|
+
stdout: options.stdout
|
|
3222
|
+
})), Layer5.provide(RpcSerialization.layerNdJsonRpc()), Layer5.provideMerge(Logger.remove(Logger.defaultLogger)), Layer5.provideMerge(Logger.remove(Logger.prettyLoggerDefault)));
|
|
3223
|
+
var layerHttp = (options) => layer2(options).pipe(Layer5.provide(RpcServer.layerProtocolHttp(options)), Layer5.provide(RpcSerialization.layerJsonRpc()));
|
|
3224
|
+
var layerHttpRouter = (options) => layer2(options).pipe(Layer5.provide(RpcServer.layerProtocolHttpRouter(options)), Layer5.provide(RpcSerialization.layerJsonRpc()));
|
|
3225
|
+
var registerToolkit = Effect9.fnUntraced(function* (toolkit) {
|
|
3226
|
+
const registry = yield* McpServer;
|
|
3227
|
+
const built = yield* toolkit;
|
|
3228
|
+
const context5 = yield* Effect9.context();
|
|
3229
|
+
for (const tool of Object.values(built.tools)) {
|
|
3230
|
+
const mcpTool = new Tool({
|
|
3231
|
+
name: tool.name,
|
|
3232
|
+
description: tool.description,
|
|
3233
|
+
inputSchema: makeJsonSchema(tool.parametersSchema.ast),
|
|
3234
|
+
annotations: new ToolAnnotations({
|
|
3235
|
+
...Context10.getOption(tool.annotations, Title).pipe(Option6.map((title) => ({ title })), Option6.getOrUndefined),
|
|
3236
|
+
readOnlyHint: Context10.get(tool.annotations, Readonly),
|
|
3237
|
+
destructiveHint: Context10.get(tool.annotations, Destructive),
|
|
3238
|
+
idempotentHint: Context10.get(tool.annotations, Idempotent),
|
|
3239
|
+
openWorldHint: Context10.get(tool.annotations, OpenWorld)
|
|
3240
|
+
})
|
|
3241
|
+
});
|
|
3242
|
+
yield* registry.addTool({
|
|
3243
|
+
tool: mcpTool,
|
|
3244
|
+
handle(payload) {
|
|
3245
|
+
return built.handle(tool.name, payload).pipe(Effect9.provide(context5), Effect9.match({
|
|
3246
|
+
onFailure: (error) => new CallToolResult({
|
|
3247
|
+
isError: true,
|
|
3248
|
+
structuredContent: typeof error === "object" ? error : undefined,
|
|
3249
|
+
content: [
|
|
3250
|
+
{
|
|
3251
|
+
type: "text",
|
|
3252
|
+
text: JSON.stringify(error)
|
|
3253
|
+
}
|
|
3254
|
+
]
|
|
3255
|
+
}),
|
|
3256
|
+
onSuccess: (result) => new CallToolResult({
|
|
3257
|
+
isError: false,
|
|
3258
|
+
structuredContent: typeof result.encodedResult === "object" ? result.encodedResult : undefined,
|
|
3259
|
+
content: [
|
|
3260
|
+
{
|
|
3261
|
+
type: "text",
|
|
3262
|
+
text: JSON.stringify(result.encodedResult)
|
|
3263
|
+
}
|
|
3264
|
+
]
|
|
3265
|
+
})
|
|
3266
|
+
}));
|
|
3267
|
+
}
|
|
3268
|
+
});
|
|
3269
|
+
}
|
|
3270
|
+
});
|
|
3271
|
+
var toolkit = (toolkit2) => Layer5.effectDiscard(registerToolkit(toolkit2)).pipe(Layer5.provide(McpServer.layer));
|
|
3272
|
+
var registerResource = function() {
|
|
3273
|
+
if (arguments.length === 1) {
|
|
3274
|
+
const options = arguments[0];
|
|
3275
|
+
return Effect9.gen(function* () {
|
|
3276
|
+
const context5 = yield* Effect9.context();
|
|
3277
|
+
const registry = yield* McpServer;
|
|
3278
|
+
yield* registry.addResource(new Resource({
|
|
3279
|
+
...options,
|
|
3280
|
+
annotations: options
|
|
3281
|
+
}), options.content.pipe(Effect9.provide(context5), Effect9.map((content) => resolveResourceContent(options.uri, content)), Effect9.catchAllCause((cause) => {
|
|
3282
|
+
const prettyError = Cause2.prettyErrors(cause)[0];
|
|
3283
|
+
return new InternalError({
|
|
3284
|
+
message: prettyError.message
|
|
3285
|
+
});
|
|
3286
|
+
})));
|
|
3287
|
+
});
|
|
3288
|
+
}
|
|
3289
|
+
const { params, routerPath, schema, uriPath } = compileUriTemplate(...arguments);
|
|
3290
|
+
return Effect9.fnUntraced(function* (options) {
|
|
3291
|
+
const context5 = yield* Effect9.context();
|
|
3292
|
+
const registry = yield* McpServer;
|
|
3293
|
+
const decode4 = Schema10.decodeUnknown(schema);
|
|
3294
|
+
const template = new ResourceTemplate({
|
|
3295
|
+
...options,
|
|
3296
|
+
uriTemplate: uriPath,
|
|
3297
|
+
annotations: options
|
|
3298
|
+
});
|
|
3299
|
+
const completions = {};
|
|
3300
|
+
for (const [param2, handle] of Object.entries(options.completion ?? {})) {
|
|
3301
|
+
const encodeArray = Schema10.encodeUnknown(Schema10.Array(params[param2]));
|
|
3302
|
+
const handler = (input) => handle(input).pipe(Effect9.flatMap(encodeArray), Effect9.map((values) => new CompleteResult({
|
|
3303
|
+
completion: {
|
|
3304
|
+
values,
|
|
3305
|
+
total: values.length,
|
|
3306
|
+
hasMore: false
|
|
3307
|
+
}
|
|
3308
|
+
})), Effect9.catchAllCause((cause) => {
|
|
3309
|
+
const prettyError = Cause2.prettyErrors(cause)[0];
|
|
3310
|
+
return new InternalError({
|
|
3311
|
+
message: prettyError.message
|
|
3312
|
+
});
|
|
3313
|
+
}), Effect9.provide(context5));
|
|
3314
|
+
completions[param2] = handler;
|
|
3315
|
+
}
|
|
3316
|
+
yield* registry.addResourceTemplate({
|
|
3317
|
+
template,
|
|
3318
|
+
routerPath,
|
|
3319
|
+
completions,
|
|
3320
|
+
handle: (uri, params2) => decode4(params2).pipe(Effect9.mapError((error) => new InvalidParams({ message: error.message })), Effect9.flatMap((params3) => options.content(uri, ...params3).pipe(Effect9.map((content) => resolveResourceContent(uri, content)), Effect9.catchAllCause((cause) => {
|
|
3321
|
+
const prettyError = Cause2.prettyErrors(cause)[0];
|
|
3322
|
+
return new InternalError({
|
|
3323
|
+
message: prettyError.message
|
|
3324
|
+
});
|
|
3325
|
+
}))), Effect9.provide(context5))
|
|
3326
|
+
});
|
|
3327
|
+
});
|
|
3328
|
+
};
|
|
3329
|
+
var resource = function() {
|
|
3330
|
+
if (arguments.length === 1) {
|
|
3331
|
+
return Layer5.effectDiscard(registerResource(arguments[0])).pipe(Layer5.provide(McpServer.layer));
|
|
3332
|
+
}
|
|
3333
|
+
const register = registerResource(...arguments);
|
|
3334
|
+
return (options) => Layer5.effectDiscard(register(options)).pipe(Layer5.provide(McpServer.layer));
|
|
3335
|
+
};
|
|
3336
|
+
var registerPrompt = (options) => {
|
|
3337
|
+
const args = Arr2.empty();
|
|
3338
|
+
const props = {};
|
|
3339
|
+
const propSignatures = options.parameters ? AST2.getPropertySignatures(options.parameters.ast) : [];
|
|
3340
|
+
for (const prop of propSignatures) {
|
|
3341
|
+
args.push({
|
|
3342
|
+
name: prop.name,
|
|
3343
|
+
description: Option6.getOrUndefined(AST2.getDescriptionAnnotation(prop)),
|
|
3344
|
+
required: !prop.isOptional
|
|
3345
|
+
});
|
|
3346
|
+
props[prop.name] = Schema10.make(prop.type);
|
|
3347
|
+
}
|
|
3348
|
+
const prompt = new Prompt2({
|
|
3349
|
+
name: options.name,
|
|
3350
|
+
description: options.description,
|
|
3351
|
+
arguments: args
|
|
3352
|
+
});
|
|
3353
|
+
const decode4 = options.parameters ? Schema10.decodeUnknown(options.parameters) : () => Effect9.succeed({});
|
|
3354
|
+
const completion = options.completion ?? {};
|
|
3355
|
+
return Effect9.gen(function* () {
|
|
3356
|
+
const registry = yield* McpServer;
|
|
3357
|
+
const context5 = yield* Effect9.context();
|
|
3358
|
+
const completions = {};
|
|
3359
|
+
for (const [param2, handle] of Object.entries(completion)) {
|
|
3360
|
+
const encodeArray = Schema10.encodeUnknown(Schema10.Array(props[param2]));
|
|
3361
|
+
const handler = (input) => handle(input).pipe(Effect9.flatMap(encodeArray), Effect9.map((values) => ({
|
|
3362
|
+
completion: {
|
|
3363
|
+
values,
|
|
3364
|
+
total: values.length,
|
|
3365
|
+
hasMore: false
|
|
3366
|
+
}
|
|
3367
|
+
})), Effect9.catchAllCause((cause) => {
|
|
3368
|
+
const prettyError = Cause2.prettyErrors(cause)[0];
|
|
3369
|
+
return new InternalError({
|
|
3370
|
+
message: prettyError.message
|
|
3371
|
+
});
|
|
3372
|
+
}), Effect9.provide(context5));
|
|
3373
|
+
completions[param2] = handler;
|
|
3374
|
+
}
|
|
3375
|
+
yield* registry.addPrompt({
|
|
3376
|
+
prompt,
|
|
3377
|
+
completions,
|
|
3378
|
+
handle: (params) => decode4(params).pipe(Effect9.mapError((error) => new InvalidParams({ message: error.message })), Effect9.flatMap((params2) => options.content(params2)), Effect9.map((messages) => {
|
|
3379
|
+
messages = typeof messages === "string" ? [
|
|
3380
|
+
{
|
|
3381
|
+
role: "user",
|
|
3382
|
+
content: TextContent.make({
|
|
3383
|
+
text: messages
|
|
3384
|
+
})
|
|
3385
|
+
}
|
|
3386
|
+
] : messages;
|
|
3387
|
+
return new GetPromptResult({
|
|
3388
|
+
messages,
|
|
3389
|
+
description: prompt.description
|
|
3390
|
+
});
|
|
3391
|
+
}), Effect9.catchAllCause((cause) => {
|
|
3392
|
+
const prettyError = Cause2.prettyErrors(cause)[0];
|
|
3393
|
+
return new InternalError({
|
|
3394
|
+
message: prettyError.message
|
|
3395
|
+
});
|
|
3396
|
+
}), Effect9.provide(context5))
|
|
3397
|
+
});
|
|
3398
|
+
});
|
|
3399
|
+
};
|
|
3400
|
+
var prompt = (options) => Layer5.effectDiscard(registerPrompt(options)).pipe(Layer5.provide(McpServer.layer));
|
|
3401
|
+
var elicit = Effect9.fnUntraced(function* (options) {
|
|
3402
|
+
const { getClient } = yield* McpServerClient;
|
|
3403
|
+
const client = yield* getClient;
|
|
3404
|
+
const request2 = Elicit.payloadSchema.make({
|
|
3405
|
+
message: options.message,
|
|
3406
|
+
requestedSchema: makeJsonSchema(options.schema.ast)
|
|
3407
|
+
});
|
|
3408
|
+
const res = yield* client["elicitation/create"](request2).pipe(Effect9.catchAllCause((cause) => Effect9.fail(new ElicitationDeclined({
|
|
3409
|
+
cause: Cause2.squash(cause),
|
|
3410
|
+
request: request2
|
|
3411
|
+
}))));
|
|
3412
|
+
switch (res.action) {
|
|
3413
|
+
case "accept":
|
|
3414
|
+
return yield* Effect9.orDie(Schema10.decodeUnknown(options.schema)(res.content));
|
|
3415
|
+
case "cancel":
|
|
3416
|
+
return yield* Effect9.interrupt;
|
|
3417
|
+
case "decline":
|
|
3418
|
+
return yield* Effect9.fail(new ElicitationDeclined({ request: request2 }));
|
|
3419
|
+
}
|
|
3420
|
+
}, Effect9.scoped);
|
|
3421
|
+
var makeUriMatcher = () => {
|
|
3422
|
+
const router = FindMyWay.make({
|
|
3423
|
+
ignoreTrailingSlash: true,
|
|
3424
|
+
ignoreDuplicateSlashes: true,
|
|
3425
|
+
caseSensitive: true
|
|
3426
|
+
});
|
|
3427
|
+
const add2 = (uri, value) => {
|
|
3428
|
+
router.on("GET", uri, value);
|
|
3429
|
+
};
|
|
3430
|
+
const find = (uri) => router.find("GET", uri);
|
|
3431
|
+
return { add: add2, find };
|
|
3432
|
+
};
|
|
3433
|
+
var compileUriTemplate = (segments, ...schemas) => {
|
|
3434
|
+
let routerPath = segments[0].replace(":", "::");
|
|
3435
|
+
let uriPath = segments[0];
|
|
3436
|
+
const params = {};
|
|
3437
|
+
let pathSchema = Schema10.Tuple();
|
|
3438
|
+
if (schemas.length > 0) {
|
|
3439
|
+
const arr = [];
|
|
3440
|
+
for (let i = 0;i < schemas.length; i++) {
|
|
3441
|
+
const schema = schemas[i];
|
|
3442
|
+
const segment = segments[i + 1];
|
|
3443
|
+
const key = String(i);
|
|
3444
|
+
arr.push(schema);
|
|
3445
|
+
routerPath += `:${key}${segment.replace(":", "::")}`;
|
|
3446
|
+
const paramName = AST2.getAnnotation(ParamAnnotation)(schema.ast).pipe(Option6.getOrElse(() => `param${key}`));
|
|
3447
|
+
params[paramName] = schema;
|
|
3448
|
+
uriPath += `{${paramName}}${segment}`;
|
|
3449
|
+
}
|
|
3450
|
+
pathSchema = Schema10.Tuple(...arr);
|
|
3451
|
+
}
|
|
3452
|
+
return {
|
|
3453
|
+
routerPath,
|
|
3454
|
+
uriPath,
|
|
3455
|
+
schema: pathSchema,
|
|
3456
|
+
params
|
|
3457
|
+
};
|
|
3458
|
+
};
|
|
3459
|
+
var layerHandlers = (serverInfo) => ClientRpcs.toLayer(Effect9.gen(function* () {
|
|
3460
|
+
const server = yield* McpServer;
|
|
3461
|
+
return {
|
|
3462
|
+
ping: () => Effect9.succeed({}),
|
|
3463
|
+
initialize(params, { clientId }) {
|
|
3464
|
+
const requestedVersion = params.protocolVersion;
|
|
3465
|
+
const capabilities = {
|
|
3466
|
+
completions: {}
|
|
3467
|
+
};
|
|
3468
|
+
if (server.tools.length > 0) {
|
|
3469
|
+
capabilities.tools = { listChanged: true };
|
|
3470
|
+
}
|
|
3471
|
+
if (server.resources.length > 0 || server.resourceTemplates.length > 0) {
|
|
3472
|
+
capabilities.resources = {
|
|
3473
|
+
listChanged: true,
|
|
3474
|
+
subscribe: false
|
|
3475
|
+
};
|
|
3476
|
+
}
|
|
3477
|
+
if (server.prompts.length > 0) {
|
|
3478
|
+
capabilities.prompts = { listChanged: true };
|
|
3479
|
+
}
|
|
3480
|
+
server.initializedClients.add(clientId);
|
|
3481
|
+
return Effect9.succeed({
|
|
3482
|
+
capabilities,
|
|
3483
|
+
serverInfo,
|
|
3484
|
+
protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION
|
|
3485
|
+
});
|
|
3486
|
+
},
|
|
3487
|
+
"completion/complete": server.completion,
|
|
3488
|
+
"logging/setLevel": () => InternalError.notImplemented,
|
|
3489
|
+
"prompts/get": server.getPromptResult,
|
|
3490
|
+
"prompts/list": () => Effect9.sync(() => new ListPromptsResult({ prompts: server.prompts })),
|
|
3491
|
+
"resources/list": () => Effect9.sync(() => new ListResourcesResult({
|
|
3492
|
+
resources: server.resources
|
|
3493
|
+
})),
|
|
3494
|
+
"resources/read": ({ uri }) => server.findResource(uri),
|
|
3495
|
+
"resources/subscribe": () => InternalError.notImplemented,
|
|
3496
|
+
"resources/unsubscribe": () => InternalError.notImplemented,
|
|
3497
|
+
"resources/templates/list": () => Effect9.sync(() => new ListResourceTemplatesResult({
|
|
3498
|
+
resourceTemplates: server.resourceTemplates
|
|
3499
|
+
})),
|
|
3500
|
+
"tools/call": server.callTool,
|
|
3501
|
+
"tools/list": () => Effect9.sync(() => new ListToolsResult({ tools: server.tools })),
|
|
3502
|
+
"notifications/cancelled": (_) => Effect9.void,
|
|
3503
|
+
"notifications/initialized": (_) => Effect9.void,
|
|
3504
|
+
"notifications/progress": (_) => Effect9.void,
|
|
3505
|
+
"notifications/roots/list_changed": (_) => Effect9.void
|
|
3506
|
+
};
|
|
3507
|
+
}));
|
|
3508
|
+
var makeJsonSchema = (ast) => {
|
|
3509
|
+
const props = AST2.getPropertySignatures(ast);
|
|
3510
|
+
if (props.length === 0) {
|
|
3511
|
+
return {
|
|
3512
|
+
type: "object",
|
|
3513
|
+
properties: {},
|
|
3514
|
+
required: [],
|
|
3515
|
+
additionalProperties: false
|
|
3516
|
+
};
|
|
3517
|
+
}
|
|
3518
|
+
const $defs = {};
|
|
3519
|
+
const schema = JsonSchema2.fromAST(ast, {
|
|
3520
|
+
definitions: $defs,
|
|
3521
|
+
topLevelReferenceStrategy: "skip"
|
|
3522
|
+
});
|
|
3523
|
+
if (Object.keys($defs).length === 0)
|
|
3524
|
+
return schema;
|
|
3525
|
+
schema.$defs = $defs;
|
|
3526
|
+
return schema;
|
|
3527
|
+
};
|
|
3528
|
+
var resolveResourceContent = (uri, content) => {
|
|
3529
|
+
if (typeof content === "string") {
|
|
3530
|
+
return {
|
|
3531
|
+
contents: [
|
|
3532
|
+
{
|
|
3533
|
+
uri,
|
|
3534
|
+
text: content
|
|
3535
|
+
}
|
|
3536
|
+
]
|
|
3537
|
+
};
|
|
3538
|
+
} else if (content instanceof Uint8Array) {
|
|
3539
|
+
return {
|
|
3540
|
+
contents: [
|
|
3541
|
+
{
|
|
3542
|
+
uri,
|
|
3543
|
+
blob: content
|
|
3544
|
+
}
|
|
3545
|
+
]
|
|
3546
|
+
};
|
|
3547
|
+
}
|
|
3548
|
+
return content;
|
|
3549
|
+
};
|
|
3550
|
+
// packages/ariadne/src/Model.ts
|
|
3551
|
+
var exports_Model = {};
|
|
3552
|
+
__export(exports_Model, {
|
|
3553
|
+
make: () => make19,
|
|
3554
|
+
TypeId: () => TypeId5,
|
|
3555
|
+
ProviderName: () => ProviderName
|
|
3556
|
+
});
|
|
3557
|
+
import * as Context11 from "effect/Context";
|
|
3558
|
+
import * as Effect10 from "effect/Effect";
|
|
3559
|
+
import { CommitPrototype as CommitPrototype2 } from "effect/Effectable";
|
|
3560
|
+
import { identity as identity4 } from "effect/Function";
|
|
3561
|
+
import * as Layer6 from "effect/Layer";
|
|
3562
|
+
var TypeId5 = "~@effect/ai/Model";
|
|
3563
|
+
|
|
3564
|
+
class ProviderName extends Context11.Tag("@effect/ai/Model/ProviderName")() {
|
|
3565
|
+
}
|
|
3566
|
+
var ModelProto = {
|
|
3567
|
+
...CommitPrototype2,
|
|
3568
|
+
[TypeId5]: TypeId5,
|
|
3569
|
+
[Layer6.LayerTypeId]: {
|
|
3570
|
+
_ROut: identity4,
|
|
3571
|
+
_E: identity4,
|
|
3572
|
+
_RIn: identity4
|
|
3573
|
+
},
|
|
3574
|
+
commit() {
|
|
3575
|
+
return Effect10.contextWith((context5) => {
|
|
3576
|
+
return Layer6.provide(this, Layer6.succeedContext(context5));
|
|
3577
|
+
});
|
|
3578
|
+
}
|
|
3579
|
+
};
|
|
3580
|
+
var make19 = (provider, layer3) => Object.assign(Object.create(ModelProto), { provider }, Layer6.merge(Layer6.succeed(ProviderName, provider), layer3));
|
|
3581
|
+
// packages/ariadne/src/Tokenizer.ts
|
|
3582
|
+
var exports_Tokenizer = {};
|
|
3583
|
+
__export(exports_Tokenizer, {
|
|
3584
|
+
make: () => make20,
|
|
3585
|
+
Tokenizer: () => Tokenizer
|
|
3586
|
+
});
|
|
3587
|
+
import * as Context12 from "effect/Context";
|
|
3588
|
+
import * as Effect11 from "effect/Effect";
|
|
3589
|
+
import * as Predicate10 from "effect/Predicate";
|
|
3590
|
+
class Tokenizer extends Context12.Tag("@effect/ai/Tokenizer")() {
|
|
3591
|
+
}
|
|
3592
|
+
var make20 = (options) => Tokenizer.of({
|
|
3593
|
+
tokenize(input) {
|
|
3594
|
+
return options.tokenize(make2(input));
|
|
3595
|
+
},
|
|
3596
|
+
truncate(input, tokens) {
|
|
3597
|
+
return truncate(make2(input), options.tokenize, tokens);
|
|
3598
|
+
}
|
|
3599
|
+
});
|
|
3600
|
+
var truncate = (self, tokenize, maxTokens) => Effect11.suspend(() => {
|
|
3601
|
+
let count = 0;
|
|
3602
|
+
let inputMessages = self.content;
|
|
3603
|
+
let outputMessages = [];
|
|
3604
|
+
const loop = Effect11.suspend(() => {
|
|
3605
|
+
const message = inputMessages[inputMessages.length - 1];
|
|
3606
|
+
if (Predicate10.isUndefined(message)) {
|
|
3607
|
+
return Effect11.succeed(fromMessages(outputMessages));
|
|
3608
|
+
}
|
|
3609
|
+
inputMessages = inputMessages.slice(0, inputMessages.length - 1);
|
|
3610
|
+
return Effect11.flatMap(tokenize(fromMessages([message])), (tokens) => {
|
|
3611
|
+
count += tokens.length;
|
|
3612
|
+
if (count > maxTokens) {
|
|
3613
|
+
return Effect11.succeed(fromMessages(outputMessages));
|
|
3614
|
+
}
|
|
3615
|
+
outputMessages = [message, ...outputMessages];
|
|
3616
|
+
return loop;
|
|
3617
|
+
});
|
|
3618
|
+
});
|
|
3619
|
+
return loop;
|
|
3620
|
+
});
|
|
3621
|
+
export {
|
|
3622
|
+
exports_Toolkit as Toolkit,
|
|
3623
|
+
exports_Tool as Tool,
|
|
3624
|
+
exports_Tokenizer as Tokenizer,
|
|
3625
|
+
exports_Telemetry as Telemetry,
|
|
3626
|
+
exports_Response as Response,
|
|
3627
|
+
exports_Prompt as Prompt,
|
|
3628
|
+
exports_Model as Model,
|
|
3629
|
+
exports_McpServer as McpServer,
|
|
3630
|
+
exports_McpSchema as McpSchema,
|
|
3631
|
+
exports_McpRegistry as McpRegistry,
|
|
3632
|
+
exports_LanguageModel as LanguageModel,
|
|
3633
|
+
exports_IdGenerator as IdGenerator,
|
|
3634
|
+
exports_EmbeddingModel as EmbeddingModel,
|
|
3635
|
+
exports_Chat as Chat,
|
|
3636
|
+
exports_AiError as AiError,
|
|
3637
|
+
exports_AgentRunner as AgentRunner
|
|
3638
|
+
};
|