a2a-exposed 0.8.16 → 0.8.17
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/package.json +1 -1
- package/worker/migrations/0010_conversation_peer.sql +25 -0
- package/worker/migrations/0011_conversation_owner.sql +34 -0
- package/worker/src/export.ts +1 -1
- package/worker/src/index.ts +150 -40
- package/worker/src/migrations.ts +4 -0
- package/worker/src/version.ts +1 -1
- package/worker/test/context-peer.test.ts +171 -0
- package/worker/test/migrations.test.ts +40 -5
package/package.json
CHANGED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
-- A wake is one peer's conversation. Two peers can use the same context id without sharing a row.
|
|
2
|
+
CREATE TABLE wakes_peer (
|
|
3
|
+
context_id TEXT NOT NULL,
|
|
4
|
+
peer TEXT NOT NULL DEFAULT '',
|
|
5
|
+
last_sent_ms INTEGER NOT NULL DEFAULT 0,
|
|
6
|
+
pending_json TEXT,
|
|
7
|
+
pending_since_ms INTEGER,
|
|
8
|
+
PRIMARY KEY (context_id, peer)
|
|
9
|
+
);
|
|
10
|
+
INSERT INTO wakes_peer (context_id, peer, last_sent_ms, pending_json, pending_since_ms)
|
|
11
|
+
SELECT
|
|
12
|
+
w.context_id,
|
|
13
|
+
COALESCE(
|
|
14
|
+
NULLIF(json_extract(w.pending_json, '$.from'), ''),
|
|
15
|
+
(SELECT t.peer FROM tasks t WHERE t.context_id = w.context_id AND t.peer IS NOT NULL AND t.peer != '' ORDER BY t.created_at, t.id LIMIT 1),
|
|
16
|
+
(SELECT h.peer FROM history h WHERE h.context_id = w.context_id AND h.peer IS NOT NULL AND h.peer != '' ORDER BY h.seq LIMIT 1),
|
|
17
|
+
''
|
|
18
|
+
),
|
|
19
|
+
w.last_sent_ms,
|
|
20
|
+
w.pending_json,
|
|
21
|
+
w.pending_since_ms
|
|
22
|
+
FROM wakes w;
|
|
23
|
+
DROP TABLE wakes;
|
|
24
|
+
ALTER TABLE wakes_peer RENAME TO wakes;
|
|
25
|
+
CREATE INDEX IF NOT EXISTS history_peer_ctx ON history(peer, context_id, seq);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
-- One owner per context id. The first peer to insert the row keeps it (ON CONFLICT DO NOTHING).
|
|
2
|
+
CREATE TABLE conversation_owners (
|
|
3
|
+
context_id TEXT NOT NULL PRIMARY KEY,
|
|
4
|
+
peer TEXT NOT NULL,
|
|
5
|
+
created_at TEXT NOT NULL
|
|
6
|
+
);
|
|
7
|
+
INSERT INTO conversation_owners (context_id, peer, created_at)
|
|
8
|
+
SELECT t.context_id, t.peer, t.created_at
|
|
9
|
+
FROM tasks t
|
|
10
|
+
WHERE t.peer IS NOT NULL AND t.peer != ''
|
|
11
|
+
AND NOT EXISTS (
|
|
12
|
+
SELECT 1 FROM tasks t2
|
|
13
|
+
WHERE t2.context_id = t.context_id AND t2.peer IS NOT NULL AND t2.peer != ''
|
|
14
|
+
AND (t2.created_at < t.created_at OR (t2.created_at = t.created_at AND t2.id < t.id))
|
|
15
|
+
);
|
|
16
|
+
INSERT INTO conversation_owners (context_id, peer, created_at)
|
|
17
|
+
SELECT h.context_id, h.peer, h.ts
|
|
18
|
+
FROM history h
|
|
19
|
+
WHERE h.peer IS NOT NULL AND h.peer != ''
|
|
20
|
+
AND NOT EXISTS (SELECT 1 FROM conversation_owners o WHERE o.context_id = h.context_id)
|
|
21
|
+
AND NOT EXISTS (
|
|
22
|
+
SELECT 1 FROM history h2
|
|
23
|
+
WHERE h2.context_id = h.context_id AND h2.peer IS NOT NULL AND h2.peer != '' AND h2.seq < h.seq
|
|
24
|
+
);
|
|
25
|
+
INSERT INTO conversation_owners (context_id, peer, created_at)
|
|
26
|
+
SELECT o.context_id, o.peer, o.sent_at
|
|
27
|
+
FROM outbound o
|
|
28
|
+
WHERE o.peer IS NOT NULL AND o.peer != ''
|
|
29
|
+
AND NOT EXISTS (SELECT 1 FROM conversation_owners c WHERE c.context_id = o.context_id)
|
|
30
|
+
AND NOT EXISTS (
|
|
31
|
+
SELECT 1 FROM outbound o2
|
|
32
|
+
WHERE o2.context_id = o.context_id AND o2.peer IS NOT NULL AND o2.peer != ''
|
|
33
|
+
AND (o2.sent_at < o.sent_at OR (o2.sent_at = o.sent_at AND o2.task_id < o.task_id))
|
|
34
|
+
);
|
package/worker/src/export.ts
CHANGED
|
@@ -16,7 +16,7 @@ export const EXPORT_TABLES = [
|
|
|
16
16
|
"peers", "tasks", "messages", "history", "outbound", "wakes",
|
|
17
17
|
"rate", "wake_budget", "device_requests", "pairing_rate", "settings",
|
|
18
18
|
"facade_owners", "oauth_clients", "oauth_codes", "mcp_grants",
|
|
19
|
-
"outbound_peers", "oauth_client_metadata", "oidc_txns",
|
|
19
|
+
"outbound_peers", "oauth_client_metadata", "oidc_txns", "conversation_owners",
|
|
20
20
|
] as const;
|
|
21
21
|
|
|
22
22
|
export type ExportTable = (typeof EXPORT_TABLES)[number];
|
package/worker/src/index.ts
CHANGED
|
@@ -67,6 +67,49 @@ function histStmt(ctx: TenantContext, contextId: string, e: Json) {
|
|
|
67
67
|
e.event ?? null, e.text ?? null, e.data !== undefined ? JSON.stringify(e.data) : null);
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
/** Claim an unused context for this peer. `conversation_owners.context_id` is unique, and the insert does nothing
|
|
71
|
+
* when another peer already holds it or already has a task, history row, or outbound task on that id. */
|
|
72
|
+
function claimContextStmt(ctx: TenantContext, contextId: string, peer: string, ts: string) {
|
|
73
|
+
return ctx.DB.prepare(
|
|
74
|
+
`INSERT INTO conversation_owners (context_id, peer, created_at)
|
|
75
|
+
SELECT ?1, ?2, ?3
|
|
76
|
+
WHERE NOT EXISTS (SELECT 1 FROM conversation_owners WHERE context_id = ?1 AND peer != ?2)
|
|
77
|
+
AND NOT EXISTS (SELECT 1 FROM tasks WHERE context_id = ?1 AND peer IS NOT NULL AND peer != '' AND peer != ?2)
|
|
78
|
+
AND NOT EXISTS (SELECT 1 FROM history WHERE context_id = ?1 AND peer IS NOT NULL AND peer != '' AND peer != ?2)
|
|
79
|
+
AND NOT EXISTS (SELECT 1 FROM outbound WHERE context_id = ?1 AND peer IS NOT NULL AND peer != '' AND peer != ?2)
|
|
80
|
+
ON CONFLICT(context_id) DO NOTHING`,
|
|
81
|
+
).bind(contextId, peer, ts);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A new task is stored only when this peer owns the context. Runs in the same batch as `claimContextStmt`. */
|
|
85
|
+
function saveTaskIfOwnerStmt(ctx: TenantContext, t: Json) {
|
|
86
|
+
return ctx.DB.prepare(
|
|
87
|
+
`INSERT INTO tasks (id, context_id, peer, state, protocol, created_at, updated_at, status_json, artifacts_json, metadata_json, push_configs_json)
|
|
88
|
+
SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11
|
|
89
|
+
WHERE (SELECT peer FROM conversation_owners WHERE context_id = ?2) = ?3
|
|
90
|
+
ON CONFLICT(id) DO UPDATE SET state=?4, updated_at=?7, status_json=?8, artifacts_json=?9, metadata_json=?10, push_configs_json=?11
|
|
91
|
+
WHERE (SELECT peer FROM conversation_owners WHERE context_id = ?2) = ?3`,
|
|
92
|
+
).bind(t.id, t.contextId, t._peer, t.status.state, t._protocol, t._createdAt, A.nowIso(), JSON.stringify(t.status),
|
|
93
|
+
JSON.stringify(t.artifacts || []), t.metadata ? JSON.stringify(t.metadata) : null, JSON.stringify(t._push || []));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function msgIfOwnerStmt(ctx: TenantContext, t: Json, m: Json) {
|
|
97
|
+
return ctx.DB.prepare(
|
|
98
|
+
`INSERT INTO messages (message_id, task_id, context_id, role, ts, message_json)
|
|
99
|
+
SELECT ?1, ?2, ?3, ?4, ?5, ?6
|
|
100
|
+
WHERE (SELECT peer FROM conversation_owners WHERE context_id = ?3) = ?7`,
|
|
101
|
+
).bind(m.messageId, t.id, t.contextId, m.role, A.nowIso(), JSON.stringify(m), t._peer);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function histIfOwnerStmt(ctx: TenantContext, contextId: string, e: Json, owner: string) {
|
|
105
|
+
return ctx.DB.prepare(
|
|
106
|
+
`INSERT INTO history (context_id, ts, dir, peer, task_id, role, state, event, text, data_json)
|
|
107
|
+
SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10
|
|
108
|
+
WHERE (SELECT peer FROM conversation_owners WHERE context_id = ?1) = ?11`,
|
|
109
|
+
).bind(contextId, e.ts || A.nowIso(), e.dir || "local", e.peer ?? null, e.taskId ?? null, e.role ?? null, e.state ?? null,
|
|
110
|
+
e.event ?? null, e.text ?? null, e.data !== undefined ? JSON.stringify(e.data) : null, owner);
|
|
111
|
+
}
|
|
112
|
+
|
|
70
113
|
// ------------------------------------------------------------------ self-aware fetch (a Worker cannot reliably fetch its own custom domain)
|
|
71
114
|
/**
|
|
72
115
|
* Another tenant on this deployment's domain. A public fetch of that hostname returns 522, so the call
|
|
@@ -118,7 +161,7 @@ async function doFetch(ctx: TenantContext, ectx: ExecutionContext, url: string,
|
|
|
118
161
|
return fetch(url, { ...init, signal: AbortSignal.timeout(15000) });
|
|
119
162
|
}
|
|
120
163
|
|
|
121
|
-
// ------------------------------------------------------------------ wake webhook (presets), debounced per context via D1
|
|
164
|
+
// ------------------------------------------------------------------ wake webhook (presets), debounced per peer and context via D1
|
|
122
165
|
const preset = (ctx: TenantContext) => (ctx.WAKE_PRESET || "generic").trim();
|
|
123
166
|
|
|
124
167
|
function wakeConfig(ctx: TenantContext): WakeConfig {
|
|
@@ -207,6 +250,21 @@ const WAKE_RETRIES = 3;
|
|
|
207
250
|
* flush it once Retry-After (30 s - 1 h) has passed, on the next request to the Worker or the optional cron. At most
|
|
208
251
|
* WAKE_RETRIES times per wake; a newer message for the conversation merges in and starts over. Pairing and test wakes
|
|
209
252
|
* are not retried (a pairing code lasts 60 minutes). */
|
|
253
|
+
function pendingWakePeer(pending: string | null | undefined): string {
|
|
254
|
+
if (!pending) return "";
|
|
255
|
+
try {
|
|
256
|
+
const from = JSON.parse(pending)?.from;
|
|
257
|
+
return typeof from === "string" ? from : "";
|
|
258
|
+
} catch { return ""; }
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The wake row for this peer's conversation. A row stored before peer was part of the key has peer ''. */
|
|
262
|
+
async function loadWake(ctx: TenantContext, contextId: string, peer: string): Promise<Json | null> {
|
|
263
|
+
const exact: Json = await ctx.DB.prepare("SELECT * FROM wakes WHERE context_id = ? AND peer = ?").bind(contextId, peer).first();
|
|
264
|
+
if (exact || !peer) return exact;
|
|
265
|
+
return ctx.DB.prepare("SELECT * FROM wakes WHERE context_id = ? AND peer = ''").bind(contextId).first();
|
|
266
|
+
}
|
|
267
|
+
|
|
210
268
|
async function requeueWake(ctx: TenantContext, ectx: ExecutionContext, payload: Json, retryAfter: string | null) {
|
|
211
269
|
if (payload.kind !== "inbound") return;
|
|
212
270
|
const attempts = (Number(payload.attempts) || 0) + 1;
|
|
@@ -214,16 +272,18 @@ async function requeueWake(ctx: TenantContext, ectx: ExecutionContext, payload:
|
|
|
214
272
|
const secs = Number(retryAfter);
|
|
215
273
|
const waitMs = Math.min(3600, Math.max(30, Number.isFinite(secs) && secs > 0 ? secs : 60)) * 1000;
|
|
216
274
|
const now = Date.now(), contextId = payload.contextId;
|
|
217
|
-
const
|
|
275
|
+
const peer = typeof payload.from === "string" ? payload.from : "";
|
|
276
|
+
const cur: Json = await loadWake(ctx, contextId, peer);
|
|
218
277
|
const prev = cur?.pending_json ? JSON.parse(cur.pending_json) : null;
|
|
219
278
|
const merged = { ...payload, attempts, taskIds: [...new Set([...(prev?.taskIds || []), ...(payload.taskIds || [])])] };
|
|
220
279
|
// flushWake and nextCronAt wait until last_sent_ms + debounce. Store Retry-After minus that debounce so the
|
|
221
280
|
// deadline is Retry-After itself, including when the debounce is longer than Retry-After. Do not keep the
|
|
222
281
|
// previous last_sent_ms: that clock is the send we just made, and keeping it would wait out the debounce.
|
|
223
282
|
const due = now + waitMs - debounceMs(ctx);
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
283
|
+
const rowPeer = cur && (cur.peer === peer || cur.peer === "" || cur.peer == null) ? (cur.peer ?? "") : peer;
|
|
284
|
+
await ctx.DB.prepare(`INSERT INTO wakes (context_id, peer, last_sent_ms, pending_json, pending_since_ms) VALUES (?, ?, ?, ?, ?)
|
|
285
|
+
ON CONFLICT(context_id, peer) DO UPDATE SET pending_json = excluded.pending_json, last_sent_ms = excluded.last_sent_ms,
|
|
286
|
+
pending_since_ms = COALESCE(wakes.pending_since_ms, excluded.pending_since_ms)`).bind(contextId, rowPeer === "" ? peer : rowPeer, due, JSON.stringify(merged), now).run();
|
|
227
287
|
log("wake_requeued", { contextId, retryInS: Math.round(waitMs / 1000), attempt: attempts });
|
|
228
288
|
// The row exists now. A hosted alarm has to be set from this turn: the request that started sendWake may already have returned.
|
|
229
289
|
await noteWakeWrite(ectx);
|
|
@@ -232,33 +292,45 @@ async function requeueWake(ctx: TenantContext, ectx: ExecutionContext, payload:
|
|
|
232
292
|
async function wake(ctx: TenantContext, ectx: ExecutionContext, contextId: string, taskId: string, from: string, preview: string, kind = "inbound") {
|
|
233
293
|
const payload: Json = { contextId, taskId, taskIds: [taskId], from, preview: preview.slice(0, 300), kind };
|
|
234
294
|
const now = Date.now(), deb = debounceMs(ctx);
|
|
235
|
-
|
|
295
|
+
let row: Json = await loadWake(ctx, contextId, from);
|
|
296
|
+
// A pre-peer row (peer '') is this conversation when it names this peer, or names nobody yet.
|
|
297
|
+
// Another peer's legacy row stays put; this peer gets its own row.
|
|
298
|
+
if (row && row.peer === "" && from) {
|
|
299
|
+
const named = pendingWakePeer(row.pending_json);
|
|
300
|
+
if (!named || named === from) {
|
|
301
|
+
const moved = await ctx.DB.prepare("UPDATE wakes SET peer = ? WHERE context_id = ? AND peer = ''").bind(from, contextId).run();
|
|
302
|
+
if (changed(moved) === 1) row = { ...row, peer: from };
|
|
303
|
+
else row = await ctx.DB.prepare("SELECT * FROM wakes WHERE context_id = ? AND peer = ?").bind(contextId, from).first();
|
|
304
|
+
} else row = null;
|
|
305
|
+
}
|
|
306
|
+
const peer = row?.peer ?? from;
|
|
236
307
|
let claimed = false;
|
|
237
308
|
if (!row) {
|
|
238
|
-
const r = await ctx.DB.prepare("INSERT INTO wakes (context_id, last_sent_ms) VALUES (?, ?) ON CONFLICT DO NOTHING").bind(contextId, now).run();
|
|
309
|
+
const r = await ctx.DB.prepare("INSERT INTO wakes (context_id, peer, last_sent_ms) VALUES (?, ?, ?) ON CONFLICT DO NOTHING").bind(contextId, peer, now).run();
|
|
239
310
|
claimed = r.meta.changes === 1;
|
|
240
311
|
} else if (!row.pending_json && now - row.last_sent_ms >= deb) {
|
|
241
|
-
const r = await ctx.DB.prepare("UPDATE wakes SET last_sent_ms = ? WHERE context_id = ? AND last_sent_ms = ? AND pending_json IS NULL")
|
|
242
|
-
.bind(now, contextId, row.last_sent_ms).run();
|
|
312
|
+
const r = await ctx.DB.prepare("UPDATE wakes SET last_sent_ms = ? WHERE context_id = ? AND peer = ? AND last_sent_ms = ? AND pending_json IS NULL")
|
|
313
|
+
.bind(now, contextId, peer, row.last_sent_ms).run();
|
|
243
314
|
claimed = r.meta.changes === 1;
|
|
244
315
|
}
|
|
245
316
|
if (claimed && (await wakeBudgetOk(ctx))) { ectx.waitUntil(sendWake(ctx, ectx, payload)); return; }
|
|
246
317
|
// debounce window (or hourly cap reached): merge into the pending wake and flush it later
|
|
247
|
-
const cur: Json = await ctx
|
|
318
|
+
const cur: Json = await loadWake(ctx, contextId, from);
|
|
319
|
+
const curPeer = cur?.peer ?? peer;
|
|
248
320
|
const prev = cur?.pending_json ? JSON.parse(cur.pending_json) : null;
|
|
249
321
|
payload.taskIds = [...new Set([...(prev?.taskIds || []), taskId])];
|
|
250
|
-
await ctx.DB.prepare("UPDATE wakes SET pending_json = ?, pending_since_ms = COALESCE(pending_since_ms, ?) WHERE context_id = ?")
|
|
251
|
-
.bind(JSON.stringify(payload), now, contextId).run();
|
|
322
|
+
await ctx.DB.prepare("UPDATE wakes SET pending_json = ?, pending_since_ms = COALESCE(pending_since_ms, ?) WHERE context_id = ? AND peer = ?")
|
|
323
|
+
.bind(JSON.stringify(payload), now, contextId, curPeer).run();
|
|
252
324
|
// The pending row exists now. A hosted alarm is set in this turn, including when the delay is too long for waitUntil.
|
|
253
325
|
await noteWakeWrite(ectx);
|
|
254
326
|
const delay = Math.max(0, (cur?.last_sent_ms || now) + deb - now) + 100;
|
|
255
327
|
// waitUntil can outlive the response by ~30s. Longer windows are flushed by a later request, the optional
|
|
256
328
|
// single-inbox cron, or the registered alarm (set above).
|
|
257
|
-
if (delay <= 25000) ectx.waitUntil(new Promise((res) => setTimeout(res, delay)).then(() => flushWake(ctx, ectx, contextId)));
|
|
329
|
+
if (delay <= 25000) ectx.waitUntil(new Promise((res) => setTimeout(res, delay)).then(() => flushWake(ctx, ectx, contextId, curPeer)));
|
|
258
330
|
}
|
|
259
331
|
|
|
260
|
-
async function flushWake(ctx: TenantContext, ectx: ExecutionContext, contextId: string) {
|
|
261
|
-
const row: Json = await ctx.DB.prepare("SELECT * FROM wakes WHERE context_id = ?").bind(contextId).first();
|
|
332
|
+
async function flushWake(ctx: TenantContext, ectx: ExecutionContext, contextId: string, peer: string) {
|
|
333
|
+
const row: Json = await ctx.DB.prepare("SELECT * FROM wakes WHERE context_id = ? AND peer = ?").bind(contextId, peer).first();
|
|
262
334
|
if (!row || !row.pending_json) return;
|
|
263
335
|
const now = Date.now();
|
|
264
336
|
if (now - row.last_sent_ms < debounceMs(ctx)) return;
|
|
@@ -268,16 +340,16 @@ async function flushWake(ctx: TenantContext, ectx: ExecutionContext, contextId:
|
|
|
268
340
|
if ((b?.count ?? 0) >= maxPerHour(ctx)) return; // keep pending until the next hour
|
|
269
341
|
}
|
|
270
342
|
const r = await ctx.DB.prepare(
|
|
271
|
-
"UPDATE wakes SET pending_json = NULL, pending_since_ms = NULL, last_sent_ms = ? WHERE context_id = ? AND last_sent_ms = ? AND pending_json IS NOT NULL",
|
|
272
|
-
).bind(now, contextId, row.last_sent_ms).run();
|
|
343
|
+
"UPDATE wakes SET pending_json = NULL, pending_since_ms = NULL, last_sent_ms = ? WHERE context_id = ? AND peer = ? AND last_sent_ms = ? AND pending_json IS NOT NULL",
|
|
344
|
+
).bind(now, contextId, peer, row.last_sent_ms).run();
|
|
273
345
|
if (r.meta.changes === 1 && (await wakeBudgetOk(ctx))) await sendWake(ctx, ectx, JSON.parse(row.pending_json));
|
|
274
346
|
}
|
|
275
347
|
|
|
276
348
|
/** Flush every pending wake whose debounce window has passed (called opportunistically and from cron). */
|
|
277
349
|
async function flushDue(ctx: TenantContext, ectx: ExecutionContext) {
|
|
278
|
-
const rows = await ctx.DB.prepare("SELECT context_id FROM wakes WHERE pending_json IS NOT NULL AND last_sent_ms <= ? LIMIT 20")
|
|
350
|
+
const rows = await ctx.DB.prepare("SELECT context_id, peer FROM wakes WHERE pending_json IS NOT NULL AND last_sent_ms <= ? LIMIT 20")
|
|
279
351
|
.bind(Date.now() - debounceMs(ctx)).all();
|
|
280
|
-
for (const r of rows.results as Json[]) await flushWake(ctx, ectx, r.context_id);
|
|
352
|
+
for (const r of rows.results as Json[]) await flushWake(ctx, ectx, r.context_id, typeof r.peer === "string" ? r.peer : "");
|
|
281
353
|
}
|
|
282
354
|
|
|
283
355
|
/**
|
|
@@ -602,6 +674,10 @@ async function ownedTask(ctx: TenantContext, id: unknown, label: string): Promis
|
|
|
602
674
|
return t;
|
|
603
675
|
}
|
|
604
676
|
|
|
677
|
+
/** A contextId this caller does not get to use. The same sentence is returned for an id the façade has no
|
|
678
|
+
* record of. It does not say whether the id exists, or which peer holds it. */
|
|
679
|
+
const UNKNOWN_CONTEXT = "Invalid params: unknown contextId (omit contextId to start a new conversation, then use the one returned)";
|
|
680
|
+
|
|
605
681
|
function normPushCfg(cfg: Json, version: string): Json {
|
|
606
682
|
if (!cfg || typeof cfg !== "object" || typeof cfg.url !== "string") throw new RpcError(-32602, "push notification config needs url");
|
|
607
683
|
const out: Json = { id: typeof cfg.id === "string" && cfg.id ? cfg.id.slice(0, 128) : A.newId(), url: cfg.url, _version: version };
|
|
@@ -634,6 +710,11 @@ const rpcSend: Rpc = async (params, label, version, ctx, ectx) => {
|
|
|
634
710
|
}
|
|
635
711
|
const contextId = task ? task.contextId : msg.contextId ? A.checkId(msg.contextId, "contextId") : A.newId();
|
|
636
712
|
const ts = A.nowIso();
|
|
713
|
+
// A client-provided id nobody owns is still this peer's new conversation (single-peer and outbound send
|
|
714
|
+
// keep passing one). An id another peer already has is not. A2A forbids minting a replacement id when the
|
|
715
|
+
// client id is refused, so this is the same error the façade returns for an unknown context, not a new id.
|
|
716
|
+
// The claim and the first task are one batch: a second peer cannot pass a read and then write its own task.
|
|
717
|
+
const creating = !task;
|
|
637
718
|
if (!task) task = { id: A.newId(), contextId, status: { state: "submitted", timestamp: ts }, artifacts: [], history: [], _peer: label, _protocol: version, _createdAt: ts, _push: [] };
|
|
638
719
|
msg.contextId = contextId; msg.taskId = task.id;
|
|
639
720
|
task.history.push(msg);
|
|
@@ -641,10 +722,23 @@ const rpcSend: Rpc = async (params, label, version, ctx, ectx) => {
|
|
|
641
722
|
if (pushCfg) task._push = [...task._push.filter((c: Json) => c.id !== pushCfg.id), pushCfg];
|
|
642
723
|
if (params.metadata && typeof params.metadata === "object") task.metadata = { ...(task.metadata || {}), ...params.metadata };
|
|
643
724
|
const preview = A.textOf(msg);
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
725
|
+
if (creating) {
|
|
726
|
+
const stored = await ctx.DB.batch([
|
|
727
|
+
claimContextStmt(ctx, contextId, label, ts),
|
|
728
|
+
saveTaskIfOwnerStmt(ctx, task),
|
|
729
|
+
msgIfOwnerStmt(ctx, task, msg),
|
|
730
|
+
histIfOwnerStmt(ctx, contextId, { dir: "in", peer: label, taskId: task.id, role: "user", text: preview, data: { messageId: msg.messageId } }, label),
|
|
731
|
+
ctx.DB.prepare("SELECT peer FROM conversation_owners WHERE context_id = ?").bind(contextId),
|
|
732
|
+
]);
|
|
733
|
+
const owner = (stored[4]?.results?.[0] as Json | undefined)?.peer;
|
|
734
|
+
const wrote = stored[1]?.meta?.changes ?? 0;
|
|
735
|
+
if (owner !== label || wrote < 1) throw new RpcError(-32602, UNKNOWN_CONTEXT);
|
|
736
|
+
} else {
|
|
737
|
+
await ctx.DB.batch([
|
|
738
|
+
saveTaskStmt(ctx, task), msgStmt(ctx, task, msg),
|
|
739
|
+
histStmt(ctx, contextId, { dir: "in", peer: label, taskId: task.id, role: "user", text: preview, data: { messageId: msg.messageId } }),
|
|
740
|
+
]);
|
|
741
|
+
}
|
|
648
742
|
log("message_received", { peer: label, contextId, taskId: task.id, chars: preview.length, version });
|
|
649
743
|
await wake(ctx, ectx, contextId, task.id, label, preview);
|
|
650
744
|
const pt = A.publicTask(task, version, conf.historyLength);
|
|
@@ -857,7 +951,7 @@ async function proxyRpc(req: Request, ctx: TenantContext, c: { raw: string; rid:
|
|
|
857
951
|
// may still be a live upstream context (another peer's, or one opened outside the façade), and the façade can't
|
|
858
952
|
// tell, so client-chosen context ids are refused; omit contextId to start a conversation and reuse the returned one.
|
|
859
953
|
if ((await ownerOf(ctx, "context", m.contextId)) !== c.label)
|
|
860
|
-
return err(-32602,
|
|
954
|
+
return err(-32602, UNKNOWN_CONTEXT);
|
|
861
955
|
}
|
|
862
956
|
} else {
|
|
863
957
|
const tid = F.taskIdOf(c.op, c.params);
|
|
@@ -1120,22 +1214,25 @@ async function ackPendingWakes(ctx: TenantContext, seen: { taskId: string; conte
|
|
|
1120
1214
|
byContext.set(row.contextId, ids);
|
|
1121
1215
|
}
|
|
1122
1216
|
for (const [contextId, seenIds] of byContext) {
|
|
1123
|
-
const
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1217
|
+
const rows = await ctx.DB.prepare("SELECT peer, pending_json FROM wakes WHERE context_id = ? AND pending_json IS NOT NULL").bind(contextId).all();
|
|
1218
|
+
for (const row of (rows.results || []) as Json[]) {
|
|
1219
|
+
if (typeof row?.pending_json !== "string") continue;
|
|
1220
|
+
let payload: Json;
|
|
1221
|
+
try { payload = JSON.parse(row.pending_json); } catch { continue; }
|
|
1222
|
+
const wakeKind = typeof payload?.kind === "string" && payload.kind ? payload.kind : "inbound";
|
|
1223
|
+
if (wakeKind !== kind) continue;
|
|
1224
|
+
if (typeof payload?.contextId === "string" && payload.contextId !== contextId) continue;
|
|
1225
|
+
const ids = wakeTaskIds(payload);
|
|
1226
|
+
if (!ids.some((id) => seenIds.has(id))) continue;
|
|
1227
|
+
const kept = ids.filter((id) => !seenIds.has(id));
|
|
1228
|
+
const peer = typeof row.peer === "string" ? row.peer : "";
|
|
1229
|
+
if (!kept.length) {
|
|
1230
|
+
await ctx.DB.prepare("UPDATE wakes SET pending_json = NULL, pending_since_ms = NULL WHERE context_id = ? AND peer = ? AND pending_json = ?").bind(contextId, peer, row.pending_json).run();
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
const next = { ...payload, taskIds: kept, taskId: kept[kept.length - 1] };
|
|
1234
|
+
await ctx.DB.prepare("UPDATE wakes SET pending_json = ? WHERE context_id = ? AND peer = ? AND pending_json = ?").bind(JSON.stringify(next), contextId, peer, row.pending_json).run();
|
|
1136
1235
|
}
|
|
1137
|
-
const next = { ...payload, taskIds: kept, taskId: kept[kept.length - 1] };
|
|
1138
|
-
await ctx.DB.prepare("UPDATE wakes SET pending_json = ? WHERE context_id = ? AND pending_json = ?").bind(JSON.stringify(next), contextId, row.pending_json).run();
|
|
1139
1236
|
}
|
|
1140
1237
|
}
|
|
1141
1238
|
|
|
@@ -1272,7 +1369,19 @@ async function handleOwner(req: Request, ctx: TenantContext, ectx: ExecutionCont
|
|
|
1272
1369
|
}
|
|
1273
1370
|
if (seg[0] === "history" && seg[1] && m === "GET") {
|
|
1274
1371
|
const n = Math.min(Number(url.searchParams.get("n") || "50"), 1000);
|
|
1275
|
-
|
|
1372
|
+
// Rows for this conversation: this context, and a peer that owns it (a task or an outbound task).
|
|
1373
|
+
// A null peer is a local note. When nothing owns the id yet, the rows that name it are the conversation.
|
|
1374
|
+
const rows = await ctx.DB.prepare(`SELECT * FROM (
|
|
1375
|
+
SELECT * FROM history WHERE context_id = ? AND (
|
|
1376
|
+
peer IS NULL OR peer = ''
|
|
1377
|
+
OR peer IN (SELECT peer FROM tasks WHERE context_id = ? AND peer IS NOT NULL AND peer != '')
|
|
1378
|
+
OR peer IN (SELECT peer FROM outbound WHERE context_id = ? AND peer IS NOT NULL AND peer != '')
|
|
1379
|
+
OR (
|
|
1380
|
+
NOT EXISTS (SELECT 1 FROM tasks WHERE context_id = ?)
|
|
1381
|
+
AND NOT EXISTS (SELECT 1 FROM outbound WHERE context_id = ?)
|
|
1382
|
+
)
|
|
1383
|
+
) ORDER BY seq DESC LIMIT ?
|
|
1384
|
+
) ORDER BY seq`).bind(seg[1], seg[1], seg[1], seg[1], seg[1], n).all();
|
|
1276
1385
|
return json((rows.results as Json[]).map((r) => ({ ...r, data: r.data_json ? JSON.parse(r.data_json) : undefined, data_json: undefined })));
|
|
1277
1386
|
}
|
|
1278
1387
|
if (seg[0] === "history" && !seg[1] && m === "POST") {
|
|
@@ -1434,6 +1543,7 @@ async function handleOwner(req: Request, ctx: TenantContext, ectx: ExecutionCont
|
|
|
1434
1543
|
ctx.DB.prepare("DELETE FROM history WHERE context_id = ?").bind(c),
|
|
1435
1544
|
ctx.DB.prepare("DELETE FROM outbound WHERE context_id = ?").bind(c),
|
|
1436
1545
|
ctx.DB.prepare("DELETE FROM wakes WHERE context_id = ?").bind(c),
|
|
1546
|
+
ctx.DB.prepare("DELETE FROM conversation_owners WHERE context_id = ?").bind(c),
|
|
1437
1547
|
]);
|
|
1438
1548
|
n += res.reduce((s, r) => s + (r.meta.changes || 0), 0);
|
|
1439
1549
|
}
|
package/worker/src/migrations.ts
CHANGED
|
@@ -9,6 +9,8 @@ import m0006 from "../migrations/0006_mcp.sql?raw";
|
|
|
9
9
|
import m0007 from "../migrations/0007_cimd.sql?raw";
|
|
10
10
|
import m0008 from "../migrations/0008_oidc_txns.sql?raw";
|
|
11
11
|
import m0009 from "../migrations/0009_outbound_seen.sql?raw";
|
|
12
|
+
import m0010 from "../migrations/0010_conversation_peer.sql?raw";
|
|
13
|
+
import m0011 from "../migrations/0011_conversation_owner.sql?raw";
|
|
12
14
|
import type { Migration } from "./storage.ts";
|
|
13
15
|
|
|
14
16
|
export const MIGRATIONS: Migration[] = [
|
|
@@ -21,4 +23,6 @@ export const MIGRATIONS: Migration[] = [
|
|
|
21
23
|
{ name: "0007_cimd.sql", sql: m0007 },
|
|
22
24
|
{ name: "0008_oidc_txns.sql", sql: m0008 },
|
|
23
25
|
{ name: "0009_outbound_seen.sql", sql: m0009 },
|
|
26
|
+
{ name: "0010_conversation_peer.sql", sql: m0010 },
|
|
27
|
+
{ name: "0011_conversation_owner.sql", sql: m0011 },
|
|
24
28
|
];
|
package/worker/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Inbox build. Keep this equal to `version` in cli/package.json. */
|
|
2
|
-
export const VERSION = "0.8.
|
|
2
|
+
export const VERSION = "0.8.17";
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// A peer must not post into another peer's conversation by reusing its contextId.
|
|
2
|
+
// Run: npm test
|
|
3
|
+
import { test } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import worker from "../src/index.ts";
|
|
6
|
+
import { d1 } from "./d1.ts";
|
|
7
|
+
|
|
8
|
+
const BASE = "https://agent.example.com";
|
|
9
|
+
const UNKNOWN = "Invalid params: unknown contextId (omit contextId to start a new conversation, then use the one returned)";
|
|
10
|
+
|
|
11
|
+
function setup() {
|
|
12
|
+
const DB = d1(new URL("../migrations/", import.meta.url));
|
|
13
|
+
const env: any = {
|
|
14
|
+
DB, PUBLIC_URL: BASE, OWNER_TOKEN: "owner-secret", AGENT_NAME: "Test Inbox", WAKE_PRESET: "generic",
|
|
15
|
+
WAKE_DEBOUNCE_SECONDS: "3600", WAKE_WEBHOOK_URL: "https://hook.example.net/wake", WAKE_WEBHOOK_KEY: "hook-key",
|
|
16
|
+
};
|
|
17
|
+
const origFetch = globalThis.fetch;
|
|
18
|
+
globalThis.fetch = (async () => new Response("ok")) as typeof fetch;
|
|
19
|
+
const call = async (method: string, path: string, json?: unknown, auth = "Bearer owner-secret") => {
|
|
20
|
+
const headers: Record<string, string> = { authorization: auth, "content-type": "application/json", "cf-connecting-ip": "198.51.100.7" };
|
|
21
|
+
const pending: Promise<unknown>[] = [];
|
|
22
|
+
const res = await worker.fetch(new Request(BASE + path, { method, headers, body: json === undefined ? undefined : JSON.stringify(json) }) as any,
|
|
23
|
+
env, { waitUntil: (p: Promise<unknown>) => pending.push(p), passThroughOnException() {} } as any);
|
|
24
|
+
await Promise.allSettled(pending);
|
|
25
|
+
const text = await res.text();
|
|
26
|
+
let data: any = text;
|
|
27
|
+
try { data = text ? JSON.parse(text) : null; } catch { /* not json */ }
|
|
28
|
+
return { status: res.status, data, text };
|
|
29
|
+
};
|
|
30
|
+
const owner = (method: string, path: string, json?: unknown) => call(method, path, json);
|
|
31
|
+
const send = (token: string, text: string, contextId?: string, method = "message/send") => call("POST", "/", {
|
|
32
|
+
jsonrpc: "2.0", id: 1, method,
|
|
33
|
+
params: { message: { kind: "message", role: "user", messageId: crypto.randomUUID(), ...(contextId ? { contextId } : {}), parts: [{ kind: "text", text }] } },
|
|
34
|
+
}, `Bearer ${token}`);
|
|
35
|
+
return { DB, owner, send, restore: () => { globalThis.fetch = origFetch; } };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test("another peer's contextId is refused without joining that conversation", async (t) => {
|
|
39
|
+
const s = setup();
|
|
40
|
+
t.after(s.restore);
|
|
41
|
+
const ada = (await s.owner("POST", "/owner/peers", { label: "ada" })).data.token as string;
|
|
42
|
+
const bob = (await s.owner("POST", "/owner/peers", { label: "bob" })).data.token as string;
|
|
43
|
+
assert.match(ada, /^a2aow_/);
|
|
44
|
+
assert.match(bob, /^a2aow_/);
|
|
45
|
+
|
|
46
|
+
const first = await s.send(ada, "y-one", "ctx-y");
|
|
47
|
+
assert.equal(first.status, 200, first.text);
|
|
48
|
+
assert.equal(first.data.result.contextId, "ctx-y");
|
|
49
|
+
const second = await s.send(ada, "y-two", "ctx-y");
|
|
50
|
+
assert.equal(second.status, 200, second.text);
|
|
51
|
+
assert.equal(second.data.result.contextId, "ctx-y");
|
|
52
|
+
|
|
53
|
+
const history = () => s.owner("GET", "/owner/history/ctx-y");
|
|
54
|
+
const beforeHist = await history();
|
|
55
|
+
assert.equal(beforeHist.status, 200, beforeHist.text);
|
|
56
|
+
const beforeTexts = (beforeHist.data as { text: string }[]).map((r) => r.text);
|
|
57
|
+
assert.deepEqual(beforeTexts, ["y-one", "y-two"]);
|
|
58
|
+
const wake = () => s.DB.db.prepare("SELECT context_id, peer, last_sent_ms, pending_json, pending_since_ms FROM wakes WHERE context_id = 'ctx-y' AND peer = 'ada'").get() as {
|
|
59
|
+
pending_json: string; peer: string; last_sent_ms: number; pending_since_ms: number;
|
|
60
|
+
};
|
|
61
|
+
const beforeWake = wake();
|
|
62
|
+
assert.equal(beforeWake.peer, "ada");
|
|
63
|
+
const pending = JSON.parse(beforeWake.pending_json);
|
|
64
|
+
assert.equal(pending.from, "ada");
|
|
65
|
+
assert.equal(pending.preview, "y-two");
|
|
66
|
+
assert.equal(pending.taskIds.includes(second.data.result.id), true);
|
|
67
|
+
|
|
68
|
+
const foreign = await s.send(bob, "x-inject", "ctx-y");
|
|
69
|
+
const foreignV1 = await s.send(bob, "x-inject-v1", "ctx-y", "SendMessage");
|
|
70
|
+
assert.deepEqual(foreign.data.error, { code: -32602, message: UNKNOWN });
|
|
71
|
+
assert.deepEqual(foreignV1.data.error, foreign.data.error);
|
|
72
|
+
const body = JSON.stringify(foreign.data);
|
|
73
|
+
assert.equal(body.includes("ada"), false);
|
|
74
|
+
assert.equal(body.includes("ctx-y"), false);
|
|
75
|
+
assert.equal(body.includes("y-one"), false);
|
|
76
|
+
assert.equal(body.includes("y-two"), false);
|
|
77
|
+
assert.equal(body.includes("exists"), false);
|
|
78
|
+
assert.equal(body.includes(ada), false);
|
|
79
|
+
assert.equal(body.includes(bob), false);
|
|
80
|
+
|
|
81
|
+
const afterHist = await history();
|
|
82
|
+
assert.deepEqual(afterHist.data, beforeHist.data);
|
|
83
|
+
assert.deepEqual(wake(), beforeWake);
|
|
84
|
+
const db = s.DB.db;
|
|
85
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM tasks WHERE context_id = 'ctx-y' AND peer = 'bob'").get() as { n: number }).n, 0);
|
|
86
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM history WHERE context_id = 'ctx-y' AND peer = 'bob'").get() as { n: number }).n, 0);
|
|
87
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM wakes WHERE context_id = 'ctx-y' AND peer = 'bob'").get() as { n: number }).n, 0);
|
|
88
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM messages WHERE context_id = 'ctx-y' AND message_json LIKE '%x-inject%'").get() as { n: number }).n, 0);
|
|
89
|
+
|
|
90
|
+
assert.equal((db.prepare("SELECT peer FROM conversation_owners WHERE context_id = 'ctx-y'").get() as { peer: string }).peer, "ada");
|
|
91
|
+
|
|
92
|
+
const follow = await s.send(ada, "y-three", "ctx-y");
|
|
93
|
+
assert.equal(follow.status, 200, follow.text);
|
|
94
|
+
assert.equal(follow.data.result.contextId, "ctx-y");
|
|
95
|
+
const texts = ((await history()).data as { text: string; peer: string }[]).map((r) => r.text);
|
|
96
|
+
assert.deepEqual(texts, ["y-one", "y-two", "y-three"]);
|
|
97
|
+
const after = JSON.parse(wake().pending_json);
|
|
98
|
+
assert.equal(after.from, "ada");
|
|
99
|
+
assert.equal(after.preview, "y-three");
|
|
100
|
+
assert.equal(String(after.preview).includes("x-inject"), false);
|
|
101
|
+
assert.equal(after.taskIds.includes(follow.data.result.id), true);
|
|
102
|
+
assert.equal(after.taskIds.includes(second.data.result.id), true);
|
|
103
|
+
|
|
104
|
+
const own = await s.send(bob, "x-own", "ctx-x");
|
|
105
|
+
assert.equal(own.status, 200, own.text);
|
|
106
|
+
assert.equal(own.data.result.contextId, "ctx-x");
|
|
107
|
+
const again = await s.send(bob, "x-again", "ctx-x");
|
|
108
|
+
assert.equal(again.status, 200, again.text);
|
|
109
|
+
assert.equal(again.data.result.contextId, "ctx-x");
|
|
110
|
+
const bobHist = await s.owner("GET", "/owner/history/ctx-x");
|
|
111
|
+
assert.deepEqual((bobHist.data as { text: string }[]).map((r) => r.text), ["x-own", "x-again"]);
|
|
112
|
+
assert.deepEqual(((await history()).data as { text: string }[]).map((r) => r.text), ["y-one", "y-two", "y-three"]);
|
|
113
|
+
assert.equal(JSON.parse(wake().pending_json).from, "ada");
|
|
114
|
+
assert.equal(JSON.parse(wake().pending_json).preview, "y-three");
|
|
115
|
+
assert.equal((db.prepare("SELECT peer FROM conversation_owners WHERE context_id = 'ctx-x'").get() as { peer: string }).peer, "bob");
|
|
116
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM conversation_owners WHERE context_id = 'ctx-y'").get() as { n: number }).n, 1);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("two peers cannot both claim one unused contextId", async (t) => {
|
|
120
|
+
const s = setup();
|
|
121
|
+
t.after(s.restore);
|
|
122
|
+
const ada = (await s.owner("POST", "/owner/peers", { label: "ada" })).data.token as string;
|
|
123
|
+
const bob = (await s.owner("POST", "/owner/peers", { label: "bob" })).data.token as string;
|
|
124
|
+
let arrived = 0;
|
|
125
|
+
let openGate = () => {};
|
|
126
|
+
const gate = new Promise<void>((resolve) => { openGate = resolve; });
|
|
127
|
+
const orig = s.DB.batch.bind(s.DB);
|
|
128
|
+
s.DB.batch = async (stmts: { __sql?: string }[]) => {
|
|
129
|
+
const claim = stmts.some((st) => typeof st.__sql === "string" && st.__sql.includes("INSERT INTO conversation_owners"));
|
|
130
|
+
if (!claim || arrived >= 2) return orig(stmts);
|
|
131
|
+
arrived++;
|
|
132
|
+
if (arrived === 2) openGate();
|
|
133
|
+
await gate;
|
|
134
|
+
return orig(stmts);
|
|
135
|
+
};
|
|
136
|
+
const [left, right] = await Promise.all([
|
|
137
|
+
s.send(ada, "from-ada", "ctx-race"),
|
|
138
|
+
s.send(bob, "from-bob", "ctx-race"),
|
|
139
|
+
]);
|
|
140
|
+
assert.equal(arrived, 2);
|
|
141
|
+
const ok = [left, right].filter((r) => r.status === 200 && !r.data.error);
|
|
142
|
+
const denied = [left, right].filter((r) => r.data?.error);
|
|
143
|
+
assert.equal(ok.length, 1, JSON.stringify([left.data, right.data]));
|
|
144
|
+
assert.equal(denied.length, 1);
|
|
145
|
+
assert.deepEqual(denied[0].data.error, { code: -32602, message: UNKNOWN });
|
|
146
|
+
assert.equal(ok[0].data.result.contextId, "ctx-race");
|
|
147
|
+
const body = JSON.stringify(denied[0].data);
|
|
148
|
+
for (const secret of ["ada", "bob", "ctx-race", "from-ada", "from-bob", "exists", ada, bob]) assert.equal(body.includes(secret), false, secret);
|
|
149
|
+
|
|
150
|
+
const db = s.DB.db;
|
|
151
|
+
const owners = db.prepare("SELECT peer FROM conversation_owners WHERE context_id = 'ctx-race'").all() as { peer: string }[];
|
|
152
|
+
assert.equal(owners.length, 1);
|
|
153
|
+
const winner = owners[0].peer;
|
|
154
|
+
const loser = winner === "ada" ? "bob" : "ada";
|
|
155
|
+
assert.equal(winner === "ada" || winner === "bob", true);
|
|
156
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM tasks WHERE context_id = 'ctx-race'").get() as { n: number }).n, 1);
|
|
157
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM tasks WHERE context_id = 'ctx-race' AND peer = ?").get(loser) as { n: number }).n, 0);
|
|
158
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM history WHERE context_id = 'ctx-race' AND peer = ?").get(loser) as { n: number }).n, 0);
|
|
159
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM messages WHERE context_id = 'ctx-race' AND message_json LIKE ?").get(`%from-${loser}%`) as { n: number }).n, 0);
|
|
160
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM wakes WHERE context_id = 'ctx-race' AND peer = ?").get(loser) as { n: number }).n, 0);
|
|
161
|
+
|
|
162
|
+
const follow = await s.send(winner === "ada" ? ada : bob, "follow", "ctx-race");
|
|
163
|
+
assert.equal(follow.status, 200, follow.text);
|
|
164
|
+
assert.equal(follow.data.result.contextId, "ctx-race");
|
|
165
|
+
const hist = await s.owner("GET", "/owner/history/ctx-race");
|
|
166
|
+
assert.deepEqual((hist.data as { text: string; peer: string }[]).map((r) => r.text), [winner === "ada" ? "from-ada" : "from-bob", "follow"]);
|
|
167
|
+
assert.equal((hist.data as { peer: string }[]).every((r) => r.peer === winner), true);
|
|
168
|
+
const again = await s.send(loser === "ada" ? ada : bob, "still-no", "ctx-race");
|
|
169
|
+
assert.deepEqual(again.data.error, { code: -32602, message: UNKNOWN });
|
|
170
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM tasks WHERE context_id = 'ctx-race' AND peer = ?").get(loser) as { n: number }).n, 0);
|
|
171
|
+
});
|
|
@@ -57,7 +57,7 @@ test("migration files: NNNN_name.sql, unique numbers, no gaps, 0002_wake_budget
|
|
|
57
57
|
test("fresh database: every migration applies in order; a second run applies nothing", () => {
|
|
58
58
|
const db = new DatabaseSync(":memory:");
|
|
59
59
|
assert.deepEqual(applyMigrations(db), [...FILES].sort(byNumber));
|
|
60
|
-
for (const t of ["peers", "tasks", "wakes", "wake_budget", "device_requests", "pairing_rate", "settings", "facade_owners", "oauth_clients", "oauth_codes", "mcp_grants", "outbound_peers", "oauth_client_metadata", "oidc_txns"]) assert.ok(tables(db).includes(t), t);
|
|
60
|
+
for (const t of ["peers", "tasks", "wakes", "wake_budget", "device_requests", "pairing_rate", "settings", "facade_owners", "oauth_clients", "oauth_codes", "mcp_grants", "outbound_peers", "oauth_client_metadata", "oidc_txns", "conversation_owners"]) assert.ok(tables(db).includes(t), t);
|
|
61
61
|
assert.ok(columns(db, "peers").includes("source"));
|
|
62
62
|
assert.ok(columns(db, "device_requests").includes("replaces_label"));
|
|
63
63
|
assert.ok(columns(db, "device_requests").includes("replaces_hash"));
|
|
@@ -67,15 +67,15 @@ test("fresh database: every migration applies in order; a second run applies not
|
|
|
67
67
|
test("database from the 0002 fix (0001-0003 recorded): only 0004 and later apply; pending requests keep working", () => {
|
|
68
68
|
const db = existingDb([sql("0001_init.sql"), sql("0002_wake_budget.sql"), sql("0003_device_pairing.sql")], ["0001_init.sql", "0002_wake_budget.sql", "0003_device_pairing.sql"]);
|
|
69
69
|
db.prepare("INSERT INTO device_requests (device_hash, user_code, status, created_ms, expires_ms, interval_s) VALUES ('h', 'WDJB4827', 'pending', 1, 2, 5)").run();
|
|
70
|
-
assert.deepEqual(applyMigrations(db), ["0004_pairing_replace.sql", "0005_facade_owners.sql", "0006_mcp.sql", "0007_cimd.sql", "0008_oidc_txns.sql", "0009_outbound_seen.sql"]);
|
|
70
|
+
assert.deepEqual(applyMigrations(db), ["0004_pairing_replace.sql", "0005_facade_owners.sql", "0006_mcp.sql", "0007_cimd.sql", "0008_oidc_txns.sql", "0009_outbound_seen.sql", "0010_conversation_peer.sql", "0011_conversation_owner.sql"]);
|
|
71
71
|
assert.equal((db.prepare("SELECT replaces_label FROM device_requests WHERE device_hash = 'h'").get() as any).replaces_label, null);
|
|
72
72
|
});
|
|
73
73
|
|
|
74
74
|
test("database from v0.2.0 (0001 and 0003 recorded): 0002 applies as a no-op and keeps the data", () => {
|
|
75
75
|
const db = existingDb([sql("0001_init.sql"), sql("0003_device_pairing.sql")], ["0001_init.sql", "0003_device_pairing.sql"]);
|
|
76
76
|
db.prepare("INSERT INTO wake_budget (hour, count) VALUES (1, 7)").run();
|
|
77
|
-
assert.deepEqual(applyMigrations(db), ["0002_wake_budget.sql", "0004_pairing_replace.sql", "0005_facade_owners.sql", "0006_mcp.sql", "0007_cimd.sql", "0008_oidc_txns.sql", "0009_outbound_seen.sql"]);
|
|
78
|
-
assert.deepEqual(recorded(db), ["0001_init.sql", "0003_device_pairing.sql", "0002_wake_budget.sql", "0004_pairing_replace.sql", "0005_facade_owners.sql", "0006_mcp.sql", "0007_cimd.sql", "0008_oidc_txns.sql", "0009_outbound_seen.sql"]);
|
|
77
|
+
assert.deepEqual(applyMigrations(db), ["0002_wake_budget.sql", "0004_pairing_replace.sql", "0005_facade_owners.sql", "0006_mcp.sql", "0007_cimd.sql", "0008_oidc_txns.sql", "0009_outbound_seen.sql", "0010_conversation_peer.sql", "0011_conversation_owner.sql"]);
|
|
78
|
+
assert.deepEqual(recorded(db), ["0001_init.sql", "0003_device_pairing.sql", "0002_wake_budget.sql", "0004_pairing_replace.sql", "0005_facade_owners.sql", "0006_mcp.sql", "0007_cimd.sql", "0008_oidc_txns.sql", "0009_outbound_seen.sql", "0010_conversation_peer.sql", "0011_conversation_owner.sql"]);
|
|
79
79
|
assert.equal((db.prepare("SELECT count FROM wake_budget WHERE hour = 1").get() as any).count, 7);
|
|
80
80
|
});
|
|
81
81
|
|
|
@@ -107,7 +107,7 @@ test("database from an earlier build without wake_budget (0001 and 0003 recorded
|
|
|
107
107
|
assert.equal(before.data.error?.code, -32603, JSON.stringify(before.data));
|
|
108
108
|
assert.equal(wakes.length, 0);
|
|
109
109
|
|
|
110
|
-
assert.deepEqual(applyMigrations(db), ["0002_wake_budget.sql", "0004_pairing_replace.sql", "0005_facade_owners.sql", "0006_mcp.sql", "0007_cimd.sql", "0008_oidc_txns.sql", "0009_outbound_seen.sql"]);
|
|
110
|
+
assert.deepEqual(applyMigrations(db), ["0002_wake_budget.sql", "0004_pairing_replace.sql", "0005_facade_owners.sql", "0006_mcp.sql", "0007_cimd.sql", "0008_oidc_txns.sql", "0009_outbound_seen.sql", "0010_conversation_peer.sql", "0011_conversation_owner.sql"]);
|
|
111
111
|
assert.deepEqual(columns(db, "wake_budget"), ["hour", "count"]);
|
|
112
112
|
assert.deepEqual(applyMigrations(db), []);
|
|
113
113
|
|
|
@@ -122,3 +122,38 @@ test("database from an earlier build without wake_budget (0001 and 0003 recorded
|
|
|
122
122
|
globalThis.fetch = origFetch;
|
|
123
123
|
}
|
|
124
124
|
});
|
|
125
|
+
|
|
126
|
+
test("0010 keys an existing wake by the peer in its payload and allows a second peer", () => {
|
|
127
|
+
const prior = [...FILES].sort(byNumber).filter((f) => f !== "0010_conversation_peer.sql");
|
|
128
|
+
const db = existingDb(prior.map(sql), prior);
|
|
129
|
+
db.prepare(`INSERT INTO tasks (id, context_id, peer, state, protocol, created_at, updated_at, status_json, artifacts_json, push_configs_json)
|
|
130
|
+
VALUES ('t1', 'ctx-y', 'ada', 'submitted', '0.3', 't', 't', '{}', '[]', '[]')`).run();
|
|
131
|
+
const pending = JSON.stringify({ contextId: "ctx-y", from: "ada", taskId: "t1", taskIds: ["t1"], kind: "inbound", preview: "hi" });
|
|
132
|
+
db.prepare("INSERT INTO wakes (context_id, last_sent_ms, pending_json, pending_since_ms) VALUES ('ctx-y', 5, ?, 5)").run(pending);
|
|
133
|
+
assert.deepEqual(applyMigrations(db), ["0010_conversation_peer.sql"]);
|
|
134
|
+
const row = db.prepare("SELECT peer, pending_json, last_sent_ms FROM wakes WHERE context_id = 'ctx-y'").get() as { peer: string; pending_json: string; last_sent_ms: number };
|
|
135
|
+
assert.equal(row.peer, "ada");
|
|
136
|
+
assert.equal(row.last_sent_ms, 5);
|
|
137
|
+
assert.equal(JSON.parse(row.pending_json).preview, "hi");
|
|
138
|
+
db.prepare("INSERT INTO wakes (context_id, peer, last_sent_ms) VALUES ('ctx-y', 'bob', 6)").run();
|
|
139
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM wakes WHERE context_id = 'ctx-y'").get() as { n: number }).n, 2);
|
|
140
|
+
assert.equal((db.prepare("SELECT pending_json FROM wakes WHERE context_id = 'ctx-y' AND peer = 'ada'").get() as { pending_json: string }).pending_json, pending);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("0011 keeps one owner per context from the earliest task, then history, then outbound", () => {
|
|
144
|
+
const prior = [...FILES].sort(byNumber).filter((f) => f !== "0011_conversation_owner.sql");
|
|
145
|
+
const db = existingDb(prior.map(sql), prior);
|
|
146
|
+
const task = `INSERT INTO tasks (id, context_id, peer, state, protocol, created_at, updated_at, status_json, artifacts_json, push_configs_json)
|
|
147
|
+
VALUES (?, ?, ?, 'submitted', '0.3', ?, ?, '{}', '[]', '[]')`;
|
|
148
|
+
db.prepare(task).run("t-bob", "ctx-y", "bob", "2026-02-01T00:00:00.000Z", "2026-02-01T00:00:00.000Z");
|
|
149
|
+
db.prepare(task).run("t-ada", "ctx-y", "ada", "2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
|
|
150
|
+
db.prepare("INSERT INTO history (context_id, ts, dir, peer, text) VALUES ('ctx-h', '2026-01-01T00:00:00.000Z', 'local', 'ada', 'note')").run();
|
|
151
|
+
db.prepare("INSERT INTO outbound (task_id, context_id, peer, sent_at) VALUES ('o1', 'ctx-o', 'alias', '2026-01-01T00:00:00.000Z')").run();
|
|
152
|
+
assert.deepEqual(applyMigrations(db), ["0011_conversation_owner.sql"]);
|
|
153
|
+
const owner = (id: string) => (db.prepare("SELECT peer FROM conversation_owners WHERE context_id = ?").get(id) as { peer: string }).peer;
|
|
154
|
+
assert.equal(owner("ctx-y"), "ada");
|
|
155
|
+
assert.equal((db.prepare("SELECT COUNT(*) AS n FROM conversation_owners WHERE context_id = 'ctx-y'").get() as { n: number }).n, 1);
|
|
156
|
+
assert.equal(owner("ctx-h"), "ada");
|
|
157
|
+
assert.equal(owner("ctx-o"), "alias");
|
|
158
|
+
assert.throws(() => db.prepare("INSERT INTO conversation_owners (context_id, peer, created_at) VALUES ('ctx-y', 'bob', 'later')").run());
|
|
159
|
+
});
|