@copilotkit/sqlite-runner 0.0.0-main-20260402184302

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.
@@ -0,0 +1,517 @@
1
+ import {
2
+ AgentRunner,
3
+ finalizeRunEvents,
4
+ type AgentRunnerConnectRequest,
5
+ type AgentRunnerIsRunningRequest,
6
+ type AgentRunnerRunRequest,
7
+ type AgentRunnerStopRequest,
8
+ } from "@copilotkit/runtime/v2";
9
+ import { Observable, ReplaySubject } from "rxjs";
10
+ import {
11
+ AbstractAgent,
12
+ BaseEvent,
13
+ RunAgentInput,
14
+ EventType,
15
+ RunStartedEvent,
16
+ compactEvents,
17
+ } from "@ag-ui/client";
18
+ import Database from "better-sqlite3";
19
+
20
+ const SCHEMA_VERSION = 1;
21
+
22
+ interface AgentRunRecord {
23
+ id: number;
24
+ thread_id: string;
25
+ run_id: string;
26
+ parent_run_id: string | null;
27
+ events: BaseEvent[];
28
+ input: RunAgentInput;
29
+ created_at: number;
30
+ version: number;
31
+ }
32
+
33
+ export interface SqliteAgentRunnerOptions {
34
+ dbPath?: string;
35
+ }
36
+
37
+ interface ActiveConnectionContext {
38
+ subject: ReplaySubject<BaseEvent>;
39
+ agent?: AbstractAgent;
40
+ runSubject?: ReplaySubject<BaseEvent>;
41
+ currentEvents?: BaseEvent[];
42
+ stopRequested?: boolean;
43
+ }
44
+
45
+ // Active connections for streaming events and stop support
46
+ const ACTIVE_CONNECTIONS = new Map<string, ActiveConnectionContext>();
47
+
48
+ export class SqliteAgentRunner extends AgentRunner {
49
+ private db: any;
50
+
51
+ constructor(options: SqliteAgentRunnerOptions = {}) {
52
+ super();
53
+ const dbPath = options.dbPath ?? ":memory:";
54
+
55
+ if (!Database) {
56
+ throw new Error(
57
+ "better-sqlite3 is required for SqliteAgentRunner but was not found.\n" +
58
+ "Please install it in your project:\n" +
59
+ " npm install better-sqlite3\n" +
60
+ " or\n" +
61
+ " pnpm add better-sqlite3\n" +
62
+ " or\n" +
63
+ " yarn add better-sqlite3\n\n" +
64
+ "If you don't need persistence, use InMemoryAgentRunner instead.",
65
+ );
66
+ }
67
+
68
+ this.db = new Database(dbPath);
69
+ this.initializeSchema();
70
+ }
71
+
72
+ private initializeSchema(): void {
73
+ // Create the agent_runs table
74
+ this.db.exec(`
75
+ CREATE TABLE IF NOT EXISTS agent_runs (
76
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
77
+ thread_id TEXT NOT NULL,
78
+ run_id TEXT NOT NULL UNIQUE,
79
+ parent_run_id TEXT,
80
+ events TEXT NOT NULL,
81
+ input TEXT NOT NULL,
82
+ created_at INTEGER NOT NULL,
83
+ version INTEGER NOT NULL
84
+ )
85
+ `);
86
+
87
+ // Create run_state table to track active runs
88
+ this.db.exec(`
89
+ CREATE TABLE IF NOT EXISTS run_state (
90
+ thread_id TEXT PRIMARY KEY,
91
+ is_running INTEGER DEFAULT 0,
92
+ current_run_id TEXT,
93
+ updated_at INTEGER NOT NULL
94
+ )
95
+ `);
96
+
97
+ // Create indexes for efficient queries
98
+ this.db.exec(`
99
+ CREATE INDEX IF NOT EXISTS idx_thread_id ON agent_runs(thread_id);
100
+ CREATE INDEX IF NOT EXISTS idx_parent_run_id ON agent_runs(parent_run_id);
101
+ `);
102
+
103
+ // Create schema version table
104
+ this.db.exec(`
105
+ CREATE TABLE IF NOT EXISTS schema_version (
106
+ version INTEGER PRIMARY KEY,
107
+ applied_at INTEGER NOT NULL
108
+ )
109
+ `);
110
+
111
+ // Check and set schema version
112
+ const currentVersion = this.db
113
+ .prepare(
114
+ "SELECT version FROM schema_version ORDER BY version DESC LIMIT 1",
115
+ )
116
+ .get() as { version: number } | undefined;
117
+
118
+ if (!currentVersion || currentVersion.version < SCHEMA_VERSION) {
119
+ this.db
120
+ .prepare(
121
+ "INSERT OR REPLACE INTO schema_version (version, applied_at) VALUES (?, ?)",
122
+ )
123
+ .run(SCHEMA_VERSION, Date.now());
124
+ }
125
+ }
126
+
127
+ private storeRun(
128
+ threadId: string,
129
+ runId: string,
130
+ events: BaseEvent[],
131
+ input: RunAgentInput,
132
+ parentRunId?: string | null,
133
+ ): void {
134
+ // Compact ONLY the events from this run
135
+ const compactedEvents = compactEvents(events);
136
+
137
+ const stmt = this.db.prepare(`
138
+ INSERT INTO agent_runs (thread_id, run_id, parent_run_id, events, input, created_at, version)
139
+ VALUES (?, ?, ?, ?, ?, ?, ?)
140
+ `);
141
+
142
+ stmt.run(
143
+ threadId,
144
+ runId,
145
+ parentRunId ?? null,
146
+ JSON.stringify(compactedEvents), // Store only this run's compacted events
147
+ JSON.stringify(input),
148
+ Date.now(),
149
+ SCHEMA_VERSION,
150
+ );
151
+ }
152
+
153
+ private getHistoricRuns(threadId: string): AgentRunRecord[] {
154
+ const stmt = this.db.prepare(`
155
+ WITH RECURSIVE run_chain AS (
156
+ -- Base case: find the root runs (those without parent)
157
+ SELECT * FROM agent_runs
158
+ WHERE thread_id = ? AND parent_run_id IS NULL
159
+
160
+ UNION ALL
161
+
162
+ -- Recursive case: find children of current level
163
+ SELECT ar.* FROM agent_runs ar
164
+ INNER JOIN run_chain rc ON ar.parent_run_id = rc.run_id
165
+ WHERE ar.thread_id = ?
166
+ )
167
+ SELECT * FROM run_chain
168
+ ORDER BY created_at ASC
169
+ `);
170
+
171
+ const rows = stmt.all(threadId, threadId) as any[];
172
+
173
+ return rows.map((row) => ({
174
+ id: row.id,
175
+ thread_id: row.thread_id,
176
+ run_id: row.run_id,
177
+ parent_run_id: row.parent_run_id,
178
+ events: JSON.parse(row.events),
179
+ input: JSON.parse(row.input),
180
+ created_at: row.created_at,
181
+ version: row.version,
182
+ }));
183
+ }
184
+
185
+ private getLatestRunId(threadId: string): string | null {
186
+ const stmt = this.db.prepare(`
187
+ SELECT run_id FROM agent_runs
188
+ WHERE thread_id = ?
189
+ ORDER BY created_at DESC
190
+ LIMIT 1
191
+ `);
192
+
193
+ const result = stmt.get(threadId) as { run_id: string } | undefined;
194
+ return result?.run_id ?? null;
195
+ }
196
+
197
+ private setRunState(
198
+ threadId: string,
199
+ isRunning: boolean,
200
+ runId?: string,
201
+ ): void {
202
+ const stmt = this.db.prepare(`
203
+ INSERT OR REPLACE INTO run_state (thread_id, is_running, current_run_id, updated_at)
204
+ VALUES (?, ?, ?, ?)
205
+ `);
206
+ stmt.run(threadId, isRunning ? 1 : 0, runId ?? null, Date.now());
207
+ }
208
+
209
+ private getRunState(threadId: string): {
210
+ isRunning: boolean;
211
+ currentRunId: string | null;
212
+ } {
213
+ const stmt = this.db.prepare(`
214
+ SELECT is_running, current_run_id FROM run_state WHERE thread_id = ?
215
+ `);
216
+ const result = stmt.get(threadId) as
217
+ | { is_running: number; current_run_id: string | null }
218
+ | undefined;
219
+
220
+ return {
221
+ isRunning: result?.is_running === 1,
222
+ currentRunId: result?.current_run_id ?? null,
223
+ };
224
+ }
225
+
226
+ run(request: AgentRunnerRunRequest): Observable<BaseEvent> {
227
+ // Check if thread is already running in database
228
+ const runState = this.getRunState(request.threadId);
229
+ if (runState.isRunning) {
230
+ throw new Error("Thread already running");
231
+ }
232
+
233
+ // Mark thread as running in database
234
+ this.setRunState(request.threadId, true, request.input.runId);
235
+
236
+ // Track seen message IDs and current run events in memory for this run
237
+ const seenMessageIds = new Set<string>();
238
+ const currentRunEvents: BaseEvent[] = [];
239
+
240
+ // Get all previously seen message IDs from historic runs
241
+ const historicRuns = this.getHistoricRuns(request.threadId);
242
+ const historicMessageIds = new Set<string>();
243
+ for (const run of historicRuns) {
244
+ for (const event of run.events) {
245
+ if ("messageId" in event && typeof event.messageId === "string") {
246
+ historicMessageIds.add(event.messageId);
247
+ }
248
+ if (event.type === EventType.RUN_STARTED) {
249
+ const runStarted = event as RunStartedEvent;
250
+ const messages = runStarted.input?.messages ?? [];
251
+ for (const message of messages) {
252
+ historicMessageIds.add(message.id);
253
+ }
254
+ }
255
+ }
256
+ }
257
+
258
+ // Get or create subject for this thread's connections
259
+ const nextSubject = new ReplaySubject<BaseEvent>(Infinity);
260
+ const prevConnection = ACTIVE_CONNECTIONS.get(request.threadId);
261
+ const prevSubject = prevConnection?.subject;
262
+
263
+ // Create a subject for run() return value
264
+ const runSubject = new ReplaySubject<BaseEvent>(Infinity);
265
+
266
+ // Update the active connection for this thread
267
+ ACTIVE_CONNECTIONS.set(request.threadId, {
268
+ subject: nextSubject,
269
+ agent: request.agent,
270
+ runSubject,
271
+ currentEvents: currentRunEvents,
272
+ stopRequested: false,
273
+ });
274
+
275
+ // Helper function to run the agent and handle errors
276
+ const runAgent = async () => {
277
+ // Get parent run ID for chaining
278
+ const parentRunId = this.getLatestRunId(request.threadId);
279
+
280
+ try {
281
+ await request.agent.runAgent(request.input, {
282
+ onEvent: ({ event }) => {
283
+ let processedEvent: BaseEvent = event;
284
+ if (event.type === EventType.RUN_STARTED) {
285
+ const runStartedEvent = event as RunStartedEvent;
286
+ if (!runStartedEvent.input) {
287
+ const sanitizedMessages = request.input.messages
288
+ ? request.input.messages.filter(
289
+ (message) => !historicMessageIds.has(message.id),
290
+ )
291
+ : undefined;
292
+ const updatedInput = {
293
+ ...request.input,
294
+ ...(sanitizedMessages !== undefined
295
+ ? { messages: sanitizedMessages }
296
+ : {}),
297
+ };
298
+ processedEvent = {
299
+ ...runStartedEvent,
300
+ input: updatedInput,
301
+ } as RunStartedEvent;
302
+ }
303
+ }
304
+
305
+ runSubject.next(processedEvent); // For run() return - only agent events
306
+ nextSubject.next(processedEvent); // For connect() / store - all events
307
+ currentRunEvents.push(processedEvent); // Accumulate for database storage
308
+ },
309
+ onNewMessage: ({ message }) => {
310
+ // Called for each new message
311
+ if (!seenMessageIds.has(message.id)) {
312
+ seenMessageIds.add(message.id);
313
+ }
314
+ },
315
+ onRunStartedEvent: () => {
316
+ // Mark input messages as seen without emitting duplicates
317
+ if (request.input.messages) {
318
+ for (const message of request.input.messages) {
319
+ if (!seenMessageIds.has(message.id)) {
320
+ seenMessageIds.add(message.id);
321
+ }
322
+ }
323
+ }
324
+ },
325
+ });
326
+
327
+ const connection = ACTIVE_CONNECTIONS.get(request.threadId);
328
+ const appendedEvents = finalizeRunEvents(currentRunEvents, {
329
+ stopRequested: connection?.stopRequested ?? false,
330
+ });
331
+ for (const event of appendedEvents) {
332
+ runSubject.next(event);
333
+ nextSubject.next(event);
334
+ }
335
+
336
+ // Store the run in database
337
+ this.storeRun(
338
+ request.threadId,
339
+ request.input.runId,
340
+ currentRunEvents,
341
+ request.input,
342
+ parentRunId,
343
+ );
344
+
345
+ // Mark run as complete in database
346
+ this.setRunState(request.threadId, false);
347
+
348
+ if (connection) {
349
+ connection.agent = undefined;
350
+ connection.runSubject = undefined;
351
+ connection.currentEvents = undefined;
352
+ connection.stopRequested = false;
353
+ }
354
+
355
+ // Complete the subjects
356
+ runSubject.complete();
357
+ nextSubject.complete();
358
+
359
+ ACTIVE_CONNECTIONS.delete(request.threadId);
360
+ } catch {
361
+ const connection = ACTIVE_CONNECTIONS.get(request.threadId);
362
+ const appendedEvents = finalizeRunEvents(currentRunEvents, {
363
+ stopRequested: connection?.stopRequested ?? false,
364
+ });
365
+ for (const event of appendedEvents) {
366
+ runSubject.next(event);
367
+ nextSubject.next(event);
368
+ }
369
+
370
+ // Store the run even if it failed (partial events)
371
+ if (currentRunEvents.length > 0) {
372
+ this.storeRun(
373
+ request.threadId,
374
+ request.input.runId,
375
+ currentRunEvents,
376
+ request.input,
377
+ parentRunId,
378
+ );
379
+ }
380
+
381
+ // Mark run as complete in database
382
+ this.setRunState(request.threadId, false);
383
+
384
+ if (connection) {
385
+ connection.agent = undefined;
386
+ connection.runSubject = undefined;
387
+ connection.currentEvents = undefined;
388
+ connection.stopRequested = false;
389
+ }
390
+
391
+ // Don't emit error to the subject, just complete it
392
+ // This allows subscribers to get events emitted before the error
393
+ runSubject.complete();
394
+ nextSubject.complete();
395
+
396
+ ACTIVE_CONNECTIONS.delete(request.threadId);
397
+ }
398
+ };
399
+
400
+ // Bridge previous events if they exist
401
+ if (prevSubject) {
402
+ prevSubject.subscribe({
403
+ next: (e) => nextSubject.next(e),
404
+ error: (err) => nextSubject.error(err),
405
+ complete: () => {
406
+ // Don't complete nextSubject here - it needs to stay open for new events
407
+ },
408
+ });
409
+ }
410
+
411
+ // Start the agent execution immediately (not lazily)
412
+ runAgent();
413
+
414
+ // Return the run subject (only agent events, no injected messages)
415
+ return runSubject.asObservable();
416
+ }
417
+
418
+ connect(request: AgentRunnerConnectRequest): Observable<BaseEvent> {
419
+ const connectionSubject = new ReplaySubject<BaseEvent>(Infinity);
420
+
421
+ // Load historic runs from database
422
+ const historicRuns = this.getHistoricRuns(request.threadId);
423
+
424
+ // Collect all historic events from database
425
+ const allHistoricEvents: BaseEvent[] = [];
426
+ for (const run of historicRuns) {
427
+ allHistoricEvents.push(...run.events);
428
+ }
429
+
430
+ // Compact all events together before emitting
431
+ const compactedEvents = compactEvents(allHistoricEvents);
432
+
433
+ // Emit compacted events and track message IDs
434
+ const emittedMessageIds = new Set<string>();
435
+ for (const event of compactedEvents) {
436
+ connectionSubject.next(event);
437
+ if ("messageId" in event && typeof event.messageId === "string") {
438
+ emittedMessageIds.add(event.messageId);
439
+ }
440
+ }
441
+
442
+ // Bridge active run to connection if exists
443
+ const activeConnection = ACTIVE_CONNECTIONS.get(request.threadId);
444
+ const runState = this.getRunState(request.threadId);
445
+
446
+ if (
447
+ activeConnection &&
448
+ (runState.isRunning || activeConnection.stopRequested)
449
+ ) {
450
+ activeConnection.subject.subscribe({
451
+ next: (event) => {
452
+ // Skip message events that we've already emitted from historic
453
+ if (
454
+ "messageId" in event &&
455
+ typeof event.messageId === "string" &&
456
+ emittedMessageIds.has(event.messageId)
457
+ ) {
458
+ return;
459
+ }
460
+ connectionSubject.next(event);
461
+ },
462
+ complete: () => connectionSubject.complete(),
463
+ error: (err) => connectionSubject.error(err),
464
+ });
465
+ } else {
466
+ // No active run, complete after historic events
467
+ connectionSubject.complete();
468
+ }
469
+
470
+ return connectionSubject.asObservable();
471
+ }
472
+
473
+ isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean> {
474
+ const runState = this.getRunState(request.threadId);
475
+ return Promise.resolve(runState.isRunning);
476
+ }
477
+
478
+ stop(request: AgentRunnerStopRequest): Promise<boolean | undefined> {
479
+ const runState = this.getRunState(request.threadId);
480
+ if (!runState.isRunning) {
481
+ return Promise.resolve(false);
482
+ }
483
+
484
+ const connection = ACTIVE_CONNECTIONS.get(request.threadId);
485
+ const agent = connection?.agent;
486
+
487
+ if (!connection || !agent) {
488
+ return Promise.resolve(false);
489
+ }
490
+
491
+ if (connection.stopRequested) {
492
+ return Promise.resolve(false);
493
+ }
494
+
495
+ connection.stopRequested = true;
496
+ this.setRunState(request.threadId, false);
497
+
498
+ try {
499
+ agent.abortRun();
500
+ return Promise.resolve(true);
501
+ } catch (error) {
502
+ console.error("Failed to abort sqlite agent run", error);
503
+ connection.stopRequested = false;
504
+ this.setRunState(request.threadId, true);
505
+ return Promise.resolve(false);
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Close the database connection (for cleanup)
511
+ */
512
+ close(): void {
513
+ if (this.db) {
514
+ this.db.close();
515
+ }
516
+ }
517
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "@copilotkit/typescript-config/base.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src",
6
+ "declaration": true,
7
+ "declarationMap": true,
8
+ "sourceMap": true,
9
+ "types": ["vitest/globals"]
10
+ },
11
+ "include": ["src/**/*"],
12
+ "exclude": ["dist", "node_modules", "src/**/__tests__/**", "src/**/*.test.ts"]
13
+ }
@@ -0,0 +1,12 @@
1
+ import { defineConfig } from "tsdown";
2
+
3
+ export default defineConfig({
4
+ entry: ["src/index.ts"],
5
+ format: ["esm", "cjs"],
6
+ dts: true,
7
+ sourcemap: true,
8
+ target: "es2022",
9
+ outDir: "dist",
10
+ unbundle: true,
11
+ exports: true,
12
+ });
@@ -0,0 +1,21 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ // Prevent Scarf telemetry events from firing during test runs
6
+ env: {
7
+ COPILOTKIT_TELEMETRY_DISABLED: "true",
8
+ },
9
+ environment: "node",
10
+ globals: true,
11
+ include: ["src/**/__tests__/**/*.{test,spec}.ts"],
12
+ reporters: [["default", { summary: false }]],
13
+ silent: true,
14
+ coverage: {
15
+ reporter: ["text", "lcov", "html"],
16
+ include: ["src/**/*.ts"],
17
+ exclude: ["src/**/*.d.ts", "src/**/index.ts"],
18
+ },
19
+ setupFiles: [],
20
+ },
21
+ });