@creatornader/agent-bridge 0.2.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.
- package/CHANGELOG.md +60 -0
- package/LICENSE +216 -0
- package/README.md +338 -0
- package/SKILL.md +24 -0
- package/bin/CLAUDE.md +11 -0
- package/bin/agent-bridge +7 -0
- package/clients/claude-code.json +20 -0
- package/clients/claude-desktop.json +20 -0
- package/clients/codex.json +20 -0
- package/clients/generic-mcp.json +13 -0
- package/clients/openclaw.json +13 -0
- package/dist/bridge-domain-BcnBeHOn.d.ts +97 -0
- package/dist/bridge-service-CfqMcMAn.d.ts +28 -0
- package/dist/bridge-store-BuGjxTn4.d.ts +61 -0
- package/dist/bridge.d.ts +102 -0
- package/dist/bridge.js +83 -0
- package/dist/bridge.js.map +1 -0
- package/dist/chunk-4KAOBC5X.js +773 -0
- package/dist/chunk-4KAOBC5X.js.map +1 -0
- package/dist/chunk-6MAZ6YLZ.js +146 -0
- package/dist/chunk-6MAZ6YLZ.js.map +1 -0
- package/dist/chunk-AXL2I7FH.js +423 -0
- package/dist/chunk-AXL2I7FH.js.map +1 -0
- package/dist/chunk-BV6W4AJK.js +211 -0
- package/dist/chunk-BV6W4AJK.js.map +1 -0
- package/dist/chunk-CKSKUBDQ.js +153 -0
- package/dist/chunk-CKSKUBDQ.js.map +1 -0
- package/dist/chunk-JOUBDRYX.js +272 -0
- package/dist/chunk-JOUBDRYX.js.map +1 -0
- package/dist/chunk-JTC5YURG.js +49 -0
- package/dist/chunk-JTC5YURG.js.map +1 -0
- package/dist/chunk-KVR4JBRF.js +80 -0
- package/dist/chunk-KVR4JBRF.js.map +1 -0
- package/dist/chunk-O26W5QHS.js +409 -0
- package/dist/chunk-O26W5QHS.js.map +1 -0
- package/dist/chunk-WEULPMUY.js +988 -0
- package/dist/chunk-WEULPMUY.js.map +1 -0
- package/dist/chunk-YD6YJATN.js +48 -0
- package/dist/chunk-YD6YJATN.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +670 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-config.d.ts +30 -0
- package/dist/client-config.js +10 -0
- package/dist/client-config.js.map +1 -0
- package/dist/client-runtime.d.ts +15 -0
- package/dist/client-runtime.js +15 -0
- package/dist/client-runtime.js.map +1 -0
- package/dist/gateway-BULozv3K.d.ts +54 -0
- package/dist/gateway-main.d.ts +2 -0
- package/dist/gateway-main.js +105 -0
- package/dist/gateway-main.js.map +1 -0
- package/dist/gateway.d.ts +4 -0
- package/dist/gateway.js +10 -0
- package/dist/gateway.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -0
- package/dist/server.d.ts +34 -0
- package/dist/server.js +19 -0
- package/dist/server.js.map +1 -0
- package/dist/sqlite.d.ts +156 -0
- package/dist/sqlite.js +24 -0
- package/dist/sqlite.js.map +1 -0
- package/llms.txt +39 -0
- package/package.json +104 -0
- package/sql/migrations/001_schema_state.sql +34 -0
- package/sql/migrations/002_workspaces_agents_credentials.sql +77 -0
- package/sql/migrations/003_messages_receipts_deliveries.sql +116 -0
- package/sql/migrations/004_message_query_indexes.sql +31 -0
- package/sql/migrations/005_delivery_events_presence.sql +79 -0
- package/sql/migrations/006_legacy_shared_context_import.sql +139 -0
- package/sql/migrations/007_runtime_role.sql +59 -0
- package/sql/setup.sql +68 -0
|
@@ -0,0 +1,988 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
assertIdempotentReplay
|
|
4
|
+
} from "./chunk-YD6YJATN.js";
|
|
5
|
+
import {
|
|
6
|
+
decodeCursor,
|
|
7
|
+
encodeCursor
|
|
8
|
+
} from "./chunk-BV6W4AJK.js";
|
|
9
|
+
|
|
10
|
+
// src/sqlite-edge-store.ts
|
|
11
|
+
import { createHash, randomUUID } from "crypto";
|
|
12
|
+
import { chmodSync, existsSync, mkdirSync } from "fs";
|
|
13
|
+
import { createRequire } from "module";
|
|
14
|
+
import { dirname } from "path";
|
|
15
|
+
var require2 = createRequire(import.meta.url);
|
|
16
|
+
function openDatabase(path) {
|
|
17
|
+
const { DatabaseSync } = require2("node:sqlite");
|
|
18
|
+
return new DatabaseSync(path);
|
|
19
|
+
}
|
|
20
|
+
var MAX_SEQUENCE = 9223372036854775807n;
|
|
21
|
+
var schema = `
|
|
22
|
+
PRAGMA journal_mode = WAL;
|
|
23
|
+
PRAGMA synchronous = FULL;
|
|
24
|
+
PRAGMA foreign_keys = ON;
|
|
25
|
+
CREATE TABLE IF NOT EXISTS edge_scopes (
|
|
26
|
+
scope_key TEXT PRIMARY KEY,
|
|
27
|
+
endpoint_hash TEXT NOT NULL,
|
|
28
|
+
workspace TEXT NOT NULL,
|
|
29
|
+
agent TEXT NOT NULL,
|
|
30
|
+
pull_cursor TEXT,
|
|
31
|
+
last_sync_at TEXT,
|
|
32
|
+
last_error TEXT
|
|
33
|
+
);
|
|
34
|
+
CREATE TABLE IF NOT EXISTS edge_outbox (
|
|
35
|
+
position INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
36
|
+
scope_key TEXT NOT NULL REFERENCES edge_scopes(scope_key),
|
|
37
|
+
message_id TEXT NOT NULL,
|
|
38
|
+
idempotency_key TEXT NOT NULL,
|
|
39
|
+
payload_hash TEXT NOT NULL,
|
|
40
|
+
draft_json TEXT NOT NULL,
|
|
41
|
+
state TEXT NOT NULL CHECK(state IN ('pending', 'blocked')),
|
|
42
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
43
|
+
available_at TEXT NOT NULL,
|
|
44
|
+
lease_token TEXT,
|
|
45
|
+
lease_expires_at TEXT,
|
|
46
|
+
last_error TEXT,
|
|
47
|
+
created_at TEXT NOT NULL,
|
|
48
|
+
UNIQUE(scope_key, message_id),
|
|
49
|
+
UNIQUE(scope_key, idempotency_key)
|
|
50
|
+
);
|
|
51
|
+
CREATE INDEX IF NOT EXISTS edge_outbox_due
|
|
52
|
+
ON edge_outbox(scope_key, state, available_at, position);
|
|
53
|
+
CREATE TABLE IF NOT EXISTS edge_inbox (
|
|
54
|
+
scope_key TEXT NOT NULL REFERENCES edge_scopes(scope_key),
|
|
55
|
+
message_id TEXT NOT NULL,
|
|
56
|
+
remote_sequence TEXT NOT NULL,
|
|
57
|
+
sequence_key TEXT NOT NULL,
|
|
58
|
+
workspace TEXT NOT NULL,
|
|
59
|
+
source TEXT NOT NULL,
|
|
60
|
+
type TEXT NOT NULL,
|
|
61
|
+
thread_id TEXT,
|
|
62
|
+
created_at TEXT NOT NULL,
|
|
63
|
+
expires_at TEXT,
|
|
64
|
+
message_json TEXT NOT NULL,
|
|
65
|
+
PRIMARY KEY(scope_key, message_id),
|
|
66
|
+
UNIQUE(scope_key, sequence_key)
|
|
67
|
+
);
|
|
68
|
+
CREATE INDEX IF NOT EXISTS edge_inbox_cursor
|
|
69
|
+
ON edge_inbox(scope_key, sequence_key);
|
|
70
|
+
CREATE INDEX IF NOT EXISTS edge_inbox_source
|
|
71
|
+
ON edge_inbox(scope_key, source, sequence_key);
|
|
72
|
+
CREATE INDEX IF NOT EXISTS edge_inbox_thread
|
|
73
|
+
ON edge_inbox(scope_key, thread_id, sequence_key);
|
|
74
|
+
CREATE INDEX IF NOT EXISTS edge_inbox_created
|
|
75
|
+
ON edge_inbox(scope_key, created_at, sequence_key);
|
|
76
|
+
`;
|
|
77
|
+
var EdgeConflictError = class extends Error {
|
|
78
|
+
constructor() {
|
|
79
|
+
super(...arguments);
|
|
80
|
+
this.code = "edge_idempotency_conflict";
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
function canonical(value) {
|
|
84
|
+
if (value === void 0) return "null";
|
|
85
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
86
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
87
|
+
return `{${Object.keys(value).filter((key) => value[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
|
|
88
|
+
}
|
|
89
|
+
function intent(message2) {
|
|
90
|
+
return {
|
|
91
|
+
workspace: message2.workspace,
|
|
92
|
+
source: message2.source,
|
|
93
|
+
type: message2.type,
|
|
94
|
+
content: message2.content,
|
|
95
|
+
contentType: message2.contentType,
|
|
96
|
+
data: message2.data ?? null,
|
|
97
|
+
targets: [...message2.targets].sort(),
|
|
98
|
+
threadId: message2.threadId ?? null,
|
|
99
|
+
replyToId: message2.replyToId ?? null,
|
|
100
|
+
correlationId: message2.correlationId ?? null,
|
|
101
|
+
causationId: message2.causationId ?? null,
|
|
102
|
+
priority: message2.priority,
|
|
103
|
+
expiresAt: message2.expiresAt ?? null,
|
|
104
|
+
atribReceiptId: message2.atribReceiptId ?? null,
|
|
105
|
+
informedBy: [...message2.informedBy ?? []].sort(),
|
|
106
|
+
metadata: message2.metadata ?? null
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function edgeMessageFingerprint(message2) {
|
|
110
|
+
return createHash("sha256").update(canonical(intent(message2))).digest("hex");
|
|
111
|
+
}
|
|
112
|
+
function stableIdempotency(message2) {
|
|
113
|
+
return message2.idempotencyKey ? message2 : { ...message2, idempotencyKey: `agent-bridge:id:${message2.id}` };
|
|
114
|
+
}
|
|
115
|
+
function edgeScopeKey(scope) {
|
|
116
|
+
return createHash("sha256").update(`${scope.endpoint.replace(/\/$/, "")}\0${scope.principal.workspace}\0${scope.principal.agent}`).digest("hex");
|
|
117
|
+
}
|
|
118
|
+
function sequenceKey(sequence) {
|
|
119
|
+
if (!/^(0|[1-9][0-9]*)$/.test(sequence) || BigInt(sequence) > MAX_SEQUENCE) {
|
|
120
|
+
throw new EdgeConflictError("remote sequence is invalid");
|
|
121
|
+
}
|
|
122
|
+
return sequence.padStart(19, "0");
|
|
123
|
+
}
|
|
124
|
+
function parseDraft(value) {
|
|
125
|
+
return JSON.parse(String(value));
|
|
126
|
+
}
|
|
127
|
+
function parseMessage(value) {
|
|
128
|
+
return JSON.parse(String(value));
|
|
129
|
+
}
|
|
130
|
+
var SQLiteEdgeStore = class {
|
|
131
|
+
constructor(path, scope, busyTimeoutMs = 2e3) {
|
|
132
|
+
this.path = path;
|
|
133
|
+
this.scope = scope;
|
|
134
|
+
this.busyTimeoutMs = busyTimeoutMs;
|
|
135
|
+
this.initialized = false;
|
|
136
|
+
if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
137
|
+
this.db = openDatabase(path);
|
|
138
|
+
this.restrictFiles();
|
|
139
|
+
this.key = edgeScopeKey(scope);
|
|
140
|
+
}
|
|
141
|
+
restrictFiles() {
|
|
142
|
+
if (this.path === ":memory:") return;
|
|
143
|
+
for (const path of [this.path, `${this.path}-wal`, `${this.path}-shm`]) {
|
|
144
|
+
if (existsSync(path)) chmodSync(path, 384);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
get scopeKey() {
|
|
148
|
+
return this.key;
|
|
149
|
+
}
|
|
150
|
+
async initialize() {
|
|
151
|
+
if (this.initialized) return;
|
|
152
|
+
this.db.exec(`PRAGMA busy_timeout = ${Math.max(1, Math.trunc(this.busyTimeoutMs))}; ${schema}`);
|
|
153
|
+
this.restrictFiles();
|
|
154
|
+
const endpointHash = createHash("sha256").update(this.scope.endpoint.replace(/\/$/, "")).digest("hex");
|
|
155
|
+
this.db.prepare(`INSERT INTO edge_scopes (scope_key, endpoint_hash, workspace, agent)
|
|
156
|
+
VALUES (?, ?, ?, ?) ON CONFLICT(scope_key) DO NOTHING`).run(this.key, endpointHash, this.scope.principal.workspace, this.scope.principal.agent);
|
|
157
|
+
this.initialized = true;
|
|
158
|
+
}
|
|
159
|
+
async ready() {
|
|
160
|
+
await this.initialize();
|
|
161
|
+
}
|
|
162
|
+
async enqueue(input, now = /* @__PURE__ */ new Date()) {
|
|
163
|
+
await this.ready();
|
|
164
|
+
const draft = stableIdempotency(input);
|
|
165
|
+
const payloadHash = edgeMessageFingerprint(draft);
|
|
166
|
+
const serialized = canonical(draft);
|
|
167
|
+
const nowText = now.toISOString();
|
|
168
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
169
|
+
try {
|
|
170
|
+
const existing = this.db.prepare(`SELECT * FROM edge_outbox
|
|
171
|
+
WHERE scope_key=? AND (message_id=? OR idempotency_key=?) ORDER BY position LIMIT 1`).get(this.key, draft.id, draft.idempotencyKey);
|
|
172
|
+
if (existing) {
|
|
173
|
+
if (String(existing.payload_hash) !== payloadHash) {
|
|
174
|
+
throw new EdgeConflictError("message ID or idempotency key is already bound to different content");
|
|
175
|
+
}
|
|
176
|
+
this.db.exec("COMMIT");
|
|
177
|
+
return { draft: parseDraft(existing.draft_json), created: false };
|
|
178
|
+
}
|
|
179
|
+
this.db.prepare(`INSERT INTO edge_outbox
|
|
180
|
+
(scope_key, message_id, idempotency_key, payload_hash, draft_json, state, available_at, created_at)
|
|
181
|
+
VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)`).run(this.key, draft.id, draft.idempotencyKey, payloadHash, serialized, nowText, nowText);
|
|
182
|
+
this.db.exec("COMMIT");
|
|
183
|
+
return { draft, created: true };
|
|
184
|
+
} catch (error) {
|
|
185
|
+
this.db.exec("ROLLBACK");
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async claimNext(now = /* @__PURE__ */ new Date(), leaseMs = 3e4) {
|
|
190
|
+
await this.ready();
|
|
191
|
+
const nowText = now.toISOString();
|
|
192
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
193
|
+
try {
|
|
194
|
+
const head = this.db.prepare(`SELECT * FROM edge_outbox
|
|
195
|
+
WHERE scope_key=? AND state='pending' ORDER BY position LIMIT 1`).get(this.key);
|
|
196
|
+
if (!head || String(head.available_at) > nowText || head.lease_expires_at && String(head.lease_expires_at) > nowText) {
|
|
197
|
+
this.db.exec("COMMIT");
|
|
198
|
+
return void 0;
|
|
199
|
+
}
|
|
200
|
+
const leaseToken = randomUUID();
|
|
201
|
+
const leaseExpiresAt = new Date(now.getTime() + leaseMs).toISOString();
|
|
202
|
+
const updated = this.db.prepare(`UPDATE edge_outbox
|
|
203
|
+
SET lease_token=?, lease_expires_at=? WHERE scope_key=? AND position=?
|
|
204
|
+
AND (lease_expires_at IS NULL OR lease_expires_at<=?)`).run(leaseToken, leaseExpiresAt, this.key, Number(head.position), nowText);
|
|
205
|
+
if (!updated.changes) {
|
|
206
|
+
this.db.exec("COMMIT");
|
|
207
|
+
return void 0;
|
|
208
|
+
}
|
|
209
|
+
this.db.exec("COMMIT");
|
|
210
|
+
return {
|
|
211
|
+
position: Number(head.position),
|
|
212
|
+
draft: parseDraft(head.draft_json),
|
|
213
|
+
payloadHash: String(head.payload_hash),
|
|
214
|
+
attempts: Number(head.attempts),
|
|
215
|
+
leaseToken,
|
|
216
|
+
createdAt: String(head.created_at)
|
|
217
|
+
};
|
|
218
|
+
} catch (error) {
|
|
219
|
+
this.db.exec("ROLLBACK");
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async retry(record, error, availableAt) {
|
|
224
|
+
await this.ready();
|
|
225
|
+
this.db.prepare(`UPDATE edge_outbox SET attempts=attempts+1, available_at=?,
|
|
226
|
+
lease_token=NULL, lease_expires_at=NULL, last_error=?
|
|
227
|
+
WHERE scope_key=? AND position=? AND lease_token=?`).run(availableAt.toISOString(), error.slice(0, 256), this.key, record.position, record.leaseToken);
|
|
228
|
+
await this.noteError(error);
|
|
229
|
+
}
|
|
230
|
+
async block(record, error) {
|
|
231
|
+
await this.ready();
|
|
232
|
+
this.db.prepare(`UPDATE edge_outbox SET state='blocked', attempts=attempts+1,
|
|
233
|
+
lease_token=NULL, lease_expires_at=NULL, last_error=?
|
|
234
|
+
WHERE scope_key=? AND position=? AND lease_token=?`).run(error.slice(0, 256), this.key, record.position, record.leaseToken);
|
|
235
|
+
await this.noteError(error);
|
|
236
|
+
}
|
|
237
|
+
async commit(record, message2, cacheVisible, now = /* @__PURE__ */ new Date()) {
|
|
238
|
+
await this.ready();
|
|
239
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
240
|
+
try {
|
|
241
|
+
if (cacheVisible) this.cacheOne(message2);
|
|
242
|
+
const deleted = this.db.prepare(`DELETE FROM edge_outbox
|
|
243
|
+
WHERE scope_key=? AND position=? AND lease_token=?`).run(this.key, record.position, record.leaseToken);
|
|
244
|
+
if (deleted.changes !== 1) throw new EdgeConflictError("outbox lease was lost before commit");
|
|
245
|
+
this.db.prepare(`UPDATE edge_scopes SET last_sync_at=?, last_error=NULL WHERE scope_key=?`).run(now.toISOString(), this.key);
|
|
246
|
+
this.db.exec("COMMIT");
|
|
247
|
+
} catch (error) {
|
|
248
|
+
this.db.exec("ROLLBACK");
|
|
249
|
+
throw error;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
cacheOne(message2) {
|
|
253
|
+
const serialized = canonical(message2);
|
|
254
|
+
const key = sequenceKey(message2.sequence);
|
|
255
|
+
const byId = this.db.prepare(`SELECT remote_sequence, message_json FROM edge_inbox
|
|
256
|
+
WHERE scope_key=? AND message_id=?`).get(this.key, message2.id);
|
|
257
|
+
const bySequence = this.db.prepare(`SELECT message_id, message_json FROM edge_inbox
|
|
258
|
+
WHERE scope_key=? AND sequence_key=?`).get(this.key, key);
|
|
259
|
+
if (byId || bySequence) {
|
|
260
|
+
if (!byId || String(byId.remote_sequence) !== message2.sequence || String(byId.message_json) !== serialized || bySequence && String(bySequence.message_id) !== message2.id) {
|
|
261
|
+
throw new EdgeConflictError("cached message conflicts with immutable remote history");
|
|
262
|
+
}
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
this.db.prepare(`INSERT INTO edge_inbox
|
|
266
|
+
(scope_key, message_id, remote_sequence, sequence_key, workspace, source, type,
|
|
267
|
+
thread_id, created_at, expires_at, message_json)
|
|
268
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
|
|
269
|
+
this.key,
|
|
270
|
+
message2.id,
|
|
271
|
+
message2.sequence,
|
|
272
|
+
key,
|
|
273
|
+
message2.workspace,
|
|
274
|
+
message2.source,
|
|
275
|
+
message2.type,
|
|
276
|
+
message2.threadId ?? null,
|
|
277
|
+
message2.createdAt,
|
|
278
|
+
message2.expiresAt ?? null,
|
|
279
|
+
serialized
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
async cachePage(messages, cursor, now = /* @__PURE__ */ new Date()) {
|
|
283
|
+
await this.ready();
|
|
284
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
285
|
+
try {
|
|
286
|
+
for (const message2 of messages) this.cacheOne(message2);
|
|
287
|
+
const current = this.db.prepare("SELECT pull_cursor FROM edge_scopes WHERE scope_key=?").get(this.key);
|
|
288
|
+
const currentCursor = current.pull_cursor ? String(current.pull_cursor) : void 0;
|
|
289
|
+
const nextCursor = !cursor ? currentCursor : !currentCursor || sequenceKey(decodeCursor(cursor)) >= sequenceKey(decodeCursor(currentCursor)) ? cursor : currentCursor;
|
|
290
|
+
this.db.prepare(`UPDATE edge_scopes SET pull_cursor=?, last_sync_at=?, last_error=NULL
|
|
291
|
+
WHERE scope_key=?`).run(nextCursor ?? null, now.toISOString(), this.key);
|
|
292
|
+
this.db.exec("COMMIT");
|
|
293
|
+
} catch (error) {
|
|
294
|
+
this.db.exec("ROLLBACK");
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async cacheLatest(messages, now = /* @__PURE__ */ new Date()) {
|
|
299
|
+
await this.ready();
|
|
300
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
301
|
+
try {
|
|
302
|
+
for (const message2 of messages) this.cacheOne(message2);
|
|
303
|
+
this.db.prepare(`UPDATE edge_scopes SET last_sync_at=?, last_error=NULL WHERE scope_key=?`).run(now.toISOString(), this.key);
|
|
304
|
+
this.db.exec("COMMIT");
|
|
305
|
+
} catch (error) {
|
|
306
|
+
this.db.exec("ROLLBACK");
|
|
307
|
+
throw error;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
async list(query = {}) {
|
|
311
|
+
await this.ready();
|
|
312
|
+
if (query.unacknowledgedBy) {
|
|
313
|
+
throw new Error("offline cache cannot evaluate unacknowledgedBy");
|
|
314
|
+
}
|
|
315
|
+
const clauses = ["scope_key=?"];
|
|
316
|
+
const args = [this.key];
|
|
317
|
+
if (!query.latest) {
|
|
318
|
+
clauses.push("sequence_key>?");
|
|
319
|
+
args.push(sequenceKey(decodeCursor(query.cursor) ?? "0"));
|
|
320
|
+
}
|
|
321
|
+
if (!query.includeExpired) {
|
|
322
|
+
clauses.push("(expires_at IS NULL OR expires_at>?)");
|
|
323
|
+
args.push((/* @__PURE__ */ new Date()).toISOString());
|
|
324
|
+
}
|
|
325
|
+
if (query.types?.length) {
|
|
326
|
+
clauses.push(`type IN (${query.types.map(() => "?").join(",")})`);
|
|
327
|
+
args.push(...query.types);
|
|
328
|
+
}
|
|
329
|
+
if (query.source) {
|
|
330
|
+
clauses.push("source=?");
|
|
331
|
+
args.push(query.source);
|
|
332
|
+
}
|
|
333
|
+
if (query.since) {
|
|
334
|
+
clauses.push("created_at>=?");
|
|
335
|
+
args.push(query.since);
|
|
336
|
+
}
|
|
337
|
+
if (query.threadId) {
|
|
338
|
+
clauses.push("thread_id=?");
|
|
339
|
+
args.push(query.threadId);
|
|
340
|
+
}
|
|
341
|
+
const limit = Math.min(Math.max(Math.trunc(query.limit ?? 50), 1), 200);
|
|
342
|
+
const rows = this.db.prepare(`SELECT message_json FROM edge_inbox
|
|
343
|
+
WHERE ${clauses.join(" AND ")} ORDER BY sequence_key ${query.latest ? "DESC" : "ASC"} LIMIT ?`).all(...args, limit);
|
|
344
|
+
const messages = rows.map((row) => parseMessage(row.message_json));
|
|
345
|
+
const cursorMessage = query.latest ? messages[0] : messages[messages.length - 1];
|
|
346
|
+
return { messages, cursor: cursorMessage ? encodeCursor(cursorMessage.sequence) : query.cursor };
|
|
347
|
+
}
|
|
348
|
+
async pullCursor() {
|
|
349
|
+
await this.ready();
|
|
350
|
+
const row = this.db.prepare("SELECT pull_cursor FROM edge_scopes WHERE scope_key=?").get(this.key);
|
|
351
|
+
return row.pull_cursor ? String(row.pull_cursor) : void 0;
|
|
352
|
+
}
|
|
353
|
+
async noteError(error) {
|
|
354
|
+
await this.ready();
|
|
355
|
+
this.db.prepare("UPDATE edge_scopes SET last_error=? WHERE scope_key=?").run(error.slice(0, 256), this.key);
|
|
356
|
+
}
|
|
357
|
+
async stats() {
|
|
358
|
+
await this.ready();
|
|
359
|
+
const counts = this.db.prepare(`SELECT
|
|
360
|
+
sum(CASE WHEN state='pending' THEN 1 ELSE 0 END) AS pending,
|
|
361
|
+
sum(CASE WHEN state='blocked' THEN 1 ELSE 0 END) AS blocked
|
|
362
|
+
FROM edge_outbox WHERE scope_key=?`).get(this.key);
|
|
363
|
+
const cache = this.db.prepare("SELECT count(*) AS count FROM edge_inbox WHERE scope_key=?").get(this.key);
|
|
364
|
+
const state = this.db.prepare(`SELECT pull_cursor, last_sync_at, last_error
|
|
365
|
+
FROM edge_scopes WHERE scope_key=?`).get(this.key);
|
|
366
|
+
return {
|
|
367
|
+
pending: Number(counts.pending ?? 0),
|
|
368
|
+
blocked: Number(counts.blocked ?? 0),
|
|
369
|
+
cached: Number(cache.count ?? 0),
|
|
370
|
+
pullCursor: state.pull_cursor ? String(state.pull_cursor) : void 0,
|
|
371
|
+
lastSyncAt: state.last_sync_at ? String(state.last_sync_at) : void 0,
|
|
372
|
+
lastError: state.last_error ? String(state.last_error) : void 0
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
async close() {
|
|
376
|
+
this.db.close();
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
// src/syncing-bridge-store.ts
|
|
381
|
+
function statusOf(error) {
|
|
382
|
+
if (!error || typeof error !== "object" || !("status" in error)) return void 0;
|
|
383
|
+
const status = Number(error.status);
|
|
384
|
+
return Number.isFinite(status) ? status : void 0;
|
|
385
|
+
}
|
|
386
|
+
function codeOf(error) {
|
|
387
|
+
if (error && typeof error === "object" && "code" in error) {
|
|
388
|
+
const code = error.code;
|
|
389
|
+
if (typeof code === "string" && code) return code.slice(0, 128);
|
|
390
|
+
}
|
|
391
|
+
return error instanceof Error ? error.name.slice(0, 128) : "sync_error";
|
|
392
|
+
}
|
|
393
|
+
function isRetryableSyncError(error) {
|
|
394
|
+
const status = statusOf(error);
|
|
395
|
+
const code = codeOf(error);
|
|
396
|
+
if (["invalid_input", "idempotency_conflict", "principal_mismatch"].includes(code)) return false;
|
|
397
|
+
return status === void 0 || status === 0 || status === 408 || status === 425 || status === 429 || status >= 500;
|
|
398
|
+
}
|
|
399
|
+
function provisional(draft, createdAt) {
|
|
400
|
+
return { ...draft, sequence: "0", createdAt };
|
|
401
|
+
}
|
|
402
|
+
var SyncingBridgeStore = class {
|
|
403
|
+
constructor(edge, remote, principal, options = {}) {
|
|
404
|
+
this.edge = edge;
|
|
405
|
+
this.remote = remote;
|
|
406
|
+
this.principal = principal;
|
|
407
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
408
|
+
this.random = options.random ?? Math.random;
|
|
409
|
+
this.baseDelayMs = options.baseDelayMs ?? 1e3;
|
|
410
|
+
this.maxDelayMs = options.maxDelayMs ?? 5 * 6e4;
|
|
411
|
+
this.leaseMs = options.leaseMs ?? 3e4;
|
|
412
|
+
}
|
|
413
|
+
async initialize() {
|
|
414
|
+
await this.edge.initialize();
|
|
415
|
+
}
|
|
416
|
+
async verifyRemote() {
|
|
417
|
+
await this.ensureRemote();
|
|
418
|
+
}
|
|
419
|
+
async ensureRemote() {
|
|
420
|
+
if (!this.remoteReady) {
|
|
421
|
+
this.remoteReady = this.remote.initialize().catch((error) => {
|
|
422
|
+
this.remoteReady = void 0;
|
|
423
|
+
throw error;
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
await this.remoteReady;
|
|
427
|
+
}
|
|
428
|
+
assertPrincipal(principal, includeInstance = true) {
|
|
429
|
+
if (principal.workspace !== this.principal.workspace || principal.agent !== this.principal.agent || includeInstance && principal.instance !== this.principal.instance) {
|
|
430
|
+
const error = new Error("principal does not match the synchronized edge scope");
|
|
431
|
+
Object.assign(error, { status: 403, code: "principal_mismatch" });
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
delay(attempts) {
|
|
436
|
+
const exponential = Math.min(this.maxDelayMs, this.baseDelayMs * 2 ** Math.min(attempts, 20));
|
|
437
|
+
const jitter = 0.8 + this.random() * 0.4;
|
|
438
|
+
return Math.max(1, Math.round(exponential * jitter));
|
|
439
|
+
}
|
|
440
|
+
async flushOne() {
|
|
441
|
+
try {
|
|
442
|
+
await this.ensureRemote();
|
|
443
|
+
} catch (error) {
|
|
444
|
+
await this.edge.noteError(codeOf(error));
|
|
445
|
+
return {
|
|
446
|
+
state: "retry",
|
|
447
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
448
|
+
retryable: isRetryableSyncError(error)
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
const record = await this.edge.claimNext(this.now(), this.leaseMs);
|
|
452
|
+
if (!record) return { state: "empty" };
|
|
453
|
+
try {
|
|
454
|
+
const result = await this.remote.insertMessage(record.draft);
|
|
455
|
+
if (edgeMessageFingerprint(result.message) !== record.payloadHash) {
|
|
456
|
+
const error = new Error("idempotency key resolved to different message content");
|
|
457
|
+
Object.assign(error, { status: 409, code: "idempotency_conflict" });
|
|
458
|
+
await this.edge.block(record, codeOf(error));
|
|
459
|
+
return { state: "blocked", error };
|
|
460
|
+
}
|
|
461
|
+
const cacheVisible = result.message.targets.length === 0 || result.message.targets.includes(this.principal.agent);
|
|
462
|
+
await this.edge.commit(record, result.message, cacheVisible, this.now());
|
|
463
|
+
return { state: "committed", result, messageId: record.draft.id };
|
|
464
|
+
} catch (error) {
|
|
465
|
+
const caught = error instanceof Error ? error : new Error(String(error));
|
|
466
|
+
if (isRetryableSyncError(error)) {
|
|
467
|
+
await this.edge.retry(
|
|
468
|
+
record,
|
|
469
|
+
codeOf(error),
|
|
470
|
+
new Date(this.now().getTime() + this.delay(record.attempts))
|
|
471
|
+
);
|
|
472
|
+
return { state: "retry", error: caught, retryable: true };
|
|
473
|
+
}
|
|
474
|
+
await this.edge.block(record, codeOf(error));
|
|
475
|
+
return { state: "blocked", error: caught };
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
async insertMessage(message2) {
|
|
479
|
+
this.assertPrincipal({ workspace: message2.workspace, agent: message2.source }, false);
|
|
480
|
+
const queued = await this.edge.enqueue(message2, this.now());
|
|
481
|
+
const draft = queued.draft;
|
|
482
|
+
const flushed = await this.flushOne();
|
|
483
|
+
if (flushed.state === "blocked") throw flushed.error;
|
|
484
|
+
if (flushed.state === "retry" && !flushed.retryable) throw flushed.error;
|
|
485
|
+
if (flushed.state === "committed" && flushed.messageId === draft.id) {
|
|
486
|
+
return { ...flushed.result, disposition: "committed", authoritative: true };
|
|
487
|
+
}
|
|
488
|
+
return {
|
|
489
|
+
message: provisional(draft, this.now().toISOString()),
|
|
490
|
+
created: queued.created,
|
|
491
|
+
disposition: "queued",
|
|
492
|
+
authoritative: false
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
async pull(maxPages) {
|
|
496
|
+
let pulled = 0;
|
|
497
|
+
for (let pageNumber = 0; pageNumber < maxPages; pageNumber += 1) {
|
|
498
|
+
const before = await this.edge.pullCursor();
|
|
499
|
+
try {
|
|
500
|
+
await this.ensureRemote();
|
|
501
|
+
const page = await this.remote.listMessages(this.principal, {
|
|
502
|
+
cursor: before,
|
|
503
|
+
limit: 200,
|
|
504
|
+
includeExpired: true
|
|
505
|
+
});
|
|
506
|
+
await this.edge.cachePage(page.messages, page.cursor, this.now());
|
|
507
|
+
pulled += page.messages.length;
|
|
508
|
+
if (page.messages.length < 200 || !page.cursor || page.cursor === before) break;
|
|
509
|
+
} catch (error) {
|
|
510
|
+
await this.edge.noteError(codeOf(error));
|
|
511
|
+
return {
|
|
512
|
+
online: false,
|
|
513
|
+
pulled,
|
|
514
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
515
|
+
retryable: isRetryableSyncError(error)
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return { online: true, pulled };
|
|
520
|
+
}
|
|
521
|
+
async sync(options = {}) {
|
|
522
|
+
await this.edge.initialize();
|
|
523
|
+
const maxPush = Math.min(Math.max(Math.trunc(options.maxPush ?? 100), 0), 1e3);
|
|
524
|
+
const maxPages = Math.min(Math.max(Math.trunc(options.maxPages ?? 20), 0), 100);
|
|
525
|
+
let pushed = 0;
|
|
526
|
+
let deduplicated = 0;
|
|
527
|
+
let online = true;
|
|
528
|
+
let lastError;
|
|
529
|
+
let failureRetryable;
|
|
530
|
+
for (let index = 0; index < maxPush; index += 1) {
|
|
531
|
+
const result = await this.flushOne();
|
|
532
|
+
if (result.state === "empty") break;
|
|
533
|
+
if (result.state === "committed") {
|
|
534
|
+
pushed += 1;
|
|
535
|
+
if (!result.result.created) deduplicated += 1;
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
lastError = codeOf(result.error);
|
|
539
|
+
failureRetryable = result.state === "retry" ? result.retryable : false;
|
|
540
|
+
if (result.state === "retry") online = false;
|
|
541
|
+
break;
|
|
542
|
+
}
|
|
543
|
+
let pulled = 0;
|
|
544
|
+
if (maxPages > 0) {
|
|
545
|
+
const pull = await this.pull(maxPages);
|
|
546
|
+
online = online && pull.online;
|
|
547
|
+
pulled = pull.pulled;
|
|
548
|
+
if (pull.error) {
|
|
549
|
+
lastError = codeOf(pull.error);
|
|
550
|
+
failureRetryable = pull.retryable;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const stats = await this.edge.stats();
|
|
554
|
+
return {
|
|
555
|
+
online,
|
|
556
|
+
pushed,
|
|
557
|
+
deduplicated,
|
|
558
|
+
pulled,
|
|
559
|
+
pending: stats.pending,
|
|
560
|
+
blocked: stats.blocked,
|
|
561
|
+
cached: stats.cached,
|
|
562
|
+
cursor: stats.pullCursor,
|
|
563
|
+
lastSyncedAt: stats.lastSyncAt,
|
|
564
|
+
lastError: lastError ?? stats.lastError,
|
|
565
|
+
failureRetryable
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
async listMessages(principal, query = {}) {
|
|
569
|
+
this.assertPrincipal(principal);
|
|
570
|
+
if (query.unacknowledgedBy) {
|
|
571
|
+
await this.ensureRemote();
|
|
572
|
+
const remotePage = await this.remote.listMessages(principal, query);
|
|
573
|
+
await this.edge.cacheLatest(remotePage.messages, this.now());
|
|
574
|
+
const stats = await this.edge.stats();
|
|
575
|
+
return { ...remotePage, source: "remote", stale: false, lastSyncedAt: stats.lastSyncAt };
|
|
576
|
+
}
|
|
577
|
+
if (query.latest) {
|
|
578
|
+
try {
|
|
579
|
+
await this.ensureRemote();
|
|
580
|
+
const remotePage = await this.remote.listMessages(principal, query);
|
|
581
|
+
await this.edge.cacheLatest(remotePage.messages, this.now());
|
|
582
|
+
const stats = await this.edge.stats();
|
|
583
|
+
return { ...remotePage, source: "remote", stale: false, lastSyncedAt: stats.lastSyncAt };
|
|
584
|
+
} catch (error) {
|
|
585
|
+
if (!isRetryableSyncError(error)) throw error;
|
|
586
|
+
await this.edge.noteError(codeOf(error));
|
|
587
|
+
const cached = await this.edge.list(query);
|
|
588
|
+
const stats = await this.edge.stats();
|
|
589
|
+
return { ...cached, source: "cache", stale: true, lastSyncedAt: stats.lastSyncAt };
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
await this.sync({ maxPush: 20, maxPages: 0 });
|
|
593
|
+
try {
|
|
594
|
+
await this.ensureRemote();
|
|
595
|
+
const remotePage = await this.remote.listMessages(principal, query);
|
|
596
|
+
await this.edge.cacheLatest(remotePage.messages, this.now());
|
|
597
|
+
const stats = await this.edge.stats();
|
|
598
|
+
return { ...remotePage, source: "remote", stale: false, lastSyncedAt: stats.lastSyncAt };
|
|
599
|
+
} catch (error) {
|
|
600
|
+
if (!isRetryableSyncError(error)) throw error;
|
|
601
|
+
await this.edge.noteError(codeOf(error));
|
|
602
|
+
const cached = await this.edge.list(query);
|
|
603
|
+
const stats = await this.edge.stats();
|
|
604
|
+
return { ...cached, source: "cache", stale: true, lastSyncedAt: stats.lastSyncAt };
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
async recordReceipt(workspace, messageIds, principal, readAt) {
|
|
608
|
+
this.assertPrincipal({ workspace, agent: principal }, false);
|
|
609
|
+
await this.ensureRemote();
|
|
610
|
+
return this.remote.recordReceipt(workspace, messageIds, principal, readAt);
|
|
611
|
+
}
|
|
612
|
+
async claimDelivery(principal, options) {
|
|
613
|
+
this.assertPrincipal(principal);
|
|
614
|
+
await this.ensureRemote();
|
|
615
|
+
return this.remote.claimDelivery(principal, options);
|
|
616
|
+
}
|
|
617
|
+
async renewDelivery(principal, deliveryId, leaseToken, leaseMs) {
|
|
618
|
+
this.assertPrincipal(principal);
|
|
619
|
+
await this.ensureRemote();
|
|
620
|
+
return this.remote.renewDelivery(principal, deliveryId, leaseToken, leaseMs);
|
|
621
|
+
}
|
|
622
|
+
async settleDelivery(principal, deliveryId, leaseToken, state, error, retryPolicy) {
|
|
623
|
+
this.assertPrincipal(principal);
|
|
624
|
+
await this.ensureRemote();
|
|
625
|
+
return this.remote.settleDelivery(principal, deliveryId, leaseToken, state, error, retryPolicy);
|
|
626
|
+
}
|
|
627
|
+
async diagnostics(principal) {
|
|
628
|
+
this.assertPrincipal(principal);
|
|
629
|
+
const edge = await this.edge.stats();
|
|
630
|
+
let remote;
|
|
631
|
+
try {
|
|
632
|
+
await this.ensureRemote();
|
|
633
|
+
remote = await this.remote.diagnostics?.(principal);
|
|
634
|
+
} catch {
|
|
635
|
+
}
|
|
636
|
+
return {
|
|
637
|
+
schemaVersion: remote?.schemaVersion ?? "postgres-v2",
|
|
638
|
+
deliverySupported: remote?.deliverySupported ?? true,
|
|
639
|
+
pending: remote?.pending ?? null,
|
|
640
|
+
claimed: remote?.claimed ?? null,
|
|
641
|
+
retrying: remote?.retrying ?? null,
|
|
642
|
+
dead: remote?.dead ?? null,
|
|
643
|
+
oldestAvailableAt: remote?.oldestAvailableAt,
|
|
644
|
+
principal: { workspace: principal.workspace, agent: principal.agent },
|
|
645
|
+
remoteReachable: Boolean(remote),
|
|
646
|
+
outboxPending: edge.pending,
|
|
647
|
+
outboxBlocked: edge.blocked,
|
|
648
|
+
cachedMessages: edge.cached,
|
|
649
|
+
lastSyncAt: edge.lastSyncAt,
|
|
650
|
+
lastSyncError: edge.lastError
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
async heartbeat(principal, leaseMs, runtimeType, capabilities = []) {
|
|
654
|
+
this.assertPrincipal(principal);
|
|
655
|
+
await this.ensureRemote();
|
|
656
|
+
if (!this.remote.heartbeat) throw new Error("presence is not supported by the remote provider");
|
|
657
|
+
return this.remote.heartbeat(principal, leaseMs, runtimeType, capabilities);
|
|
658
|
+
}
|
|
659
|
+
async listPresence(principal) {
|
|
660
|
+
this.assertPrincipal(principal);
|
|
661
|
+
await this.ensureRemote();
|
|
662
|
+
if (!this.remote.listPresence) throw new Error("presence is not supported by the remote provider");
|
|
663
|
+
return this.remote.listPresence(principal);
|
|
664
|
+
}
|
|
665
|
+
async close() {
|
|
666
|
+
await this.edge.close();
|
|
667
|
+
await this.remote.close?.();
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
// src/sqlite-bridge-store.ts
|
|
672
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
673
|
+
import { chmodSync as chmodSync2, existsSync as existsSync2 } from "fs";
|
|
674
|
+
import { createRequire as createRequire2 } from "module";
|
|
675
|
+
var require3 = createRequire2(import.meta.url);
|
|
676
|
+
function openDatabase2(path) {
|
|
677
|
+
const { DatabaseSync } = require3("node:sqlite");
|
|
678
|
+
return new DatabaseSync(path);
|
|
679
|
+
}
|
|
680
|
+
var schema2 = `
|
|
681
|
+
PRAGMA journal_mode = WAL;
|
|
682
|
+
PRAGMA synchronous = FULL;
|
|
683
|
+
PRAGMA foreign_keys = ON;
|
|
684
|
+
CREATE TABLE IF NOT EXISTS bridge_messages (
|
|
685
|
+
sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, workspace TEXT NOT NULL, source TEXT NOT NULL,
|
|
686
|
+
type TEXT NOT NULL, content TEXT NOT NULL, content_type TEXT NOT NULL, data TEXT, targets TEXT NOT NULL DEFAULT '[]',
|
|
687
|
+
thread_id TEXT, reply_to_id TEXT, correlation_id TEXT, causation_id TEXT, priority TEXT NOT NULL, expires_at TEXT,
|
|
688
|
+
idempotency_key TEXT, atrib_receipt_id TEXT, informed_by TEXT, metadata TEXT, created_at TEXT NOT NULL,
|
|
689
|
+
UNIQUE(workspace, id), CHECK(json_valid(targets) AND json_type(targets) = 'array'),
|
|
690
|
+
CHECK(priority IN ('info', 'high', 'urgent'))
|
|
691
|
+
);
|
|
692
|
+
CREATE UNIQUE INDEX IF NOT EXISTS bridge_messages_idempotency ON bridge_messages(workspace, source, idempotency_key) WHERE idempotency_key IS NOT NULL;
|
|
693
|
+
CREATE INDEX IF NOT EXISTS bridge_messages_cursor ON bridge_messages(workspace, sequence);
|
|
694
|
+
CREATE INDEX IF NOT EXISTS bridge_messages_source ON bridge_messages(workspace, source, sequence);
|
|
695
|
+
CREATE INDEX IF NOT EXISTS bridge_messages_thread ON bridge_messages(workspace, thread_id, sequence) WHERE thread_id IS NOT NULL;
|
|
696
|
+
CREATE INDEX IF NOT EXISTS bridge_messages_created ON bridge_messages(workspace, created_at, sequence);
|
|
697
|
+
CREATE TABLE IF NOT EXISTS bridge_receipts (workspace TEXT NOT NULL, message_id TEXT NOT NULL, principal TEXT NOT NULL, read_at TEXT NOT NULL, PRIMARY KEY(workspace, message_id, principal), FOREIGN KEY(workspace, message_id) REFERENCES bridge_messages(workspace, id) ON DELETE CASCADE);
|
|
698
|
+
CREATE TABLE IF NOT EXISTS bridge_deliveries (
|
|
699
|
+
id TEXT PRIMARY KEY, message_id TEXT NOT NULL, workspace TEXT NOT NULL, recipient TEXT NOT NULL,
|
|
700
|
+
state TEXT NOT NULL, attempt INTEGER NOT NULL DEFAULT 0, available_at TEXT NOT NULL, lease_token TEXT, lease_owner TEXT, lease_expires_at TEXT, last_error TEXT,
|
|
701
|
+
UNIQUE(message_id, recipient), FOREIGN KEY(workspace, message_id) REFERENCES bridge_messages(workspace, id) ON DELETE CASCADE,
|
|
702
|
+
CHECK(state IN ('pending', 'claimed', 'acked', 'retrying', 'dead')), CHECK(attempt >= 0),
|
|
703
|
+
CHECK((state = 'claimed' AND lease_token IS NOT NULL AND lease_expires_at IS NOT NULL) OR (state <> 'claimed' AND lease_token IS NULL AND lease_owner IS NULL AND lease_expires_at IS NULL))
|
|
704
|
+
);
|
|
705
|
+
CREATE INDEX IF NOT EXISTS bridge_deliveries_claim ON bridge_deliveries(workspace, recipient, state, available_at);
|
|
706
|
+
CREATE TABLE IF NOT EXISTS bridge_delivery_events (
|
|
707
|
+
sequence INTEGER PRIMARY KEY AUTOINCREMENT, delivery_id TEXT NOT NULL,
|
|
708
|
+
message_id TEXT NOT NULL, workspace TEXT NOT NULL, recipient TEXT NOT NULL,
|
|
709
|
+
from_state TEXT, to_state TEXT NOT NULL, attempt INTEGER NOT NULL,
|
|
710
|
+
lease_owner TEXT, error TEXT, created_at TEXT NOT NULL
|
|
711
|
+
);
|
|
712
|
+
CREATE INDEX IF NOT EXISTS bridge_delivery_events_lookup
|
|
713
|
+
ON bridge_delivery_events(workspace, delivery_id, sequence);
|
|
714
|
+
CREATE TRIGGER IF NOT EXISTS bridge_delivery_events_insert
|
|
715
|
+
AFTER INSERT ON bridge_deliveries BEGIN
|
|
716
|
+
INSERT INTO bridge_delivery_events
|
|
717
|
+
(delivery_id,message_id,workspace,recipient,from_state,to_state,attempt,lease_owner,error,created_at)
|
|
718
|
+
VALUES
|
|
719
|
+
(NEW.id,NEW.message_id,NEW.workspace,NEW.recipient,NULL,NEW.state,NEW.attempt,NEW.lease_owner,NEW.last_error,strftime('%Y-%m-%dT%H:%M:%fZ','now'));
|
|
720
|
+
END;
|
|
721
|
+
CREATE TRIGGER IF NOT EXISTS bridge_delivery_events_update
|
|
722
|
+
AFTER UPDATE ON bridge_deliveries
|
|
723
|
+
WHEN OLD.state IS NOT NEW.state OR OLD.attempt IS NOT NEW.attempt BEGIN
|
|
724
|
+
INSERT INTO bridge_delivery_events
|
|
725
|
+
(delivery_id,message_id,workspace,recipient,from_state,to_state,attempt,lease_owner,error,created_at)
|
|
726
|
+
VALUES
|
|
727
|
+
(NEW.id,NEW.message_id,NEW.workspace,NEW.recipient,OLD.state,NEW.state,NEW.attempt,NEW.lease_owner,NEW.last_error,strftime('%Y-%m-%dT%H:%M:%fZ','now'));
|
|
728
|
+
END;
|
|
729
|
+
CREATE TABLE IF NOT EXISTS bridge_presence (
|
|
730
|
+
workspace TEXT NOT NULL, agent TEXT NOT NULL, instance TEXT NOT NULL, runtime_type TEXT,
|
|
731
|
+
capabilities TEXT NOT NULL DEFAULT '[]', lease_expires_at TEXT NOT NULL, last_seen_at TEXT NOT NULL,
|
|
732
|
+
PRIMARY KEY(workspace, agent, instance), CHECK(json_valid(capabilities) AND json_type(capabilities)='array')
|
|
733
|
+
);
|
|
734
|
+
CREATE INDEX IF NOT EXISTS bridge_presence_active ON bridge_presence(workspace, lease_expires_at);
|
|
735
|
+
CREATE TRIGGER IF NOT EXISTS bridge_messages_no_update BEFORE UPDATE ON bridge_messages BEGIN SELECT RAISE(ABORT, 'bridge messages are immutable'); END;
|
|
736
|
+
CREATE TRIGGER IF NOT EXISTS bridge_messages_no_delete BEFORE DELETE ON bridge_messages BEGIN SELECT RAISE(ABORT, 'bridge messages are immutable'); END;
|
|
737
|
+
`;
|
|
738
|
+
function stringify(value) {
|
|
739
|
+
return value === void 0 ? null : JSON.stringify(value);
|
|
740
|
+
}
|
|
741
|
+
function parse(value) {
|
|
742
|
+
return typeof value === "string" ? JSON.parse(value) : void 0;
|
|
743
|
+
}
|
|
744
|
+
function message(row) {
|
|
745
|
+
return { id: String(row.id), workspace: String(row.workspace), source: String(row.source), sequence: String(row.sequence), type: String(row.type), content: String(row.content), contentType: String(row.content_type), data: parse(row.data), targets: parse(row.targets) ?? [], threadId: row.thread_id, replyToId: row.reply_to_id, correlationId: row.correlation_id, causationId: row.causation_id, priority: row.priority, expiresAt: row.expires_at, idempotencyKey: row.idempotency_key, atribReceiptId: row.atrib_receipt_id, informedBy: parse(row.informed_by), metadata: parse(row.metadata), createdAt: String(row.created_at) };
|
|
746
|
+
}
|
|
747
|
+
function delivery(row) {
|
|
748
|
+
return { id: String(row.id), messageId: String(row.message_id), workspace: String(row.workspace), recipient: String(row.recipient), state: row.state, attempt: Number(row.attempt), availableAt: String(row.available_at), leaseToken: row.lease_token, leaseOwner: row.lease_owner, leaseExpiresAt: row.lease_expires_at, lastError: row.last_error };
|
|
749
|
+
}
|
|
750
|
+
function presence(row) {
|
|
751
|
+
return { workspace: String(row.workspace), agent: String(row.agent), instance: String(row.instance), runtimeType: row.runtime_type, capabilities: parse(row.capabilities) ?? [], leaseExpiresAt: String(row.lease_expires_at), lastSeenAt: String(row.last_seen_at) };
|
|
752
|
+
}
|
|
753
|
+
function deliveryEvent(row) {
|
|
754
|
+
return { sequence: String(row.sequence), deliveryId: String(row.delivery_id), messageId: String(row.message_id), workspace: String(row.workspace), recipient: String(row.recipient), fromState: row.from_state, toState: row.to_state, attempt: Number(row.attempt), leaseOwner: row.lease_owner, error: row.error, createdAt: String(row.created_at) };
|
|
755
|
+
}
|
|
756
|
+
var SQLiteBridgeStore = class {
|
|
757
|
+
constructor(path = ":memory:", busyTimeoutMs = 2e3) {
|
|
758
|
+
this.path = path;
|
|
759
|
+
this.busyTimeoutMs = busyTimeoutMs;
|
|
760
|
+
this.initialized = false;
|
|
761
|
+
this.db = openDatabase2(path);
|
|
762
|
+
this.restrictFiles();
|
|
763
|
+
}
|
|
764
|
+
restrictFiles() {
|
|
765
|
+
if (this.path === ":memory:") return;
|
|
766
|
+
for (const path of [this.path, `${this.path}-wal`, `${this.path}-shm`]) {
|
|
767
|
+
if (existsSync2(path)) chmodSync2(path, 384);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
async initialize() {
|
|
771
|
+
if (this.initialized) return;
|
|
772
|
+
const versionRow = this.db.prepare("SELECT sqlite_version() AS version").get();
|
|
773
|
+
const parts = String(versionRow.version).split(".").map(Number);
|
|
774
|
+
const encoded = (parts[0] ?? 0) * 1e6 + (parts[1] ?? 0) * 1e3 + (parts[2] ?? 0);
|
|
775
|
+
if (encoded < 3051003) throw new Error("SQLite 3.51.3 or newer is required");
|
|
776
|
+
this.db.exec(`PRAGMA busy_timeout = ${Math.max(1, Math.trunc(this.busyTimeoutMs))}; ${schema2}`);
|
|
777
|
+
this.restrictFiles();
|
|
778
|
+
this.initialized = true;
|
|
779
|
+
}
|
|
780
|
+
async ready() {
|
|
781
|
+
await this.initialize();
|
|
782
|
+
}
|
|
783
|
+
async insertMessage(input) {
|
|
784
|
+
await this.ready();
|
|
785
|
+
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
786
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
787
|
+
try {
|
|
788
|
+
if (input.idempotencyKey) {
|
|
789
|
+
const existing = this.db.prepare("SELECT * FROM bridge_messages WHERE workspace = ? AND source = ? AND idempotency_key = ?").get(input.workspace, input.source, input.idempotencyKey);
|
|
790
|
+
if (existing) {
|
|
791
|
+
const replay = message(existing);
|
|
792
|
+
assertIdempotentReplay(replay, input);
|
|
793
|
+
this.db.exec("COMMIT");
|
|
794
|
+
return { message: replay, created: false };
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
this.db.prepare(`INSERT INTO bridge_messages (id,workspace,source,type,content,content_type,data,targets,thread_id,reply_to_id,correlation_id,causation_id,priority,expires_at,idempotency_key,atrib_receipt_id,informed_by,metadata,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(input.id, input.workspace, input.source, input.type, input.content, input.contentType, stringify(input.data), JSON.stringify(input.targets), input.threadId ?? null, input.replyToId ?? null, input.correlationId ?? null, input.causationId ?? null, input.priority, input.expiresAt ?? null, input.idempotencyKey ?? null, input.atribReceiptId ?? null, stringify(input.informedBy), stringify(input.metadata), createdAt);
|
|
798
|
+
for (const recipient of input.targets) this.db.prepare("INSERT INTO bridge_deliveries (id,message_id,workspace,recipient,state,available_at) VALUES (?,?,?,?,?,?)").run(randomUUID2(), input.id, input.workspace, recipient, "pending", createdAt);
|
|
799
|
+
const row = this.db.prepare("SELECT * FROM bridge_messages WHERE id = ?").get(input.id);
|
|
800
|
+
this.db.exec("COMMIT");
|
|
801
|
+
return { message: message(row), created: true };
|
|
802
|
+
} catch (error) {
|
|
803
|
+
this.db.exec("ROLLBACK");
|
|
804
|
+
throw error;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
async listMessages(principal, query = {}) {
|
|
808
|
+
await this.ready();
|
|
809
|
+
const cursor = decodeCursor(query.cursor);
|
|
810
|
+
const limit = Math.min(Math.max(Math.trunc(query.limit ?? 50), 1), 200);
|
|
811
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
812
|
+
const highWaterRow = query.latest ? void 0 : this.db.prepare("SELECT max(sequence) AS sequence FROM bridge_messages WHERE workspace=?").get(principal.workspace);
|
|
813
|
+
const highWater = highWaterRow?.sequence === null || highWaterRow?.sequence === void 0 ? void 0 : String(highWaterRow.sequence);
|
|
814
|
+
const clauses = ["workspace = ?", query.latest ? "1=1" : "sequence > ?", "(targets = '[]' OR EXISTS (SELECT 1 FROM json_each(targets) WHERE value = ?))"];
|
|
815
|
+
const args = query.latest ? [principal.workspace, principal.agent] : [principal.workspace, cursor ?? "0", principal.agent];
|
|
816
|
+
if (highWater) {
|
|
817
|
+
clauses.push("sequence <= ?");
|
|
818
|
+
args.push(highWater);
|
|
819
|
+
}
|
|
820
|
+
if (!query.includeExpired) {
|
|
821
|
+
clauses.push("(expires_at IS NULL OR expires_at > ?)");
|
|
822
|
+
args.push(now);
|
|
823
|
+
}
|
|
824
|
+
if (query.types?.length) {
|
|
825
|
+
clauses.push(`type IN (${query.types.map(() => "?").join(",")})`);
|
|
826
|
+
args.push(...query.types);
|
|
827
|
+
}
|
|
828
|
+
if (query.source) {
|
|
829
|
+
clauses.push("source = ?");
|
|
830
|
+
args.push(query.source);
|
|
831
|
+
}
|
|
832
|
+
if (query.since) {
|
|
833
|
+
clauses.push("created_at >= ?");
|
|
834
|
+
args.push(query.since);
|
|
835
|
+
}
|
|
836
|
+
if (query.unacknowledgedBy) {
|
|
837
|
+
clauses.push("NOT EXISTS (SELECT 1 FROM bridge_receipts receipt WHERE receipt.workspace=bridge_messages.workspace AND receipt.message_id=bridge_messages.id AND receipt.principal=?)");
|
|
838
|
+
args.push(query.unacknowledgedBy);
|
|
839
|
+
}
|
|
840
|
+
if (query.threadId) {
|
|
841
|
+
clauses.push("thread_id = ?");
|
|
842
|
+
args.push(query.threadId);
|
|
843
|
+
}
|
|
844
|
+
const rows = this.db.prepare(`SELECT * FROM bridge_messages WHERE ${clauses.join(" AND ")} ORDER BY sequence ${query.latest ? "DESC" : "ASC"} LIMIT ?`).all(...args, limit);
|
|
845
|
+
const messages = rows.map(message);
|
|
846
|
+
const last = messages[messages.length - 1];
|
|
847
|
+
if (query.latest) return { messages, cursor: messages[0] ? encodeCursor(messages[0].sequence) : query.cursor };
|
|
848
|
+
if (messages.length === limit) return { messages, cursor: encodeCursor(last.sequence) };
|
|
849
|
+
return { messages, cursor: highWater ? encodeCursor(highWater) : query.cursor };
|
|
850
|
+
}
|
|
851
|
+
async recordReceipt(workspace, messageIds, principal, readAt = /* @__PURE__ */ new Date()) {
|
|
852
|
+
await this.ready();
|
|
853
|
+
const stmt = this.db.prepare("INSERT OR IGNORE INTO bridge_receipts (workspace,message_id,principal,read_at) SELECT workspace,id,?,? FROM bridge_messages WHERE workspace=? AND id=? AND (targets='[]' OR EXISTS (SELECT 1 FROM json_each(targets) WHERE value=?))");
|
|
854
|
+
let changed = 0;
|
|
855
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
856
|
+
try {
|
|
857
|
+
for (const id of messageIds) changed += Number(stmt.run(principal, readAt.toISOString(), workspace, id, principal).changes);
|
|
858
|
+
this.db.exec("COMMIT");
|
|
859
|
+
return changed;
|
|
860
|
+
} catch (e) {
|
|
861
|
+
this.db.exec("ROLLBACK");
|
|
862
|
+
throw e;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
async claimDelivery(principal, options) {
|
|
866
|
+
await this.ready();
|
|
867
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
868
|
+
const nowText = now.toISOString();
|
|
869
|
+
const expires = new Date(now.getTime() + options.leaseMs).toISOString();
|
|
870
|
+
const owner = principal.instance ?? principal.agent;
|
|
871
|
+
const maxAttempts = options.maxAttempts ?? 5;
|
|
872
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
873
|
+
try {
|
|
874
|
+
this.db.prepare("UPDATE bridge_deliveries SET state='dead', last_error='message expired', lease_token=NULL, lease_owner=NULL, lease_expires_at=NULL WHERE workspace=? AND recipient=? AND state IN ('pending','retrying','claimed') AND EXISTS (SELECT 1 FROM bridge_messages message WHERE message.workspace=bridge_deliveries.workspace AND message.id=bridge_deliveries.message_id AND message.expires_at IS NOT NULL AND message.expires_at <= ?)").run(principal.workspace, principal.agent, nowText);
|
|
875
|
+
this.db.prepare("UPDATE bridge_deliveries SET state='dead', last_error='maximum attempts reached', lease_token=NULL, lease_owner=NULL, lease_expires_at=NULL WHERE workspace=? AND recipient=? AND attempt>=? AND (state IN ('pending','retrying') OR (state='claimed' AND lease_expires_at<=?))").run(principal.workspace, principal.agent, maxAttempts, nowText);
|
|
876
|
+
this.db.prepare("UPDATE bridge_deliveries SET state='retrying', lease_token=NULL, lease_owner=NULL, lease_expires_at=NULL WHERE workspace=? AND recipient=? AND state='claimed' AND lease_expires_at <= ? AND attempt<?").run(principal.workspace, principal.agent, nowText, maxAttempts);
|
|
877
|
+
const candidate = this.db.prepare("SELECT delivery.id FROM bridge_deliveries delivery JOIN bridge_messages message ON message.workspace=delivery.workspace AND message.id=delivery.message_id WHERE delivery.workspace=? AND delivery.recipient=? AND delivery.state IN ('pending','retrying') AND delivery.available_at <= ? AND delivery.attempt<? AND (message.expires_at IS NULL OR message.expires_at > ?) ORDER BY delivery.available_at,delivery.id LIMIT 1").get(principal.workspace, principal.agent, nowText, maxAttempts, nowText);
|
|
878
|
+
if (!candidate) {
|
|
879
|
+
this.db.exec("COMMIT");
|
|
880
|
+
return null;
|
|
881
|
+
}
|
|
882
|
+
const candidateId = String(candidate.id);
|
|
883
|
+
const token = randomUUID2();
|
|
884
|
+
this.db.prepare("UPDATE bridge_deliveries SET state='claimed', attempt=attempt+1, lease_token=?, lease_owner=?, lease_expires_at=? WHERE id=?").run(token, owner, expires, candidateId);
|
|
885
|
+
const claimed = this.db.prepare("SELECT * FROM bridge_deliveries WHERE id=?").get(candidateId);
|
|
886
|
+
this.db.exec("COMMIT");
|
|
887
|
+
return delivery(claimed);
|
|
888
|
+
} catch (e) {
|
|
889
|
+
this.db.exec("ROLLBACK");
|
|
890
|
+
throw e;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
async renewDelivery(principal, id, token, leaseMs) {
|
|
894
|
+
await this.ready();
|
|
895
|
+
const now = /* @__PURE__ */ new Date();
|
|
896
|
+
const expires = new Date(now.getTime() + leaseMs).toISOString();
|
|
897
|
+
const owner = principal.instance ?? principal.agent;
|
|
898
|
+
const result = this.db.prepare("UPDATE bridge_deliveries SET lease_expires_at=? WHERE workspace=? AND recipient=? AND lease_owner=? AND id=? AND lease_token=? AND state='claimed' AND lease_expires_at > ?").run(expires, principal.workspace, principal.agent, owner, id, token, now.toISOString());
|
|
899
|
+
if (!result.changes) return null;
|
|
900
|
+
return delivery(this.db.prepare("SELECT * FROM bridge_deliveries WHERE id=?").get(id));
|
|
901
|
+
}
|
|
902
|
+
async settleDelivery(principal, id, token, state, error, retryPolicy) {
|
|
903
|
+
await this.ready();
|
|
904
|
+
const now = /* @__PURE__ */ new Date();
|
|
905
|
+
const owner = principal.instance ?? principal.agent;
|
|
906
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
907
|
+
try {
|
|
908
|
+
const current = this.db.prepare("SELECT * FROM bridge_deliveries WHERE workspace=? AND recipient=? AND lease_owner=? AND id=? AND lease_token=? AND state='claimed' AND lease_expires_at > ?").get(principal.workspace, principal.agent, owner, id, token, now.toISOString());
|
|
909
|
+
if (!current) {
|
|
910
|
+
this.db.exec("COMMIT");
|
|
911
|
+
return null;
|
|
912
|
+
}
|
|
913
|
+
const attempt = Number(current.attempt);
|
|
914
|
+
const nextState = state === "retrying" && attempt >= retryPolicy.maxAttempts ? "dead" : state;
|
|
915
|
+
const exponential = Math.min(retryPolicy.maxDelayMs, retryPolicy.baseDelayMs * 2 ** Math.max(0, attempt - 1));
|
|
916
|
+
const jitter = 1 + (Math.random() * 2 - 1) * retryPolicy.jitterRatio;
|
|
917
|
+
const delay = nextState === "retrying" ? Math.max(1, Math.round(exponential * jitter)) : 0;
|
|
918
|
+
const available = new Date(now.getTime() + delay).toISOString();
|
|
919
|
+
this.db.prepare("UPDATE bridge_deliveries SET state=?, available_at=?, last_error=?, lease_token=NULL, lease_owner=NULL, lease_expires_at=NULL WHERE id=?").run(nextState, available, error?.slice(0, 1024) ?? null, id);
|
|
920
|
+
const result = delivery(this.db.prepare("SELECT * FROM bridge_deliveries WHERE id=?").get(id));
|
|
921
|
+
this.db.exec("COMMIT");
|
|
922
|
+
return result;
|
|
923
|
+
} catch (caught) {
|
|
924
|
+
this.db.exec("ROLLBACK");
|
|
925
|
+
throw caught;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
async diagnostics(principal) {
|
|
929
|
+
await this.ready();
|
|
930
|
+
const rows = this.db.prepare("SELECT state, count(*) AS count, min(available_at) AS oldest FROM bridge_deliveries WHERE workspace=? AND recipient=? GROUP BY state").all(principal.workspace, principal.agent);
|
|
931
|
+
const counts = new Map(rows.map((row) => [String(row.state), Number(row.count)]));
|
|
932
|
+
const oldest = rows.filter((row) => row.state === "pending" || row.state === "retrying").map((row) => row.oldest ? String(row.oldest) : void 0).filter(Boolean).sort()[0];
|
|
933
|
+
return { schemaVersion: "local-v2", deliverySupported: true, pending: counts.get("pending") ?? 0, claimed: counts.get("claimed") ?? 0, retrying: counts.get("retrying") ?? 0, dead: counts.get("dead") ?? 0, oldestAvailableAt: oldest };
|
|
934
|
+
}
|
|
935
|
+
async heartbeat(principal, leaseMs, runtimeType, capabilities = []) {
|
|
936
|
+
await this.ready();
|
|
937
|
+
const now = /* @__PURE__ */ new Date();
|
|
938
|
+
const nowText = now.toISOString();
|
|
939
|
+
const expires = new Date(now.getTime() + leaseMs).toISOString();
|
|
940
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
941
|
+
try {
|
|
942
|
+
this.db.prepare("DELETE FROM bridge_presence WHERE workspace=? AND lease_expires_at<=?").run(principal.workspace, nowText);
|
|
943
|
+
const current = this.db.prepare("SELECT 1 FROM bridge_presence WHERE workspace=? AND agent=? AND instance=?").get(principal.workspace, principal.agent, principal.instance);
|
|
944
|
+
const agentCount = this.db.prepare("SELECT count(*) AS count FROM bridge_presence WHERE workspace=? AND agent=?").get(principal.workspace, principal.agent);
|
|
945
|
+
const workspaceCount = this.db.prepare("SELECT count(*) AS count FROM bridge_presence WHERE workspace=?").get(principal.workspace);
|
|
946
|
+
if (!current && (Number(agentCount.count) >= 128 || Number(workspaceCount.count) >= 4096)) {
|
|
947
|
+
throw Object.assign(new Error("active instance limit reached"), {
|
|
948
|
+
status: 429,
|
|
949
|
+
code: "presence_limit"
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
this.db.prepare("INSERT INTO bridge_presence (workspace,agent,instance,runtime_type,capabilities,lease_expires_at,last_seen_at) VALUES (?,?,?,?,?,?,?) ON CONFLICT(workspace,agent,instance) DO UPDATE SET runtime_type=excluded.runtime_type, capabilities=excluded.capabilities, lease_expires_at=excluded.lease_expires_at, last_seen_at=excluded.last_seen_at").run(principal.workspace, principal.agent, principal.instance, runtimeType ?? null, JSON.stringify(capabilities), expires, nowText);
|
|
953
|
+
const result = presence(this.db.prepare("SELECT * FROM bridge_presence WHERE workspace=? AND agent=? AND instance=?").get(principal.workspace, principal.agent, principal.instance));
|
|
954
|
+
this.db.exec("COMMIT");
|
|
955
|
+
return result;
|
|
956
|
+
} catch (error) {
|
|
957
|
+
this.db.exec("ROLLBACK");
|
|
958
|
+
throw error;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
async listPresence(principal) {
|
|
962
|
+
await this.ready();
|
|
963
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
964
|
+
this.db.prepare("DELETE FROM bridge_presence WHERE workspace=? AND lease_expires_at<=?").run(principal.workspace, now);
|
|
965
|
+
const rows = this.db.prepare("SELECT * FROM bridge_presence WHERE workspace=? ORDER BY agent,instance").all(principal.workspace);
|
|
966
|
+
return rows.map(presence);
|
|
967
|
+
}
|
|
968
|
+
async listDeliveryEvents(deliveryId) {
|
|
969
|
+
await this.ready();
|
|
970
|
+
const rows = this.db.prepare("SELECT * FROM bridge_delivery_events WHERE delivery_id=? ORDER BY sequence").all(deliveryId);
|
|
971
|
+
return rows.map(deliveryEvent);
|
|
972
|
+
}
|
|
973
|
+
async close() {
|
|
974
|
+
this.db.close();
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
export {
|
|
979
|
+
EdgeConflictError,
|
|
980
|
+
edgeMessageFingerprint,
|
|
981
|
+
stableIdempotency,
|
|
982
|
+
edgeScopeKey,
|
|
983
|
+
SQLiteEdgeStore,
|
|
984
|
+
isRetryableSyncError,
|
|
985
|
+
SyncingBridgeStore,
|
|
986
|
+
SQLiteBridgeStore
|
|
987
|
+
};
|
|
988
|
+
//# sourceMappingURL=chunk-WEULPMUY.js.map
|