@copilotkitnext/sqlite-runner 0.0.22-alpha.0 → 0.0.22-alpha.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.
@@ -1,23 +1,23 @@
1
1
 
2
2
  
3
- > @copilotkitnext/sqlite-runner@0.0.22-alpha.0 build /Users/mme/Projects/CopilotKit2/threads-final-review/packages/sqlite-runner
3
+ > @copilotkitnext/sqlite-runner@0.0.22-alpha.1 build /Users/ran/Desktop/vnext_experimental/packages/sqlite-runner
4
4
  > tsup
5
5
 
6
6
  CLI Building entry: src/index.ts
7
7
  CLI Using tsconfig: tsconfig.json
8
8
  CLI tsup v8.5.0
9
- CLI Using tsup config: /Users/mme/Projects/CopilotKit2/threads-final-review/packages/sqlite-runner/tsup.config.ts
9
+ CLI Using tsup config: /Users/ran/Desktop/vnext_experimental/packages/sqlite-runner/tsup.config.ts
10
10
  CLI Target: es2022
11
11
  CLI Cleaning output folder
12
12
  CJS Build start
13
13
  ESM Build start
14
- CJS dist/index.js 8.08 KB
15
- CJS dist/index.js.map 11.82 KB
16
- CJS ⚡️ Build success in 16ms
17
- ESM dist/index.mjs 6.37 KB
18
- ESM dist/index.mjs.map 11.70 KB
19
- ESM ⚡️ Build success in 16ms
14
+ ESM dist/index.mjs 11.55 KB
15
+ ESM dist/index.mjs.map 22.22 KB
16
+ ESM ⚡️ Build success in 8ms
17
+ CJS dist/index.js 13.32 KB
18
+ CJS dist/index.js.map 22.31 KB
19
+ CJS ⚡️ Build success in 9ms
20
20
  DTS Build start
21
- DTS ⚡️ Build success in 1333ms
22
- DTS dist/index.d.ts 1.69 KB
23
- DTS dist/index.d.mts 1.69 KB
21
+ DTS ⚡️ Build success in 796ms
22
+ DTS dist/index.d.ts 1009.00 B
23
+ DTS dist/index.d.mts 1009.00 B
package/dist/index.d.mts CHANGED
@@ -1,46 +1,26 @@
1
- import * as _ag_ui_client from '@ag-ui/client';
2
- import { BaseEvent, RunAgentInput } from '@ag-ui/client';
3
- import { AgentRunnerBase } from '@copilotkitnext/runtime';
1
+ import { AgentRunner, AgentRunnerRunRequest, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerStopRequest } from '@copilotkitnext/runtime';
4
2
  import { Observable } from 'rxjs';
3
+ import { BaseEvent } from '@ag-ui/client';
5
4
 
6
5
  interface SqliteAgentRunnerOptions {
7
6
  dbPath?: string;
8
7
  }
