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

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