@mozaik-ai/core 4.0.6 → 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,1764 +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 {
725
- constructor() {
726
- this.specification = new MessageReceivedSpecification();
727
- }
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
- };
737
- }
738
- };
739
- var InferenceToFunctionCallRule = class {
88
+ // src/infrastructure/repositories/in-memory-space-repository.ts
89
+ var InMemorySpaceRepository = class {
740
90
  constructor() {
741
- this.specification = new InferenceProducedFunctionCallSpecification();
742
- }
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
- };
91
+ this.spaces = [];
758
92
  }
759
- };
760
- var InferenceToModelMessageRule = class {
761
- constructor() {
762
- this.specification = new InferenceProducedModelMessageSpecification();
93
+ async save(space) {
94
+ this.spaces.push(space);
763
95
  }
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
- };
96
+ async findById(id) {
97
+ return this.spaces.find((space) => space.getId() === id);
781
98
  }
782
- };
783
- var FunctionCallToInferenceRule = class {
784
- constructor() {
785
- this.specification = new FunctionCallCompletedSpecification();
99
+ async findAllByOwnerId(ownerId) {
100
+ return this.spaces.filter((space) => space.getOwnerId() === ownerId);
786
101
  }
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
- };
813
- }
814
- };
815
-
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()) {
1286
- this.endpointMapper = endpointMapper;
1287
- }
1288
- get client() {
1289
- var _a;
1290
- return (_a = this._client) != null ? _a : this._client = new OpenAI();
1291
- }
1292
- async infer(inferenceInput) {
1293
- const request = this.endpointMapper.toRequest(inferenceInput);
1294
- const response = await this.client.responses.create(request);
1295
- return this.endpointMapper.toResponse(response);
1296
- }
1297
- async *stream(inferenceInput) {
1298
- const request = this.endpointMapper.toRequest(inferenceInput);
1299
- const stream = await this.client.responses.create({ ...request, stream: true });
1300
- let completedResponse = void 0;
1301
- for await (const event of stream) {
1302
- if (event.type === "response.completed") {
1303
- completedResponse = event.response;
1304
- }
1305
- yield event;
1306
- }
1307
- if (!completedResponse) {
1308
- throw new Error("Stream ended without a completed response");
1309
- }
1310
- const output = this.endpointMapper.toResponse(completedResponse);
1311
- yield {
1312
- type: "inference.output",
1313
- payload: output,
1314
- occurredAt: /* @__PURE__ */ new Date(),
1315
- producerId: inferenceInput.model
1316
- };
1317
- }
1318
- };
1319
-
1320
- // src/infrastructure/providers/gemini/endpoints/gemini-generate-content.ts
1321
- import { GoogleGenAI } from "@google/genai";
1322
-
1323
- // src/infrastructure/providers/gemini/endpoints/gemini-generate-content-mapper.ts
1324
- var GeminiGenerateContentMapper = class {
1325
- toRequest(inferenceInput) {
1326
- const { contents, systemInstruction } = this.mapContextItems(inferenceInput);
1327
- const config = {};
1328
- if (systemInstruction) {
1329
- config.systemInstruction = systemInstruction;
1330
- }
1331
- if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1332
- config.tools = [
1333
- {
1334
- functionDeclarations: inferenceInput.tools.map((tool) => ({
1335
- name: tool.name,
1336
- description: tool.description,
1337
- parametersJsonSchema: tool.parameters
1338
- }))
1339
- }
1340
- ];
1341
- }
1342
- if (inferenceInput.structuredOutput) {
1343
- config.responseMimeType = "application/json";
1344
- config.responseSchema = inferenceInput.structuredOutput.schema;
1345
- }
1346
- if (inferenceInput.reasoningEffort) {
1347
- config.thinkingConfig = {
1348
- thinkingLevel: inferenceInput.reasoningEffort,
1349
- includeThoughts: true
1350
- };
1351
- }
1352
- const request = {
1353
- model: inferenceInput.model,
1354
- contents,
1355
- config
1356
- };
1357
- if (inferenceInput.streaming) {
1358
- request.stream = inferenceInput.streaming;
1359
- }
1360
- return request;
1361
- }
1362
- mapContextItems(inferenceInput) {
1363
- var _a;
1364
- const context = inferenceInput.context;
1365
- const contents = [];
1366
- const system = [];
1367
- const callNames = /* @__PURE__ */ new Map();
1368
- for (const item of context.getItems()) {
1369
- if (item instanceof DeveloperMessageItem || item instanceof SystemMessageItem) {
1370
- system.push(item.content.text);
1371
- continue;
1372
- }
1373
- if (item instanceof UserMessageItem) {
1374
- this.addPart(contents, "user", { text: item.content.text });
1375
- continue;
1376
- }
1377
- if (item instanceof ModelMessageItem) {
1378
- this.addPart(contents, "model", { text: item.content.text });
1379
- continue;
1380
- }
1381
- if (item instanceof FunctionCallItem) {
1382
- callNames.set(item.callId, item.name);
1383
- let args;
1384
- try {
1385
- args = JSON.parse(item.args);
1386
- } catch (e) {
1387
- args = {};
1388
- }
1389
- this.addPart(contents, "model", { functionCall: { id: item.callId, name: item.name, args } });
1390
- continue;
1391
- }
1392
- if (item instanceof FunctionCallOutputItem) {
1393
- this.addPart(contents, "user", {
1394
- functionResponse: {
1395
- id: item.callId,
1396
- name: (_a = callNames.get(item.callId)) != null ? _a : "",
1397
- response: this.parseResponse(item.output.text)
1398
- }
1399
- });
1400
- }
1401
- }
1402
- return {
1403
- contents,
1404
- systemInstruction: system.length > 0 ? system.join("\n\n") : void 0
1405
- };
1406
- }
1407
- addPart(contents, role, part) {
1408
- const last = contents[contents.length - 1];
1409
- if ((last == null ? void 0 : last.role) === role) {
1410
- last.parts.push(part);
1411
- return;
1412
- }
1413
- contents.push({ role, parts: [part] });
1414
- }
1415
- parseResponse(output) {
1416
- try {
1417
- const parsed = JSON.parse(output);
1418
- return parsed && typeof parsed === "object" ? parsed : { output };
1419
- } catch (e) {
1420
- return { output };
1421
- }
1422
- }
1423
- extractTokenUsage(response) {
1424
- var _a, _b, _c, _d, _e;
1425
- const usage = response.usageMetadata;
1426
- if (!usage) {
1427
- return void 0;
1428
- }
1429
- return new TokenUsage(
1430
- (_a = usage.promptTokenCount) != null ? _a : 0,
1431
- (_b = usage.candidatesTokenCount) != null ? _b : 0,
1432
- (_c = usage.totalTokenCount) != null ? _c : 0,
1433
- new InputTokenDetails((_d = usage.cachedContentTokenCount) != null ? _d : 0),
1434
- new OutputTokenDetails((_e = usage.thoughtsTokenCount) != null ? _e : 0)
1435
- );
1436
- }
1437
- toResponse(response) {
1438
- var _a, _b, _c, _d, _e, _f;
1439
- const items = [];
1440
- 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 : [];
1441
- for (const part of parts) {
1442
- if (part.thought && part.text) {
1443
- items.push(
1444
- ReasoningItem.rehydrate({
1445
- content: InputText.rehydrate({ text: part.text }),
1446
- encryptedContent: void 0,
1447
- summary: []
1448
- })
1449
- );
1450
- continue;
1451
- }
1452
- if (part.text) {
1453
- items.push(ModelMessageItem.rehydrate({ text: part.text }));
1454
- continue;
1455
- }
1456
- if (part.functionCall) {
1457
- items.push(
1458
- FunctionCallItem.rehydrate({
1459
- callId: (_e = part.functionCall.id) != null ? _e : "",
1460
- name: part.functionCall.name,
1461
- args: JSON.stringify((_f = part.functionCall.args) != null ? _f : {})
1462
- })
1463
- );
1464
- }
1465
- }
1466
- return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
102
+ async delete(id) {
103
+ this.spaces = this.spaces.filter((space) => space.getId() !== id);
1467
104
  }
1468
105
  };
