@ekairos/story 1.21.30-beta.0 → 1.21.32-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +174 -0
  2. package/dist/agent.builder.d.ts +52 -0
  3. package/dist/agent.builder.d.ts.map +1 -0
  4. package/dist/agent.builder.js +110 -0
  5. package/dist/agent.builder.js.map +1 -0
  6. package/dist/agent.d.ts +2 -119
  7. package/dist/agent.d.ts.map +1 -1
  8. package/dist/agent.engine.d.ts +75 -0
  9. package/dist/agent.engine.d.ts.map +1 -0
  10. package/dist/agent.engine.js +455 -0
  11. package/dist/agent.engine.js.map +1 -0
  12. package/dist/agent.js +8 -607
  13. package/dist/agent.js.map +1 -1
  14. package/dist/ekairos.config.d.ts +21 -0
  15. package/dist/ekairos.config.d.ts.map +1 -0
  16. package/dist/ekairos.config.js +26 -0
  17. package/dist/ekairos.config.js.map +1 -0
  18. package/dist/events.d.ts +11 -7
  19. package/dist/events.d.ts.map +1 -1
  20. package/dist/events.js +37 -210
  21. package/dist/events.js.map +1 -1
  22. package/dist/index.d.ts +4 -4
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +7 -25
  25. package/dist/index.js.map +1 -1
  26. package/dist/legacy.story.d.ts +5 -0
  27. package/dist/legacy.story.d.ts.map +1 -0
  28. package/dist/legacy.story.js +15 -0
  29. package/dist/legacy.story.js.map +1 -0
  30. package/dist/runtime.d.ts +12 -0
  31. package/dist/runtime.js +12 -0
  32. package/dist/schema-document.d.ts +0 -1
  33. package/dist/schema-document.js +14 -18
  34. package/dist/schema-document.js.map +1 -1
  35. package/dist/schema.d.ts +0 -1
  36. package/dist/schema.js +22 -26
  37. package/dist/schema.js.map +1 -1
  38. package/dist/steps/do-story-stream-step.d.ts +29 -0
  39. package/dist/steps/do-story-stream-step.d.ts.map +1 -0
  40. package/dist/steps/do-story-stream-step.js +89 -0
  41. package/dist/steps/do-story-stream-step.js.map +1 -0
  42. package/dist/steps/index.d.ts +1 -3
  43. package/dist/steps/index.d.ts.map +1 -1
  44. package/dist/steps/index.js +3 -17
  45. package/dist/steps/index.js.map +1 -1
  46. package/dist/steps/store.steps.d.ts +43 -0
  47. package/dist/steps/store.steps.d.ts.map +1 -0
  48. package/dist/steps/store.steps.js +123 -0
  49. package/dist/steps/store.steps.js.map +1 -0
  50. package/dist/steps/story.steps.d.ts +35 -0
  51. package/dist/steps/story.steps.d.ts.map +1 -0
  52. package/dist/steps/story.steps.js +59 -0
  53. package/dist/steps/story.steps.js.map +1 -0
  54. package/dist/steps/stream.steps.d.ts +28 -0
  55. package/dist/steps/stream.steps.d.ts.map +1 -0
  56. package/dist/steps/stream.steps.js +75 -0
  57. package/dist/steps/stream.steps.js.map +1 -0
  58. package/dist/stores/instant.document-parser.d.ts +5 -0
  59. package/dist/stores/instant.document-parser.d.ts.map +1 -0
  60. package/dist/stores/instant.document-parser.js +116 -0
  61. package/dist/stores/instant.document-parser.js.map +1 -0
  62. package/dist/stores/instant.documents.d.ts +16 -0
  63. package/dist/stores/instant.documents.js +108 -0
  64. package/dist/stores/instant.store.d.ts +40 -0
  65. package/dist/stores/instant.store.d.ts.map +1 -0
  66. package/dist/stores/instant.store.js +207 -0
  67. package/dist/stores/instant.store.js.map +1 -0
  68. package/dist/story.builder.d.ts +116 -0
  69. package/dist/story.builder.d.ts.map +1 -0
  70. package/dist/story.builder.js +130 -0
  71. package/dist/story.builder.js.map +1 -0
  72. package/dist/story.config.d.ts +43 -0
  73. package/dist/story.config.d.ts.map +1 -0
  74. package/dist/story.config.js +57 -0
  75. package/dist/story.config.js.map +1 -0
  76. package/dist/story.d.ts +2 -50
  77. package/dist/story.d.ts.map +1 -1
  78. package/dist/story.engine.d.ts +174 -0
  79. package/dist/story.engine.d.ts.map +1 -0
  80. package/dist/story.engine.js +283 -0
  81. package/dist/story.engine.js.map +1 -0
  82. package/dist/story.js +6 -55
  83. package/dist/story.js.map +1 -1
  84. package/dist/story.legacy.d.ts +12 -0
  85. package/dist/story.legacy.d.ts.map +1 -0
  86. package/dist/story.legacy.js +15 -0
  87. package/dist/story.legacy.js.map +1 -0
  88. package/dist/story.registry.d.ts +21 -0
  89. package/dist/story.registry.d.ts.map +1 -0
  90. package/dist/story.registry.js +30 -0
  91. package/dist/story.registry.js.map +1 -0
  92. package/dist/story.store.d.ts +59 -0
  93. package/dist/story.store.d.ts.map +1 -0
  94. package/dist/story.store.js +1 -0
  95. package/dist/story.store.js.map +1 -0
  96. package/dist/story.streams.d.ts +55 -0
  97. package/dist/story.streams.d.ts.map +1 -0
  98. package/dist/story.streams.js +99 -0
  99. package/dist/story.streams.js.map +1 -0
  100. package/dist/story.toolcalls.d.ts +60 -0
  101. package/dist/story.toolcalls.d.ts.map +1 -0
  102. package/dist/story.toolcalls.js +73 -0
  103. package/dist/story.toolcalls.js.map +1 -0
  104. package/dist/tools-to-model-tools.d.ts +19 -0
  105. package/dist/tools-to-model-tools.js +21 -0
  106. package/dist/workflow.d.ts +20 -0
  107. package/dist/workflow.js +27 -0
  108. package/package.json +15 -4
