@mozaik-ai/core 4.2.0-beta.2 → 4.2.0-beta.4

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 CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,14 +17,24 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
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
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ Agent: () => Agent,
23
34
  Participant: () => Participant,
24
35
  SituationSpecification: () => SituationSpecification,
25
36
  SpaceEvent: () => SpaceEvent,
37
+ defineAgentModule: () => defineAgentModule,
26
38
  defineRuntime: () => defineRuntime
27
39
  });
28
40
  module.exports = __toCommonJS(index_exports);
@@ -394,11 +406,2221 @@ var NotSituationSpecification = class extends SituationSpecification {
394
406
  return !this.rule.isSatisfiedBy(situationContext);
395
407
  }
396
408
  };
409
+
410
+ // src/domain/agent/agent.ts
411
+ var Agent = class _Agent extends Participant {
412
+ constructor(manifest, tools, memory, handlers) {
413
+ super(manifest, handlers);
414
+ this.memory = memory;
415
+ this.tools = tools;
416
+ }
417
+ getTools() {
418
+ return this.tools;
419
+ }
420
+ getMemory() {
421
+ return this.memory;
422
+ }
423
+ static create({
424
+ manifest,
425
+ tools,
426
+ memory,
427
+ handlers
428
+ }) {
429
+ return new _Agent(manifest, tools, memory, handlers);
430
+ }
431
+ static rehydrate(record) {
432
+ return new _Agent(record.manifest, record.tools, record.memory, record.handlers);
433
+ }
434
+ };
435
+
436
+ // src/application/use-cases/create-agent.ts
437
+ var CreateAgentUseCase = class {
438
+ constructor(agentRepository, memoryFactory) {
439
+ this.agentRepository = agentRepository;
440
+ this.memoryFactory = memoryFactory;
441
+ }
442
+ async execute(name, instruction, tools, handlers) {
443
+ const id = UuidGenerator.create();
444
+ const manifest = { id, name, role: "agent" };
445
+ const memory = this.memoryFactory.create();
446
+ const developerMessageItem = {
447
+ type: "developer_message",
448
+ text: instruction
449
+ };
450
+ memory.saveItem(developerMessageItem);
451
+ const agentRecord = { id, manifest, tools, memory, handlers };
452
+ const agent = Agent.create(agentRecord);
453
+ await this.agentRepository.save(agent);
454
+ return agentRecord;
455
+ }
456
+ };
457
+
458
+ // src/infrastructure/repositories/in-memory-agent-repository.ts
459
+ var InMemoryAgentRepository = class {
460
+ constructor() {
461
+ this.agents = [];
462
+ }
463
+ exists(id) {
464
+ return Promise.resolve(this.agents.some((agent) => agent.getManifest().id === id));
465
+ }
466
+ findById(id) {
467
+ return Promise.resolve(this.agents.find((agent) => agent.getManifest().id === id));
468
+ }
469
+ findAll() {
470
+ return Promise.resolve(this.agents);
471
+ }
472
+ async save(agent) {
473
+ this.agents.push(agent);
474
+ }
475
+ };
476
+
477
+ // src/domain/agent/loop/loop.ts
478
+ var Loop = class _Loop {
479
+ constructor(loopId, agentId, subject, createdAt, state, inferenceRequest, pendingOperation, transitionHistory, operationHistory, rules) {
480
+ this.loopId = loopId;
481
+ this.agentId = agentId;
482
+ this.subject = subject;
483
+ this.createdAt = createdAt;
484
+ this.state = state;
485
+ this.inferenceRequest = inferenceRequest;
486
+ this.pendingOperation = pendingOperation;
487
+ this.transitionHistory = transitionHistory;
488
+ this.operationHistory = operationHistory;
489
+ this.loopRules = rules;
490
+ }
491
+ get id() {
492
+ return this.loopId;
493
+ }
494
+ get stateId() {
495
+ return this.state;
496
+ }
497
+ get pending() {
498
+ return this.pendingOperation;
499
+ }
500
+ get history() {
501
+ return this.transitionHistory;
502
+ }
503
+ get completedOperations() {
504
+ return this.operationHistory;
505
+ }
506
+ get request() {
507
+ return this.inferenceRequest;
508
+ }
509
+ get rules() {
510
+ return this.loopRules;
511
+ }
512
+ getAgentId() {
513
+ return this.agentId;
514
+ }
515
+ record() {
516
+ return {
517
+ id: this.id,
518
+ agentId: this.agentId,
519
+ subject: this.subject,
520
+ createdAt: this.createdAt,
521
+ state: this.state,
522
+ inferenceRequest: this.inferenceRequest,
523
+ pendingOperation: this.pendingOperation,
524
+ transitionHistory: [...this.transitionHistory],
525
+ operationHistory: [...this.operationHistory],
526
+ rules: [...this.rules]
527
+ };
528
+ }
529
+ moveToIdle(reason, transitionId) {
530
+ this.transitionTo("idle", reason, transitionId);
531
+ this.pendingOperation = void 0;
532
+ }
533
+ moveToAwaitingInference(operation) {
534
+ this.assertAwaitingInferenceRequest();
535
+ this.pendingOperation = operation;
536
+ this.transitionTo("awaiting_inference", "inference_requested", operation.id);
537
+ }
538
+ moveToAwaitingToolOutput(operation, occurredAt) {
539
+ this.assertIdle();
540
+ this.pendingOperation = operation;
541
+ this.transitionTo("awaiting_tool_output", "tool_execution_requested", operation.id);
542
+ }
543
+ requestInference(request) {
544
+ this.assertAwaitingInferenceRequest();
545
+ this.inferenceRequest = request;
546
+ const operation = {
547
+ id: UuidGenerator.create(),
548
+ type: "inference",
549
+ requestedAt: SystemClock.now(),
550
+ request: this.inferenceRequest
551
+ };
552
+ this.moveToAwaitingInference(operation);
553
+ return operation;
554
+ }
555
+ requestToolUse(operationId, call, requestedAt) {
556
+ this.assertIdle();
557
+ const operation = {
558
+ id: operationId,
559
+ type: "tool_execution",
560
+ requestedAt,
561
+ call
562
+ };
563
+ this.moveToAwaitingToolOutput(operation, requestedAt);
564
+ return operation;
565
+ }
566
+ transitionTo(nextState, reason, operationId) {
567
+ const occurredAt = SystemClock.now();
568
+ const previousState = this.state;
569
+ this.state = nextState;
570
+ this.transitionHistory.push({
571
+ occurredAt,
572
+ previousState,
573
+ nextState,
574
+ reason,
575
+ operationId
576
+ });
577
+ }
578
+ assertIdle() {
579
+ if (this.state !== "idle") {
580
+ throw new Error(`Expected idle loop, but loop is ${this.state}`);
581
+ }
582
+ }
583
+ assertAwaitingInferenceRequest() {
584
+ if (this.state !== "awaiting_inference_request") {
585
+ throw new Error(`Expected awaiting inference request loop, but loop is ${this.state}`);
586
+ }
587
+ }
588
+ receiveInferenceResult(operationId, result) {
589
+ if (this.state !== "awaiting_inference") {
590
+ throw new Error(`Cannot receive inference result while loop is ${this.state}`);
591
+ }
592
+ const operation = this.pendingOperation;
593
+ if ((operation == null ? void 0 : operation.type) !== "inference" || operation.id !== operationId) {
594
+ throw new Error(`Inference result does not match pending operation ${operationId}`);
595
+ }
596
+ if (!this.inferenceRequest) {
597
+ throw new Error("Inference request is not provided");
598
+ }
599
+ this.moveToIdle("inference_completed", operationId);
600
+ this.operationHistory.push({
601
+ type: "inference",
602
+ operationId,
603
+ requestedAt: operation.requestedAt,
604
+ completedAt: SystemClock.now(),
605
+ request: operation.request,
606
+ result
607
+ });
608
+ this.inferenceRequest.context.items.push(...result.items);
609
+ const call = result.items.find((item) => item.type === "tool_use_request");
610
+ if (call) {
611
+ this.pendingOperation = {
612
+ id: call.requestId,
613
+ type: "tool_execution",
614
+ requestedAt: SystemClock.now(),
615
+ call
616
+ };
617
+ this.transitionTo("awaiting_tool_output", "tool_use_requested", call.requestId);
618
+ return;
619
+ }
620
+ this.pendingOperation = void 0;
621
+ }
622
+ receiveToolUseResult(operationId, result) {
623
+ if (this.state !== "awaiting_tool_output") {
624
+ throw new Error(`Cannot receive tool output while loop is ${this.state}`);
625
+ }
626
+ const operation = this.pendingOperation;
627
+ if ((operation == null ? void 0 : operation.type) !== "tool_execution" || operation.id !== operationId) {
628
+ throw new Error(`Tool output does not match pending operation ${operationId}`);
629
+ }
630
+ if (!this.inferenceRequest) {
631
+ throw new Error("Inference request is not provided");
632
+ }
633
+ this.operationHistory.push({
634
+ type: "tool_use",
635
+ operationId,
636
+ requestedAt: operation.requestedAt,
637
+ completedAt: SystemClock.now(),
638
+ call: operation.call,
639
+ result
640
+ });
641
+ this.inferenceRequest.context.items.push(result);
642
+ this.pendingOperation = void 0;
643
+ this.transitionTo("awaiting_inference_request", "tool_use_completed", operationId);
644
+ }
645
+ complete(reason) {
646
+ this.assertNotSettled("complete");
647
+ this.pendingOperation = void 0;
648
+ this.transitionTo("completed", reason);
649
+ }
650
+ stop(reason) {
651
+ this.assertNotSettled("stop");
652
+ this.pendingOperation = void 0;
653
+ this.transitionTo("stopped", reason);
654
+ }
655
+ wait(reason) {
656
+ this.assertNotSettled("wait");
657
+ this.pendingOperation = void 0;
658
+ this.transitionTo("idle", reason);
659
+ }
660
+ assertNotSettled(intent) {
661
+ if (this.state === "completed" || this.state === "stopped") {
662
+ throw new Error(`Cannot ${intent} a loop that is already ${this.state}`);
663
+ }
664
+ }
665
+ static create(id, agentId, subject, rules) {
666
+ const createdAt = SystemClock.now();
667
+ return new _Loop(
668
+ id,
669
+ agentId,
670
+ subject,
671
+ createdAt,
672
+ "awaiting_inference_request",
673
+ void 0,
674
+ void 0,
675
+ [],
676
+ [],
677
+ rules
678
+ );
679
+ }
680
+ static rehydrate(record) {
681
+ return new _Loop(
682
+ record.id,
683
+ record.agentId,
684
+ record.subject,
685
+ record.createdAt,
686
+ record.state,
687
+ record.inferenceRequest,
688
+ record.pendingOperation,
689
+ [...record.transitionHistory],
690
+ [...record.operationHistory],
691
+ [...record.rules]
692
+ );
693
+ }
694
+ };
695
+
696
+ // src/application/use-cases/create-loop.ts
697
+ var CreateAgentLoopUseCase = class {
698
+ constructor(loopRepository) {
699
+ this.loopRepository = loopRepository;
700
+ }
701
+ async execute(subject, agentId, rules) {
702
+ const loop = Loop.create(UuidGenerator.create(), agentId, subject, rules);
703
+ await this.loopRepository.save(loop);
704
+ return loop;
705
+ }
706
+ };
707
+
708
+ // src/infrastructure/repositories/in-memory-loop-repository.ts
709
+ var InMemoryLoopRepository = class {
710
+ constructor() {
711
+ this.loops = [];
712
+ }
713
+ findById(id) {
714
+ return Promise.resolve(this.loops.find((loop) => loop.id === id));
715
+ }
716
+ save(loop) {
717
+ const index = this.loops.findIndex((stored) => stored.id === loop.id);
718
+ if (index === -1) {
719
+ this.loops.push(loop);
720
+ } else {
721
+ this.loops[index] = loop;
722
+ }
723
+ return Promise.resolve();
724
+ }
725
+ };
726
+
727
+ // src/domain/inference/tool-use-item-factory.ts
728
+ var ToolUseItemFactory = class {
729
+ create(toolUseRequest, result) {
730
+ const toolUseResult = {
731
+ type: "tool_use_result",
732
+ requestId: toolUseRequest.requestId,
733
+ result: {
734
+ type: "input_text",
735
+ text: result
736
+ }
737
+ };
738
+ return toolUseResult;
739
+ }
740
+ };
741
+
742
+ // src/application/runners/local-tool-runner.ts
743
+ var LocalToolRunner = class {
744
+ constructor() {
745
+ this.toolUseItemFactory = new ToolUseItemFactory();
746
+ }
747
+ async run(input, tool) {
748
+ try {
749
+ const result = await tool.invoke(JSON.parse(input.toolArguments));
750
+ const resultText = typeof result === "string" ? result : JSON.stringify(result);
751
+ return this.toolUseItemFactory.create(input, resultText);
752
+ } catch (error) {
753
+ const errorText = `Error calling tool: ${error}`;
754
+ return this.toolUseItemFactory.create(input, errorText);
755
+ }
756
+ }
757
+ };
758
+
759
+ // src/application/runners/inference-runner.ts
760
+ var DefaultInferenceRunner = class {
761
+ constructor(supportedModels2, requestValidator) {
762
+ this.supportedModels = supportedModels2;
763
+ this.requestValidator = requestValidator;
764
+ }
765
+ async run(input) {
766
+ const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
767
+ if (!generativeModel) {
768
+ throw new Error(`Unsupported model: ${input.model}`);
769
+ }
770
+ this.requestValidator.validate(input, generativeModel.specification);
771
+ return await generativeModel.endpoint.infer(input);
772
+ }
773
+ async *stream(input) {
774
+ const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
775
+ if (!generativeModel) {
776
+ throw new Error(`Unsupported model: ${input.model}`);
777
+ }
778
+ this.requestValidator.validate(input, generativeModel.specification);
779
+ yield* generativeModel.endpoint.stream(input);
780
+ }
781
+ };
782
+
783
+ // src/domain/inference/request-validation/reasoning-effort.ts
784
+ var ReasoningEffortValidation = class {
785
+ constructor() {
786
+ this.name = "reasoning-effort";
787
+ }
788
+ isValid(inferenceRequest, model) {
789
+ if (inferenceRequest.reasoningEffort === void 0) {
790
+ return true;
791
+ }
792
+ if (!model.supportsReasoningEffort) {
793
+ return false;
794
+ }
795
+ return model.supportedReasoningEfforts.includes(inferenceRequest.reasoningEffort);
796
+ }
797
+ };
798
+
799
+ // src/domain/inference/request-validation/tool-calling.ts
800
+ var ToolUseRequestingValidation = class {
801
+ constructor() {
802
+ this.name = "tool-calling";
803
+ }
804
+ isValid(inferenceRequest, model) {
805
+ if (inferenceRequest.tools === void 0) {
806
+ return true;
807
+ }
808
+ return model.supportsFunctionCalling;
809
+ }
810
+ };
811
+
812
+ // src/domain/inference/request-validation/streaming.ts
813
+ var StreamingValidation = class {
814
+ constructor() {
815
+ this.name = "streaming";
816
+ }
817
+ isValid(inferenceRequest, model) {
818
+ if (!inferenceRequest.streaming) {
819
+ return true;
820
+ }
821
+ return model.supportsStreaming;
822
+ }
823
+ };
824
+
825
+ // src/domain/inference/request-validation/structured-output.ts
826
+ var StructuredOutputValidation = class {
827
+ constructor() {
828
+ this.name = "structured-output";
829
+ }
830
+ isValid(inferenceRequest, model) {
831
+ if (inferenceRequest.structuredOutput === void 0) {
832
+ return true;
833
+ }
834
+ return model.supportsStructuredOutput;
835
+ }
836
+ };
837
+
838
+ // src/domain/inference/request-validation/context.ts
839
+ function getContextItemValidationKey(item) {
840
+ if (item.type === "user_message") {
841
+ return "user_message";
842
+ }
843
+ if (item.type === "system_message") {
844
+ return "system_message";
845
+ }
846
+ if (item.type === "developer_message") {
847
+ return "developer_message";
848
+ }
849
+ if (item.type === "model_message") {
850
+ return "model_message";
851
+ }
852
+ return item.type;
853
+ }
854
+ var ContextValidation = class {
855
+ constructor() {
856
+ this.name = "context";
857
+ }
858
+ isValid(inferenceRequest, model) {
859
+ return inferenceRequest.context.items.every(
860
+ (item) => model.supportedContextItemTypes.includes(getContextItemValidationKey(item))
861
+ );
862
+ }
863
+ };
864
+
865
+ // src/domain/inference/request-validation/inference-request-validator.ts
866
+ var defaultRequestValidationRules = [
867
+ new ReasoningEffortValidation(),
868
+ new ToolUseRequestingValidation(),
869
+ new StreamingValidation(),
870
+ new StructuredOutputValidation(),
871
+ new ContextValidation()
872
+ ];
873
+ var InferenceRequestValidator = class {
874
+ constructor(rules = defaultRequestValidationRules) {
875
+ this.rules = rules;
876
+ }
877
+ validate(inferenceRequest, model) {
878
+ for (const rule of this.rules) {
879
+ if (!rule.isValid(inferenceRequest, model)) {
880
+ throw new Error(`Request validation "${rule.name}" failed for model "${model.name}"`);
881
+ }
882
+ }
883
+ }
884
+ };
885
+
886
+ // src/domain/inference/token-usage.ts
887
+ var InputTokenDetails = class {
888
+ constructor(cached_tokens) {
889
+ this.cached_tokens = cached_tokens;
890
+ }
891
+ };
892
+ var OutputTokenDetails = class {
893
+ constructor(reasoning_tokens) {
894
+ this.reasoning_tokens = reasoning_tokens;
895
+ }
896
+ };
897
+ var TokenUsage = class {
898
+ constructor(inputTokens, outputTokens, totalTokens, inputTokenDetails, outputTokenDetails) {
899
+ this.inputTokens = inputTokens;
900
+ this.outputTokens = outputTokens;
901
+ this.totalTokens = totalTokens;
902
+ this.inputTokenDetails = inputTokenDetails;
903
+ this.outputTokenDetails = outputTokenDetails;
904
+ }
905
+ };
906
+
907
+ // src/infrastructure/providers/anthropic/anthropic-messages-mapper.ts
908
+ var AnthropicMessagesMapper = class {
909
+ toRequest(inferenceRequest) {
910
+ const { messages, system } = this.mapContextItems(inferenceRequest);
911
+ const outputConfig = {};
912
+ const request = {
913
+ model: inferenceRequest.model,
914
+ messages
915
+ };
916
+ request.max_tokens = inferenceRequest.maxOutputTokens;
917
+ if (system) {
918
+ request.system = system;
919
+ }
920
+ if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
921
+ request.tools = inferenceRequest.tools.map((tool) => ({
922
+ name: tool.name,
923
+ description: tool.description,
924
+ input_schema: tool.parameters
925
+ }));
926
+ }
927
+ if (inferenceRequest.structuredOutput) {
928
+ outputConfig.format = {
929
+ type: "json_schema",
930
+ schema: inferenceRequest.structuredOutput.schema
931
+ };
932
+ }
933
+ if (inferenceRequest.reasoningEffort) {
934
+ request.thinking = { type: "adaptive" };
935
+ outputConfig.effort = inferenceRequest.reasoningEffort;
936
+ }
937
+ if (Object.keys(outputConfig).length > 0) {
938
+ request.output_config = outputConfig;
939
+ }
940
+ if (inferenceRequest.streaming) {
941
+ request.stream = inferenceRequest.streaming;
942
+ }
943
+ return request;
944
+ }
945
+ addContentBlock(messages, role, block) {
946
+ const lastMessage = messages[messages.length - 1];
947
+ if ((lastMessage == null ? void 0 : lastMessage.role) === role) {
948
+ lastMessage.content.push(block);
949
+ return;
950
+ }
951
+ messages.push({
952
+ role,
953
+ content: [block]
954
+ });
955
+ }
956
+ mapContextItems(inferenceRequest) {
957
+ var _a, _b, _c;
958
+ const context = inferenceRequest.context;
959
+ const messages = [];
960
+ const system = [];
961
+ for (const item of context.items) {
962
+ if (item.type === "developer_message" || item.type === "system_message") {
963
+ system.push(item.text);
964
+ continue;
965
+ }
966
+ if (item.type === "user_message") {
967
+ this.addContentBlock(messages, "user", { type: "text", text: item.text });
968
+ continue;
969
+ }
970
+ if (item.type === "model_message") {
971
+ this.addContentBlock(messages, "assistant", { type: "text", text: item.text });
972
+ continue;
973
+ }
974
+ if (item.type === "reasoning") {
975
+ const reasoning = item;
976
+ this.addContentBlock(messages, "assistant", {
977
+ type: "thinking",
978
+ thinking: (_b = (_a = reasoning.content) == null ? void 0 : _a.text) != null ? _b : "",
979
+ signature: (_c = reasoning.encryptedContent) != null ? _c : ""
980
+ });
981
+ continue;
982
+ }
983
+ if (item.type === "tool_use_request") {
984
+ const toolUseRequest = item;
985
+ let input;
986
+ try {
987
+ input = JSON.parse(toolUseRequest.toolArguments);
988
+ } catch (e) {
989
+ input = toolUseRequest.toolArguments;
990
+ }
991
+ this.addContentBlock(messages, "assistant", {
992
+ type: "tool_use",
993
+ id: toolUseRequest.requestId,
994
+ name: toolUseRequest.toolName,
995
+ input
996
+ });
997
+ continue;
998
+ }
999
+ if (item.type === "tool_use_result") {
1000
+ const toolUseResult = item;
1001
+ this.addContentBlock(messages, "user", {
1002
+ type: "tool_result",
1003
+ tool_use_id: toolUseResult.requestId,
1004
+ content: toolUseResult.result.text
1005
+ });
1006
+ }
1007
+ }
1008
+ return {
1009
+ messages,
1010
+ system: system.length > 0 ? system.join("\n\n") : void 0
1011
+ };
1012
+ }
1013
+ extractTokenUsage(response) {
1014
+ var _a, _b;
1015
+ if (!response.usage) {
1016
+ return void 0;
1017
+ }
1018
+ return new TokenUsage(
1019
+ response.usage.input_tokens,
1020
+ response.usage.output_tokens,
1021
+ response.usage.input_tokens + response.usage.output_tokens,
1022
+ new InputTokenDetails(
1023
+ ((_a = response.usage.cache_creation_input_tokens) != null ? _a : 0) + ((_b = response.usage.cache_read_input_tokens) != null ? _b : 0)
1024
+ ),
1025
+ new OutputTokenDetails(0)
1026
+ );
1027
+ }
1028
+ toResponse(response) {
1029
+ var _a;
1030
+ const items = [];
1031
+ for (const block of response.content) {
1032
+ if (block.type === "text") {
1033
+ items.push({
1034
+ type: "model_message",
1035
+ text: block.text
1036
+ });
1037
+ continue;
1038
+ }
1039
+ if (block.type === "tool_use") {
1040
+ items.push({
1041
+ type: "tool_use_request",
1042
+ requestId: block.id,
1043
+ toolName: block.name,
1044
+ toolArguments: JSON.stringify((_a = block.input) != null ? _a : {})
1045
+ });
1046
+ continue;
1047
+ }
1048
+ if (block.type === "thinking") {
1049
+ items.push({
1050
+ type: "reasoning",
1051
+ content: block.thinking ? { type: "input_text", text: block.thinking } : void 0,
1052
+ encryptedContent: block.signature,
1053
+ summary: []
1054
+ });
1055
+ }
1056
+ }
1057
+ return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1058
+ }
1059
+ };
1060
+
1061
+ // src/infrastructure/providers/anthropic/anthropic-messages.ts
1062
+ var import_sdk = __toESM(require("@anthropic-ai/sdk"));
1063
+ var AnthropicMessages = class {
1064
+ constructor(endpointMapper = new AnthropicMessagesMapper(), config = {}) {
1065
+ this.endpointMapper = endpointMapper;
1066
+ this.clientConfig = config;
1067
+ }
1068
+ get client() {
1069
+ var _a;
1070
+ return (_a = this._client) != null ? _a : this._client = new import_sdk.default({
1071
+ baseURL: this.clientConfig.baseURL,
1072
+ apiKey: this.clientConfig.apiKey
1073
+ });
1074
+ }
1075
+ async infer(inferenceRequest) {
1076
+ const request = this.endpointMapper.toRequest(inferenceRequest);
1077
+ const response = await this.client.messages.create(request);
1078
+ return this.endpointMapper.toResponse(response);
1079
+ }
1080
+ async *stream(inferenceRequest) {
1081
+ const request = this.endpointMapper.toRequest(inferenceRequest);
1082
+ const stream = this.client.messages.stream(request);
1083
+ for await (const event of stream) {
1084
+ yield event;
1085
+ }
1086
+ const output = this.endpointMapper.toResponse(await stream.finalMessage());
1087
+ yield {
1088
+ type: "inference.output",
1089
+ producerId: request.model,
1090
+ occurredAt: /* @__PURE__ */ new Date(),
1091
+ payload: output
1092
+ };
1093
+ }
1094
+ };
1095
+
1096
+ // src/infrastructure/providers/openai/openai-responses-mapper.ts
1097
+ var OpenAIResponsesMapper = class {
1098
+ toRequest(inferenceRequest) {
1099
+ var _a, _b;
1100
+ const request = {
1101
+ model: inferenceRequest.model,
1102
+ input: this.mapContextItems(inferenceRequest)
1103
+ };
1104
+ if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1105
+ request.tools = inferenceRequest.tools.map((tool) => ({
1106
+ type: tool.type,
1107
+ name: tool.name,
1108
+ description: tool.description,
1109
+ parameters: tool.parameters
1110
+ }));
1111
+ }
1112
+ if (inferenceRequest.reasoningEffort) {
1113
+ request.reasoning = {
1114
+ effort: inferenceRequest.reasoningEffort
1115
+ };
1116
+ }
1117
+ if (inferenceRequest.structuredOutput) {
1118
+ const format = inferenceRequest.structuredOutput;
1119
+ request.text = {
1120
+ format: {
1121
+ type: "json_schema",
1122
+ name: (_a = format.name) != null ? _a : "response",
1123
+ schema: format.schema,
1124
+ strict: (_b = format.strict) != null ? _b : true
1125
+ }
1126
+ };
1127
+ }
1128
+ if (inferenceRequest.streaming) {
1129
+ request.stream = inferenceRequest.streaming;
1130
+ }
1131
+ return request;
1132
+ }
1133
+ mapContextItems(inferenceRequest) {
1134
+ const input = [];
1135
+ for (const item of inferenceRequest.context.items) {
1136
+ if (item.type === "developer_message" || item.type === "system_message" || item.type === "user_message") {
1137
+ const role = item.type === "developer_message" ? "developer" : item.type === "system_message" ? "system" : "user";
1138
+ input.push({
1139
+ type: "message",
1140
+ role,
1141
+ content: [{ type: "input_text", text: item.text }]
1142
+ });
1143
+ continue;
1144
+ }
1145
+ if (item.type === "model_message") {
1146
+ input.push({
1147
+ type: "message",
1148
+ role: "assistant",
1149
+ content: [{ type: "output_text", text: item.text }]
1150
+ });
1151
+ continue;
1152
+ }
1153
+ if (item.type === "tool_use_request") {
1154
+ const toolUseRequest = item;
1155
+ input.push({
1156
+ type: "function_call",
1157
+ call_id: toolUseRequest.requestId,
1158
+ name: toolUseRequest.toolName,
1159
+ arguments: toolUseRequest.toolArguments
1160
+ });
1161
+ continue;
1162
+ }
1163
+ if (item.type === "tool_use_result") {
1164
+ const toolUseResult = item;
1165
+ input.push({
1166
+ type: "function_call_output",
1167
+ call_id: toolUseResult.requestId,
1168
+ output: [{ type: "input_text", text: toolUseResult.result.text }]
1169
+ });
1170
+ continue;
1171
+ }
1172
+ if (item.type === "reasoning") {
1173
+ const reasoning = item;
1174
+ const reasoningInput = {
1175
+ type: "reasoning",
1176
+ summary: reasoning.summary.map((summary) => ({ type: "summary_text", text: summary.text }))
1177
+ };
1178
+ if (reasoning.encryptedContent !== void 0) {
1179
+ reasoningInput.encrypted_content = reasoning.encryptedContent;
1180
+ }
1181
+ input.push(reasoningInput);
1182
+ }
1183
+ }
1184
+ return input;
1185
+ }
1186
+ extractTokenUsage(response) {
1187
+ var _a, _b, _c, _d;
1188
+ if (!response.usage) {
1189
+ return void 0;
1190
+ }
1191
+ return new TokenUsage(
1192
+ response.usage.input_tokens,
1193
+ response.usage.output_tokens,
1194
+ response.usage.total_tokens,
1195
+ new InputTokenDetails((_b = (_a = response.usage.input_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0),
1196
+ new OutputTokenDetails((_d = (_c = response.usage.output_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0)
1197
+ );
1198
+ }
1199
+ toResponse(response) {
1200
+ var _a, _b, _c;
1201
+ const items = [];
1202
+ for (const item of (_a = response.output) != null ? _a : []) {
1203
+ if (item.type === "message" && item.role === "assistant") {
1204
+ const firstContent = (_b = item.content) == null ? void 0 : _b[0];
1205
+ if (firstContent) {
1206
+ items.push({
1207
+ type: "model_message",
1208
+ text: firstContent.text
1209
+ });
1210
+ }
1211
+ continue;
1212
+ }
1213
+ if (item.type === "function_call") {
1214
+ const toolUseRequest = {
1215
+ type: "tool_use_request",
1216
+ requestId: item.call_id,
1217
+ toolName: item.name,
1218
+ toolArguments: item.arguments
1219
+ };
1220
+ items.push(toolUseRequest);
1221
+ continue;
1222
+ }
1223
+ if (item.type === "reasoning") {
1224
+ items.push({
1225
+ type: "reasoning",
1226
+ content: void 0,
1227
+ encryptedContent: item.encrypted_content,
1228
+ summary: ((_c = item.summary) != null ? _c : []).map((summary) => ({
1229
+ type: "summary_text",
1230
+ text: summary.text
1231
+ }))
1232
+ });
1233
+ }
1234
+ }
1235
+ return {
1236
+ items,
1237
+ tokenUsage: this.extractTokenUsage(response),
1238
+ rowResponse: response
1239
+ };
1240
+ }
1241
+ };
1242
+
1243
+ // src/infrastructure/providers/openai/openai-responses.ts
1244
+ var import_openai = __toESM(require("openai"));
1245
+ var OpenAIResponses = class {
1246
+ constructor(endpointMapper = new OpenAIResponsesMapper(), config = {}) {
1247
+ this.endpointMapper = endpointMapper;
1248
+ this.clientConfig = config;
1249
+ }
1250
+ get client() {
1251
+ var _a;
1252
+ return (_a = this._client) != null ? _a : this._client = new import_openai.default({
1253
+ baseURL: this.clientConfig.baseURL,
1254
+ apiKey: this.clientConfig.apiKey
1255
+ });
1256
+ }
1257
+ async infer(inferenceRequest) {
1258
+ const request = this.endpointMapper.toRequest(inferenceRequest);
1259
+ const response = await this.client.responses.create(request);
1260
+ return this.endpointMapper.toResponse(response);
1261
+ }
1262
+ async *stream(inferenceRequest) {
1263
+ const request = this.endpointMapper.toRequest(inferenceRequest);
1264
+ const stream = await this.client.responses.create({ ...request, stream: true });
1265
+ let completedResponse = void 0;
1266
+ for await (const event of stream) {
1267
+ if (event.type === "response.completed") {
1268
+ completedResponse = event.response;
1269
+ }
1270
+ yield event;
1271
+ }
1272
+ if (!completedResponse) {
1273
+ throw new Error("Stream ended without a completed response");
1274
+ }
1275
+ const output = this.endpointMapper.toResponse(completedResponse);
1276
+ yield {
1277
+ type: "inference.output",
1278
+ payload: output,
1279
+ occurredAt: /* @__PURE__ */ new Date(),
1280
+ producerId: inferenceRequest.model
1281
+ };
1282
+ }
1283
+ };
1284
+
1285
+ // src/infrastructure/providers/gemini/gemini-generate-content.ts
1286
+ var import_genai = require("@google/genai");
1287
+
1288
+ // src/infrastructure/providers/gemini/gemini-generate-content-mapper.ts
1289
+ var GeminiGenerateContentMapper = class {
1290
+ toRequest(inferenceRequest) {
1291
+ const { contents, systemInstruction } = this.mapContextItems(inferenceRequest);
1292
+ const config = {};
1293
+ if (systemInstruction) {
1294
+ config.systemInstruction = systemInstruction;
1295
+ }
1296
+ if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1297
+ config.tools = [
1298
+ {
1299
+ functionDeclarations: inferenceRequest.tools.map((tool) => ({
1300
+ name: tool.name,
1301
+ description: tool.description,
1302
+ parametersJsonSchema: tool.parameters
1303
+ }))
1304
+ }
1305
+ ];
1306
+ }
1307
+ if (inferenceRequest.structuredOutput) {
1308
+ config.responseMimeType = "application/json";
1309
+ config.responseSchema = inferenceRequest.structuredOutput.schema;
1310
+ }
1311
+ if (inferenceRequest.reasoningEffort) {
1312
+ config.thinkingConfig = {
1313
+ thinkingLevel: inferenceRequest.reasoningEffort,
1314
+ includeThoughts: true
1315
+ };
1316
+ }
1317
+ const request = {
1318
+ model: inferenceRequest.model,
1319
+ contents,
1320
+ config
1321
+ };
1322
+ if (inferenceRequest.streaming) {
1323
+ request.stream = inferenceRequest.streaming;
1324
+ }
1325
+ return request;
1326
+ }
1327
+ mapContextItems(inferenceRequest) {
1328
+ var _a;
1329
+ const context = inferenceRequest.context;
1330
+ const contents = [];
1331
+ const system = [];
1332
+ const callNames = /* @__PURE__ */ new Map();
1333
+ for (const item of context.items) {
1334
+ if (item.type === "developer_message" || item.type === "system_message") {
1335
+ system.push(item.text);
1336
+ continue;
1337
+ }
1338
+ if (item.type === "user_message") {
1339
+ this.addPart(contents, "user", { text: item.text });
1340
+ continue;
1341
+ }
1342
+ if (item.type === "model_message") {
1343
+ this.addPart(contents, "model", { text: item.text });
1344
+ continue;
1345
+ }
1346
+ if (item.type === "tool_use_request") {
1347
+ const toolUseRequest = item;
1348
+ callNames.set(toolUseRequest.requestId, toolUseRequest.toolName);
1349
+ let args;
1350
+ try {
1351
+ args = JSON.parse(toolUseRequest.toolArguments);
1352
+ } catch (e) {
1353
+ args = {};
1354
+ }
1355
+ this.addPart(contents, "model", {
1356
+ functionCall: { id: toolUseRequest.requestId, name: toolUseRequest.toolName, args }
1357
+ });
1358
+ continue;
1359
+ }
1360
+ if (item.type === "tool_use_result") {
1361
+ const toolUseResult = item;
1362
+ this.addPart(contents, "user", {
1363
+ functionResponse: {
1364
+ id: toolUseResult.requestId,
1365
+ name: (_a = callNames.get(toolUseResult.requestId)) != null ? _a : "",
1366
+ response: this.parseResponse(toolUseResult.result.text)
1367
+ }
1368
+ });
1369
+ }
1370
+ }
1371
+ return {
1372
+ contents,
1373
+ systemInstruction: system.length > 0 ? system.join("\n\n") : void 0
1374
+ };
1375
+ }
1376
+ addPart(contents, role, part) {
1377
+ const last = contents[contents.length - 1];
1378
+ if ((last == null ? void 0 : last.role) === role) {
1379
+ last.parts.push(part);
1380
+ return;
1381
+ }
1382
+ contents.push({ role, parts: [part] });
1383
+ }
1384
+ parseResponse(output) {
1385
+ try {
1386
+ const parsed = JSON.parse(output);
1387
+ return parsed && typeof parsed === "object" ? parsed : { output };
1388
+ } catch (e) {
1389
+ return { output };
1390
+ }
1391
+ }
1392
+ extractTokenUsage(response) {
1393
+ var _a, _b, _c, _d, _e;
1394
+ const usage = response.usageMetadata;
1395
+ if (!usage) {
1396
+ return void 0;
1397
+ }
1398
+ return new TokenUsage(
1399
+ (_a = usage.promptTokenCount) != null ? _a : 0,
1400
+ (_b = usage.candidatesTokenCount) != null ? _b : 0,
1401
+ (_c = usage.totalTokenCount) != null ? _c : 0,
1402
+ new InputTokenDetails((_d = usage.cachedContentTokenCount) != null ? _d : 0),
1403
+ new OutputTokenDetails((_e = usage.thoughtsTokenCount) != null ? _e : 0)
1404
+ );
1405
+ }
1406
+ toResponse(response) {
1407
+ var _a, _b, _c, _d, _e, _f;
1408
+ const items = [];
1409
+ const parts = (_d = (_c = (_b = (_a = response.candidates) == null ? void 0 : _a[0]) == null ? void 0 : _b.content) == null ? void 0 : _c.parts) != null ? _d : [];
1410
+ for (const part of parts) {
1411
+ if (part.thought && part.text) {
1412
+ items.push({
1413
+ type: "reasoning",
1414
+ content: { type: "input_text", text: part.text },
1415
+ encryptedContent: void 0,
1416
+ summary: []
1417
+ });
1418
+ continue;
1419
+ }
1420
+ if (part.text) {
1421
+ items.push({
1422
+ type: "model_message",
1423
+ text: part.text
1424
+ });
1425
+ continue;
1426
+ }
1427
+ if (part.functionCall) {
1428
+ items.push({
1429
+ type: "tool_use_request",
1430
+ requestId: (_e = part.functionCall.id) != null ? _e : "",
1431
+ toolName: part.functionCall.name,
1432
+ toolArguments: JSON.stringify((_f = part.functionCall.args) != null ? _f : {})
1433
+ });
1434
+ }
1435
+ }
1436
+ return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1437
+ }
1438
+ };
1439
+
1440
+ // src/infrastructure/providers/gemini/gemini-generate-content.ts
1441
+ var GeminiGenerateContent = class {
1442
+ constructor(endpointMapper = new GeminiGenerateContentMapper(), config = {}) {
1443
+ this.endpointMapper = endpointMapper;
1444
+ this.clientConfig = config;
1445
+ }
1446
+ get client() {
1447
+ var _a, _b;
1448
+ return (_b = this._client) != null ? _b : this._client = new import_genai.GoogleGenAI({
1449
+ apiKey: (_a = this.clientConfig.apiKey) != null ? _a : process.env.GEMINI_API_KEY,
1450
+ ...this.clientConfig.baseURL ? { httpOptions: { baseUrl: this.clientConfig.baseURL } } : {}
1451
+ });
1452
+ }
1453
+ async infer(inferenceRequest) {
1454
+ const request = this.endpointMapper.toRequest(inferenceRequest);
1455
+ const response = await this.client.models.generateContent(request);
1456
+ return this.endpointMapper.toResponse(response);
1457
+ }
1458
+ async *stream(inferenceRequest) {
1459
+ const request = this.endpointMapper.toRequest(inferenceRequest);
1460
+ const stream = await this.client.models.generateContentStream(request);
1461
+ let lastEvent = void 0;
1462
+ for await (const chunk of stream) {
1463
+ lastEvent = chunk;
1464
+ yield chunk;
1465
+ }
1466
+ if (!lastEvent) {
1467
+ throw new Error("Last event not found");
1468
+ }
1469
+ const output = this.endpointMapper.toResponse(lastEvent);
1470
+ yield {
1471
+ type: "inference.output",
1472
+ producerId: request.model,
1473
+ occurredAt: /* @__PURE__ */ new Date(),
1474
+ payload: output
1475
+ };
1476
+ }
1477
+ };
1478
+
1479
+ // src/infrastructure/providers/openai/openai-chat-completions-mapper.ts
1480
+ var OpenAIChatCompletionsMapper = class {
1481
+ toRequest(inferenceRequest) {
1482
+ const request = {
1483
+ model: inferenceRequest.model,
1484
+ messages: this.mapContextItems(inferenceRequest)
1485
+ };
1486
+ if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1487
+ request.tools = inferenceRequest.tools.map((tool) => ({
1488
+ type: "function",
1489
+ function: {
1490
+ name: tool.name,
1491
+ description: tool.description,
1492
+ parameters: tool.parameters
1493
+ }
1494
+ }));
1495
+ }
1496
+ if (inferenceRequest.reasoningEffort) {
1497
+ request.reasoning_effort = inferenceRequest.reasoningEffort;
1498
+ }
1499
+ if (inferenceRequest.streaming) {
1500
+ request.stream = inferenceRequest.streaming;
1501
+ }
1502
+ return request;
1503
+ }
1504
+ mapContextItems(inferenceRequest) {
1505
+ var _a;
1506
+ const messages = [];
1507
+ for (const item of inferenceRequest.context.items) {
1508
+ if (item.type === "developer_message" || item.type === "system_message") {
1509
+ messages.push({ role: "system", content: item.text });
1510
+ continue;
1511
+ }
1512
+ if (item.type === "user_message") {
1513
+ messages.push({ role: "user", content: item.text });
1514
+ continue;
1515
+ }
1516
+ if (item.type === "model_message") {
1517
+ messages.push({ role: "assistant", content: item.text });
1518
+ continue;
1519
+ }
1520
+ if (item.type === "tool_use_request") {
1521
+ const toolUseRequest = item;
1522
+ const toolCall = {
1523
+ id: toolUseRequest.requestId,
1524
+ type: "function",
1525
+ function: { name: toolUseRequest.toolName, arguments: toolUseRequest.toolArguments }
1526
+ };
1527
+ const last = messages[messages.length - 1];
1528
+ if ((last == null ? void 0 : last.role) === "assistant") {
1529
+ last.tool_calls = (_a = last.tool_calls) != null ? _a : [];
1530
+ last.tool_calls.push(toolCall);
1531
+ } else {
1532
+ messages.push({ role: "assistant", content: null, tool_calls: [toolCall] });
1533
+ }
1534
+ continue;
1535
+ }
1536
+ if (item.type === "tool_use_result") {
1537
+ const toolUseResult = item;
1538
+ messages.push({
1539
+ role: "tool",
1540
+ tool_call_id: toolUseResult.requestId,
1541
+ content: toolUseResult.result.text
1542
+ });
1543
+ }
1544
+ }
1545
+ return messages;
1546
+ }
1547
+ extractTokenUsage(response) {
1548
+ var _a, _b, _c, _d;
1549
+ if (!response.usage) {
1550
+ return void 0;
1551
+ }
1552
+ return new TokenUsage(
1553
+ response.usage.prompt_tokens,
1554
+ response.usage.completion_tokens,
1555
+ response.usage.total_tokens,
1556
+ new InputTokenDetails((_b = (_a = response.usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0),
1557
+ new OutputTokenDetails((_d = (_c = response.usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0)
1558
+ );
1559
+ }
1560
+ toResponse(response) {
1561
+ var _a, _b, _c;
1562
+ const items = [];
1563
+ const message = (_b = (_a = response.choices) == null ? void 0 : _a[0]) == null ? void 0 : _b.message;
1564
+ if (!message) {
1565
+ return { items: [], tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1566
+ }
1567
+ if (message.reasoning_content) {
1568
+ items.push({
1569
+ type: "reasoning",
1570
+ content: { type: "input_text", text: message.reasoning_content },
1571
+ encryptedContent: void 0,
1572
+ summary: []
1573
+ });
1574
+ }
1575
+ if (message.content) {
1576
+ items.push({
1577
+ type: "model_message",
1578
+ text: message.content
1579
+ });
1580
+ }
1581
+ for (const toolCall of (_c = message.tool_calls) != null ? _c : []) {
1582
+ items.push({
1583
+ type: "tool_use_request",
1584
+ requestId: toolCall.id,
1585
+ toolName: toolCall.function.name,
1586
+ toolArguments: toolCall.function.arguments
1587
+ });
1588
+ }
1589
+ return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1590
+ }
1591
+ };
1592
+
1593
+ // src/infrastructure/providers/openai/openai-chat-completions.ts
1594
+ var import_openai2 = __toESM(require("openai"));
1595
+ var OpenAIChatCompletions = class {
1596
+ constructor(endpointMapper = new OpenAIChatCompletionsMapper(), config = {}) {
1597
+ var _a;
1598
+ this.endpointMapper = endpointMapper;
1599
+ this.clientConfig = config;
1600
+ this.extraBody = (_a = config.extraBody) != null ? _a : {};
1601
+ }
1602
+ get client() {
1603
+ var _a;
1604
+ return (_a = this._client) != null ? _a : this._client = new import_openai2.default({
1605
+ baseURL: this.clientConfig.baseURL,
1606
+ apiKey: this.clientConfig.apiKey
1607
+ });
1608
+ }
1609
+ buildRequest(inferenceRequest) {
1610
+ return {
1611
+ ...this.extraBody,
1612
+ ...this.endpointMapper.toRequest(inferenceRequest)
1613
+ };
1614
+ }
1615
+ async infer(inferenceRequest) {
1616
+ const response = await this.client.chat.completions.create(this.buildRequest(inferenceRequest));
1617
+ return this.endpointMapper.toResponse(response);
1618
+ }
1619
+ async *stream(inferenceRequest) {
1620
+ const stream = this.client.chat.completions.stream(this.buildRequest(inferenceRequest));
1621
+ for await (const chunk of stream) {
1622
+ yield chunk;
1623
+ }
1624
+ const output = this.endpointMapper.toResponse(await stream.finalChatCompletion());
1625
+ yield {
1626
+ type: "inference.output",
1627
+ payload: output,
1628
+ occurredAt: /* @__PURE__ */ new Date(),
1629
+ producerId: inferenceRequest.model
1630
+ };
1631
+ }
1632
+ };
1633
+
1634
+ // src/infrastructure/providers/anthropic/models/claude-4-6-sonnet.ts
1635
+ var claudeSonnet46Specification = {
1636
+ name: "claude-sonnet-4-6",
1637
+ provider: "anthropic",
1638
+ supportsReasoningEffort: true,
1639
+ supportedReasoningEfforts: ["max", "high", "medium", "low"],
1640
+ supportedContextItemTypes: [
1641
+ "user_message",
1642
+ "system_message",
1643
+ "developer_message",
1644
+ "reasoning",
1645
+ "tool_use_request",
1646
+ "tool_use_result",
1647
+ "model_message"
1648
+ ],
1649
+ supportsStreaming: true,
1650
+ contextWindowSize: 2e5,
1651
+ maxOutputTokens: 64e3,
1652
+ supportsFunctionCalling: true,
1653
+ supportsStructuredOutput: true
1654
+ };
1655
+
1656
+ // src/infrastructure/providers/anthropic/models/claude-4-8-opus.ts
1657
+ var claudeOpus48Specification = {
1658
+ name: "claude-opus-4-8",
1659
+ provider: "anthropic",
1660
+ supportsReasoningEffort: true,
1661
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1662
+ supportedContextItemTypes: [
1663
+ "user_message",
1664
+ "system_message",
1665
+ "developer_message",
1666
+ "reasoning",
1667
+ "tool_use_request",
1668
+ "tool_use_result",
1669
+ "model_message"
1670
+ ],
1671
+ supportsStreaming: true,
1672
+ contextWindowSize: 2e5,
1673
+ maxOutputTokens: 32e3,
1674
+ supportsFunctionCalling: true,
1675
+ supportsStructuredOutput: true
1676
+ };
1677
+
1678
+ // src/infrastructure/providers/anthropic/models/claude-4-7-opus.ts
1679
+ var claudeOpus47Specification = {
1680
+ name: "claude-opus-4-7",
1681
+ provider: "anthropic",
1682
+ supportsReasoningEffort: true,
1683
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1684
+ supportedContextItemTypes: [
1685
+ "user_message",
1686
+ "system_message",
1687
+ "developer_message",
1688
+ "reasoning",
1689
+ "tool_use_request",
1690
+ "tool_use_result",
1691
+ "model_message"
1692
+ ],
1693
+ supportsStreaming: true,
1694
+ contextWindowSize: 2e5,
1695
+ maxOutputTokens: 32e3,
1696
+ supportsFunctionCalling: true,
1697
+ supportsStructuredOutput: true
1698
+ };
1699
+
1700
+ // src/infrastructure/providers/gemini/models/gemini-3-5-flash.ts
1701
+ var gemini35FlashSpecification = {
1702
+ name: "gemini-3.5-flash",
1703
+ provider: "google",
1704
+ supportsReasoningEffort: true,
1705
+ supportedReasoningEfforts: ["high", "medium", "low", "minimal", "none"],
1706
+ supportedContextItemTypes: [
1707
+ "user_message",
1708
+ "system_message",
1709
+ "developer_message",
1710
+ "reasoning",
1711
+ "tool_use_request",
1712
+ "tool_use_result",
1713
+ "model_message"
1714
+ ],
1715
+ supportsStreaming: true,
1716
+ contextWindowSize: 1048576,
1717
+ maxOutputTokens: 64e3,
1718
+ supportsFunctionCalling: true,
1719
+ supportsStructuredOutput: true
1720
+ };
1721
+
1722
+ // src/infrastructure/providers/gemini/models/gemini-3-1-pro.ts
1723
+ var gemini31ProSpecification = {
1724
+ name: "gemini-3.1-pro-preview",
1725
+ provider: "google",
1726
+ supportsReasoningEffort: true,
1727
+ supportedReasoningEfforts: ["high", "medium", "low", "minimal", "none"],
1728
+ supportedContextItemTypes: [
1729
+ "user_message",
1730
+ "system_message",
1731
+ "developer_message",
1732
+ "reasoning",
1733
+ "tool_use_request",
1734
+ "tool_use_result",
1735
+ "model_message"
1736
+ ],
1737
+ supportsStreaming: true,
1738
+ contextWindowSize: 1048576,
1739
+ maxOutputTokens: 64e3,
1740
+ supportsFunctionCalling: true,
1741
+ supportsStructuredOutput: true
1742
+ };
1743
+
1744
+ // src/infrastructure/providers/deepseek/models/deepseek-v4-flash.ts
1745
+ var deepSeekV4FlashSpecification = {
1746
+ name: "deepseek-v4-flash",
1747
+ provider: "deepseek",
1748
+ supportsReasoningEffort: true,
1749
+ supportedReasoningEfforts: ["max", "high", "medium", "low", "none"],
1750
+ supportedContextItemTypes: [
1751
+ "user_message",
1752
+ "system_message",
1753
+ "developer_message",
1754
+ "reasoning",
1755
+ "tool_use_request",
1756
+ "tool_use_result",
1757
+ "model_message"
1758
+ ],
1759
+ supportsStreaming: true,
1760
+ contextWindowSize: 1e6,
1761
+ maxOutputTokens: 384e3,
1762
+ supportsFunctionCalling: true,
1763
+ supportsStructuredOutput: false
1764
+ };
1765
+
1766
+ // src/infrastructure/providers/deepseek/models/deepseek-v4-pro.ts
1767
+ var deepSeekV4ProSpecification = {
1768
+ name: "deepseek-v4-pro",
1769
+ provider: "deepseek",
1770
+ supportsReasoningEffort: true,
1771
+ supportedReasoningEfforts: ["max", "high", "medium", "low", "none"],
1772
+ supportedContextItemTypes: [
1773
+ "user_message",
1774
+ "system_message",
1775
+ "developer_message",
1776
+ "reasoning",
1777
+ "tool_use_request",
1778
+ "tool_use_result",
1779
+ "model_message"
1780
+ ],
1781
+ supportsStreaming: true,
1782
+ contextWindowSize: 1e6,
1783
+ maxOutputTokens: 384e3,
1784
+ supportsFunctionCalling: true,
1785
+ supportsStructuredOutput: false
1786
+ };
1787
+
1788
+ // src/infrastructure/providers/openai/models/gpt-5-4.ts
1789
+ var gpt54Specification = {
1790
+ name: "gpt-5.4",
1791
+ provider: "openai",
1792
+ supportsReasoningEffort: true,
1793
+ supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1794
+ supportedContextItemTypes: [
1795
+ "user_message",
1796
+ "system_message",
1797
+ "developer_message",
1798
+ "reasoning",
1799
+ "tool_use_request",
1800
+ "tool_use_result",
1801
+ "model_message"
1802
+ ],
1803
+ supportsStreaming: true,
1804
+ contextWindowSize: 105e4,
1805
+ maxOutputTokens: 128e3,
1806
+ supportsFunctionCalling: true,
1807
+ supportsStructuredOutput: true
1808
+ };
1809
+
1810
+ // src/infrastructure/providers/openai/models/gpt-5-4-mini.ts
1811
+ var gpt54MiniSpecification = {
1812
+ name: "gpt-5.4-mini",
1813
+ provider: "openai",
1814
+ supportsReasoningEffort: true,
1815
+ supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1816
+ supportedContextItemTypes: [
1817
+ "user_message",
1818
+ "system_message",
1819
+ "developer_message",
1820
+ "reasoning",
1821
+ "tool_use_request",
1822
+ "tool_use_result",
1823
+ "model_message"
1824
+ ],
1825
+ supportsStreaming: true,
1826
+ contextWindowSize: 4e5,
1827
+ maxOutputTokens: 128e3,
1828
+ supportsFunctionCalling: true,
1829
+ supportsStructuredOutput: true
1830
+ };
1831
+
1832
+ // src/infrastructure/providers/openai/models/gpt-5-4-nano.ts
1833
+ var gpt54NanoSpecification = {
1834
+ name: "gpt-5.4-nano",
1835
+ provider: "openai",
1836
+ supportsReasoningEffort: true,
1837
+ supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1838
+ supportedContextItemTypes: [
1839
+ "user_message",
1840
+ "system_message",
1841
+ "developer_message",
1842
+ "reasoning",
1843
+ "tool_use_request",
1844
+ "tool_use_result",
1845
+ "model_message"
1846
+ ],
1847
+ supportsStreaming: true,
1848
+ contextWindowSize: 4e5,
1849
+ maxOutputTokens: 128e3,
1850
+ supportsFunctionCalling: true,
1851
+ supportsStructuredOutput: true
1852
+ };
1853
+
1854
+ // src/infrastructure/providers/openai/models/gpt-5-5.ts
1855
+ var gpt55Specification = {
1856
+ name: "gpt-5.5",
1857
+ provider: "openai",
1858
+ supportsReasoningEffort: true,
1859
+ supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1860
+ supportedContextItemTypes: [
1861
+ "user_message",
1862
+ "system_message",
1863
+ "developer_message",
1864
+ "reasoning",
1865
+ "tool_use_request",
1866
+ "tool_use_result",
1867
+ "model_message"
1868
+ ],
1869
+ supportsStreaming: true,
1870
+ contextWindowSize: 105e4,
1871
+ maxOutputTokens: 128e3,
1872
+ supportsFunctionCalling: true,
1873
+ supportsStructuredOutput: true
1874
+ };
1875
+
1876
+ // src/infrastructure/providers/anthropic/models/claude-4-5-haiku.ts
1877
+ var claudeHaiku45Specification = {
1878
+ name: "claude-haiku-4-5",
1879
+ provider: "anthropic",
1880
+ supportsReasoningEffort: true,
1881
+ supportedReasoningEfforts: ["high", "medium", "low", "none"],
1882
+ supportedContextItemTypes: [
1883
+ "user_message",
1884
+ "system_message",
1885
+ "developer_message",
1886
+ "reasoning",
1887
+ "tool_use_request",
1888
+ "tool_use_result",
1889
+ "model_message"
1890
+ ],
1891
+ supportsStreaming: true,
1892
+ contextWindowSize: 2e5,
1893
+ maxOutputTokens: 64e3,
1894
+ supportsFunctionCalling: true,
1895
+ supportsStructuredOutput: true
1896
+ };
1897
+
1898
+ // src/infrastructure/providers/openai/models/gpt-6-luna.ts
1899
+ var gpt6LunaSpecification = {
1900
+ name: "gpt-6-luna",
1901
+ provider: "openai",
1902
+ supportsReasoningEffort: true,
1903
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
1904
+ supportedContextItemTypes: [
1905
+ "user_message",
1906
+ "system_message",
1907
+ "developer_message",
1908
+ "reasoning",
1909
+ "function_call",
1910
+ "function_call_output",
1911
+ "model_message"
1912
+ ],
1913
+ supportsStreaming: true,
1914
+ contextWindowSize: 105e4,
1915
+ maxOutputTokens: 128e3,
1916
+ supportsFunctionCalling: true,
1917
+ supportsStructuredOutput: true
1918
+ };
1919
+
1920
+ // src/infrastructure/providers/openai/models/gpt-6-sol.ts
1921
+ var gpt6SolSpecification = {
1922
+ name: "gpt-6-sol",
1923
+ provider: "openai",
1924
+ supportsReasoningEffort: true,
1925
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
1926
+ supportedContextItemTypes: [
1927
+ "user_message",
1928
+ "system_message",
1929
+ "developer_message",
1930
+ "reasoning",
1931
+ "function_call",
1932
+ "function_call_output",
1933
+ "model_message"
1934
+ ],
1935
+ supportsStreaming: true,
1936
+ contextWindowSize: 105e4,
1937
+ maxOutputTokens: 128e3,
1938
+ supportsFunctionCalling: true,
1939
+ supportsStructuredOutput: true
1940
+ };
1941
+
1942
+ // src/infrastructure/providers/openai/models/gpt-6-1-sol.ts
1943
+ var gpt61SolSpecification = {
1944
+ name: "gpt-6.1-sol",
1945
+ provider: "openai",
1946
+ supportsReasoningEffort: true,
1947
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1948
+ supportedContextItemTypes: [
1949
+ "user_message",
1950
+ "system_message",
1951
+ "developer_message",
1952
+ "reasoning",
1953
+ "function_call",
1954
+ "function_call_output",
1955
+ "model_message"
1956
+ ],
1957
+ supportsStreaming: true,
1958
+ contextWindowSize: 105e4,
1959
+ maxOutputTokens: 128e3,
1960
+ supportsFunctionCalling: true,
1961
+ supportsStructuredOutput: true
1962
+ };
1963
+
1964
+ // src/infrastructure/providers/openai/models/gpt-6-astra.ts
1965
+ var gpt6AstraSpecification = {
1966
+ name: "gpt-6-astra",
1967
+ provider: "openai",
1968
+ supportsReasoningEffort: true,
1969
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1970
+ supportedContextItemTypes: [
1971
+ "user_message",
1972
+ "system_message",
1973
+ "developer_message",
1974
+ "reasoning",
1975
+ "function_call",
1976
+ "function_call_output",
1977
+ "model_message"
1978
+ ],
1979
+ supportsStreaming: true,
1980
+ contextWindowSize: 105e4,
1981
+ maxOutputTokens: 128e3,
1982
+ supportsFunctionCalling: true,
1983
+ supportsStructuredOutput: true
1984
+ };
1985
+
1986
+ // src/infrastructure/providers/anthropic/models/claude-5-sonnet.ts
1987
+ var claudeSonnet5Specification = {
1988
+ name: "claude-sonnet-5",
1989
+ provider: "anthropic",
1990
+ supportsReasoningEffort: true,
1991
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1992
+ supportedContextItemTypes: [
1993
+ "user_message",
1994
+ "system_message",
1995
+ "developer_message",
1996
+ "reasoning",
1997
+ "function_call",
1998
+ "function_call_output",
1999
+ "model_message"
2000
+ ],
2001
+ supportsStreaming: true,
2002
+ contextWindowSize: 1e6,
2003
+ maxOutputTokens: 128e3,
2004
+ supportsFunctionCalling: true,
2005
+ supportsStructuredOutput: true
2006
+ };
2007
+
2008
+ // src/infrastructure/providers/anthropic/models/claude-5-5-sonnet.ts
2009
+ var claudeSonnet55Specification = {
2010
+ name: "claude-sonnet-5-5",
2011
+ provider: "anthropic",
2012
+ supportsReasoningEffort: true,
2013
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2014
+ supportedContextItemTypes: [
2015
+ "user_message",
2016
+ "system_message",
2017
+ "developer_message",
2018
+ "reasoning",
2019
+ "function_call",
2020
+ "function_call_output",
2021
+ "model_message"
2022
+ ],
2023
+ supportsStreaming: true,
2024
+ contextWindowSize: 1e6,
2025
+ maxOutputTokens: 128e3,
2026
+ supportsFunctionCalling: true,
2027
+ supportsStructuredOutput: true
2028
+ };
2029
+
2030
+ // src/infrastructure/providers/anthropic/models/claude-5-5-opus.ts
2031
+ var claudeOpus55Specification = {
2032
+ name: "claude-opus-5-5",
2033
+ provider: "anthropic",
2034
+ supportsReasoningEffort: true,
2035
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2036
+ supportedContextItemTypes: [
2037
+ "user_message",
2038
+ "system_message",
2039
+ "developer_message",
2040
+ "reasoning",
2041
+ "function_call",
2042
+ "function_call_output",
2043
+ "model_message"
2044
+ ],
2045
+ supportsStreaming: true,
2046
+ contextWindowSize: 1e6,
2047
+ maxOutputTokens: 128e3,
2048
+ supportsFunctionCalling: true,
2049
+ supportsStructuredOutput: true
2050
+ };
2051
+
2052
+ // src/infrastructure/providers/anthropic/models/claude-5-1-fable.ts
2053
+ var claudeFable51Specification = {
2054
+ name: "claude-fable-5-1",
2055
+ provider: "anthropic",
2056
+ supportsReasoningEffort: true,
2057
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2058
+ supportedContextItemTypes: [
2059
+ "user_message",
2060
+ "system_message",
2061
+ "developer_message",
2062
+ "reasoning",
2063
+ "function_call",
2064
+ "function_call_output",
2065
+ "model_message"
2066
+ ],
2067
+ supportsStreaming: true,
2068
+ contextWindowSize: 1e6,
2069
+ maxOutputTokens: 128e3,
2070
+ supportsFunctionCalling: true,
2071
+ supportsStructuredOutput: true
2072
+ };
2073
+
2074
+ // src/infrastructure/providers/gemini/models/gemini-3-5-flash-lite.ts
2075
+ var gemini35FlashLiteSpecification = {
2076
+ name: "gemini-3.5-flash-lite",
2077
+ provider: "google",
2078
+ supportsReasoningEffort: true,
2079
+ supportedReasoningEfforts: ["high", "medium", "low", "minimal"],
2080
+ supportedContextItemTypes: [
2081
+ "user_message",
2082
+ "system_message",
2083
+ "developer_message",
2084
+ "reasoning",
2085
+ "function_call",
2086
+ "function_call_output",
2087
+ "model_message"
2088
+ ],
2089
+ supportsStreaming: true,
2090
+ contextWindowSize: 1048576,
2091
+ maxOutputTokens: 65536,
2092
+ supportsFunctionCalling: true,
2093
+ supportsStructuredOutput: true
2094
+ };
2095
+
2096
+ // src/infrastructure/providers/gemini/models/gemini-3-8-flash.ts
2097
+ var gemini38FlashSpecification = {
2098
+ name: "gemini-3.8-flash",
2099
+ provider: "google",
2100
+ supportsReasoningEffort: true,
2101
+ supportedReasoningEfforts: ["high", "medium", "low"],
2102
+ supportedContextItemTypes: [
2103
+ "user_message",
2104
+ "system_message",
2105
+ "developer_message",
2106
+ "reasoning",
2107
+ "function_call",
2108
+ "function_call_output",
2109
+ "model_message"
2110
+ ],
2111
+ supportsStreaming: true,
2112
+ contextWindowSize: 1048576,
2113
+ maxOutputTokens: 65536,
2114
+ supportsFunctionCalling: true,
2115
+ supportsStructuredOutput: true
2116
+ };
2117
+
2118
+ // src/infrastructure/providers/deepseek/models/deepseek-flash.ts
2119
+ var deepSeekFlashSpecification = {
2120
+ name: "deepseek-flash",
2121
+ provider: "deepseek",
2122
+ supportsReasoningEffort: true,
2123
+ supportedReasoningEfforts: ["max", "high", "medium", "low", "none"],
2124
+ supportedContextItemTypes: [
2125
+ "user_message",
2126
+ "system_message",
2127
+ "developer_message",
2128
+ "reasoning",
2129
+ "function_call",
2130
+ "function_call_output",
2131
+ "model_message"
2132
+ ],
2133
+ supportsStreaming: true,
2134
+ contextWindowSize: 1e6,
2135
+ maxOutputTokens: 384e3,
2136
+ supportsFunctionCalling: true,
2137
+ supportsStructuredOutput: false
2138
+ };
2139
+
2140
+ // src/infrastructure/providers/supported-models.ts
2141
+ var supportedModels = [
2142
+ {
2143
+ endpoint: new OpenAIResponses(),
2144
+ specification: gpt54Specification
2145
+ },
2146
+ {
2147
+ endpoint: new OpenAIResponses(),
2148
+ specification: gpt54MiniSpecification
2149
+ },
2150
+ {
2151
+ endpoint: new OpenAIResponses(),
2152
+ specification: gpt54NanoSpecification
2153
+ },
2154
+ {
2155
+ endpoint: new OpenAIResponses(),
2156
+ specification: gpt55Specification
2157
+ },
2158
+ {
2159
+ endpoint: new OpenAIResponses(),
2160
+ specification: gpt6LunaSpecification
2161
+ },
2162
+ {
2163
+ endpoint: new OpenAIResponses(),
2164
+ specification: gpt6SolSpecification
2165
+ },
2166
+ {
2167
+ endpoint: new OpenAIResponses(),
2168
+ specification: gpt61SolSpecification
2169
+ },
2170
+ {
2171
+ endpoint: new OpenAIResponses(),
2172
+ specification: gpt6AstraSpecification
2173
+ },
2174
+ {
2175
+ endpoint: new AnthropicMessages(),
2176
+ specification: claudeHaiku45Specification
2177
+ },
2178
+ {
2179
+ endpoint: new AnthropicMessages(),
2180
+ specification: claudeSonnet46Specification
2181
+ },
2182
+ {
2183
+ endpoint: new AnthropicMessages(),
2184
+ specification: claudeOpus47Specification
2185
+ },
2186
+ {
2187
+ endpoint: new AnthropicMessages(),
2188
+ specification: claudeOpus48Specification
2189
+ },
2190
+ {
2191
+ endpoint: new AnthropicMessages(),
2192
+ specification: claudeSonnet5Specification
2193
+ },
2194
+ {
2195
+ endpoint: new AnthropicMessages(),
2196
+ specification: claudeSonnet55Specification
2197
+ },
2198
+ {
2199
+ endpoint: new AnthropicMessages(),
2200
+ specification: claudeOpus55Specification
2201
+ },
2202
+ {
2203
+ endpoint: new AnthropicMessages(),
2204
+ specification: claudeFable51Specification
2205
+ },
2206
+ {
2207
+ endpoint: new GeminiGenerateContent(),
2208
+ specification: gemini35FlashSpecification
2209
+ },
2210
+ {
2211
+ endpoint: new GeminiGenerateContent(),
2212
+ specification: gemini31ProSpecification
2213
+ },
2214
+ {
2215
+ endpoint: new GeminiGenerateContent(),
2216
+ specification: gemini35FlashLiteSpecification
2217
+ },
2218
+ {
2219
+ endpoint: new GeminiGenerateContent(),
2220
+ specification: gemini38FlashSpecification
2221
+ },
2222
+ {
2223
+ endpoint: new OpenAIChatCompletions(),
2224
+ specification: deepSeekV4FlashSpecification
2225
+ },
2226
+ {
2227
+ endpoint: new OpenAIChatCompletions(),
2228
+ specification: deepSeekV4ProSpecification
2229
+ },
2230
+ {
2231
+ endpoint: new OpenAIChatCompletions(),
2232
+ specification: deepSeekFlashSpecification
2233
+ }
2234
+ ];
2235
+
2236
+ // src/domain/agent/loop/rule-engine.ts
2237
+ var RuleEngine = class {
2238
+ decide(agent, loop) {
2239
+ const agentLoop = { agent, loop };
2240
+ const satisfiedRules = loop.rules.filter((rule) => rule.condition.isSatisfiedBy(agentLoop));
2241
+ if (satisfiedRules.length === 0) {
2242
+ return void 0;
2243
+ }
2244
+ const highestPriorityRule = satisfiedRules.reduce((highest, current) => {
2245
+ return highest.priority > current.priority ? highest : current;
2246
+ });
2247
+ return highestPriorityRule.action.execute(agentLoop);
2248
+ }
2249
+ };
2250
+
2251
+ // src/application/use-cases/run-loop.ts
2252
+ var RunLoopUseCase = class {
2253
+ constructor(agentRepository, loopRepository, directiveExecutionStrategyResolver) {
2254
+ this.agentRepository = agentRepository;
2255
+ this.loopRepository = loopRepository;
2256
+ this.directiveExecutionStrategyResolver = directiveExecutionStrategyResolver;
2257
+ this.ruleEngine = new RuleEngine();
2258
+ }
2259
+ async execute(loopId) {
2260
+ const loop = await this.loopRepository.findById(loopId);
2261
+ if (!loop) {
2262
+ throw new Error("Loop not found");
2263
+ }
2264
+ const agent = await this.agentRepository.findById(loop.getAgentId());
2265
+ if (!agent) {
2266
+ throw new Error("Agent not found");
2267
+ }
2268
+ while (loop.stateId !== "completed") {
2269
+ const directive = this.ruleEngine.decide(agent, loop);
2270
+ if (!directive) return loop;
2271
+ const strategy = this.directiveExecutionStrategyResolver.resolve(directive);
2272
+ await strategy.execute(directive, agent, loop);
2273
+ }
2274
+ await this.loopRepository.save(loop);
2275
+ return loop;
2276
+ }
2277
+ };
2278
+
2279
+ // src/domain/agent/loop/specification.ts
2280
+ var LoopSpecification = class {
2281
+ and(other) {
2282
+ return new AndLoopSpecification(this, other);
2283
+ }
2284
+ or(other) {
2285
+ return new OrLoopSpecification(this, other);
2286
+ }
2287
+ not() {
2288
+ return new NotLoopSpecification(this);
2289
+ }
2290
+ };
2291
+ var AndLoopSpecification = class extends LoopSpecification {
2292
+ constructor(left, right) {
2293
+ super();
2294
+ this.left = left;
2295
+ this.right = right;
2296
+ }
2297
+ isSatisfiedBy(agentLoop) {
2298
+ return this.left.isSatisfiedBy(agentLoop) && this.right.isSatisfiedBy(agentLoop);
2299
+ }
2300
+ };
2301
+ var OrLoopSpecification = class extends LoopSpecification {
2302
+ constructor(left, right) {
2303
+ super();
2304
+ this.left = left;
2305
+ this.right = right;
2306
+ }
2307
+ isSatisfiedBy(agentLoop) {
2308
+ return this.left.isSatisfiedBy(agentLoop) || this.right.isSatisfiedBy(agentLoop);
2309
+ }
2310
+ };
2311
+ var NotLoopSpecification = class extends LoopSpecification {
2312
+ constructor(rule) {
2313
+ super();
2314
+ this.rule = rule;
2315
+ }
2316
+ isSatisfiedBy(agentLoop) {
2317
+ return !this.rule.isSatisfiedBy(agentLoop);
2318
+ }
2319
+ };
2320
+ var Idle = class extends LoopSpecification {
2321
+ isSatisfiedBy(agentLoop) {
2322
+ return agentLoop.loop.stateId === "idle";
2323
+ }
2324
+ };
2325
+ var AwaitingInference = class extends LoopSpecification {
2326
+ isSatisfiedBy(agentLoop) {
2327
+ return agentLoop.loop.stateId === "awaiting_inference";
2328
+ }
2329
+ };
2330
+ var AwaitingInferenceRequest = class extends LoopSpecification {
2331
+ isSatisfiedBy(agentLoop) {
2332
+ return agentLoop.loop.stateId === "awaiting_inference_request";
2333
+ }
2334
+ };
2335
+ var AwaitingToolOutput = class extends LoopSpecification {
2336
+ isSatisfiedBy(agentLoop) {
2337
+ return agentLoop.loop.stateId === "awaiting_tool_output";
2338
+ }
2339
+ };
2340
+ var Stopped = class extends LoopSpecification {
2341
+ isSatisfiedBy(agentLoop) {
2342
+ return agentLoop.loop.stateId === "stopped";
2343
+ }
2344
+ };
2345
+ var Completed = class extends LoopSpecification {
2346
+ isSatisfiedBy(agentLoop) {
2347
+ return agentLoop.loop.stateId === "completed";
2348
+ }
2349
+ };
2350
+ var ModelAnswered = class extends LoopSpecification {
2351
+ isSatisfiedBy(agentLoop) {
2352
+ const operations = agentLoop.loop.completedOperations;
2353
+ const lastOperation = operations[operations.length - 1];
2354
+ if ((lastOperation == null ? void 0 : lastOperation.type) !== "inference") {
2355
+ return false;
2356
+ }
2357
+ return lastOperation.result.items.some((item) => item.type === "model_message");
2358
+ }
2359
+ };
2360
+
2361
+ // src/application/use-cases/loop-state.ts
2362
+ var LoopStateUseCase = class {
2363
+ execute(loopStateId) {
2364
+ if (loopStateId === "idle") {
2365
+ return new Idle();
2366
+ }
2367
+ if (loopStateId === "awaiting_inference_request") {
2368
+ return new AwaitingInferenceRequest();
2369
+ }
2370
+ if (loopStateId === "awaiting_inference") {
2371
+ return new AwaitingInference();
2372
+ }
2373
+ if (loopStateId === "awaiting_tool_output") {
2374
+ return new AwaitingToolOutput();
2375
+ }
2376
+ if (loopStateId === "stopped") {
2377
+ return new Stopped();
2378
+ }
2379
+ if (loopStateId === "completed") {
2380
+ return new Completed();
2381
+ }
2382
+ throw new Error(`Invalid loop state: ${loopStateId}`);
2383
+ }
2384
+ };
2385
+
2386
+ // src/domain/agent/loop/action.ts
2387
+ var LoopAction = class {
2388
+ };
2389
+ var InferenceAction = class extends LoopAction {
2390
+ execute(agentLoop) {
2391
+ const request = agentLoop.loop.request;
2392
+ if (!request) {
2393
+ return { type: "wait", reason: "no request" };
2394
+ }
2395
+ return { type: "inference", request };
2396
+ }
2397
+ };
2398
+ var ToolUseAction = class extends LoopAction {
2399
+ execute(agentLoop) {
2400
+ if (!agentLoop.loop.pending) {
2401
+ return { type: "wait" };
2402
+ }
2403
+ const pendingOperation = agentLoop.loop.pending;
2404
+ if (pendingOperation.type === "tool_execution") {
2405
+ return { type: "tool_use", call: pendingOperation.call };
2406
+ }
2407
+ return { type: "wait" };
2408
+ }
2409
+ };
2410
+ var CompleteAction = class extends LoopAction {
2411
+ constructor(reason) {
2412
+ super();
2413
+ this.reason = reason;
2414
+ }
2415
+ execute() {
2416
+ return { type: "complete", reason: this.reason };
2417
+ }
2418
+ };
2419
+ var WaitAction = class extends LoopAction {
2420
+ constructor(reason) {
2421
+ super();
2422
+ this.reason = reason;
2423
+ }
2424
+ execute() {
2425
+ return { type: "wait", reason: this.reason };
2426
+ }
2427
+ };
2428
+
2429
+ // src/domain/agent/loop/rule.ts
2430
+ var LoopRule = class _LoopRule {
2431
+ constructor(id, condition, action, priority) {
2432
+ this._id = id;
2433
+ this._priority = priority;
2434
+ this._condition = condition;
2435
+ this._action = action;
2436
+ }
2437
+ get id() {
2438
+ return this._id;
2439
+ }
2440
+ get priority() {
2441
+ return this._priority;
2442
+ }
2443
+ get condition() {
2444
+ return this._condition;
2445
+ }
2446
+ get action() {
2447
+ return this._action;
2448
+ }
2449
+ static create(spec) {
2450
+ var _a;
2451
+ const priority = (_a = spec.priority) != null ? _a : 0;
2452
+ const id = crypto.randomUUID();
2453
+ return new _LoopRule(id, spec.when, spec.then, priority);
2454
+ }
2455
+ static rehydrate(spec) {
2456
+ var _a;
2457
+ const priority = (_a = spec.priority) != null ? _a : 0;
2458
+ const rule = new _LoopRule(spec.id, spec.condition, spec.action, priority);
2459
+ return rule;
2460
+ }
2461
+ };
2462
+
2463
+ // src/infrastructure/memory/runtime-memory.ts
2464
+ var RuntimeMemory = class {
2465
+ constructor(context) {
2466
+ this.context = context;
2467
+ }
2468
+ getContext() {
2469
+ return this.context;
2470
+ }
2471
+ saveItem(item) {
2472
+ this.context.items.push(item);
2473
+ }
2474
+ saveItems(items) {
2475
+ this.context.items.push(...items);
2476
+ }
2477
+ };
2478
+
2479
+ // src/infrastructure/memory/runtime-memory-factory.ts
2480
+ var RuntimeMemoryFactory = class {
2481
+ create() {
2482
+ const context = {
2483
+ items: []
2484
+ };
2485
+ return new RuntimeMemory(context);
2486
+ }
2487
+ };
2488
+
2489
+ // src/application/directive-execution/directive-execution-strategy-resolver.ts
2490
+ var DirectiveExecutionStrategyResolver = class {
2491
+ constructor(strategies) {
2492
+ this.strategies = strategies;
2493
+ }
2494
+ resolve(directive) {
2495
+ return this.strategies[directive.type];
2496
+ }
2497
+ };
2498
+
2499
+ // src/application/directive-execution/complete-execution-strategy.ts
2500
+ var CompleteExecutionStrategy = class {
2501
+ async execute(directive, agent, loop) {
2502
+ if (directive.type !== "complete") {
2503
+ throw new Error("Expected a completion directive");
2504
+ }
2505
+ loop.complete(directive.reason);
2506
+ }
2507
+ };
2508
+
2509
+ // src/application/directive-execution/inference-execution-strategy.ts
2510
+ var InferenceExecutionStrategy = class {
2511
+ constructor(inferenceRunner) {
2512
+ this.inferenceRunner = inferenceRunner;
2513
+ }
2514
+ async execute(directive, agent, loop) {
2515
+ if (directive.type !== "inference") {
2516
+ throw new Error("Expected an inference directive");
2517
+ }
2518
+ const pending = loop.requestInference(directive.request);
2519
+ const result = await this.inferenceRunner.run(directive.request);
2520
+ loop.receiveInferenceResult(pending.id, result);
2521
+ }
2522
+ };
2523
+
2524
+ // src/application/directive-execution/tool-use-execution-strategy.ts
2525
+ var ToolUseExecutionStrategy = class {
2526
+ constructor(toolRunner) {
2527
+ this.toolRunner = toolRunner;
2528
+ }
2529
+ async execute(directive, agent, loop) {
2530
+ if (directive.type !== "tool_use") {
2531
+ throw new Error("Expected a tool-use directive");
2532
+ }
2533
+ const pending = loop.pending;
2534
+ if ((pending == null ? void 0 : pending.type) !== "tool_execution") {
2535
+ throw new Error("The loop has no pending tool execution");
2536
+ }
2537
+ const tool = agent.getTools().find((tool2) => tool2.name === directive.call.toolName);
2538
+ if (!tool) {
2539
+ throw new Error(`Tool "${directive.call.toolName}" not found`);
2540
+ }
2541
+ const result = await this.toolRunner.run(directive.call, tool);
2542
+ loop.receiveToolUseResult(pending.id, result);
2543
+ }
2544
+ };
2545
+
2546
+ // src/application/directive-execution/wait-execution-strategy.ts
2547
+ var WaitExecutionStrategy = class {
2548
+ async execute(directive, agent, loop) {
2549
+ if (directive.type !== "wait") {
2550
+ throw new Error("Expected a wait directive");
2551
+ }
2552
+ loop.wait(directive.reason);
2553
+ }
2554
+ };
2555
+
2556
+ // src/agent-module.ts
2557
+ function defineAgentModule(config) {
2558
+ var _a, _b, _c, _d, _e, _f, _g;
2559
+ const agentRepository = (_a = config.agentRepository) != null ? _a : new InMemoryAgentRepository();
2560
+ const agentLoopRepository = (_b = config.agentLoopRepository) != null ? _b : new InMemoryLoopRepository();
2561
+ const inferenceRunner = (_f = (_c = config.inferenceRunnerConfig) == null ? void 0 : _c.runner) != null ? _f : new DefaultInferenceRunner(
2562
+ (_e = (_d = config.inferenceRunnerConfig) == null ? void 0 : _d.supportedModels) != null ? _e : supportedModels,
2563
+ new InferenceRequestValidator()
2564
+ );
2565
+ const toolRunner = (_g = config.toolRunner) != null ? _g : new LocalToolRunner();
2566
+ const memoryFactory = new RuntimeMemoryFactory();
2567
+ const createAgentUseCase = new CreateAgentUseCase(agentRepository, memoryFactory);
2568
+ const createLoopUseCase = new CreateAgentLoopUseCase(agentLoopRepository);
2569
+ async function createAgent(config2) {
2570
+ return await createAgentUseCase.execute(config2.name, config2.instruction, config2.tools, config2.handlers);
2571
+ }
2572
+ async function createLoop(params) {
2573
+ const rules = params.rules.map((rule) => LoopRule.create(rule));
2574
+ return await createLoopUseCase.execute(params.subject, params.agentId, rules);
2575
+ }
2576
+ const directiveExecutionStrategyResolver = new DirectiveExecutionStrategyResolver({
2577
+ inference: new InferenceExecutionStrategy(inferenceRunner),
2578
+ tool_use: new ToolUseExecutionStrategy(toolRunner),
2579
+ complete: new CompleteExecutionStrategy(),
2580
+ wait: new WaitExecutionStrategy()
2581
+ });
2582
+ const runLoopUseCase = new RunLoopUseCase(agentRepository, agentLoopRepository, directiveExecutionStrategyResolver);
2583
+ async function runLoop(loopId) {
2584
+ return await runLoopUseCase.execute(loopId);
2585
+ }
2586
+ const getLoopStateUseCase = new LoopStateUseCase();
2587
+ function state(loopStateId) {
2588
+ return getLoopStateUseCase.execute(loopStateId);
2589
+ }
2590
+ function modelAnswered() {
2591
+ return new ModelAnswered();
2592
+ }
2593
+ function runInference() {
2594
+ return new InferenceAction();
2595
+ }
2596
+ function toolUse() {
2597
+ return new ToolUseAction();
2598
+ }
2599
+ function complete(reason) {
2600
+ return new CompleteAction(reason != null ? reason : "completed");
2601
+ }
2602
+ function wait(reason) {
2603
+ return new WaitAction(reason != null ? reason : "waiting");
2604
+ }
2605
+ return {
2606
+ createAgent,
2607
+ createLoop,
2608
+ runLoop,
2609
+ state,
2610
+ modelAnswered,
2611
+ runInference,
2612
+ toolUse,
2613
+ complete,
2614
+ wait
2615
+ };
2616
+ }
397
2617
  // Annotate the CommonJS export names for ESM import in node:
398
2618
  0 && (module.exports = {
2619
+ Agent,
399
2620
  Participant,
400
2621
  SituationSpecification,
401
2622
  SpaceEvent,
2623
+ defineAgentModule,
402
2624
  defineRuntime
403
2625
  });
404
2626
  //# sourceMappingURL=index.js.map