@mozaik-ai/core 0.7.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.js ADDED
@@ -0,0 +1,1039 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Agent: () => Agent,
34
+ PlanningAgent: () => PlanningAgent,
35
+ Task: () => Task,
36
+ WorkUnit: () => WorkUnit,
37
+ Workflow: () => Workflow
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+
41
+ // src/core/workflow/work-unit.ts
42
+ var WorkUnit = class {
43
+ constructor() {
44
+ }
45
+ };
46
+
47
+ // src/core/endpoint/request-gateway.ts
48
+ var RequestGateway = class {
49
+ constructor(endpointResolver) {
50
+ this.endpointResolver = endpointResolver;
51
+ }
52
+ async invoke(command) {
53
+ this.endpoint = this.endpointResolver.resolve(command.model);
54
+ return await this.endpoint.sendRequest(command);
55
+ }
56
+ };
57
+
58
+ // src/core/endpoint/endpoint-resolver.ts
59
+ var EndpointResolver = class {
60
+ };
61
+
62
+ // src/types/model.ts
63
+ var OPENAI_MODELS = ["gpt-5", "gpt-5-mini", "gpt-5-nano", "gpt-5.1"];
64
+ var latest_sonnet = "claude-sonnet-4-5-20250929";
65
+ var latest_haiku = "claude-haiku-4-5-20251001";
66
+ var latest_opus = "claude-opus-4-5-20251101";
67
+ var ANTHROPIC_MODELS = ["claude-sonnet-4.5", "claude-haiku-4.5", "claude-opus-4.5"];
68
+ var ANTHROPIC_MODEL_MAP = {
69
+ "claude-sonnet-4.5": latest_sonnet,
70
+ "claude-haiku-4.5": latest_haiku,
71
+ "claude-opus-4.5": latest_opus
72
+ };
73
+
74
+ // src/core/command-handler/capability.ts
75
+ var CapabilityHandler = class {
76
+ setNextHandler(capability) {
77
+ this.nextHandler = capability;
78
+ return this.nextHandler;
79
+ }
80
+ handle(command, builder) {
81
+ this.apply(command, builder);
82
+ if (this.nextHandler) {
83
+ this.nextHandler.handle(command, builder);
84
+ }
85
+ }
86
+ };
87
+
88
+ // src/core/command-handler/messages.ts
89
+ var MessagesHandler = class extends CapabilityHandler {
90
+ apply(command, builder) {
91
+ if (command.messages) {
92
+ builder.addMessages(command.messages);
93
+ }
94
+ }
95
+ };
96
+
97
+ // src/core/command-handler/task.ts
98
+ var TaskHandler = class extends CapabilityHandler {
99
+ apply(command, builder) {
100
+ if (command.task) {
101
+ builder.addTask(command.task);
102
+ }
103
+ }
104
+ };
105
+
106
+ // src/core/command-handler/model.ts
107
+ var ModelHandler = class extends CapabilityHandler {
108
+ apply(command, builder) {
109
+ if (command.model) {
110
+ builder.addModel(command.model);
111
+ }
112
+ }
113
+ };
114
+
115
+ // src/core/command-handler/structured-output.ts
116
+ var StructuredOutputlHandler = class extends CapabilityHandler {
117
+ apply(command, builder) {
118
+ if (command.structuredOutput) {
119
+ builder.addStructuredOutput(command.structuredOutput);
120
+ }
121
+ }
122
+ };
123
+
124
+ // src/core/command-handler/tools.ts
125
+ var ToolsHandler = class extends CapabilityHandler {
126
+ apply(command, requestBuilder) {
127
+ if (command.tools && command.tools.length > 0) {
128
+ requestBuilder.addTools(command.tools);
129
+ }
130
+ }
131
+ };
132
+
133
+ // src/core/endpoint/endpoint.ts
134
+ var Endpoint = class {
135
+ constructor() {
136
+ this.command = null;
137
+ }
138
+ buildRequest(command) {
139
+ this.command = command;
140
+ this.requestBuilder.initialize();
141
+ const messagesHandler = new MessagesHandler();
142
+ const taskHandler = new TaskHandler();
143
+ const modelHandler = new ModelHandler();
144
+ const structuredOutputHandler = new StructuredOutputlHandler();
145
+ const toolsHandler = new ToolsHandler();
146
+ messagesHandler.setNextHandler(taskHandler).setNextHandler(modelHandler).setNextHandler(structuredOutputHandler).setNextHandler(toolsHandler);
147
+ messagesHandler.handle(command, this.requestBuilder);
148
+ return this.requestBuilder.build();
149
+ }
150
+ };
151
+
152
+ // src/core/endpoint/request-builder.ts
153
+ var RequestBuilder = class {
154
+ initialize() {
155
+ this.request = {};
156
+ }
157
+ build() {
158
+ return this.request;
159
+ }
160
+ };
161
+
162
+ // src/providers/openai/mapper.ts
163
+ var OpenAIResponsesMapper = class {
164
+ /**
165
+ * Convert domain Messages to Responses API instructions format
166
+ *
167
+ * The Responses API uses 'instructions' (system prompt) rather than messages array.
168
+ * For multi-turn conversations, use conversation.id or previous_response_id parameters.
169
+ */
170
+ toInstructions(messages) {
171
+ if (messages.length === 0) {
172
+ throw new Error("[ResponsesMapper] Cannot create instructions from empty messages");
173
+ }
174
+ const systemMessage = messages.find((m) => m.role === "system");
175
+ if (systemMessage) {
176
+ return typeof systemMessage.content === "string" ? systemMessage.content : this.extractTextFromContent(systemMessage.content);
177
+ }
178
+ return "You are a helpful assistant.";
179
+ }
180
+ /**
181
+ * Extract the user's input from messages
182
+ * Returns the last user message content for use in prompt variables.
183
+ * In Responses API, the actual user query is typically passed via prompt variables
184
+ * or handled through conversation continuation.
185
+ */
186
+ extractUserInput(messages) {
187
+ const userMessages = messages.filter((m) => m.role === "user");
188
+ if (userMessages.length === 0) {
189
+ return "";
190
+ }
191
+ const lastUserMessage = userMessages[userMessages.length - 1];
192
+ return typeof lastUserMessage.content === "string" ? lastUserMessage.content : this.extractTextFromContent(lastUserMessage.content);
193
+ }
194
+ extractTextFromContent(content) {
195
+ return content.filter((part) => part.type === "text").map((part) => part.text).join(" ");
196
+ }
197
+ /**
198
+ * Map tools to Responses API format
199
+ */
200
+ toTools(tools) {
201
+ return tools.map((t) => ({
202
+ type: "function",
203
+ name: t.name,
204
+ description: t.description,
205
+ parameters: t.schema,
206
+ strict: true
207
+ // Enable strict mode by default for better validation
208
+ }));
209
+ }
210
+ };
211
+
212
+ // src/providers/openai/builder.ts
213
+ var import_zod = require("openai/helpers/zod");
214
+ var OpenAIResponsesBuilder = class extends RequestBuilder {
215
+ constructor(mapper = new OpenAIResponsesMapper()) {
216
+ super();
217
+ this.mapper = mapper;
218
+ }
219
+ addModel(model) {
220
+ this.request.model = model;
221
+ return this;
222
+ }
223
+ addTask(task) {
224
+ this.request.input = task;
225
+ return this;
226
+ }
227
+ addMessages(messages) {
228
+ const instructions = this.mapper.toInstructions(messages);
229
+ if (instructions && instructions !== "You are a helpful assistant.") {
230
+ this.request.instructions = instructions;
231
+ }
232
+ return this;
233
+ }
234
+ addStructuredOutput(schema) {
235
+ this.request.text = {
236
+ format: (0, import_zod.zodTextFormat)(schema, "outputSchema")
237
+ };
238
+ return this;
239
+ }
240
+ addTools(tools) {
241
+ this.request.tools = tools.map((tool) => ({
242
+ type: "function",
243
+ name: tool.name,
244
+ description: tool.description,
245
+ parameters: tool.schema
246
+ }));
247
+ return this;
248
+ }
249
+ };
250
+
251
+ // src/providers/openai/client/default.ts
252
+ var import_openai = __toESM(require("openai"));
253
+ var OpenAIDefaultClient = class {
254
+ constructor(client = new import_openai.default()) {
255
+ this.client = client;
256
+ }
257
+ async send(request) {
258
+ return await this.client.responses.create(request);
259
+ }
260
+ };
261
+
262
+ // src/providers/openai/client/parser.ts
263
+ var import_openai2 = __toESM(require("openai"));
264
+ var OpenAIParserClient = class {
265
+ constructor(client = new import_openai2.default()) {
266
+ this.client = client;
267
+ }
268
+ async send(request) {
269
+ return await this.client.responses.parse(request);
270
+ }
271
+ };
272
+
273
+ // src/providers/openai/client/resolver.ts
274
+ var OpenAIClientResolver = class {
275
+ static resolve(request) {
276
+ if (request.text && request.text.format) {
277
+ return new OpenAIParserClient();
278
+ } else {
279
+ return new OpenAIDefaultClient();
280
+ }
281
+ }
282
+ };
283
+
284
+ // src/core/endpoint/response-handler.ts
285
+ var ResponseHandler = class {
286
+ setNextHandler(responseHandler) {
287
+ this.nextHandler = responseHandler;
288
+ return this.nextHandler;
289
+ }
290
+ };
291
+
292
+ // src/providers/openai/response-handler/output-parsed.ts
293
+ var OutputParsedHandler = class extends ResponseHandler {
294
+ async handle(responseContext) {
295
+ const providerResponse = responseContext.providerResponse;
296
+ if (providerResponse.output_parsed) {
297
+ responseContext.setResponse(providerResponse.output_parsed);
298
+ return responseContext;
299
+ }
300
+ return await this.nextHandler.handle(responseContext);
301
+ }
302
+ };
303
+
304
+ // src/providers/openai/response-handler/content.ts
305
+ var ContentHandler = class extends ResponseHandler {
306
+ async handle(responseContext) {
307
+ var _a, _b;
308
+ const providerResponse = responseContext.providerResponse;
309
+ const firstOutput = (_a = providerResponse.output) == null ? void 0 : _a[0];
310
+ if (firstOutput && "content" in firstOutput) {
311
+ const firstContent = (_b = firstOutput.content) == null ? void 0 : _b[0];
312
+ if (firstContent && "text" in firstContent) {
313
+ responseContext.setResponse(firstContent.text);
314
+ return responseContext;
315
+ }
316
+ }
317
+ return await this.nextHandler.handle(responseContext);
318
+ }
319
+ };
320
+
321
+ // src/providers/openai/response-handler/output-text.ts
322
+ var OutputTextHandler = class extends ResponseHandler {
323
+ async handle(responseContext) {
324
+ const providerResponse = responseContext.providerResponse;
325
+ if (providerResponse.output_text) {
326
+ responseContext.setResponse(providerResponse.output_text);
327
+ return responseContext;
328
+ }
329
+ return await this.nextHandler.handle(responseContext);
330
+ }
331
+ };
332
+
333
+ // src/core/endpoint/usage.ts
334
+ var UsageEntry = class {
335
+ constructor(inputTokens, outputTokens, model) {
336
+ this.inputTokens = inputTokens;
337
+ this.outputTokens = outputTokens;
338
+ this.model = model;
339
+ this.totalTokens = inputTokens + outputTokens;
340
+ }
341
+ };
342
+
343
+ // src/providers/openai/response-handler/function-calls.ts
344
+ var FunctionCallsHandler = class extends ResponseHandler {
345
+ constructor(request, tools) {
346
+ super();
347
+ this.request = request;
348
+ this.tools = tools;
349
+ this.client = new OpenAIDefaultClient();
350
+ }
351
+ hasToolCalls(response) {
352
+ var _a;
353
+ return (_a = response.output) == null ? void 0 : _a.some((item) => item.type === "function_call");
354
+ }
355
+ extractToolCalls(response) {
356
+ var _a;
357
+ return ((_a = response.output) == null ? void 0 : _a.filter((item) => item.type === "function_call")) || [];
358
+ }
359
+ resolveTool(call, tools) {
360
+ var _a;
361
+ return (_a = tools.find((t) => t.name === call.name)) != null ? _a : null;
362
+ }
363
+ async executeTool(tool, rawArgs) {
364
+ const args = typeof rawArgs === "string" ? JSON.parse(rawArgs) : rawArgs;
365
+ return await tool.invoke(args);
366
+ }
367
+ formatToolResult(callId, payload) {
368
+ return {
369
+ type: "function_call_output",
370
+ call_id: callId,
371
+ output: JSON.stringify(payload)
372
+ };
373
+ }
374
+ async executeToolCalls(toolCalls, tools) {
375
+ var _a;
376
+ const results = [];
377
+ for (const call of toolCalls) {
378
+ const tool = this.resolveTool(call, tools);
379
+ if (!tool) {
380
+ results.push(
381
+ this.formatToolResult(call.call_id, {
382
+ error: `Unknown tool: ${call.name}`
383
+ })
384
+ );
385
+ continue;
386
+ }
387
+ try {
388
+ const result = await this.executeTool(tool, call.arguments);
389
+ results.push(this.formatToolResult(call.call_id, result));
390
+ } catch (err) {
391
+ results.push(
392
+ this.formatToolResult(call.call_id, {
393
+ error: (_a = err.message) != null ? _a : "Tool execution failed"
394
+ })
395
+ );
396
+ }
397
+ }
398
+ return results;
399
+ }
400
+ async handle(responseContext) {
401
+ let providerResponse = responseContext.providerResponse;
402
+ let toolCallingResponse;
403
+ while (this.hasToolCalls(providerResponse)) {
404
+ const toolCalls = this.extractToolCalls(providerResponse);
405
+ const toolResults = await this.executeToolCalls(toolCalls, this.tools);
406
+ this.request.input = toolResults;
407
+ this.request.previous_response_id = providerResponse.id;
408
+ toolCallingResponse = await this.client.send(this.request);
409
+ responseContext.addUsageEntry(
410
+ new UsageEntry(
411
+ toolCallingResponse.usage.input_tokens,
412
+ toolCallingResponse.usage.output_tokens,
413
+ toolCallingResponse.model
414
+ )
415
+ );
416
+ responseContext.setProviderResponse(toolCallingResponse);
417
+ responseContext.setResponse(toolCallingResponse);
418
+ providerResponse = toolCallingResponse;
419
+ }
420
+ return await this.nextHandler.handle(responseContext);
421
+ }
422
+ };
423
+
424
+ // src/core/endpoint/response-context.ts
425
+ var ResponseContext = class {
426
+ constructor() {
427
+ this.usageEntries = [];
428
+ }
429
+ setProviderResponse(providerResponse) {
430
+ this.providerResponse = providerResponse;
431
+ return this;
432
+ }
433
+ addUsageEntry(usageEntry) {
434
+ this.usageEntries.push(usageEntry);
435
+ return this;
436
+ }
437
+ setResponse(response) {
438
+ this.response = response;
439
+ return this;
440
+ }
441
+ };
442
+
443
+ // src/providers/openai/response-handler/usage.ts
444
+ var UsageHandler = class extends ResponseHandler {
445
+ async handle(responseContext) {
446
+ const providerResponse = responseContext.providerResponse;
447
+ const usage = providerResponse.usage;
448
+ if (usage) {
449
+ responseContext.addUsageEntry(
450
+ new UsageEntry(usage.input_tokens, usage.output_tokens, providerResponse.model)
451
+ );
452
+ }
453
+ return await this.nextHandler.handle(responseContext);
454
+ }
455
+ };
456
+
457
+ // src/providers/openai/endpoint.ts
458
+ var OpenAIResponses = class extends Endpoint {
459
+ constructor() {
460
+ super();
461
+ this.requestBuilder = new OpenAIResponsesBuilder();
462
+ }
463
+ async sendRequest(command) {
464
+ try {
465
+ const request = this.buildRequest(command);
466
+ const client = OpenAIClientResolver.resolve(request);
467
+ const response = await client.send(request);
468
+ const responseContext = new ResponseContext();
469
+ responseContext.setProviderResponse(response);
470
+ const usageHandler = new UsageHandler();
471
+ const functionCallsHandler = new FunctionCallsHandler(
472
+ request,
473
+ command.tools ? command.tools : []
474
+ );
475
+ const outputParsedHandler = new OutputParsedHandler();
476
+ const outputTextHandler = new OutputTextHandler();
477
+ const contentHandler = new ContentHandler();
478
+ usageHandler.setNextHandler(functionCallsHandler).setNextHandler(outputParsedHandler).setNextHandler(outputTextHandler).setNextHandler(contentHandler);
479
+ const responseHandler = usageHandler;
480
+ return await responseHandler.handle(responseContext);
481
+ } catch (error) {
482
+ console.warn("[OpenAIProvider] Responses API request failed:", error);
483
+ throw error;
484
+ }
485
+ }
486
+ };
487
+
488
+ // src/providers/anthropic/mapper.ts
489
+ var AnthropicMapper = class {
490
+ /**
491
+ * Transforms domain messages to Anthropic API format.
492
+ * Separates system messages from conversation messages.
493
+ */
494
+ toMessages(messages) {
495
+ const anthropicMessages = [];
496
+ let systemPrompt;
497
+ for (const msg of messages) {
498
+ if (msg.role === "system") {
499
+ const content = typeof msg.content === "string" ? msg.content : msg.content.map((p) => p.text).join("\n");
500
+ systemPrompt = systemPrompt ? `${systemPrompt}
501
+
502
+ ${content}` : content;
503
+ continue;
504
+ }
505
+ if (msg.role === "tool") {
506
+ continue;
507
+ }
508
+ if (msg.role === "user" || msg.role === "assistant") {
509
+ if (typeof msg.content === "string") {
510
+ anthropicMessages.push({
511
+ role: msg.role,
512
+ content: msg.content
513
+ });
514
+ } else {
515
+ const contentBlocks = msg.content.map((part) => {
516
+ if (part.type === "text") {
517
+ return {
518
+ type: "text",
519
+ text: part.text
520
+ };
521
+ } else if (part.type === "image_url") {
522
+ const imageUrl = part.url;
523
+ if (imageUrl.startsWith("data:image")) {
524
+ const matches = imageUrl.match(/data:image\/(\w+);base64,(.+)/);
525
+ if (matches) {
526
+ const [, mediaType, data] = matches;
527
+ return {
528
+ type: "image",
529
+ source: {
530
+ type: "base64",
531
+ media_type: `image/${mediaType}`,
532
+ data
533
+ }
534
+ };
535
+ }
536
+ }
537
+ throw new Error(
538
+ "[AnthropicMapper] Image URLs must be base64-encoded. Convert to data:image/[type];base64,[data] format."
539
+ );
540
+ }
541
+ return { type: "text", text: "" };
542
+ });
543
+ anthropicMessages.push({
544
+ role: msg.role,
545
+ content: contentBlocks
546
+ });
547
+ }
548
+ }
549
+ }
550
+ const validated = this.ensureAlternatingRoles(anthropicMessages);
551
+ return {
552
+ messages: validated,
553
+ system: systemPrompt
554
+ };
555
+ }
556
+ /**
557
+ * Ensures messages alternate between user and assistant roles.
558
+ * Anthropic API requires this constraint.
559
+ */
560
+ ensureAlternatingRoles(messages) {
561
+ if (messages.length === 0) return messages;
562
+ const result = [];
563
+ let lastRole;
564
+ for (const msg of messages) {
565
+ if (lastRole === msg.role && result.length > 0) {
566
+ const lastMsg = result[result.length - 1];
567
+ if (typeof lastMsg.content === "string" && typeof msg.content === "string") {
568
+ lastMsg.content = `${lastMsg.content}
569
+ ${msg.content}`;
570
+ } else {
571
+ const lastContent = Array.isArray(lastMsg.content) ? lastMsg.content : [{ type: "text", text: lastMsg.content }];
572
+ const newContent = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }];
573
+ lastMsg.content = [...lastContent, ...newContent];
574
+ }
575
+ } else {
576
+ result.push(msg);
577
+ lastRole = msg.role;
578
+ }
579
+ }
580
+ if (result.length > 0 && result[0].role !== "user") {
581
+ throw new Error(
582
+ "[AnthropicMapper] First message must be from user. Anthropic API requires conversations to start with a user message."
583
+ );
584
+ }
585
+ return result;
586
+ }
587
+ };
588
+
589
+ // src/providers/anthropic/builder.ts
590
+ var import_zod2 = require("@anthropic-ai/sdk/helpers/beta/zod");
591
+ var AnthropicRequestBuilder = class extends RequestBuilder {
592
+ constructor() {
593
+ super(...arguments);
594
+ this.mapper = new AnthropicMapper();
595
+ }
596
+ addModel(model) {
597
+ this.request.model = ANTHROPIC_MODEL_MAP[model];
598
+ return this;
599
+ }
600
+ addTask(task) {
601
+ const message = {
602
+ role: "user",
603
+ content: task
604
+ };
605
+ if (!this.request.messages) {
606
+ this.request.messages = [];
607
+ }
608
+ this.request.messages.push(message);
609
+ return this;
610
+ }
611
+ addMessages(messages) {
612
+ const { messages: anthropicMessages, system } = this.mapper.toMessages(messages);
613
+ this.request.messages = anthropicMessages;
614
+ if (system) {
615
+ this.request.system = system;
616
+ }
617
+ return this;
618
+ }
619
+ addStructuredOutput(schema) {
620
+ this.request.betas = ["structured-outputs-2025-11-13"];
621
+ this.request.output_format = (0, import_zod2.betaZodOutputFormat)(schema);
622
+ return this;
623
+ }
624
+ addTools(tools) {
625
+ this.request.tools = tools.map((tool) => ({
626
+ name: tool.name,
627
+ description: tool.description,
628
+ input_schema: tool.schema
629
+ }));
630
+ return this;
631
+ }
632
+ build() {
633
+ if (!this.request.max_tokens) {
634
+ this.request.max_tokens = 1024;
635
+ }
636
+ return this.request;
637
+ }
638
+ };
639
+
640
+ // src/providers/anthropic/client/default.ts
641
+ var import_sdk = __toESM(require("@anthropic-ai/sdk"));
642
+ var AnthropicDefaultClient = class {
643
+ constructor(client = new import_sdk.default()) {
644
+ this.client = client;
645
+ }
646
+ async send(request) {
647
+ return await this.client.messages.create(request);
648
+ }
649
+ };
650
+
651
+ // src/providers/anthropic/client/parser.ts
652
+ var import_sdk2 = __toESM(require("@anthropic-ai/sdk"));
653
+ var AnthropicParserClient = class {
654
+ constructor(client = new import_sdk2.default()) {
655
+ this.client = client;
656
+ }
657
+ async send(request) {
658
+ return await this.client.beta.messages.parse(request);
659
+ }
660
+ };
661
+
662
+ // src/providers/anthropic/client/resolver.ts
663
+ var AnthropicClientResolver = class {
664
+ static resolve(request) {
665
+ return request.output_format ? new AnthropicParserClient() : new AnthropicDefaultClient();
666
+ }
667
+ };
668
+
669
+ // src/providers/anthropic/response-handler/parsed-output.ts
670
+ var ParsedOutputHandler = class extends ResponseHandler {
671
+ async handle(responseContext) {
672
+ const providerResponse = responseContext.providerResponse;
673
+ if (providerResponse.parsed_output) {
674
+ responseContext.setResponse(providerResponse.parsed_output);
675
+ return responseContext;
676
+ }
677
+ return await this.nextHandler.handle(responseContext);
678
+ }
679
+ };
680
+
681
+ // src/providers/anthropic/response-handler/content.ts
682
+ var ContentHandler2 = class extends ResponseHandler {
683
+ async handle(responseContext) {
684
+ const providerResponse = responseContext.providerResponse;
685
+ const content = providerResponse.content.filter((block) => block.type === "text").map((block) => block.type === "text" ? block.text : "").join("");
686
+ if (content) {
687
+ responseContext.setResponse(content);
688
+ return responseContext;
689
+ }
690
+ return await this.nextHandler.handle(responseContext);
691
+ }
692
+ };
693
+
694
+ // src/providers/anthropic/response-handler/tool-use.ts
695
+ var ToolUseHandler = class extends ResponseHandler {
696
+ constructor(request, tools) {
697
+ super();
698
+ this.tools = tools;
699
+ this.request = request;
700
+ this.client = new AnthropicDefaultClient();
701
+ }
702
+ async executeToolCalls(tools, toolUseBlocks) {
703
+ const results = [];
704
+ for (const toolUse of toolUseBlocks) {
705
+ const tool = tools == null ? void 0 : tools.find((t) => t.name === toolUse.name);
706
+ if (!tool) {
707
+ results.push({
708
+ type: "tool_result",
709
+ tool_use_id: toolUse.id,
710
+ content: JSON.stringify({ error: `Unknown tool: ${toolUse.name}` })
711
+ });
712
+ continue;
713
+ }
714
+ try {
715
+ const result = await tool.invoke(toolUse.input);
716
+ results.push({
717
+ type: "tool_result",
718
+ tool_use_id: toolUse.id,
719
+ content: JSON.stringify(result)
720
+ });
721
+ } catch (error) {
722
+ results.push({
723
+ type: "tool_result",
724
+ tool_use_id: toolUse.id,
725
+ content: JSON.stringify({ error: error.message })
726
+ });
727
+ }
728
+ }
729
+ return results;
730
+ }
731
+ async handle(responseContext) {
732
+ let providerResponse = responseContext.providerResponse;
733
+ while (providerResponse.stop_reason === "tool_use") {
734
+ const toolUseBlocks = providerResponse.content.filter(
735
+ (block) => block.type === "tool_use"
736
+ );
737
+ this.request.messages.push({
738
+ role: "assistant",
739
+ content: providerResponse.content
740
+ });
741
+ const toolResults = await this.executeToolCalls(this.tools, toolUseBlocks);
742
+ this.request.messages.push({
743
+ role: "user",
744
+ content: toolResults
745
+ });
746
+ const toolCallingResponse = await this.client.send(this.request);
747
+ responseContext.addUsageEntry(
748
+ new UsageEntry(
749
+ toolCallingResponse.usage.input_tokens,
750
+ toolCallingResponse.usage.output_tokens,
751
+ toolCallingResponse.model
752
+ )
753
+ );
754
+ responseContext.setProviderResponse(toolCallingResponse);
755
+ providerResponse = toolCallingResponse;
756
+ }
757
+ return await this.nextHandler.handle(responseContext);
758
+ }
759
+ };
760
+
761
+ // src/providers/anthropic/response-handler/usage.ts
762
+ var UsageHandler2 = class extends ResponseHandler {
763
+ async handle(responseContext) {
764
+ const providerResponse = responseContext.providerResponse;
765
+ const usage = providerResponse.usage;
766
+ if (usage) {
767
+ responseContext.addUsageEntry(
768
+ new UsageEntry(usage.input_tokens, usage.output_tokens, providerResponse.model)
769
+ );
770
+ }
771
+ return await this.nextHandler.handle(responseContext);
772
+ }
773
+ };
774
+
775
+ // src/providers/anthropic/response-handler/undhandled.ts
776
+ var UnhandledResponseHandler = class extends ResponseHandler {
777
+ async handle(responseContext) {
778
+ var _a, _b;
779
+ const providerResponse = responseContext.providerResponse;
780
+ const id = (_a = providerResponse == null ? void 0 : providerResponse.id) != null ? _a : "unknown";
781
+ const model = (_b = providerResponse == null ? void 0 : providerResponse.model) != null ? _b : "unknown";
782
+ throw new Error(`No response handler matched. response_id=${id} model=${model}`);
783
+ }
784
+ };
785
+
786
+ // src/providers/anthropic/endpoint.ts
787
+ var AnthropicEndpoint = class extends Endpoint {
788
+ constructor() {
789
+ super(...arguments);
790
+ this.requestBuilder = new AnthropicRequestBuilder();
791
+ }
792
+ async sendRequest(command) {
793
+ const request = this.buildRequest(command);
794
+ const client = AnthropicClientResolver.resolve(request);
795
+ const response = await client.send(request);
796
+ const responseContext = new ResponseContext();
797
+ responseContext.setProviderResponse(response);
798
+ const usageHandler = new UsageHandler2();
799
+ const toolUseHandler = new ToolUseHandler(request, command.tools ? command.tools : []);
800
+ const parsedOutputHandler = new ParsedOutputHandler();
801
+ const contentHandler = new ContentHandler2();
802
+ const unhandledResponseHandler = new UnhandledResponseHandler();
803
+ usageHandler.setNextHandler(toolUseHandler).setNextHandler(parsedOutputHandler).setNextHandler(contentHandler).setNextHandler(unhandledResponseHandler);
804
+ const responseHandler = usageHandler;
805
+ return await responseHandler.handle(responseContext);
806
+ }
807
+ };
808
+
809
+ // src/providers/endpoint-resolver.ts
810
+ var DefaultEndpointResolver = class extends EndpointResolver {
811
+ isOpenAIModel(value) {
812
+ return OPENAI_MODELS.includes(value);
813
+ }
814
+ isAnthropicModel(value) {
815
+ return ANTHROPIC_MODELS.includes(value);
816
+ }
817
+ resolve(model) {
818
+ if (this.isOpenAIModel(model)) {
819
+ return new OpenAIResponses();
820
+ } else if (this.isAnthropicModel(model)) {
821
+ return new AnthropicEndpoint();
822
+ }
823
+ throw new Error("Provider not found");
824
+ }
825
+ };
826
+
827
+ // src/core/agents/agent.ts
828
+ var Agent = class {
829
+ constructor(command) {
830
+ this.gateway = new RequestGateway(new DefaultEndpointResolver());
831
+ this.command = command;
832
+ }
833
+ setModel(model) {
834
+ this.command.model = model;
835
+ }
836
+ setMessages(messages) {
837
+ this.command.messages = messages;
838
+ }
839
+ setTask(task) {
840
+ this.command.task = task;
841
+ }
842
+ setStructuredOutput(schema) {
843
+ this.command.structuredOutput = schema;
844
+ }
845
+ async act(task) {
846
+ if (task) {
847
+ this.command.task = task;
848
+ }
849
+ return await this.gateway.invoke(this.command);
850
+ }
851
+ };
852
+
853
+ // src/core/workflow/schema/plan.ts
854
+ var import_zod3 = __toESM(require("zod"));
855
+ var ModelSchema = import_zod3.default.enum([...OPENAI_MODELS, ...ANTHROPIC_MODELS]);
856
+ var TaskPlanNodeSchema = import_zod3.default.object({
857
+ kind: import_zod3.default.literal("task"),
858
+ task: import_zod3.default.string(),
859
+ model: ModelSchema
860
+ });
861
+ var WorkflowPlanNodeSchema = import_zod3.default.lazy(
862
+ () => import_zod3.default.object({
863
+ kind: import_zod3.default.literal("workflow"),
864
+ mode: import_zod3.default.enum(["sequential", "parallel"]),
865
+ units: import_zod3.default.array(PlanNodeSchema)
866
+ })
867
+ );
868
+ var PlanNodeSchema = TaskPlanNodeSchema.or(WorkflowPlanNodeSchema);
869
+ var PlanSchema = import_zod3.default.object({
870
+ root: PlanNodeSchema
871
+ });
872
+
873
+ // src/core/workflow/execution/parallel.ts
874
+ var ParallelExecution = class {
875
+ async execute(workflow, hook) {
876
+ const promises = [];
877
+ for (const u of workflow.units) {
878
+ promises.push(u.execute(hook));
879
+ }
880
+ const results = await Promise.all(promises);
881
+ return results;
882
+ }
883
+ };
884
+
885
+ // src/core/workflow/execution/sequential.ts
886
+ var SequentalExecution = class {
887
+ async execute(workflow, hook) {
888
+ const results = [];
889
+ for (const u of workflow.units) {
890
+ results.push(await u.execute(hook));
891
+ }
892
+ return results;
893
+ }
894
+ };
895
+
896
+ // src/core/workflow/execution/strategy-factory.ts
897
+ var ExecutionStrategyFactory = class {
898
+ static create(mode) {
899
+ let strategy;
900
+ if (mode == "parallel") {
901
+ strategy = new ParallelExecution();
902
+ } else {
903
+ strategy = new SequentalExecution();
904
+ }
905
+ return strategy;
906
+ }
907
+ };
908
+
909
+ // src/core/workflow/hooks/cluster.ts
910
+ var ClusterHook = class {
911
+ constructor(hooks) {
912
+ this.hooks = hooks;
913
+ }
914
+ beforeTask(task) {
915
+ this.hooks.forEach((h) => h.beforeTask(task));
916
+ }
917
+ afterTask(task, result) {
918
+ this.hooks.forEach((h) => h.afterTask(task, result));
919
+ }
920
+ beforeWorkflow(wf) {
921
+ this.hooks.forEach((h) => h.beforeWorkflow(wf));
922
+ }
923
+ afterWorkflow(wf, result) {
924
+ this.hooks.forEach((h) => h.afterWorkflow(wf, result));
925
+ }
926
+ };
927
+
928
+ // src/core/workflow/hooks/logger.ts
929
+ var Logger = class {
930
+ beforeWorkflow(workflow) {
931
+ console.log(`[Workflow:start], Mode: ${workflow.mode}`);
932
+ }
933
+ afterWorkflow(workflow) {
934
+ console.log(`[Workflow:end], Mode: ${workflow.mode}`);
935
+ }
936
+ beforeTask(task) {
937
+ console.log(`[Task:end]: Model: ${task.getModel()} Task: ${task.getTask()}`);
938
+ }
939
+ afterTask(task, result) {
940
+ console.log(`[Task:end]: Model: ${task.getModel()} Task: ${task.getTask()}`);
941
+ }
942
+ };
943
+
944
+ // src/core/workflow/hooks/index.ts
945
+ var loggingHook = new Logger();
946
+ var defaultHooks = [loggingHook];
947
+ var clusterHook = new ClusterHook(defaultHooks);
948
+ var DEFAULT_CLUSTER_HOOK = clusterHook;
949
+
950
+ // src/core/workflow/workflow.ts
951
+ var Workflow = class extends WorkUnit {
952
+ constructor(mode, units) {
953
+ super();
954
+ this.mode = mode;
955
+ this.units = units;
956
+ }
957
+ async execute(hook = DEFAULT_CLUSTER_HOOK) {
958
+ hook.beforeWorkflow(this);
959
+ const executionStrategy = ExecutionStrategyFactory.create(this.mode);
960
+ const result = await executionStrategy.execute(this, hook);
961
+ hook.afterWorkflow(this, result);
962
+ return result;
963
+ }
964
+ };
965
+
966
+ // src/core/workflow/task.ts
967
+ var Task = class extends WorkUnit {
968
+ constructor(task, model) {
969
+ super();
970
+ this.task = task;
971
+ this.model = model;
972
+ }
973
+ getTask() {
974
+ return this.task;
975
+ }
976
+ getModel() {
977
+ return this.model;
978
+ }
979
+ async execute(hook = DEFAULT_CLUSTER_HOOK) {
980
+ hook.beforeTask(this);
981
+ const command = {
982
+ model: this.model,
983
+ task: this.task
984
+ };
985
+ const agent = new Agent(command);
986
+ const result = await agent.act(this.task);
987
+ hook.afterTask(this, result);
988
+ return result;
989
+ }
990
+ };
991
+
992
+ // src/core/workflow/mapper.ts
993
+ var PlanWorkflowMapper = class {
994
+ static fromPlan(plan) {
995
+ return this.fromNode(plan.root);
996
+ }
997
+ static fromNode(node) {
998
+ if (node.kind !== "workflow") {
999
+ throw new Error("Root must be workflow");
1000
+ }
1001
+ return new Workflow(node.mode, node.units.map(this.mapNode));
1002
+ }
1003
+ static mapNode(node) {
1004
+ if (node.kind === "task") {
1005
+ return new Task(node.task, node.model);
1006
+ }
1007
+ return new Workflow(node.mode, node.units.map(this.mapNode));
1008
+ }
1009
+ };
1010
+
1011
+ // src/core/agents/planner.ts
1012
+ var PROMPT = `You are a planner.
1013
+
1014
+ Rules:
1015
+ - Use 'parallel' for the task that can be run in parallel.
1016
+ - Pick model based on the task complexity
1017
+ - Keep prompts actionable.
1018
+ - Don't ask user for any input, just do the thing with available data you have.
1019
+ `;
1020
+ var PlanningAgent = class extends Agent {
1021
+ constructor(command) {
1022
+ super(command);
1023
+ }
1024
+ async planFromGoal(goal) {
1025
+ this.setStructuredOutput(PlanSchema);
1026
+ const plan = await this.act(`${PROMPT}
1027
+ Goal: ${goal}`);
1028
+ return PlanWorkflowMapper.fromPlan(plan);
1029
+ }
1030
+ };
1031
+ // Annotate the CommonJS export names for ESM import in node:
1032
+ 0 && (module.exports = {
1033
+ Agent,
1034
+ PlanningAgent,
1035
+ Task,
1036
+ WorkUnit,
1037
+ Workflow
1038
+ });
1039
+ //# sourceMappingURL=index.js.map