package/dist/agent.js CHANGED
@@ -1,610 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Agent = exports.Story = void 0;
4
- exports.agent = agent;
5
- exports.createAgent = createAgent;
6
- const admin_1 = require("@instantdb/admin");
7
- const ai_1 = require("ai");
8
- const openai_1 = require("@ai-sdk/openai");
9
- const zod_1 = require("zod");
10
- const braintrust_1 = require("braintrust");
11
- const service_1 = require("./service");
12
- const events_1 = require("./events");
13
- // Inicializar Braintrust logger
14
- const logger = (0, braintrust_1.initLogger)({
15
- projectName: "pulzar platform",
16
- apiKey: process.env.BRAINTRUST_API_KEY,
17
- });
18
- const createDataStream = ai_1.createUIMessageStream;
19
- class Story {
20
- constructor(db, opts = {}) {
21
- this.opts = opts;
22
- this.db = db;
23
- this.agentService = new service_1.AgentService(db);
24
- }
25
- getModel(context) {
26
- return "openai/gpt-5";
27
- }
28
- includeBaseTools() {
29
- return { createMessage: true, requestDirection: true, end: true };
30
- }
31
- async getFinalizationToolNames() {
32
- return [];
33
- }
34
- getBaseTools(dataStream, threadId) {
35
- const include = this.includeBaseTools();
36
- const baseTools = {};
37
- if (include.createMessage) {
38
- baseTools.createMessage = (0, ai_1.tool)({
39
- description: "Send a message to the user. Use for final confirmations or information.",
40
- inputSchema: zod_1.z.object({
41
- message: zod_1.z.string().describe("Message for the user in markdown format")
42
- }),
43
- });
44
- }
45
- if (include.requestDirection) {
46
- baseTools.requestDirection = (0, ai_1.tool)({
47
- description: "Ask a human for guidance when blocked or unsure.",
48
- inputSchema: zod_1.z.object({
49
- issue: zod_1.z.string(),
50
- context: zod_1.z.string(),
51
- suggestedActions: zod_1.z.array(zod_1.z.string()).optional(),
52
- urgency: zod_1.z.enum(["low", "medium", "high"]).default("medium"),
53
- }),
54
- });
55
- }
56
- if (include.end) {
57
- baseTools.end = (0, ai_1.tool)({
58
- description: "End the current interaction loop.",
59
- inputSchema: zod_1.z.object({}).strict(),
60
- execute: async () => {
61
- return { success: true, message: "Ended" };
62
- },
63
- });
64
- }
65
- return baseTools;
66
- }
67
- async executeCreateMessage(eventId, args, threadId, dataStream) {
68
- const assistantMessage = { id: eventId, role: "assistant", content: args.message, createdAt: new Date() };
69
- try {
70
- await this.saveMessagesToThread(threadId, [assistantMessage]);
71
- }
72
- catch { }
73
- if (dataStream) {
74
- //dataStream.writeData({ type: "user-response", message: args.message, responseType: args.type, includeContext: Boolean(args.includeContext), timestamp: new Date().toISOString() } as any)
75
- }
76
- return { success: true, message: args.message, data: { messageId: assistantMessage.id, threadId } };
77
- }
78
- async executeRequestDirection(eventId, args, threadId, _dataStream) {
79
- const systemMessage = { id: eventId, role: "assistant", content: `Direction requested: ${args.issue}\nContext: ${args.context}`, createdAt: new Date() };
80
- return { success: true, message: "Direction requested", data: { messageId: systemMessage.id, threadId } };
81
- }
82
- async progressStream(incomingEvent, contextIdentifier, options) {
83
- // get or create context
84
- const currentContext = await this.agentService.getOrCreateContext(contextIdentifier);
85
- const contextSelector = contextIdentifier?.id
86
- ? { id: String(contextIdentifier.id) }
87
- : contextIdentifier?.key
88
- ? { key: contextIdentifier.key }
89
- : { id: String(currentContext.id) };
90
- // save incoming event
91
- const triggerEvent = await this.agentService.saveEvent(contextSelector, incomingEvent);
92
- const triggerEventId = triggerEvent.id; // trigger event id
93
- const eventId = (0, admin_1.id)(); // reaction event id
94
- // Set context status to "streaming" before creating execution
95
- await this.agentService.updateContextStatus(contextSelector, "streaming");
96
- // create execution and set context status
97
- const execution = await this.agentService.createExecution(contextSelector, triggerEventId, eventId);
98
- const executionId = execution.id;
99
- let latestReactionEvent = null;
100
- let executionStatus = "executing";
101
- const markFailure = async () => {
102
- if (latestReactionEvent && latestReactionEvent.status !== "failed") {
103
- try {
104
- latestReactionEvent = await this.agentService.updateEvent(latestReactionEvent.id, {
105
- ...latestReactionEvent,
106
- status: "failed",
107
- });
108
- }
109
- catch (eventError) {
110
- console.error("Failed to mark reaction event as failed", eventError);
111
- }
112
- }
113
- if (executionStatus === "executing") {
114
- try {
115
- await this.agentService.completeExecution(contextSelector, executionId, "failed");
116
- executionStatus = "failed";
117
- }
118
- catch (executionError) {
119
- console.error("Failed to mark execution as failed", executionError);
120
- }
121
- }
122
- };
123
- const dataStreamResult = createDataStream({
124
- execute: async ({ writer: dataStream }) => {
125
- let loopSafety = 0;
126
- const MAX_LOOPS = 20;
127
- // load previous events (already in chronological order from InstantDB)
128
- const events = await this.agentService.getEvents(contextSelector);
129
- const contextId = currentContext.id;
130
- console.log("[agent] Loaded events from InstantDB:", {
131
- contextId,
132
- eventsCount: events.length,
133
- eventsPreview: events.slice(-3).map((e) => ({
134
- id: e.id,
135
- type: e.type,
136
- createdAt: e.createdAt
137
- }))
138
- });
139
- let reactionEvent = await this.agentService.saveEvent(contextSelector, {
140
- id: eventId,
141
- type: "assistant",
142
- channel: "agent",
143
- createdAt: new Date().toISOString(),
144
- content: { parts: [] },
145
- status: "pending",
146
- });
147
- latestReactionEvent = reactionEvent;
148
- dataStream.write({ type: "event-start", data: { eventId: eventId } });
149
- while (loopSafety < MAX_LOOPS) {
150
- dataStream.write({ type: "start-step" });
151
- loopSafety++;
152
- // Read context
153
- const currentContext = await this.agentService.getContext(contextSelector);
154
- dataStream.write({ type: "data-context-id", data: { contextId: currentContext.id } });
155
- // Initialize on each loop and get new context data
156
- const contextContent = await this.initialize(currentContext);
157
- // Update context
158
- const updatedContext = await this.agentService.updateContextContent({ id: String(currentContext.id) }, contextContent);
159
- // Build tools
160
- const subclassToolsAll = await this.buildTools(updatedContext, dataStream);
161
- // Build base tools for agent loop control
162
- const baseTools = this.getBaseTools(dataStream, String(updatedContext.id));
163
- const tools = { ...subclassToolsAll, ...baseTools };
164
- // Add web search if enabled
165
- if (options?.webSearch) {
166
- tools.web_search = openai_1.openai.tools.webSearch();
167
- }
168
- // Extract execute functions from tools
169
- const executeMap = {};
170
- for (const [name, t] of Object.entries(subclassToolsAll)) {
171
- if (t.execute) {
172
- executeMap[name] = t.execute;
173
- }
174
- }
175
- const include = this.includeBaseTools();
176
- if (include.createMessage) {
177
- executeMap["createMessage"] = (args) => this.executeCreateMessage(eventId, args, String(updatedContext.id), dataStream);
178
- }
179
- if (include.requestDirection) {
180
- executeMap["requestDirection"] = (args) => this.executeRequestDirection(eventId, args, String(updatedContext.id), dataStream);
181
- }
182
- for (const [, t] of Object.entries(tools)) {
183
- delete t.execute;
184
- }
185
- const messagesForModel = await (0, events_1.convertEventsToModelMessages)(reactionEvent.status !== "pending"
186
- ? [...events, reactionEvent]
187
- : [...events], this.db);
188
- const systemPrompt = await this.buildSystemPrompt(updatedContext);
189
- const providerOptions = {};
190
- const hasReasoning = options?.reasoningEffort && options.reasoningEffort !== "off";
191
- if (hasReasoning) {
192
- providerOptions.openai = {
193
- reasoningEffort: options.reasoningEffort,
194
- reasoningSummary: 'detailed',
195
- };
196
- console.log("[agent] Reasoning enabled:", {
197
- reasoningEffort: options.reasoningEffort,
198
- model: this.getModel(updatedContext),
199
- providerOptions
200
- });
201
- }
202
- else {
203
- console.log("[agent] Reasoning disabled or off");
204
- }
205
- // Allow more steps when using reasoning to give the model time to think
206
- const maxSteps = hasReasoning ? 5 : 1;
207
- const result = (0, ai_1.streamText)({
208
- model: this.getModel(updatedContext),
209
- system: systemPrompt,
210
- messages: messagesForModel,
211
- tools,
212
- toolChoice: "required",
213
- onStepFinish: (step) => {
214
- console.log("onStepFinish", step);
215
- },
216
- stopWhen: (0, ai_1.stepCountIs)(maxSteps),
217
- experimental_transform: (0, ai_1.smoothStream)({
218
- delayInMs: 30,
219
- chunking: 'word',
220
- }),
221
- ...(Object.keys(providerOptions).length > 0 && { providerOptions }),
222
- });
223
- result.consumeStream();
224
- // create promise
225
- let resolveFinish;
226
- let rejectFinish;
227
- const finishPromise = new Promise((resolve, reject) => {
228
- resolveFinish = resolve;
229
- rejectFinish = reject;
230
- });
231
- dataStream.merge(result.toUIMessageStream({
232
- sendStart: false,
233
- generateMessageId: () => {
234
- return eventId;
235
- },
236
- messageMetadata(options) {
237
- return {
238
- eventId: eventId,
239
- };
240
- },
241
- onFinish: ({ messages }) => {
242
- console.log("[agent] Messages finished:", messages.map((m) => ({
243
- role: m.role,
244
- parts: m.parts?.map((p) => ({
245
- type: p.type,
246
- text: p.text?.substring(0, 100),
247
- hasReasoning: p.type === "reasoning"
248
- }))
249
- })));
250
- const lastEvent = (0, events_1.createAssistantEventFromUIMessages)(eventId, messages);
251
- resolveFinish(lastEvent);
252
- },
253
- onError: (e) => {
254
- console.error("Agent error:", e);
255
- rejectFinish(e);
256
- const message = e instanceof Error ? e.message : String(e);
257
- return message;
258
- }
259
- }).pipeThrough(new TransformStream({
260
- transform(chunk, controller) {
261
- if (chunk.type === "start") {
262
- return;
263
- }
264
- if (chunk.type === "finish-step") {
265
- return;
266
- }
267
- if (chunk.type === "start-step") {
268
- return;
269
- }
270
- if (chunk.type === "finish") {
271
- return;
272
- }
273
- controller.enqueue(chunk);
274
- }
275
- })));
276
- // wait for the on finish here
277
- const lastEvent = await finishPromise;
278
- const toolCalls = lastEvent.content.parts.reduce((acc, p) => {
279
- if (typeof p.type === "string" && p.type.startsWith("tool-")) {
280
- const toolName = p.type.split("-")[1];
281
- acc.push({ toolCallId: p.toolCallId, toolName: toolName, args: p.input });
282
- }
283
- return acc;
284
- }, []);
285
- console.log("agent.toolCalls.detected", {
286
- eventId,
287
- toolCalls: toolCalls.map((call) => ({ toolCallId: call.toolCallId, toolName: call.toolName }))
288
- });
289
- if (!toolCalls.length) {
290
- const shouldEndInteraction = await this.callOnEnd(lastEvent);
291
- if (shouldEndInteraction) {
292
- break;
293
- }
294
- continue;
295
- }
296
- const reactionEventWithParts = {
297
- ...reactionEvent,
298
- content: { parts: [...reactionEvent.content.parts, ...lastEvent.content.parts] },
299
- };
300
- let currentEventState = await this.agentService.updateEvent(reactionEvent.id, reactionEventWithParts);
301
- latestReactionEvent = currentEventState;
302
- const executionResults = await Promise.all(toolCalls.map(async (tc) => {
303
- console.log("agent.toolCall.selected", {
304
- eventId,
305
- toolCallId: tc.toolCallId,
306
- toolName: tc.toolName
307
- });
308
- let execSuccess = true;
309
- let execMessage = "Executed";
310
- let execResult = null;
311
- try {
312
- const execFn = executeMap[tc.toolName];
313
- if (execFn) {
314
- console.log("agent.toolCall.execute.start", { toolCallId: tc.toolCallId, toolName: tc.toolName });
315
- execResult = await execFn(tc.args);
316
- execSuccess = execResult?.success !== false;
317
- execMessage = execResult?.message || execMessage;
318
- console.log("agent.toolCall.execute.success", {
319
- toolCallId: tc.toolCallId,
320
- toolName: tc.toolName,
321
- success: execSuccess
322
- });
323
- console.log("agent.toolCall.execute.result", {
324
- toolCallId: tc.toolCallId,
325
- toolName: tc.toolName,
326
- result: execResult
327
- });
328
- }
329
- }
330
- catch (err) {
331
- execSuccess = false;
332
- execMessage = err.message;
333
- console.error("agent.toolCall.execute.error", {
334
- toolCallId: tc.toolCallId,
335
- toolName: tc.toolName,
336
- error: err
337
- });
338
- }
339
- return { tc, execSuccess, execMessage, execResult };
340
- }));
341
- let exitOuterLoop = false;
342
- const customFinalizationTools = await this.getFinalizationToolNames();
343
- const allFinalToolNames = [...Story.FINAL_TOOL_NAMES, ...customFinalizationTools];
344
- for (const { tc, execSuccess, execMessage, execResult } of executionResults) {
345
- try {
346
- if (execSuccess) {
347
- dataStream.write({
348
- type: "tool-output-available",
349
- toolCallId: tc.toolCallId,
350
- output: execResult,
351
- });
352
- }
353
- else {
354
- dataStream.write({
355
- type: "tool-output-error",
356
- toolCallId: tc.toolCallId,
357
- errorText: String(execMessage || "Error"),
358
- });
359
- }
360
- }
361
- catch (e) {
362
- console.error("Failed to write tool result to stream", e);
363
- }
364
- const existingParts = currentEventState?.content?.parts || [];
365
- const mergedParts = existingParts.map((p) => {
366
- if (p.type === `tool-${tc.toolName}` && p.toolCallId === tc.toolCallId) {
367
- if (execSuccess) {
368
- return {
369
- ...p,
370
- state: "output-available",
371
- output: execResult,
372
- };
373
- }
374
- return {
375
- ...p,
376
- state: "output-error",
377
- errorText: String(execMessage || "Error"),
378
- };
379
- }
380
- return p;
381
- });
382
- currentEventState = await this.agentService.updateEvent(currentEventState.id, {
383
- id: currentEventState.id,
384
- type: currentEventState.type,
385
- channel: "agent",
386
- createdAt: currentEventState.createdAt,
387
- content: { parts: mergedParts },
388
- });
389
- dataStream.write({ type: "finish-step" });
390
- await this.opts.onToolCallExecuted?.({
391
- id: currentEventState.id,
392
- toolCall: tc,
393
- event: currentEventState.id,
394
- success: execSuccess,
395
- message: execMessage,
396
- result: execResult,
397
- });
398
- let shouldEnd = false;
399
- if (!execSuccess) {
400
- const shouldEndInteraction = await this.callOnEnd(lastEvent);
401
- if (shouldEndInteraction) {
402
- shouldEnd = true;
403
- }
404
- }
405
- if (!shouldEnd) {
406
- if (allFinalToolNames.includes(tc.toolName)) {
407
- const shouldEndInteraction = await this.callOnEnd(lastEvent);
408
- if (shouldEndInteraction) {
409
- shouldEnd = true;
410
- }
411
- }
412
- }
413
- if (shouldEnd) {
414
- dataStream.write({ type: "finish", override: true });
415
- exitOuterLoop = true;
416
- break;
417
- }
418
- }
419
- reactionEvent = currentEventState;
420
- if (exitOuterLoop) {
421
- break;
422
- }
423
- }
424
- reactionEvent = await this.agentService.updateEvent(reactionEvent.id, {
425
- ...reactionEvent,
426
- status: "completed",
427
- });
428
- latestReactionEvent = reactionEvent;
429
- try {
430
- await this.agentService.completeExecution(contextSelector, executionId, "completed");
431
- executionStatus = "completed";
432
- }
433
- catch (error) {
434
- console.error("Failed to mark execution as completed", error);
435
- }
436
- },
437
- onError: (error) => {
438
- console.error("Agent error:", error);
439
- void markFailure();
440
- return error instanceof Error ? error.message : String(error);
441
- },
442
- onFinish: async () => {
443
- if (executionStatus === "executing") {
444
- try {
445
- await this.agentService.completeExecution(contextSelector, executionId, "completed");
446
- executionStatus = "completed";
447
- }
448
- catch (executionError) {
449
- console.error("Failed to finalize execution on finish", executionError);
450
- }
451
- }
452
- console.log("Agent finished");
453
- }
454
- });
455
- // start the stream
456
- const dataStreamFilteredResult = dataStreamResult.pipeThrough(new TransformStream({
457
- transform(chunk, controller) {
458
- if (chunk.type === "start") {
459
- console.log("start", chunk.data);
460
- return;
461
- }
462
- if (chunk.type === "event-start") {
463
- controller.enqueue({ type: "start", messageId: chunk.data.eventId });
464
- return;
465
- }
466
- controller.enqueue(chunk);
467
- }
468
- }));
469
- return {
470
- contextId: currentContext.id,
471
- triggerEventId,
472
- reactionEventId: eventId,
473
- stream: dataStreamFilteredResult,
474
- executionId,
475
- };
476
- }
477
- async saveMessagesToThread(threadId, messages) {
478
- // Placeholder for persistence hook. Not implemented in current scope.
479
- return;
480
- }
481
- async callOnEnd(lastEvent) {
482
- if (!this.opts.onEnd) {
483
- return true;
484
- }
485
- try {
486
- const result = await this.opts.onEnd(lastEvent);
487
- if (typeof result === "boolean") {
488
- return result;
489
- }
490
- if (result && typeof result === "object") {
491
- if (Object.prototype.hasOwnProperty.call(result, "end")) {
492
- return Boolean(result.end);
493
- }
494
- }
495
- return true;
496
- }
497
- catch (error) {
498
- console.error("onEnd callback failed", error);
499
- return true;
500
- }
501
- }
502
- }
503
- exports.Story = Story;
504
- exports.Agent = Story;
505
- Story.FINAL_TOOL_NAMES = ["createMessage", "requestDirection", "end"];
506
- function agent(config) {
507
- class FunctionalAgent extends Story {
508
- constructor() {
509
- super(config.db, config.opts);
510
- this.__config = config;
511
- }
512
- includeBaseTools() {
513
- if (config.includeBaseTools) {
514
- return {
515
- createMessage: config.includeBaseTools.createMessage ?? true,
516
- requestDirection: config.includeBaseTools.requestDirection ?? true,
517
- end: config.includeBaseTools.end ?? true,
518
- };
519
- }
520
- return super.includeBaseTools();
521
- }
522
- async buildSystemPrompt(context) {
523
- return config.systemPrompt(context);
524
- }
525
- async buildTools(context, dataStream) {
526
- return config.tools(context, dataStream);
527
- }
528
- async initialize(context) {
529
- return config.context(context);
530
- }
531
- getModel(context) {
532
- if (typeof config.model === 'function') {
533
- return config.model(context);
534
- }
535
- return config.model || super.getModel(context);
536
- }
537
- }
538
- const instance = new FunctionalAgent();
539
- return Object.assign(instance, { __config: config });
540
- }
541
- function assertConfigComplete(config) {
542
- if (!config.db) {
543
- throw new Error("createAgent: Debes proporcionar db como parámetro.");
544
- }
545
- if (!config.context) {
546
- throw new Error("createAgent: Debes definir context() antes de construir el agente.");
547
- }
548
- if (!config.systemPrompt) {
549
- throw new Error("createAgent: Debes definir systemPrompt() antes de construir el agente.");
550
- }
551
- if (!config.tools) {
552
- throw new Error("createAgent: Debes definir tools() antes de construir el agente.");
553
- }
554
- }
555
- function ensureInitializedContext(context) {
556
- if (!context.content) {
557
- throw new Error("createAgent: context() debe devolver datos antes de usar systemPrompt/tools.");
558
- }
559
- return context;
560
- }
561
- function createAgent(db) {
562
- const initializeBuilder = (initializer) => {
563
- const typedInitializer = (context) => initializer(context);
564
- const fluentState = {
565
- db,
566
- context: typedInitializer,
567
- };
568
- const builder = {
569
- systemPrompt(systemPrompt) {
570
- fluentState.systemPrompt = (context) => systemPrompt(ensureInitializedContext(context));
571
- return builder;
572
- },
573
- tools(toolsFactory) {
574
- fluentState.tools = (context, dataStream) => toolsFactory(ensureInitializedContext(context), dataStream);
575
- return builder;
576
- },
577
- model(model) {
578
- if (typeof model === "function") {
579
- fluentState.model = (context) => model(ensureInitializedContext(context));
580
- }
581
- else {
582
- fluentState.model = model;
583
- }
584
- return builder;
585
- },
586
- opts(options) {
587
- fluentState.opts = options;
588
- return builder;
589
- },
590
- includeBaseTools(baseTools) {
591
- fluentState.includeBaseTools = baseTools;
592
- return builder;
593
- },
594
- config() {
595
- assertConfigComplete(fluentState);
596
- return fluentState;
597
- },
598
- build() {
599
- assertConfigComplete(fluentState);
600
- return agent(fluentState);
601
- },
602
- };
603
- return builder;
604
- };
605
- return {
606
- context: initializeBuilder,
607
- initialize: initializeBuilder,
608
- };
609
- }
3
+ exports.createStory = exports.story = exports.Story = void 0;
4
+ var agent_engine_1 = require("./agent.engine");
5
+ // engine
6
+ Object.defineProperty(exports, "Story", { enumerable: true, get: function () { return agent_engine_1.Story; } });
7
+ var agent_builder_1 = require("./agent.builder");
8
+ // builder
9
+ Object.defineProperty(exports, "story", { enumerable: true, get: function () { return agent_builder_1.story; } });
10
+ Object.defineProperty(exports, "createStory", { enumerable: true, get: function () { return agent_builder_1.createStory; } });
610
11
  //# sourceMappingURL=agent.js.map