@cogitator-ai/bridge 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +330 -2
  3. package/dist/adapter.d.ts +123 -0
  4. package/dist/adapter.d.ts.map +1 -0
  5. package/dist/adapter.js +2 -0
  6. package/dist/adapter.js.map +1 -0
  7. package/dist/adapters/claude.d.ts +90 -0
  8. package/dist/adapters/claude.d.ts.map +1 -0
  9. package/dist/adapters/claude.js +359 -0
  10. package/dist/adapters/claude.js.map +1 -0
  11. package/dist/adapters/codex.d.ts +58 -0
  12. package/dist/adapters/codex.d.ts.map +1 -0
  13. package/dist/adapters/codex.js +330 -0
  14. package/dist/adapters/codex.js.map +1 -0
  15. package/dist/adapters/exec.d.ts +57 -0
  16. package/dist/adapters/exec.d.ts.map +1 -0
  17. package/dist/adapters/exec.js +149 -0
  18. package/dist/adapters/exec.js.map +1 -0
  19. package/dist/adapters/hosted.d.ts +168 -0
  20. package/dist/adapters/hosted.d.ts.map +1 -0
  21. package/dist/adapters/hosted.js +361 -0
  22. package/dist/adapters/hosted.js.map +1 -0
  23. package/dist/client.d.ts +81 -0
  24. package/dist/client.d.ts.map +1 -0
  25. package/dist/client.js +216 -0
  26. package/dist/client.js.map +1 -0
  27. package/dist/dispatcher.d.ts +296 -0
  28. package/dist/dispatcher.d.ts.map +1 -0
  29. package/dist/dispatcher.js +1524 -0
  30. package/dist/dispatcher.js.map +1 -0
  31. package/dist/errors.d.ts +10 -0
  32. package/dist/errors.d.ts.map +1 -0
  33. package/dist/errors.js +16 -0
  34. package/dist/errors.js.map +1 -0
  35. package/dist/guards.d.ts +36 -0
  36. package/dist/guards.d.ts.map +1 -0
  37. package/dist/guards.js +85 -0
  38. package/dist/guards.js.map +1 -0
  39. package/dist/host.d.ts +49 -0
  40. package/dist/host.d.ts.map +1 -0
  41. package/dist/host.js +150 -0
  42. package/dist/host.js.map +1 -0
  43. package/dist/index.d.ts +50 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +32 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/inputs.d.ts +184 -0
  48. package/dist/inputs.d.ts.map +1 -0
  49. package/dist/inputs.js +116 -0
  50. package/dist/inputs.js.map +1 -0
  51. package/dist/job-record.d.ts +47 -0
  52. package/dist/job-record.d.ts.map +1 -0
  53. package/dist/job-record.js +65 -0
  54. package/dist/job-record.js.map +1 -0
  55. package/dist/letters.d.ts +49 -0
  56. package/dist/letters.d.ts.map +1 -0
  57. package/dist/letters.js +96 -0
  58. package/dist/letters.js.map +1 -0
  59. package/dist/paths.d.ts +38 -0
  60. package/dist/paths.d.ts.map +1 -0
  61. package/dist/paths.js +149 -0
  62. package/dist/paths.js.map +1 -0
  63. package/dist/protocol.d.ts +83 -0
  64. package/dist/protocol.d.ts.map +1 -0
  65. package/dist/protocol.js +71 -0
  66. package/dist/protocol.js.map +1 -0
  67. package/dist/registry.d.ts +62 -0
  68. package/dist/registry.d.ts.map +1 -0
  69. package/dist/registry.js +185 -0
  70. package/dist/registry.js.map +1 -0
  71. package/dist/server.d.ts +31 -0
  72. package/dist/server.d.ts.map +1 -0
  73. package/dist/server.js +254 -0
  74. package/dist/server.js.map +1 -0
  75. package/dist/store/sqlite.d.ts +56 -0
  76. package/dist/store/sqlite.d.ts.map +1 -0
  77. package/dist/store/sqlite.js +737 -0
  78. package/dist/store/sqlite.js.map +1 -0
  79. package/dist/store/store.d.ts +128 -0
  80. package/dist/store/store.d.ts.map +1 -0
  81. package/dist/store/store.js +2 -0
  82. package/dist/store/store.js.map +1 -0
  83. package/dist/testing/conformance.d.ts +65 -0
  84. package/dist/testing/conformance.d.ts.map +1 -0
  85. package/dist/testing/conformance.js +217 -0
  86. package/dist/testing/conformance.js.map +1 -0
  87. package/dist/testing/fake-harnesses.d.ts +101 -0
  88. package/dist/testing/fake-harnesses.d.ts.map +1 -0
  89. package/dist/testing/fake-harnesses.js +291 -0
  90. package/dist/testing/fake-harnesses.js.map +1 -0
  91. package/dist/testing/index.d.ts +5 -0
  92. package/dist/testing/index.d.ts.map +1 -0
  93. package/dist/testing/index.js +3 -0
  94. package/dist/testing/index.js.map +1 -0
  95. package/dist/types.d.ts +286 -0
  96. package/dist/types.d.ts.map +1 -0
  97. package/dist/types.js +132 -0
  98. package/dist/types.js.map +1 -0
  99. package/dist/waiter.d.ts +36 -0
  100. package/dist/waiter.d.ts.map +1 -0
  101. package/dist/waiter.js +92 -0
  102. package/dist/waiter.js.map +1 -0
  103. package/fakes/claude.mjs +450 -0
  104. package/fakes/codex.mjs +391 -0
  105. package/fakes/lib.mjs +507 -0
  106. package/package.json +76 -3