1469
106
 
1470
- // src/infrastructure/providers/gemini/endpoints/gemini-generate-content.ts
1471
- var GeminiGenerateContent = class {
1472
- constructor(endpointMapper = new GeminiGenerateContentMapper(), config = {}) {
1473
- this.endpointMapper = endpointMapper;
1474
- this.clientConfig = config;
1475
- }
1476
- get client() {
1477
- var _a, _b;
1478
- return (_b = this._client) != null ? _b : this._client = new GoogleGenAI({
1479
- apiKey: (_a = this.clientConfig.apiKey) != null ? _a : process.env.GEMINI_API_KEY,
1480
- ...this.clientConfig.baseURL ? { httpOptions: { baseUrl: this.clientConfig.baseURL } } : {}
1481
- });
1482
- }
1483
- async infer(inferenceInput) {
1484
- const request = this.endpointMapper.toRequest(inferenceInput);
1485
- const response = await this.client.models.generateContent(request);
1486
- return this.endpointMapper.toResponse(response);
1487
- }
1488
- async *stream(inferenceInput) {
1489
- const request = this.endpointMapper.toRequest(inferenceInput);
1490
- const stream = await this.client.models.generateContentStream(request);
1491
- let lastEvent = void 0;
1492
- for await (const chunk of stream) {
1493
- lastEvent = chunk;
1494
- yield chunk;
1495
- }
1496
- if (!lastEvent) {
1497
- throw new Error("Last event not found");
1498
- }
1499
- const output = this.endpointMapper.toResponse(lastEvent);
1500
- yield {
1501
- type: "inference.output",
1502
- producerId: request.model,
1503
- occurredAt: /* @__PURE__ */ new Date(),
1504
- payload: output
1505
- };
1506
- }
1507
- };
1508
-
1509
- // src/infrastructure/providers/openai/endpoints/openai-chat-completions-mapper.ts
1510
- var OpenAIChatCompletionsMapper = class {
1511
- toRequest(inferenceInput) {
1512
- const request = {
1513
- model: inferenceInput.model,
1514
- messages: this.mapContextItems(inferenceInput)
1515
- };
1516
- if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1517
- request.tools = inferenceInput.tools.map((tool) => ({
1518
- type: "function",
1519
- function: {
1520
- name: tool.name,
1521
- description: tool.description,
1522
- parameters: tool.parameters
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 });
1523
114
  }
1524
- }));
1525
- }
1526
- if (inferenceInput.reasoningEffort) {
1527
- request.reasoning_effort = inferenceInput.reasoningEffort;
1528
- }
1529
- if (inferenceInput.streaming) {
1530
- request.stream = inferenceInput.streaming;
1531
- }
1532
- return request;
1533
- }
1534
- mapContextItems(inferenceInput) {
1535
- var _a;
1536
- const messages = [];
1537
- for (const item of inferenceInput.context.getItems()) {
1538
- if (item instanceof DeveloperMessageItem || item instanceof SystemMessageItem) {
1539
- messages.push({ role: "system", content: item.content.text });
1540
- continue;
1541
- }
1542
- if (item instanceof UserMessageItem) {
1543
- messages.push({ role: "user", content: item.content.text });
1544
- continue;
1545
- }
1546
- if (item instanceof ModelMessageItem) {
1547
- messages.push({ role: "assistant", content: item.content.text });
1548
- continue;
1549
- }
1550
- if (item instanceof FunctionCallItem) {
1551
- const toolCall = {
1552
- id: item.callId,
1553
- type: "function",
1554
- function: { name: item.name, arguments: item.args }
1555
- };
1556
- const last = messages[messages.length - 1];
1557
- if ((last == null ? void 0 : last.role) === "assistant") {
1558
- last.tool_calls = (_a = last.tool_calls) != null ? _a : [];
1559
- last.tool_calls.push(toolCall);
1560
- } else {
1561
- messages.push({ role: "assistant", content: null, tool_calls: [toolCall] });
1562
- }
1563
- continue;
1564
- }
1565
- if (item instanceof FunctionCallOutputItem) {
1566
- messages.push({ role: "tool", tool_call_id: item.callId, content: item.output.text });
1567
- }
1568
- }
1569
- return messages;
1570
- }
1571
- extractTokenUsage(response) {
1572
- var _a, _b, _c, _d;
1573
- if (!response.usage) {
1574
- return void 0;
1575
- }
1576
- return new TokenUsage(
1577
- response.usage.prompt_tokens,
1578
- response.usage.completion_tokens,
1579
- response.usage.total_tokens,
1580
- new InputTokenDetails((_b = (_a = response.usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0),
1581
- new OutputTokenDetails((_d = (_c = response.usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0)
1582
- );
1583
- }
1584
- toResponse(response) {
1585
- var _a, _b, _c;
1586
- const items = [];
1587
- const message = (_b = (_a = response.choices) == null ? void 0 : _a[0]) == null ? void 0 : _b.message;
1588
- if (!message) {
1589
- return { items: [], tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1590
- }
1591
- if (message.reasoning_content) {
1592
- items.push(
1593
- ReasoningItem.rehydrate({
1594
- content: InputText.rehydrate({ text: message.reasoning_content }),
1595
- encryptedContent: void 0,
1596
- summary: []
1597
- })
1598
- );
1599
- }
1600
- if (message.content) {
1601
- items.push(ModelMessageItem.rehydrate({ text: message.content }));
1602
- }
1603
- for (const toolCall of (_c = message.tool_calls) != null ? _c : []) {
1604
- items.push(
1605
- FunctionCallItem.rehydrate({
1606
- callId: toolCall.id,
1607
- name: toolCall.function.name,
1608
- args: toolCall.function.arguments
1609
- })
1610
- );
1611
- }
1612
- return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1613
- }
1614
- };
1615
-
1616
- // src/infrastructure/providers/openai/endpoints/openai-chat-completions.ts
1617
- import OpenAI2 from "openai";
1618
- var OpenAIChatCompletions = class {
1619
- constructor(endpointMapper = new OpenAIChatCompletionsMapper(), config = {}) {
1620
- var _a;
1621
- this.endpointMapper = endpointMapper;
1622
- this.clientConfig = config;
1623
- this.extraBody = (_a = config.extraBody) != null ? _a : {};
1624
- }
1625
- get client() {
1626
- var _a;
1627
- return (_a = this._client) != null ? _a : this._client = new OpenAI2({
1628
- baseURL: this.clientConfig.baseURL,
1629
- apiKey: this.clientConfig.apiKey
1630
- });
1631
- }
1632
- buildRequest(inferenceInput) {
1633
- return {
1634
- ...this.extraBody,
1635
- ...this.endpointMapper.toRequest(inferenceInput)
1636
- };
1637
- }
1638
- async infer(inferenceInput) {
1639
- const response = await this.client.chat.completions.create(this.buildRequest(inferenceInput));
1640
- return this.endpointMapper.toResponse(response);
1641
- }
1642
- async *stream(inferenceInput) {
1643
- const stream = this.client.chat.completions.stream(this.buildRequest(inferenceInput));
1644
- for await (const chunk of stream) {
1645
- yield chunk;
1646
- }
1647
- const output = this.endpointMapper.toResponse(await stream.finalChatCompletion());
1648
- yield {
1649
- type: "inference.output",
1650
- payload: output,
1651
- occurredAt: /* @__PURE__ */ new Date(),
1652
- producerId: inferenceInput.model
1653
- };
1654
- }
1655
- };
1656
-
1657
- // src/infrastructure/providers/anthropic/models/claude-4-6-sonnet.ts
1658
- var claudeSonnet46Specification = {
1659
- name: "claude-sonnet-4-6",
1660
- provider: "anthropic",
1661
- supportsReasoningEffort: true,
1662
- supportedReasoningEfforts: ["max", "high", "medium", "low"],
1663
- supportedContextItemTypes: [
1664
- "user_message",
1665
- "system_message",
1666
- "developer_message",
1667
- "reasoning",
1668
- "function_call",
1669
- "function_call_output",
1670
- "model_message"
1671
- ],
1672
- supportsStreaming: true,
1673
- contextWindowSize: 2e5,
1674
- maxOutputTokens: 64e3,
1675
- supportsFunctionCalling: true,
1676
- supportsStructuredOutput: true
1677
- };
1678
-
1679
- // src/infrastructure/providers/anthropic/models/claude-4-8-opus.ts
1680
- var claudeOpus48Specification = {
1681
- name: "claude-opus-4-8",
1682
- provider: "anthropic",
1683
- supportsReasoningEffort: true,
1684
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1685
- supportedContextItemTypes: [
1686
- "user_message",
1687
- "system_message",
1688
- "developer_message",
1689
- "reasoning",
1690
- "function_call",
1691
- "function_call_output",
1692
- "model_message"
1693
- ],
1694
- supportsStreaming: true,
1695
- contextWindowSize: 2e5,
1696
- maxOutputTokens: 32e3,
1697
- supportsFunctionCalling: true,
1698
- supportsStructuredOutput: true
1699
- };
1700
-
1701
- // src/infrastructure/providers/anthropic/models/claude-4-7-opus.ts
1702
- var claudeOpus47Specification = {
1703
- name: "claude-opus-4-7",
1704
- provider: "anthropic",
1705
- supportsReasoningEffort: true,
1706
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1707
- supportedContextItemTypes: [
1708
- "user_message",
1709
- "system_message",
1710
- "developer_message",
1711
- "reasoning",
1712
- "function_call",
1713
- "function_call_output",
1714
- "model_message"
1715
- ],
1716
- supportsStreaming: true,
1717
- contextWindowSize: 2e5,
1718
- maxOutputTokens: 32e3,
1719
- supportsFunctionCalling: true,
1720
- supportsStructuredOutput: true
1721
- };
1722
-
1723
- // src/infrastructure/providers/gemini/models/gemini-3-5-flash.ts
1724
- var gemini35FlashSpecification = {
1725
- name: "gemini-3.5-flash",
1726
- provider: "google",
1727
- supportsReasoningEffort: true,
1728
- supportedReasoningEfforts: ["high", "medium", "low", "minimal", "none"],
1729
- supportedContextItemTypes: [
1730
- "user_message",
1731
- "system_message",
1732
- "developer_message",
1733
- "reasoning",
1734
- "function_call",
1735
- "function_call_output",
1736
- "model_message"
1737
- ],
1738
- supportsStreaming: true,
1739
- contextWindowSize: 1048576,
1740
- maxOutputTokens: 64e3,
1741
- supportsFunctionCalling: true,
1742
- supportsStructuredOutput: true
1743
- };
1744
-
1745
- // src/infrastructure/providers/gemini/models/gemini-3-1-pro.ts
1746
- var gemini31ProSpecification = {
1747
- name: "gemini-3.1-pro-preview",
1748
- provider: "google",
1749
- supportsReasoningEffort: true,
1750
- supportedReasoningEfforts: ["high", "medium", "low", "minimal", "none"],
1751
- supportedContextItemTypes: [
1752
- "user_message",
1753
- "system_message",
1754
- "developer_message",
1755
- "reasoning",
1756
- "function_call",
1757
- "function_call_output",
1758
- "model_message"
1759
- ],
1760
- supportsStreaming: true,
1761
- contextWindowSize: 1048576,
1762
- maxOutputTokens: 64e3,
1763
- supportsFunctionCalling: true,
1764
- supportsStructuredOutput: true
1765
- };
1766
-
1767
- // src/infrastructure/providers/deepseek/models/deepseek-v4-flash.ts
1768
- var deepSeekV4FlashSpecification = {
1769
- name: "deepseek-v4-flash",
1770
- provider: "deepseek",
1771
- supportsReasoningEffort: true,
1772
- supportedReasoningEfforts: ["max", "high", "medium", "low", "none"],
1773
- supportedContextItemTypes: [
1774
- "user_message",
1775
- "system_message",
1776
- "developer_message",
1777
- "reasoning",
1778
- "function_call",
1779
- "function_call_output",
1780
- "model_message"
1781
- ],
1782
- supportsStreaming: true,
1783
- contextWindowSize: 1e6,
1784
- maxOutputTokens: 384e3,
1785
- supportsFunctionCalling: true,
1786
- supportsStructuredOutput: false
1787
- };
1788
-
1789
- // src/infrastructure/providers/deepseek/models/deepseek-v4-pro.ts
1790
- var deepSeekV4ProSpecification = {
1791
- name: "deepseek-v4-pro",
1792
- provider: "deepseek",
1793
- supportsReasoningEffort: true,
1794
- supportedReasoningEfforts: ["max", "high", "medium", "low", "none"],
1795
- supportedContextItemTypes: [
1796
- "user_message",
1797
- "system_message",
1798
- "developer_message",
1799
- "reasoning",
1800
- "function_call",
1801
- "function_call_output",
1802
- "model_message"
1803
- ],
1804
- supportsStreaming: true,
1805
- contextWindowSize: 1e6,
1806
- maxOutputTokens: 384e3,
1807
- supportsFunctionCalling: true,
1808
- supportsStructuredOutput: false
1809
- };
1810
-
1811
- // src/infrastructure/providers/openai/models/gpt-5-4.ts
1812
- var gpt54Specification = {
1813
- name: "gpt-5.4",
1814
- provider: "openai",
1815
- supportsReasoningEffort: true,
1816
- supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1817
- supportedContextItemTypes: [
1818
- "user_message",
1819
- "system_message",
1820
- "developer_message",
1821
- "reasoning",
1822
- "function_call",
1823
- "function_call_output",
1824
- "model_message"
1825
- ],
1826
- supportsStreaming: true,
1827
- contextWindowSize: 105e4,
1828
- maxOutputTokens: 128e3,
1829
- supportsFunctionCalling: true,
1830
- supportsStructuredOutput: true
1831
- };
1832
-
1833
- // src/infrastructure/providers/openai/models/gpt-5-4-mini.ts
1834
- var gpt54MiniSpecification = {
1835
- name: "gpt-5.4-mini",
1836
- provider: "openai",
1837
- supportsReasoningEffort: true,
1838
- supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1839
- supportedContextItemTypes: [
1840
- "user_message",
1841
- "system_message",
1842
- "developer_message",
1843
- "reasoning",
1844
- "function_call",
1845
- "function_call_output",
1846
- "model_message"
1847
- ],
1848
- supportsStreaming: true,
1849
- contextWindowSize: 4e5,
1850
- maxOutputTokens: 128e3,
1851
- supportsFunctionCalling: true,
1852
- supportsStructuredOutput: true
1853
- };
1854
-
1855
- // src/infrastructure/providers/openai/models/gpt-5-4-nano.ts
1856
- var gpt54NanoSpecification = {
1857
- name: "gpt-5.4-nano",
1858
- provider: "openai",
1859
- supportsReasoningEffort: true,
1860
- supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1861
- supportedContextItemTypes: [
1862
- "user_message",
1863
- "system_message",
1864
- "developer_message",
1865
- "reasoning",
1866
- "function_call",
1867
- "function_call_output",
1868
- "model_message"
1869
- ],
1870
- supportsStreaming: true,
1871
- contextWindowSize: 4e5,
1872
- maxOutputTokens: 128e3,
1873
- supportsFunctionCalling: true,
1874
- supportsStructuredOutput: true
1875
- };
1876
-
1877
- // src/infrastructure/providers/openai/models/gpt-5-5.ts
1878
- var gpt55Specification = {
1879
- name: "gpt-5.5",
1880
- provider: "openai",
1881
- supportsReasoningEffort: true,
1882
- supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1883
- supportedContextItemTypes: [
1884
- "user_message",
1885
- "system_message",
1886
- "developer_message",
1887
- "reasoning",
1888
- "function_call",
1889
- "function_call_output",
1890
- "model_message"
1891
- ],
1892
- supportsStreaming: true,
1893
- contextWindowSize: 105e4,
1894
- maxOutputTokens: 128e3,
1895
- supportsFunctionCalling: true,
1896
- supportsStructuredOutput: true
1897
- };
1898
-
1899
- // src/infrastructure/providers/anthropic/models/claude-4-5-haiku.ts
1900
- var claudeHaiku45Specification = {
1901
- name: "claude-haiku-4-5",
1902
- provider: "anthropic",
1903
- supportsReasoningEffort: true,
1904
- supportedReasoningEfforts: ["high", "medium", "low", "none"],
1905
- supportedContextItemTypes: [
1906
- "user_message",
1907
- "system_message",
1908
- "developer_message",
1909
- "reasoning",
1910
- "function_call",
1911
- "function_call_output",
1912
- "model_message"
1913
- ],
1914
- supportsStreaming: true,
1915
- contextWindowSize: 2e5,
1916
- maxOutputTokens: 64e3,
1917
- supportsFunctionCalling: true,
1918
- supportsStructuredOutput: true
1919
- };
1920
-
1921
- // src/application/services/models.ts
1922
- var supportedModels = [
1923
- {
1924
- endpoint: new OpenAIResponses(),
1925
- specification: gpt54Specification
1926
- },
1927
- {
1928
- endpoint: new OpenAIResponses(),
1929
- specification: gpt54MiniSpecification
1930
- },
1931
- {
1932
- endpoint: new OpenAIResponses(),
1933
- specification: gpt54NanoSpecification
1934
- },
1935
- {
1936
- endpoint: new OpenAIResponses(),
1937
- specification: gpt55Specification
1938
- },
1939
- {
1940
- endpoint: new AnthropicMessages(),
1941
- specification: claudeHaiku45Specification
1942
- },
1943
- {
1944
- endpoint: new AnthropicMessages(),
1945
- specification: claudeSonnet46Specification
1946
- },
1947
- {
1948
- endpoint: new AnthropicMessages(),
1949
- specification: claudeOpus47Specification
1950
- },
1951
- {
1952
- endpoint: new AnthropicMessages(),
1953
- specification: claudeOpus48Specification
1954
- },
1955
- {
1956
- endpoint: new GeminiGenerateContent(),
1957
- specification: gemini35FlashSpecification
1958
- },
1959
- {
1960
- endpoint: new GeminiGenerateContent(),
1961
- specification: gemini31ProSpecification
1962
- },
1963
- {
1964
- endpoint: new OpenAIChatCompletions(),
1965
- specification: deepSeekV4FlashSpecification
1966
- },
1967
- {
1968
- endpoint: new OpenAIChatCompletions(),
1969
- specification: deepSeekV4ProSpecification
1970
- }
1971
- ];
1972
-
1973
- // src/domain/generative-model/request-validation/reasoning-effort.ts
1974
- var ReasoningEffortValidation = class {
1975
- constructor() {
1976
- this.name = "reasoning-effort";
1977
- }
1978
- isValid(inferenceInput, model) {
1979
- if (inferenceInput.reasoningEffort === void 0) {
1980
- return true;
1981
- }
1982
- if (!model.supportsReasoningEffort) {
1983
- return false;
115
+ });
1984
116
  }
1985
- return model.supportedReasoningEfforts.includes(inferenceInput.reasoningEffort);
1986
117
  }
1987
118
  };
1988
119
 
1989
- // src/domain/generative-model/request-validation/tool-calling.ts
1990
- var ToolCallingValidation = class {
1991
- constructor() {
1992
- 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;
1993
125
  }
1994
- isValid(inferenceInput, model) {
1995
- if (inferenceInput.tools === void 0) {
1996
- 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");
1997
130
  }
1998
- return model.supportsFunctionCalling;
1999
- }
2000
- };
2001
-
2002
- // src/domain/generative-model/request-validation/streaming.ts
2003
- var StreamingValidation = class {
2004
- constructor() {
2005
- this.name = "streaming";
2006
- }
2007
- isValid(inferenceInput, model) {
2008
- if (!inferenceInput.streaming) {
2009
- return true;
131
+ const participant = space.getParticipant(participantId);
132
+ if (!participant) {
133
+ throw new Error("Participant not found");
2010
134
  }
2011
- return model.supportsStreaming;
2012
- }
2013
- };
2014
-
2015
- // src/domain/generative-model/request-validation/context.ts
2016
- function getContextItemValidationKey(item) {
2017
- if (item instanceof UserMessageItem) {
2018
- return "user_message";
2019
- }
2020
- if (item instanceof SystemMessageItem) {
2021
- return "system_message";
2022
- }
2023
- if (item instanceof DeveloperMessageItem) {
2024
- return "developer_message";
2025
- }
2026
- if (item instanceof ModelMessageItem) {
2027
- return "model_message";
2028
- }
2029
- return item.getType();
2030
- }
2031
- var ContextValidation = class {
2032
- constructor() {
2033
- this.name = "context";
2034
- }
2035
- isValid(inferenceInput, model) {
2036
- return inferenceInput.context.items.every(
2037
- (item) => model.supportedContextItemTypes.includes(getContextItemValidationKey(item))
2038
- );
2039
- }
2040
- };
2041
-
2042
- // src/domain/generative-model/request-validation/inference-request-validator.ts
2043
- var defaultRequestValidationRules = [
2044
- new ReasoningEffortValidation(),
2045
- new ToolCallingValidation(),
2046
- new StreamingValidation(),
2047
- new StructuredOutputValidation(),
2048
- new ContextValidation()
2049
- ];
2050
- var InferenceInputValidator = class {
2051
- constructor(rules = defaultRequestValidationRules) {
2052
- this.rules = rules;
2053
- }
2054
- validate(inferenceInput, model) {
2055
- for (const rule of this.rules) {
2056
- if (!rule.isValid(inferenceInput, model)) {
2057
- throw new Error(`Request validation "${rule.name}" failed for model "${model.name}"`);
2058
- }
135
+ const event = space.removeParticipant(participant, occurredAt);
136
+ if (event) {
137
+ this.eventPublisher.publish(event, space.getParticipants());
2059
138
  }
139
+ await this.spaceRepository.save(space);
2060
140
  }
2061
141
  };
2062
142
 
2063
- // src/application/services/inference-runner.ts
2064
- var DefaultInferenceRunner = class {
2065
- constructor(supportedModels2, requestValidator) {
2066
- this.supportedModels = supportedModels2;
2067
- 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;
2068
148
  }
2069
- async run(input) {
2070
- const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
2071
- if (!generativeModel) {
2072
- 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");
2073
153
  }
2074
- this.requestValidator.validate(input, generativeModel.specification);
2075
- return await generativeModel.endpoint.infer(input);
2076
- }
2077
- async *stream(input) {
2078
- const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
2079
- if (!generativeModel) {
2080
- throw new Error(`Unsupported model: ${input.model}`);
154
+ const participant = space.getParticipant(participantId);
155
+ if (!participant) {
156
+ throw new Error("Participant not found");
2081
157
  }
2082
- this.requestValidator.validate(input, generativeModel.specification);
2083
- yield* generativeModel.endpoint.stream(input);
2084
- }
2085
- };
2086
-
2087
- // src/application/services/function-call.ts
2088
- var DefaultFunctionCallRunner = class {
2089
- async run(input, tool) {
2090
- try {
2091
- const result = await tool.invoke(JSON.parse(input.args));
2092
- return FunctionCallOutputItem.create(
2093
- input.callId,
2094
- typeof result === "string" ? result : JSON.stringify(result)
2095
- );
2096
- } catch (error) {
2097
- 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());
2098
161
  }
162
+ await this.spaceRepository.save(space);
2099
163
  }
2100
164
  };
2101
165
 
2102
- // src/application/use-cases/send-event.ts
2103
- function createSendEvent(resolveRuntime) {
2104
- return function sendEvent(event, senderId) {
2105
- const runtime = resolveRuntime();
2106
- const participant = runtime.getParticipant(senderId);
2107
- if (!participant) {
2108
- throw new Error(`Participant ${senderId} not found`);
2109
- }
2110
- runtime.publish(event);
2111
- };
2112
- }
2113
-
2114
166
  // src/define-runtime.ts
2115
167
  function defineRuntime() {
2116
168
  let runtime = null;
2117
- const processor = new EventProcessor();
2118
169
  function initializeRuntime(config) {
2119
- var _a, _b, _c, _d;
2120
170
  if (runtime) {
2121
171
  throw new Error("Runtime already initialized");
2122
172
  }
2123
- const inferenceRunner = (_d = (_a = config.inferenceRunnerConfig) == null ? void 0 : _a.runner) != null ? _d : new DefaultInferenceRunner(
2124
- (_c = (_b = config.inferenceRunnerConfig) == null ? void 0 : _b.supportedModels) != null ? _c : supportedModels,
2125
- new InferenceInputValidator()
2126
- );
2127
- const functionCallRunner = new DefaultFunctionCallRunner();
2128
- runtime = new RuntimeService(config.state, processor, inferenceRunner, functionCallRunner);
173
+ runtime = new RuntimeService(config.state);
2129
174
  return runtime;
2130
175
  }
2131
176
  function resolveRuntime() {
@@ -2134,34 +179,55 @@ function defineRuntime() {
2134
179
  }
2135
180
  return runtime;
2136
181
  }
2137
- function resolveParticipant(id) {
2138
- if (!runtime) {
2139
- throw new Error("Runtime not initialized");
2140
- }
2141
- const participant = runtime.state.getParticipant(id);
2142
- if (!participant) {
2143
- 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
+ };
2144
217
  }
2145
- return participant;
2146
- }
2147
- const join = createJoin(resolveRuntime);
2148
- const leave = createLeave(resolveRuntime);
2149
- const sendMessage = createSendMessage(resolveRuntime);
2150
- const sendEvent = createSendEvent(resolveRuntime);
2151
- const runLoop = createRunLoop(resolveRuntime);
218
+ };
2152
219
  return {
2153
220
  initializeRuntime,
2154
221
  resolveRuntime,
2155
- resolveParticipant,
222
+ createParticipant,
2156
223
  join,
2157
224
  leave,
2158
225
  sendMessage,
2159
- sendEvent,
2160
- runLoop
226
+ sendMessageTool
2161
227
  };
2162
228
  }
2163
229
 
2164
- // src/domain/agentic-environment/situation/situation-specification.ts
230
+ // src/domain/space/situation-specification.ts
2165
231
  var SituationSpecification = class {
2166
232
  and(other) {
2167
233
  return new AndSituationSpecification(this, other);
@@ -2203,34 +269,9 @@ var NotSituationSpecification = class extends SituationSpecification {
2203
269
  }
2204
270
  };
2205
271
  export {
2206
- Agent,
2207
- AnthropicMessages,
2208
- ContextItem,
2209
- DefaultInferenceRunner,
2210
- DeveloperMessageItem,
2211
- FunctionCallItem,
2212
- FunctionCallOutputItem,
2213
- GeminiGenerateContent,
2214
- Human,
2215
- InputTokenDetails,
2216
- McpClient,
2217
- McpToolRegistry,
2218
- ModelContext,
2219
- ModelMessageItem,
2220
- OpenAIChatCompletions,
2221
- OpenAIResponses,
2222
- OutputTokenDetails,
2223
272
  Participant,
2224
- ReasoningItem,
2225
- RuntimeState,
2226
- SemanticEvent,
2227
273
  SituationSpecification,
2228
- SystemMessageItem,
2229
- TokenUsage,
2230
- UserMessageItem,
2231
- createAgent,
2232
- createHuman,
2233
- defineRuntime,
2234
- supportedModels
274
+ SpaceEvent,
275
+ defineRuntime
2235
276
  };
2236
277
  //# sourceMappingURL=index.mjs.map