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