@@ -0,0 +1,737 @@
1
+ import { chmodSync, closeSync, constants, lstatSync, mkdirSync, openSync, statSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { TASK_AGENT_KEY, compareTasksNewestFirst, isTaskVisibleTo, taskCreatedAt, taskTime, } from '@cogitator-ai/a2a';
4
+ import { BridgeError } from '../errors.js';
5
+ import { jobRecordOf } from '../job-record.js';
6
+ import { AdapterCapabilitiesSchema, BRIDGE_JOB_KEY, } from '../types.js';
7
+ /** The version of the schema this code reads and writes, kept in `PRAGMA user_version`. */
8
+ export const BRIDGE_SCHEMA_VERSION = 1;
9
+ const MEMORY_PATH = ':memory:';
10
+ const LEASE_KEY = 'lease';
11
+ const SCHEMA = `
12
+ CREATE TABLE meta (
13
+ key TEXT PRIMARY KEY,
14
+ value TEXT NOT NULL
15
+ );
16
+
17
+ CREATE TABLE tasks (
18
+ id TEXT PRIMARY KEY,
19
+ context_id TEXT NOT NULL,
20
+ state TEXT NOT NULL,
21
+ created_at INTEGER NOT NULL,
22
+ updated_at INTEGER NOT NULL,
23
+ job_number INTEGER UNIQUE,
24
+ job_from TEXT,
25
+ job_to TEXT,
26
+ job_project TEXT,
27
+ job_deadline_at INTEGER,
28
+ job_parent INTEGER,
29
+ job_created_at INTEGER,
30
+ data TEXT NOT NULL
31
+ );
32
+ CREATE INDEX tasks_context ON tasks (context_id);
33
+ CREATE INDEX tasks_updated ON tasks (updated_at DESC, id DESC);
34
+ CREATE INDEX tasks_job_state ON tasks (state, job_deadline_at) WHERE job_number IS NOT NULL;
35
+ CREATE INDEX tasks_job_to ON tasks (job_to, state) WHERE job_number IS NOT NULL;
36
+ CREATE INDEX tasks_job_from ON tasks (job_from, job_created_at) WHERE job_number IS NOT NULL;
37
+ CREATE INDEX tasks_job_parent ON tasks (job_parent) WHERE job_parent IS NOT NULL;
38
+
39
+ CREATE TABLE job_numbers (
40
+ number INTEGER PRIMARY KEY AUTOINCREMENT
41
+ );
42
+
43
+ CREATE TABLE agents (
44
+ name TEXT PRIMARY KEY,
45
+ harness TEXT NOT NULL,
46
+ session_id TEXT NOT NULL,
47
+ session_name TEXT,
48
+ project TEXT NOT NULL,
49
+ cwd TEXT NOT NULL,
50
+ delivery TEXT NOT NULL,
51
+ capabilities TEXT NOT NULL,
52
+ status TEXT NOT NULL,
53
+ registered_at INTEGER NOT NULL,
54
+ last_seen_at INTEGER NOT NULL
55
+ );
56
+ CREATE UNIQUE INDEX agents_session ON agents (harness, session_id) WHERE session_id <> '';
57
+ CREATE INDEX agents_project ON agents (project, harness);
58
+ CREATE INDEX agents_seen ON agents (status, last_seen_at);
59
+
60
+ CREATE TABLE letters (
61
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
62
+ id TEXT NOT NULL UNIQUE,
63
+ job INTEGER NOT NULL,
64
+ kind TEXT NOT NULL,
65
+ sender TEXT NOT NULL,
66
+ recipient TEXT NOT NULL,
67
+ body TEXT NOT NULL,
68
+ in_reply_to TEXT,
69
+ outcome TEXT,
70
+ state TEXT NOT NULL,
71
+ created_at INTEGER NOT NULL,
72
+ delivered_at INTEGER,
73
+ read_at INTEGER,
74
+ handled_at INTEGER,
75
+ attempts INTEGER NOT NULL DEFAULT 0,
76
+ last_error TEXT,
77
+ next_attempt_at INTEGER,
78
+ reply_due_at INTEGER,
79
+ reminded_at INTEGER
80
+ );
81
+ CREATE INDEX letters_recipient ON letters (recipient, state, seq);
82
+ CREATE INDEX letters_job ON letters (job, seq);
83
+ CREATE INDEX letters_due ON letters (reply_due_at) WHERE reply_due_at IS NOT NULL;
84
+
85
+ CREATE TABLE journal (
86
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
87
+ at INTEGER NOT NULL,
88
+ type TEXT NOT NULL,
89
+ job INTEGER,
90
+ letter TEXT,
91
+ agent TEXT,
92
+ data TEXT
93
+ );
94
+ CREATE INDEX journal_job ON journal (job, seq);
95
+ CREATE TRIGGER journal_no_update BEFORE UPDATE ON journal
96
+ BEGIN
97
+ SELECT RAISE(ABORT, 'the bridge journal is append-only');
98
+ END;
99
+ CREATE TRIGGER journal_no_delete BEFORE DELETE ON journal
100
+ BEGIN
101
+ SELECT RAISE(ABORT, 'the bridge journal is append-only');
102
+ END;
103
+ `;
104
+ function iso(ms) {
105
+ return new Date(ms).toISOString();
106
+ }
107
+ function ms(time) {
108
+ const value = Date.parse(time);
109
+ if (Number.isNaN(value))
110
+ throw new BridgeError('storage', `Not a time: ${time}`);
111
+ return value;
112
+ }
113
+ function optionalMs(time) {
114
+ return time === undefined ? null : ms(time);
115
+ }
116
+ function processIsAlive(pid) {
117
+ try {
118
+ process.kill(pid, 0);
119
+ return true;
120
+ }
121
+ catch (error) {
122
+ return error.code === 'EPERM';
123
+ }
124
+ }
125
+ function toAgent(row) {
126
+ return {
127
+ name: row.name,
128
+ harness: row.harness,
129
+ sessionId: row.session_id,
130
+ ...(row.session_name !== null && { sessionName: row.session_name }),
131
+ project: row.project,
132
+ cwd: row.cwd,
133
+ delivery: row.delivery,
134
+ capabilities: AdapterCapabilitiesSchema.parse(JSON.parse(row.capabilities)),
135
+ status: row.status,
136
+ registeredAt: iso(row.registered_at),
137
+ lastSeenAt: iso(row.last_seen_at),
138
+ };
139
+ }
140
+ function toLetter(row) {
141
+ return {
142
+ id: row.id,
143
+ seq: row.seq,
144
+ job: row.job,
145
+ kind: row.kind,
146
+ from: row.sender,
147
+ to: row.recipient,
148
+ body: row.body,
149
+ ...(row.in_reply_to !== null && { inReplyTo: row.in_reply_to }),
150
+ ...(row.outcome !== null && { outcome: row.outcome }),
151
+ state: row.state,
152
+ createdAt: iso(row.created_at),
153
+ ...(row.delivered_at !== null && { deliveredAt: iso(row.delivered_at) }),
154
+ ...(row.read_at !== null && { readAt: iso(row.read_at) }),
155
+ ...(row.handled_at !== null && { handledAt: iso(row.handled_at) }),
156
+ attempts: row.attempts,
157
+ ...(row.last_error !== null && { lastError: row.last_error }),
158
+ ...(row.next_attempt_at !== null && { nextAttemptAt: iso(row.next_attempt_at) }),
159
+ ...(row.reply_due_at !== null && { replyDueAt: iso(row.reply_due_at) }),
160
+ ...(row.reminded_at !== null && { remindedAt: iso(row.reminded_at) }),
161
+ };
162
+ }
163
+ function toJournalEntry(row) {
164
+ return {
165
+ seq: row.seq,
166
+ at: iso(row.at),
167
+ type: row.type,
168
+ ...(row.job !== null && { job: row.job }),
169
+ ...(row.letter !== null && { letter: row.letter }),
170
+ ...(row.agent !== null && { agent: row.agent }),
171
+ ...(row.data !== null && { data: JSON.parse(row.data) }),
172
+ };
173
+ }
174
+ /**
175
+ * Makes sure the folder and the database are this user's and nobody else's before anything is
176
+ * written to them: the database is created with mode 0600 from the start (SQLite gives its
177
+ * `-wal` and `-shm` files the same mode), a file that is already there is narrowed, and a folder
178
+ * or a file that belongs to someone else is refused. A filesystem without owners and modes
179
+ * (Windows) keeps the protection of the user's profile, and root, who owns everything anyway, is
180
+ * not asked whose the files are (a container often runs as root on a volume of the host's user).
181
+ *
182
+ * @throws BridgeError `storage` when the folder or the file belongs to another user, or the
183
+ * file is not a plain file
184
+ */
185
+ function makePrivate(path) {
186
+ const folder = dirname(path);
187
+ if (process.platform === 'win32') {
188
+ mkdirSync(folder, { recursive: true });
189
+ return;
190
+ }
191
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
192
+ const self = process.getuid?.();
193
+ const uid = self === 0 ? undefined : self;
194
+ if (uid !== undefined && statSync(folder).uid !== uid) {
195
+ throw new BridgeError('storage', `The bridge folder ${folder} belongs to another user. Point COGITATOR_BRIDGE_HOME at a folder of your own`);
196
+ }
197
+ try {
198
+ closeSync(openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR, 0o600));
199
+ return;
200
+ }
201
+ catch (error) {
202
+ if (error.code !== 'EEXIST')
203
+ throw error;
204
+ }
205
+ const file = lstatSync(path);
206
+ if (!file.isFile() || (uid !== undefined && file.uid !== uid)) {
207
+ throw new BridgeError('storage', `The bridge database ${path} is not a plain file of this user. Remove it or point COGITATOR_BRIDGE_HOME elsewhere`);
208
+ }
209
+ for (const each of [path, `${path}-wal`, `${path}-shm`]) {
210
+ try {
211
+ chmodSync(each, 0o600);
212
+ }
213
+ catch (error) {
214
+ if (each === path || error.code !== 'ENOENT')
215
+ throw error;
216
+ }
217
+ }
218
+ }
219
+ function placeholders(count) {
220
+ return Array.from({ length: count }, () => '?').join(', ');
221
+ }
222
+ class SqliteTaskStore {
223
+ db;
224
+ constructor(db) {
225
+ this.db = db;
226
+ }
227
+ async create(task) {
228
+ this.write(task, 'INSERT');
229
+ }
230
+ async get(taskId) {
231
+ return this.read(taskId) ?? null;
232
+ }
233
+ async update(taskId, update) {
234
+ this.db.transaction(() => {
235
+ const existing = this.read(taskId);
236
+ if (!existing)
237
+ return;
238
+ this.write({ ...existing, ...update }, 'REPLACE');
239
+ })();
240
+ }
241
+ async list(filter) {
242
+ const where = [];
243
+ const binds = [];
244
+ if (filter?.contextId) {
245
+ where.push('context_id = ?');
246
+ binds.push(filter.contextId);
247
+ }
248
+ if (filter?.state) {
249
+ where.push('state = ?');
250
+ binds.push(filter.state);
251
+ }
252
+ const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
253
+ const rows = this.db.prepare(`SELECT data FROM tasks ${clause}`).all(...binds);
254
+ let tasks = rows.map((row) => JSON.parse(row.data));
255
+ if (filter?.visibleTo !== undefined) {
256
+ const userId = filter.visibleTo;
257
+ tasks = tasks.filter((task) => isTaskVisibleTo(task, userId));
258
+ }
259
+ tasks.sort(compareTasksNewestFirst);
260
+ const offset = filter?.offset ?? 0;
261
+ return tasks.slice(offset, offset + (filter?.limit ?? tasks.length));
262
+ }
263
+ async delete(taskId) {
264
+ this.db.prepare('DELETE FROM tasks WHERE id = ?').run(taskId);
265
+ }
266
+ read(taskId) {
267
+ const row = this.db
268
+ .prepare('SELECT data FROM tasks WHERE id = ?')
269
+ .get(taskId);
270
+ return row ? JSON.parse(row.data) : undefined;
271
+ }
272
+ write(task, verb) {
273
+ const job = jobRecordOf(task);
274
+ this.db
275
+ .prepare(`${verb} INTO tasks
276
+ (id, context_id, state, created_at, updated_at, job_number, job_from, job_to, job_project, job_deadline_at, job_parent, job_created_at, data)
277
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
278
+ .run(task.id, task.contextId, task.status.state, taskCreatedAt(task), taskTime(task), job?.number ?? null, job?.from ?? null, job?.to ?? null, job?.project ?? null, job ? ms(job.deadlineAt) : null, job?.parent ?? null, job ? ms(job.createdAt) : null, JSON.stringify(task));
279
+ }
280
+ }
281
+ /**
282
+ * The bridge's store in one SQLite file. Reads and writes are synchronous underneath, and a
283
+ * transaction spans the awaits of the work it wraps, which holds as long as one piece of work
284
+ * runs at a time, as the dispatcher's queue makes sure.
285
+ */
286
+ export class SqliteBridgeStore {
287
+ db;
288
+ readonly;
289
+ tasks;
290
+ taskRows;
291
+ open = true;
292
+ inTransaction = false;
293
+ constructor(db, readonly) {
294
+ this.db = db;
295
+ this.readonly = readonly;
296
+ this.taskRows = new SqliteTaskStore(db);
297
+ this.tasks = this.taskRows;
298
+ }
299
+ /**
300
+ * Opens the store at `path` (`:memory:` for one that lives with the process), creating the
301
+ * file and its folder when they are missing.
302
+ *
303
+ * @throws BridgeError `storage` when `better-sqlite3` is not installed, the file cannot be
304
+ * opened, or it was written by a newer version of the bridge
305
+ */
306
+ static async open(path, options = {}) {
307
+ let Database;
308
+ try {
309
+ Database = (await import('better-sqlite3')).default;
310
+ }
311
+ catch {
312
+ throw new BridgeError('storage', 'The bridge keeps its state in SQLite and needs the "better-sqlite3" package. Install it: pnpm add better-sqlite3');
313
+ }
314
+ const readonly = options.readonly ?? false;
315
+ const inMemory = path === MEMORY_PATH;
316
+ let db;
317
+ try {
318
+ if (!readonly && !inMemory)
319
+ makePrivate(path);
320
+ db = readonly ? new Database(path, { fileMustExist: true }) : new Database(path);
321
+ }
322
+ catch (error) {
323
+ if (error instanceof BridgeError)
324
+ throw error;
325
+ throw new BridgeError('storage', `Cannot open the bridge database ${path}: ${error instanceof Error ? error.message : String(error)}`);
326
+ }
327
+ try {
328
+ db.pragma('busy_timeout = 5000');
329
+ if (readonly) {
330
+ db.pragma('query_only = ON');
331
+ }
332
+ else {
333
+ if (!inMemory) {
334
+ db.pragma('journal_mode = WAL');
335
+ db.pragma('synchronous = NORMAL');
336
+ }
337
+ }
338
+ SqliteBridgeStore.migrate(db, path, readonly);
339
+ }
340
+ catch (error) {
341
+ db.close();
342
+ throw error;
343
+ }
344
+ return new SqliteBridgeStore(db, readonly);
345
+ }
346
+ static migrate(db, path, readonly) {
347
+ const check = () => {
348
+ const version = db.pragma('user_version', { simple: true });
349
+ if (version > BRIDGE_SCHEMA_VERSION) {
350
+ throw new BridgeError('storage', `The bridge database ${path} was written by a newer version (schema ${version}, this one reads ${BRIDGE_SCHEMA_VERSION}). Update @cogitator-ai/bridge`);
351
+ }
352
+ return version === BRIDGE_SCHEMA_VERSION;
353
+ };
354
+ if (check())
355
+ return;
356
+ if (readonly) {
357
+ throw new BridgeError('storage', `The bridge database ${path} is empty: no dispatcher ran yet`);
358
+ }
359
+ db.transaction(() => {
360
+ if (check())
361
+ return;
362
+ db.exec(SCHEMA);
363
+ db.pragma(`user_version = ${BRIDGE_SCHEMA_VERSION}`);
364
+ }).immediate();
365
+ }
366
+ async transaction(work) {
367
+ if (this.inTransaction) {
368
+ throw new BridgeError('storage', 'A bridge transaction is already running');
369
+ }
370
+ this.db.exec('BEGIN IMMEDIATE');
371
+ this.inTransaction = true;
372
+ try {
373
+ const result = await work();
374
+ this.db.exec('COMMIT');
375
+ return result;
376
+ }
377
+ catch (error) {
378
+ if (this.open && this.db.inTransaction)
379
+ this.db.exec('ROLLBACK');
380
+ throw error;
381
+ }
382
+ finally {
383
+ this.inTransaction = false;
384
+ }
385
+ }
386
+ acquireLease(candidate, options) {
387
+ const isAlive = options.isAlive ?? processIsAlive;
388
+ return this.db
389
+ .transaction(() => {
390
+ const holder = this.readLease();
391
+ if (holder &&
392
+ holder.nonce !== candidate.nonce &&
393
+ isAlive(holder.pid) &&
394
+ options.now - holder.heartbeatAt <= options.ttlMs) {
395
+ return { acquired: false, holder };
396
+ }
397
+ const lease = { ...candidate, acquiredAt: options.now, heartbeatAt: options.now };
398
+ this.db
399
+ .prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value')
400
+ .run(LEASE_KEY, JSON.stringify(lease));
401
+ return { acquired: true, lease };
402
+ })
403
+ .immediate();
404
+ }
405
+ renewLease(nonce, now) {
406
+ return this.db
407
+ .transaction(() => {
408
+ const holder = this.readLease();
409
+ if (holder?.nonce !== nonce)
410
+ return false;
411
+ this.db
412
+ .prepare('UPDATE meta SET value = ? WHERE key = ?')
413
+ .run(JSON.stringify({ ...holder, heartbeatAt: now }), LEASE_KEY);
414
+ return true;
415
+ })
416
+ .immediate();
417
+ }
418
+ releaseLease(nonce) {
419
+ this.db
420
+ .transaction(() => {
421
+ if (this.readLease()?.nonce === nonce) {
422
+ this.db.prepare('DELETE FROM meta WHERE key = ?').run(LEASE_KEY);
423
+ }
424
+ })
425
+ .immediate();
426
+ }
427
+ readLease() {
428
+ const row = this.db
429
+ .prepare('SELECT value FROM meta WHERE key = ?')
430
+ .get(LEASE_KEY);
431
+ return row ? JSON.parse(row.value) : undefined;
432
+ }
433
+ nextJobNumber() {
434
+ const result = this.db.prepare('INSERT INTO job_numbers DEFAULT VALUES').run();
435
+ return Number(result.lastInsertRowid);
436
+ }
437
+ taskOfJob(number) {
438
+ const row = this.db
439
+ .prepare('SELECT data FROM tasks WHERE job_number = ?')
440
+ .get(number);
441
+ return row ? JSON.parse(row.data) : undefined;
442
+ }
443
+ jobTasks(filter = {}) {
444
+ const where = ['job_number IS NOT NULL'];
445
+ const binds = [];
446
+ if (filter.states) {
447
+ if (filter.states.length === 0)
448
+ return [];
449
+ where.push(`state IN (${placeholders(filter.states.length)})`);
450
+ binds.push(...filter.states);
451
+ }
452
+ if (filter.from !== undefined) {
453
+ where.push('job_from = ?');
454
+ binds.push(filter.from);
455
+ }
456
+ if (filter.to !== undefined) {
457
+ where.push('job_to = ?');
458
+ binds.push(filter.to);
459
+ }
460
+ if (filter.party !== undefined) {
461
+ where.push('(job_from = ? OR job_to = ?)');
462
+ binds.push(filter.party, filter.party);
463
+ }
464
+ if (filter.project !== undefined) {
465
+ where.push('job_project = ?');
466
+ binds.push(filter.project);
467
+ }
468
+ if (filter.deadlineBy !== undefined) {
469
+ where.push('job_deadline_at <= ?');
470
+ binds.push(filter.deadlineBy);
471
+ }
472
+ if (filter.parent !== undefined) {
473
+ where.push('job_parent = ?');
474
+ binds.push(filter.parent);
475
+ }
476
+ if (filter.createdSince !== undefined) {
477
+ where.push('job_created_at >= ?');
478
+ binds.push(filter.createdSince);
479
+ }
480
+ const limit = filter.limit !== undefined ? 'LIMIT ?' : '';
481
+ if (filter.limit !== undefined)
482
+ binds.push(filter.limit);
483
+ return this.db
484
+ .prepare(`SELECT data FROM tasks WHERE ${where.join(' AND ')} ORDER BY job_number DESC ${limit}`)
485
+ .all(...binds)
486
+ .map((row) => JSON.parse(row.data));
487
+ }
488
+ putAgent(agent) {
489
+ this.db
490
+ .prepare(`INSERT INTO agents
491
+ (name, harness, session_id, session_name, project, cwd, delivery, capabilities, status, registered_at, last_seen_at)
492
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
493
+ ON CONFLICT (name) DO UPDATE SET
494
+ harness = excluded.harness,
495
+ session_id = excluded.session_id,
496
+ session_name = excluded.session_name,
497
+ project = excluded.project,
498
+ cwd = excluded.cwd,
499
+ delivery = excluded.delivery,
500
+ capabilities = excluded.capabilities,
501
+ status = excluded.status,
502
+ registered_at = excluded.registered_at,
503
+ last_seen_at = excluded.last_seen_at`)
504
+ .run(agent.name, agent.harness, agent.sessionId, agent.sessionName ?? null, agent.project, agent.cwd, agent.delivery, JSON.stringify(agent.capabilities), agent.status, ms(agent.registeredAt), ms(agent.lastSeenAt));
505
+ }
506
+ getAgent(name) {
507
+ const row = this.db
508
+ .prepare('SELECT * FROM agents WHERE name = ?')
509
+ .get(name);
510
+ return row ? toAgent(row) : undefined;
511
+ }
512
+ agentOfSession(harness, sessionId) {
513
+ if (sessionId === '')
514
+ return undefined;
515
+ const row = this.db
516
+ .prepare('SELECT * FROM agents WHERE harness = ? AND session_id = ?')
517
+ .get(harness, sessionId);
518
+ return row ? toAgent(row) : undefined;
519
+ }
520
+ listAgents(filter = {}) {
521
+ const where = [];
522
+ const binds = [];
523
+ if (filter.project !== undefined) {
524
+ where.push('project = ?');
525
+ binds.push(filter.project);
526
+ }
527
+ if (filter.harness !== undefined) {
528
+ where.push('harness = ?');
529
+ binds.push(filter.harness);
530
+ }
531
+ if (filter.statuses) {
532
+ if (filter.statuses.length === 0)
533
+ return [];
534
+ where.push(`status IN (${placeholders(filter.statuses.length)})`);
535
+ binds.push(...filter.statuses);
536
+ }
537
+ if (filter.seenBefore !== undefined) {
538
+ where.push('last_seen_at < ?');
539
+ binds.push(filter.seenBefore);
540
+ }
541
+ const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
542
+ return this.db
543
+ .prepare(`SELECT * FROM agents ${clause} ORDER BY registered_at, name`)
544
+ .all(...binds)
545
+ .map(toAgent);
546
+ }
547
+ mergeAgent(from, to) {
548
+ if (from === to)
549
+ return;
550
+ this.db.transaction(() => {
551
+ this.db.prepare('UPDATE letters SET sender = ? WHERE sender = ?').run(to, from);
552
+ this.db.prepare('UPDATE letters SET recipient = ? WHERE recipient = ?').run(to, from);
553
+ const rows = this.db
554
+ .prepare('SELECT data FROM tasks WHERE job_from = ? OR job_to = ?')
555
+ .all(from, from);
556
+ for (const row of rows) {
557
+ const task = JSON.parse(row.data);
558
+ const record = jobRecordOf(task);
559
+ if (!record)
560
+ continue;
561
+ this.taskRows.write({
562
+ ...task,
563
+ metadata: {
564
+ ...task.metadata,
565
+ ...(task.metadata?.[TASK_AGENT_KEY] === from && { [TASK_AGENT_KEY]: to }),
566
+ [BRIDGE_JOB_KEY]: {
567
+ ...record,
568
+ from: record.from === from ? to : record.from,
569
+ to: record.to === from ? to : record.to,
570
+ },
571
+ },
572
+ }, 'REPLACE');
573
+ }
574
+ this.db.prepare('DELETE FROM agents WHERE name = ?').run(from);
575
+ })();
576
+ }
577
+ insertLetter(letter) {
578
+ const result = this.db
579
+ .prepare(`INSERT INTO letters
580
+ (id, job, kind, sender, recipient, body, in_reply_to, outcome, state, created_at,
581
+ delivered_at, read_at, handled_at, attempts, last_error, next_attempt_at, reply_due_at, reminded_at)
582
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
583
+ .run(letter.id, letter.job, letter.kind, letter.from, letter.to, letter.body, letter.inReplyTo ?? null, letter.outcome ?? null, letter.state, ms(letter.createdAt), optionalMs(letter.deliveredAt), optionalMs(letter.readAt), optionalMs(letter.handledAt), letter.attempts, letter.lastError ?? null, optionalMs(letter.nextAttemptAt), optionalMs(letter.replyDueAt), optionalMs(letter.remindedAt));
584
+ return { ...letter, seq: Number(result.lastInsertRowid) };
585
+ }
586
+ getLetter(id) {
587
+ const row = this.db.prepare('SELECT * FROM letters WHERE id = ?').get(id);
588
+ return row ? toLetter(row) : undefined;
589
+ }
590
+ updateLetter(id, patch) {
591
+ const sets = [];
592
+ const binds = [];
593
+ const set = (column, value) => {
594
+ sets.push(`${column} = ?`);
595
+ binds.push(value);
596
+ };
597
+ if (patch.state !== undefined)
598
+ set('state', patch.state);
599
+ if (patch.deliveredAt !== undefined)
600
+ set('delivered_at', ms(patch.deliveredAt));
601
+ if (patch.readAt !== undefined)
602
+ set('read_at', ms(patch.readAt));
603
+ if (patch.handledAt !== undefined)
604
+ set('handled_at', ms(patch.handledAt));
605
+ if (patch.attempts !== undefined)
606
+ set('attempts', patch.attempts);
607
+ if (patch.lastError !== undefined)
608
+ set('last_error', patch.lastError);
609
+ if (patch.nextAttemptAt !== undefined)
610
+ set('next_attempt_at', ms(patch.nextAttemptAt));
611
+ if (patch.replyDueAt !== undefined)
612
+ set('reply_due_at', ms(patch.replyDueAt));
613
+ if (patch.remindedAt !== undefined)
614
+ set('reminded_at', ms(patch.remindedAt));
615
+ const clearable = {
616
+ lastError: 'last_error',
617
+ nextAttemptAt: 'next_attempt_at',
618
+ replyDueAt: 'reply_due_at',
619
+ };
620
+ for (const field of patch.clear ?? [])
621
+ set(clearable[field], null);
622
+ if (sets.length > 0) {
623
+ this.db.prepare(`UPDATE letters SET ${sets.join(', ')} WHERE id = ?`).run(...binds, id);
624
+ }
625
+ const letter = this.getLetter(id);
626
+ if (!letter)
627
+ throw new BridgeError('unknown_letter', `There is no letter ${id}`, { letter: id });
628
+ return letter;
629
+ }
630
+ listLetters(filter = {}) {
631
+ const query = this.letterQuery(filter);
632
+ if (!query)
633
+ return [];
634
+ const order = filter.newestFirst ? 'DESC' : 'ASC';
635
+ const limit = filter.limit !== undefined ? 'LIMIT ?' : '';
636
+ const binds = filter.limit !== undefined ? [...query.binds, filter.limit] : query.binds;
637
+ return this.db
638
+ .prepare(`SELECT * FROM letters ${query.clause} ORDER BY seq ${order} ${limit}`)
639
+ .all(...binds)
640
+ .map(toLetter);
641
+ }
642
+ countLetters(filter = {}) {
643
+ const query = this.letterQuery(filter);
644
+ if (!query)
645
+ return 0;
646
+ const row = this.db
647
+ .prepare(`SELECT COUNT(*) AS total FROM letters ${query.clause}`)
648
+ .get(...query.binds);
649
+ return row?.total ?? 0;
650
+ }
651
+ queuedRecipients() {
652
+ return this.db
653
+ .prepare("SELECT DISTINCT recipient FROM letters WHERE state = 'queued' ORDER BY recipient")
654
+ .all()
655
+ .map((row) => row.recipient);
656
+ }
657
+ letterQuery(filter) {
658
+ const where = [];
659
+ const binds = [];
660
+ if (filter.job !== undefined) {
661
+ where.push('job = ?');
662
+ binds.push(filter.job);
663
+ }
664
+ if (filter.from !== undefined) {
665
+ where.push('sender = ?');
666
+ binds.push(filter.from);
667
+ }
668
+ if (filter.to !== undefined) {
669
+ where.push('recipient = ?');
670
+ binds.push(filter.to);
671
+ }
672
+ if (filter.states) {
673
+ if (filter.states.length === 0)
674
+ return undefined;
675
+ where.push(`state IN (${placeholders(filter.states.length)})`);
676
+ binds.push(...filter.states);
677
+ }
678
+ if (filter.kinds) {
679
+ if (filter.kinds.length === 0)
680
+ return undefined;
681
+ where.push(`kind IN (${placeholders(filter.kinds.length)})`);
682
+ binds.push(...filter.kinds);
683
+ }
684
+ if (filter.afterSeq !== undefined) {
685
+ where.push('seq > ?');
686
+ binds.push(filter.afterSeq);
687
+ }
688
+ if (filter.attemptsBelow !== undefined) {
689
+ where.push('attempts < ?');
690
+ binds.push(filter.attemptsBelow);
691
+ }
692
+ if (filter.replyDueBy !== undefined) {
693
+ where.push('reply_due_at IS NOT NULL AND reply_due_at <= ?');
694
+ binds.push(filter.replyDueBy);
695
+ }
696
+ return { clause: where.length > 0 ? `WHERE ${where.join(' AND ')}` : '', binds };
697
+ }
698
+ appendJournal(entry) {
699
+ const result = this.db
700
+ .prepare('INSERT INTO journal (at, type, job, letter, agent, data) VALUES (?, ?, ?, ?, ?, ?)')
701
+ .run(ms(entry.at), entry.type, entry.job ?? null, entry.letter ?? null, entry.agent ?? null, entry.data === undefined ? null : JSON.stringify(entry.data));
702
+ return { ...entry, seq: Number(result.lastInsertRowid) };
703
+ }
704
+ readJournal(query = {}) {
705
+ const where = [];
706
+ const binds = [];
707
+ if (query.afterSeq !== undefined) {
708
+ where.push('seq > ?');
709
+ binds.push(query.afterSeq);
710
+ }
711
+ if (query.job !== undefined) {
712
+ where.push('job = ?');
713
+ binds.push(query.job);
714
+ }
715
+ const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
716
+ if (query.tail !== undefined) {
717
+ return this.db
718
+ .prepare(`SELECT * FROM (SELECT * FROM journal ${clause} ORDER BY seq DESC LIMIT ?) ORDER BY seq ASC`)
719
+ .all(...binds, query.tail)
720
+ .map(toJournalEntry);
721
+ }
722
+ const limit = query.limit !== undefined ? 'LIMIT ?' : '';
723
+ if (query.limit !== undefined)
724
+ binds.push(query.limit);
725
+ return this.db
726
+ .prepare(`SELECT * FROM journal ${clause} ORDER BY seq ASC ${limit}`)
727
+ .all(...binds)
728
+ .map(toJournalEntry);
729
+ }
730
+ close() {
731
+ if (!this.open)
732
+ return;
733
+ this.open = false;
734
+ this.db.close();
735
+ }
736
+ }
737
+ //# sourceMappingURL=sqlite.js.map