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