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