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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,2054 +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 {
117
+ // src/infrastructure/repositories/in-memory-space-repository.ts
118
+ var InMemorySpaceRepository = class {
789
119
  constructor() {
790
- this.specification = new MessageReceivedSpecification();
120
+ this.spaces = [];
791
121
  }
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
- };
122
+ async save(space) {
123
+ this.spaces.push(space);
801
124
  }
802
- };
803
- var InferenceToFunctionCallRule = class {
804
- constructor() {
805
- this.specification = new InferenceProducedFunctionCallSpecification();
125
+ async findById(id) {
126
+ return this.spaces.find((space) => space.getId() === id);
806
127
  }
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
- };
822
- }
823
- };
824
- var InferenceToModelMessageRule = class {
825
- constructor() {
826
- this.specification = new InferenceProducedModelMessageSpecification();
128
+ async findAllByOwnerId(ownerId) {
129
+ return this.spaces.filter((space) => space.getOwnerId() === ownerId);
827
130
  }
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
- };
845
- }
846
- };
847
- var FunctionCallToInferenceRule = class {
848
- constructor() {
849
- this.specification = new FunctionCallCompletedSpecification();
850
- }
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
- };
131
+ async delete(id) {
132
+ this.spaces = this.spaces.filter((space) => space.getId() !== id);
877
133
  }
878
134
  };
