@copilotkitnext/runtime 0.0.1

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 (47) hide show
  1. package/.cursor/rules/runtime.always.mdc +9 -0
  2. package/.turbo/turbo-build.log +22 -0
  3. package/.turbo/turbo-check-types.log +4 -0
  4. package/.turbo/turbo-lint.log +56 -0
  5. package/.turbo/turbo-test$colon$coverage.log +149 -0
  6. package/.turbo/turbo-test.log +107 -0
  7. package/LICENSE +11 -0
  8. package/README-RUNNERS.md +78 -0
  9. package/dist/index.d.mts +245 -0
  10. package/dist/index.d.ts +245 -0
  11. package/dist/index.js +1873 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/index.mjs +1841 -0
  14. package/dist/index.mjs.map +1 -0
  15. package/eslint.config.mjs +3 -0
  16. package/package.json +62 -0
  17. package/src/__tests__/get-runtime-info.test.ts +117 -0
  18. package/src/__tests__/handle-run.test.ts +69 -0
  19. package/src/__tests__/handle-transcribe.test.ts +289 -0
  20. package/src/__tests__/in-process-agent-runner-messages.test.ts +599 -0
  21. package/src/__tests__/in-process-agent-runner.test.ts +726 -0
  22. package/src/__tests__/middleware.test.ts +432 -0
  23. package/src/__tests__/routing.test.ts +257 -0
  24. package/src/endpoint.ts +150 -0
  25. package/src/handler.ts +3 -0
  26. package/src/handlers/get-runtime-info.ts +50 -0
  27. package/src/handlers/handle-connect.ts +144 -0
  28. package/src/handlers/handle-run.ts +156 -0
  29. package/src/handlers/handle-transcribe.ts +126 -0
  30. package/src/index.ts +8 -0
  31. package/src/middleware.ts +232 -0
  32. package/src/runner/__tests__/enterprise-runner.test.ts +992 -0
  33. package/src/runner/__tests__/event-compaction.test.ts +253 -0
  34. package/src/runner/__tests__/in-memory-runner.test.ts +483 -0
  35. package/src/runner/__tests__/sqlite-runner.test.ts +975 -0
  36. package/src/runner/agent-runner.ts +27 -0
  37. package/src/runner/enterprise.ts +653 -0
  38. package/src/runner/event-compaction.ts +250 -0
  39. package/src/runner/in-memory.ts +322 -0
  40. package/src/runner/index.ts +0 -0
  41. package/src/runner/sqlite.ts +481 -0
  42. package/src/runtime.ts +53 -0
  43. package/src/transcription-service/transcription-service-openai.ts +29 -0
  44. package/src/transcription-service/transcription-service.ts +11 -0
  45. package/tsconfig.json +13 -0
  46. package/tsup.config.ts +11 -0
  47. package/vitest.config.mjs +15 -0
