@mozaik-ai/core 4.2.0-beta.8 → 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,1115 +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;
233
- }
234
- getId() {
235
- return this.id;
236
- }
237
- getName() {
238
- return this.name;
186
+ this.args = args;
239
187
  }
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 extends Participant {
409
- constructor(manifest, tools, memory, handlers) {
410
- super(manifest, handlers);
411
- this.memory = memory;
412
- this.tools = tools;
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: {} });
413
273
  }
414
- getTools() {
415
- return this.tools;
274
+ async connect() {
275
+ if (this.connected) return;
276
+ await this.client.connect(this.transport);
277
+ this.connected = true;
416
278
  }
417
- getMemory() {
418
- 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
+ });
419
292
  }
420
- static create({
421
- manifest,
422
- tools,
423
- memory,
424
- handlers
425
- }) {
426
- return new _Agent(manifest, tools, memory, handlers);
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;
427
302
  }
428
- static rehydrate(record) {
429
- return new _Agent(record.manifest, record.tools, record.memory, record.handlers);
303
+ async close() {
304
+ if (!this.connected) return;
305
+ try {
306
+ await this.client.close();
307
+ } catch (e) {
308
+ }
309
+ this.connected = false;
430
310
  }
431
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
+ }
432
317
 
433
- // src/application/use-cases/create-agent.ts
434
- var CreateAgentUseCase = class {
435
- constructor(agentRepository, memoryFactory) {
436
- this.agentRepository = agentRepository;
437
- 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;
438
343
  }
439
- async execute(name, instruction, tools, handlers) {
440
- const id = UuidGenerator.create();
441
- const manifest = { id, name, role: "agent" };
442
- const memory = this.memoryFactory.create();
443
- const agentRecord = { id, manifest, tools, memory, handlers };
444
- const agent = Agent.create(agentRecord);
445
- await this.agentRepository.save(agent);
446
- return agentRecord;
344
+ /** Close all underlying MCP connections. */
345
+ async close() {
346
+ await Promise.all(this.clients.map((c) => c.close()));
447
347
  }
448
348
  };
449
349
 
450
- // src/infrastructure/repositories/in-memory-agent-repository.ts
451
- var InMemoryAgentRepository = class {
452
- constructor() {
453
- this.agents = [];
454
- }
455
- exists(id) {
456
- return Promise.resolve(this.agents.some((agent) => agent.getManifest().id === id));
457
- }
458
- findById(id) {
459
- 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;
460
357
  }
461
- findAll() {
462
- return Promise.resolve(this.agents);
358
+ static create(text) {
359
+ const content = InputText.create(text);
360
+ return new _SystemMessageItem(content);
463
361
  }
464
- async save(agent) {
465
- this.agents.push(agent);
362
+ static rehydrate(data) {
363
+ const content = InputText.rehydrate(data);
364
+ return new _SystemMessageItem(content);
466
365
  }
467
366
  };
468
367
 
469
- // src/domain/agent/loop/specification.ts
470
- var LoopSpecification = class {
471
- and(other) {
472
- 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;
473
375
  }
474
- or(other) {
475
- 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);
476
379
  }
477
- not() {
478
- return new NotLoopSpecification(this);
380
+ };
381
+ var ParticipantJoinedEvent = class extends SemanticEvent {
382
+ static init(manifest) {
383
+ return SemanticEvent.create("participant.joined", manifest.id, manifest);
479
384
  }
480
385
  };
481
- var AndLoopSpecification = class extends LoopSpecification {
482
- constructor(left, right) {
483
- super();
484
- this.left = left;
485
- this.right = right;
386
+ var ParticipantLeftEvent = class extends SemanticEvent {
387
+ static init(manifest) {
388
+ return SemanticEvent.create("participant.left", manifest.id, manifest);
486
389
  }
487
- isSatisfiedBy(agentLoop) {
488
- 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 });
489
394
  }
490
395
  };
491
- var OrLoopSpecification = class extends LoopSpecification {
492
- constructor(left, right) {
493
- super();
494
- this.left = left;
495
- 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";
496
402
  }
497
- isSatisfiedBy(agentLoop) {
498
- 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
+ };
499
412
  }
500
413
  };
501
- var NotLoopSpecification = class extends LoopSpecification {
502
- constructor(rule) {
503
- super();
504
- 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;
505
420
  }
506
- isSatisfiedBy(agentLoop) {
507
- return !this.rule.isSatisfiedBy(agentLoop);
421
+ getManifest() {
422
+ return this.manifest;
508
423
  }
509
- };
510
- var AwaitingInference = class extends LoopSpecification {
511
- isSatisfiedBy(agentLoop) {
512
- return agentLoop.loop.stateId === "awaiting_inference";
424
+ getId() {
425
+ return this.manifest.id;
513
426
  }
514
- };
515
- var AwaitingRequest = class extends LoopSpecification {
516
- isSatisfiedBy(agentLoop) {
517
- return agentLoop.loop.stateId === "awaiting_inference_request";
427
+ getHandlers() {
428
+ return this.handlers;
518
429
  }
519
- };
520
- var AwaitingToolOutput = class extends LoopSpecification {
521
- isSatisfiedBy(agentLoop) {
522
- return agentLoop.loop.stateId === "awaiting_tool_output";
430
+ setHandlers(handlers) {
431
+ this.handlers = handlers;
523
432
  }
524
433
  };
525
- var ModelAnswered = class extends LoopSpecification {
526
- isSatisfiedBy(agentLoop) {
527
- const operations = agentLoop.loop.completedOperations;
528
- const lastOperation = operations[operations.length - 1];
529
- if ((lastOperation == null ? void 0 : lastOperation.type) !== "inference") {
530
- return false;
531
- }
532
- 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);
533
446
  }
534
447
  };
535
448
 
536
- // src/domain/agent/loop/action.ts
537
- var LoopAction = class {
538
- };
539
- var RequestPreparationAction = class extends LoopAction {
540
- constructor(request) {
541
- super();
542
- 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;
543
456
  }
544
- execute(agentLoop) {
545
- return {
546
- type: "inference",
547
- request: this.request
548
- };
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);
549
470
  }
550
- };
551
- var InferenceAction = class extends LoopAction {
552
- execute(agentLoop) {
553
- const request = agentLoop.loop.request;
554
- if (!request) {
555
- return { type: "wait", reason: "no request" };
556
- }
557
- return { type: "inference", request };
471
+ getTools() {
472
+ return this.tools;
558
473
  }
559
- };
560
- var ToolUseAction = class extends LoopAction {
561
- execute(agentLoop) {
562
- if (!agentLoop.loop.pending) {
563
- return { type: "wait" };
564
- }
565
- const pendingOperation = agentLoop.loop.pending;
566
- if (pendingOperation.type === "tool_execution") {
567
- return { type: "tool_use", call: pendingOperation.call };
568
- }
569
- return { type: "wait" };
474
+ getDeveloperMessage() {
475
+ return this.developerMessage;
476
+ }
477
+ getMemory() {
478
+ return this.memory;
570
479
  }
571
480
  };
572
- var CompleteAction = class extends LoopAction {
573
- constructor(reason) {
574
- super();
575
- 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);
576
497
  }
577
- execute() {
578
- 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);
579
506
  }
580
507
  };
581
508
 
582
- // src/domain/agent/loop/rule.ts
583
- var LoopRule = class _LoopRule {
584
- constructor(id, condition, action, priority) {
585
- this._id = id;
586
- this._priority = priority;
587
- this._condition = condition;
588
- this._action = action;
589
- }
590
- get id() {
591
- return this._id;
592
- }
593
- get priority() {
594
- 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();
595
522
  }
596
- get condition() {
597
- 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);
598
527
  }
599
- get action() {
600
- return this._action;
528
+ removeParticipant(participant) {
529
+ this.participants.delete(participant.getId());
601
530
  }
602
- static create(spec) {
603
- var _a;
604
- const priority = (_a = spec.priority) != null ? _a : 0;
605
- const id = crypto.randomUUID();
606
- return new _LoopRule(id, spec.when, spec.then, priority);
531
+ getParticipant(id) {
532
+ return this.participants.get(id);
607
533
  }
608
- static rehydrate(spec) {
609
- var _a;
610
- const priority = (_a = spec.priority) != null ? _a : 0;
611
- const rule = new _LoopRule(spec.id, spec.condition, spec.action, priority);
612
- return rule;
534
+ getParticipants() {
535
+ return [...this.participants.values()];
613
536
  }
614
537
  };
615
- var RuleBook = class _RuleBook {
616
- constructor(rules) {
617
- 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;
618
546
  }
619
- addRule(rule) {
620
- this.rules.push(rule);
547
+ join(participant) {
548
+ this.state.addParticipant(participant);
549
+ this.publish(ParticipantJoinedEvent.init(participant.getManifest()));
621
550
  }
622
- removeRule(rule) {
623
- 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()));
624
554
  }
625
- getRules() {
626
- return this.rules;
555
+ publish(event) {
556
+ for (const participant of this.state.getParticipants()) {
557
+ this.processor.process(event, participant);
558
+ }
627
559
  }
628
- static create(loopRuleParams) {
629
- const rules = loopRuleParams.map((param) => LoopRule.create(param));
630
- 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);
631
565
  }
632
- static rehydrate(record) {
633
- const rules = record.rules.map((rule) => LoopRule.rehydrate(rule));
634
- return new _RuleBook(rules);
566
+ getInferenceRunner() {
567
+ return this.inferenceRunner;
635
568
  }
636
- record() {
637
- return {
638
- rules: this.rules.map((rule) => ({
639
- id: rule.id,
640
- priority: rule.priority,
641
- condition: rule.condition,
642
- action: rule.action
643
- }))
644
- };
569
+ getFunctionCallRunner() {
570
+ return this.functionCallRunner;
645
571
  }
646
572
  };
647
- var defaultRules = (request) => [
648
- {
649
- when: new AwaitingRequest(),
650
- then: new RequestPreparationAction(request)
651
- },
652
- {
653
- when: new AwaitingInference(),
654
- then: new InferenceAction()
655
- },
656
- {
657
- when: new AwaitingToolOutput(),
658
- then: new ToolUseAction()
659
- },
660
- {
661
- when: new ModelAnswered(),
662
- 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
+ }
663
586
  }
664
- ];
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
+ }
665
615
 
666
- // src/domain/agent/loop/loop.ts
667
- var Loop = class _Loop {
668
- 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) {
669
619
  this.loopId = loopId;
670
- this.agentId = agentId;
671
- this.subject = subject;
672
- this.createdAt = createdAt;
673
- this.state = state;
674
- this.inferenceRequest = inferenceRequest;
675
- this.pendingOperation = pendingOperation;
676
- this.transitionHistory = transitionHistory;
677
- this.operationHistory = operationHistory;
678
- this._ruleBook = ruleBook;
679
- }
680
- get id() {
681
- return this.loopId;
682
- }
683
- get stateId() {
684
- return this.state;
620
+ this.stateExecutor = stateExecutor;
621
+ this.transitionResolver = transitionResolver;
622
+ this.interceptionHandler = interceptionHandler;
685
623
  }
686
- get pending() {
687
- return this.pendingOperation;
688
- }
689
- get history() {
690
- 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
+ }
691
640
  }
692
- get completedOperations() {
693
- return this.operationHistory;
641
+ getLoopId() {
642
+ return this.loopId;
694
643
  }
695
- get request() {
696
- return this.inferenceRequest;
644
+ static create(stateExecutor, transitionResolver, interceptionHandler) {
645
+ const loopId = crypto.randomUUID();
646
+ return new _AgentLoop(loopId, stateExecutor, transitionResolver, interceptionHandler);
697
647
  }
698
- get ruleBook() {
699
- 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;
700
658
  }
701
- getSubject() {
702
- 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
+ }
703
672
  }
704
- getAgentId() {
705
- 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";
706
680
  }
707
- 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);
708
697
  return {
709
- id: this.id,
710
- agentId: this.agentId,
711
- subject: this.subject,
712
- createdAt: this.createdAt,
713
- state: this.state,
714
- inferenceRequest: this.inferenceRequest,
715
- pendingOperation: this.pendingOperation,
716
- transitionHistory: [...this.transitionHistory],
717
- operationHistory: [...this.operationHistory],
718
- ruleBook: this.ruleBook.record()
698
+ stateId: this.id,
699
+ input,
700
+ output: {
701
+ item
702
+ }
719
703
  };
720
704
  }
721
- moveToIdle(reason, transitionId) {
722
- this.transitionTo("idle", reason, transitionId);
723
- this.pendingOperation = void 0;
724
- }
725
- moveToAwaitingInference(operation) {
726
- this.assertAwaitingInferenceRequest();
727
- this.pendingOperation = operation;
728
- this.transitionTo("awaiting_inference", "inference_requested", operation.id);
729
- }
730
- moveToAwaitingToolOutput(operation, occurredAt) {
731
- this.assertIdle();
732
- this.pendingOperation = operation;
733
- this.transitionTo("awaiting_tool_output", "tool_execution_requested", operation.id);
734
- }
735
- requestInference(request) {
736
- this.assertAwaitingInferenceRequest();
737
- this.inferenceRequest = request;
738
- const operation = {
739
- id: UuidGenerator.create(),
740
- type: "inference",
741
- requestedAt: SystemClock.now(),
742
- 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])
743
718
  };
744
- this.moveToAwaitingInference(operation);
745
- return operation;
746
- }
747
- requestToolUse(operationId, call, requestedAt) {
748
- this.assertIdle();
749
- const operation = {
750
- id: operationId,
751
- type: "tool_execution",
752
- requestedAt,
753
- call
719
+ loopVisitor.visitMessageReceivedCompleted(output);
720
+ return {
721
+ stateId: this.id,
722
+ input,
723
+ output
754
724
  };
755
- this.moveToAwaitingToolOutput(operation, requestedAt);
756
- return operation;
757
- }
758
- transitionTo(nextState, reason, operationId) {
759
- const occurredAt = SystemClock.now();
760
- const previousState = this.state;
761
- this.state = nextState;
762
- this.transitionHistory.push({
763
- occurredAt,
764
- previousState,
765
- nextState,
766
- reason,
767
- operationId
768
- });
769
- }
770
- assertIdle() {
771
- if (this.state !== "idle") {
772
- throw new Error(`Expected idle loop, but loop is ${this.state}`);
773
- }
774
- }
775
- assertAwaitingInferenceRequest() {
776
- if (this.state !== "awaiting_inference_request") {
777
- throw new Error(`Expected awaiting inference request loop, but loop is ${this.state}`);
778
- }
779
- }
780
- receiveInferenceResult(operationId, result) {
781
- if (this.state !== "awaiting_inference") {
782
- throw new Error(`Cannot receive inference result while loop is ${this.state}`);
783
- }
784
- const operation = this.pendingOperation;
785
- if ((operation == null ? void 0 : operation.type) !== "inference" || operation.id !== operationId) {
786
- throw new Error(`Inference result does not match pending operation ${operationId}`);
787
- }
788
- if (!this.inferenceRequest) {
789
- throw new Error("Inference request is not provided");
790
- }
791
- this.moveToIdle("inference_completed", operationId);
792
- this.operationHistory.push({
793
- type: "inference",
794
- operationId,
795
- requestedAt: operation.requestedAt,
796
- completedAt: SystemClock.now(),
797
- request: operation.request,
798
- result
799
- });
800
- this.inferenceRequest.context.items.push(...result.items);
801
- const call = result.items.find((item) => item.type === "tool_use_request");
802
- if (call) {
803
- this.pendingOperation = {
804
- id: call.requestId,
805
- type: "tool_execution",
806
- requestedAt: SystemClock.now(),
807
- call
808
- };
809
- this.transitionTo("awaiting_tool_output", "tool_use_requested", call.requestId);
810
- return;
811
- }
812
- this.pendingOperation = void 0;
813
725
  }
814
- receiveToolUseResult(operationId, result) {
815
- if (this.state !== "awaiting_tool_output") {
816
- throw new Error(`Cannot receive tool output while loop is ${this.state}`);
817
- }
818
- const operation = this.pendingOperation;
819
- if ((operation == null ? void 0 : operation.type) !== "tool_execution" || operation.id !== operationId) {
820
- throw new Error(`Tool output does not match pending operation ${operationId}`);
821
- }
822
- if (!this.inferenceRequest) {
823
- throw new Error("Inference request is not provided");
824
- }
825
- this.operationHistory.push({
826
- type: "tool_use",
827
- operationId,
828
- requestedAt: operation.requestedAt,
829
- completedAt: SystemClock.now(),
830
- call: operation.call,
831
- result
832
- });
833
- this.inferenceRequest.context.items.push(result);
834
- this.pendingOperation = void 0;
835
- this.transitionTo("awaiting_inference_request", "tool_use_completed", operationId);
836
- }
837
- complete(reason) {
838
- this.assertNotSettled("complete");
839
- this.pendingOperation = void 0;
840
- this.transitionTo("completed", reason);
841
- }
842
- stop(reason) {
843
- this.assertNotSettled("stop");
844
- this.pendingOperation = void 0;
845
- this.transitionTo("stopped", reason);
846
- }
847
- wait(reason) {
848
- this.assertNotSettled("wait");
849
- this.pendingOperation = void 0;
850
- this.transitionTo("idle", reason);
851
- }
852
- assertNotSettled(intent) {
853
- if (this.state === "completed" || this.state === "stopped") {
854
- throw new Error(`Cannot ${intent} a loop that is already ${this.state}`);
855
- }
856
- }
857
- static create(agentId, subject, ruleBook) {
858
- const createdAt = SystemClock.now();
859
- const id = UuidGenerator.create();
860
- return new _Loop(
861
- id,
862
- agentId,
863
- subject,
864
- createdAt,
865
- "awaiting_inference_request",
866
- void 0,
867
- void 0,
868
- [],
869
- [],
870
- ruleBook
871
- );
726
+ };
727
+
728
+ // src/application/states/model-message.ts
729
+ var ModelMessageState = class {
730
+ constructor() {
731
+ this.id = "model_message";
872
732
  }
873
- static rehydrate(record) {
874
- return new _Loop(
875
- record.id,
876
- record.agentId,
877
- record.subject,
878
- record.createdAt,
879
- record.state,
880
- record.inferenceRequest,
881
- record.pendingOperation,
882
- [...record.transitionHistory],
883
- [...record.operationHistory],
884
- RuleBook.rehydrate(record.ruleBook)
885
- );
733
+ async run(input, loopVisitor) {
734
+ loopVisitor.visitModelAnswer(input);
735
+ return {
736
+ stateId: this.id,
737
+ input,
738
+ output: void 0
739
+ };
886
740
  }
887
741
  };
888
742
 
889
- // src/application/use-cases/create-loop.ts
890
- var CreateAgentLoopUseCase = class {
891
- constructor(loopRepository) {
892
- this.loopRepository = loopRepository;
743
+ // src/domain/agentic-environment/loop/transition-resolver.ts
744
+ var TransitionResolver = class {
745
+ constructor(rules) {
746
+ this.rules = rules;
893
747
  }
894
- async execute(params) {
895
- if ("rules" in params) {
896
- const ruleBook = RuleBook.create(params.rules);
897
- const loop = Loop.create(params.agentId, params.subject, ruleBook);
898
- await this.loopRepository.save(loop);
899
- return loop;
900
- } else {
901
- const ruleBook = RuleBook.create(defaultRules(params.request));
902
- const loop = Loop.create(params.agentId, params.subject, ruleBook);
903
- await this.loopRepository.save(loop);
904
- 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}"`);
905
752
  }
753
+ return rule.createTransition(execution);
906
754
  }
907
755
  };
908
756
 
909
- // src/infrastructure/repositories/in-memory-loop-repository.ts
910
- var InMemoryLoopRepository = class {
911
- constructor() {
912
- this.loops = [];
757
+ // src/domain/agentic-environment/loop/transition-specification.ts
758
+ var MessageReceivedSpecification = class {
759
+ isSatisfiedBy(execution) {
760
+ return execution.stateId === "message_received";
913
761
  }
914
- findById(id) {
915
- 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");
916
769
  }
917
- save(loop) {
918
- const index = this.loops.findIndex((stored) => stored.id === loop.id);
919
- if (index === -1) {
920
- this.loops.push(loop);
921
- } else {
922
- this.loops[index] = loop;
923
- }
924
- 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");
925
774
  }
926
775
  };
927
-
928
- // src/domain/inference/tool-use-item-factory.ts
929
- var ToolUseItemFactory = class {
930
- create(toolUseRequest, result) {
931
- const toolUseResult = {
932
- type: "tool_use_result",
933
- requestId: toolUseRequest.requestId,
934
- result: {
935
- type: "input_text",
936
- text: result
937
- }
938
- };
939
- 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";
940
784
  }
941
785
  };
942
786
 
943
- // src/application/runners/local-tool-runner.ts
944
- var LocalToolRunner = class {
787
+ // src/domain/agentic-environment/loop/transition-rule.ts
788
+ var ContextPreparationToInferenceRule = class {
945
789
  constructor() {
946
- this.toolUseItemFactory = new ToolUseItemFactory();
790
+ this.specification = new MessageReceivedSpecification();
947
791
  }
948
- async run(input, tool) {
949
- try {
950
- const result = await tool.invoke(JSON.parse(input.toolArguments));
951
- const resultText = typeof result === "string" ? result : JSON.stringify(result);
952
- return this.toolUseItemFactory.create(input, resultText);
953
- } catch (error) {
954
- const errorText = `Error calling tool: ${error}`;
955
- return this.toolUseItemFactory.create(input, errorText);
792
+ createTransition(execution) {
793
+ if (execution.stateId !== "message_received") {
794
+ throw new Error("Expected context_preparation execution");
956
795
  }
796
+ const nextStateId = execution.output.streaming ? "inference_streaming" : "inference";
797
+ return {
798
+ nextStateId,
799
+ input: execution.output
800
+ };
957
801
  }
958
802
  };
959
-
960
- // src/application/runners/inference-runner.ts
961
- var DefaultInferenceRunner = class {
962
- constructor(supportedModels2, requestValidator) {
963
- this.supportedModels = supportedModels2;
964
- this.requestValidator = requestValidator;
803
+ var InferenceToFunctionCallRule = class {
804
+ constructor() {
805
+ this.specification = new InferenceProducedFunctionCallSpecification();
965
806
  }
966
- async run(input) {
967
- const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
968
- if (!generativeModel) {
969
- 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");
970
810
  }
971
- this.requestValidator.validate(input, generativeModel.specification);
972
- return await generativeModel.endpoint.infer(input);
973
- }
974
- async *stream(input) {
975
- const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
976
- if (!generativeModel) {
977
- 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");
978
814
  }
979
- this.requestValidator.validate(input, generativeModel.specification);
980
- yield* generativeModel.endpoint.stream(input);
815
+ return {
816
+ nextStateId: "function_call",
817
+ input: {
818
+ call: functionCallItem,
819
+ inferenceInput: execution.input
820
+ }
821
+ };
981
822
  }
982
823
  };
983
-
984
- // src/domain/inference/request-validation/reasoning-effort.ts
985
- var ReasoningEffortValidation = class {
824
+ var InferenceToModelMessageRule = class {
986
825
  constructor() {
987
- this.name = "reasoning-effort";
826
+ this.specification = new InferenceProducedModelMessageSpecification();
988
827
  }
989
- isValid(inferenceRequest, model) {
990
- if (inferenceRequest.reasoningEffort === void 0) {
991
- 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");
992
831
  }
993
- if (!model.supportsReasoningEffort) {
994
- 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");
995
837
  }
996
- 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
+ };
997
845
  }
998
846
  };
999
-
1000
- // src/domain/inference/request-validation/tool-calling.ts
1001
- var ToolUseRequestingValidation = class {
847
+ var FunctionCallToInferenceRule = class {
1002
848
  constructor() {
1003
- this.name = "tool-calling";
849
+ this.specification = new FunctionCallCompletedSpecification();
1004
850
  }
1005
- isValid(inferenceRequest, model) {
1006
- if (inferenceRequest.tools === void 0) {
1007
- return true;
851
+ createTransition(execution) {
852
+ if (execution.stateId !== "function_call") {
853
+ throw new Error("Expected function_call execution");
1008
854
  }
1009
- 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
+ };
1010
863
  }
1011
864
  };
1012
-
1013
- // src/domain/inference/request-validation/streaming.ts
1014
- var StreamingValidation = class {
865
+ var ModelMessageToIdleRule = class {
1015
866
  constructor() {
1016
- this.name = "streaming";
867
+ this.specification = new ModelMessageCompletedSpecification();
1017
868
  }
1018
- isValid(inferenceRequest, model) {
1019
- if (!inferenceRequest.streaming) {
1020
- return true;
869
+ createTransition(execution) {
870
+ if (execution.stateId !== "model_message") {
871
+ throw new Error("Expected model_message execution");
1021
872
  }
1022
- return model.supportsStreaming;
873
+ return {
874
+ nextStateId: "idle",
875
+ input: void 0
876
+ };
1023
877
  }
1024
878
  };
1025
879
 
1026
- // src/domain/inference/request-validation/structured-output.ts
1027
- var StructuredOutputValidation = class {
1028
- constructor() {
1029
- 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)();
1030
888
  }
1031
- isValid(inferenceRequest, model) {
1032
- if (inferenceRequest.structuredOutput === void 0) {
1033
- return true;
1034
- }
1035
- return model.supportsStructuredOutput;
889
+ visitMessageReceivedStarted(input) {
890
+ this.publish("message_received.started", input);
1036
891
  }
1037
- };
1038
-
1039
- // src/domain/inference/request-validation/context.ts
1040
- function getContextItemValidationKey(item) {
1041
- if (item.type === "user_message") {
1042
- return "user_message";
892
+ visitMessageReceivedCompleted(output) {
893
+ this.publish("message_received.completed", output);
1043
894
  }
1044
- if (item.type === "system_message") {
1045
- return "system_message";
895
+ visitInferenceStarted(input) {
896
+ this.publish("inference.started", input);
1046
897
  }
1047
- if (item.type === "developer_message") {
1048
- return "developer_message";
898
+ visitInferenceEvent(event) {
899
+ this.publish("inference.stream", event);
1049
900
  }
1050
- if (item.type === "model_message") {
1051
- return "model_message";
901
+ visitInferenceCompleted(output) {
902
+ this.publish("inference.completed", output);
1052
903
  }
1053
- return item.type;
1054
- }
1055
- var ContextValidation = class {
1056
- constructor() {
1057
- this.name = "context";
904
+ visitFunctionCallStarted(input) {
905
+ this.publish("function_call.started", input);
1058
906
  }
1059
- isValid(inferenceRequest, model) {
1060
- return inferenceRequest.context.items.every(
1061
- (item) => model.supportedContextItemTypes.includes(getContextItemValidationKey(item))
1062
- );
907
+ visitFunctionCallCompleted(output) {
908
+ this.publish("function_call.completed", output);
1063
909
  }
1064
- };
1065
-
1066
- // src/domain/inference/request-validation/inference-request-validator.ts
1067
- var defaultRequestValidationRules = [
1068
- new ReasoningEffortValidation(),
1069
- new ToolUseRequestingValidation(),
1070
- new StreamingValidation(),
1071
- new StructuredOutputValidation(),
1072
- new ContextValidation()
1073
- ];
1074
- var InferenceRequestValidator = class {
1075
- constructor(rules = defaultRequestValidationRules) {
1076
- this.rules = rules;
910
+ visitModelAnswer(input) {
911
+ this.publish("model.answer", input);
1077
912
  }
1078
- validate(inferenceRequest, model) {
1079
- for (const rule of this.rules) {
1080
- if (!rule.isValid(inferenceRequest, model)) {
1081
- 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
+ });
1082
942
  }
1083
943
  }
1084
944
  }
1085
945
  };
1086
946
 
1087
- // src/domain/inference/token-usage.ts
1088
- var InputTokenDetails = class {
1089
- constructor(cached_tokens) {
1090
- this.cached_tokens = cached_tokens;
1091
- }
1092
- };
1093
- var OutputTokenDetails = class {
1094
- constructor(reasoning_tokens) {
1095
- this.reasoning_tokens = reasoning_tokens;
1096
- }
1097
- };
1098
- var TokenUsage = class {
1099
- constructor(inputTokens, outputTokens, totalTokens, inputTokenDetails, outputTokenDetails) {
1100
- this.inputTokens = inputTokens;
1101
- this.outputTokens = outputTokens;
1102
- this.totalTokens = totalTokens;
1103
- this.inputTokenDetails = inputTokenDetails;
1104
- 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
+ };
1105
971
  }
1106
972
  };
1107
973
 
1108
- // 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
1109
1008
  var AnthropicMessagesMapper = class {
1110
- toRequest(inferenceRequest) {
1111
- const { messages, system } = this.mapContextItems(inferenceRequest);
1009
+ toRequest(inferenceInput) {
1010
+ const { messages, system } = this.mapContextItems(inferenceInput);
1112
1011
  const outputConfig = {};
1113
1012
  const request = {
1114
- model: inferenceRequest.model,
1013
+ model: inferenceInput.model,
1115
1014
  messages
1116
1015
  };
1117
- request.max_tokens = inferenceRequest.maxOutputTokens;
1016
+ request.max_tokens = inferenceInput.maxOutputTokens;
1118
1017
  if (system) {
1119
1018
  request.system = system;
1120
1019
  }
1121
- if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1122
- request.tools = inferenceRequest.tools.map((tool) => ({
1020
+ if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1021
+ request.tools = inferenceInput.tools.map((tool) => ({
1123
1022
  name: tool.name,
1124
1023
  description: tool.description,
1125
1024
  input_schema: tool.parameters
1126
1025
  }));
1127
1026
  }
1128
- if (inferenceRequest.structuredOutput) {
1027
+ if (inferenceInput.structuredOutput) {
1129
1028
  outputConfig.format = {
1130
1029
  type: "json_schema",
1131
- schema: inferenceRequest.structuredOutput.schema
1030
+ schema: inferenceInput.structuredOutput.schema
1132
1031
  };
1133
1032
  }
1134
- if (inferenceRequest.reasoningEffort) {
1033
+ if (inferenceInput.reasoningEffort) {
1135
1034
  request.thinking = { type: "adaptive" };
1136
- outputConfig.effort = inferenceRequest.reasoningEffort;
1035
+ outputConfig.effort = inferenceInput.reasoningEffort;
1137
1036
  }
1138
1037
  if (Object.keys(outputConfig).length > 0) {
1139
1038
  request.output_config = outputConfig;
1140
1039
  }
1141
- if (inferenceRequest.streaming) {
1142
- request.stream = inferenceRequest.streaming;
1040
+ if (inferenceInput.streaming) {
1041
+ request.stream = inferenceInput.streaming;
1143
1042
  }
1144
1043
  return request;
1145
1044
  }
@@ -1154,55 +1053,52 @@ var AnthropicMessagesMapper = class {
1154
1053
  content: [block]
1155
1054
  });
1156
1055
  }
1157
- mapContextItems(inferenceRequest) {
1056
+ mapContextItems(inferenceInput) {
1158
1057
  var _a, _b, _c;
1159
- const context = inferenceRequest.context;
1058
+ const context = inferenceInput.context;
1160
1059
  const messages = [];
1161
1060
  const system = [];
1162
- for (const item of context.items) {
1163
- if (item.type === "developer_message" || item.type === "system_message") {
1164
- 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);
1165
1064
  continue;
1166
1065
  }
1167
- if (item.type === "user_message") {
1168
- 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 });
1169
1068
  continue;
1170
1069
  }
1171
- if (item.type === "model_message") {
1172
- 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 });
1173
1072
  continue;
1174
1073
  }
1175
- if (item.type === "reasoning") {
1176
- const reasoning = item;
1074
+ if (item instanceof ReasoningItem) {
1177
1075
  this.addContentBlock(messages, "assistant", {
1178
1076
  type: "thinking",
1179
- thinking: (_b = (_a = reasoning.content) == null ? void 0 : _a.text) != null ? _b : "",
1180
- 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 : ""
1181
1079
  });
1182
1080
  continue;
1183
1081
  }
1184
- if (item.type === "tool_use_request") {
1185
- const toolUseRequest = item;
1082
+ if (item instanceof FunctionCallItem) {
1186
1083
  let input;
1187
1084
  try {
1188
- input = JSON.parse(toolUseRequest.toolArguments);
1085
+ input = JSON.parse(item.args);
1189
1086
  } catch (e) {
1190
- input = toolUseRequest.toolArguments;
1087
+ input = item.args;
1191
1088
  }
1192
1089
  this.addContentBlock(messages, "assistant", {
1193
1090
  type: "tool_use",
1194
- id: toolUseRequest.requestId,
1195
- name: toolUseRequest.toolName,
1091
+ id: item.callId,
1092
+ name: item.name,
1196
1093
  input
1197
1094
  });
1198
1095
  continue;
1199
1096
  }
1200
- if (item.type === "tool_use_result") {
1201
- const toolUseResult = item;
1097
+ if (item instanceof FunctionCallOutputItem) {
1202
1098
  this.addContentBlock(messages, "user", {
1203
1099
  type: "tool_result",
1204
- tool_use_id: toolUseResult.requestId,
1205
- content: toolUseResult.result.text
1100
+ tool_use_id: item.callId,
1101
+ content: item.output.text
1206
1102
  });
1207
1103
  }
1208
1104
  }
@@ -1231,35 +1127,34 @@ var AnthropicMessagesMapper = class {
1231
1127
  const items = [];
1232
1128
  for (const block of response.content) {
1233
1129
  if (block.type === "text") {
1234
- items.push({
1235
- type: "model_message",
1236
- text: block.text
1237
- });
1130
+ items.push(ModelMessageItem.rehydrate({ text: block.text }));
1238
1131
  continue;
1239
1132
  }
1240
1133
  if (block.type === "tool_use") {
1241
- items.push({
1242
- type: "tool_use_request",
1243
- requestId: block.id,
1244
- toolName: block.name,
1245
- toolArguments: JSON.stringify((_a = block.input) != null ? _a : {})
1246
- });
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
+ );
1247
1141
  continue;
1248
1142
  }
1249
1143
  if (block.type === "thinking") {
1250
- items.push({
1251
- type: "reasoning",
1252
- content: block.thinking ? { type: "input_text", text: block.thinking } : void 0,
1253
- encryptedContent: block.signature,
1254
- summary: []
1255
- });
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
+ );
1256
1151
  }
1257
1152
  }
1258
1153
  return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1259
1154
  }
1260
1155
  };
1261
1156
 
1262
- // src/infrastructure/providers/anthropic/anthropic-messages.ts
1157
+ // src/infrastructure/providers/anthropic/endpoints/anthropic-messages.ts
1263
1158
  var import_sdk = __toESM(require("@anthropic-ai/sdk"));
1264
1159
  var AnthropicMessages = class {
1265
1160
  constructor(endpointMapper = new AnthropicMessagesMapper(), config = {}) {
@@ -1273,13 +1168,13 @@ var AnthropicMessages = class {
1273
1168
  apiKey: this.clientConfig.apiKey
1274
1169
  });
1275
1170
  }
1276
- async infer(inferenceRequest) {
1277
- const request = this.endpointMapper.toRequest(inferenceRequest);
1171
+ async infer(inferenceInput) {
1172
+ const request = this.endpointMapper.toRequest(inferenceInput);
1278
1173
  const response = await this.client.messages.create(request);
1279
1174
  return this.endpointMapper.toResponse(response);
1280
1175
  }
1281
- async *stream(inferenceRequest) {
1282
- const request = this.endpointMapper.toRequest(inferenceRequest);
1176
+ async *stream(inferenceInput) {
1177
+ const request = this.endpointMapper.toRequest(inferenceInput);
1283
1178
  const stream = this.client.messages.stream(request);
1284
1179
  for await (const event of stream) {
1285
1180
  yield event;
@@ -1294,29 +1189,44 @@ var AnthropicMessages = class {
1294
1189
  }
1295
1190
  };
1296
1191
 
1297
- // 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
1298
1208
  var OpenAIResponsesMapper = class {
1299
- toRequest(inferenceRequest) {
1209
+ toRequest(inferenceInput) {
1300
1210
  var _a, _b;
1301
1211
  const request = {
1302
- model: inferenceRequest.model,
1303
- input: this.mapContextItems(inferenceRequest)
1212
+ model: inferenceInput.model,
1213
+ input: this.mapContextItems(inferenceInput)
1304
1214
  };
1305
- if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1306
- request.tools = inferenceRequest.tools.map((tool) => ({
1215
+ if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1216
+ request.tools = inferenceInput.tools.map((tool) => ({
1307
1217
  type: tool.type,
1308
1218
  name: tool.name,
1309
1219
  description: tool.description,
1310
1220
  parameters: tool.parameters
1311
1221
  }));
1312
1222
  }
1313
- if (inferenceRequest.reasoningEffort) {
1223
+ if (inferenceInput.reasoningEffort) {
1314
1224
  request.reasoning = {
1315
- effort: inferenceRequest.reasoningEffort
1225
+ effort: inferenceInput.reasoningEffort
1316
1226
  };
1317
1227
  }
1318
- if (inferenceRequest.structuredOutput) {
1319
- const format = inferenceRequest.structuredOutput;
1228
+ if (inferenceInput.structuredOutput) {
1229
+ const format = inferenceInput.structuredOutput;
1320
1230
  request.text = {
1321
1231
  format: {
1322
1232
  type: "json_schema",
@@ -1326,58 +1236,54 @@ var OpenAIResponsesMapper = class {
1326
1236
  }
1327
1237
  };
1328
1238
  }
1329
- if (inferenceRequest.streaming) {
1330
- request.stream = inferenceRequest.streaming;
1239
+ if (inferenceInput.streaming) {
1240
+ request.stream = inferenceInput.streaming;
1331
1241
  }
1332
1242
  return request;
1333
1243
  }
1334
- mapContextItems(inferenceRequest) {
1244
+ mapContextItems(inferenceInput) {
1335
1245
  const input = [];
1336
- for (const item of inferenceRequest.context.items) {
1337
- if (item.type === "developer_message" || item.type === "system_message" || item.type === "user_message") {
1338
- 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) {
1339
1248
  input.push({
1340
- type: "message",
1341
- role,
1342
- content: [{ type: "input_text", text: item.text }]
1249
+ type: item.type,
1250
+ role: item.role,
1251
+ content: [{ type: "input_text", text: item.content.text }]
1343
1252
  });
1344
1253
  continue;
1345
1254
  }
1346
- if (item.type === "model_message") {
1255
+ if (item instanceof ModelMessageItem) {
1347
1256
  input.push({
1348
- type: "message",
1349
- role: "assistant",
1350
- content: [{ type: "output_text", text: item.text }]
1257
+ type: item.type,
1258
+ role: item.role,
1259
+ content: [{ type: "output_text", text: item.content.text }]
1351
1260
  });
1352
1261
  continue;
1353
1262
  }
1354
- if (item.type === "tool_use_request") {
1355
- const toolUseRequest = item;
1263
+ if (item instanceof FunctionCallItem) {
1356
1264
  input.push({
1357
- type: "function_call",
1358
- call_id: toolUseRequest.requestId,
1359
- name: toolUseRequest.toolName,
1360
- arguments: toolUseRequest.toolArguments
1265
+ type: item.type,
1266
+ call_id: item.callId,
1267
+ name: item.name,
1268
+ arguments: item.args
1361
1269
  });
1362
1270
  continue;
1363
1271
  }
1364
- if (item.type === "tool_use_result") {
1365
- const toolUseResult = item;
1272
+ if (item instanceof FunctionCallOutputItem) {
1366
1273
  input.push({
1367
- type: "function_call_output",
1368
- call_id: toolUseResult.requestId,
1369
- 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 }]
1370
1277
  });
1371
1278
  continue;
1372
1279
  }
1373
- if (item.type === "reasoning") {
1374
- const reasoning = item;
1280
+ if (item instanceof ReasoningItem) {
1375
1281
  const reasoningInput = {
1376
- type: "reasoning",
1377
- 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 }))
1378
1284
  };
1379
- if (reasoning.encryptedContent !== void 0) {
1380
- reasoningInput.encrypted_content = reasoning.encryptedContent;
1285
+ if (item.encryptedContent !== void 0) {
1286
+ reasoningInput.encrypted_content = item.encryptedContent;
1381
1287
  }
1382
1288
  input.push(reasoningInput);
1383
1289
  }
@@ -1404,33 +1310,30 @@ var OpenAIResponsesMapper = class {
1404
1310
  if (item.type === "message" && item.role === "assistant") {
1405
1311
  const firstContent = (_b = item.content) == null ? void 0 : _b[0];
1406
1312
  if (firstContent) {
1407
- items.push({
1408
- type: "model_message",
1409
- text: firstContent.text
1410
- });
1313
+ items.push(ModelMessageItem.rehydrate(firstContent));
1411
1314
  }
1412
1315
  continue;
1413
1316
  }
1414
1317
  if (item.type === "function_call") {
1415
- const toolUseRequest = {
1416
- type: "tool_use_request",
1417
- requestId: item.call_id,
1418
- toolName: item.name,
1419
- toolArguments: item.arguments
1420
- };
1421
- items.push(toolUseRequest);
1318
+ items.push(
1319
+ FunctionCallItem.rehydrate({
1320
+ callId: item.call_id,
1321
+ name: item.name,
1322
+ args: item.arguments
1323
+ })
1324
+ );
1422
1325
  continue;
1423
1326
  }
1424
1327
  if (item.type === "reasoning") {
1425
- items.push({
1426
- type: "reasoning",
1427
- content: void 0,
1428
- encryptedContent: item.encrypted_content,
1429
- summary: ((_c = item.summary) != null ? _c : []).map((summary) => ({
1430
- type: "summary_text",
1431
- text: summary.text
1432
- }))
1433
- });
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
+ );
1434
1337
  }
1435
1338
  }
1436
1339
  return {
@@ -1441,8 +1344,7 @@ var OpenAIResponsesMapper = class {
1441
1344
  }
1442
1345
  };
1443
1346
 
1444
- // src/infrastructure/providers/openai/openai-responses.ts
1445
- var import_openai = __toESM(require("openai"));
1347
+ // src/infrastructure/providers/openai/endpoints/openai-responses.ts
1446
1348
  var OpenAIResponses = class {
1447
1349
  constructor(endpointMapper = new OpenAIResponsesMapper(), config = {}) {
1448
1350
  this.endpointMapper = endpointMapper;
@@ -1455,13 +1357,13 @@ var OpenAIResponses = class {
1455
1357
  apiKey: this.clientConfig.apiKey
1456
1358
  });
1457
1359
  }
1458
- async infer(inferenceRequest) {
1459
- const request = this.endpointMapper.toRequest(inferenceRequest);
1360
+ async infer(inferenceInput) {
1361
+ const request = this.endpointMapper.toRequest(inferenceInput);
1460
1362
  const response = await this.client.responses.create(request);
1461
1363
  return this.endpointMapper.toResponse(response);
1462
1364
  }
1463
- async *stream(inferenceRequest) {
1464
- const request = this.endpointMapper.toRequest(inferenceRequest);
1365
+ async *stream(inferenceInput) {
1366
+ const request = this.endpointMapper.toRequest(inferenceInput);
1465
1367
  const stream = await this.client.responses.create({ ...request, stream: true });
1466
1368
  let completedResponse = void 0;
1467
1369
  for await (const event of stream) {
@@ -1478,26 +1380,26 @@ var OpenAIResponses = class {
1478
1380
  type: "inference.output",
1479
1381
  payload: output,
1480
1382
  occurredAt: /* @__PURE__ */ new Date(),
1481
- producerId: inferenceRequest.model
1383
+ producerId: inferenceInput.model
1482
1384
  };
1483
1385
  }
1484
1386
  };
1485
1387
 
1486
- // src/infrastructure/providers/gemini/gemini-generate-content.ts
1388
+ // src/infrastructure/providers/gemini/endpoints/gemini-generate-content.ts
1487
1389
  var import_genai = require("@google/genai");
1488
1390
 
1489
- // src/infrastructure/providers/gemini/gemini-generate-content-mapper.ts
1391
+ // src/infrastructure/providers/gemini/endpoints/gemini-generate-content-mapper.ts
1490
1392
  var GeminiGenerateContentMapper = class {
1491
- toRequest(inferenceRequest) {
1492
- const { contents, systemInstruction } = this.mapContextItems(inferenceRequest);
1393
+ toRequest(inferenceInput) {
1394
+ const { contents, systemInstruction } = this.mapContextItems(inferenceInput);
1493
1395
  const config = {};
1494
1396
  if (systemInstruction) {
1495
1397
  config.systemInstruction = systemInstruction;
1496
1398
  }
1497
- if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1399
+ if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1498
1400
  config.tools = [
1499
1401
  {
1500
- functionDeclarations: inferenceRequest.tools.map((tool) => ({
1402
+ functionDeclarations: inferenceInput.tools.map((tool) => ({
1501
1403
  name: tool.name,
1502
1404
  description: tool.description,
1503
1405
  parametersJsonSchema: tool.parameters
@@ -1505,66 +1407,62 @@ var GeminiGenerateContentMapper = class {
1505
1407
  }
1506
1408
  ];
1507
1409
  }
1508
- if (inferenceRequest.structuredOutput) {
1410
+ if (inferenceInput.structuredOutput) {
1509
1411
  config.responseMimeType = "application/json";
1510
- config.responseSchema = inferenceRequest.structuredOutput.schema;
1412
+ config.responseSchema = inferenceInput.structuredOutput.schema;
1511
1413
  }
1512
- if (inferenceRequest.reasoningEffort) {
1414
+ if (inferenceInput.reasoningEffort) {
1513
1415
  config.thinkingConfig = {
1514
- thinkingLevel: inferenceRequest.reasoningEffort,
1416
+ thinkingLevel: inferenceInput.reasoningEffort,
1515
1417
  includeThoughts: true
1516
1418
  };
1517
1419
  }
1518
1420
  const request = {
1519
- model: inferenceRequest.model,
1421
+ model: inferenceInput.model,
1520
1422
  contents,
1521
1423
  config
1522
1424
  };
1523
- if (inferenceRequest.streaming) {
1524
- request.stream = inferenceRequest.streaming;
1425
+ if (inferenceInput.streaming) {
1426
+ request.stream = inferenceInput.streaming;
1525
1427
  }
1526
1428
  return request;
1527
1429
  }
1528
- mapContextItems(inferenceRequest) {
1430
+ mapContextItems(inferenceInput) {
1529
1431
  var _a;
1530
- const context = inferenceRequest.context;
1432
+ const context = inferenceInput.context;
1531
1433
  const contents = [];
1532
1434
  const system = [];
1533
1435
  const callNames = /* @__PURE__ */ new Map();
1534
- for (const item of context.items) {
1535
- if (item.type === "developer_message" || item.type === "system_message") {
1536
- 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);
1537
1439
  continue;
1538
1440
  }
1539
- if (item.type === "user_message") {
1540
- this.addPart(contents, "user", { text: item.text });
1441
+ if (item instanceof UserMessageItem) {
1442
+ this.addPart(contents, "user", { text: item.content.text });
1541
1443
  continue;
1542
1444
  }
1543
- if (item.type === "model_message") {
1544
- this.addPart(contents, "model", { text: item.text });
1445
+ if (item instanceof ModelMessageItem) {
1446
+ this.addPart(contents, "model", { text: item.content.text });
1545
1447
  continue;
1546
1448
  }
1547
- if (item.type === "tool_use_request") {
1548
- const toolUseRequest = item;
1549
- callNames.set(toolUseRequest.requestId, toolUseRequest.toolName);
1449
+ if (item instanceof FunctionCallItem) {
1450
+ callNames.set(item.callId, item.name);
1550
1451
  let args;
1551
1452
  try {
1552
- args = JSON.parse(toolUseRequest.toolArguments);
1453
+ args = JSON.parse(item.args);
1553
1454
  } catch (e) {
1554
1455
  args = {};
1555
1456
  }
1556
- this.addPart(contents, "model", {
1557
- functionCall: { id: toolUseRequest.requestId, name: toolUseRequest.toolName, args }
1558
- });
1457
+ this.addPart(contents, "model", { functionCall: { id: item.callId, name: item.name, args } });
1559
1458
  continue;
1560
1459
  }
1561
- if (item.type === "tool_use_result") {
1562
- const toolUseResult = item;
1460
+ if (item instanceof FunctionCallOutputItem) {
1563
1461
  this.addPart(contents, "user", {
1564
1462
  functionResponse: {
1565
- id: toolUseResult.requestId,
1566
- name: (_a = callNames.get(toolUseResult.requestId)) != null ? _a : "",
1567
- 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)
1568
1466
  }
1569
1467
  });
1570
1468
  }
@@ -1610,35 +1508,34 @@ var GeminiGenerateContentMapper = class {
1610
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 : [];
1611
1509
  for (const part of parts) {
1612
1510
  if (part.thought && part.text) {
1613
- items.push({
1614
- type: "reasoning",
1615
- content: { type: "input_text", text: part.text },
1616
- encryptedContent: void 0,
1617
- summary: []
1618
- });
1511
+ items.push(
1512
+ ReasoningItem.rehydrate({
1513
+ content: InputText.rehydrate({ text: part.text }),
1514
+ encryptedContent: void 0,
1515
+ summary: []
1516
+ })
1517
+ );
1619
1518
  continue;
1620
1519
  }
1621
1520
  if (part.text) {
1622
- items.push({
1623
- type: "model_message",
1624
- text: part.text
1625
- });
1521
+ items.push(ModelMessageItem.rehydrate({ text: part.text }));
1626
1522
  continue;
1627
1523
  }
1628
1524
  if (part.functionCall) {
1629
- items.push({
1630
- type: "tool_use_request",
1631
- requestId: (_e = part.functionCall.id) != null ? _e : "",
1632
- toolName: part.functionCall.name,
1633
- toolArguments: JSON.stringify((_f = part.functionCall.args) != null ? _f : {})
1634
- });
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
+ );
1635
1532
  }
1636
1533
  }
1637
1534
  return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1638
1535
  }
1639
1536
  };
1640
1537
 
1641
- // src/infrastructure/providers/gemini/gemini-generate-content.ts
1538
+ // src/infrastructure/providers/gemini/endpoints/gemini-generate-content.ts
1642
1539
  var GeminiGenerateContent = class {
1643
1540
  constructor(endpointMapper = new GeminiGenerateContentMapper(), config = {}) {
1644
1541
  this.endpointMapper = endpointMapper;
@@ -1651,13 +1548,13 @@ var GeminiGenerateContent = class {
1651
1548
  ...this.clientConfig.baseURL ? { httpOptions: { baseUrl: this.clientConfig.baseURL } } : {}
1652
1549
  });
1653
1550
  }
1654
- async infer(inferenceRequest) {
1655
- const request = this.endpointMapper.toRequest(inferenceRequest);
1551
+ async infer(inferenceInput) {
1552
+ const request = this.endpointMapper.toRequest(inferenceInput);
1656
1553
  const response = await this.client.models.generateContent(request);
1657
1554
  return this.endpointMapper.toResponse(response);
1658
1555
  }
1659
- async *stream(inferenceRequest) {
1660
- const request = this.endpointMapper.toRequest(inferenceRequest);
1556
+ async *stream(inferenceInput) {
1557
+ const request = this.endpointMapper.toRequest(inferenceInput);
1661
1558
  const stream = await this.client.models.generateContentStream(request);
1662
1559
  let lastEvent = void 0;
1663
1560
  for await (const chunk of stream) {
@@ -1677,15 +1574,15 @@ var GeminiGenerateContent = class {
1677
1574
  }
1678
1575
  };
1679
1576
 
1680
- // src/infrastructure/providers/openai/openai-chat-completions-mapper.ts
1577
+ // src/infrastructure/providers/openai/endpoints/openai-chat-completions-mapper.ts
1681
1578
  var OpenAIChatCompletionsMapper = class {
1682
- toRequest(inferenceRequest) {
1579
+ toRequest(inferenceInput) {
1683
1580
  const request = {
1684
- model: inferenceRequest.model,
1685
- messages: this.mapContextItems(inferenceRequest)
1581
+ model: inferenceInput.model,
1582
+ messages: this.mapContextItems(inferenceInput)
1686
1583
  };
1687
- if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1688
- request.tools = inferenceRequest.tools.map((tool) => ({
1584
+ if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1585
+ request.tools = inferenceInput.tools.map((tool) => ({
1689
1586
  type: "function",
1690
1587
  function: {
1691
1588
  name: tool.name,
@@ -1694,36 +1591,35 @@ var OpenAIChatCompletionsMapper = class {
1694
1591
  }
1695
1592
  }));
1696
1593
  }
1697
- if (inferenceRequest.reasoningEffort) {
1698
- request.reasoning_effort = inferenceRequest.reasoningEffort;
1594
+ if (inferenceInput.reasoningEffort) {
1595
+ request.reasoning_effort = inferenceInput.reasoningEffort;
1699
1596
  }
1700
- if (inferenceRequest.streaming) {
1701
- request.stream = inferenceRequest.streaming;
1597
+ if (inferenceInput.streaming) {
1598
+ request.stream = inferenceInput.streaming;
1702
1599
  }
1703
1600
  return request;
1704
1601
  }
1705
- mapContextItems(inferenceRequest) {
1602
+ mapContextItems(inferenceInput) {
1706
1603
  var _a;
1707
1604
  const messages = [];
1708
- for (const item of inferenceRequest.context.items) {
1709
- if (item.type === "developer_message" || item.type === "system_message") {
1710
- 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 });
1711
1608
  continue;
1712
1609
  }
1713
- if (item.type === "user_message") {
1714
- messages.push({ role: "user", content: item.text });
1610
+ if (item instanceof UserMessageItem) {
1611
+ messages.push({ role: "user", content: item.content.text });
1715
1612
  continue;
1716
1613
  }
1717
- if (item.type === "model_message") {
1718
- messages.push({ role: "assistant", content: item.text });
1614
+ if (item instanceof ModelMessageItem) {
1615
+ messages.push({ role: "assistant", content: item.content.text });
1719
1616
  continue;
1720
1617
  }
1721
- if (item.type === "tool_use_request") {
1722
- const toolUseRequest = item;
1618
+ if (item instanceof FunctionCallItem) {
1723
1619
  const toolCall = {
1724
- id: toolUseRequest.requestId,
1620
+ id: item.callId,
1725
1621
  type: "function",
1726
- function: { name: toolUseRequest.toolName, arguments: toolUseRequest.toolArguments }
1622
+ function: { name: item.name, arguments: item.args }
1727
1623
  };
1728
1624
  const last = messages[messages.length - 1];
1729
1625
  if ((last == null ? void 0 : last.role) === "assistant") {
@@ -1734,13 +1630,8 @@ var OpenAIChatCompletionsMapper = class {
1734
1630
  }
1735
1631
  continue;
1736
1632
  }
1737
- if (item.type === "tool_use_result") {
1738
- const toolUseResult = item;
1739
- messages.push({
1740
- role: "tool",
1741
- tool_call_id: toolUseResult.requestId,
1742
- content: toolUseResult.result.text
1743
- });
1633
+ if (item instanceof FunctionCallOutputItem) {
1634
+ messages.push({ role: "tool", tool_call_id: item.callId, content: item.output.text });
1744
1635
  }
1745
1636
  }
1746
1637
  return messages;
@@ -1766,32 +1657,31 @@ var OpenAIChatCompletionsMapper = class {
1766
1657
  return { items: [], tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1767
1658
  }
1768
1659
  if (message.reasoning_content) {
1769
- items.push({
1770
- type: "reasoning",
1771
- content: { type: "input_text", text: message.reasoning_content },
1772
- encryptedContent: void 0,
1773
- summary: []
1774
- });
1660
+ items.push(
1661
+ ReasoningItem.rehydrate({
1662
+ content: InputText.rehydrate({ text: message.reasoning_content }),
1663
+ encryptedContent: void 0,
1664
+ summary: []
1665
+ })
1666
+ );
1775
1667
  }
1776
1668
  if (message.content) {
1777
- items.push({
1778
- type: "model_message",
1779
- text: message.content
1780
- });
1669
+ items.push(ModelMessageItem.rehydrate({ text: message.content }));
1781
1670
  }
1782
1671
  for (const toolCall of (_c = message.tool_calls) != null ? _c : []) {
1783
- items.push({
1784
- type: "tool_use_request",
1785
- requestId: toolCall.id,
1786
- toolName: toolCall.function.name,
1787
- toolArguments: toolCall.function.arguments
1788
- });
1672
+ items.push(
1673
+ FunctionCallItem.rehydrate({
1674
+ callId: toolCall.id,
1675
+ name: toolCall.function.name,
1676
+ args: toolCall.function.arguments
1677
+ })
1678
+ );
1789
1679
  }
1790
1680
  return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1791
1681
  }
1792
1682
  };
1793
1683
 
1794
- // src/infrastructure/providers/openai/openai-chat-completions.ts
1684
+ // src/infrastructure/providers/openai/endpoints/openai-chat-completions.ts
1795
1685
  var import_openai2 = __toESM(require("openai"));
1796
1686
  var OpenAIChatCompletions = class {
1797
1687
  constructor(endpointMapper = new OpenAIChatCompletionsMapper(), config = {}) {
@@ -1807,18 +1697,18 @@ var OpenAIChatCompletions = class {
1807
1697
  apiKey: this.clientConfig.apiKey
1808
1698
  });
1809
1699
  }
1810
- buildRequest(inferenceRequest) {
1700
+ buildRequest(inferenceInput) {
1811
1701
  return {
1812
1702
  ...this.extraBody,
1813
- ...this.endpointMapper.toRequest(inferenceRequest)
1703
+ ...this.endpointMapper.toRequest(inferenceInput)
1814
1704
  };
1815
1705
  }
1816
- async infer(inferenceRequest) {
1817
- 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));
1818
1708
  return this.endpointMapper.toResponse(response);
1819
1709
  }
1820
- async *stream(inferenceRequest) {
1821
- 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));
1822
1712
  for await (const chunk of stream) {
1823
1713
  yield chunk;
1824
1714
  }
@@ -1827,7 +1717,7 @@ var OpenAIChatCompletions = class {
1827
1717
  type: "inference.output",
1828
1718
  payload: output,
1829
1719
  occurredAt: /* @__PURE__ */ new Date(),
1830
- producerId: inferenceRequest.model
1720
+ producerId: inferenceInput.model
1831
1721
  };
1832
1722
  }
1833
1723
  };
@@ -1843,8 +1733,8 @@ var claudeSonnet46Specification = {
1843
1733
  "system_message",
1844
1734
  "developer_message",
1845
1735
  "reasoning",
1846
- "tool_use_request",
1847
- "tool_use_result",
1736
+ "function_call",
1737
+ "function_call_output",
1848
1738
  "model_message"
1849
1739
  ],
1850
1740
  supportsStreaming: true,
@@ -1865,8 +1755,8 @@ var claudeOpus48Specification = {
1865
1755
  "system_message",
1866
1756
  "developer_message",
1867
1757
  "reasoning",
1868
- "tool_use_request",
1869
- "tool_use_result",
1758
+ "function_call",
1759
+ "function_call_output",
1870
1760
  "model_message"
1871
1761
  ],
1872
1762
  supportsStreaming: true,
@@ -1887,8 +1777,8 @@ var claudeOpus47Specification = {
1887
1777
  "system_message",
1888
1778
  "developer_message",
1889
1779
  "reasoning",
1890
- "tool_use_request",
1891
- "tool_use_result",
1780
+ "function_call",
1781
+ "function_call_output",
1892
1782
  "model_message"
1893
1783
  ],
1894
1784
  supportsStreaming: true,
@@ -1909,8 +1799,8 @@ var gemini35FlashSpecification = {
1909
1799
  "system_message",
1910
1800
  "developer_message",
1911
1801
  "reasoning",
1912
- "tool_use_request",
1913
- "tool_use_result",
1802
+ "function_call",
1803
+ "function_call_output",
1914
1804
  "model_message"
1915
1805
  ],
1916
1806
  supportsStreaming: true,
@@ -1931,8 +1821,8 @@ var gemini31ProSpecification = {
1931
1821
  "system_message",
1932
1822
  "developer_message",
1933
1823
  "reasoning",
1934
- "tool_use_request",
1935
- "tool_use_result",
1824
+ "function_call",
1825
+ "function_call_output",
1936
1826
  "model_message"
1937
1827
  ],
1938
1828
  supportsStreaming: true,
@@ -1953,8 +1843,8 @@ var deepSeekV4FlashSpecification = {
1953
1843
  "system_message",
1954
1844
  "developer_message",
1955
1845
  "reasoning",
1956
- "tool_use_request",
1957
- "tool_use_result",
1846
+ "function_call",
1847
+ "function_call_output",
1958
1848
  "model_message"
1959
1849
  ],
1960
1850
  supportsStreaming: true,
@@ -1975,8 +1865,8 @@ var deepSeekV4ProSpecification = {
1975
1865
  "system_message",
1976
1866
  "developer_message",
1977
1867
  "reasoning",
1978
- "tool_use_request",
1979
- "tool_use_result",
1868
+ "function_call",
1869
+ "function_call_output",
1980
1870
  "model_message"
1981
1871
  ],
1982
1872
  supportsStreaming: true,
@@ -1997,8 +1887,8 @@ var gpt54Specification = {
1997
1887
  "system_message",
1998
1888
  "developer_message",
1999
1889
  "reasoning",
2000
- "tool_use_request",
2001
- "tool_use_result",
1890
+ "function_call",
1891
+ "function_call_output",
2002
1892
  "model_message"
2003
1893
  ],
2004
1894
  supportsStreaming: true,
@@ -2019,8 +1909,8 @@ var gpt54MiniSpecification = {
2019
1909
  "system_message",
2020
1910
  "developer_message",
2021
1911
  "reasoning",
2022
- "tool_use_request",
2023
- "tool_use_result",
1912
+ "function_call",
1913
+ "function_call_output",
2024
1914
  "model_message"
2025
1915
  ],
2026
1916
  supportsStreaming: true,
@@ -2041,8 +1931,8 @@ var gpt54NanoSpecification = {
2041
1931
  "system_message",
2042
1932
  "developer_message",
2043
1933
  "reasoning",
2044
- "tool_use_request",
2045
- "tool_use_result",
1934
+ "function_call",
1935
+ "function_call_output",
2046
1936
  "model_message"
2047
1937
  ],
2048
1938
  supportsStreaming: true,
@@ -2063,8 +1953,8 @@ var gpt55Specification = {
2063
1953
  "system_message",
2064
1954
  "developer_message",
2065
1955
  "reasoning",
2066
- "tool_use_request",
2067
- "tool_use_result",
1956
+ "function_call",
1957
+ "function_call_output",
2068
1958
  "model_message"
2069
1959
  ],
2070
1960
  supportsStreaming: true,
@@ -2085,8 +1975,8 @@ var claudeHaiku45Specification = {
2085
1975
  "system_message",
2086
1976
  "developer_message",
2087
1977
  "reasoning",
2088
- "tool_use_request",
2089
- "tool_use_result",
1978
+ "function_call",
1979
+ "function_call_output",
2090
1980
  "model_message"
2091
1981
  ],
2092
1982
  supportsStreaming: true,
@@ -2096,12 +1986,12 @@ var claudeHaiku45Specification = {
2096
1986
  supportsStructuredOutput: true
2097
1987
  };
2098
1988
 
2099
- // src/infrastructure/providers/openai/models/gpt-6-luna.ts
2100
- var gpt6LunaSpecification = {
2101
- name: "gpt-6-luna",
1989
+ // src/infrastructure/providers/openai/models/gpt-6-astra.ts
1990
+ var gpt6AstraSpecification = {
1991
+ name: "gpt-6-astra",
2102
1992
  provider: "openai",
2103
1993
  supportsReasoningEffort: true,
2104
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
1994
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2105
1995
  supportedContextItemTypes: [
2106
1996
  "user_message",
2107
1997
  "system_message",
@@ -2118,12 +2008,12 @@ var gpt6LunaSpecification = {
2118
2008
  supportsStructuredOutput: true
2119
2009
  };
2120
2010
 
2121
- // src/infrastructure/providers/openai/models/gpt-6-sol.ts
2122
- var gpt6SolSpecification = {
2123
- name: "gpt-6-sol",
2011
+ // src/infrastructure/providers/openai/models/gpt-6-1-sol.ts
2012
+ var gpt61SolSpecification = {
2013
+ name: "gpt-6.1-sol",
2124
2014
  provider: "openai",
2125
2015
  supportsReasoningEffort: true,
2126
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
2016
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2127
2017
  supportedContextItemTypes: [
2128
2018
  "user_message",
2129
2019
  "system_message",
@@ -2140,12 +2030,12 @@ var gpt6SolSpecification = {
2140
2030
  supportsStructuredOutput: true
2141
2031
  };
2142
2032
 
2143
- // src/infrastructure/providers/openai/models/gpt-6-1-sol.ts
2144
- var gpt61SolSpecification = {
2145
- name: "gpt-6.1-sol",
2033
+ // src/infrastructure/providers/openai/models/gpt-6-sol.ts
2034
+ var gpt6SolSpecification = {
2035
+ name: "gpt-6-sol",
2146
2036
  provider: "openai",
2147
2037
  supportsReasoningEffort: true,
2148
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2038
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
2149
2039
  supportedContextItemTypes: [
2150
2040
  "user_message",
2151
2041
  "system_message",
@@ -2162,12 +2052,12 @@ var gpt61SolSpecification = {
2162
2052
  supportsStructuredOutput: true
2163
2053
  };
2164
2054
 
2165
- // src/infrastructure/providers/openai/models/gpt-6-astra.ts
2166
- var gpt6AstraSpecification = {
2167
- name: "gpt-6-astra",
2055
+ // src/infrastructure/providers/openai/models/gpt-6-luna.ts
2056
+ var gpt6LunaSpecification = {
2057
+ name: "gpt-6-luna",
2168
2058
  provider: "openai",
2169
2059
  supportsReasoningEffort: true,
2170
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2060
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
2171
2061
  supportedContextItemTypes: [
2172
2062
  "user_message",
2173
2063
  "system_message",
@@ -2184,9 +2074,9 @@ var gpt6AstraSpecification = {
2184
2074
  supportsStructuredOutput: true
2185
2075
  };
2186
2076
 
2187
- // src/infrastructure/providers/anthropic/models/claude-5-sonnet.ts
2188
- var claudeSonnet5Specification = {
2189
- name: "claude-sonnet-5",
2077
+ // src/infrastructure/providers/anthropic/models/claude-5-1-fable.ts
2078
+ var claudeFable51Specification = {
2079
+ name: "claude-fable-5-1",
2190
2080
  provider: "anthropic",
2191
2081
  supportsReasoningEffort: true,
2192
2082
  supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
@@ -2206,9 +2096,9 @@ var claudeSonnet5Specification = {
2206
2096
  supportsStructuredOutput: true
2207
2097
  };
2208
2098
 
2209
- // src/infrastructure/providers/anthropic/models/claude-5-5-sonnet.ts
2210
- var claudeSonnet55Specification = {
2211
- 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",
2212
2102
  provider: "anthropic",
2213
2103
  supportsReasoningEffort: true,
2214
2104
  supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
@@ -2228,9 +2118,9 @@ var claudeSonnet55Specification = {
2228
2118
  supportsStructuredOutput: true
2229
2119
  };
2230
2120
 
2231
- // src/infrastructure/providers/anthropic/models/claude-5-5-opus.ts
2232
- var claudeOpus55Specification = {
2233
- 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",
2234
2124
  provider: "anthropic",
2235
2125
  supportsReasoningEffort: true,
2236
2126
  supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
@@ -2250,9 +2140,9 @@ var claudeOpus55Specification = {
2250
2140
  supportsStructuredOutput: true
2251
2141
  };
2252
2142
 
2253
- // src/infrastructure/providers/anthropic/models/claude-5-1-fable.ts
2254
- var claudeFable51Specification = {
2255
- name: "claude-fable-5-1",
2143
+ // src/infrastructure/providers/anthropic/models/claude-5-sonnet.ts
2144
+ var claudeSonnet5Specification = {
2145
+ name: "claude-sonnet-5",
2256
2146
  provider: "anthropic",
2257
2147
  supportsReasoningEffort: true,
2258
2148
  supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
@@ -2272,12 +2162,12 @@ var claudeFable51Specification = {
2272
2162
  supportsStructuredOutput: true
2273
2163
  };
2274
2164
 
2275
- // src/infrastructure/providers/gemini/models/gemini-3-5-flash-lite.ts
2276
- var gemini35FlashLiteSpecification = {
2277
- 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",
2278
2168
  provider: "google",
2279
2169
  supportsReasoningEffort: true,
2280
- supportedReasoningEfforts: ["high", "medium", "low", "minimal"],
2170
+ supportedReasoningEfforts: ["high", "medium", "low"],
2281
2171
  supportedContextItemTypes: [
2282
2172
  "user_message",
2283
2173
  "system_message",
@@ -2294,12 +2184,12 @@ var gemini35FlashLiteSpecification = {
2294
2184
  supportsStructuredOutput: true
2295
2185
  };
2296
2186
 
2297
- // src/infrastructure/providers/gemini/models/gemini-3-8-flash.ts
2298
- var gemini38FlashSpecification = {
2299
- 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",
2300
2190
  provider: "google",
2301
2191
  supportsReasoningEffort: true,
2302
- supportedReasoningEfforts: ["high", "medium", "low"],
2192
+ supportedReasoningEfforts: ["high", "medium", "low", "minimal"],
2303
2193
  supportedContextItemTypes: [
2304
2194
  "user_message",
2305
2195
  "system_message",
@@ -2338,7 +2228,7 @@ var deepSeekFlashSpecification = {
2338
2228
  supportsStructuredOutput: false
2339
2229
  };
2340
2230
 
2341
- // src/infrastructure/providers/supported-models.ts
2231
+ // src/application/services/models.ts
2342
2232
  var supportedModels = [
2343
2233
  {
2344
2234
  endpoint: new OpenAIResponses(),
@@ -2434,181 +2324,268 @@ var supportedModels = [
2434
2324
  }
2435
2325
  ];
2436
2326
 
2437
- // src/domain/agent/loop/rule-engine.ts
2438
- var RuleEngine = class {
2439
- decide(agent, loop) {
2440
- const agentLoop = { agent, loop };
2441
- const satisfiedRules = loop.ruleBook.getRules().filter((rule) => rule.condition.isSatisfiedBy(agentLoop));
2442
- if (satisfiedRules.length === 0) {
2443
- 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;
2444
2335
  }
2445
- const highestPriorityRule = satisfiedRules.reduce((highest, current) => {
2446
- return highest.priority > current.priority ? highest : current;
2447
- });
2448
- return highestPriorityRule.action.execute(agentLoop);
2336
+ if (!model.supportsReasoningEffort) {
2337
+ return false;
2338
+ }
2339
+ return model.supportedReasoningEfforts.includes(inferenceInput.reasoningEffort);
2449
2340
  }
2450
2341
  };
2451
2342
 
2452
- // src/application/use-cases/run-loop.ts
2453
- var RunLoopUseCase = class {
2454
- constructor(agentRepository, loopRepository, directiveExecutionStrategyResolver) {
2455
- this.agentRepository = agentRepository;
2456
- this.loopRepository = loopRepository;
2457
- this.directiveExecutionStrategyResolver = directiveExecutionStrategyResolver;
2458
- 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";
2459
2347
  }
2460
- async execute(loopId) {
2461
- const loop = await this.loopRepository.findById(loopId);
2462
- if (!loop) {
2463
- throw new Error("Loop not found");
2464
- }
2465
- const agent = await this.agentRepository.findById(loop.getAgentId());
2466
- if (!agent) {
2467
- throw new Error("Agent not found");
2468
- }
2469
- while (loop.stateId !== "completed") {
2470
- const directive = this.ruleEngine.decide(agent, loop);
2471
- if (!directive) return loop;
2472
- const strategy = this.directiveExecutionStrategyResolver.resolve(directive);
2473
- await strategy.execute(directive, agent, loop);
2348
+ isValid(inferenceInput, model) {
2349
+ if (inferenceInput.tools === void 0) {
2350
+ return true;
2474
2351
  }
2475
- await this.loopRepository.save(loop);
2476
- return loop;
2352
+ return model.supportsFunctionCalling;
2477
2353
  }
2478
2354
  };
2479
2355
 
2480
- // src/infrastructure/memory/runtime-memory.ts
2481
- var RuntimeMemory = class {
2482
- constructor(context) {
2483
- this.context = context;
2484
- }
2485
- remember(items, participantId) {
2486
- 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";
2487
2360
  }
2488
- recall(topic, participantId) {
2489
- throw new Error("Method not implemented.");
2361
+ isValid(inferenceInput, model) {
2362
+ if (!inferenceInput.streaming) {
2363
+ return true;
2364
+ }
2365
+ return model.supportsStreaming;
2490
2366
  }
2491
2367
  };
2492
2368
 
2493
- // src/infrastructure/memory/runtime-memory-factory.ts
2494
- var RuntimeMemoryFactory = class {
2495
- create() {
2496
- const context = {
2497
- items: []
2498
- };
2499
- 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";
2500
2373
  }
2501
- };
2502
-
2503
- // src/application/directive-execution/directive-execution-strategy-resolver.ts
2504
- var DirectiveExecutionStrategyResolver = class {
2505
- constructor(strategies) {
2506
- this.strategies = strategies;
2374
+ if (item instanceof SystemMessageItem) {
2375
+ return "system_message";
2507
2376
  }
2508
- resolve(directive) {
2509
- return this.strategies[directive.type];
2377
+ if (item instanceof DeveloperMessageItem) {
2378
+ return "developer_message";
2510
2379
  }
2511
- };
2512
-
2513
- // src/application/directive-execution/complete-execution-strategy.ts
2514
- var CompleteExecutionStrategy = class {
2515
- async execute(directive, agent, loop) {
2516
- if (directive.type !== "complete") {
2517
- throw new Error("Expected a completion directive");
2518
- }
2519
- 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
+ );
2520
2393
  }
2521
2394
  };
2522
2395
 
2523
- // src/application/directive-execution/inference-execution-strategy.ts
2524
- var InferenceExecutionStrategy = class {
2525
- constructor(inferenceRunner) {
2526
- 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;
2527
2407
  }
2528
- async execute(directive, agent, loop) {
2529
- if (directive.type !== "inference") {
2530
- 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
+ }
2531
2413
  }
2532
- const pending = loop.requestInference(directive.request);
2533
- const result = await this.inferenceRunner.run(directive.request);
2534
- loop.receiveInferenceResult(pending.id, result);
2535
2414
  }
2536
2415
  };
2537
2416
 
2538
- // src/application/directive-execution/tool-use-execution-strategy.ts
2539
- var ToolUseExecutionStrategy = class {
2540
- constructor(toolRunner) {
2541
- 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;
2542
2422
  }
2543
- async execute(directive, agent, loop) {
2544
- if (directive.type !== "tool_use") {
2545
- throw new Error("Expected a tool-use directive");
2546
- }
2547
- const pending = loop.pending;
2548
- if ((pending == null ? void 0 : pending.type) !== "tool_execution") {
2549
- 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}`);
2550
2427
  }
2551
- const tool = agent.getTools().find((tool2) => tool2.name === directive.call.toolName);
2552
- if (!tool) {
2553
- 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}`);
2554
2435
  }
2555
- const result = await this.toolRunner.run(directive.call, tool);
2556
- loop.receiveToolUseResult(pending.id, result);
2436
+ this.requestValidator.validate(input, generativeModel.specification);
2437
+ yield* generativeModel.endpoint.stream(input);
2557
2438
  }
2558
2439
  };
2559
2440
 
2560
- // src/application/directive-execution/wait-execution-strategy.ts
2561
- var WaitExecutionStrategy = class {
2562
- async execute(directive, agent, loop) {
2563
- if (directive.type !== "wait") {
2564
- 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}`);
2565
2452
  }
2566
- loop.wait(directive.reason);
2567
2453
  }
2568
2454
  };
2569
2455
 
2570
- // src/agent-module.ts
2571
- function defineAgentModule(config) {
2572
- var _a, _b, _c, _d, _e, _f, _g;
2573
- const agentRepository = (_a = config.agentRepository) != null ? _a : new InMemoryAgentRepository();
2574
- const agentLoopRepository = (_b = config.agentLoopRepository) != null ? _b : new InMemoryLoopRepository();
2575
- const inferenceRunner = (_f = (_c = config.inferenceRunnerConfig) == null ? void 0 : _c.runner) != null ? _f : new DefaultInferenceRunner(
2576
- (_e = (_d = config.inferenceRunnerConfig) == null ? void 0 : _d.supportedModels) != null ? _e : supportedModels,
2577
- new InferenceRequestValidator()
2578
- );
2579
- const toolRunner = (_g = config.toolRunner) != null ? _g : new LocalToolRunner();
2580
- const memoryFactory = new RuntimeMemoryFactory();
2581
- const createAgentUseCase = new CreateAgentUseCase(agentRepository, memoryFactory);
2582
- const createLoopUseCase = new CreateAgentLoopUseCase(agentLoopRepository);
2583
- async function createAgent(config2) {
2584
- return await createAgentUseCase.execute(config2.name, config2.instruction, config2.tools, config2.handlers);
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;
2585
2484
  }
2586
- async function createLoop(params) {
2587
- return await createLoopUseCase.execute(params);
2485
+ function resolveRuntime() {
2486
+ if (!runtime) {
2487
+ throw new Error("Runtime not initialized");
2488
+ }
2489
+ return runtime;
2588
2490
  }
2589
- const directiveExecutionStrategyResolver = new DirectiveExecutionStrategyResolver({
2590
- inference: new InferenceExecutionStrategy(inferenceRunner),
2591
- tool_use: new ToolUseExecutionStrategy(toolRunner),
2592
- complete: new CompleteExecutionStrategy(),
2593
- wait: new WaitExecutionStrategy()
2594
- });
2595
- const runLoopUseCase = new RunLoopUseCase(agentRepository, agentLoopRepository, directiveExecutionStrategyResolver);
2596
- async function runLoop(loopId) {
2597
- 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;
2598
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);
2599
2506
  return {
2600
- createAgent,
2601
- createLoop,
2507
+ initializeRuntime,
2508
+ resolveRuntime,
2509
+ resolveParticipant,
2510
+ join,
2511
+ leave,
2512
+ sendMessage,
2513
+ sendEvent,
2602
2514
  runLoop
2603
2515
  };
2604
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
+ };
2605
2559
  // Annotate the CommonJS export names for ESM import in node:
2606
2560
  0 && (module.exports = {
2607
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,
2608
2578
  Participant,
2579
+ ReasoningItem,
2580
+ RuntimeState,
2581
+ SemanticEvent,
2609
2582
  SituationSpecification,
2610
- SpaceEvent,
2611
- defineAgentModule,
2612
- defineRuntime
2583
+ SystemMessageItem,
2584
+ TokenUsage,
2585
+ UserMessageItem,
2586
+ createAgent,
2587
+ createHuman,
2588
+ defineRuntime,
2589
+ supportedModels
2613
2590
  });
2614
2591
  //# sourceMappingURL=index.js.map