879
135
 
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(), config = {}) {
1350
- this.endpointMapper = endpointMapper;
1351
- this.clientConfig = config;
1352
- }
1353
- get client() {
1354
- var _a;
1355
- return (_a = this._client) != null ? _a : this._client = new import_openai.default({
1356
- baseURL: this.clientConfig.baseURL,
1357
- apiKey: this.clientConfig.apiKey
1358
- });
1359
- }
1360
- async infer(inferenceInput) {
1361
- const request = this.endpointMapper.toRequest(inferenceInput);
1362
- const response = await this.client.responses.create(request);
1363
- return this.endpointMapper.toResponse(response);
1364
- }
1365
- async *stream(inferenceInput) {
1366
- const request = this.endpointMapper.toRequest(inferenceInput);
1367
- const stream = await this.client.responses.create({ ...request, stream: true });
1368
- let completedResponse = void 0;
1369
- for await (const event of stream) {
1370
- if (event.type === "response.completed") {
1371
- completedResponse = event.response;
1372
- }
1373
- yield event;
1374
- }
1375
- if (!completedResponse) {
1376
- throw new Error("Stream ended without a completed response");
1377
- }
1378
- const output = this.endpointMapper.toResponse(completedResponse);
1379
- yield {
1380
- type: "inference.output",
1381
- payload: output,
1382
- occurredAt: /* @__PURE__ */ new Date(),
1383
- producerId: inferenceInput.model
1384
- };
1385
- }
1386
- };
1387
-
1388
- // src/infrastructure/providers/gemini/endpoints/gemini-generate-content.ts
1389
- var import_genai = require("@google/genai");
1390
-
1391
- // src/infrastructure/providers/gemini/endpoints/gemini-generate-content-mapper.ts
1392
- var GeminiGenerateContentMapper = class {
1393
- toRequest(inferenceInput) {
1394
- const { contents, systemInstruction } = this.mapContextItems(inferenceInput);
1395
- const config = {};
1396
- if (systemInstruction) {
1397
- config.systemInstruction = systemInstruction;
1398
- }
1399
- if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1400
- config.tools = [
1401
- {
1402
- functionDeclarations: inferenceInput.tools.map((tool) => ({
1403
- name: tool.name,
1404
- description: tool.description,
1405
- parametersJsonSchema: tool.parameters
1406
- }))
1407
- }
1408
- ];
1409
- }
1410
- if (inferenceInput.structuredOutput) {
1411
- config.responseMimeType = "application/json";
1412
- config.responseSchema = inferenceInput.structuredOutput.schema;
1413
- }
1414
- if (inferenceInput.reasoningEffort) {
1415
- config.thinkingConfig = {
1416
- thinkingLevel: inferenceInput.reasoningEffort,
1417
- includeThoughts: true
1418
- };
1419
- }
1420
- const request = {
1421
- model: inferenceInput.model,
1422
- contents,
1423
- config
1424
- };
1425
- if (inferenceInput.streaming) {
1426
- request.stream = inferenceInput.streaming;
1427
- }
1428
- return request;
1429
- }
1430
- mapContextItems(inferenceInput) {
1431
- var _a;
1432
- const context = inferenceInput.context;
1433
- const contents = [];
1434
- const system = [];
1435
- const callNames = /* @__PURE__ */ new Map();
1436
- for (const item of context.getItems()) {
1437
- if (item instanceof DeveloperMessageItem || item instanceof SystemMessageItem) {
1438
- system.push(item.content.text);
1439
- continue;
1440
- }
1441
- if (item instanceof UserMessageItem) {
1442
- this.addPart(contents, "user", { text: item.content.text });
1443
- continue;
1444
- }
1445
- if (item instanceof ModelMessageItem) {
1446
- this.addPart(contents, "model", { text: item.content.text });
1447
- continue;
1448
- }
1449
- if (item instanceof FunctionCallItem) {
1450
- callNames.set(item.callId, item.name);
1451
- let args;
1452
- try {
1453
- args = JSON.parse(item.args);
1454
- } catch (e) {
1455
- args = {};
1456
- }
1457
- this.addPart(contents, "model", { functionCall: { id: item.callId, name: item.name, args } });
1458
- continue;
1459
- }
1460
- if (item instanceof FunctionCallOutputItem) {
1461
- this.addPart(contents, "user", {
1462
- functionResponse: {
1463
- id: item.callId,
1464
- name: (_a = callNames.get(item.callId)) != null ? _a : "",
1465
- response: this.parseResponse(item.output.text)
1466
- }
1467
- });
1468
- }
1469
- }
1470
- return {
1471
- contents,
1472
- systemInstruction: system.length > 0 ? system.join("\n\n") : void 0
1473
- };
1474
- }
1475
- addPart(contents, role, part) {
1476
- const last = contents[contents.length - 1];
1477
- if ((last == null ? void 0 : last.role) === role) {
1478
- last.parts.push(part);
1479
- return;
1480
- }
1481
- contents.push({ role, parts: [part] });
1482
- }
1483
- parseResponse(output) {
1484
- try {
1485
- const parsed = JSON.parse(output);
1486
- return parsed && typeof parsed === "object" ? parsed : { output };
1487
- } catch (e) {
1488
- return { output };
1489
- }
1490
- }
1491
- extractTokenUsage(response) {
1492
- var _a, _b, _c, _d, _e;
1493
- const usage = response.usageMetadata;
1494
- if (!usage) {
1495
- return void 0;
1496
- }
1497
- return new TokenUsage(
1498
- (_a = usage.promptTokenCount) != null ? _a : 0,
1499
- (_b = usage.candidatesTokenCount) != null ? _b : 0,
1500
- (_c = usage.totalTokenCount) != null ? _c : 0,
1501
- new InputTokenDetails((_d = usage.cachedContentTokenCount) != null ? _d : 0),
1502
- new OutputTokenDetails((_e = usage.thoughtsTokenCount) != null ? _e : 0)
1503
- );
1504
- }
1505
- toResponse(response) {
1506
- var _a, _b, _c, _d, _e, _f;
1507
- const items = [];
1508
- 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 : [];
1509
- for (const part of parts) {
1510
- if (part.thought && part.text) {
1511
- items.push(
1512
- ReasoningItem.rehydrate({
1513
- content: InputText.rehydrate({ text: part.text }),
1514
- encryptedContent: void 0,
1515
- summary: []
1516
- })
1517
- );
1518
- continue;
1519
- }
1520
- if (part.text) {
1521
- items.push(ModelMessageItem.rehydrate({ text: part.text }));
1522
- continue;
1523
- }
1524
- if (part.functionCall) {
1525
- items.push(
1526
- FunctionCallItem.rehydrate({
1527
- callId: (_e = part.functionCall.id) != null ? _e : "",
1528
- name: part.functionCall.name,
1529
- args: JSON.stringify((_f = part.functionCall.args) != null ? _f : {})
1530
- })
1531
- );
1532
- }
1533
- }
1534
- return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1535
- }
1536
- };
1537
-
1538
- // src/infrastructure/providers/gemini/endpoints/gemini-generate-content.ts
1539
- var GeminiGenerateContent = class {
1540
- constructor(endpointMapper = new GeminiGenerateContentMapper(), config = {}) {
1541
- this.endpointMapper = endpointMapper;
1542
- this.clientConfig = config;
1543
- }
1544
- get client() {
1545
- var _a, _b;
1546
- return (_b = this._client) != null ? _b : this._client = new import_genai.GoogleGenAI({
1547
- apiKey: (_a = this.clientConfig.apiKey) != null ? _a : process.env.GEMINI_API_KEY,
1548
- ...this.clientConfig.baseURL ? { httpOptions: { baseUrl: this.clientConfig.baseURL } } : {}
1549
- });
1550
- }
1551
- async infer(inferenceInput) {
1552
- const request = this.endpointMapper.toRequest(inferenceInput);
1553
- const response = await this.client.models.generateContent(request);
1554
- return this.endpointMapper.toResponse(response);
1555
- }
1556
- async *stream(inferenceInput) {
1557
- const request = this.endpointMapper.toRequest(inferenceInput);
1558
- const stream = await this.client.models.generateContentStream(request);
1559
- let lastEvent = void 0;
1560
- for await (const chunk of stream) {
1561
- lastEvent = chunk;
1562
- yield chunk;
1563
- }
1564
- if (!lastEvent) {
1565
- throw new Error("Last event not found");
1566
- }
1567
- const output = this.endpointMapper.toResponse(lastEvent);
1568
- yield {
1569
- type: "inference.output",
1570
- producerId: request.model,
1571
- occurredAt: /* @__PURE__ */ new Date(),
1572
- payload: output
1573
- };
1574
- }
1575
- };
1576
-
1577
- // src/infrastructure/providers/openai/endpoints/openai-chat-completions-mapper.ts
1578
- var OpenAIChatCompletionsMapper = class {
1579
- toRequest(inferenceInput) {
1580
- const request = {
1581
- model: inferenceInput.model,
1582
- messages: this.mapContextItems(inferenceInput)
1583
- };
1584
- if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1585
- request.tools = inferenceInput.tools.map((tool) => ({
1586
- type: "function",
1587
- function: {
1588
- name: tool.name,
1589
- description: tool.description,
1590
- parameters: tool.parameters
1591
- }
1592
- }));
1593
- }
1594
- if (inferenceInput.reasoningEffort) {
1595
- request.reasoning_effort = inferenceInput.reasoningEffort;
1596
- }
1597
- if (inferenceInput.streaming) {
1598
- request.stream = inferenceInput.streaming;
1599
- }
1600
- return request;
1601
- }
1602
- mapContextItems(inferenceInput) {
1603
- var _a;
1604
- const messages = [];
1605
- for (const item of inferenceInput.context.getItems()) {
1606
- if (item instanceof DeveloperMessageItem || item instanceof SystemMessageItem) {
1607
- messages.push({ role: "system", content: item.content.text });
1608
- continue;
1609
- }
1610
- if (item instanceof UserMessageItem) {
1611
- messages.push({ role: "user", content: item.content.text });
1612
- continue;
1613
- }
1614
- if (item instanceof ModelMessageItem) {
1615
- messages.push({ role: "assistant", content: item.content.text });
1616
- continue;
1617
- }
1618
- if (item instanceof FunctionCallItem) {
1619
- const toolCall = {
1620
- id: item.callId,
1621
- type: "function",
1622
- function: { name: item.name, arguments: item.args }
1623
- };
1624
- const last = messages[messages.length - 1];
1625
- if ((last == null ? void 0 : last.role) === "assistant") {
1626
- last.tool_calls = (_a = last.tool_calls) != null ? _a : [];
1627
- last.tool_calls.push(toolCall);
1628
- } else {
1629
- messages.push({ role: "assistant", content: null, tool_calls: [toolCall] });
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 });
1630
143
  }
1631
- continue;
1632
- }
1633
- if (item instanceof FunctionCallOutputItem) {
1634
- messages.push({ role: "tool", tool_call_id: item.callId, content: item.output.text });
1635
- }
1636
- }
1637
- return messages;
1638
- }
1639
- extractTokenUsage(response) {
1640
- var _a, _b, _c, _d;
1641
- if (!response.usage) {
1642
- return void 0;
1643
- }
1644
- return new TokenUsage(
1645
- response.usage.prompt_tokens,
1646
- response.usage.completion_tokens,
1647
- response.usage.total_tokens,
1648
- new InputTokenDetails((_b = (_a = response.usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0),
1649
- new OutputTokenDetails((_d = (_c = response.usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0)
1650
- );
1651
- }
1652
- toResponse(response) {
1653
- var _a, _b, _c;
1654
- const items = [];
1655
- const message = (_b = (_a = response.choices) == null ? void 0 : _a[0]) == null ? void 0 : _b.message;
1656
- if (!message) {
1657
- return { items: [], tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1658
- }
1659
- if (message.reasoning_content) {
1660
- items.push(
1661
- ReasoningItem.rehydrate({
1662
- content: InputText.rehydrate({ text: message.reasoning_content }),
1663
- encryptedContent: void 0,
1664
- summary: []
1665
- })
1666
- );
1667
- }
1668
- if (message.content) {
1669
- items.push(ModelMessageItem.rehydrate({ text: message.content }));
1670
- }
1671
- for (const toolCall of (_c = message.tool_calls) != null ? _c : []) {
1672
- items.push(
1673
- FunctionCallItem.rehydrate({
1674
- callId: toolCall.id,
1675
- name: toolCall.function.name,
1676
- args: toolCall.function.arguments
1677
- })
1678
- );
1679
- }
1680
- return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1681
- }
1682
- };
1683
-
1684
- // src/infrastructure/providers/openai/endpoints/openai-chat-completions.ts
1685
- var import_openai2 = __toESM(require("openai"));
1686
- var OpenAIChatCompletions = class {
1687
- constructor(endpointMapper = new OpenAIChatCompletionsMapper(), config = {}) {
1688
- var _a;
1689
- this.endpointMapper = endpointMapper;
1690
- this.clientConfig = config;
1691
- this.extraBody = (_a = config.extraBody) != null ? _a : {};
1692
- }
1693
- get client() {
1694
- var _a;
1695
- return (_a = this._client) != null ? _a : this._client = new import_openai2.default({
1696
- baseURL: this.clientConfig.baseURL,
1697
- apiKey: this.clientConfig.apiKey
1698
- });
1699
- }
1700
- buildRequest(inferenceInput) {
1701
- return {
1702
- ...this.extraBody,
1703
- ...this.endpointMapper.toRequest(inferenceInput)
1704
- };
1705
- }
1706
- async infer(inferenceInput) {
1707
- const response = await this.client.chat.completions.create(this.buildRequest(inferenceInput));
1708
- return this.endpointMapper.toResponse(response);
1709
- }
1710
- async *stream(inferenceInput) {
1711
- const stream = this.client.chat.completions.stream(this.buildRequest(inferenceInput));
1712
- for await (const chunk of stream) {
1713
- yield chunk;
1714
- }
1715
- const output = this.endpointMapper.toResponse(await stream.finalChatCompletion());
1716
- yield {
1717
- type: "inference.output",
1718
- payload: output,
1719
- occurredAt: /* @__PURE__ */ new Date(),
1720
- producerId: inferenceInput.model
1721
- };
1722
- }
1723
- };
1724
-
1725
- // src/infrastructure/providers/anthropic/models/claude-4-6-sonnet.ts
1726
- var claudeSonnet46Specification = {
1727
- name: "claude-sonnet-4-6",
1728
- provider: "anthropic",
1729
- supportsReasoningEffort: true,
1730
- supportedReasoningEfforts: ["max", "high", "medium", "low"],
1731
- supportedContextItemTypes: [
1732
- "user_message",
1733
- "system_message",
1734
- "developer_message",
1735
- "reasoning",
1736
- "function_call",
1737
- "function_call_output",
1738
- "model_message"
1739
- ],
1740
- supportsStreaming: true,
1741
- contextWindowSize: 2e5,
1742
- maxOutputTokens: 64e3,
1743
- supportsFunctionCalling: true,
1744
- supportsStructuredOutput: true
1745
- };
1746
-
1747
- // src/infrastructure/providers/anthropic/models/claude-4-8-opus.ts
1748
- var claudeOpus48Specification = {
1749
- name: "claude-opus-4-8",
1750
- provider: "anthropic",
1751
- supportsReasoningEffort: true,
1752
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1753
- supportedContextItemTypes: [
1754
- "user_message",
1755
- "system_message",
1756
- "developer_message",
1757
- "reasoning",
1758
- "function_call",
1759
- "function_call_output",
1760
- "model_message"
1761
- ],
1762
- supportsStreaming: true,
1763
- contextWindowSize: 2e5,
1764
- maxOutputTokens: 32e3,
1765
- supportsFunctionCalling: true,
1766
- supportsStructuredOutput: true
1767
- };
1768
-
1769
- // src/infrastructure/providers/anthropic/models/claude-4-7-opus.ts
1770
- var claudeOpus47Specification = {
1771
- name: "claude-opus-4-7",
1772
- provider: "anthropic",
1773
- supportsReasoningEffort: true,
1774
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1775
- supportedContextItemTypes: [
1776
- "user_message",
1777
- "system_message",
1778
- "developer_message",
1779
- "reasoning",
1780
- "function_call",
1781
- "function_call_output",
1782
- "model_message"
1783
- ],
1784
- supportsStreaming: true,
1785
- contextWindowSize: 2e5,
1786
- maxOutputTokens: 32e3,
1787
- supportsFunctionCalling: true,
1788
- supportsStructuredOutput: true
1789
- };
1790
-
1791
- // src/infrastructure/providers/gemini/models/gemini-3-5-flash.ts
1792
- var gemini35FlashSpecification = {
1793
- name: "gemini-3.5-flash",
1794
- provider: "google",
1795
- supportsReasoningEffort: true,
1796
- supportedReasoningEfforts: ["high", "medium", "low", "minimal", "none"],
1797
- supportedContextItemTypes: [
1798
- "user_message",
1799
- "system_message",
1800
- "developer_message",
1801
- "reasoning",
1802
- "function_call",
1803
- "function_call_output",
1804
- "model_message"
1805
- ],
1806
- supportsStreaming: true,
1807
- contextWindowSize: 1048576,
1808
- maxOutputTokens: 64e3,
1809
- supportsFunctionCalling: true,
1810
- supportsStructuredOutput: true
1811
- };
1812
-
1813
- // src/infrastructure/providers/gemini/models/gemini-3-1-pro.ts
1814
- var gemini31ProSpecification = {
1815
- name: "gemini-3.1-pro-preview",
1816
- provider: "google",
1817
- supportsReasoningEffort: true,
1818
- supportedReasoningEfforts: ["high", "medium", "low", "minimal", "none"],
1819
- supportedContextItemTypes: [
1820
- "user_message",
1821
- "system_message",
1822
- "developer_message",
1823
- "reasoning",
1824
- "function_call",
1825
- "function_call_output",
1826
- "model_message"
1827
- ],
1828
- supportsStreaming: true,
1829
- contextWindowSize: 1048576,
1830
- maxOutputTokens: 64e3,
1831
- supportsFunctionCalling: true,
1832
- supportsStructuredOutput: true
1833
- };
1834
-
1835
- // src/infrastructure/providers/deepseek/models/deepseek-v4-flash.ts
1836
- var deepSeekV4FlashSpecification = {
1837
- name: "deepseek-v4-flash",
1838
- provider: "deepseek",
1839
- supportsReasoningEffort: true,
1840
- supportedReasoningEfforts: ["max", "high", "medium", "low", "none"],
1841
- supportedContextItemTypes: [
1842
- "user_message",
1843
- "system_message",
1844
- "developer_message",
1845
- "reasoning",
1846
- "function_call",
1847
- "function_call_output",
1848
- "model_message"
1849
- ],
1850
- supportsStreaming: true,
1851
- contextWindowSize: 1e6,
1852
- maxOutputTokens: 384e3,
1853
- supportsFunctionCalling: true,
1854
- supportsStructuredOutput: false
1855
- };
1856
-
1857
- // src/infrastructure/providers/deepseek/models/deepseek-v4-pro.ts
1858
- var deepSeekV4ProSpecification = {
1859
- name: "deepseek-v4-pro",
1860
- provider: "deepseek",
1861
- supportsReasoningEffort: true,
1862
- supportedReasoningEfforts: ["max", "high", "medium", "low", "none"],
1863
- supportedContextItemTypes: [
1864
- "user_message",
1865
- "system_message",
1866
- "developer_message",
1867
- "reasoning",
1868
- "function_call",
1869
- "function_call_output",
1870
- "model_message"
1871
- ],
1872
- supportsStreaming: true,
1873
- contextWindowSize: 1e6,
1874
- maxOutputTokens: 384e3,
1875
- supportsFunctionCalling: true,
1876
- supportsStructuredOutput: false
1877
- };
1878
-
1879
- // src/infrastructure/providers/openai/models/gpt-5-4.ts
1880
- var gpt54Specification = {
1881
- name: "gpt-5.4",
1882
- provider: "openai",
1883
- supportsReasoningEffort: true,
1884
- supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1885
- supportedContextItemTypes: [
1886
- "user_message",
1887
- "system_message",
1888
- "developer_message",
1889
- "reasoning",
1890
- "function_call",
1891
- "function_call_output",
1892
- "model_message"
1893
- ],
1894
- supportsStreaming: true,
1895
- contextWindowSize: 105e4,
1896
- maxOutputTokens: 128e3,
1897
- supportsFunctionCalling: true,
1898
- supportsStructuredOutput: true
1899
- };
1900
-
1901
- // src/infrastructure/providers/openai/models/gpt-5-4-mini.ts
1902
- var gpt54MiniSpecification = {
1903
- name: "gpt-5.4-mini",
1904
- provider: "openai",
1905
- supportsReasoningEffort: true,
1906
- supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1907
- supportedContextItemTypes: [
1908
- "user_message",
1909
- "system_message",
1910
- "developer_message",
1911
- "reasoning",
1912
- "function_call",
1913
- "function_call_output",
1914
- "model_message"
1915
- ],
1916
- supportsStreaming: true,
1917
- contextWindowSize: 4e5,
1918
- maxOutputTokens: 128e3,
1919
- supportsFunctionCalling: true,
1920
- supportsStructuredOutput: true
1921
- };
1922
-
1923
- // src/infrastructure/providers/openai/models/gpt-5-4-nano.ts
1924
- var gpt54NanoSpecification = {
1925
- name: "gpt-5.4-nano",
1926
- provider: "openai",
1927
- supportsReasoningEffort: true,
1928
- supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1929
- supportedContextItemTypes: [
1930
- "user_message",
1931
- "system_message",
1932
- "developer_message",
1933
- "reasoning",
1934
- "function_call",
1935
- "function_call_output",
1936
- "model_message"
1937
- ],
1938
- supportsStreaming: true,
1939
- contextWindowSize: 4e5,
1940
- maxOutputTokens: 128e3,
1941
- supportsFunctionCalling: true,
1942
- supportsStructuredOutput: true
1943
- };
1944
-
1945
- // src/infrastructure/providers/openai/models/gpt-5-5.ts
1946
- var gpt55Specification = {
1947
- name: "gpt-5.5",
1948
- provider: "openai",
1949
- supportsReasoningEffort: true,
1950
- supportedReasoningEfforts: ["xhigh", "high", "medium", "low", "none"],
1951
- supportedContextItemTypes: [
1952
- "user_message",
1953
- "system_message",
1954
- "developer_message",
1955
- "reasoning",
1956
- "function_call",
1957
- "function_call_output",
1958
- "model_message"
1959
- ],
1960
- supportsStreaming: true,
1961
- contextWindowSize: 105e4,
1962
- maxOutputTokens: 128e3,
1963
- supportsFunctionCalling: true,
1964
- supportsStructuredOutput: true
1965
- };
1966
-
1967
- // src/infrastructure/providers/anthropic/models/claude-4-5-haiku.ts
1968
- var claudeHaiku45Specification = {
1969
- name: "claude-haiku-4-5",
1970
- provider: "anthropic",
1971
- supportsReasoningEffort: true,
1972
- supportedReasoningEfforts: ["high", "medium", "low", "none"],
1973
- supportedContextItemTypes: [
1974
- "user_message",
1975
- "system_message",
1976
- "developer_message",
1977
- "reasoning",
1978
- "function_call",
1979
- "function_call_output",
1980
- "model_message"
1981
- ],
1982
- supportsStreaming: true,
1983
- contextWindowSize: 2e5,
1984
- maxOutputTokens: 64e3,
1985
- supportsFunctionCalling: true,
1986
- supportsStructuredOutput: true
1987
- };
1988
-
1989
- // src/infrastructure/providers/openai/models/gpt-6-astra.ts
1990
- var gpt6AstraSpecification = {
1991
- name: "gpt-6-astra",
1992
- provider: "openai",
1993
- supportsReasoningEffort: true,
1994
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1995
- supportedContextItemTypes: [
1996
- "user_message",
1997
- "system_message",
1998
- "developer_message",
1999
- "reasoning",
2000
- "function_call",
2001
- "function_call_output",
2002
- "model_message"
2003
- ],
2004
- supportsStreaming: true,
2005
- contextWindowSize: 105e4,
2006
- maxOutputTokens: 128e3,
2007
- supportsFunctionCalling: true,
2008
- supportsStructuredOutput: true
2009
- };
2010
-
2011
- // src/infrastructure/providers/openai/models/gpt-6-1-sol.ts
2012
- var gpt61SolSpecification = {
2013
- name: "gpt-6.1-sol",
2014
- provider: "openai",
2015
- supportsReasoningEffort: true,
2016
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2017
- supportedContextItemTypes: [
2018
- "user_message",
2019
- "system_message",
2020
- "developer_message",
2021
- "reasoning",
2022
- "function_call",
2023
- "function_call_output",
2024
- "model_message"
2025
- ],
2026
- supportsStreaming: true,
2027
- contextWindowSize: 105e4,
2028
- maxOutputTokens: 128e3,
2029
- supportsFunctionCalling: true,
2030
- supportsStructuredOutput: true
2031
- };
2032
-
2033
- // src/infrastructure/providers/openai/models/gpt-6-sol.ts
2034
- var gpt6SolSpecification = {
2035
- name: "gpt-6-sol",
2036
- provider: "openai",
2037
- supportsReasoningEffort: true,
2038
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
2039
- supportedContextItemTypes: [
2040
- "user_message",
2041
- "system_message",
2042
- "developer_message",
2043
- "reasoning",
2044
- "function_call",
2045
- "function_call_output",
2046
- "model_message"
2047
- ],
2048
- supportsStreaming: true,
2049
- contextWindowSize: 105e4,
2050
- maxOutputTokens: 128e3,
2051
- supportsFunctionCalling: true,
2052
- supportsStructuredOutput: true
2053
- };
2054
-
2055
- // src/infrastructure/providers/openai/models/gpt-6-luna.ts
2056
- var gpt6LunaSpecification = {
2057
- name: "gpt-6-luna",
2058
- provider: "openai",
2059
- supportsReasoningEffort: true,
2060
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
2061
- supportedContextItemTypes: [
2062
- "user_message",
2063
- "system_message",
2064
- "developer_message",
2065
- "reasoning",
2066
- "function_call",
2067
- "function_call_output",
2068
- "model_message"
2069
- ],
2070
- supportsStreaming: true,
2071
- contextWindowSize: 105e4,
2072
- maxOutputTokens: 128e3,
2073
- supportsFunctionCalling: true,
2074
- supportsStructuredOutput: true
2075
- };
2076
-
2077
- // src/infrastructure/providers/anthropic/models/claude-5-1-fable.ts
2078
- var claudeFable51Specification = {
2079
- name: "claude-fable-5-1",
2080
- provider: "anthropic",
2081
- supportsReasoningEffort: true,
2082
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2083
- supportedContextItemTypes: [
2084
- "user_message",
2085
- "system_message",
2086
- "developer_message",
2087
- "reasoning",
2088
- "function_call",
2089
- "function_call_output",
2090
- "model_message"
2091
- ],
2092
- supportsStreaming: true,
2093
- contextWindowSize: 1e6,
2094
- maxOutputTokens: 128e3,
2095
- supportsFunctionCalling: true,
2096
- supportsStructuredOutput: true
2097
- };
2098
-
2099
- // src/infrastructure/providers/anthropic/models/claude-5-5-opus.ts
2100
- var claudeOpus55Specification = {
2101
- name: "claude-opus-5-5",
2102
- provider: "anthropic",
2103
- supportsReasoningEffort: true,
2104
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2105
- supportedContextItemTypes: [
2106
- "user_message",
2107
- "system_message",
2108
- "developer_message",
2109
- "reasoning",
2110
- "function_call",
2111
- "function_call_output",
2112
- "model_message"
2113
- ],
2114
- supportsStreaming: true,
2115
- contextWindowSize: 1e6,
2116
- maxOutputTokens: 128e3,
2117
- supportsFunctionCalling: true,
2118
- supportsStructuredOutput: true
2119
- };
2120
-
2121
- // src/infrastructure/providers/anthropic/models/claude-5-5-sonnet.ts
2122
- var claudeSonnet55Specification = {
2123
- name: "claude-sonnet-5-5",
2124
- provider: "anthropic",
2125
- supportsReasoningEffort: true,
2126
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2127
- supportedContextItemTypes: [
2128
- "user_message",
2129
- "system_message",
2130
- "developer_message",
2131
- "reasoning",
2132
- "function_call",
2133
- "function_call_output",
2134
- "model_message"
2135
- ],
2136
- supportsStreaming: true,
2137
- contextWindowSize: 1e6,
2138
- maxOutputTokens: 128e3,
2139
- supportsFunctionCalling: true,
2140
- supportsStructuredOutput: true
2141
- };
2142
-
2143
- // src/infrastructure/providers/anthropic/models/claude-5-sonnet.ts
2144
- var claudeSonnet5Specification = {
2145
- name: "claude-sonnet-5",
2146
- provider: "anthropic",
2147
- supportsReasoningEffort: true,
2148
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2149
- supportedContextItemTypes: [
2150
- "user_message",
2151
- "system_message",
2152
- "developer_message",
2153
- "reasoning",
2154
- "function_call",
2155
- "function_call_output",
2156
- "model_message"
2157
- ],
2158
- supportsStreaming: true,
2159
- contextWindowSize: 1e6,
2160
- maxOutputTokens: 128e3,
2161
- supportsFunctionCalling: true,
2162
- supportsStructuredOutput: true
2163
- };
2164
-
2165
- // src/infrastructure/providers/gemini/models/gemini-3-8-flash.ts
2166
- var gemini38FlashSpecification = {
2167
- name: "gemini-3.8-flash",
2168
- provider: "google",
2169
- supportsReasoningEffort: true,
2170
- supportedReasoningEfforts: ["high", "medium", "low"],
2171
- supportedContextItemTypes: [
2172
- "user_message",
2173
- "system_message",
2174
- "developer_message",
2175
- "reasoning",
2176
- "function_call",
2177
- "function_call_output",
2178
- "model_message"
2179
- ],
2180
- supportsStreaming: true,
2181
- contextWindowSize: 1048576,
2182
- maxOutputTokens: 65536,
2183
- supportsFunctionCalling: true,
2184
- supportsStructuredOutput: true
2185
- };
2186
-
2187
- // src/infrastructure/providers/gemini/models/gemini-3-5-flash-lite.ts
2188
- var gemini35FlashLiteSpecification = {
2189
- name: "gemini-3.5-flash-lite",
2190
- provider: "google",
2191
- supportsReasoningEffort: true,
2192
- supportedReasoningEfforts: ["high", "medium", "low", "minimal"],
2193
- supportedContextItemTypes: [
2194
- "user_message",
2195
- "system_message",
2196
- "developer_message",
2197
- "reasoning",
2198
- "function_call",
2199
- "function_call_output",
2200
- "model_message"
2201
- ],
2202
- supportsStreaming: true,
2203
- contextWindowSize: 1048576,
2204
- maxOutputTokens: 65536,
2205
- supportsFunctionCalling: true,
2206
- supportsStructuredOutput: true
2207
- };
2208
-
2209
- // src/infrastructure/providers/deepseek/models/deepseek-flash.ts
2210
- var deepSeekFlashSpecification = {
2211
- name: "deepseek-flash",
2212
- provider: "deepseek",
2213
- supportsReasoningEffort: true,
2214
- supportedReasoningEfforts: ["max", "high", "medium", "low", "none"],
2215
- supportedContextItemTypes: [
2216
- "user_message",
2217
- "system_message",
2218
- "developer_message",
2219
- "reasoning",
2220
- "function_call",
2221
- "function_call_output",
2222
- "model_message"
2223
- ],
2224
- supportsStreaming: true,
2225
- contextWindowSize: 1e6,
2226
- maxOutputTokens: 384e3,
2227
- supportsFunctionCalling: true,
2228
- supportsStructuredOutput: false
2229
- };
2230
-
2231
- // src/application/services/models.ts
2232
- var supportedModels = [
2233
- {
2234
- endpoint: new OpenAIResponses(),
2235
- specification: gpt54Specification
2236
- },
2237
- {
2238
- endpoint: new OpenAIResponses(),
2239
- specification: gpt54MiniSpecification
2240
- },
2241
- {
2242
- endpoint: new OpenAIResponses(),
2243
- specification: gpt54NanoSpecification
2244
- },
2245
- {
2246
- endpoint: new OpenAIResponses(),
2247
- specification: gpt55Specification
2248
- },
2249
- {
2250
- endpoint: new OpenAIResponses(),
2251
- specification: gpt6LunaSpecification
2252
- },
2253
- {
2254
- endpoint: new OpenAIResponses(),
2255
- specification: gpt6SolSpecification
2256
- },
2257
- {
2258
- endpoint: new OpenAIResponses(),
2259
- specification: gpt61SolSpecification
2260
- },
2261
- {
2262
- endpoint: new OpenAIResponses(),
2263
- specification: gpt6AstraSpecification
2264
- },
2265
- {
2266
- endpoint: new AnthropicMessages(),
2267
- specification: claudeHaiku45Specification
2268
- },
2269
- {
2270
- endpoint: new AnthropicMessages(),
2271
- specification: claudeSonnet46Specification
2272
- },
2273
- {
2274
- endpoint: new AnthropicMessages(),
2275
- specification: claudeOpus47Specification
2276
- },
2277
- {
2278
- endpoint: new AnthropicMessages(),
2279
- specification: claudeOpus48Specification
2280
- },
2281
- {
2282
- endpoint: new AnthropicMessages(),
2283
- specification: claudeSonnet5Specification
2284
- },
2285
- {
2286
- endpoint: new AnthropicMessages(),
2287
- specification: claudeSonnet55Specification
2288
- },
2289
- {
2290
- endpoint: new AnthropicMessages(),
2291
- specification: claudeOpus55Specification
2292
- },
2293
- {
2294
- endpoint: new AnthropicMessages(),
2295
- specification: claudeFable51Specification
2296
- },
2297
- {
2298
- endpoint: new GeminiGenerateContent(),
2299
- specification: gemini35FlashSpecification
2300
- },
2301
- {
2302
- endpoint: new GeminiGenerateContent(),
2303
- specification: gemini31ProSpecification
2304
- },
2305
- {
2306
- endpoint: new GeminiGenerateContent(),
2307
- specification: gemini35FlashLiteSpecification
2308
- },
2309
- {
2310
- endpoint: new GeminiGenerateContent(),
2311
- specification: gemini38FlashSpecification
2312
- },
2313
- {
2314
- endpoint: new OpenAIChatCompletions(),
2315
- specification: deepSeekV4FlashSpecification
2316
- },
2317
- {
2318
- endpoint: new OpenAIChatCompletions(),
2319
- specification: deepSeekV4ProSpecification
2320
- },
2321
- {
2322
- endpoint: new OpenAIChatCompletions(),
2323
- specification: deepSeekFlashSpecification
2324
- }
2325
- ];
2326
-
2327
- // src/domain/generative-model/request-validation/reasoning-effort.ts
2328
- var ReasoningEffortValidation = class {
2329
- constructor() {
2330
- this.name = "reasoning-effort";
2331
- }
2332
- isValid(inferenceInput, model) {
2333
- if (inferenceInput.reasoningEffort === void 0) {
2334
- return true;
2335
- }
2336
- if (!model.supportsReasoningEffort) {
2337
- return false;
144
+ });
2338
145
  }
2339
- return model.supportedReasoningEfforts.includes(inferenceInput.reasoningEffort);
2340
146
  }
2341
147
  };
2342
148
 
2343
- // src/domain/generative-model/request-validation/tool-calling.ts
2344
- var ToolCallingValidation = class {
2345
- constructor() {
2346
- 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;
2347
154
  }
2348
- isValid(inferenceInput, model) {
2349
- if (inferenceInput.tools === void 0) {
2350
- 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");
2351
159
  }
2352
- return model.supportsFunctionCalling;
2353
- }
2354
- };
2355
-
2356
- // src/domain/generative-model/request-validation/streaming.ts
2357
- var StreamingValidation = class {
2358
- constructor() {
2359
- this.name = "streaming";
2360
- }
2361
- isValid(inferenceInput, model) {
2362
- if (!inferenceInput.streaming) {
2363
- return true;
160
+ const participant = space.getParticipant(participantId);
161
+ if (!participant) {
162
+ throw new Error("Participant not found");
2364
163
  }
2365
- return model.supportsStreaming;
2366
- }
2367
- };
2368
-
2369
- // src/domain/generative-model/request-validation/context.ts
2370
- function getContextItemValidationKey(item) {
2371
- if (item instanceof UserMessageItem) {
2372
- return "user_message";
2373
- }
2374
- if (item instanceof SystemMessageItem) {
2375
- return "system_message";
2376
- }
2377
- if (item instanceof DeveloperMessageItem) {
2378
- return "developer_message";
2379
- }
2380
- if (item instanceof ModelMessageItem) {
2381
- return "model_message";
2382
- }
2383
- return item.getType();
2384
- }
2385
- var ContextValidation = class {
2386
- constructor() {
2387
- this.name = "context";
2388
- }
2389
- isValid(inferenceInput, model) {
2390
- return inferenceInput.context.items.every(
2391
- (item) => model.supportedContextItemTypes.includes(getContextItemValidationKey(item))
2392
- );
2393
- }
2394
- };
2395
-
2396
- // src/domain/generative-model/request-validation/inference-request-validator.ts
2397
- var defaultRequestValidationRules = [
2398
- new ReasoningEffortValidation(),
2399
- new ToolCallingValidation(),
2400
- new StreamingValidation(),
2401
- new StructuredOutputValidation(),
2402
- new ContextValidation()
2403
- ];
2404
- var InferenceInputValidator = class {
2405
- constructor(rules = defaultRequestValidationRules) {
2406
- this.rules = rules;
2407
- }
2408
- validate(inferenceInput, model) {
2409
- for (const rule of this.rules) {
2410
- if (!rule.isValid(inferenceInput, model)) {
2411
- throw new Error(`Request validation "${rule.name}" failed for model "${model.name}"`);
2412
- }
164
+ const event = space.removeParticipant(participant, occurredAt);
165
+ if (event) {
166
+ this.eventPublisher.publish(event, space.getParticipants());
2413
167
  }
168
+ await this.spaceRepository.save(space);
2414
169
  }
2415
170
  };
2416
171
 
2417
- // src/application/services/inference-runner.ts
2418
- var DefaultInferenceRunner = class {
2419
- constructor(supportedModels2, requestValidator) {
2420
- this.supportedModels = supportedModels2;
2421
- 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;
2422
177
  }
2423
- async run(input) {
2424
- const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
2425
- if (!generativeModel) {
2426
- 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");
2427
182
  }
2428
- this.requestValidator.validate(input, generativeModel.specification);
2429
- return await generativeModel.endpoint.infer(input);
2430
- }
2431
- async *stream(input) {
2432
- const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
2433
- if (!generativeModel) {
2434
- throw new Error(`Unsupported model: ${input.model}`);
183
+ const participant = space.getParticipant(participantId);
184
+ if (!participant) {
185
+ throw new Error("Participant not found");
2435
186
  }
2436
- this.requestValidator.validate(input, generativeModel.specification);
2437
- yield* generativeModel.endpoint.stream(input);
2438
- }
2439
- };
2440
-
2441
- // src/application/services/function-call.ts
2442
- var DefaultFunctionCallRunner = class {
2443
- async run(input, tool) {
2444
- try {
2445
- const result = await tool.invoke(JSON.parse(input.args));
2446
- return FunctionCallOutputItem.create(
2447
- input.callId,
2448
- typeof result === "string" ? result : JSON.stringify(result)
2449
- );
2450
- } catch (error) {
2451
- 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());
2452
190
  }
191
+ await this.spaceRepository.save(space);
2453
192
  }
2454
193
  };
2455
194
 
2456
- // src/application/use-cases/send-event.ts
2457
- function createSendEvent(resolveRuntime) {
2458
- return function sendEvent(event, senderId) {
2459
- const runtime = resolveRuntime();
2460
- const participant = runtime.getParticipant(senderId);
2461
- if (!participant) {
2462
- throw new Error(`Participant ${senderId} not found`);
2463
- }
2464
- runtime.publish(event);
2465
- };
2466
- }
2467
-
2468
195
  // src/define-runtime.ts
2469
196
  function defineRuntime() {
2470
197
  let runtime = null;
2471
- const processor = new EventProcessor();
2472
198
  function initializeRuntime(config) {
2473
- var _a, _b, _c, _d;
2474
199
  if (runtime) {
2475
200
  throw new Error("Runtime already initialized");
2476
201
  }
2477
- const inferenceRunner = (_d = (_a = config.inferenceRunnerConfig) == null ? void 0 : _a.runner) != null ? _d : new DefaultInferenceRunner(
2478
- (_c = (_b = config.inferenceRunnerConfig) == null ? void 0 : _b.supportedModels) != null ? _c : supportedModels,
2479
- new InferenceInputValidator()
2480
- );
2481
- const functionCallRunner = new DefaultFunctionCallRunner();
2482
- runtime = new RuntimeService(config.state, processor, inferenceRunner, functionCallRunner);
202
+ runtime = new RuntimeService(config.state);
2483
203
  return runtime;
2484
204
  }
2485
205
  function resolveRuntime() {
@@ -2488,34 +208,55 @@ function defineRuntime() {
2488
208
  }
2489
209
  return runtime;
2490
210
  }
2491
- function resolveParticipant(id) {
2492
- if (!runtime) {
2493
- throw new Error("Runtime not initialized");
2494
- }
2495
- const participant = runtime.state.getParticipant(id);
2496
- if (!participant) {
2497
- 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
+ };
2498
246
  }
2499
- return participant;
2500
- }
2501
- const join = createJoin(resolveRuntime);
2502
- const leave = createLeave(resolveRuntime);
2503
- const sendMessage = createSendMessage(resolveRuntime);
2504
- const sendEvent = createSendEvent(resolveRuntime);
2505
- const runLoop = createRunLoop(resolveRuntime);
247
+ };
2506
248
  return {
2507
249
  initializeRuntime,
2508
250
  resolveRuntime,
2509
- resolveParticipant,
251
+ createParticipant,
2510
252
  join,
2511
253
  leave,
2512
254
  sendMessage,
2513
- sendEvent,
2514
- runLoop
255
+ sendMessageTool
2515
256
  };
2516
257
  }
2517
258
 
2518
- // src/domain/agentic-environment/situation/situation-specification.ts
259
+ // src/domain/space/situation-specification.ts
2519
260
  var SituationSpecification = class {
2520
261
  and(other) {
2521
262
  return new AndSituationSpecification(this, other);
@@ -2558,34 +299,9 @@ var NotSituationSpecification = class extends SituationSpecification {
2558
299
  };
2559
300
  // Annotate the CommonJS export names for ESM import in node:
2560
301
  0 && (module.exports = {
2561
- Agent,
2562
- AnthropicMessages,
2563
- ContextItem,
2564
- DefaultInferenceRunner,
2565
- DeveloperMessageItem,
2566
- FunctionCallItem,
2567
- FunctionCallOutputItem,
2568
- GeminiGenerateContent,
2569
- Human,
2570
- InputTokenDetails,
2571
- McpClient,
2572
- McpToolRegistry,
2573
- ModelContext,
2574
- ModelMessageItem,
2575
- OpenAIChatCompletions,
2576
- OpenAIResponses,
2577
- OutputTokenDetails,
2578
302
  Participant,
2579
- ReasoningItem,
2580
- RuntimeState,
2581
- SemanticEvent,
2582
303
  SituationSpecification,
2583
- SystemMessageItem,
2584
- TokenUsage,
2585
- UserMessageItem,
2586
- createAgent,
2587
- createHuman,
2588
- defineRuntime,
2589
- supportedModels
304
+ SpaceEvent,
305
+ defineRuntime
2590
306
  });
2591
307
  //# sourceMappingURL=index.js.map