@mozaik-ai/core 4.2.0-beta.1 → 4.2.0-beta.3

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