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