@copilotkitnext/sqlite-runner 1.51.5-next.0 → 1.51.5-next.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @copilotkitnext/sqlite-runner
2
2
 
3
+ ## 1.51.5-next.1
4
+
5
+ ### Patch Changes
6
+
7
+ - @copilotkitnext/runtime@1.51.5-next.1
8
+
3
9
  ## 1.51.5-next.0
4
10
 
5
11
  ### Patch Changes
@@ -0,0 +1,29 @@
1
+ //#region \0rolldown/runtime.js
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 __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+
29
+ exports.__toESM = __toESM;
package/dist/index.cjs ADDED
@@ -0,0 +1,4 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_sqlite_runner = require('./sqlite-runner.cjs');
3
+
4
+ exports.SqliteAgentRunner = require_sqlite_runner.SqliteAgentRunner;
@@ -0,0 +1,2 @@
1
+ import { SqliteAgentRunner, SqliteAgentRunnerOptions } from "./sqlite-runner.cjs";
2
+ export { SqliteAgentRunner, SqliteAgentRunnerOptions };
package/dist/index.d.mts CHANGED
@@ -1,27 +1,2 @@
1
- import { AgentRunner, AgentRunnerRunRequest, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerStopRequest } from '@copilotkitnext/runtime';
2
- import { Observable } from 'rxjs';
3
- import { BaseEvent } from '@ag-ui/client';
4
-
5
- interface SqliteAgentRunnerOptions {
6
- dbPath?: string;
7
- }
8
- declare class SqliteAgentRunner extends AgentRunner {
9
- private db;
10
- constructor(options?: SqliteAgentRunnerOptions);
11
- private initializeSchema;
12
- private storeRun;
13
- private getHistoricRuns;
14
- private getLatestRunId;
15
- private setRunState;
16
- private getRunState;
17
- run(request: AgentRunnerRunRequest): Observable<BaseEvent>;
18
- connect(request: AgentRunnerConnectRequest): Observable<BaseEvent>;
19
- isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean>;
20
- stop(request: AgentRunnerStopRequest): Promise<boolean | undefined>;
21
- /**
22
- * Close the database connection (for cleanup)
23
- */
24
- close(): void;
25
- }
26
-
27
- export { SqliteAgentRunner, type SqliteAgentRunnerOptions };
1
+ import { SqliteAgentRunner, SqliteAgentRunnerOptions } from "./sqlite-runner.mjs";
2
+ export { SqliteAgentRunner, SqliteAgentRunnerOptions };
package/dist/index.mjs CHANGED
@@ -1,356 +1,3 @@
1
- // src/sqlite-runner.ts
2
- import {
3
- AgentRunner,
4
- finalizeRunEvents
5
- } from "@copilotkitnext/runtime";
6
- import { ReplaySubject } from "rxjs";
7
- import {
8
- EventType,
9
- compactEvents
10
- } from "@ag-ui/client";
11
- import Database from "better-sqlite3";
12
- var SCHEMA_VERSION = 1;
13
- var ACTIVE_CONNECTIONS = /* @__PURE__ */ new Map();
14
- var SqliteAgentRunner = class extends AgentRunner {
15
- db;
16
- constructor(options = {}) {
17
- super();
18
- const dbPath = options.dbPath ?? ":memory:";
19
- if (!Database) {
20
- throw new Error(
21
- "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."
22
- );
23
- }
24
- this.db = new Database(dbPath);
25
- this.initializeSchema();
26
- }
27
- initializeSchema() {
28
- this.db.exec(`
29
- CREATE TABLE IF NOT EXISTS agent_runs (
30
- id INTEGER PRIMARY KEY AUTOINCREMENT,
31
- thread_id TEXT NOT NULL,
32
- run_id TEXT NOT NULL UNIQUE,
33
- parent_run_id TEXT,
34
- events TEXT NOT NULL,
35
- input TEXT NOT NULL,
36
- created_at INTEGER NOT NULL,
37
- version INTEGER NOT NULL
38
- )
39
- `);
40
- this.db.exec(`
41
- CREATE TABLE IF NOT EXISTS run_state (
42
- thread_id TEXT PRIMARY KEY,
43
- is_running INTEGER DEFAULT 0,
44
- current_run_id TEXT,
45
- updated_at INTEGER NOT NULL
46
- )
47
- `);
48
- this.db.exec(`
49
- CREATE INDEX IF NOT EXISTS idx_thread_id ON agent_runs(thread_id);
50
- CREATE INDEX IF NOT EXISTS idx_parent_run_id ON agent_runs(parent_run_id);
51
- `);
52
- this.db.exec(`
53
- CREATE TABLE IF NOT EXISTS schema_version (
54
- version INTEGER PRIMARY KEY,
55
- applied_at INTEGER NOT NULL
56
- )
57
- `);
58
- const currentVersion = this.db.prepare(
59
- "SELECT version FROM schema_version ORDER BY version DESC LIMIT 1"
60
- ).get();
61
- if (!currentVersion || currentVersion.version < SCHEMA_VERSION) {
62
- this.db.prepare(
63
- "INSERT OR REPLACE INTO schema_version (version, applied_at) VALUES (?, ?)"
64
- ).run(SCHEMA_VERSION, Date.now());
65
- }
66
- }
67
- storeRun(threadId, runId, events, input, parentRunId) {
68
- const compactedEvents = compactEvents(events);
69
- const stmt = this.db.prepare(`
70
- INSERT INTO agent_runs (thread_id, run_id, parent_run_id, events, input, created_at, version)
71
- VALUES (?, ?, ?, ?, ?, ?, ?)
72
- `);
73
- stmt.run(
74
- threadId,
75
- runId,
76
- parentRunId ?? null,
77
- JSON.stringify(compactedEvents),
78
- // Store only this run's compacted events
79
- JSON.stringify(input),
80
- Date.now(),
81
- SCHEMA_VERSION
82
- );
83
- }
84
- getHistoricRuns(threadId) {
85
- const stmt = this.db.prepare(`
86
- WITH RECURSIVE run_chain AS (
87
- -- Base case: find the root runs (those without parent)
88
- SELECT * FROM agent_runs
89
- WHERE thread_id = ? AND parent_run_id IS NULL
90
-
91
- UNION ALL
92
-
93
- -- Recursive case: find children of current level
94
- SELECT ar.* FROM agent_runs ar
95
- INNER JOIN run_chain rc ON ar.parent_run_id = rc.run_id
96
- WHERE ar.thread_id = ?
97
- )
98
- SELECT * FROM run_chain
99
- ORDER BY created_at ASC
100
- `);
101
- const rows = stmt.all(threadId, threadId);
102
- return rows.map((row) => ({
103
- id: row.id,
104
- thread_id: row.thread_id,
105
- run_id: row.run_id,
106
- parent_run_id: row.parent_run_id,
107
- events: JSON.parse(row.events),
108
- input: JSON.parse(row.input),
109
- created_at: row.created_at,
110
- version: row.version
111
- }));
112
- }
113
- getLatestRunId(threadId) {
114
- const stmt = this.db.prepare(`
115
- SELECT run_id FROM agent_runs
116
- WHERE thread_id = ?
117
- ORDER BY created_at DESC
118
- LIMIT 1
119
- `);
120
- const result = stmt.get(threadId);
121
- return result?.run_id ?? null;
122
- }
123
- setRunState(threadId, isRunning, runId) {
124
- const stmt = this.db.prepare(`
125
- INSERT OR REPLACE INTO run_state (thread_id, is_running, current_run_id, updated_at)
126
- VALUES (?, ?, ?, ?)
127
- `);
128
- stmt.run(threadId, isRunning ? 1 : 0, runId ?? null, Date.now());
129
- }
130
- getRunState(threadId) {
131
- const stmt = this.db.prepare(`
132
- SELECT is_running, current_run_id FROM run_state WHERE thread_id = ?
133
- `);
134
- const result = stmt.get(threadId);
135
- return {
136
- isRunning: result?.is_running === 1,
137
- currentRunId: result?.current_run_id ?? null
138
- };
139
- }
140
- run(request) {
141
- const runState = this.getRunState(request.threadId);
142
- if (runState.isRunning) {
143
- throw new Error("Thread already running");
144
- }
145
- this.setRunState(request.threadId, true, request.input.runId);
146
- const seenMessageIds = /* @__PURE__ */ new Set();
147
- const currentRunEvents = [];
148
- const historicRuns = this.getHistoricRuns(request.threadId);
149
- const historicMessageIds = /* @__PURE__ */ new Set();
150
- for (const run of historicRuns) {
151
- for (const event of run.events) {
152
- if ("messageId" in event && typeof event.messageId === "string") {
153
- historicMessageIds.add(event.messageId);
154
- }
155
- if (event.type === EventType.RUN_STARTED) {
156
- const runStarted = event;
157
- const messages = runStarted.input?.messages ?? [];
158
- for (const message of messages) {
159
- historicMessageIds.add(message.id);
160
- }
161
- }
162
- }
163
- }
164
- const nextSubject = new ReplaySubject(Infinity);
165
- const prevConnection = ACTIVE_CONNECTIONS.get(request.threadId);
166
- const prevSubject = prevConnection?.subject;
167
- const runSubject = new ReplaySubject(Infinity);
168
- ACTIVE_CONNECTIONS.set(request.threadId, {
169
- subject: nextSubject,
170
- agent: request.agent,
171
- runSubject,
172
- currentEvents: currentRunEvents,
173
- stopRequested: false
174
- });
175
- const runAgent = async () => {
176
- const parentRunId = this.getLatestRunId(request.threadId);
177
- try {
178
- await request.agent.runAgent(request.input, {
179
- onEvent: ({ event }) => {
180
- let processedEvent = event;
181
- if (event.type === EventType.RUN_STARTED) {
182
- const runStartedEvent = event;
183
- if (!runStartedEvent.input) {
184
- const sanitizedMessages = request.input.messages ? request.input.messages.filter(
185
- (message) => !historicMessageIds.has(message.id)
186
- ) : void 0;
187
- const updatedInput = {
188
- ...request.input,
189
- ...sanitizedMessages !== void 0 ? { messages: sanitizedMessages } : {}
190
- };
191
- processedEvent = {
192
- ...runStartedEvent,
193
- input: updatedInput
194
- };
195
- }
196
- }
197
- runSubject.next(processedEvent);
198
- nextSubject.next(processedEvent);
199
- currentRunEvents.push(processedEvent);
200
- },
201
- onNewMessage: ({ message }) => {
202
- if (!seenMessageIds.has(message.id)) {
203
- seenMessageIds.add(message.id);
204
- }
205
- },
206
- onRunStartedEvent: () => {
207
- if (request.input.messages) {
208
- for (const message of request.input.messages) {
209
- if (!seenMessageIds.has(message.id)) {
210
- seenMessageIds.add(message.id);
211
- }
212
- }
213
- }
214
- }
215
- });
216
- const connection = ACTIVE_CONNECTIONS.get(request.threadId);
217
- const appendedEvents = finalizeRunEvents(currentRunEvents, {
218
- stopRequested: connection?.stopRequested ?? false
219
- });
220
- for (const event of appendedEvents) {
221
- runSubject.next(event);
222
- nextSubject.next(event);
223
- }
224
- this.storeRun(
225
- request.threadId,
226
- request.input.runId,
227
- currentRunEvents,
228
- request.input,
229
- parentRunId
230
- );
231
- this.setRunState(request.threadId, false);
232
- if (connection) {
233
- connection.agent = void 0;
234
- connection.runSubject = void 0;
235
- connection.currentEvents = void 0;
236
- connection.stopRequested = false;
237
- }
238
- runSubject.complete();
239
- nextSubject.complete();
240
- ACTIVE_CONNECTIONS.delete(request.threadId);
241
- } catch {
242
- const connection = ACTIVE_CONNECTIONS.get(request.threadId);
243
- const appendedEvents = finalizeRunEvents(currentRunEvents, {
244
- stopRequested: connection?.stopRequested ?? false
245
- });
246
- for (const event of appendedEvents) {
247
- runSubject.next(event);
248
- nextSubject.next(event);
249
- }
250
- if (currentRunEvents.length > 0) {
251
- this.storeRun(
252
- request.threadId,
253
- request.input.runId,
254
- currentRunEvents,
255
- request.input,
256
- parentRunId
257
- );
258
- }
259
- this.setRunState(request.threadId, false);
260
- if (connection) {
261
- connection.agent = void 0;
262
- connection.runSubject = void 0;
263
- connection.currentEvents = void 0;
264
- connection.stopRequested = false;
265
- }
266
- runSubject.complete();
267
- nextSubject.complete();
268
- ACTIVE_CONNECTIONS.delete(request.threadId);
269
- }
270
- };
271
- if (prevSubject) {
272
- prevSubject.subscribe({
273
- next: (e) => nextSubject.next(e),
274
- error: (err) => nextSubject.error(err),
275
- complete: () => {
276
- }
277
- });
278
- }
279
- runAgent();
280
- return runSubject.asObservable();
281
- }
282
- connect(request) {
283
- const connectionSubject = new ReplaySubject(Infinity);
284
- const historicRuns = this.getHistoricRuns(request.threadId);
285
- const allHistoricEvents = [];
286
- for (const run of historicRuns) {
287
- allHistoricEvents.push(...run.events);
288
- }
289
- const compactedEvents = compactEvents(allHistoricEvents);
290
- const emittedMessageIds = /* @__PURE__ */ new Set();
291
- for (const event of compactedEvents) {
292
- connectionSubject.next(event);
293
- if ("messageId" in event && typeof event.messageId === "string") {
294
- emittedMessageIds.add(event.messageId);
295
- }
296
- }
297
- const activeConnection = ACTIVE_CONNECTIONS.get(request.threadId);
298
- const runState = this.getRunState(request.threadId);
299
- if (activeConnection && (runState.isRunning || activeConnection.stopRequested)) {
300
- activeConnection.subject.subscribe({
301
- next: (event) => {
302
- if ("messageId" in event && typeof event.messageId === "string" && emittedMessageIds.has(event.messageId)) {
303
- return;
304
- }
305
- connectionSubject.next(event);
306
- },
307
- complete: () => connectionSubject.complete(),
308
- error: (err) => connectionSubject.error(err)
309
- });
310
- } else {
311
- connectionSubject.complete();
312
- }
313
- return connectionSubject.asObservable();
314
- }
315
- isRunning(request) {
316
- const runState = this.getRunState(request.threadId);
317
- return Promise.resolve(runState.isRunning);
318
- }
319
- stop(request) {
320
- const runState = this.getRunState(request.threadId);
321
- if (!runState.isRunning) {
322
- return Promise.resolve(false);
323
- }
324
- const connection = ACTIVE_CONNECTIONS.get(request.threadId);
325
- const agent = connection?.agent;
326
- if (!connection || !agent) {
327
- return Promise.resolve(false);
328
- }
329
- if (connection.stopRequested) {
330
- return Promise.resolve(false);
331
- }
332
- connection.stopRequested = true;
333
- this.setRunState(request.threadId, false);
334
- try {
335
- agent.abortRun();
336
- return Promise.resolve(true);
337
- } catch (error) {
338
- console.error("Failed to abort sqlite agent run", error);
339
- connection.stopRequested = false;
340
- this.setRunState(request.threadId, true);
341
- return Promise.resolve(false);
342
- }
343
- }
344
- /**
345
- * Close the database connection (for cleanup)
346
- */
347
- close() {
348
- if (this.db) {
349
- this.db.close();
350
- }
351
- }
352
- };
353
- export {
354
- SqliteAgentRunner
355
- };
356
- //# sourceMappingURL=index.mjs.map
1
+ import { SqliteAgentRunner } from "./sqlite-runner.mjs";
2
+
3
+ export { SqliteAgentRunner };