9
- declare class SqliteAgentRunner extends AgentRunnerBase {
8
+ declare class SqliteAgentRunner extends AgentRunner {
10
9
  private db;
11
- private channels;
12
10
  constructor(options?: SqliteAgentRunnerOptions);
13
- private static initializeSchema;
14
- protected acquireRun(threadId: string, runId: string): Promise<boolean>;
15
- protected releaseRun(threadId: string): Promise<void>;
16
- protected isRunningState(threadId: string): Promise<boolean>;
17
- protected listRuns(threadId: string): Promise<Array<{
18
- runId: string;
19
- events: BaseEvent[];
20
- createdAt: number;
21
- }>>;
22
- protected saveRun(threadId: string, runId: string, events: BaseEvent[], input: RunAgentInput, parentRunId: string | null): Promise<void>;
23
- protected pageThreads(params: {
24
- scope?: any;
25
- limit?: number;
26
- offset?: number;
27
- }): Promise<{
28
- threadIds: string[];
29
- total: number;
30
- }>;
31
- protected deleteThreadStorage(threadId: string): Promise<void>;
32
- private ensureChannel;
33
- protected publishLive(threadId: string, event: BaseEvent): void;
34
- protected completeLive(threadId: string): void;
35
- protected subscribeLive(threadId: string): Observable<BaseEvent>;
36
- protected closeLive(threadId: string): Promise<void>;
37
- connect(request: {
38
- threadId: string;
39
- }): Observable<{
40
- type: _ag_ui_client.EventType;
41
- timestamp?: number | undefined;
42
- rawEvent?: any;
43
- }>;
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
+ */
44
24
  close(): void;
45
25
  }
46
26
 
package/dist/index.d.ts CHANGED
@@ -1,46 +1,26 @@
1
- import * as _ag_ui_client from '@ag-ui/client';
2
- import { BaseEvent, RunAgentInput } from '@ag-ui/client';
3
- import { AgentRunnerBase } from '@copilotkitnext/runtime';
1
+ import { AgentRunner, AgentRunnerRunRequest, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerStopRequest } from '@copilotkitnext/runtime';
4
2
  import { Observable } from 'rxjs';
3
+ import { BaseEvent } from '@ag-ui/client';
5
4
 
6
5
  interface SqliteAgentRunnerOptions {
7
6
  dbPath?: string;
8
7
  }
9
- declare class SqliteAgentRunner extends AgentRunnerBase {
8
+ declare class SqliteAgentRunner extends AgentRunner {
10
9
  private db;
11
- private channels;
12
10
  constructor(options?: SqliteAgentRunnerOptions);
13
- private static initializeSchema;
14
- protected acquireRun(threadId: string, runId: string): Promise<boolean>;
15
- protected releaseRun(threadId: string): Promise<void>;
16
- protected isRunningState(threadId: string): Promise<boolean>;
17
- protected listRuns(threadId: string): Promise<Array<{
18
- runId: string;
19
- events: BaseEvent[];
20
- createdAt: number;
21
- }>>;
22
- protected saveRun(threadId: string, runId: string, events: BaseEvent[], input: RunAgentInput, parentRunId: string | null): Promise<void>;
23
- protected pageThreads(params: {
24
- scope?: any;
25
- limit?: number;
26
- offset?: number;
27
- }): Promise<{
28
- threadIds: string[];
29
- total: number;
30
- }>;
31
- protected deleteThreadStorage(threadId: string): Promise<void>;
32
- private ensureChannel;
33
- protected publishLive(threadId: string, event: BaseEvent): void;
34
- protected completeLive(threadId: string): void;
35
- protected subscribeLive(threadId: string): Observable<BaseEvent>;
36
- protected closeLive(threadId: string): Promise<void>;
37
- connect(request: {
38
- threadId: string;
39
- }): Observable<{
40
- type: _ag_ui_client.EventType;
41
- timestamp?: number | undefined;
42
- rawEvent?: any;
43
- }>;
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
+ */
44
24
  close(): void;
45
25
  }
46
26
 
package/dist/index.js CHANGED
@@ -36,12 +36,13 @@ module.exports = __toCommonJS(index_exports);
36
36
 
37
37
  // src/sqlite-runner.ts
38
38
  var import_runtime = require("@copilotkitnext/runtime");
39
- var import_better_sqlite3 = __toESM(require("better-sqlite3"));
40
39
  var import_rxjs = require("rxjs");
40
+ var import_client = require("@ag-ui/client");
41
+ var import_better_sqlite3 = __toESM(require("better-sqlite3"));
41
42
  var SCHEMA_VERSION = 1;
42
- var SqliteAgentRunner = class _SqliteAgentRunner extends import_runtime.AgentRunnerBase {
43
+ var ACTIVE_CONNECTIONS = /* @__PURE__ */ new Map();
44
+ var SqliteAgentRunner = class extends import_runtime.AgentRunner {
43
45
  db;
44
- channels = /* @__PURE__ */ new Map();
45
46
  constructor(options = {}) {
46
47
  super();
47
48
  const dbPath = options.dbPath ?? ":memory:";
@@ -50,12 +51,11 @@ var SqliteAgentRunner = class _SqliteAgentRunner extends import_runtime.AgentRun
50
51
  "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."
51
52
  );
52
53
  }
53
- const db = new import_better_sqlite3.default(dbPath);
54
- _SqliteAgentRunner.initializeSchema(db);
55
- this.db = db;
54
+ this.db = new import_better_sqlite3.default(dbPath);
55
+ this.initializeSchema();
56
56
  }
57
- static initializeSchema(db) {
58
- db.exec(`
57
+ initializeSchema() {
58
+ this.db.exec(`
59
59
  CREATE TABLE IF NOT EXISTS agent_runs (
60
60
  id INTEGER PRIMARY KEY AUTOINCREMENT,
61
61
  thread_id TEXT NOT NULL,
@@ -67,7 +67,7 @@ var SqliteAgentRunner = class _SqliteAgentRunner extends import_runtime.AgentRun
67
67
  version INTEGER NOT NULL
68
68
  )
69
69
  `);
70
- db.exec(`
70
+ this.db.exec(`
71
71
  CREATE TABLE IF NOT EXISTS run_state (
72
72
  thread_id TEXT PRIMARY KEY,
73
73
  is_running INTEGER DEFAULT 0,
@@ -75,143 +75,305 @@ var SqliteAgentRunner = class _SqliteAgentRunner extends import_runtime.AgentRun
75
75
  updated_at INTEGER NOT NULL
76
76
  )
77
77
  `);
78
- db.exec(`
78
+ this.db.exec(`
79
79
  CREATE INDEX IF NOT EXISTS idx_thread_id ON agent_runs(thread_id);
80
80
  CREATE INDEX IF NOT EXISTS idx_parent_run_id ON agent_runs(parent_run_id);
81
81
  `);
82
- db.exec(`
82
+ this.db.exec(`
83
83
  CREATE TABLE IF NOT EXISTS schema_version (
84
84
  version INTEGER PRIMARY KEY,
85
85
  applied_at INTEGER NOT NULL
86
86
  )
87
87
  `);
88
- const currentVersion = db.prepare("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1").get();
88
+ const currentVersion = this.db.prepare("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1").get();
89
89
  if (!currentVersion || currentVersion.version < SCHEMA_VERSION) {
90
- db.prepare("INSERT OR REPLACE INTO schema_version (version, applied_at) VALUES (?, ?)").run(SCHEMA_VERSION, Date.now());
90
+ this.db.prepare("INSERT OR REPLACE INTO schema_version (version, applied_at) VALUES (?, ?)").run(SCHEMA_VERSION, Date.now());
91
91
  }
92
92
  }
93
- // Hooks implementation using SQLite
94
- async acquireRun(threadId, runId) {
95
- const row = this.db.prepare("SELECT is_running FROM run_state WHERE thread_id = ?").get(threadId);
96
- if (row?.is_running === 1) return false;
97
- this.db.prepare(
98
- "INSERT OR REPLACE INTO run_state (thread_id, is_running, current_run_id, updated_at) VALUES (?, ?, ?, ?)"
99
- ).run(threadId, 1, runId, Date.now());
100
- return true;
101
- }
102
- async releaseRun(threadId) {
103
- this.db.prepare("INSERT OR REPLACE INTO run_state (thread_id, is_running, current_run_id, updated_at) VALUES (?, 0, NULL, ?)").run(threadId, Date.now());
104
- }
105
- async isRunningState(threadId) {
106
- const row = this.db.prepare("SELECT is_running FROM run_state WHERE thread_id = ?").get(threadId);
107
- return row?.is_running === 1;
108
- }
109
- async listRuns(threadId) {
110
- const rows = this.db.prepare(
111
- "SELECT run_id, events, created_at FROM agent_runs WHERE thread_id = ? ORDER BY created_at ASC"
112
- ).all(threadId);
113
- return rows.map((r) => ({ runId: r.run_id, events: JSON.parse(r.events), createdAt: r.created_at }));
114
- }
115
- async saveRun(threadId, runId, events, input, parentRunId) {
116
- const stmt = this.db.prepare(
117
- "INSERT INTO agent_runs (thread_id, run_id, parent_run_id, events, input, created_at, version) VALUES (?, ?, ?, ?, ?, ?, ?)"
118
- );
93
+ storeRun(threadId, runId, events, input, parentRunId) {
94
+ const compactedEvents = (0, import_client.compactEvents)(events);
95
+ const stmt = this.db.prepare(`
96
+ INSERT INTO agent_runs (thread_id, run_id, parent_run_id, events, input, created_at, version)
97
+ VALUES (?, ?, ?, ?, ?, ?, ?)
98
+ `);
119
99
  stmt.run(
120
100
  threadId,
121
101
  runId,
122
102
  parentRunId ?? null,
123
- JSON.stringify(events),
103
+ JSON.stringify(compactedEvents),
104
+ // Store only this run's compacted events
124
105
  JSON.stringify(input),
125
106
  Date.now(),
126
107
  SCHEMA_VERSION
127
108
  );
128
109
  }
129
- async pageThreads(params) {
130
- const limit = params.limit ?? 20;
131
- const offset = params.offset ?? 0;
132
- const totalRow = this.db.prepare("SELECT COUNT(DISTINCT thread_id) AS total FROM agent_runs").get();
133
- const rows = this.db.prepare(
134
- "SELECT thread_id, MAX(created_at) AS last FROM agent_runs GROUP BY thread_id ORDER BY last DESC LIMIT ? OFFSET ?"
135
- ).all(limit, offset);
136
- return { threadIds: rows.map((r) => r.thread_id), total: totalRow.total };
137
- }
138
- async deleteThreadStorage(threadId) {
139
- this.db.prepare("DELETE FROM agent_runs WHERE thread_id = ?").run(threadId);
140
- this.db.prepare("DELETE FROM run_state WHERE thread_id = ?").run(threadId);
141
- }
142
- ensureChannel(threadId) {
143
- let s = this.channels.get(threadId);
144
- if (!s || s.closed) {
145
- s = new import_rxjs.ReplaySubject(Infinity);
146
- this.channels.set(threadId, s);
147
- }
148
- return s;
149
- }
150
- publishLive(threadId, event) {
151
- if (event.type === "RUN_STARTED") {
152
- const s = new import_rxjs.ReplaySubject(Infinity);
153
- this.channels.set(threadId, s);
154
- }
155
- this.ensureChannel(threadId).next(event);
110
+ getHistoricRuns(threadId) {
111
+ const stmt = this.db.prepare(`
112
+ WITH RECURSIVE run_chain AS (
113
+ -- Base case: find the root runs (those without parent)
114
+ SELECT * FROM agent_runs
115
+ WHERE thread_id = ? AND parent_run_id IS NULL
116
+
117
+ UNION ALL
118
+
119
+ -- Recursive case: find children of current level
120
+ SELECT ar.* FROM agent_runs ar
121
+ INNER JOIN run_chain rc ON ar.parent_run_id = rc.run_id
122
+ WHERE ar.thread_id = ?
123
+ )
124
+ SELECT * FROM run_chain
125
+ ORDER BY created_at ASC
126
+ `);
127
+ const rows = stmt.all(threadId, threadId);
128
+ return rows.map((row) => ({
129
+ id: row.id,
130
+ thread_id: row.thread_id,
131
+ run_id: row.run_id,
132
+ parent_run_id: row.parent_run_id,
133
+ events: JSON.parse(row.events),
134
+ input: JSON.parse(row.input),
135
+ created_at: row.created_at,
136
+ version: row.version
137
+ }));
156
138
  }
157
- completeLive(threadId) {
158
- const s = this.ensureChannel(threadId);
159
- if (!s.closed) s.complete();
139
+ getLatestRunId(threadId) {
140
+ const stmt = this.db.prepare(`
141
+ SELECT run_id FROM agent_runs
142
+ WHERE thread_id = ?
143
+ ORDER BY created_at DESC
144
+ LIMIT 1
145
+ `);
146
+ const result = stmt.get(threadId);
147
+ return result?.run_id ?? null;
160
148
  }
161
- subscribeLive(threadId) {
162
- return this.ensureChannel(threadId).asObservable();
149
+ setRunState(threadId, isRunning, runId) {
150
+ const stmt = this.db.prepare(`
151
+ INSERT OR REPLACE INTO run_state (thread_id, is_running, current_run_id, updated_at)
152
+ VALUES (?, ?, ?, ?)
153
+ `);
154
+ stmt.run(threadId, isRunning ? 1 : 0, runId ?? null, Date.now());
163
155
  }
164
- async closeLive(threadId) {
165
- const s = this.channels.get(threadId);
166
- if (s && !s.closed) s.complete();
167
- this.channels.delete(threadId);
156
+ getRunState(threadId) {
157
+ const stmt = this.db.prepare(`
158
+ SELECT is_running, current_run_id FROM run_state WHERE thread_id = ?
159
+ `);
160
+ const result = stmt.get(threadId);
161
+ return {
162
+ isRunning: result?.is_running === 1,
163
+ currentRunId: result?.current_run_id ?? null
164
+ };
168
165
  }
169
- // Override connect to preserve original sqlite-runner ordering without re-compacting across runs
170
- connect(request) {
171
- const { threadId } = request;
172
- const subject = new import_rxjs.ReplaySubject(Infinity);
173
- void (async () => {
174
- const runs = await this.listRuns(threadId);
175
- const emittedMessageIds = /* @__PURE__ */ new Set();
176
- for (const r of runs) {
177
- for (const e of r.events) {
178
- subject.next(e);
179
- const id = e.messageId;
180
- if (typeof id === "string") emittedMessageIds.add(id);
166
+ run(request) {
167
+ const runState = this.getRunState(request.threadId);
168
+ if (runState.isRunning) {
169
+ throw new Error("Thread already running");
170
+ }
171
+ this.setRunState(request.threadId, true, request.input.runId);
172
+ const seenMessageIds = /* @__PURE__ */ new Set();
173
+ const currentRunEvents = [];
174
+ const historicRuns = this.getHistoricRuns(request.threadId);
175
+ const historicMessageIds = /* @__PURE__ */ new Set();
176
+ for (const run of historicRuns) {
177
+ for (const event of run.events) {
178
+ if ("messageId" in event && typeof event.messageId === "string") {
179
+ historicMessageIds.add(event.messageId);
180
+ }
181
+ if (event.type === import_client.EventType.RUN_STARTED) {
182
+ const runStarted = event;
183
+ const messages = runStarted.input?.messages ?? [];
184
+ for (const message of messages) {
185
+ historicMessageIds.add(message.id);
186
+ }
181
187
  }
182
188
  }
183
- const running = await this.isRunningState(threadId);
184
- if (!running) {
185
- subject.complete();
186
- return;
187
- }
188
- const live$ = this.subscribeLive(threadId);
189
- let completed = false;
190
- live$.subscribe({
191
- next: (e) => {
192
- const id = e.messageId;
193
- if (typeof id === "string" && emittedMessageIds.has(id)) return;
194
- subject.next(e);
195
- if (e.type === "RUN_FINISHED" || e.type === "RUN_ERROR") {
196
- if (!completed) {
197
- completed = true;
198
- subject.complete();
189
+ }
190
+ const nextSubject = new import_rxjs.ReplaySubject(Infinity);
191
+ const prevConnection = ACTIVE_CONNECTIONS.get(request.threadId);
192
+ const prevSubject = prevConnection?.subject;
193
+ const runSubject = new import_rxjs.ReplaySubject(Infinity);
194
+ ACTIVE_CONNECTIONS.set(request.threadId, {
195
+ subject: nextSubject,
196
+ agent: request.agent,
197
+ runSubject,
198
+ currentEvents: currentRunEvents,
199
+ stopRequested: false
200
+ });
201
+ const runAgent = async () => {
202
+ const parentRunId = this.getLatestRunId(request.threadId);
203
+ try {
204
+ await request.agent.runAgent(request.input, {
205
+ onEvent: ({ event }) => {
206
+ let processedEvent = event;
207
+ if (event.type === import_client.EventType.RUN_STARTED) {
208
+ const runStartedEvent = event;
209
+ if (!runStartedEvent.input) {
210
+ const sanitizedMessages = request.input.messages ? request.input.messages.filter(
211
+ (message) => !historicMessageIds.has(message.id)
212
+ ) : void 0;
213
+ const updatedInput = {
214
+ ...request.input,
215
+ ...sanitizedMessages !== void 0 ? { messages: sanitizedMessages } : {}
216
+ };
217
+ processedEvent = {
218
+ ...runStartedEvent,
219
+ input: updatedInput
220
+ };
221
+ }
222
+ }
223
+ runSubject.next(processedEvent);
224
+ nextSubject.next(processedEvent);
225
+ currentRunEvents.push(processedEvent);
226
+ },
227
+ onNewMessage: ({ message }) => {
228
+ if (!seenMessageIds.has(message.id)) {
229
+ seenMessageIds.add(message.id);
230
+ }
231
+ },
232
+ onRunStartedEvent: () => {
233
+ if (request.input.messages) {
234
+ for (const message of request.input.messages) {
235
+ if (!seenMessageIds.has(message.id)) {
236
+ seenMessageIds.add(message.id);
237
+ }
238
+ }
199
239
  }
200
240
  }
201
- },
202
- error: (err) => subject.error(err),
241
+ });
242
+ const connection = ACTIVE_CONNECTIONS.get(request.threadId);
243
+ const appendedEvents = (0, import_runtime.finalizeRunEvents)(currentRunEvents, {
244
+ stopRequested: connection?.stopRequested ?? false
245
+ });
246
+ for (const event of appendedEvents) {
247
+ runSubject.next(event);
248
+ nextSubject.next(event);
249
+ }
250
+ this.storeRun(
251
+ request.threadId,
252
+ request.input.runId,
253
+ currentRunEvents,
254
+ request.input,
255
+ parentRunId
256
+ );
257
+ this.setRunState(request.threadId, false);
258
+ if (connection) {
259
+ connection.agent = void 0;
260
+ connection.runSubject = void 0;
261
+ connection.currentEvents = void 0;
262
+ connection.stopRequested = false;
263
+ }
264
+ runSubject.complete();
265
+ nextSubject.complete();
266
+ ACTIVE_CONNECTIONS.delete(request.threadId);
267
+ } catch {
268
+ const connection = ACTIVE_CONNECTIONS.get(request.threadId);
269
+ const appendedEvents = (0, import_runtime.finalizeRunEvents)(currentRunEvents, {
270
+ stopRequested: connection?.stopRequested ?? false
271
+ });
272
+ for (const event of appendedEvents) {
273
+ runSubject.next(event);
274
+ nextSubject.next(event);
275
+ }
276
+ if (currentRunEvents.length > 0) {
277
+ this.storeRun(
278
+ request.threadId,
279
+ request.input.runId,
280
+ currentRunEvents,
281
+ request.input,
282
+ parentRunId
283
+ );
284
+ }
285
+ this.setRunState(request.threadId, false);
286
+ if (connection) {
287
+ connection.agent = void 0;
288
+ connection.runSubject = void 0;
289
+ connection.currentEvents = void 0;
290
+ connection.stopRequested = false;
291
+ }
292
+ runSubject.complete();
293
+ nextSubject.complete();
294
+ ACTIVE_CONNECTIONS.delete(request.threadId);
295
+ }
296
+ };
297
+ if (prevSubject) {
298
+ prevSubject.subscribe({
299
+ next: (e) => nextSubject.next(e),
300
+ error: (err) => nextSubject.error(err),
203
301
  complete: () => {
204
- if (!completed) {
205
- completed = true;
206
- subject.complete();
207
- }
208
302
  }
209
303
  });
210
- })();
211
- return subject.asObservable();
304
+ }
305
+ runAgent();
306
+ return runSubject.asObservable();
212
307
  }
308
+ connect(request) {
309
+ const connectionSubject = new import_rxjs.ReplaySubject(Infinity);
310
+ const historicRuns = this.getHistoricRuns(request.threadId);
311
+ const allHistoricEvents = [];
312
+ for (const run of historicRuns) {
313
+ allHistoricEvents.push(...run.events);
314
+ }
315
+ const compactedEvents = (0, import_client.compactEvents)(allHistoricEvents);
316
+ const emittedMessageIds = /* @__PURE__ */ new Set();
317
+ for (const event of compactedEvents) {
318
+ connectionSubject.next(event);
319
+ if ("messageId" in event && typeof event.messageId === "string") {
320
+ emittedMessageIds.add(event.messageId);
321
+ }
322
+ }
323
+ const activeConnection = ACTIVE_CONNECTIONS.get(request.threadId);
324
+ const runState = this.getRunState(request.threadId);
325
+ if (activeConnection && (runState.isRunning || activeConnection.stopRequested)) {
326
+ activeConnection.subject.subscribe({
327
+ next: (event) => {
328
+ if ("messageId" in event && typeof event.messageId === "string" && emittedMessageIds.has(event.messageId)) {
329
+ return;
330
+ }
331
+ connectionSubject.next(event);
332
+ },
333
+ complete: () => connectionSubject.complete(),
334
+ error: (err) => connectionSubject.error(err)
335
+ });
336
+ } else {
337
+ connectionSubject.complete();
338
+ }
339
+ return connectionSubject.asObservable();
340
+ }
341
+ isRunning(request) {
342
+ const runState = this.getRunState(request.threadId);
343
+ return Promise.resolve(runState.isRunning);
344
+ }
345
+ stop(request) {
346
+ const runState = this.getRunState(request.threadId);
347
+ if (!runState.isRunning) {
348
+ return Promise.resolve(false);
349
+ }
350
+ const connection = ACTIVE_CONNECTIONS.get(request.threadId);
351
+ const agent = connection?.agent;
352
+ if (!connection || !agent) {
353
+ return Promise.resolve(false);
354
+ }
355
+ if (connection.stopRequested) {
356
+ return Promise.resolve(false);
357
+ }
358
+ connection.stopRequested = true;
359
+ this.setRunState(request.threadId, false);
360
+ try {
361
+ agent.abortRun();
362
+ return Promise.resolve(true);
363
+ } catch (error) {
364
+ console.error("Failed to abort sqlite agent run", error);
365
+ connection.stopRequested = false;
366
+ this.setRunState(request.threadId, true);
367
+ return Promise.resolve(false);
368
+ }
369
+ }
370
+ /**
371
+ * Close the database connection (for cleanup)
372
+ */
213
373
  close() {
214
- if (this.db) this.db.close();
374
+ if (this.db) {
375
+ this.db.close();
376
+ }
215
377
  }
216
378
  };
217
379
  // Annotate the CommonJS export names for ESM import in node: