@mozaik-ai/core 4.2.0-beta.9 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,1113 +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;
122
+ this.args = args;
192
123
  }
193
- getId() {
194
- return this.id;
195
- }
196
- getName() {
197
- return this.name;
198
- }
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 {
368
- constructor(id, name, instruction, tools, memory) {
369
- this._id = id;
370
- this._name = name;
371
- this._instruction = instruction;
372
- this._memory = memory;
373
- this._tools = tools;
374
- }
375
- get id() {
376
- return this._id;
377
- }
378
- get name() {
379
- return this._name;
380
- }
381
- get instruction() {
382
- return this._instruction;
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: {} });
383
209
  }
384
- get tools() {
385
- return this._tools;
210
+ async connect() {
211
+ if (this.connected) return;
212
+ await this.client.connect(this.transport);
213
+ this.connected = true;
386
214
  }
387
- get memory() {
388
- 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
+ });
389
228
  }
390
- static create({
391
- name,
392
- instruction,
393
- tools,
394
- memory
395
- }) {
396
- const id = UuidGenerator.create();
397
- return new _Agent(id, name, instruction, tools, memory);
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;
398
238
  }
399
- static rehydrate(record) {
400
- return new _Agent(record.id, record.name, record.instruction, record.tools, record.memory);
239
+ async close() {
240
+ if (!this.connected) return;
241
+ try {
242
+ await this.client.close();
243
+ } catch (e) {
244
+ }
245
+ this.connected = false;
401
246
  }
402
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
+ }
403
253
 
404
- // src/application/use-cases/create-agent.ts
405
- var CreateAgentUseCase = class {
406
- constructor(agentRepository, memoryFactory) {
407
- this.agentRepository = agentRepository;
408
- 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;
409
279
  }
410
- async execute(name, instruction, tools) {
411
- const memory = this.memoryFactory.create();
412
- const agent = Agent.create({ name, instruction, tools, memory });
413
- await this.agentRepository.save(agent);
414
- return agent;
280
+ /** Close all underlying MCP connections. */
281
+ async close() {
282
+ await Promise.all(this.clients.map((c) => c.close()));
415
283
  }
416
284
  };
417
285
 
418
- // src/infrastructure/repositories/in-memory-agent-repository.ts
419
- var InMemoryAgentRepository = class {
420
- constructor() {
421
- this.agents = [];
422
- }
423
- exists(id) {
424
- return Promise.resolve(this.agents.some((agent) => agent.getManifest().id === id));
425
- }
426
- findById(id) {
427
- 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;
428
293
  }
429
- findAll() {
430
- return Promise.resolve(this.agents);
294
+ static create(text) {
295
+ const content = InputText.create(text);
296
+ return new _SystemMessageItem(content);
431
297
  }
432
- async save(agent) {
433
- this.agents.push(agent);
298
+ static rehydrate(data) {
299
+ const content = InputText.rehydrate(data);
300
+ return new _SystemMessageItem(content);
434
301
  }
435
302
  };
436
303
 
437
- // src/domain/agent/loop/specification.ts
438
- var LoopSpecification = class {
439
- and(other) {
440
- 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;
441
311
  }
442
- or(other) {
443
- 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);
444
315
  }
445
- not() {
446
- return new NotLoopSpecification(this);
316
+ };
317
+ var ParticipantJoinedEvent = class extends SemanticEvent {
318
+ static init(manifest) {
319
+ return SemanticEvent.create("participant.joined", manifest.id, manifest);
447
320
  }
448
321
  };
449
- var AndLoopSpecification = class extends LoopSpecification {
450
- constructor(left, right) {
451
- super();
452
- this.left = left;
453
- this.right = right;
322
+ var ParticipantLeftEvent = class extends SemanticEvent {
323
+ static init(manifest) {
324
+ return SemanticEvent.create("participant.left", manifest.id, manifest);
454
325
  }
455
- isSatisfiedBy(agentLoop) {
456
- 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 });
457
330
  }
458
331
  };
459
- var OrLoopSpecification = class extends LoopSpecification {
460
- constructor(left, right) {
461
- super();
462
- this.left = left;
463
- 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";
464
338
  }
465
- isSatisfiedBy(agentLoop) {
466
- 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
+ };
467
348
  }
468
349
  };
469
- var NotLoopSpecification = class extends LoopSpecification {
470
- constructor(rule) {
471
- super();
472
- 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;
473
356
  }
474
- isSatisfiedBy(agentLoop) {
475
- return !this.rule.isSatisfiedBy(agentLoop);
357
+ getManifest() {
358
+ return this.manifest;
476
359
  }
477
- };
478
- var AwaitingInference = class extends LoopSpecification {
479
- isSatisfiedBy(agentLoop) {
480
- return agentLoop.loop.stateId === "awaiting_inference";
360
+ getId() {
361
+ return this.manifest.id;
481
362
  }
482
- };
483
- var AwaitingRequest = class extends LoopSpecification {
484
- isSatisfiedBy(agentLoop) {
485
- return agentLoop.loop.stateId === "awaiting_inference_request";
363
+ getHandlers() {
364
+ return this.handlers;
486
365
  }
487
- };
488
- var AwaitingToolOutput = class extends LoopSpecification {
489
- isSatisfiedBy(agentLoop) {
490
- return agentLoop.loop.stateId === "awaiting_tool_output";
366
+ setHandlers(handlers) {
367
+ this.handlers = handlers;
491
368
  }
492
369
  };
493
- var ModelAnswered = class extends LoopSpecification {
494
- isSatisfiedBy(agentLoop) {
495
- const operations = agentLoop.loop.completedOperations;
496
- const lastOperation = operations[operations.length - 1];
497
- if ((lastOperation == null ? void 0 : lastOperation.type) !== "inference") {
498
- return false;
499
- }
500
- 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);
501
382
  }
502
383
  };
503
384
 
504
- // src/domain/agent/loop/action.ts
505
- var LoopAction = class {
506
- };
507
- var RequestPreparationAction = class extends LoopAction {
508
- constructor(request) {
509
- super();
510
- 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;
511
392
  }
512
- execute(agentLoop) {
513
- return {
514
- type: "inference",
515
- request: this.request
516
- };
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);
517
406
  }
518
- };
519
- var InferenceAction = class extends LoopAction {
520
- execute(agentLoop) {
521
- const request = agentLoop.loop.request;
522
- if (!request) {
523
- return { type: "wait", reason: "no request" };
524
- }
525
- return { type: "inference", request };
407
+ getTools() {
408
+ return this.tools;
526
409
  }
527
- };
528
- var ToolUseAction = class extends LoopAction {
529
- execute(agentLoop) {
530
- if (!agentLoop.loop.pending) {
531
- return { type: "wait" };
532
- }
533
- const pendingOperation = agentLoop.loop.pending;
534
- if (pendingOperation.type === "tool_execution") {
535
- return { type: "tool_use", call: pendingOperation.call };
536
- }
537
- return { type: "wait" };
410
+ getDeveloperMessage() {
411
+ return this.developerMessage;
412
+ }
413
+ getMemory() {
414
+ return this.memory;
538
415
  }
539
416
  };
540
- var CompleteAction = class extends LoopAction {
541
- constructor(reason) {
542
- super();
543
- 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);
544
433
  }
545
- execute() {
546
- 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);
547
442
  }
548
443
  };
549
444
 
550
- // src/domain/agent/loop/rule.ts
551
- var LoopRule = class _LoopRule {
552
- constructor(id, condition, action, priority) {
553
- this._id = id;
554
- this._priority = priority;
555
- this._condition = condition;
556
- this._action = action;
557
- }
558
- get id() {
559
- return this._id;
560
- }
561
- get priority() {
562
- 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();
563
458
  }
564
- get condition() {
565
- 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);
566
463
  }
567
- get action() {
568
- return this._action;
464
+ removeParticipant(participant) {
465
+ this.participants.delete(participant.getId());
569
466
  }
570
- static create(spec) {
571
- var _a;
572
- const priority = (_a = spec.priority) != null ? _a : 0;
573
- const id = crypto.randomUUID();
574
- return new _LoopRule(id, spec.when, spec.then, priority);
467
+ getParticipant(id) {
468
+ return this.participants.get(id);
575
469
  }
576
- static rehydrate(spec) {
577
- var _a;
578
- const priority = (_a = spec.priority) != null ? _a : 0;
579
- const rule = new _LoopRule(spec.id, spec.condition, spec.action, priority);
580
- return rule;
470
+ getParticipants() {
471
+ return [...this.participants.values()];
581
472
  }
582
473
  };
583
- var RuleBook = class _RuleBook {
584
- constructor(rules) {
585
- 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;
586
482
  }
587
- addRule(rule) {
588
- this.rules.push(rule);
483
+ join(participant) {
484
+ this.state.addParticipant(participant);
485
+ this.publish(ParticipantJoinedEvent.init(participant.getManifest()));
589
486
  }
590
- removeRule(rule) {
591
- 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()));
592
490
  }
593
- getRules() {
594
- return this.rules;
491
+ publish(event) {
492
+ for (const participant of this.state.getParticipants()) {
493
+ this.processor.process(event, participant);
494
+ }
595
495
  }
596
- static create(loopRuleParams) {
597
- const rules = loopRuleParams.map((param) => LoopRule.create(param));
598
- 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);
599
501
  }
600
- static rehydrate(record) {
601
- const rules = record.rules.map((rule) => LoopRule.rehydrate(rule));
602
- return new _RuleBook(rules);
502
+ getInferenceRunner() {
503
+ return this.inferenceRunner;
603
504
  }
604
- record() {
605
- return {
606
- rules: this.rules.map((rule) => ({
607
- id: rule.id,
608
- priority: rule.priority,
609
- condition: rule.condition,
610
- action: rule.action
611
- }))
612
- };
505
+ getFunctionCallRunner() {
506
+ return this.functionCallRunner;
613
507
  }
614
508
  };
615
- var defaultRules = (request) => [
616
- {
617
- when: new AwaitingRequest(),
618
- then: new RequestPreparationAction(request)
619
- },
620
- {
621
- when: new AwaitingInference(),
622
- then: new InferenceAction()
623
- },
624
- {
625
- when: new AwaitingToolOutput(),
626
- then: new ToolUseAction()
627
- },
628
- {
629
- when: new ModelAnswered(),
630
- 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
+ }
631
522
  }
632
- ];
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
+ }
633
551
 
634
- // src/domain/agent/loop/loop.ts
635
- var Loop = class _Loop {
636
- 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) {
637
555
  this.loopId = loopId;
638
- this.agentId = agentId;
639
- this.subject = subject;
640
- this.createdAt = createdAt;
641
- this.state = state;
642
- this.inferenceRequest = inferenceRequest;
643
- this.pendingOperation = pendingOperation;
644
- this.transitionHistory = transitionHistory;
645
- this.operationHistory = operationHistory;
646
- this._ruleBook = ruleBook;
647
- }
648
- get id() {
649
- return this.loopId;
650
- }
651
- get stateId() {
652
- return this.state;
556
+ this.stateExecutor = stateExecutor;
557
+ this.transitionResolver = transitionResolver;
558
+ this.interceptionHandler = interceptionHandler;
653
559
  }
654
- get pending() {
655
- return this.pendingOperation;
656
- }
657
- get history() {
658
- 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
+ }
659
576
  }
660
- get completedOperations() {
661
- return this.operationHistory;
577
+ getLoopId() {
578
+ return this.loopId;
662
579
  }
663
- get request() {
664
- return this.inferenceRequest;
580
+ static create(stateExecutor, transitionResolver, interceptionHandler) {
581
+ const loopId = crypto.randomUUID();
582
+ return new _AgentLoop(loopId, stateExecutor, transitionResolver, interceptionHandler);
665
583
  }
666
- get ruleBook() {
667
- 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;
668
594
  }
669
- getSubject() {
670
- 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
+ }
671
608
  }
672
- getAgentId() {
673
- 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";
674
616
  }
675
- 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);
676
633
  return {
677
- id: this.id,
678
- agentId: this.agentId,
679
- subject: this.subject,
680
- createdAt: this.createdAt,
681
- state: this.state,
682
- inferenceRequest: this.inferenceRequest,
683
- pendingOperation: this.pendingOperation,
684
- transitionHistory: [...this.transitionHistory],
685
- operationHistory: [...this.operationHistory],
686
- ruleBook: this.ruleBook.record()
634
+ stateId: this.id,
635
+ input,
636
+ output: {
637
+ item
638
+ }
687
639
  };
688
640
  }
689
- moveToIdle(reason, transitionId) {
690
- this.transitionTo("idle", reason, transitionId);
691
- this.pendingOperation = void 0;
692
- }
693
- moveToAwaitingInference(operation) {
694
- this.assertAwaitingInferenceRequest();
695
- this.pendingOperation = operation;
696
- this.transitionTo("awaiting_inference", "inference_requested", operation.id);
697
- }
698
- moveToAwaitingToolOutput(operation, occurredAt) {
699
- this.assertIdle();
700
- this.pendingOperation = operation;
701
- this.transitionTo("awaiting_tool_output", "tool_execution_requested", operation.id);
702
- }
703
- requestInference(request) {
704
- this.assertAwaitingInferenceRequest();
705
- this.inferenceRequest = request;
706
- const operation = {
707
- id: UuidGenerator.create(),
708
- type: "inference",
709
- requestedAt: SystemClock.now(),
710
- 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])
711
654
  };
712
- this.moveToAwaitingInference(operation);
713
- return operation;
714
- }
715
- requestToolUse(operationId, call, requestedAt) {
716
- this.assertIdle();
717
- const operation = {
718
- id: operationId,
719
- type: "tool_execution",
720
- requestedAt,
721
- call
655
+ loopVisitor.visitMessageReceivedCompleted(output);
656
+ return {
657
+ stateId: this.id,
658
+ input,
659
+ output
722
660
  };
723
- this.moveToAwaitingToolOutput(operation, requestedAt);
724
- return operation;
725
- }
726
- transitionTo(nextState, reason, operationId) {
727
- const occurredAt = SystemClock.now();
728
- const previousState = this.state;
729
- this.state = nextState;
730
- this.transitionHistory.push({
731
- occurredAt,
732
- previousState,
733
- nextState,
734
- reason,
735
- operationId
736
- });
737
- }
738
- assertIdle() {
739
- if (this.state !== "idle") {
740
- throw new Error(`Expected idle loop, but loop is ${this.state}`);
741
- }
742
- }
743
- assertAwaitingInferenceRequest() {
744
- if (this.state !== "awaiting_inference_request") {
745
- throw new Error(`Expected awaiting inference request loop, but loop is ${this.state}`);
746
- }
747
- }
748
- receiveInferenceResult(operationId, result) {
749
- if (this.state !== "awaiting_inference") {
750
- throw new Error(`Cannot receive inference result while loop is ${this.state}`);
751
- }
752
- const operation = this.pendingOperation;
753
- if ((operation == null ? void 0 : operation.type) !== "inference" || operation.id !== operationId) {
754
- throw new Error(`Inference result does not match pending operation ${operationId}`);
755
- }
756
- if (!this.inferenceRequest) {
757
- throw new Error("Inference request is not provided");
758
- }
759
- this.moveToIdle("inference_completed", operationId);
760
- this.operationHistory.push({
761
- type: "inference",
762
- operationId,
763
- requestedAt: operation.requestedAt,
764
- completedAt: SystemClock.now(),
765
- request: operation.request,
766
- result
767
- });
768
- this.inferenceRequest.context.items.push(...result.items);
769
- const call = result.items.find((item) => item.type === "tool_use_request");
770
- if (call) {
771
- this.pendingOperation = {
772
- id: call.requestId,
773
- type: "tool_execution",
774
- requestedAt: SystemClock.now(),
775
- call
776
- };
777
- this.transitionTo("awaiting_tool_output", "tool_use_requested", call.requestId);
778
- return;
779
- }
780
- this.pendingOperation = void 0;
781
661
  }
782
- receiveToolUseResult(operationId, result) {
783
- if (this.state !== "awaiting_tool_output") {
784
- throw new Error(`Cannot receive tool output while loop is ${this.state}`);
785
- }
786
- const operation = this.pendingOperation;
787
- if ((operation == null ? void 0 : operation.type) !== "tool_execution" || operation.id !== operationId) {
788
- throw new Error(`Tool output does not match pending operation ${operationId}`);
789
- }
790
- if (!this.inferenceRequest) {
791
- throw new Error("Inference request is not provided");
792
- }
793
- this.operationHistory.push({
794
- type: "tool_use",
795
- operationId,
796
- requestedAt: operation.requestedAt,
797
- completedAt: SystemClock.now(),
798
- call: operation.call,
799
- result
800
- });
801
- this.inferenceRequest.context.items.push(result);
802
- this.pendingOperation = void 0;
803
- this.transitionTo("awaiting_inference_request", "tool_use_completed", operationId);
804
- }
805
- complete(reason) {
806
- this.assertNotSettled("complete");
807
- this.pendingOperation = void 0;
808
- this.transitionTo("completed", reason);
809
- }
810
- stop(reason) {
811
- this.assertNotSettled("stop");
812
- this.pendingOperation = void 0;
813
- this.transitionTo("stopped", reason);
814
- }
815
- wait(reason) {
816
- this.assertNotSettled("wait");
817
- this.pendingOperation = void 0;
818
- this.transitionTo("idle", reason);
819
- }
820
- assertNotSettled(intent) {
821
- if (this.state === "completed" || this.state === "stopped") {
822
- throw new Error(`Cannot ${intent} a loop that is already ${this.state}`);
823
- }
824
- }
825
- static create(agentId, subject, ruleBook) {
826
- const createdAt = SystemClock.now();
827
- const id = UuidGenerator.create();
828
- return new _Loop(
829
- id,
830
- agentId,
831
- subject,
832
- createdAt,
833
- "awaiting_inference_request",
834
- void 0,
835
- void 0,
836
- [],
837
- [],
838
- ruleBook
839
- );
662
+ };
663
+
664
+ // src/application/states/model-message.ts
665
+ var ModelMessageState = class {
666
+ constructor() {
667
+ this.id = "model_message";
840
668
  }
841
- static rehydrate(record) {
842
- return new _Loop(
843
- record.id,
844
- record.agentId,
845
- record.subject,
846
- record.createdAt,
847
- record.state,
848
- record.inferenceRequest,
849
- record.pendingOperation,
850
- [...record.transitionHistory],
851
- [...record.operationHistory],
852
- RuleBook.rehydrate(record.ruleBook)
853
- );
669
+ async run(input, loopVisitor) {
670
+ loopVisitor.visitModelAnswer(input);
671
+ return {
672
+ stateId: this.id,
673
+ input,
674
+ output: void 0
675
+ };
854
676
  }
855
677
  };
856
678
 
857
- // src/application/use-cases/create-loop.ts
858
- var CreateAgentLoopUseCase = class {
859
- constructor(loopRepository) {
860
- this.loopRepository = loopRepository;
679
+ // src/domain/agentic-environment/loop/transition-resolver.ts
680
+ var TransitionResolver = class {
681
+ constructor(rules) {
682
+ this.rules = rules;
861
683
  }
862
- async execute(params) {
863
- if ("rules" in params) {
864
- const ruleBook = RuleBook.create(params.rules);
865
- const loop = Loop.create(params.agentId, params.subject, ruleBook);
866
- await this.loopRepository.save(loop);
867
- return loop;
868
- } else {
869
- const ruleBook = RuleBook.create(defaultRules(params.request));
870
- const loop = Loop.create(params.agentId, params.subject, ruleBook);
871
- await this.loopRepository.save(loop);
872
- 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}"`);
873
688
  }
689
+ return rule.createTransition(execution);
874
690
  }
875
691
  };
876
692
 
877
- // src/infrastructure/repositories/in-memory-loop-repository.ts
878
- var InMemoryLoopRepository = class {
879
- constructor() {
880
- this.loops = [];
693
+ // src/domain/agentic-environment/loop/transition-specification.ts
694
+ var MessageReceivedSpecification = class {
695
+ isSatisfiedBy(execution) {
696
+ return execution.stateId === "message_received";
881
697
  }
882
- findById(id) {
883
- 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");
884
705
  }
885
- save(loop) {
886
- const index = this.loops.findIndex((stored) => stored.id === loop.id);
887
- if (index === -1) {
888
- this.loops.push(loop);
889
- } else {
890
- this.loops[index] = loop;
891
- }
892
- 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");
893
710
  }
894
711
  };
895
-
896
- // src/domain/inference/tool-use-item-factory.ts
897
- var ToolUseItemFactory = class {
898
- create(toolUseRequest, result) {
899
- const toolUseResult = {
900
- type: "tool_use_result",
901
- requestId: toolUseRequest.requestId,
902
- result: {
903
- type: "input_text",
904
- text: result
905
- }
906
- };
907
- 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";
908
720
  }
909
721
  };
910
722
 
911
- // src/application/runners/local-tool-runner.ts
912
- var LocalToolRunner = class {
723
+ // src/domain/agentic-environment/loop/transition-rule.ts
724
+ var ContextPreparationToInferenceRule = class {
913
725
  constructor() {
914
- this.toolUseItemFactory = new ToolUseItemFactory();
726
+ this.specification = new MessageReceivedSpecification();
915
727
  }
916
- async run(input, tool) {
917
- try {
918
- const result = await tool.invoke(JSON.parse(input.toolArguments));
919
- const resultText = typeof result === "string" ? result : JSON.stringify(result);
920
- return this.toolUseItemFactory.create(input, resultText);
921
- } catch (error) {
922
- const errorText = `Error calling tool: ${error}`;
923
- return this.toolUseItemFactory.create(input, errorText);
728
+ createTransition(execution) {
729
+ if (execution.stateId !== "message_received") {
730
+ throw new Error("Expected context_preparation execution");
924
731
  }
732
+ const nextStateId = execution.output.streaming ? "inference_streaming" : "inference";
733
+ return {
734
+ nextStateId,
735
+ input: execution.output
736
+ };
925
737
  }
926
738
  };
927
-
928
- // src/application/runners/inference-runner.ts
929
- var DefaultInferenceRunner = class {
930
- constructor(supportedModels2, requestValidator) {
931
- this.supportedModels = supportedModels2;
932
- this.requestValidator = requestValidator;
739
+ var InferenceToFunctionCallRule = class {
740
+ constructor() {
741
+ this.specification = new InferenceProducedFunctionCallSpecification();
933
742
  }
934
- async run(input) {
935
- const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
936
- if (!generativeModel) {
937
- 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");
938
746
  }
939
- this.requestValidator.validate(input, generativeModel.specification);
940
- return await generativeModel.endpoint.infer(input);
941
- }
942
- async *stream(input) {
943
- const generativeModel = this.supportedModels.find((model) => model.specification.name === input.model);
944
- if (!generativeModel) {
945
- 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");
946
750
  }
947
- this.requestValidator.validate(input, generativeModel.specification);
948
- yield* generativeModel.endpoint.stream(input);
751
+ return {
752
+ nextStateId: "function_call",
753
+ input: {
754
+ call: functionCallItem,
755
+ inferenceInput: execution.input
756
+ }
757
+ };
949
758
  }
950
759
  };
951
-
952
- // src/domain/inference/request-validation/reasoning-effort.ts
953
- var ReasoningEffortValidation = class {
760
+ var InferenceToModelMessageRule = class {
954
761
  constructor() {
955
- this.name = "reasoning-effort";
762
+ this.specification = new InferenceProducedModelMessageSpecification();
956
763
  }
957
- isValid(inferenceRequest, model) {
958
- if (inferenceRequest.reasoningEffort === void 0) {
959
- 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");
960
767
  }
961
- if (!model.supportsReasoningEffort) {
962
- 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");
963
773
  }
964
- 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
+ };
965
781
  }
966
782
  };
967
-
968
- // src/domain/inference/request-validation/tool-calling.ts
969
- var ToolUseRequestingValidation = class {
783
+ var FunctionCallToInferenceRule = class {
970
784
  constructor() {
971
- this.name = "tool-calling";
785
+ this.specification = new FunctionCallCompletedSpecification();
972
786
  }
973
- isValid(inferenceRequest, model) {
974
- if (inferenceRequest.tools === void 0) {
975
- return true;
787
+ createTransition(execution) {
788
+ if (execution.stateId !== "function_call") {
789
+ throw new Error("Expected function_call execution");
976
790
  }
977
- 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
+ };
978
799
  }
979
800
  };
980
-
981
- // src/domain/inference/request-validation/streaming.ts
982
- var StreamingValidation = class {
801
+ var ModelMessageToIdleRule = class {
983
802
  constructor() {
984
- this.name = "streaming";
803
+ this.specification = new ModelMessageCompletedSpecification();
985
804
  }
986
- isValid(inferenceRequest, model) {
987
- if (!inferenceRequest.streaming) {
988
- return true;
805
+ createTransition(execution) {
806
+ if (execution.stateId !== "model_message") {
807
+ throw new Error("Expected model_message execution");
989
808
  }
990
- return model.supportsStreaming;
809
+ return {
810
+ nextStateId: "idle",
811
+ input: void 0
812
+ };
991
813
  }
992
814
  };
993
815
 
994
- // src/domain/inference/request-validation/structured-output.ts
995
- var StructuredOutputValidation = class {
996
- constructor() {
997
- 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();
998
824
  }
999
- isValid(inferenceRequest, model) {
1000
- if (inferenceRequest.structuredOutput === void 0) {
1001
- return true;
1002
- }
1003
- return model.supportsStructuredOutput;
825
+ visitMessageReceivedStarted(input) {
826
+ this.publish("message_received.started", input);
1004
827
  }
1005
- };
1006
-
1007
- // src/domain/inference/request-validation/context.ts
1008
- function getContextItemValidationKey(item) {
1009
- if (item.type === "user_message") {
1010
- return "user_message";
828
+ visitMessageReceivedCompleted(output) {
829
+ this.publish("message_received.completed", output);
1011
830
  }
1012
- if (item.type === "system_message") {
1013
- return "system_message";
831
+ visitInferenceStarted(input) {
832
+ this.publish("inference.started", input);
1014
833
  }
1015
- if (item.type === "developer_message") {
1016
- return "developer_message";
834
+ visitInferenceEvent(event) {
835
+ this.publish("inference.stream", event);
1017
836
  }
1018
- if (item.type === "model_message") {
1019
- return "model_message";
837
+ visitInferenceCompleted(output) {
838
+ this.publish("inference.completed", output);
1020
839
  }
1021
- return item.type;
1022
- }
1023
- var ContextValidation = class {
1024
- constructor() {
1025
- this.name = "context";
840
+ visitFunctionCallStarted(input) {
841
+ this.publish("function_call.started", input);
1026
842
  }
1027
- isValid(inferenceRequest, model) {
1028
- return inferenceRequest.context.items.every(
1029
- (item) => model.supportedContextItemTypes.includes(getContextItemValidationKey(item))
1030
- );
843
+ visitFunctionCallCompleted(output) {
844
+ this.publish("function_call.completed", output);
1031
845
  }
1032
- };
1033
-
1034
- // src/domain/inference/request-validation/inference-request-validator.ts
1035
- var defaultRequestValidationRules = [
1036
- new ReasoningEffortValidation(),
1037
- new ToolUseRequestingValidation(),
1038
- new StreamingValidation(),
1039
- new StructuredOutputValidation(),
1040
- new ContextValidation()
1041
- ];
1042
- var InferenceRequestValidator = class {
1043
- constructor(rules = defaultRequestValidationRules) {
1044
- this.rules = rules;
846
+ visitModelAnswer(input) {
847
+ this.publish("model.answer", input);
1045
848
  }
1046
- validate(inferenceRequest, model) {
1047
- for (const rule of this.rules) {
1048
- if (!rule.isValid(inferenceRequest, model)) {
1049
- 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
+ });
1050
878
  }
1051
879
  }
1052
880
  }
1053
881
  };
1054
882
 
1055
- // src/domain/inference/token-usage.ts
1056
- var InputTokenDetails = class {
1057
- constructor(cached_tokens) {
1058
- this.cached_tokens = cached_tokens;
1059
- }
1060
- };
1061
- var OutputTokenDetails = class {
1062
- constructor(reasoning_tokens) {
1063
- this.reasoning_tokens = reasoning_tokens;
1064
- }
1065
- };
1066
- var TokenUsage = class {
1067
- constructor(inputTokens, outputTokens, totalTokens, inputTokenDetails, outputTokenDetails) {
1068
- this.inputTokens = inputTokens;
1069
- this.outputTokens = outputTokens;
1070
- this.totalTokens = totalTokens;
1071
- this.inputTokenDetails = inputTokenDetails;
1072
- 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
+ };
1073
907
  }
1074
908
  };
1075
909
 
1076
- // 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
1077
944
  var AnthropicMessagesMapper = class {
1078
- toRequest(inferenceRequest) {
1079
- const { messages, system } = this.mapContextItems(inferenceRequest);
945
+ toRequest(inferenceInput) {
946
+ const { messages, system } = this.mapContextItems(inferenceInput);
1080
947
  const outputConfig = {};
1081
948
  const request = {
1082
- model: inferenceRequest.model,
949
+ model: inferenceInput.model,
1083
950
  messages
1084
951
  };
1085
- request.max_tokens = inferenceRequest.maxOutputTokens;
952
+ request.max_tokens = inferenceInput.maxOutputTokens;
1086
953
  if (system) {
1087
954
  request.system = system;
1088
955
  }
1089
- if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1090
- request.tools = inferenceRequest.tools.map((tool) => ({
956
+ if (inferenceInput.tools && inferenceInput.tools.length > 0) {
957
+ request.tools = inferenceInput.tools.map((tool) => ({
1091
958
  name: tool.name,
1092
959
  description: tool.description,
1093
960
  input_schema: tool.parameters
1094
961
  }));
1095
962
  }
1096
- if (inferenceRequest.structuredOutput) {
963
+ if (inferenceInput.structuredOutput) {
1097
964
  outputConfig.format = {
1098
965
  type: "json_schema",
1099
- schema: inferenceRequest.structuredOutput.schema
966
+ schema: inferenceInput.structuredOutput.schema
1100
967
  };
1101
968
  }
1102
- if (inferenceRequest.reasoningEffort) {
969
+ if (inferenceInput.reasoningEffort) {
1103
970
  request.thinking = { type: "adaptive" };
1104
- outputConfig.effort = inferenceRequest.reasoningEffort;
971
+ outputConfig.effort = inferenceInput.reasoningEffort;
1105
972
  }
1106
973
  if (Object.keys(outputConfig).length > 0) {
1107
974
  request.output_config = outputConfig;
1108
975
  }
1109
- if (inferenceRequest.streaming) {
1110
- request.stream = inferenceRequest.streaming;
976
+ if (inferenceInput.streaming) {
977
+ request.stream = inferenceInput.streaming;
1111
978
  }
1112
979
  return request;
1113
980
  }
@@ -1122,55 +989,52 @@ var AnthropicMessagesMapper = class {
1122
989
  content: [block]
1123
990
  });
1124
991
  }
1125
- mapContextItems(inferenceRequest) {
992
+ mapContextItems(inferenceInput) {
1126
993
  var _a, _b, _c;
1127
- const context = inferenceRequest.context;
994
+ const context = inferenceInput.context;
1128
995
  const messages = [];
1129
996
  const system = [];
1130
- for (const item of context.items) {
1131
- if (item.type === "developer_message" || item.type === "system_message") {
1132
- 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);
1133
1000
  continue;
1134
1001
  }
1135
- if (item.type === "user_message") {
1136
- 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 });
1137
1004
  continue;
1138
1005
  }
1139
- if (item.type === "model_message") {
1140
- 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 });
1141
1008
  continue;
1142
1009
  }
1143
- if (item.type === "reasoning") {
1144
- const reasoning = item;
1010
+ if (item instanceof ReasoningItem) {
1145
1011
  this.addContentBlock(messages, "assistant", {
1146
1012
  type: "thinking",
1147
- thinking: (_b = (_a = reasoning.content) == null ? void 0 : _a.text) != null ? _b : "",
1148
- 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 : ""
1149
1015
  });
1150
1016
  continue;
1151
1017
  }
1152
- if (item.type === "tool_use_request") {
1153
- const toolUseRequest = item;
1018
+ if (item instanceof FunctionCallItem) {
1154
1019
  let input;
1155
1020
  try {
1156
- input = JSON.parse(toolUseRequest.toolArguments);
1021
+ input = JSON.parse(item.args);
1157
1022
  } catch (e) {
1158
- input = toolUseRequest.toolArguments;
1023
+ input = item.args;
1159
1024
  }
1160
1025
  this.addContentBlock(messages, "assistant", {
1161
1026
  type: "tool_use",
1162
- id: toolUseRequest.requestId,
1163
- name: toolUseRequest.toolName,
1027
+ id: item.callId,
1028
+ name: item.name,
1164
1029
  input
1165
1030
  });
1166
1031
  continue;
1167
1032
  }
1168
- if (item.type === "tool_use_result") {
1169
- const toolUseResult = item;
1033
+ if (item instanceof FunctionCallOutputItem) {
1170
1034
  this.addContentBlock(messages, "user", {
1171
1035
  type: "tool_result",
1172
- tool_use_id: toolUseResult.requestId,
1173
- content: toolUseResult.result.text
1036
+ tool_use_id: item.callId,
1037
+ content: item.output.text
1174
1038
  });
1175
1039
  }
1176
1040
  }
@@ -1199,35 +1063,34 @@ var AnthropicMessagesMapper = class {
1199
1063
  const items = [];
1200
1064
  for (const block of response.content) {
1201
1065
  if (block.type === "text") {
1202
- items.push({
1203
- type: "model_message",
1204
- text: block.text
1205
- });
1066
+ items.push(ModelMessageItem.rehydrate({ text: block.text }));
1206
1067
  continue;
1207
1068
  }
1208
1069
  if (block.type === "tool_use") {
1209
- items.push({
1210
- type: "tool_use_request",
1211
- requestId: block.id,
1212
- toolName: block.name,
1213
- toolArguments: JSON.stringify((_a = block.input) != null ? _a : {})
1214
- });
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
+ );
1215
1077
  continue;
1216
1078
  }
1217
1079
  if (block.type === "thinking") {
1218
- items.push({
1219
- type: "reasoning",
1220
- content: block.thinking ? { type: "input_text", text: block.thinking } : void 0,
1221
- encryptedContent: block.signature,
1222
- summary: []
1223
- });
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
+ );
1224
1087
  }
1225
1088
  }
1226
1089
  return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1227
1090
  }
1228
1091
  };
1229
1092
 
1230
- // src/infrastructure/providers/anthropic/anthropic-messages.ts
1093
+ // src/infrastructure/providers/anthropic/endpoints/anthropic-messages.ts
1231
1094
  import Anthropic from "@anthropic-ai/sdk";
1232
1095
  var AnthropicMessages = class {
1233
1096
  constructor(endpointMapper = new AnthropicMessagesMapper(), config = {}) {
@@ -1241,13 +1104,13 @@ var AnthropicMessages = class {
1241
1104
  apiKey: this.clientConfig.apiKey
1242
1105
  });
1243
1106
  }
1244
- async infer(inferenceRequest) {
1245
- const request = this.endpointMapper.toRequest(inferenceRequest);
1107
+ async infer(inferenceInput) {
1108
+ const request = this.endpointMapper.toRequest(inferenceInput);
1246
1109
  const response = await this.client.messages.create(request);
1247
1110
  return this.endpointMapper.toResponse(response);
1248
1111
  }
1249
- async *stream(inferenceRequest) {
1250
- const request = this.endpointMapper.toRequest(inferenceRequest);
1112
+ async *stream(inferenceInput) {
1113
+ const request = this.endpointMapper.toRequest(inferenceInput);
1251
1114
  const stream = this.client.messages.stream(request);
1252
1115
  for await (const event of stream) {
1253
1116
  yield event;
@@ -1262,29 +1125,44 @@ var AnthropicMessages = class {
1262
1125
  }
1263
1126
  };
1264
1127
 
1265
- // 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
1266
1144
  var OpenAIResponsesMapper = class {
1267
- toRequest(inferenceRequest) {
1145
+ toRequest(inferenceInput) {
1268
1146
  var _a, _b;
1269
1147
  const request = {
1270
- model: inferenceRequest.model,
1271
- input: this.mapContextItems(inferenceRequest)
1148
+ model: inferenceInput.model,
1149
+ input: this.mapContextItems(inferenceInput)
1272
1150
  };
1273
- if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1274
- request.tools = inferenceRequest.tools.map((tool) => ({
1151
+ if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1152
+ request.tools = inferenceInput.tools.map((tool) => ({
1275
1153
  type: tool.type,
1276
1154
  name: tool.name,
1277
1155
  description: tool.description,
1278
1156
  parameters: tool.parameters
1279
1157
  }));
1280
1158
  }
1281
- if (inferenceRequest.reasoningEffort) {
1159
+ if (inferenceInput.reasoningEffort) {
1282
1160
  request.reasoning = {
1283
- effort: inferenceRequest.reasoningEffort
1161
+ effort: inferenceInput.reasoningEffort
1284
1162
  };
1285
1163
  }
1286
- if (inferenceRequest.structuredOutput) {
1287
- const format = inferenceRequest.structuredOutput;
1164
+ if (inferenceInput.structuredOutput) {
1165
+ const format = inferenceInput.structuredOutput;
1288
1166
  request.text = {
1289
1167
  format: {
1290
1168
  type: "json_schema",
@@ -1294,58 +1172,54 @@ var OpenAIResponsesMapper = class {
1294
1172
  }
1295
1173
  };
1296
1174
  }
1297
- if (inferenceRequest.streaming) {
1298
- request.stream = inferenceRequest.streaming;
1175
+ if (inferenceInput.streaming) {
1176
+ request.stream = inferenceInput.streaming;
1299
1177
  }
1300
1178
  return request;
1301
1179
  }
1302
- mapContextItems(inferenceRequest) {
1180
+ mapContextItems(inferenceInput) {
1303
1181
  const input = [];
1304
- for (const item of inferenceRequest.context.items) {
1305
- if (item.type === "developer_message" || item.type === "system_message" || item.type === "user_message") {
1306
- 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) {
1307
1184
  input.push({
1308
- type: "message",
1309
- role,
1310
- content: [{ type: "input_text", text: item.text }]
1185
+ type: item.type,
1186
+ role: item.role,
1187
+ content: [{ type: "input_text", text: item.content.text }]
1311
1188
  });
1312
1189
  continue;
1313
1190
  }
1314
- if (item.type === "model_message") {
1191
+ if (item instanceof ModelMessageItem) {
1315
1192
  input.push({
1316
- type: "message",
1317
- role: "assistant",
1318
- content: [{ type: "output_text", text: item.text }]
1193
+ type: item.type,
1194
+ role: item.role,
1195
+ content: [{ type: "output_text", text: item.content.text }]
1319
1196
  });
1320
1197
  continue;
1321
1198
  }
1322
- if (item.type === "tool_use_request") {
1323
- const toolUseRequest = item;
1199
+ if (item instanceof FunctionCallItem) {
1324
1200
  input.push({
1325
- type: "function_call",
1326
- call_id: toolUseRequest.requestId,
1327
- name: toolUseRequest.toolName,
1328
- arguments: toolUseRequest.toolArguments
1201
+ type: item.type,
1202
+ call_id: item.callId,
1203
+ name: item.name,
1204
+ arguments: item.args
1329
1205
  });
1330
1206
  continue;
1331
1207
  }
1332
- if (item.type === "tool_use_result") {
1333
- const toolUseResult = item;
1208
+ if (item instanceof FunctionCallOutputItem) {
1334
1209
  input.push({
1335
- type: "function_call_output",
1336
- call_id: toolUseResult.requestId,
1337
- 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 }]
1338
1213
  });
1339
1214
  continue;
1340
1215
  }
1341
- if (item.type === "reasoning") {
1342
- const reasoning = item;
1216
+ if (item instanceof ReasoningItem) {
1343
1217
  const reasoningInput = {
1344
- type: "reasoning",
1345
- 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 }))
1346
1220
  };
1347
- if (reasoning.encryptedContent !== void 0) {
1348
- reasoningInput.encrypted_content = reasoning.encryptedContent;
1221
+ if (item.encryptedContent !== void 0) {
1222
+ reasoningInput.encrypted_content = item.encryptedContent;
1349
1223
  }
1350
1224
  input.push(reasoningInput);
1351
1225
  }
@@ -1372,33 +1246,30 @@ var OpenAIResponsesMapper = class {
1372
1246
  if (item.type === "message" && item.role === "assistant") {
1373
1247
  const firstContent = (_b = item.content) == null ? void 0 : _b[0];
1374
1248
  if (firstContent) {
1375
- items.push({
1376
- type: "model_message",
1377
- text: firstContent.text
1378
- });
1249
+ items.push(ModelMessageItem.rehydrate(firstContent));
1379
1250
  }
1380
1251
  continue;
1381
1252
  }
1382
1253
  if (item.type === "function_call") {
1383
- const toolUseRequest = {
1384
- type: "tool_use_request",
1385
- requestId: item.call_id,
1386
- toolName: item.name,
1387
- toolArguments: item.arguments
1388
- };
1389
- items.push(toolUseRequest);
1254
+ items.push(
1255
+ FunctionCallItem.rehydrate({
1256
+ callId: item.call_id,
1257
+ name: item.name,
1258
+ args: item.arguments
1259
+ })
1260
+ );
1390
1261
  continue;
1391
1262
  }
1392
1263
  if (item.type === "reasoning") {
1393
- items.push({
1394
- type: "reasoning",
1395
- content: void 0,
1396
- encryptedContent: item.encrypted_content,
1397
- summary: ((_c = item.summary) != null ? _c : []).map((summary) => ({
1398
- type: "summary_text",
1399
- text: summary.text
1400
- }))
1401
- });
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
+ );
1402
1273
  }
1403
1274
  }
1404
1275
  return {
@@ -1409,8 +1280,7 @@ var OpenAIResponsesMapper = class {
1409
1280
  }
1410
1281
  };
1411
1282
 
1412
- // src/infrastructure/providers/openai/openai-responses.ts
1413
- import OpenAI from "openai";
1283
+ // src/infrastructure/providers/openai/endpoints/openai-responses.ts
1414
1284
  var OpenAIResponses = class {
1415
1285
  constructor(endpointMapper = new OpenAIResponsesMapper(), config = {}) {
1416
1286
  this.endpointMapper = endpointMapper;
@@ -1423,13 +1293,13 @@ var OpenAIResponses = class {
1423
1293
  apiKey: this.clientConfig.apiKey
1424
1294
  });
1425
1295
  }
1426
- async infer(inferenceRequest) {
1427
- const request = this.endpointMapper.toRequest(inferenceRequest);
1296
+ async infer(inferenceInput) {
1297
+ const request = this.endpointMapper.toRequest(inferenceInput);
1428
1298
  const response = await this.client.responses.create(request);
1429
1299
  return this.endpointMapper.toResponse(response);
1430
1300
  }
1431
- async *stream(inferenceRequest) {
1432
- const request = this.endpointMapper.toRequest(inferenceRequest);
1301
+ async *stream(inferenceInput) {
1302
+ const request = this.endpointMapper.toRequest(inferenceInput);
1433
1303
  const stream = await this.client.responses.create({ ...request, stream: true });
1434
1304
  let completedResponse = void 0;
1435
1305
  for await (const event of stream) {
@@ -1446,26 +1316,26 @@ var OpenAIResponses = class {
1446
1316
  type: "inference.output",
1447
1317
  payload: output,
1448
1318
  occurredAt: /* @__PURE__ */ new Date(),
1449
- producerId: inferenceRequest.model
1319
+ producerId: inferenceInput.model
1450
1320
  };
1451
1321
  }
1452
1322
  };
1453
1323
 
1454
- // src/infrastructure/providers/gemini/gemini-generate-content.ts
1324
+ // src/infrastructure/providers/gemini/endpoints/gemini-generate-content.ts
1455
1325
  import { GoogleGenAI } from "@google/genai";
1456
1326
 
1457
- // src/infrastructure/providers/gemini/gemini-generate-content-mapper.ts
1327
+ // src/infrastructure/providers/gemini/endpoints/gemini-generate-content-mapper.ts
1458
1328
  var GeminiGenerateContentMapper = class {
1459
- toRequest(inferenceRequest) {
1460
- const { contents, systemInstruction } = this.mapContextItems(inferenceRequest);
1329
+ toRequest(inferenceInput) {
1330
+ const { contents, systemInstruction } = this.mapContextItems(inferenceInput);
1461
1331
  const config = {};
1462
1332
  if (systemInstruction) {
1463
1333
  config.systemInstruction = systemInstruction;
1464
1334
  }
1465
- if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1335
+ if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1466
1336
  config.tools = [
1467
1337
  {
1468
- functionDeclarations: inferenceRequest.tools.map((tool) => ({
1338
+ functionDeclarations: inferenceInput.tools.map((tool) => ({
1469
1339
  name: tool.name,
1470
1340
  description: tool.description,
1471
1341
  parametersJsonSchema: tool.parameters
@@ -1473,66 +1343,62 @@ var GeminiGenerateContentMapper = class {
1473
1343
  }
1474
1344
  ];
1475
1345
  }
1476
- if (inferenceRequest.structuredOutput) {
1346
+ if (inferenceInput.structuredOutput) {
1477
1347
  config.responseMimeType = "application/json";
1478
- config.responseSchema = inferenceRequest.structuredOutput.schema;
1348
+ config.responseSchema = inferenceInput.structuredOutput.schema;
1479
1349
  }
1480
- if (inferenceRequest.reasoningEffort) {
1350
+ if (inferenceInput.reasoningEffort) {
1481
1351
  config.thinkingConfig = {
1482
- thinkingLevel: inferenceRequest.reasoningEffort,
1352
+ thinkingLevel: inferenceInput.reasoningEffort,
1483
1353
  includeThoughts: true
1484
1354
  };
1485
1355
  }
1486
1356
  const request = {
1487
- model: inferenceRequest.model,
1357
+ model: inferenceInput.model,
1488
1358
  contents,
1489
1359
  config
1490
1360
  };
1491
- if (inferenceRequest.streaming) {
1492
- request.stream = inferenceRequest.streaming;
1361
+ if (inferenceInput.streaming) {
1362
+ request.stream = inferenceInput.streaming;
1493
1363
  }
1494
1364
  return request;
1495
1365
  }
1496
- mapContextItems(inferenceRequest) {
1366
+ mapContextItems(inferenceInput) {
1497
1367
  var _a;
1498
- const context = inferenceRequest.context;
1368
+ const context = inferenceInput.context;
1499
1369
  const contents = [];
1500
1370
  const system = [];
1501
1371
  const callNames = /* @__PURE__ */ new Map();
1502
- for (const item of context.items) {
1503
- if (item.type === "developer_message" || item.type === "system_message") {
1504
- 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);
1505
1375
  continue;
1506
1376
  }
1507
- if (item.type === "user_message") {
1508
- this.addPart(contents, "user", { text: item.text });
1377
+ if (item instanceof UserMessageItem) {
1378
+ this.addPart(contents, "user", { text: item.content.text });
1509
1379
  continue;
1510
1380
  }
1511
- if (item.type === "model_message") {
1512
- this.addPart(contents, "model", { text: item.text });
1381
+ if (item instanceof ModelMessageItem) {
1382
+ this.addPart(contents, "model", { text: item.content.text });
1513
1383
  continue;
1514
1384
  }
1515
- if (item.type === "tool_use_request") {
1516
- const toolUseRequest = item;
1517
- callNames.set(toolUseRequest.requestId, toolUseRequest.toolName);
1385
+ if (item instanceof FunctionCallItem) {
1386
+ callNames.set(item.callId, item.name);
1518
1387
  let args;
1519
1388
  try {
1520
- args = JSON.parse(toolUseRequest.toolArguments);
1389
+ args = JSON.parse(item.args);
1521
1390
  } catch (e) {
1522
1391
  args = {};
1523
1392
  }
1524
- this.addPart(contents, "model", {
1525
- functionCall: { id: toolUseRequest.requestId, name: toolUseRequest.toolName, args }
1526
- });
1393
+ this.addPart(contents, "model", { functionCall: { id: item.callId, name: item.name, args } });
1527
1394
  continue;
1528
1395
  }
1529
- if (item.type === "tool_use_result") {
1530
- const toolUseResult = item;
1396
+ if (item instanceof FunctionCallOutputItem) {
1531
1397
  this.addPart(contents, "user", {
1532
1398
  functionResponse: {
1533
- id: toolUseResult.requestId,
1534
- name: (_a = callNames.get(toolUseResult.requestId)) != null ? _a : "",
1535
- 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)
1536
1402
  }
1537
1403
  });
1538
1404
  }
@@ -1578,35 +1444,34 @@ var GeminiGenerateContentMapper = class {
1578
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 : [];
1579
1445
  for (const part of parts) {
1580
1446
  if (part.thought && part.text) {
1581
- items.push({
1582
- type: "reasoning",
1583
- content: { type: "input_text", text: part.text },
1584
- encryptedContent: void 0,
1585
- summary: []
1586
- });
1447
+ items.push(
1448
+ ReasoningItem.rehydrate({
1449
+ content: InputText.rehydrate({ text: part.text }),
1450
+ encryptedContent: void 0,
1451
+ summary: []
1452
+ })
1453
+ );
1587
1454
  continue;
1588
1455
  }
1589
1456
  if (part.text) {
1590
- items.push({
1591
- type: "model_message",
1592
- text: part.text
1593
- });
1457
+ items.push(ModelMessageItem.rehydrate({ text: part.text }));
1594
1458
  continue;
1595
1459
  }
1596
1460
  if (part.functionCall) {
1597
- items.push({
1598
- type: "tool_use_request",
1599
- requestId: (_e = part.functionCall.id) != null ? _e : "",
1600
- toolName: part.functionCall.name,
1601
- toolArguments: JSON.stringify((_f = part.functionCall.args) != null ? _f : {})
1602
- });
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
+ );
1603
1468
  }
1604
1469
  }
1605
1470
  return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1606
1471
  }
1607
1472
  };
1608
1473
 
1609
- // src/infrastructure/providers/gemini/gemini-generate-content.ts
1474
+ // src/infrastructure/providers/gemini/endpoints/gemini-generate-content.ts
1610
1475
  var GeminiGenerateContent = class {
1611
1476
  constructor(endpointMapper = new GeminiGenerateContentMapper(), config = {}) {
1612
1477
  this.endpointMapper = endpointMapper;
@@ -1619,13 +1484,13 @@ var GeminiGenerateContent = class {
1619
1484
  ...this.clientConfig.baseURL ? { httpOptions: { baseUrl: this.clientConfig.baseURL } } : {}
1620
1485
  });
1621
1486
  }
1622
- async infer(inferenceRequest) {
1623
- const request = this.endpointMapper.toRequest(inferenceRequest);
1487
+ async infer(inferenceInput) {
1488
+ const request = this.endpointMapper.toRequest(inferenceInput);
1624
1489
  const response = await this.client.models.generateContent(request);
1625
1490
  return this.endpointMapper.toResponse(response);
1626
1491
  }
1627
- async *stream(inferenceRequest) {
1628
- const request = this.endpointMapper.toRequest(inferenceRequest);
1492
+ async *stream(inferenceInput) {
1493
+ const request = this.endpointMapper.toRequest(inferenceInput);
1629
1494
  const stream = await this.client.models.generateContentStream(request);
1630
1495
  let lastEvent = void 0;
1631
1496
  for await (const chunk of stream) {
@@ -1645,15 +1510,15 @@ var GeminiGenerateContent = class {
1645
1510
  }
1646
1511
  };
1647
1512
 
1648
- // src/infrastructure/providers/openai/openai-chat-completions-mapper.ts
1513
+ // src/infrastructure/providers/openai/endpoints/openai-chat-completions-mapper.ts
1649
1514
  var OpenAIChatCompletionsMapper = class {
1650
- toRequest(inferenceRequest) {
1515
+ toRequest(inferenceInput) {
1651
1516
  const request = {
1652
- model: inferenceRequest.model,
1653
- messages: this.mapContextItems(inferenceRequest)
1517
+ model: inferenceInput.model,
1518
+ messages: this.mapContextItems(inferenceInput)
1654
1519
  };
1655
- if (inferenceRequest.tools && inferenceRequest.tools.length > 0) {
1656
- request.tools = inferenceRequest.tools.map((tool) => ({
1520
+ if (inferenceInput.tools && inferenceInput.tools.length > 0) {
1521
+ request.tools = inferenceInput.tools.map((tool) => ({
1657
1522
  type: "function",
1658
1523
  function: {
1659
1524
  name: tool.name,
@@ -1662,36 +1527,35 @@ var OpenAIChatCompletionsMapper = class {
1662
1527
  }
1663
1528
  }));
1664
1529
  }
1665
- if (inferenceRequest.reasoningEffort) {
1666
- request.reasoning_effort = inferenceRequest.reasoningEffort;
1530
+ if (inferenceInput.reasoningEffort) {
1531
+ request.reasoning_effort = inferenceInput.reasoningEffort;
1667
1532
  }
1668
- if (inferenceRequest.streaming) {
1669
- request.stream = inferenceRequest.streaming;
1533
+ if (inferenceInput.streaming) {
1534
+ request.stream = inferenceInput.streaming;
1670
1535
  }
1671
1536
  return request;
1672
1537
  }
1673
- mapContextItems(inferenceRequest) {
1538
+ mapContextItems(inferenceInput) {
1674
1539
  var _a;
1675
1540
  const messages = [];
1676
- for (const item of inferenceRequest.context.items) {
1677
- if (item.type === "developer_message" || item.type === "system_message") {
1678
- 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 });
1679
1544
  continue;
1680
1545
  }
1681
- if (item.type === "user_message") {
1682
- messages.push({ role: "user", content: item.text });
1546
+ if (item instanceof UserMessageItem) {
1547
+ messages.push({ role: "user", content: item.content.text });
1683
1548
  continue;
1684
1549
  }
1685
- if (item.type === "model_message") {
1686
- messages.push({ role: "assistant", content: item.text });
1550
+ if (item instanceof ModelMessageItem) {
1551
+ messages.push({ role: "assistant", content: item.content.text });
1687
1552
  continue;
1688
1553
  }
1689
- if (item.type === "tool_use_request") {
1690
- const toolUseRequest = item;
1554
+ if (item instanceof FunctionCallItem) {
1691
1555
  const toolCall = {
1692
- id: toolUseRequest.requestId,
1556
+ id: item.callId,
1693
1557
  type: "function",
1694
- function: { name: toolUseRequest.toolName, arguments: toolUseRequest.toolArguments }
1558
+ function: { name: item.name, arguments: item.args }
1695
1559
  };
1696
1560
  const last = messages[messages.length - 1];
1697
1561
  if ((last == null ? void 0 : last.role) === "assistant") {
@@ -1702,13 +1566,8 @@ var OpenAIChatCompletionsMapper = class {
1702
1566
  }
1703
1567
  continue;
1704
1568
  }
1705
- if (item.type === "tool_use_result") {
1706
- const toolUseResult = item;
1707
- messages.push({
1708
- role: "tool",
1709
- tool_call_id: toolUseResult.requestId,
1710
- content: toolUseResult.result.text
1711
- });
1569
+ if (item instanceof FunctionCallOutputItem) {
1570
+ messages.push({ role: "tool", tool_call_id: item.callId, content: item.output.text });
1712
1571
  }
1713
1572
  }
1714
1573
  return messages;
@@ -1734,32 +1593,31 @@ var OpenAIChatCompletionsMapper = class {
1734
1593
  return { items: [], tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1735
1594
  }
1736
1595
  if (message.reasoning_content) {
1737
- items.push({
1738
- type: "reasoning",
1739
- content: { type: "input_text", text: message.reasoning_content },
1740
- encryptedContent: void 0,
1741
- summary: []
1742
- });
1596
+ items.push(
1597
+ ReasoningItem.rehydrate({
1598
+ content: InputText.rehydrate({ text: message.reasoning_content }),
1599
+ encryptedContent: void 0,
1600
+ summary: []
1601
+ })
1602
+ );
1743
1603
  }
1744
1604
  if (message.content) {
1745
- items.push({
1746
- type: "model_message",
1747
- text: message.content
1748
- });
1605
+ items.push(ModelMessageItem.rehydrate({ text: message.content }));
1749
1606
  }
1750
1607
  for (const toolCall of (_c = message.tool_calls) != null ? _c : []) {
1751
- items.push({
1752
- type: "tool_use_request",
1753
- requestId: toolCall.id,
1754
- toolName: toolCall.function.name,
1755
- toolArguments: toolCall.function.arguments
1756
- });
1608
+ items.push(
1609
+ FunctionCallItem.rehydrate({
1610
+ callId: toolCall.id,
1611
+ name: toolCall.function.name,
1612
+ args: toolCall.function.arguments
1613
+ })
1614
+ );
1757
1615
  }
1758
1616
  return { items, tokenUsage: this.extractTokenUsage(response), rowResponse: response };
1759
1617
  }
1760
1618
  };
1761
1619
 
1762
- // src/infrastructure/providers/openai/openai-chat-completions.ts
1620
+ // src/infrastructure/providers/openai/endpoints/openai-chat-completions.ts
1763
1621
  import OpenAI2 from "openai";
1764
1622
  var OpenAIChatCompletions = class {
1765
1623
  constructor(endpointMapper = new OpenAIChatCompletionsMapper(), config = {}) {
@@ -1775,18 +1633,18 @@ var OpenAIChatCompletions = class {
1775
1633
  apiKey: this.clientConfig.apiKey
1776
1634
  });
1777
1635
  }
1778
- buildRequest(inferenceRequest) {
1636
+ buildRequest(inferenceInput) {
1779
1637
  return {
1780
1638
  ...this.extraBody,
1781
- ...this.endpointMapper.toRequest(inferenceRequest)
1639
+ ...this.endpointMapper.toRequest(inferenceInput)
1782
1640
  };
1783
1641
  }
1784
- async infer(inferenceRequest) {
1785
- 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));
1786
1644
  return this.endpointMapper.toResponse(response);
1787
1645
  }
1788
- async *stream(inferenceRequest) {
1789
- 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));
1790
1648
  for await (const chunk of stream) {
1791
1649
  yield chunk;
1792
1650
  }
@@ -1795,7 +1653,7 @@ var OpenAIChatCompletions = class {
1795
1653
  type: "inference.output",
1796
1654
  payload: output,
1797
1655
  occurredAt: /* @__PURE__ */ new Date(),
1798
- producerId: inferenceRequest.model
1656
+ producerId: inferenceInput.model
1799
1657
  };
1800
1658
  }
1801
1659
  };
@@ -1811,8 +1669,8 @@ var claudeSonnet46Specification = {
1811
1669
  "system_message",
1812
1670
  "developer_message",
1813
1671
  "reasoning",
1814
- "tool_use_request",
1815
- "tool_use_result",
1672
+ "function_call",
1673
+ "function_call_output",
1816
1674
  "model_message"
1817
1675
  ],
1818
1676
  supportsStreaming: true,
@@ -1833,8 +1691,8 @@ var claudeOpus48Specification = {
1833
1691
  "system_message",
1834
1692
  "developer_message",
1835
1693
  "reasoning",
1836
- "tool_use_request",
1837
- "tool_use_result",
1694
+ "function_call",
1695
+ "function_call_output",
1838
1696
  "model_message"
1839
1697
  ],
1840
1698
  supportsStreaming: true,
@@ -1855,8 +1713,8 @@ var claudeOpus47Specification = {
1855
1713
  "system_message",
1856
1714
  "developer_message",
1857
1715
  "reasoning",
1858
- "tool_use_request",
1859
- "tool_use_result",
1716
+ "function_call",
1717
+ "function_call_output",
1860
1718
  "model_message"
1861
1719
  ],
1862
1720
  supportsStreaming: true,
@@ -1877,8 +1735,8 @@ var gemini35FlashSpecification = {
1877
1735
  "system_message",
1878
1736
  "developer_message",
1879
1737
  "reasoning",
1880
- "tool_use_request",
1881
- "tool_use_result",
1738
+ "function_call",
1739
+ "function_call_output",
1882
1740
  "model_message"
1883
1741
  ],
1884
1742
  supportsStreaming: true,
@@ -1899,8 +1757,8 @@ var gemini31ProSpecification = {
1899
1757
  "system_message",
1900
1758
  "developer_message",
1901
1759
  "reasoning",
1902
- "tool_use_request",
1903
- "tool_use_result",
1760
+ "function_call",
1761
+ "function_call_output",
1904
1762
  "model_message"
1905
1763
  ],
1906
1764
  supportsStreaming: true,
@@ -1921,8 +1779,8 @@ var deepSeekV4FlashSpecification = {
1921
1779
  "system_message",
1922
1780
  "developer_message",
1923
1781
  "reasoning",
1924
- "tool_use_request",
1925
- "tool_use_result",
1782
+ "function_call",
1783
+ "function_call_output",
1926
1784
  "model_message"
1927
1785
  ],
1928
1786
  supportsStreaming: true,
@@ -1943,8 +1801,8 @@ var deepSeekV4ProSpecification = {
1943
1801
  "system_message",
1944
1802
  "developer_message",
1945
1803
  "reasoning",
1946
- "tool_use_request",
1947
- "tool_use_result",
1804
+ "function_call",
1805
+ "function_call_output",
1948
1806
  "model_message"
1949
1807
  ],
1950
1808
  supportsStreaming: true,
@@ -1965,8 +1823,8 @@ var gpt54Specification = {
1965
1823
  "system_message",
1966
1824
  "developer_message",
1967
1825
  "reasoning",
1968
- "tool_use_request",
1969
- "tool_use_result",
1826
+ "function_call",
1827
+ "function_call_output",
1970
1828
  "model_message"
1971
1829
  ],
1972
1830
  supportsStreaming: true,
@@ -1987,8 +1845,8 @@ var gpt54MiniSpecification = {
1987
1845
  "system_message",
1988
1846
  "developer_message",
1989
1847
  "reasoning",
1990
- "tool_use_request",
1991
- "tool_use_result",
1848
+ "function_call",
1849
+ "function_call_output",
1992
1850
  "model_message"
1993
1851
  ],
1994
1852
  supportsStreaming: true,
@@ -2009,8 +1867,8 @@ var gpt54NanoSpecification = {
2009
1867
  "system_message",
2010
1868
  "developer_message",
2011
1869
  "reasoning",
2012
- "tool_use_request",
2013
- "tool_use_result",
1870
+ "function_call",
1871
+ "function_call_output",
2014
1872
  "model_message"
2015
1873
  ],
2016
1874
  supportsStreaming: true,
@@ -2031,8 +1889,8 @@ var gpt55Specification = {
2031
1889
  "system_message",
2032
1890
  "developer_message",
2033
1891
  "reasoning",
2034
- "tool_use_request",
2035
- "tool_use_result",
1892
+ "function_call",
1893
+ "function_call_output",
2036
1894
  "model_message"
2037
1895
  ],
2038
1896
  supportsStreaming: true,
@@ -2053,8 +1911,8 @@ var claudeHaiku45Specification = {
2053
1911
  "system_message",
2054
1912
  "developer_message",
2055
1913
  "reasoning",
2056
- "tool_use_request",
2057
- "tool_use_result",
1914
+ "function_call",
1915
+ "function_call_output",
2058
1916
  "model_message"
2059
1917
  ],
2060
1918
  supportsStreaming: true,
@@ -2064,12 +1922,12 @@ var claudeHaiku45Specification = {
2064
1922
  supportsStructuredOutput: true
2065
1923
  };
2066
1924
 
2067
- // src/infrastructure/providers/openai/models/gpt-6-luna.ts
2068
- var gpt6LunaSpecification = {
2069
- name: "gpt-6-luna",
1925
+ // src/infrastructure/providers/openai/models/gpt-6-astra.ts
1926
+ var gpt6AstraSpecification = {
1927
+ name: "gpt-6-astra",
2070
1928
  provider: "openai",
2071
1929
  supportsReasoningEffort: true,
2072
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
1930
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2073
1931
  supportedContextItemTypes: [
2074
1932
  "user_message",
2075
1933
  "system_message",
@@ -2086,12 +1944,12 @@ var gpt6LunaSpecification = {
2086
1944
  supportsStructuredOutput: true
2087
1945
  };
2088
1946
 
2089
- // src/infrastructure/providers/openai/models/gpt-6-sol.ts
2090
- var gpt6SolSpecification = {
2091
- name: "gpt-6-sol",
1947
+ // src/infrastructure/providers/openai/models/gpt-6-1-sol.ts
1948
+ var gpt61SolSpecification = {
1949
+ name: "gpt-6.1-sol",
2092
1950
  provider: "openai",
2093
1951
  supportsReasoningEffort: true,
2094
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
1952
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
2095
1953
  supportedContextItemTypes: [
2096
1954
  "user_message",
2097
1955
  "system_message",
@@ -2108,12 +1966,12 @@ var gpt6SolSpecification = {
2108
1966
  supportsStructuredOutput: true
2109
1967
  };
2110
1968
 
2111
- // src/infrastructure/providers/openai/models/gpt-6-1-sol.ts
2112
- var gpt61SolSpecification = {
2113
- name: "gpt-6.1-sol",
1969
+ // src/infrastructure/providers/openai/models/gpt-6-sol.ts
1970
+ var gpt6SolSpecification = {
1971
+ name: "gpt-6-sol",
2114
1972
  provider: "openai",
2115
1973
  supportsReasoningEffort: true,
2116
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1974
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
2117
1975
  supportedContextItemTypes: [
2118
1976
  "user_message",
2119
1977
  "system_message",
@@ -2130,12 +1988,12 @@ var gpt61SolSpecification = {
2130
1988
  supportsStructuredOutput: true
2131
1989
  };
2132
1990
 
2133
- // src/infrastructure/providers/openai/models/gpt-6-astra.ts
2134
- var gpt6AstraSpecification = {
2135
- name: "gpt-6-astra",
1991
+ // src/infrastructure/providers/openai/models/gpt-6-luna.ts
1992
+ var gpt6LunaSpecification = {
1993
+ name: "gpt-6-luna",
2136
1994
  provider: "openai",
2137
1995
  supportsReasoningEffort: true,
2138
- supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
1996
+ supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low", "none"],
2139
1997
  supportedContextItemTypes: [
2140
1998
  "user_message",
2141
1999
  "system_message",
@@ -2152,9 +2010,9 @@ var gpt6AstraSpecification = {
2152
2010
  supportsStructuredOutput: true
2153
2011
  };
2154
2012
 
2155
- // src/infrastructure/providers/anthropic/models/claude-5-sonnet.ts
2156
- var claudeSonnet5Specification = {
2157
- name: "claude-sonnet-5",
2013
+ // src/infrastructure/providers/anthropic/models/claude-5-1-fable.ts
2014
+ var claudeFable51Specification = {
2015
+ name: "claude-fable-5-1",
2158
2016
  provider: "anthropic",
2159
2017
  supportsReasoningEffort: true,
2160
2018
  supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
@@ -2174,9 +2032,9 @@ var claudeSonnet5Specification = {
2174
2032
  supportsStructuredOutput: true
2175
2033
  };
2176
2034
 
2177
- // src/infrastructure/providers/anthropic/models/claude-5-5-sonnet.ts
2178
- var claudeSonnet55Specification = {
2179
- 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",
2180
2038
  provider: "anthropic",
2181
2039
  supportsReasoningEffort: true,
2182
2040
  supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
@@ -2196,9 +2054,9 @@ var claudeSonnet55Specification = {
2196
2054
  supportsStructuredOutput: true
2197
2055
  };
2198
2056
 
2199
- // src/infrastructure/providers/anthropic/models/claude-5-5-opus.ts
2200
- var claudeOpus55Specification = {
2201
- 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",
2202
2060
  provider: "anthropic",
2203
2061
  supportsReasoningEffort: true,
2204
2062
  supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
@@ -2218,9 +2076,9 @@ var claudeOpus55Specification = {
2218
2076
  supportsStructuredOutput: true
2219
2077
  };
2220
2078
 
2221
- // src/infrastructure/providers/anthropic/models/claude-5-1-fable.ts
2222
- var claudeFable51Specification = {
2223
- name: "claude-fable-5-1",
2079
+ // src/infrastructure/providers/anthropic/models/claude-5-sonnet.ts
2080
+ var claudeSonnet5Specification = {
2081
+ name: "claude-sonnet-5",
2224
2082
  provider: "anthropic",
2225
2083
  supportsReasoningEffort: true,
2226
2084
  supportedReasoningEfforts: ["max", "xhigh", "high", "medium", "low"],
@@ -2240,12 +2098,12 @@ var claudeFable51Specification = {
2240
2098
  supportsStructuredOutput: true
2241
2099
  };
2242
2100
 
2243
- // src/infrastructure/providers/gemini/models/gemini-3-5-flash-lite.ts
2244
- var gemini35FlashLiteSpecification = {
2245
- 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",
2246
2104
  provider: "google",
2247
2105
  supportsReasoningEffort: true,
2248
- supportedReasoningEfforts: ["high", "medium", "low", "minimal"],
2106
+ supportedReasoningEfforts: ["high", "medium", "low"],
2249
2107
  supportedContextItemTypes: [
2250
2108
  "user_message",
2251
2109
  "system_message",
@@ -2262,12 +2120,12 @@ var gemini35FlashLiteSpecification = {
2262
2120
  supportsStructuredOutput: true
2263
2121
  };
2264
2122
 
2265
- // src/infrastructure/providers/gemini/models/gemini-3-8-flash.ts
2266
- var gemini38FlashSpecification = {
2267
- 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",
2268
2126
  provider: "google",
2269
2127
  supportsReasoningEffort: true,
2270
- supportedReasoningEfforts: ["high", "medium", "low"],
2128
+ supportedReasoningEfforts: ["high", "medium", "low", "minimal"],
2271
2129
  supportedContextItemTypes: [
2272
2130
  "user_message",
2273
2131
  "system_message",
@@ -2306,7 +2164,7 @@ var deepSeekFlashSpecification = {
2306
2164
  supportsStructuredOutput: false
2307
2165
  };
2308
2166
 
2309
- // src/infrastructure/providers/supported-models.ts
2167
+ // src/application/services/models.ts
2310
2168
  var supportedModels = [
2311
2169
  {
2312
2170
  endpoint: new OpenAIResponses(),
@@ -2402,180 +2260,267 @@ var supportedModels = [
2402
2260
  }
2403
2261
  ];
2404
2262
 
2405
- // src/domain/agent/loop/rule-engine.ts
2406
- var RuleEngine = class {
2407
- decide(agent, loop) {
2408
- const agentLoop = { agent, loop };
2409
- const satisfiedRules = loop.ruleBook.getRules().filter((rule) => rule.condition.isSatisfiedBy(agentLoop));
2410
- if (satisfiedRules.length === 0) {
2411
- 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;
2412
2271
  }
2413
- const highestPriorityRule = satisfiedRules.reduce((highest, current) => {
2414
- return highest.priority > current.priority ? highest : current;
2415
- });
2416
- return highestPriorityRule.action.execute(agentLoop);
2272
+ if (!model.supportsReasoningEffort) {
2273
+ return false;
2274
+ }
2275
+ return model.supportedReasoningEfforts.includes(inferenceInput.reasoningEffort);
2417
2276
  }
2418
2277
  };
2419
2278
 
2420
- // src/application/use-cases/run-loop.ts
2421
- var RunLoopUseCase = class {
2422
- constructor(agentRepository, loopRepository, directiveExecutionStrategyResolver) {
2423
- this.agentRepository = agentRepository;
2424
- this.loopRepository = loopRepository;
2425
- this.directiveExecutionStrategyResolver = directiveExecutionStrategyResolver;
2426
- 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";
2427
2283
  }
2428
- async execute(loopId) {
2429
- const loop = await this.loopRepository.findById(loopId);
2430
- if (!loop) {
2431
- throw new Error("Loop not found");
2432
- }
2433
- const agent = await this.agentRepository.findById(loop.getAgentId());
2434
- if (!agent) {
2435
- throw new Error("Agent not found");
2436
- }
2437
- while (loop.stateId !== "completed") {
2438
- const directive = this.ruleEngine.decide(agent, loop);
2439
- if (!directive) return loop;
2440
- const strategy = this.directiveExecutionStrategyResolver.resolve(directive);
2441
- await strategy.execute(directive, agent, loop);
2284
+ isValid(inferenceInput, model) {
2285
+ if (inferenceInput.tools === void 0) {
2286
+ return true;
2442
2287
  }
2443
- await this.loopRepository.save(loop);
2444
- return loop;
2288
+ return model.supportsFunctionCalling;
2445
2289
  }
2446
2290
  };
2447
2291
 
2448
- // src/infrastructure/memory/runtime-memory.ts
2449
- var RuntimeMemory = class {
2450
- constructor(context) {
2451
- this.context = context;
2452
- }
2453
- remember(items, participantId) {
2454
- 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";
2455
2296
  }
2456
- recall(topic, participantId) {
2457
- throw new Error("Method not implemented.");
2297
+ isValid(inferenceInput, model) {
2298
+ if (!inferenceInput.streaming) {
2299
+ return true;
2300
+ }
2301
+ return model.supportsStreaming;
2458
2302
  }
2459
2303
  };
2460
2304
 
2461
- // src/infrastructure/memory/runtime-memory-factory.ts
2462
- var RuntimeMemoryFactory = class {
2463
- create() {
2464
- const context = {
2465
- items: []
2466
- };
2467
- 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";
2468
2309
  }
2469
- };
2470
-
2471
- // src/application/directive-execution/directive-execution-strategy-resolver.ts
2472
- var DirectiveExecutionStrategyResolver = class {
2473
- constructor(strategies) {
2474
- this.strategies = strategies;
2310
+ if (item instanceof SystemMessageItem) {
2311
+ return "system_message";
2475
2312
  }
2476
- resolve(directive) {
2477
- return this.strategies[directive.type];
2313
+ if (item instanceof DeveloperMessageItem) {
2314
+ return "developer_message";
2478
2315
  }
2479
- };
2480
-
2481
- // src/application/directive-execution/complete-execution-strategy.ts
2482
- var CompleteExecutionStrategy = class {
2483
- async execute(directive, agent, loop) {
2484
- if (directive.type !== "complete") {
2485
- throw new Error("Expected a completion directive");
2486
- }
2487
- 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
+ );
2488
2329
  }
2489
2330
  };
2490
2331
 
2491
- // src/application/directive-execution/inference-execution-strategy.ts
2492
- var InferenceExecutionStrategy = class {
2493
- constructor(inferenceRunner) {
2494
- 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;
2495
2343
  }
2496
- async execute(directive, agent, loop) {
2497
- if (directive.type !== "inference") {
2498
- 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
+ }
2499
2349
  }
2500
- const pending = loop.requestInference(directive.request);
2501
- const result = await this.inferenceRunner.run(directive.request);
2502
- loop.receiveInferenceResult(pending.id, result);
2503
2350
  }
2504
2351
  };
2505
2352
 
2506
- // src/application/directive-execution/tool-use-execution-strategy.ts
2507
- var ToolUseExecutionStrategy = class {
2508
- constructor(toolRunner) {
2509
- 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;
2510
2358
  }
2511
- async execute(directive, agent, loop) {
2512
- if (directive.type !== "tool_use") {
2513
- throw new Error("Expected a tool-use directive");
2514
- }
2515
- const pending = loop.pending;
2516
- if ((pending == null ? void 0 : pending.type) !== "tool_execution") {
2517
- 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}`);
2518
2363
  }
2519
- const tool = agent.getTools().find((tool2) => tool2.name === directive.call.toolName);
2520
- if (!tool) {
2521
- 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}`);
2522
2371
  }
2523
- const result = await this.toolRunner.run(directive.call, tool);
2524
- loop.receiveToolUseResult(pending.id, result);
2372
+ this.requestValidator.validate(input, generativeModel.specification);
2373
+ yield* generativeModel.endpoint.stream(input);
2525
2374
  }
2526
2375
  };
2527
2376
 
2528
- // src/application/directive-execution/wait-execution-strategy.ts
2529
- var WaitExecutionStrategy = class {
2530
- async execute(directive, agent, loop) {
2531
- if (directive.type !== "wait") {
2532
- 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}`);
2533
2388
  }
2534
- loop.wait(directive.reason);
2535
2389
  }
2536
2390
  };
2537
2391
 
2538
- // src/agent-module.ts
2539
- function defineAgentModule(config) {
2540
- var _a, _b, _c, _d, _e, _f, _g;
2541
- const agentRepository = (_a = config.agentRepository) != null ? _a : new InMemoryAgentRepository();
2542
- const agentLoopRepository = (_b = config.agentLoopRepository) != null ? _b : new InMemoryLoopRepository();
2543
- const inferenceRunner = (_f = (_c = config.inferenceRunnerConfig) == null ? void 0 : _c.runner) != null ? _f : new DefaultInferenceRunner(
2544
- (_e = (_d = config.inferenceRunnerConfig) == null ? void 0 : _d.supportedModels) != null ? _e : supportedModels,
2545
- new InferenceRequestValidator()
2546
- );
2547
- const toolRunner = (_g = config.toolRunner) != null ? _g : new LocalToolRunner();
2548
- const memoryFactory = new RuntimeMemoryFactory();
2549
- const createAgentUseCase = new CreateAgentUseCase(agentRepository, memoryFactory);
2550
- const createLoopUseCase = new CreateAgentLoopUseCase(agentLoopRepository);
2551
- async function createAgent(config2) {
2552
- return await createAgentUseCase.execute(config2.name, config2.instruction, config2.tools);
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;
2553
2420
  }
2554
- async function createLoop(params) {
2555
- return await createLoopUseCase.execute(params);
2421
+ function resolveRuntime() {
2422
+ if (!runtime) {
2423
+ throw new Error("Runtime not initialized");
2424
+ }
2425
+ return runtime;
2556
2426
  }
2557
- const directiveExecutionStrategyResolver = new DirectiveExecutionStrategyResolver({
2558
- inference: new InferenceExecutionStrategy(inferenceRunner),
2559
- tool_use: new ToolUseExecutionStrategy(toolRunner),
2560
- complete: new CompleteExecutionStrategy(),
2561
- wait: new WaitExecutionStrategy()
2562
- });
2563
- const runLoopUseCase = new RunLoopUseCase(agentRepository, agentLoopRepository, directiveExecutionStrategyResolver);
2564
- async function runLoop(loopId) {
2565
- 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;
2566
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);
2567
2442
  return {
2568
- createAgent,
2569
- createLoop,
2443
+ initializeRuntime,
2444
+ resolveRuntime,
2445
+ resolveParticipant,
2446
+ join,
2447
+ leave,
2448
+ sendMessage,
2449
+ sendEvent,
2570
2450
  runLoop
2571
2451
  };
2572
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
+ };
2573
2495
  export {
2574
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,
2575
2513
  Participant,
2514
+ ReasoningItem,
2515
+ RuntimeState,
2516
+ SemanticEvent,
2576
2517
  SituationSpecification,
2577
- SpaceEvent,
2578
- defineAgentModule,
2579
- defineRuntime
2518
+ SystemMessageItem,
2519
+ TokenUsage,
2520
+ UserMessageItem,
2521
+ createAgent,
2522
+ createHuman,
2523
+ defineRuntime,
2524
+ supportedModels
2580
2525
  };
2581
2526
  //# sourceMappingURL=index.mjs.map