@mozaik-ai/core 4.1.0 → 4.2.0-beta.0

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