package/dist/index.js ADDED
@@ -0,0 +1,1873 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ CopilotRuntime: () => CopilotRuntime,
34
+ EnterpriseAgentRunner: () => EnterpriseAgentRunner,
35
+ InMemoryAgentRunner: () => InMemoryAgentRunner,
36
+ SqliteAgentRunner: () => SqliteAgentRunner,
37
+ VERSION: () => VERSION,
38
+ createCopilotEndpoint: () => createCopilotEndpoint
39
+ });
40
+ module.exports = __toCommonJS(index_exports);
41
+
42
+ // package.json
43
+ var package_default = {
44
+ name: "@copilotkitnext/runtime",
45
+ version: "0.0.1",
46
+ description: "Server-side runtime package for CopilotKit2",
47
+ main: "dist/index.js",
48
+ types: "dist/index.d.ts",
49
+ exports: {
50
+ ".": {
51
+ types: "./dist/index.d.ts",
52
+ import: "./dist/index.mjs",
53
+ require: "./dist/index.js"
54
+ }
55
+ },
56
+ publishConfig: {
57
+ access: "public"
58
+ },
59
+ scripts: {
60
+ build: "tsup",
61
+ prepublishOnly: "pnpm run build",
62
+ dev: "tsup --watch",
63
+ lint: "eslint . --max-warnings 0",
64
+ "check-types": "tsc --noEmit",
65
+ clean: "rm -rf dist",
66
+ test: "vitest run",
67
+ "test:watch": "vitest",
68
+ "test:coverage": "vitest run --coverage"
69
+ },
70
+ devDependencies: {
71
+ "@copilotkitnext/eslint-config": "workspace:*",
72
+ "@copilotkitnext/typescript-config": "workspace:*",
73
+ "@types/better-sqlite3": "^7.6.13",
74
+ "@types/node": "^22.15.3",
75
+ "better-sqlite3": "^12.2.0",
76
+ eslint: "^9.30.0",
77
+ "ioredis-mock": "^8.9.0",
78
+ openai: "^5.9.0",
79
+ tsup: "^8.5.0",
80
+ typescript: "5.8.2",
81
+ vitest: "^3.0.5"
82
+ },
83
+ dependencies: {
84
+ "@ag-ui/client": "0.0.36-alpha.1",
85
+ "@ag-ui/core": "0.0.36-alpha.1",
86
+ "@ag-ui/encoder": "0.0.36-alpha.1",
87
+ "@copilotkitnext/shared": "workspace:*",
88
+ hono: "^4.6.13",
89
+ ioredis: "^5.7.0",
90
+ kysely: "^0.28.5",
91
+ rxjs: "7.8.1"
92
+ },
93
+ peerDependencies: {
94
+ "better-sqlite3": "^12.2.0",
95
+ openai: "^5.9.0"
96
+ },
97
+ peerDependenciesMeta: {
98
+ "better-sqlite3": {
99
+ optional: true
100
+ }
101
+ },
102
+ engines: {
103
+ node: ">=18"
104
+ }
105
+ };
106
+
107
+ // src/runner/agent-runner.ts
108
+ var AgentRunner = class {
109
+ };
110
+
111
+ // src/runner/in-memory.ts
112
+ var import_rxjs = require("rxjs");
113
+ var import_client2 = require("@ag-ui/client");
114
+
115
+ // src/runner/event-compaction.ts
116
+ var import_client = require("@ag-ui/client");
117
+ function compactEvents(events) {
118
+ const compacted = [];
119
+ const pendingTextMessages = /* @__PURE__ */ new Map();
120
+ const pendingToolCalls = /* @__PURE__ */ new Map();
121
+ for (const event of events) {
122
+ if (event.type === import_client.EventType.TEXT_MESSAGE_START) {
123
+ const startEvent = event;
124
+ const messageId = startEvent.messageId;
125
+ if (!pendingTextMessages.has(messageId)) {
126
+ pendingTextMessages.set(messageId, {
127
+ contents: [],
128
+ otherEvents: []
129
+ });
130
+ }
131
+ const pending = pendingTextMessages.get(messageId);
132
+ pending.start = startEvent;
133
+ } else if (event.type === import_client.EventType.TEXT_MESSAGE_CONTENT) {
134
+ const contentEvent = event;
135
+ const messageId = contentEvent.messageId;
136
+ if (!pendingTextMessages.has(messageId)) {
137
+ pendingTextMessages.set(messageId, {
138
+ contents: [],
139
+ otherEvents: []
140
+ });
141
+ }
142
+ const pending = pendingTextMessages.get(messageId);
143
+ pending.contents.push(contentEvent);
144
+ } else if (event.type === import_client.EventType.TEXT_MESSAGE_END) {
145
+ const endEvent = event;
146
+ const messageId = endEvent.messageId;
147
+ if (!pendingTextMessages.has(messageId)) {
148
+ pendingTextMessages.set(messageId, {
149
+ contents: [],
150
+ otherEvents: []
151
+ });
152
+ }
153
+ const pending = pendingTextMessages.get(messageId);
154
+ pending.end = endEvent;
155
+ flushTextMessage(messageId, pending, compacted);
156
+ pendingTextMessages.delete(messageId);
157
+ } else if (event.type === import_client.EventType.TOOL_CALL_START) {
158
+ const startEvent = event;
159
+ const toolCallId = startEvent.toolCallId;
160
+ if (!pendingToolCalls.has(toolCallId)) {
161
+ pendingToolCalls.set(toolCallId, {
162
+ args: [],
163
+ otherEvents: []
164
+ });
165
+ }
166
+ const pending = pendingToolCalls.get(toolCallId);
167
+ pending.start = startEvent;
168
+ } else if (event.type === import_client.EventType.TOOL_CALL_ARGS) {
169
+ const argsEvent = event;
170
+ const toolCallId = argsEvent.toolCallId;
171
+ if (!pendingToolCalls.has(toolCallId)) {
172
+ pendingToolCalls.set(toolCallId, {
173
+ args: [],
174
+ otherEvents: []
175
+ });
176
+ }
177
+ const pending = pendingToolCalls.get(toolCallId);
178
+ pending.args.push(argsEvent);
179
+ } else if (event.type === import_client.EventType.TOOL_CALL_END) {
180
+ const endEvent = event;
181
+ const toolCallId = endEvent.toolCallId;
182
+ if (!pendingToolCalls.has(toolCallId)) {
183
+ pendingToolCalls.set(toolCallId, {
184
+ args: [],
185
+ otherEvents: []
186
+ });
187
+ }
188
+ const pending = pendingToolCalls.get(toolCallId);
189
+ pending.end = endEvent;
190
+ flushToolCall(toolCallId, pending, compacted);
191
+ pendingToolCalls.delete(toolCallId);
192
+ } else {
193
+ let addedToBuffer = false;
194
+ for (const [messageId, pending] of pendingTextMessages) {
195
+ if (pending.start && !pending.end) {
196
+ pending.otherEvents.push(event);
197
+ addedToBuffer = true;
198
+ break;
199
+ }
200
+ }
201
+ if (!addedToBuffer) {
202
+ for (const [toolCallId, pending] of pendingToolCalls) {
203
+ if (pending.start && !pending.end) {
204
+ pending.otherEvents.push(event);
205
+ addedToBuffer = true;
206
+ break;
207
+ }
208
+ }
209
+ }
210
+ if (!addedToBuffer) {
211
+ compacted.push(event);
212
+ }
213
+ }
214
+ }
215
+ for (const [messageId, pending] of pendingTextMessages) {
216
+ flushTextMessage(messageId, pending, compacted);
217
+ }
218
+ for (const [toolCallId, pending] of pendingToolCalls) {
219
+ flushToolCall(toolCallId, pending, compacted);
220
+ }
221
+ return compacted;
222
+ }
223
+ function flushTextMessage(messageId, pending, compacted) {
224
+ if (pending.start) {
225
+ compacted.push(pending.start);
226
+ }
227
+ if (pending.contents.length > 0) {
228
+ const concatenatedDelta = pending.contents.map((c) => c.delta).join("");
229
+ const compactedContent = {
230
+ type: import_client.EventType.TEXT_MESSAGE_CONTENT,
231
+ messageId,
232
+ delta: concatenatedDelta
233
+ };
234
+ compacted.push(compactedContent);
235
+ }
236
+ if (pending.end) {
237
+ compacted.push(pending.end);
238
+ }
239
+ for (const otherEvent of pending.otherEvents) {
240
+ compacted.push(otherEvent);
241
+ }
242
+ }
243
+ function flushToolCall(toolCallId, pending, compacted) {
244
+ if (pending.start) {
245
+ compacted.push(pending.start);
246
+ }
247
+ if (pending.args.length > 0) {
248
+ const concatenatedArgs = pending.args.map((a) => a.delta).join("");
249
+ const compactedArgs = {
250
+ type: import_client.EventType.TOOL_CALL_ARGS,
251
+ toolCallId,
252
+ delta: concatenatedArgs
253
+ };
254
+ compacted.push(compactedArgs);
255
+ }
256
+ if (pending.end) {
257
+ compacted.push(pending.end);
258
+ }
259
+ for (const otherEvent of pending.otherEvents) {
260
+ compacted.push(otherEvent);
261
+ }
262
+ }
263
+
264
+ // src/runner/in-memory.ts
265
+ var InMemoryEventStore = class {
266
+ constructor(threadId) {
267
+ this.threadId = threadId;
268
+ }
269
+ /** The subject that current consumers subscribe to. */
270
+ subject = null;
271
+ /** True while a run is actively producing events. */
272
+ isRunning = false;
273
+ /** Lets stop() cancel the current producer. */
274
+ abortController = new AbortController();
275
+ /** Current run ID */
276
+ currentRunId = null;
277
+ /** Historic completed runs */
278
+ historicRuns = [];
279
+ };
280
+ var GLOBAL_STORE = /* @__PURE__ */ new Map();
281
+ var InMemoryAgentRunner = class extends AgentRunner {
282
+ convertMessageToEvents(message) {
283
+ const events = [];
284
+ if ((message.role === "assistant" || message.role === "user" || message.role === "developer" || message.role === "system") && message.content) {
285
+ const textStartEvent = {
286
+ type: import_client2.EventType.TEXT_MESSAGE_START,
287
+ messageId: message.id,
288
+ role: message.role
289
+ };
290
+ events.push(textStartEvent);
291
+ const textContentEvent = {
292
+ type: import_client2.EventType.TEXT_MESSAGE_CONTENT,
293
+ messageId: message.id,
294
+ delta: message.content
295
+ };
296
+ events.push(textContentEvent);
297
+ const textEndEvent = {
298
+ type: import_client2.EventType.TEXT_MESSAGE_END,
299
+ messageId: message.id
300
+ };
301
+ events.push(textEndEvent);
302
+ }
303
+ if (message.role === "assistant" && message.toolCalls) {
304
+ for (const toolCall of message.toolCalls) {
305
+ const toolStartEvent = {
306
+ type: import_client2.EventType.TOOL_CALL_START,
307
+ toolCallId: toolCall.id,
308
+ toolCallName: toolCall.function.name,
309
+ parentMessageId: message.id
310
+ };
311
+ events.push(toolStartEvent);
312
+ const toolArgsEvent = {
313
+ type: import_client2.EventType.TOOL_CALL_ARGS,
314
+ toolCallId: toolCall.id,
315
+ delta: toolCall.function.arguments
316
+ };
317
+ events.push(toolArgsEvent);
318
+ const toolEndEvent = {
319
+ type: import_client2.EventType.TOOL_CALL_END,
320
+ toolCallId: toolCall.id
321
+ };
322
+ events.push(toolEndEvent);
323
+ }
324
+ }
325
+ if (message.role === "tool" && message.toolCallId) {
326
+ const toolResultEvent = {
327
+ type: import_client2.EventType.TOOL_CALL_RESULT,
328
+ messageId: message.id,
329
+ toolCallId: message.toolCallId,
330
+ content: message.content,
331
+ role: "tool"
332
+ };
333
+ events.push(toolResultEvent);
334
+ }
335
+ return events;
336
+ }
337
+ run(request) {
338
+ let existingStore = GLOBAL_STORE.get(request.threadId);
339
+ if (!existingStore) {
340
+ existingStore = new InMemoryEventStore(request.threadId);
341
+ GLOBAL_STORE.set(request.threadId, existingStore);
342
+ }
343
+ const store = existingStore;
344
+ if (store.isRunning) {
345
+ throw new Error("Thread already running");
346
+ }
347
+ store.isRunning = true;
348
+ store.currentRunId = request.input.runId;
349
+ const seenMessageIds = /* @__PURE__ */ new Set();
350
+ const currentRunEvents = [];
351
+ const historicMessageIds = /* @__PURE__ */ new Set();
352
+ for (const run of store.historicRuns) {
353
+ for (const event of run.events) {
354
+ if ("messageId" in event && typeof event.messageId === "string") {
355
+ historicMessageIds.add(event.messageId);
356
+ }
357
+ }
358
+ }
359
+ const nextSubject = new import_rxjs.ReplaySubject(Infinity);
360
+ const prevSubject = store.subject;
361
+ store.subject = nextSubject;
362
+ store.abortController = new AbortController();
363
+ const runSubject = new import_rxjs.ReplaySubject(Infinity);
364
+ const runAgent = async () => {
365
+ const lastRun = store.historicRuns[store.historicRuns.length - 1];
366
+ const parentRunId = lastRun?.runId ?? null;
367
+ try {
368
+ await request.agent.runAgent(request.input, {
369
+ onEvent: ({ event }) => {
370
+ runSubject.next(event);
371
+ nextSubject.next(event);
372
+ currentRunEvents.push(event);
373
+ },
374
+ onNewMessage: ({ message }) => {
375
+ if (!seenMessageIds.has(message.id)) {
376
+ seenMessageIds.add(message.id);
377
+ }
378
+ },
379
+ onRunStartedEvent: () => {
380
+ if (request.input.messages) {
381
+ for (const message of request.input.messages) {
382
+ if (!seenMessageIds.has(message.id)) {
383
+ seenMessageIds.add(message.id);
384
+ const events = this.convertMessageToEvents(message);
385
+ const isNewMessage = !historicMessageIds.has(message.id);
386
+ for (const event of events) {
387
+ nextSubject.next(event);
388
+ if (isNewMessage) {
389
+ currentRunEvents.push(event);
390
+ }
391
+ }
392
+ }
393
+ }
394
+ }
395
+ }
396
+ });
397
+ if (store.currentRunId) {
398
+ const compactedEvents = compactEvents(currentRunEvents);
399
+ store.historicRuns.push({
400
+ threadId: request.threadId,
401
+ runId: store.currentRunId,
402
+ parentRunId,
403
+ events: compactedEvents,
404
+ createdAt: Date.now()
405
+ });
406
+ }
407
+ store.isRunning = false;
408
+ store.currentRunId = null;
409
+ runSubject.complete();
410
+ nextSubject.complete();
411
+ } catch {
412
+ if (store.currentRunId && currentRunEvents.length > 0) {
413
+ const compactedEvents = compactEvents(currentRunEvents);
414
+ store.historicRuns.push({
415
+ threadId: request.threadId,
416
+ runId: store.currentRunId,
417
+ parentRunId,
418
+ events: compactedEvents,
419
+ createdAt: Date.now()
420
+ });
421
+ }
422
+ store.isRunning = false;
423
+ store.currentRunId = null;
424
+ runSubject.complete();
425
+ nextSubject.complete();
426
+ }
427
+ };
428
+ if (prevSubject) {
429
+ prevSubject.subscribe({
430
+ next: (e) => nextSubject.next(e),
431
+ error: (err) => nextSubject.error(err),
432
+ complete: () => {
433
+ }
434
+ });
435
+ }
436
+ runAgent();
437
+ return runSubject.asObservable();
438
+ }
439
+ connect(request) {
440
+ const store = GLOBAL_STORE.get(request.threadId);
441
+ const connectionSubject = new import_rxjs.ReplaySubject(Infinity);
442
+ if (!store) {
443
+ connectionSubject.complete();
444
+ return connectionSubject.asObservable();
445
+ }
446
+ const allHistoricEvents = [];
447
+ for (const run of store.historicRuns) {
448
+ allHistoricEvents.push(...run.events);
449
+ }
450
+ const compactedEvents = compactEvents(allHistoricEvents);
451
+ const emittedMessageIds = /* @__PURE__ */ new Set();
452
+ for (const event of compactedEvents) {
453
+ connectionSubject.next(event);
454
+ if ("messageId" in event && typeof event.messageId === "string") {
455
+ emittedMessageIds.add(event.messageId);
456
+ }
457
+ }
458
+ if (store.subject && store.isRunning) {
459
+ store.subject.subscribe({
460
+ next: (event) => {
461
+ if ("messageId" in event && typeof event.messageId === "string" && emittedMessageIds.has(event.messageId)) {
462
+ return;
463
+ }
464
+ connectionSubject.next(event);
465
+ },
466
+ complete: () => connectionSubject.complete(),
467
+ error: (err) => connectionSubject.error(err)
468
+ });
469
+ } else {
470
+ connectionSubject.complete();
471
+ }
472
+ return connectionSubject.asObservable();
473
+ }
474
+ isRunning(request) {
475
+ const store = GLOBAL_STORE.get(request.threadId);
476
+ return Promise.resolve(store?.isRunning ?? false);
477
+ }
478
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
479
+ stop(_request) {
480
+ throw new Error("Method not implemented.");
481
+ }
482
+ };
483
+
484
+ // src/runtime.ts
485
+ var VERSION = package_default.version;
486
+ var CopilotRuntime = class {
487
+ agents;
488
+ transcriptionService;
489
+ beforeRequestMiddleware;
490
+ afterRequestMiddleware;
491
+ runner;
492
+ constructor({
493
+ agents,
494
+ transcriptionService,
495
+ beforeRequestMiddleware,
496
+ afterRequestMiddleware,
497
+ runner
498
+ }) {
499
+ this.agents = agents;
500
+ this.transcriptionService = transcriptionService;
501
+ this.beforeRequestMiddleware = beforeRequestMiddleware;
502
+ this.afterRequestMiddleware = afterRequestMiddleware;
503
+ this.runner = runner ?? new InMemoryAgentRunner();
504
+ }
505
+ };
506
+
507
+ // src/endpoint.ts
508
+ var import_hono = require("hono");
509
+
510
+ // src/handlers/handle-run.ts
511
+ var import_client3 = require("@ag-ui/client");
512
+ var import_encoder = require("@ag-ui/encoder");
513
+ async function handleRunAgent({
514
+ runtime,
515
+ request,
516
+ agentId
517
+ }) {
518
+ try {
519
+ const agents = await runtime.agents;
520
+ if (!agents[agentId]) {
521
+ return new Response(
522
+ JSON.stringify({
523
+ error: "Agent not found",
524
+ message: `Agent '${agentId}' does not exist`
525
+ }),
526
+ {
527
+ status: 404,
528
+ headers: { "Content-Type": "application/json" }
529
+ }
530
+ );
531
+ }
532
+ const agent = agents[agentId].clone();
533
+ const stream = new TransformStream();
534
+ const writer = stream.writable.getWriter();
535
+ const encoder = new import_encoder.EventEncoder();
536
+ let streamClosed = false;
537
+ (async () => {
538
+ let input;
539
+ try {
540
+ const requestBody = await request.json();
541
+ input = import_client3.RunAgentInputSchema.parse(requestBody);
542
+ } catch {
543
+ return new Response(
544
+ JSON.stringify({
545
+ error: "Invalid request body"
546
+ }),
547
+ { status: 400 }
548
+ );
549
+ }
550
+ agent.setMessages(input.messages);
551
+ agent.setState(input.state);
552
+ agent.threadId = input.threadId;
553
+ runtime.runner.run({
554
+ threadId: input.threadId,
555
+ agent,
556
+ input
557
+ }).subscribe({
558
+ next: async (event) => {
559
+ if (!request.signal.aborted && !streamClosed) {
560
+ try {
561
+ await writer.write(encoder.encode(event));
562
+ } catch (error) {
563
+ if (error instanceof Error && error.name === "AbortError") {
564
+ streamClosed = true;
565
+ }
566
+ }
567
+ }
568
+ },
569
+ error: async (error) => {
570
+ console.error("Error running agent:", error);
571
+ if (!streamClosed) {
572
+ try {
573
+ await writer.close();
574
+ streamClosed = true;
575
+ } catch {
576
+ }
577
+ }
578
+ },
579
+ complete: async () => {
580
+ if (!streamClosed) {
581
+ try {
582
+ await writer.close();
583
+ streamClosed = true;
584
+ } catch {
585
+ }
586
+ }
587
+ }
588
+ });
589
+ })().catch((error) => {
590
+ console.error("Error running agent:", error);
591
+ console.error(
592
+ "Error stack:",
593
+ error instanceof Error ? error.stack : "No stack trace"
594
+ );
595
+ console.error("Error details:", {
596
+ name: error instanceof Error ? error.name : "Unknown",
597
+ message: error instanceof Error ? error.message : String(error),
598
+ cause: error instanceof Error ? error.cause : void 0
599
+ });
600
+ if (!streamClosed) {
601
+ try {
602
+ writer.close();
603
+ streamClosed = true;
604
+ } catch {
605
+ }
606
+ }
607
+ });
608
+ return new Response(stream.readable, {
609
+ status: 200,
610
+ headers: {
611
+ "Content-Type": "text/event-stream",
612
+ "Cache-Control": "no-cache",
613
+ Connection: "keep-alive"
614
+ }
615
+ });
616
+ } catch (error) {
617
+ console.error("Error running agent:", error);
618
+ console.error(
619
+ "Error stack:",
620
+ error instanceof Error ? error.stack : "No stack trace"
621
+ );
622
+ console.error("Error details:", {
623
+ name: error instanceof Error ? error.name : "Unknown",
624
+ message: error instanceof Error ? error.message : String(error),
625
+ cause: error instanceof Error ? error.cause : void 0
626
+ });
627
+ return new Response(
628
+ JSON.stringify({
629
+ error: "Failed to run agent",
630
+ message: error instanceof Error ? error.message : "Unknown error"
631
+ }),
632
+ {
633
+ status: 500,
634
+ headers: { "Content-Type": "application/json" }
635
+ }
636
+ );
637
+ }
638
+ }
639
+
640
+ // src/handlers/get-runtime-info.ts
641
+ async function handleGetRuntimeInfo({
642
+ runtime
643
+ }) {
644
+ try {
645
+ const agents = await runtime.agents;
646
+ const agentsDict = Object.entries(agents).reduce(
647
+ (acc, [name, agent]) => {
648
+ acc[name] = {
649
+ name,
650
+ description: agent.description,
651
+ className: agent.constructor.name
652
+ };
653
+ return acc;
654
+ },
655
+ {}
656
+ );
657
+ const runtimeInfo = {
658
+ version: VERSION,
659
+ agents: agentsDict,
660
+ audioFileTranscriptionEnabled: !!runtime.transcriptionService
661
+ };
662
+ return new Response(JSON.stringify(runtimeInfo), {
663
+ status: 200,
664
+ headers: { "Content-Type": "application/json" }
665
+ });
666
+ } catch (error) {
667
+ return new Response(
668
+ JSON.stringify({
669
+ error: "Failed to retrieve runtime information",
670
+ message: error instanceof Error ? error.message : "Unknown error"
671
+ }),
672
+ {
673
+ status: 500,
674
+ headers: { "Content-Type": "application/json" }
675
+ }
676
+ );
677
+ }
678
+ }
679
+
680
+ // src/handlers/handle-transcribe.ts
681
+ async function handleTranscribe({
682
+ runtime,
683
+ request
684
+ }) {
685
+ try {
686
+ if (!runtime.transcriptionService) {
687
+ return new Response(
688
+ JSON.stringify({
689
+ error: "Transcription service not configured",
690
+ message: "No transcription service has been configured in the runtime"
691
+ }),
692
+ {
693
+ status: 503,
694
+ headers: { "Content-Type": "application/json" }
695
+ }
696
+ );
697
+ }
698
+ const contentType = request.headers.get("content-type");
699
+ if (!contentType || !contentType.includes("multipart/form-data")) {
700
+ return new Response(
701
+ JSON.stringify({
702
+ error: "Invalid content type",
703
+ message: "Request must contain multipart/form-data with an audio file"
704
+ }),
705
+ {
706
+ status: 400,
707
+ headers: { "Content-Type": "application/json" }
708
+ }
709
+ );
710
+ }
711
+ const formData = await request.formData();
712
+ const audioFile = formData.get("audio");
713
+ if (!audioFile || !(audioFile instanceof File)) {
714
+ return new Response(
715
+ JSON.stringify({
716
+ error: "Missing audio file",
717
+ message: "No audio file found in form data. Please include an 'audio' field."
718
+ }),
719
+ {
720
+ status: 400,
721
+ headers: { "Content-Type": "application/json" }
722
+ }
723
+ );
724
+ }
725
+ const validAudioTypes = [
726
+ "audio/mpeg",
727
+ "audio/mp3",
728
+ "audio/mp4",
729
+ "audio/wav",
730
+ "audio/webm",
731
+ "audio/ogg",
732
+ "audio/flac",
733
+ "audio/aac"
734
+ ];
735
+ const isValidType = validAudioTypes.includes(audioFile.type) || audioFile.type === "" || audioFile.type === "application/octet-stream";
736
+ if (!isValidType) {
737
+ return new Response(
738
+ JSON.stringify({
739
+ error: "Invalid file type",
740
+ message: `Unsupported audio file type: ${audioFile.type}. Supported types: ${validAudioTypes.join(", ")}, or files with unknown/empty types`
741
+ }),
742
+ {
743
+ status: 400,
744
+ headers: { "Content-Type": "application/json" }
745
+ }
746
+ );
747
+ }
748
+ const transcription = await runtime.transcriptionService.transcribeFile({
749
+ audioFile,
750
+ mimeType: audioFile.type,
751
+ size: audioFile.size
752
+ });
753
+ return new Response(
754
+ JSON.stringify({
755
+ text: transcription,
756
+ size: audioFile.size,
757
+ type: audioFile.type
758
+ }),
759
+ {
760
+ status: 200,
761
+ headers: { "Content-Type": "application/json" }
762
+ }
763
+ );
764
+ } catch (error) {
765
+ return new Response(
766
+ JSON.stringify({
767
+ error: "Transcription failed",
768
+ message: error instanceof Error ? error.message : "Unknown error occurred during transcription"
769
+ }),
770
+ {
771
+ status: 500,
772
+ headers: { "Content-Type": "application/json" }
773
+ }
774
+ );
775
+ }
776
+ }
777
+
778
+ // src/endpoint.ts
779
+ var import_shared2 = require("@copilotkitnext/shared");
780
+
781
+ // src/middleware.ts
782
+ var import_shared = require("@copilotkitnext/shared");
783
+ function isMiddlewareURL(value) {
784
+ return typeof value === "string" && /^https?:\/\//.test(value);
785
+ }
786
+ async function callBeforeRequestMiddleware({
787
+ runtime,
788
+ request,
789
+ path
790
+ }) {
791
+ const mw = runtime.beforeRequestMiddleware;
792
+ if (!mw) return;
793
+ if (typeof mw === "function") {
794
+ return mw({ runtime, request, path });
795
+ }
796
+ if (isMiddlewareURL(mw)) {
797
+ const clone = request.clone();
798
+ const url = new URL(request.url);
799
+ const headersObj = {};
800
+ clone.headers.forEach((v, k) => {
801
+ headersObj[k] = v;
802
+ });
803
+ let bodyJson = void 0;
804
+ try {
805
+ bodyJson = await clone.json();
806
+ } catch {
807
+ }
808
+ const payload = {
809
+ method: request.method,
810
+ path: url.pathname,
811
+ query: url.search.startsWith("?") ? url.search.slice(1) : url.search,
812
+ headers: headersObj,
813
+ body: bodyJson
814
+ };
815
+ const ac = new AbortController();
816
+ const to = setTimeout(() => ac.abort(), 2e3);
817
+ let res;
818
+ try {
819
+ res = await fetch(mw, {
820
+ method: "POST",
821
+ headers: {
822
+ "content-type": "application/json",
823
+ "X-CopilotKit-Webhook-Stage": "before_request" /* BeforeRequest */
824
+ },
825
+ body: JSON.stringify(payload),
826
+ signal: ac.signal
827
+ });
828
+ } catch {
829
+ clearTimeout(to);
830
+ throw new Response(void 0, { status: 502 });
831
+ }
832
+ clearTimeout(to);
833
+ if (res.status >= 500) {
834
+ throw new Response(void 0, { status: 502 });
835
+ }
836
+ if (res.status >= 400) {
837
+ const errBody = await res.text();
838
+ throw new Response(errBody || null, {
839
+ status: res.status,
840
+ headers: {
841
+ "content-type": res.headers.get("content-type") || "application/json"
842
+ }
843
+ });
844
+ }
845
+ if (res.status === 204) return;
846
+ let json;
847
+ try {
848
+ json = await res.json();
849
+ } catch {
850
+ return;
851
+ }
852
+ if (json && typeof json === "object") {
853
+ const { headers, body } = json;
854
+ const init = {
855
+ method: request.method
856
+ };
857
+ if (headers) {
858
+ init.headers = headers;
859
+ }
860
+ if (body !== void 0 && request.method !== "GET" && request.method !== "HEAD") {
861
+ init.body = JSON.stringify(body);
862
+ }
863
+ return new Request(request.url, init);
864
+ }
865
+ return;
866
+ }
867
+ import_shared.logger.warn({ mw }, "Unsupported beforeRequestMiddleware value \u2013 skipped");
868
+ return;
869
+ }
870
+ async function callAfterRequestMiddleware({
871
+ runtime,
872
+ response,
873
+ path
874
+ }) {
875
+ const mw = runtime.afterRequestMiddleware;
876
+ if (!mw) return;
877
+ if (typeof mw === "function") {
878
+ return mw({ runtime, response, path });
879
+ }
880
+ if (isMiddlewareURL(mw)) {
881
+ const clone = response.clone();
882
+ const headersObj = {};
883
+ clone.headers.forEach((v, k) => {
884
+ headersObj[k] = v;
885
+ });
886
+ let body = "";
887
+ try {
888
+ body = await clone.text();
889
+ } catch {
890
+ }
891
+ const payload = {
892
+ status: clone.status,
893
+ headers: headersObj,
894
+ body
895
+ };
896
+ const ac = new AbortController();
897
+ const to = setTimeout(() => ac.abort(), 2e3);
898
+ let res;
899
+ try {
900
+ res = await fetch(mw, {
901
+ method: "POST",
902
+ headers: {
903
+ "content-type": "application/json",
904
+ "X-CopilotKit-Webhook-Stage": "after_request" /* AfterRequest */
905
+ },
906
+ body: JSON.stringify(payload),
907
+ signal: ac.signal
908
+ });
909
+ } finally {
910
+ clearTimeout(to);
911
+ }
912
+ if (!res.ok) {
913
+ throw new Error(
914
+ `after_request webhook ${mw} responded with ${res.status}`
915
+ );
916
+ }
917
+ return;
918
+ }
919
+ import_shared.logger.warn({ mw }, "Unsupported afterRequestMiddleware value \u2013 skipped");
920
+ }
921
+
922
+ // src/handlers/handle-connect.ts
923
+ var import_client4 = require("@ag-ui/client");
924
+ var import_encoder2 = require("@ag-ui/encoder");
925
+ async function handleConnectAgent({
926
+ runtime,
927
+ request,
928
+ agentId
929
+ }) {
930
+ try {
931
+ const agents = await runtime.agents;
932
+ if (!agents[agentId]) {
933
+ return new Response(
934
+ JSON.stringify({
935
+ error: "Agent not found",
936
+ message: `Agent '${agentId}' does not exist`
937
+ }),
938
+ {
939
+ status: 404,
940
+ headers: { "Content-Type": "application/json" }
941
+ }
942
+ );
943
+ }
944
+ const stream = new TransformStream();
945
+ const writer = stream.writable.getWriter();
946
+ const encoder = new import_encoder2.EventEncoder();
947
+ let streamClosed = false;
948
+ (async () => {
949
+ let input;
950
+ try {
951
+ const requestBody = await request.json();
952
+ input = import_client4.RunAgentInputSchema.parse(requestBody);
953
+ } catch {
954
+ return new Response(
955
+ JSON.stringify({
956
+ error: "Invalid request body"
957
+ }),
958
+ { status: 400 }
959
+ );
960
+ }
961
+ runtime.runner.connect({
962
+ threadId: input.threadId
963
+ }).subscribe({
964
+ next: async (event) => {
965
+ if (!request.signal.aborted && !streamClosed) {
966
+ try {
967
+ await writer.write(encoder.encode(event));
968
+ } catch (error) {
969
+ if (error instanceof Error && error.name === "AbortError") {
970
+ streamClosed = true;
971
+ }
972
+ }
973
+ }
974
+ },
975
+ error: async (error) => {
976
+ console.error("Error running agent:", error);
977
+ if (!streamClosed) {
978
+ try {
979
+ await writer.close();
980
+ streamClosed = true;
981
+ } catch {
982
+ }
983
+ }
984
+ },
985
+ complete: async () => {
986
+ if (!streamClosed) {
987
+ try {
988
+ await writer.close();
989
+ streamClosed = true;
990
+ } catch {
991
+ }
992
+ }
993
+ }
994
+ });
995
+ })().catch((error) => {
996
+ console.error("Error running agent:", error);
997
+ console.error(
998
+ "Error stack:",
999
+ error instanceof Error ? error.stack : "No stack trace"
1000
+ );
1001
+ console.error("Error details:", {
1002
+ name: error instanceof Error ? error.name : "Unknown",
1003
+ message: error instanceof Error ? error.message : String(error),
1004
+ cause: error instanceof Error ? error.cause : void 0
1005
+ });
1006
+ if (!streamClosed) {
1007
+ try {
1008
+ writer.close();
1009
+ streamClosed = true;
1010
+ } catch {
1011
+ }
1012
+ }
1013
+ });
1014
+ return new Response(stream.readable, {
1015
+ status: 200,
1016
+ headers: {
1017
+ "Content-Type": "text/event-stream",
1018
+ "Cache-Control": "no-cache",
1019
+ Connection: "keep-alive"
1020
+ }
1021
+ });
1022
+ } catch (error) {
1023
+ console.error("Error running agent:", error);
1024
+ console.error(
1025
+ "Error stack:",
1026
+ error instanceof Error ? error.stack : "No stack trace"
1027
+ );
1028
+ console.error("Error details:", {
1029
+ name: error instanceof Error ? error.name : "Unknown",
1030
+ message: error instanceof Error ? error.message : String(error),
1031
+ cause: error instanceof Error ? error.cause : void 0
1032
+ });
1033
+ return new Response(
1034
+ JSON.stringify({
1035
+ error: "Failed to run agent",
1036
+ message: error instanceof Error ? error.message : "Unknown error"
1037
+ }),
1038
+ {
1039
+ status: 500,
1040
+ headers: { "Content-Type": "application/json" }
1041
+ }
1042
+ );
1043
+ }
1044
+ }
1045
+
1046
+ // src/endpoint.ts
1047
+ function createCopilotEndpoint({
1048
+ runtime,
1049
+ basePath
1050
+ }) {
1051
+ const app = new import_hono.Hono();
1052
+ return app.basePath(basePath).use("*", async (c, next) => {
1053
+ const request = c.req.raw;
1054
+ const path = c.req.path;
1055
+ try {
1056
+ const maybeModifiedRequest = await callBeforeRequestMiddleware({
1057
+ runtime,
1058
+ request,
1059
+ path
1060
+ });
1061
+ if (maybeModifiedRequest) {
1062
+ c.set("modifiedRequest", maybeModifiedRequest);
1063
+ }
1064
+ } catch (error) {
1065
+ import_shared2.logger.error(
1066
+ { err: error, url: request.url, path },
1067
+ "Error running before request middleware"
1068
+ );
1069
+ if (error instanceof Response) {
1070
+ return error;
1071
+ }
1072
+ throw error;
1073
+ }
1074
+ await next();
1075
+ }).use("*", async (c, next) => {
1076
+ await next();
1077
+ const response = c.res;
1078
+ const path = c.req.path;
1079
+ callAfterRequestMiddleware({
1080
+ runtime,
1081
+ response,
1082
+ path
1083
+ }).catch((error) => {
1084
+ import_shared2.logger.error(
1085
+ { err: error, url: c.req.url, path },
1086
+ "Error running after request middleware"
1087
+ );
1088
+ });
1089
+ }).post("/agent/:agentId/run", async (c) => {
1090
+ const agentId = c.req.param("agentId");
1091
+ const request = c.get("modifiedRequest") || c.req.raw;
1092
+ try {
1093
+ return await handleRunAgent({
1094
+ runtime,
1095
+ request,
1096
+ agentId
1097
+ });
1098
+ } catch (error) {
1099
+ import_shared2.logger.error(
1100
+ { err: error, url: request.url, path: c.req.path },
1101
+ "Error running request handler"
1102
+ );
1103
+ throw error;
1104
+ }
1105
+ }).post("/agent/:agentId/connect", async (c) => {
1106
+ const agentId = c.req.param("agentId");
1107
+ const request = c.get("modifiedRequest") || c.req.raw;
1108
+ try {
1109
+ return await handleConnectAgent({
1110
+ runtime,
1111
+ request,
1112
+ agentId
1113
+ });
1114
+ } catch (error) {
1115
+ import_shared2.logger.error(
1116
+ { err: error, url: request.url, path: c.req.path },
1117
+ "Error running request handler"
1118
+ );
1119
+ throw error;
1120
+ }
1121
+ }).get("/info", async (c) => {
1122
+ const request = c.get("modifiedRequest") || c.req.raw;
1123
+ try {
1124
+ return await handleGetRuntimeInfo({
1125
+ runtime,
1126
+ request
1127
+ });
1128
+ } catch (error) {
1129
+ import_shared2.logger.error(
1130
+ { err: error, url: request.url, path: c.req.path },
1131
+ "Error running request handler"
1132
+ );
1133
+ throw error;
1134
+ }
1135
+ }).post("/transcribe", async (c) => {
1136
+ const request = c.get("modifiedRequest") || c.req.raw;
1137
+ try {
1138
+ return await handleTranscribe({
1139
+ runtime,
1140
+ request
1141
+ });
1142
+ } catch (error) {
1143
+ import_shared2.logger.error(
1144
+ { err: error, url: request.url, path: c.req.path },
1145
+ "Error running request handler"
1146
+ );
1147
+ throw error;
1148
+ }
1149
+ }).notFound((c) => {
1150
+ return c.json({ error: "Not found" }, 404);
1151
+ });
1152
+ }
1153
+
1154
+ // src/runner/sqlite.ts
1155
+ var import_rxjs2 = require("rxjs");
1156
+ var import_client5 = require("@ag-ui/client");
1157
+ var import_better_sqlite3 = __toESM(require("better-sqlite3"));
1158
+ var SCHEMA_VERSION = 1;
1159
+ var ACTIVE_CONNECTIONS = /* @__PURE__ */ new Map();
1160
+ var SqliteAgentRunner = class extends AgentRunner {
1161
+ db;
1162
+ constructor(options = {}) {
1163
+ super();
1164
+ const dbPath = options.dbPath ?? ":memory:";
1165
+ if (!import_better_sqlite3.default) {
1166
+ throw new Error(
1167
+ "better-sqlite3 is required for SqliteAgentRunner but was not found.\nPlease install it in your project:\n npm install better-sqlite3\n or\n pnpm add better-sqlite3\n or\n yarn add better-sqlite3\n\nIf you don't need persistence, use InMemoryAgentRunner instead."
1168
+ );
1169
+ }
1170
+ this.db = new import_better_sqlite3.default(dbPath);
1171
+ this.initializeSchema();
1172
+ }
1173
+ convertMessageToEvents(message) {
1174
+ const events = [];
1175
+ if ((message.role === "assistant" || message.role === "user" || message.role === "developer" || message.role === "system") && message.content) {
1176
+ const textStartEvent = {
1177
+ type: import_client5.EventType.TEXT_MESSAGE_START,
1178
+ messageId: message.id,
1179
+ role: message.role
1180
+ };
1181
+ events.push(textStartEvent);
1182
+ const textContentEvent = {
1183
+ type: import_client5.EventType.TEXT_MESSAGE_CONTENT,
1184
+ messageId: message.id,
1185
+ delta: message.content
1186
+ };
1187
+ events.push(textContentEvent);
1188
+ const textEndEvent = {
1189
+ type: import_client5.EventType.TEXT_MESSAGE_END,
1190
+ messageId: message.id
1191
+ };
1192
+ events.push(textEndEvent);
1193
+ }
1194
+ if (message.role === "assistant" && message.toolCalls) {
1195
+ for (const toolCall of message.toolCalls) {
1196
+ const toolStartEvent = {
1197
+ type: import_client5.EventType.TOOL_CALL_START,
1198
+ toolCallId: toolCall.id,
1199
+ toolCallName: toolCall.function.name,
1200
+ parentMessageId: message.id
1201
+ };
1202
+ events.push(toolStartEvent);
1203
+ const toolArgsEvent = {
1204
+ type: import_client5.EventType.TOOL_CALL_ARGS,
1205
+ toolCallId: toolCall.id,
1206
+ delta: toolCall.function.arguments
1207
+ };
1208
+ events.push(toolArgsEvent);
1209
+ const toolEndEvent = {
1210
+ type: import_client5.EventType.TOOL_CALL_END,
1211
+ toolCallId: toolCall.id
1212
+ };
1213
+ events.push(toolEndEvent);
1214
+ }
1215
+ }
1216
+ if (message.role === "tool" && message.toolCallId) {
1217
+ const toolResultEvent = {
1218
+ type: import_client5.EventType.TOOL_CALL_RESULT,
1219
+ messageId: message.id,
1220
+ toolCallId: message.toolCallId,
1221
+ content: message.content,
1222
+ role: "tool"
1223
+ };
1224
+ events.push(toolResultEvent);
1225
+ }
1226
+ return events;
1227
+ }
1228
+ initializeSchema() {
1229
+ this.db.exec(`
1230
+ CREATE TABLE IF NOT EXISTS agent_runs (
1231
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1232
+ thread_id TEXT NOT NULL,
1233
+ run_id TEXT NOT NULL UNIQUE,
1234
+ parent_run_id TEXT,
1235
+ events TEXT NOT NULL,
1236
+ input TEXT NOT NULL,
1237
+ created_at INTEGER NOT NULL,
1238
+ version INTEGER NOT NULL
1239
+ )
1240
+ `);
1241
+ this.db.exec(`
1242
+ CREATE TABLE IF NOT EXISTS run_state (
1243
+ thread_id TEXT PRIMARY KEY,
1244
+ is_running INTEGER DEFAULT 0,
1245
+ current_run_id TEXT,
1246
+ updated_at INTEGER NOT NULL
1247
+ )
1248
+ `);
1249
+ this.db.exec(`
1250
+ CREATE INDEX IF NOT EXISTS idx_thread_id ON agent_runs(thread_id);
1251
+ CREATE INDEX IF NOT EXISTS idx_parent_run_id ON agent_runs(parent_run_id);
1252
+ `);
1253
+ this.db.exec(`
1254
+ CREATE TABLE IF NOT EXISTS schema_version (
1255
+ version INTEGER PRIMARY KEY,
1256
+ applied_at INTEGER NOT NULL
1257
+ )
1258
+ `);
1259
+ const currentVersion = this.db.prepare("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1").get();
1260
+ if (!currentVersion || currentVersion.version < SCHEMA_VERSION) {
1261
+ this.db.prepare("INSERT OR REPLACE INTO schema_version (version, applied_at) VALUES (?, ?)").run(SCHEMA_VERSION, Date.now());
1262
+ }
1263
+ }
1264
+ storeRun(threadId, runId, events, input, parentRunId) {
1265
+ const compactedEvents = compactEvents(events);
1266
+ const stmt = this.db.prepare(`
1267
+ INSERT INTO agent_runs (thread_id, run_id, parent_run_id, events, input, created_at, version)
1268
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1269
+ `);
1270
+ stmt.run(
1271
+ threadId,
1272
+ runId,
1273
+ parentRunId ?? null,
1274
+ JSON.stringify(compactedEvents),
1275
+ // Store only this run's compacted events
1276
+ JSON.stringify(input),
1277
+ Date.now(),
1278
+ SCHEMA_VERSION
1279
+ );
1280
+ }
1281
+ getHistoricRuns(threadId) {
1282
+ const stmt = this.db.prepare(`
1283
+ WITH RECURSIVE run_chain AS (
1284
+ -- Base case: find the root runs (those without parent)
1285
+ SELECT * FROM agent_runs
1286
+ WHERE thread_id = ? AND parent_run_id IS NULL
1287
+
1288
+ UNION ALL
1289
+
1290
+ -- Recursive case: find children of current level
1291
+ SELECT ar.* FROM agent_runs ar
1292
+ INNER JOIN run_chain rc ON ar.parent_run_id = rc.run_id
1293
+ WHERE ar.thread_id = ?
1294
+ )
1295
+ SELECT * FROM run_chain
1296
+ ORDER BY created_at ASC
1297
+ `);
1298
+ const rows = stmt.all(threadId, threadId);
1299
+ return rows.map((row) => ({
1300
+ id: row.id,
1301
+ thread_id: row.thread_id,
1302
+ run_id: row.run_id,
1303
+ parent_run_id: row.parent_run_id,
1304
+ events: JSON.parse(row.events),
1305
+ input: JSON.parse(row.input),
1306
+ created_at: row.created_at,
1307
+ version: row.version
1308
+ }));
1309
+ }
1310
+ getLatestRunId(threadId) {
1311
+ const stmt = this.db.prepare(`
1312
+ SELECT run_id FROM agent_runs
1313
+ WHERE thread_id = ?
1314
+ ORDER BY created_at DESC
1315
+ LIMIT 1
1316
+ `);
1317
+ const result = stmt.get(threadId);
1318
+ return result?.run_id ?? null;
1319
+ }
1320
+ setRunState(threadId, isRunning, runId) {
1321
+ const stmt = this.db.prepare(`
1322
+ INSERT OR REPLACE INTO run_state (thread_id, is_running, current_run_id, updated_at)
1323
+ VALUES (?, ?, ?, ?)
1324
+ `);
1325
+ stmt.run(threadId, isRunning ? 1 : 0, runId ?? null, Date.now());
1326
+ }
1327
+ getRunState(threadId) {
1328
+ const stmt = this.db.prepare(`
1329
+ SELECT is_running, current_run_id FROM run_state WHERE thread_id = ?
1330
+ `);
1331
+ const result = stmt.get(threadId);
1332
+ return {
1333
+ isRunning: result?.is_running === 1,
1334
+ currentRunId: result?.current_run_id ?? null
1335
+ };
1336
+ }
1337
+ run(request) {
1338
+ const runState = this.getRunState(request.threadId);
1339
+ if (runState.isRunning) {
1340
+ throw new Error("Thread already running");
1341
+ }
1342
+ this.setRunState(request.threadId, true, request.input.runId);
1343
+ const seenMessageIds = /* @__PURE__ */ new Set();
1344
+ const currentRunEvents = [];
1345
+ const historicRuns = this.getHistoricRuns(request.threadId);
1346
+ const historicMessageIds = /* @__PURE__ */ new Set();
1347
+ for (const run of historicRuns) {
1348
+ for (const event of run.events) {
1349
+ if ("messageId" in event && typeof event.messageId === "string") {
1350
+ historicMessageIds.add(event.messageId);
1351
+ }
1352
+ }
1353
+ }
1354
+ const nextSubject = new import_rxjs2.ReplaySubject(Infinity);
1355
+ const prevSubject = ACTIVE_CONNECTIONS.get(request.threadId);
1356
+ ACTIVE_CONNECTIONS.set(request.threadId, nextSubject);
1357
+ const runSubject = new import_rxjs2.ReplaySubject(Infinity);
1358
+ const runAgent = async () => {
1359
+ const parentRunId = this.getLatestRunId(request.threadId);
1360
+ try {
1361
+ await request.agent.runAgent(request.input, {
1362
+ onEvent: ({ event }) => {
1363
+ runSubject.next(event);
1364
+ nextSubject.next(event);
1365
+ currentRunEvents.push(event);
1366
+ },
1367
+ onNewMessage: ({ message }) => {
1368
+ if (!seenMessageIds.has(message.id)) {
1369
+ seenMessageIds.add(message.id);
1370
+ }
1371
+ },
1372
+ onRunStartedEvent: () => {
1373
+ if (request.input.messages) {
1374
+ for (const message of request.input.messages) {
1375
+ if (!seenMessageIds.has(message.id)) {
1376
+ seenMessageIds.add(message.id);
1377
+ const events = this.convertMessageToEvents(message);
1378
+ const isNewMessage = !historicMessageIds.has(message.id);
1379
+ for (const event of events) {
1380
+ nextSubject.next(event);
1381
+ if (isNewMessage) {
1382
+ currentRunEvents.push(event);
1383
+ }
1384
+ }
1385
+ }
1386
+ }
1387
+ }
1388
+ }
1389
+ });
1390
+ this.storeRun(
1391
+ request.threadId,
1392
+ request.input.runId,
1393
+ currentRunEvents,
1394
+ request.input,
1395
+ parentRunId
1396
+ );
1397
+ this.setRunState(request.threadId, false);
1398
+ runSubject.complete();
1399
+ nextSubject.complete();
1400
+ } catch {
1401
+ if (currentRunEvents.length > 0) {
1402
+ this.storeRun(
1403
+ request.threadId,
1404
+ request.input.runId,
1405
+ currentRunEvents,
1406
+ request.input,
1407
+ parentRunId
1408
+ );
1409
+ }
1410
+ this.setRunState(request.threadId, false);
1411
+ runSubject.complete();
1412
+ nextSubject.complete();
1413
+ }
1414
+ };
1415
+ if (prevSubject) {
1416
+ prevSubject.subscribe({
1417
+ next: (e) => nextSubject.next(e),
1418
+ error: (err) => nextSubject.error(err),
1419
+ complete: () => {
1420
+ }
1421
+ });
1422
+ }
1423
+ runAgent();
1424
+ return runSubject.asObservable();
1425
+ }
1426
+ connect(request) {
1427
+ const connectionSubject = new import_rxjs2.ReplaySubject(Infinity);
1428
+ const historicRuns = this.getHistoricRuns(request.threadId);
1429
+ const allHistoricEvents = [];
1430
+ for (const run of historicRuns) {
1431
+ allHistoricEvents.push(...run.events);
1432
+ }
1433
+ const compactedEvents = compactEvents(allHistoricEvents);
1434
+ const emittedMessageIds = /* @__PURE__ */ new Set();
1435
+ for (const event of compactedEvents) {
1436
+ connectionSubject.next(event);
1437
+ if ("messageId" in event && typeof event.messageId === "string") {
1438
+ emittedMessageIds.add(event.messageId);
1439
+ }
1440
+ }
1441
+ const activeSubject = ACTIVE_CONNECTIONS.get(request.threadId);
1442
+ const runState = this.getRunState(request.threadId);
1443
+ if (activeSubject && runState.isRunning) {
1444
+ activeSubject.subscribe({
1445
+ next: (event) => {
1446
+ if ("messageId" in event && typeof event.messageId === "string" && emittedMessageIds.has(event.messageId)) {
1447
+ return;
1448
+ }
1449
+ connectionSubject.next(event);
1450
+ },
1451
+ complete: () => connectionSubject.complete(),
1452
+ error: (err) => connectionSubject.error(err)
1453
+ });
1454
+ } else {
1455
+ connectionSubject.complete();
1456
+ }
1457
+ return connectionSubject.asObservable();
1458
+ }
1459
+ isRunning(request) {
1460
+ const runState = this.getRunState(request.threadId);
1461
+ return Promise.resolve(runState.isRunning);
1462
+ }
1463
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1464
+ stop(_request) {
1465
+ throw new Error("Method not implemented.");
1466
+ }
1467
+ /**
1468
+ * Close the database connection (for cleanup)
1469
+ */
1470
+ close() {
1471
+ if (this.db) {
1472
+ this.db.close();
1473
+ }
1474
+ }
1475
+ };
1476
+
1477
+ // src/runner/enterprise.ts
1478
+ var import_rxjs3 = require("rxjs");
1479
+ var import_client6 = require("@ag-ui/client");
1480
+ var SCHEMA_VERSION2 = 1;
1481
+ var redisKeys = {
1482
+ stream: (threadId, runId) => `stream:${threadId}:${runId}`,
1483
+ active: (threadId) => `active:${threadId}`,
1484
+ lock: (threadId) => `lock:${threadId}`
1485
+ };
1486
+ var EnterpriseAgentRunner = class extends AgentRunner {
1487
+ db;
1488
+ redis;
1489
+ redisSub;
1490
+ serverId;
1491
+ streamRetentionMs;
1492
+ streamActiveTTLMs;
1493
+ lockTTLMs;
1494
+ constructor(options) {
1495
+ super();
1496
+ this.db = options.kysely;
1497
+ this.redis = options.redis;
1498
+ this.redisSub = options.redisSub || options.redis.duplicate();
1499
+ this.serverId = options.serverId || this.generateServerId();
1500
+ this.streamRetentionMs = options.streamRetentionMs ?? 36e5;
1501
+ this.streamActiveTTLMs = options.streamActiveTTLMs ?? 3e5;
1502
+ this.lockTTLMs = options.lockTTLMs ?? 3e5;
1503
+ this.initializeSchema();
1504
+ }
1505
+ run(request) {
1506
+ const runSubject = new import_rxjs3.ReplaySubject(Infinity);
1507
+ const executeRun = async () => {
1508
+ const { threadId, input, agent } = request;
1509
+ const runId = input.runId;
1510
+ const streamKey = redisKeys.stream(threadId, runId);
1511
+ const activeRunId = await this.redis.get(redisKeys.active(threadId));
1512
+ if (activeRunId) {
1513
+ throw new Error("Thread already running");
1514
+ }
1515
+ const lockAcquired = await this.redis.set(
1516
+ redisKeys.lock(threadId),
1517
+ this.serverId,
1518
+ "PX",
1519
+ this.lockTTLMs,
1520
+ "NX"
1521
+ );
1522
+ if (!lockAcquired) {
1523
+ throw new Error("Thread already running");
1524
+ }
1525
+ await this.redis.setex(
1526
+ redisKeys.active(threadId),
1527
+ Math.floor(this.lockTTLMs / 1e3),
1528
+ runId
1529
+ );
1530
+ await this.setRunState(threadId, true, runId);
1531
+ const currentRunEvents = [];
1532
+ const seenMessageIds = /* @__PURE__ */ new Set();
1533
+ const historicRuns = await this.getHistoricRuns(threadId);
1534
+ const historicMessageIds = /* @__PURE__ */ new Set();
1535
+ for (const run of historicRuns) {
1536
+ const events = JSON.parse(run.events);
1537
+ for (const event of events) {
1538
+ if ("messageId" in event && typeof event.messageId === "string") {
1539
+ historicMessageIds.add(event.messageId);
1540
+ }
1541
+ }
1542
+ }
1543
+ const parentRunId = historicRuns[historicRuns.length - 1]?.run_id ?? null;
1544
+ try {
1545
+ await agent.runAgent(input, {
1546
+ onEvent: async ({ event }) => {
1547
+ runSubject.next(event);
1548
+ currentRunEvents.push(event);
1549
+ await this.redis.xadd(
1550
+ streamKey,
1551
+ "MAXLEN",
1552
+ "~",
1553
+ "10000",
1554
+ "*",
1555
+ "type",
1556
+ event.type,
1557
+ "data",
1558
+ JSON.stringify(event)
1559
+ );
1560
+ await this.redis.pexpire(streamKey, this.streamActiveTTLMs);
1561
+ if (event.type === import_client6.EventType.RUN_FINISHED || event.type === import_client6.EventType.RUN_ERROR) {
1562
+ await this.redis.pexpire(streamKey, this.streamRetentionMs);
1563
+ }
1564
+ },
1565
+ onNewMessage: ({ message }) => {
1566
+ if (!seenMessageIds.has(message.id)) {
1567
+ seenMessageIds.add(message.id);
1568
+ }
1569
+ },
1570
+ onRunStartedEvent: async () => {
1571
+ if (input.messages) {
1572
+ for (const message of input.messages) {
1573
+ if (!seenMessageIds.has(message.id)) {
1574
+ seenMessageIds.add(message.id);
1575
+ const events = this.convertMessageToEvents(message);
1576
+ const isNewMessage = !historicMessageIds.has(message.id);
1577
+ for (const event of events) {
1578
+ await this.redis.xadd(
1579
+ streamKey,
1580
+ "MAXLEN",
1581
+ "~",
1582
+ "10000",
1583
+ "*",
1584
+ "type",
1585
+ event.type,
1586
+ "data",
1587
+ JSON.stringify(event)
1588
+ );
1589
+ if (isNewMessage) {
1590
+ currentRunEvents.push(event);
1591
+ }
1592
+ }
1593
+ }
1594
+ }
1595
+ }
1596
+ await this.redis.pexpire(streamKey, this.streamActiveTTLMs);
1597
+ }
1598
+ });
1599
+ const compactedEvents = compactEvents(currentRunEvents);
1600
+ await this.storeRun(threadId, runId, compactedEvents, input, parentRunId);
1601
+ } finally {
1602
+ await this.setRunState(threadId, false);
1603
+ await this.redis.del(redisKeys.active(threadId));
1604
+ await this.redis.del(redisKeys.lock(threadId));
1605
+ const exists = await this.redis.exists(streamKey);
1606
+ if (exists) {
1607
+ await this.redis.pexpire(streamKey, this.streamRetentionMs);
1608
+ }
1609
+ runSubject.complete();
1610
+ }
1611
+ };
1612
+ executeRun().catch((error) => {
1613
+ runSubject.error(error);
1614
+ });
1615
+ return runSubject.asObservable();
1616
+ }
1617
+ connect(request) {
1618
+ const connectionSubject = new import_rxjs3.ReplaySubject(Infinity);
1619
+ const streamConnection = async () => {
1620
+ const { threadId } = request;
1621
+ const historicRuns = await this.getHistoricRuns(threadId);
1622
+ const allHistoricEvents = [];
1623
+ for (const run of historicRuns) {
1624
+ const events = JSON.parse(run.events);
1625
+ allHistoricEvents.push(...events);
1626
+ }
1627
+ const compactedEvents = compactEvents(allHistoricEvents);
1628
+ const emittedMessageIds = /* @__PURE__ */ new Set();
1629
+ for (const event of compactedEvents) {
1630
+ connectionSubject.next(event);
1631
+ if ("messageId" in event && typeof event.messageId === "string") {
1632
+ emittedMessageIds.add(event.messageId);
1633
+ }
1634
+ }
1635
+ const activeRunId = await this.redis.get(redisKeys.active(threadId));
1636
+ if (activeRunId) {
1637
+ const streamKey = redisKeys.stream(threadId, activeRunId);
1638
+ let lastId = "0-0";
1639
+ let consecutiveEmptyReads = 0;
1640
+ while (true) {
1641
+ try {
1642
+ const result = await this.redis.call(
1643
+ "XREAD",
1644
+ "BLOCK",
1645
+ "5000",
1646
+ "COUNT",
1647
+ "100",
1648
+ "STREAMS",
1649
+ streamKey,
1650
+ lastId
1651
+ );
1652
+ if (!result || result.length === 0) {
1653
+ consecutiveEmptyReads++;
1654
+ const exists = await this.redis.exists(streamKey);
1655
+ if (!exists) {
1656
+ break;
1657
+ }
1658
+ const stillActive = await this.redis.get(redisKeys.active(threadId));
1659
+ if (stillActive !== activeRunId) {
1660
+ break;
1661
+ }
1662
+ if (consecutiveEmptyReads > 3) {
1663
+ break;
1664
+ }
1665
+ continue;
1666
+ }
1667
+ consecutiveEmptyReads = 0;
1668
+ const [, messages] = result[0] || [null, []];
1669
+ for (const [id, fields] of messages || []) {
1670
+ lastId = id;
1671
+ let eventData = null;
1672
+ let eventType = null;
1673
+ for (let i = 0; i < fields.length; i += 2) {
1674
+ if (fields[i] === "data") {
1675
+ eventData = fields[i + 1] ?? null;
1676
+ } else if (fields[i] === "type") {
1677
+ eventType = fields[i + 1] ?? null;
1678
+ }
1679
+ }
1680
+ if (eventData) {
1681
+ const event = JSON.parse(eventData);
1682
+ if ("messageId" in event && typeof event.messageId === "string" && emittedMessageIds.has(event.messageId)) {
1683
+ continue;
1684
+ }
1685
+ connectionSubject.next(event);
1686
+ if (eventType === import_client6.EventType.RUN_FINISHED || eventType === import_client6.EventType.RUN_ERROR) {
1687
+ connectionSubject.complete();
1688
+ return;
1689
+ }
1690
+ }
1691
+ }
1692
+ } catch {
1693
+ break;
1694
+ }
1695
+ }
1696
+ }
1697
+ connectionSubject.complete();
1698
+ };
1699
+ streamConnection().catch(() => connectionSubject.complete());
1700
+ return connectionSubject.asObservable();
1701
+ }
1702
+ async isRunning(request) {
1703
+ const { threadId } = request;
1704
+ const activeRunId = await this.redis.get(redisKeys.active(threadId));
1705
+ if (activeRunId) return true;
1706
+ const lockExists = await this.redis.exists(redisKeys.lock(threadId));
1707
+ if (lockExists) return true;
1708
+ const state = await this.db.selectFrom("run_state").where("thread_id", "=", threadId).selectAll().executeTakeFirst();
1709
+ return state?.is_running === 1;
1710
+ }
1711
+ async stop(request) {
1712
+ const { threadId } = request;
1713
+ const activeRunId = await this.redis.get(redisKeys.active(threadId));
1714
+ if (!activeRunId) {
1715
+ return false;
1716
+ }
1717
+ const streamKey = redisKeys.stream(threadId, activeRunId);
1718
+ await this.redis.xadd(
1719
+ streamKey,
1720
+ "*",
1721
+ "type",
1722
+ import_client6.EventType.RUN_ERROR,
1723
+ "data",
1724
+ JSON.stringify({
1725
+ type: import_client6.EventType.RUN_ERROR,
1726
+ error: "Run stopped by user"
1727
+ })
1728
+ );
1729
+ await this.redis.pexpire(streamKey, this.streamRetentionMs);
1730
+ await this.setRunState(threadId, false);
1731
+ await this.redis.del(redisKeys.active(threadId));
1732
+ await this.redis.del(redisKeys.lock(threadId));
1733
+ return true;
1734
+ }
1735
+ // Helper methods
1736
+ convertMessageToEvents(message) {
1737
+ const events = [];
1738
+ if ((message.role === "assistant" || message.role === "user" || message.role === "developer" || message.role === "system") && message.content) {
1739
+ const textStartEvent = {
1740
+ type: import_client6.EventType.TEXT_MESSAGE_START,
1741
+ messageId: message.id,
1742
+ role: message.role
1743
+ };
1744
+ events.push(textStartEvent);
1745
+ const textContentEvent = {
1746
+ type: import_client6.EventType.TEXT_MESSAGE_CONTENT,
1747
+ messageId: message.id,
1748
+ delta: message.content
1749
+ };
1750
+ events.push(textContentEvent);
1751
+ const textEndEvent = {
1752
+ type: import_client6.EventType.TEXT_MESSAGE_END,
1753
+ messageId: message.id
1754
+ };
1755
+ events.push(textEndEvent);
1756
+ }
1757
+ if (message.role === "assistant" && message.toolCalls) {
1758
+ for (const toolCall of message.toolCalls) {
1759
+ const toolStartEvent = {
1760
+ type: import_client6.EventType.TOOL_CALL_START,
1761
+ toolCallId: toolCall.id,
1762
+ toolCallName: toolCall.function.name,
1763
+ parentMessageId: message.id
1764
+ };
1765
+ events.push(toolStartEvent);
1766
+ const toolArgsEvent = {
1767
+ type: import_client6.EventType.TOOL_CALL_ARGS,
1768
+ toolCallId: toolCall.id,
1769
+ delta: toolCall.function.arguments
1770
+ };
1771
+ events.push(toolArgsEvent);
1772
+ const toolEndEvent = {
1773
+ type: import_client6.EventType.TOOL_CALL_END,
1774
+ toolCallId: toolCall.id
1775
+ };
1776
+ events.push(toolEndEvent);
1777
+ }
1778
+ }
1779
+ if (message.role === "tool" && message.toolCallId) {
1780
+ const toolResultEvent = {
1781
+ type: import_client6.EventType.TOOL_CALL_RESULT,
1782
+ messageId: message.id,
1783
+ toolCallId: message.toolCallId,
1784
+ content: message.content,
1785
+ role: "tool"
1786
+ };
1787
+ events.push(toolResultEvent);
1788
+ }
1789
+ return events;
1790
+ }
1791
+ async initializeSchema() {
1792
+ try {
1793
+ await this.db.schema.createTable("agent_runs").ifNotExists().addColumn("id", "integer", (col) => col.primaryKey().autoIncrement()).addColumn("thread_id", "text", (col) => col.notNull()).addColumn("run_id", "text", (col) => col.notNull().unique()).addColumn("parent_run_id", "text").addColumn("events", "text", (col) => col.notNull()).addColumn("input", "text", (col) => col.notNull()).addColumn("created_at", "integer", (col) => col.notNull()).addColumn("version", "integer", (col) => col.notNull()).execute().catch(() => {
1794
+ });
1795
+ await this.db.schema.createTable("run_state").ifNotExists().addColumn("thread_id", "text", (col) => col.primaryKey()).addColumn("is_running", "integer", (col) => col.defaultTo(0)).addColumn("current_run_id", "text").addColumn("server_id", "text").addColumn("updated_at", "integer", (col) => col.notNull()).execute().catch(() => {
1796
+ });
1797
+ await this.db.schema.createTable("schema_version").ifNotExists().addColumn("version", "integer", (col) => col.primaryKey()).addColumn("applied_at", "integer", (col) => col.notNull()).execute().catch(() => {
1798
+ });
1799
+ await this.db.schema.createIndex("idx_thread_id").ifNotExists().on("agent_runs").column("thread_id").execute().catch(() => {
1800
+ });
1801
+ await this.db.schema.createIndex("idx_parent_run_id").ifNotExists().on("agent_runs").column("parent_run_id").execute().catch(() => {
1802
+ });
1803
+ const currentVersion = await this.db.selectFrom("schema_version").orderBy("version", "desc").limit(1).selectAll().executeTakeFirst();
1804
+ if (!currentVersion || currentVersion.version < SCHEMA_VERSION2) {
1805
+ await this.db.insertInto("schema_version").values({
1806
+ version: SCHEMA_VERSION2,
1807
+ applied_at: Date.now()
1808
+ }).onConflict(
1809
+ (oc) => oc.column("version").doUpdateSet({ applied_at: Date.now() })
1810
+ ).execute();
1811
+ }
1812
+ } catch {
1813
+ }
1814
+ }
1815
+ async storeRun(threadId, runId, events, input, parentRunId) {
1816
+ await this.db.insertInto("agent_runs").values({
1817
+ thread_id: threadId,
1818
+ run_id: runId,
1819
+ parent_run_id: parentRunId,
1820
+ events: JSON.stringify(events),
1821
+ input: JSON.stringify(input),
1822
+ created_at: Date.now(),
1823
+ version: SCHEMA_VERSION2
1824
+ }).execute();
1825
+ }
1826
+ async getHistoricRuns(threadId) {
1827
+ const rows = await this.db.selectFrom("agent_runs").where("thread_id", "=", threadId).orderBy("created_at", "asc").selectAll().execute();
1828
+ return rows.map((row) => ({
1829
+ id: Number(row.id),
1830
+ thread_id: row.thread_id,
1831
+ run_id: row.run_id,
1832
+ parent_run_id: row.parent_run_id,
1833
+ events: row.events,
1834
+ input: row.input,
1835
+ created_at: row.created_at,
1836
+ version: row.version
1837
+ }));
1838
+ }
1839
+ async setRunState(threadId, isRunning, runId) {
1840
+ await this.db.insertInto("run_state").values({
1841
+ thread_id: threadId,
1842
+ is_running: isRunning ? 1 : 0,
1843
+ current_run_id: runId ?? null,
1844
+ server_id: this.serverId,
1845
+ updated_at: Date.now()
1846
+ }).onConflict(
1847
+ (oc) => oc.column("thread_id").doUpdateSet({
1848
+ is_running: isRunning ? 1 : 0,
1849
+ current_run_id: runId ?? null,
1850
+ server_id: this.serverId,
1851
+ updated_at: Date.now()
1852
+ })
1853
+ ).execute();
1854
+ }
1855
+ async close() {
1856
+ await this.db.destroy();
1857
+ this.redis.disconnect();
1858
+ this.redisSub.disconnect();
1859
+ }
1860
+ generateServerId() {
1861
+ return `server-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
1862
+ }
1863
+ };
1864
+ // Annotate the CommonJS export names for ESM import in node:
1865
+ 0 && (module.exports = {
1866
+ CopilotRuntime,
1867
+ EnterpriseAgentRunner,
1868
+ InMemoryAgentRunner,
1869
+ SqliteAgentRunner,
1870
+ VERSION,
1871
+ createCopilotEndpoint
1872
+ });
1873
+ //# sourceMappingURL=index.js.map