@jbkjr/relay 1.2.2 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -12
- package/adapters/claude/relay/.claude-plugin/plugin.json +1 -1
- package/adapters/claude/relay/skills/discuss/SKILL.md +3 -0
- package/adapters/codex/AGENTS.snippet.md +2 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +1 -1
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +3 -0
- package/adapters/generate.mjs +6 -1
- package/codex-pin.json +2 -2
- package/dist/build-info.json +2 -2
- package/dist/cli.js +160 -2
- package/dist/confine/canary.js +19 -4
- package/dist/confine/probe.js +11 -3
- package/dist/core/approvals.js +29 -4
- package/dist/core/db.js +44 -2
- package/dist/core/identity.js +43 -3
- package/dist/core/ops.js +9 -9
- package/dist/core/retention.js +66 -12
- package/dist/core/room-clipboard.js +86 -0
- package/dist/core/room-policy.js +17 -0
- package/dist/core/room-terminal.js +227 -0
- package/dist/core/room-types.js +130 -0
- package/dist/core/rooms.js +839 -0
- package/dist/core/secrets.js +4 -0
- package/dist/core/shown.js +19 -3
- package/dist/core/storage.js +2 -2
- package/dist/install/doctor.js +1 -0
- package/dist/mcp/elicit.js +81 -0
- package/dist/mcp/host.js +121 -1
- package/dist/mcp/server.js +159 -11
- package/docs/UPGRADING.md +88 -0
- package/docs/pinned-codex.md +3 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/scripts/codex-qualify/codex-qualifier.mjs +22 -8
- package/scripts/codex-qualify/codex-stage2.mjs +57 -5
- package/scripts/codex-qualify/stage2-parallel.mjs +200 -0
- package/test/fixtures/stable-surfaces/registry.json +25 -1
- package/test/fixtures/stable-surfaces/room.json +681 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +57 -0
- package/test/fixtures/stable-surfaces/tools.json +54 -0
- package/test/fixtures/stable-surfaces/usage.txt +11 -1
- package/test/fixtures/stage2-parallel/fake-driver.mjs +34 -0
- package/test/fixtures/stage2-parallel/harness.mjs +8 -0
- package/test/helpers.ts +20 -1
- package/test/never-policy.test.ts +4 -4
- package/test/stable-surfaces.test.ts +125 -1
- package/test/wp4-interlock.test.ts +1 -1
|
@@ -0,0 +1,839 @@
|
|
|
1
|
+
// Rooms bind existing owners to two seats. All delivery and mutation share the registry writer
|
|
2
|
+
// lock; no room owns a run, and transcript text is never interpreted as an instruction.
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import { db, now, tx } from "./db.js";
|
|
5
|
+
import { relayHome } from "./config.js";
|
|
6
|
+
import { pidAlive, procStart } from "./procs.js";
|
|
7
|
+
import { markRoomExposure, roomOwnerExposed, roomOwnerHash } from "./room-policy.js";
|
|
8
|
+
import { redact, roomCredentialInText } from "./secrets.js";
|
|
9
|
+
import { roomClientName } from "./shown.js";
|
|
10
|
+
import { waitUntil } from "./wait.js";
|
|
11
|
+
import { invitePrompt } from "./room-terminal.js";
|
|
12
|
+
import * as R from "./room-types.js";
|
|
13
|
+
const hex = () => crypto.randomBytes(R.ROOM_RANDOM_BYTES).toString("hex");
|
|
14
|
+
export const newRoomId = () => `rm_${hex()}`;
|
|
15
|
+
export const newRoomMemberId = () => `m_${hex()}`;
|
|
16
|
+
export const newRoomInvite = () => `ri1_${hex()}`;
|
|
17
|
+
const hash = (domain, value) => crypto.createHash("sha256").update(domain).update(value).digest("hex");
|
|
18
|
+
const wellFormed = (text) => text.toWellFormed();
|
|
19
|
+
const iso = (at) => new Date(at).toISOString();
|
|
20
|
+
const bytes = (value) => Buffer.byteLength(JSON.stringify(value, null, 2), "utf8");
|
|
21
|
+
const unavailable = () => ({ error: R.ROOM_UNAVAILABLE_ERROR, recovery: R.ROOM_UNAVAILABLE_RECOVERY });
|
|
22
|
+
const refusal = (reason) => ({ refused: true, reason });
|
|
23
|
+
const limit = (name, retry) => retry === undefined ? `Refused: room limit reached: ${name}.` : `Refused: room limit reached: ${name}; retry after ${iso(retry)}.`;
|
|
24
|
+
const room = (id) => db().prepare("SELECT * FROM rooms WHERE id = ?").get(id);
|
|
25
|
+
const seats = (id) => db().prepare("SELECT * FROM room_members WHERE room_id = ? ORDER BY ordinal").all(id);
|
|
26
|
+
const messages = (id) => db().prepare("SELECT * FROM room_messages WHERE room_id = ? ORDER BY seq").all(id);
|
|
27
|
+
const binding = (owner) => db().prepare("SELECT * FROM room_bindings WHERE owner_hash = ?").get(owner);
|
|
28
|
+
const latest = (id) => Number(db().prepare("SELECT COALESCE(MAX(seq),0) AS seq FROM room_messages WHERE room_id = ?").get(id).seq);
|
|
29
|
+
const label = (m) => m.ordinal === 1 ? "member-1" : "member-2";
|
|
30
|
+
const terminalSender = { member_id: null, label: "terminal", host: "terminal", client: null, family: "unknown" };
|
|
31
|
+
const wire = (m) => ({ seq: m.seq, sender: JSON.parse(m.sender_json), at: iso(m.created_at), text: m.text, stance: m.stance });
|
|
32
|
+
let operations = 0;
|
|
33
|
+
const sweptAt = new Map();
|
|
34
|
+
function writing(fn) {
|
|
35
|
+
operations++;
|
|
36
|
+
try {
|
|
37
|
+
return tx(fn);
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
operations--;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** A failed process-table read is unknown, never evidence to revoke a seat or lease. */
|
|
44
|
+
function liveness(pid, start, fresh = false) {
|
|
45
|
+
if (!pid)
|
|
46
|
+
return "unknown";
|
|
47
|
+
if (!pidAlive(pid))
|
|
48
|
+
return "dead";
|
|
49
|
+
// Authenticated room calls use procStart's short cache; terminal seat reviews read afresh.
|
|
50
|
+
const actual = procStart(pid, { fresh });
|
|
51
|
+
if (!actual || !start)
|
|
52
|
+
return "unknown";
|
|
53
|
+
return actual.replace(/\s+/g, " ") === start.replace(/\s+/g, " ") ? "alive" : "dead";
|
|
54
|
+
}
|
|
55
|
+
function end(r, ending, at, bumpRevision = true) {
|
|
56
|
+
if (r.state === "ended")
|
|
57
|
+
return;
|
|
58
|
+
db().prepare("UPDATE rooms SET state = 'ended', ended_at = ?, ending_json = ?, revision = revision + ? WHERE id = ?")
|
|
59
|
+
.run(at, JSON.stringify(ending), bumpRevision ? 1 : 0, r.id);
|
|
60
|
+
}
|
|
61
|
+
const noAgreement = (reason, closed_by = null) => ({ outcome: "no_agreement", reason, conclusion_seq: null, closed_by });
|
|
62
|
+
function expiry(r) {
|
|
63
|
+
if (r.state !== "waiting")
|
|
64
|
+
return r.expires_at;
|
|
65
|
+
const pending = db().prepare(`SELECT MIN(i.expires_at) AS at FROM room_invites i JOIN room_members m
|
|
66
|
+
ON m.room_id = i.room_id AND m.id = i.member_id AND m.generation = i.generation
|
|
67
|
+
WHERE i.room_id = ? AND i.consumed_at IS NULL`).get(r.id).at;
|
|
68
|
+
return Math.min(r.expires_at, pending ?? Infinity);
|
|
69
|
+
}
|
|
70
|
+
function refresh(r, at) {
|
|
71
|
+
// Expiry is independent of access; record its actual boundary, not the later sweep time.
|
|
72
|
+
if (r.state !== "ended" && expiry(r) <= at)
|
|
73
|
+
end(r, noAgreement("expired"), expiry(r));
|
|
74
|
+
r = room(r.id);
|
|
75
|
+
if (r.state !== "ended")
|
|
76
|
+
for (const m of seats(r.id)) {
|
|
77
|
+
if (m.owner_kind === "dedicated" && m.owner_hash && liveness(m.pid, m.pid_start) === "dead") {
|
|
78
|
+
db().prepare("DELETE FROM room_bindings WHERE room_id = ? AND member_id = ?").run(r.id, m.id);
|
|
79
|
+
db().prepare(`UPDATE room_members SET owner_hash = NULL, owner_kind = NULL, pid = NULL, pid_start = NULL,
|
|
80
|
+
wait_pid = NULL, wait_start = NULL, wait_nonce = NULL WHERE room_id = ? AND id = ?`).run(r.id, m.id);
|
|
81
|
+
db().prepare("UPDATE rooms SET state = 'waiting', revision = revision + 1 WHERE id = ?").run(r.id);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return room(r.id);
|
|
85
|
+
}
|
|
86
|
+
function sweep(options) {
|
|
87
|
+
const at = options.at ?? now(), expired = [], deleted = [];
|
|
88
|
+
for (const r of db().prepare("SELECT * FROM rooms WHERE state != 'ended'").all()) {
|
|
89
|
+
if (refresh(r, at).state === "ended")
|
|
90
|
+
expired.push(r.id);
|
|
91
|
+
}
|
|
92
|
+
if (options.keep_records_days !== null && Number.isFinite(options.keep_records_days) && options.keep_records_days >= 0) {
|
|
93
|
+
const cutoff = at - options.keep_records_days * 86400000;
|
|
94
|
+
const old = db().prepare("SELECT id FROM rooms WHERE state = 'ended' AND ended_at <= ?").all(cutoff);
|
|
95
|
+
if (old.length) {
|
|
96
|
+
const secure = Number(db().prepare("PRAGMA secure_delete").get().secure_delete);
|
|
97
|
+
db().exec("PRAGMA secure_delete = ON");
|
|
98
|
+
try {
|
|
99
|
+
for (const { id } of old) {
|
|
100
|
+
for (const table of ["room_messages", "room_invites", "room_bindings", "room_members"])
|
|
101
|
+
db().prepare(`DELETE FROM ${table} WHERE room_id = ?`).run(id);
|
|
102
|
+
db().prepare("DELETE FROM rooms WHERE id = ?").run(id);
|
|
103
|
+
deleted.push(id);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
db().exec(`PRAGMA secure_delete = ${secure}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { expired, deleted };
|
|
112
|
+
}
|
|
113
|
+
function opportunistic(at) {
|
|
114
|
+
const home = relayHome();
|
|
115
|
+
if (at - (sweptAt.get(home) ?? -Infinity) < R.ROOM_SWEEP_INTERVAL_MS)
|
|
116
|
+
return;
|
|
117
|
+
// Expire only. Deleting transcripts is maintenance's (retention.ts), which records the registry
|
|
118
|
+
// rebuild before rows go; a deletion here would leave nothing to say a rebuild is owed.
|
|
119
|
+
sweep({ at, keep_records_days: null });
|
|
120
|
+
// Advancing this hint before a caller's rollback is harmless: access still refreshes its room.
|
|
121
|
+
sweptAt.set(home, at);
|
|
122
|
+
}
|
|
123
|
+
export function roomSweep(options) {
|
|
124
|
+
return writing(() => sweep(options));
|
|
125
|
+
}
|
|
126
|
+
export function roomMaintenanceBusy() {
|
|
127
|
+
if (operations)
|
|
128
|
+
return true;
|
|
129
|
+
return db().prepare("SELECT wait_pid, wait_start FROM room_members WHERE wait_nonce IS NOT NULL").all()
|
|
130
|
+
.some((m) => liveness(m.wait_pid, m.wait_start) !== "dead");
|
|
131
|
+
}
|
|
132
|
+
function authenticate(owner, expected) {
|
|
133
|
+
const b = binding(owner);
|
|
134
|
+
if (!b || (expected && (b.room_id !== expected.room_id || b.member_id !== expected.member_id || b.generation !== expected.generation)))
|
|
135
|
+
return;
|
|
136
|
+
const found = room(b.room_id);
|
|
137
|
+
if (!found)
|
|
138
|
+
return;
|
|
139
|
+
const r = refresh(found, now());
|
|
140
|
+
const m = seats(r.id).find((m) => m.id === b.member_id);
|
|
141
|
+
if (!m || m.owner_hash !== owner || m.generation !== b.generation || !binding(owner))
|
|
142
|
+
return;
|
|
143
|
+
return { r, m, owner };
|
|
144
|
+
}
|
|
145
|
+
function touch(a, at) {
|
|
146
|
+
db().prepare("UPDATE room_members SET last_call_at = ?, call_no = call_no + 1 WHERE room_id = ? AND id = ?").run(at, a.r.id, a.m.id);
|
|
147
|
+
}
|
|
148
|
+
const stamp = (a) => ({ owner_hash: a.owner, room_id: a.r.id, member_id: a.m.id, generation: a.m.generation });
|
|
149
|
+
const cursorOK = (a, cursor) => Number.isSafeInteger(cursor) && cursor >= 0 && cursor <= latest(a.r.id);
|
|
150
|
+
function fields(input, action) {
|
|
151
|
+
const allowed = { open: ["action", "purpose"], join: ["action", "invite"], send: ["action", "cursor", "text", "stance", "request_id"], wait: ["action", "cursor", "wait_s"], transcript: ["action", "cursor"], close: ["action", "cursor"] }[action];
|
|
152
|
+
if (!input || input.action !== action || Object.keys(input).some((key) => !allowed.includes(key)))
|
|
153
|
+
return false;
|
|
154
|
+
if (input.action === "open")
|
|
155
|
+
return input.purpose === undefined || (typeof input.purpose === "string" && input.purpose.length <= R.ROOM_PURPOSE_INPUT_UNITS);
|
|
156
|
+
if (input.action === "join")
|
|
157
|
+
return typeof input.invite === "string" && input.invite.length <= R.ROOM_INVITE_INPUT_UNITS;
|
|
158
|
+
if (!Number.isSafeInteger(input.cursor) || input.cursor < 0)
|
|
159
|
+
return false;
|
|
160
|
+
if (input.action === "send")
|
|
161
|
+
return typeof input.text === "string" && ["continue", "agree", "crux"].includes(input.stance)
|
|
162
|
+
&& typeof input.request_id === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(input.request_id);
|
|
163
|
+
return input.action !== "wait" || input.wait_s === undefined || (Number.isInteger(input.wait_s) && input.wait_s >= 0 && input.wait_s <= R.ROOM_LONG_WAIT_S);
|
|
164
|
+
}
|
|
165
|
+
function preflight(inst, input, action, call) {
|
|
166
|
+
if (!call.eligibility.eligible || inst.ctx.kind !== "root")
|
|
167
|
+
return refusal(R.ROOM_REFUSALS.ineligible);
|
|
168
|
+
if (!fields(input, action))
|
|
169
|
+
return refusal(R.ROOM_REFUSALS.arguments);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Whether the peer's conversation is still there, as far as relay can prove: a dedicated seat's
|
|
173
|
+
* recorded server process, alive or gone. A seat detached when its server exited (refresh) keeps
|
|
174
|
+
* its join time and last call, so it reads as gone until it is re-seated. A shared seat, a seat
|
|
175
|
+
* never joined or re-seated, or an unreadable process table is unknown.
|
|
176
|
+
*/
|
|
177
|
+
function peerProcess(peer) {
|
|
178
|
+
if (!peer.owner_hash)
|
|
179
|
+
return peer.joined_at !== null && peer.last_call_at !== null ? "gone" : "unknown";
|
|
180
|
+
if (peer.owner_kind !== "dedicated")
|
|
181
|
+
return "unknown";
|
|
182
|
+
const l = liveness(peer.pid, peer.pid_start);
|
|
183
|
+
return l === "dead" ? "gone" : l;
|
|
184
|
+
}
|
|
185
|
+
/** Waits stop when the peer is gone, or, only where its process is unknown, after ROOM_PEER_SILENCE_S of silence. */
|
|
186
|
+
function peerStop(peer, at) {
|
|
187
|
+
const process = peerProcess(peer);
|
|
188
|
+
if (process === "gone")
|
|
189
|
+
return { process, stopped: true, until: at };
|
|
190
|
+
if (process === "alive" || peer.last_call_at === null)
|
|
191
|
+
return { process, stopped: false, until: Infinity };
|
|
192
|
+
const until = peer.last_call_at + R.ROOM_PEER_SILENCE_S * 1000;
|
|
193
|
+
return { process, stopped: at >= until, until };
|
|
194
|
+
}
|
|
195
|
+
/** One consistent page. Skipped own rows cover sequence space, never an omitted external row. */
|
|
196
|
+
function view(a, cursor, transcript = false) {
|
|
197
|
+
const r = room(a.r.id), members = seats(r.id), peer = members.find((m) => m.id !== a.m.id);
|
|
198
|
+
const rows = messages(r.id), pending = r.state === "waiting" ? [] : rows.filter((row) => row.seq > cursor && (transcript || row.sender_owner_hash !== a.owner));
|
|
199
|
+
const page = pending.slice(0, R.ROOM_PAGE_ROWS), omitted = pending[R.ROOM_PAGE_ROWS];
|
|
200
|
+
const through = r.state === "waiting" ? cursor : omitted ? omitted.seq - 1 : rows.at(-1)?.seq ?? cursor;
|
|
201
|
+
if (page.some((row) => row.sender_owner_hash !== a.owner))
|
|
202
|
+
markRoomExposure(a.owner);
|
|
203
|
+
const idle = peer.last_call_at === null ? null : Math.max(0, (now() - peer.last_call_at) / 1000);
|
|
204
|
+
const stop = peerStop(peer, now());
|
|
205
|
+
const common = {
|
|
206
|
+
room_id: r.id, origin: r.origin, member_id: a.m.id, turns: r.turns, max_turns: r.max_turns, revision: r.revision,
|
|
207
|
+
cursor, through_seq: through, latest_seq: rows.at(-1)?.seq ?? 0, remaining: Math.max(0, pending.length - page.length),
|
|
208
|
+
peer: { member_id: peer.id, seat: peer.owner_hash ? "joined" : "unseated", last_call_at: peer.last_call_at === null ? null : iso(peer.last_call_at), process: stop.process },
|
|
209
|
+
poll: { peer_idle_s: idle, stop_after_s: stop.process === "unknown" ? R.ROOM_PEER_SILENCE_S : null, stopped: stop.stopped },
|
|
210
|
+
messages: page.map(wire), note: R.ROOM_NOTE, user_confirmed_ignored: roomOwnerExposed(a.owner),
|
|
211
|
+
};
|
|
212
|
+
if (r.state === "waiting")
|
|
213
|
+
return { ...common, state: "waiting", next: null, messages: [] };
|
|
214
|
+
if (r.state === "ended")
|
|
215
|
+
return { ...common, state: "ended", next: null, ending: JSON.parse(r.ending_json) };
|
|
216
|
+
return { ...common, state: "open", next: members.find((m) => m.ordinal === r.next_ordinal).id };
|
|
217
|
+
}
|
|
218
|
+
function refusedView(a, cursor, reason) {
|
|
219
|
+
return { ...view(a, cursor), refused: true, reason };
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Room text hygiene, shared by member messages, terminal lines and an opener's purpose line (with
|
|
223
|
+
* its own, smaller cap). Invites and session tokens refuse the text outright; any other credential
|
|
224
|
+
* relay recognizes (redact) is cut before the display sanitizer escapes what is left, so the
|
|
225
|
+
* escaped marker and line count describe the stored text. The author's limits are measured on the
|
|
226
|
+
* text as written, so whether a text fits never depends on what redaction finds in it; the stored
|
|
227
|
+
* bound is measured after redaction and escaping, since a cut can lengthen text (a short
|
|
228
|
+
* registered value becomes "[redacted: …]").
|
|
229
|
+
*/
|
|
230
|
+
function prepareText(text, sanitize, codePoints = R.ROOM_TEXT_CODE_POINTS) {
|
|
231
|
+
if (!text.trim())
|
|
232
|
+
return { reason: R.ROOM_REFUSALS.text_empty };
|
|
233
|
+
if ([...text].length > codePoints || Buffer.byteLength(text, "utf8") > R.ROOM_TEXT_BYTES)
|
|
234
|
+
return { reason: R.ROOM_REFUSALS.text_long };
|
|
235
|
+
if (roomCredentialInText(text))
|
|
236
|
+
return { reason: R.ROOM_REFUSALS.text_secret };
|
|
237
|
+
const clean = sanitize(redact(wellFormed(text)));
|
|
238
|
+
if (!clean.trim())
|
|
239
|
+
return { reason: R.ROOM_REFUSALS.text_empty };
|
|
240
|
+
if (roomCredentialInText(clean))
|
|
241
|
+
return { reason: R.ROOM_REFUSALS.text_secret };
|
|
242
|
+
if (clean.length > Math.min(R.ROOM_SANITIZED_UNITS, codePoints * 3))
|
|
243
|
+
return { reason: R.ROOM_REFUSALS.text };
|
|
244
|
+
return { clean };
|
|
245
|
+
}
|
|
246
|
+
function fits(row) {
|
|
247
|
+
// A full wire row, plus space for indentation, the longest refusal, ending and presence.
|
|
248
|
+
// P3 reserves any wrapper additions within the same whole-result budget.
|
|
249
|
+
return bytes(row) <= R.ROOM_ROW_BYTES && bytes(row) + 2000 <= R.ROOM_RESULT_BYTES;
|
|
250
|
+
}
|
|
251
|
+
function sender(inst, m, call) {
|
|
252
|
+
const client = call.identity.harness === null ? null : roomClientName(call.identity.harness);
|
|
253
|
+
return { member_id: m.id, label: label(m), host: inst.family, client, family: call.identity.family };
|
|
254
|
+
}
|
|
255
|
+
function issue(r, m, at) {
|
|
256
|
+
const invite = newRoomInvite(), until = at + R.ROOM_INVITE_LIFETIME_MS;
|
|
257
|
+
db().prepare("INSERT INTO room_invites (code_hash, room_id, member_id, generation, expires_at) VALUES (?,?,?,?,?)")
|
|
258
|
+
.run(hash(R.ROOM_INVITE_DOMAIN, invite), r, m.id, m.generation, until);
|
|
259
|
+
return { member_id: m.id, label: label(m), invite, expires_at: iso(until) };
|
|
260
|
+
}
|
|
261
|
+
/** Home-wide creation rate and live-room cap, shared by terminal creation and revision 3's open. */
|
|
262
|
+
function creationLimit(at) {
|
|
263
|
+
const recent = db().prepare("SELECT created_at FROM rooms WHERE created_at > ? ORDER BY created_at").all(at - R.ROOM_RATE_WINDOW_MS);
|
|
264
|
+
if (recent.length >= R.ROOM_CREATIONS_PER_MINUTE)
|
|
265
|
+
return limit("ROOM_CREATIONS_PER_MINUTE", recent[0].created_at + R.ROOM_RATE_WINDOW_MS);
|
|
266
|
+
if (Number(db().prepare("SELECT COUNT(*) AS n FROM rooms WHERE state != 'ended'").get().n) >= R.ROOM_LIVE_PER_HOME)
|
|
267
|
+
return limit("ROOM_LIVE_PER_HOME");
|
|
268
|
+
}
|
|
269
|
+
function insertRoom(at, origin, purpose = null) {
|
|
270
|
+
const id = newRoomId();
|
|
271
|
+
db().prepare("INSERT INTO rooms (id,state,created_at,expires_at,max_turns,origin,purpose) VALUES (?,'waiting',?,?,?,?,?)").run(id, at, at + R.ROOM_LIFETIME_MS, R.ROOM_MAX_TURNS, origin, purpose);
|
|
272
|
+
for (let ordinal = 1; ordinal <= R.ROOM_MEMBERS; ordinal++)
|
|
273
|
+
db().prepare("INSERT INTO room_members (room_id,id,ordinal) VALUES (?,?,?)").run(id, newRoomMemberId(), ordinal);
|
|
274
|
+
return id;
|
|
275
|
+
}
|
|
276
|
+
/** Bind an owner to a seat, replacing its binding to an ended room (join's rule). */
|
|
277
|
+
function seat(inst, owner, r, m, call, at) {
|
|
278
|
+
const previous = binding(owner);
|
|
279
|
+
if (previous) {
|
|
280
|
+
db().prepare("DELETE FROM room_bindings WHERE owner_hash = ?").run(owner);
|
|
281
|
+
db().prepare("UPDATE room_members SET owner_hash = NULL, owner_kind = NULL, pid = NULL, pid_start = NULL WHERE room_id = ? AND id = ? AND owner_hash = ?")
|
|
282
|
+
.run(previous.room_id, previous.member_id, owner);
|
|
283
|
+
}
|
|
284
|
+
const shared = !!inst.carried;
|
|
285
|
+
db().prepare(`UPDATE room_members SET owner_hash = ?, owner_kind = ?, pid = ?, pid_start = ?, joined_at = ?,
|
|
286
|
+
joined_sender_json = ?, last_call_at = ?, call_no = call_no + 1 WHERE room_id = ? AND id = ?`)
|
|
287
|
+
.run(owner, shared ? "shared" : "dedicated", shared ? null : process.pid, shared ? null : procStart(process.pid), at, JSON.stringify(sender(inst, m, call)), at, r, m.id);
|
|
288
|
+
db().prepare("INSERT INTO room_bindings (owner_hash,room_id,member_id,generation) VALUES (?,?,?,?)").run(owner, r, m.id, m.generation);
|
|
289
|
+
}
|
|
290
|
+
export function roomCreate() {
|
|
291
|
+
return writing(() => {
|
|
292
|
+
const at = now();
|
|
293
|
+
opportunistic(at);
|
|
294
|
+
const capacity = creationLimit(at);
|
|
295
|
+
if (capacity)
|
|
296
|
+
return refusal(capacity);
|
|
297
|
+
const id = insertRoom(at, "terminal");
|
|
298
|
+
const members = seats(id);
|
|
299
|
+
return { room_id: id, state: "waiting", expires_at: iso(at + R.ROOM_LIFETIME_MS), invites: [issue(id, members[0], at), issue(id, members[1], at)] };
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
// Revision 3: a room prompt open now, by relay home and owner, so that one conversation never has
|
|
303
|
+
// two of its prompts on the person's screen at once. Every owner that can reach a prompt is a
|
|
304
|
+
// dedicated process (host.ts roomOpenDialog admits no shared or keyed entry), so its own server
|
|
305
|
+
// holds this exactly. There is no rate limit (decided 2026-11-16): the person can decline.
|
|
306
|
+
const opening = new Set();
|
|
307
|
+
const OPEN_ANSWER_REFUSAL = {
|
|
308
|
+
declined: R.ROOM_REFUSALS.open_declined, cancelled: R.ROOM_REFUSALS.open_cancelled, timed_out: R.ROOM_REFUSALS.open_timed_out,
|
|
309
|
+
unverified: R.ROOM_REFUSALS.open_unverified, unavailable: R.ROOM_REFUSALS.open_unavailable,
|
|
310
|
+
};
|
|
311
|
+
const liveSeat = (owner) => {
|
|
312
|
+
const a = authenticate(owner);
|
|
313
|
+
return a !== undefined && a.r.state !== "ended";
|
|
314
|
+
};
|
|
315
|
+
/**
|
|
316
|
+
* Revision 3: a root conversation asks the person, through its host's own prompt, to open a room.
|
|
317
|
+
* Only `prompt.ask` resolving "yes" opens one; the caller then holds member-1 and gets member-2's
|
|
318
|
+
* prompt to show the person. No invite or room exists before the yes, and a refused open creates
|
|
319
|
+
* no room, seat or invite; like every room call it still runs the opportunistic expiry sweep.
|
|
320
|
+
*/
|
|
321
|
+
export async function roomOpen(inst, input, call, prompt) {
|
|
322
|
+
const bad = preflight(inst, input, "open", call);
|
|
323
|
+
if (bad)
|
|
324
|
+
return bad;
|
|
325
|
+
// The opener's purpose line (Q7): the model's own words, one line, sanitized like room text and
|
|
326
|
+
// shown to the person only labelled as such. A bad one refuses before anyone is asked.
|
|
327
|
+
let purpose = null;
|
|
328
|
+
if (input.purpose !== undefined) {
|
|
329
|
+
const prepared = /[\r\n\v\f\u0085\u2028\u2029]/u.test(input.purpose) ? undefined : prepareText(input.purpose, call.sanitizeText, R.ROOM_PURPOSE_CODE_POINTS);
|
|
330
|
+
const line = prepared && "clean" in prepared ? prepared.clean : undefined;
|
|
331
|
+
if (line === undefined || /[\r\n\v\f\u0085\u2028\u2029]/u.test(line))
|
|
332
|
+
return refusal(R.ROOM_REFUSALS.purpose);
|
|
333
|
+
purpose = line;
|
|
334
|
+
}
|
|
335
|
+
if (!prompt)
|
|
336
|
+
return refusal(R.ROOM_REFUSALS.open_unavailable);
|
|
337
|
+
const owner = roomOwnerHash(inst.token), key = `${relayHome()}\0${owner}`;
|
|
338
|
+
const before = writing(() => {
|
|
339
|
+
const at = now();
|
|
340
|
+
opportunistic(at);
|
|
341
|
+
if (liveSeat(owner))
|
|
342
|
+
return refusal(R.ROOM_REFUSALS.open_bound);
|
|
343
|
+
const capacity = creationLimit(at);
|
|
344
|
+
if (capacity)
|
|
345
|
+
return refusal(capacity);
|
|
346
|
+
});
|
|
347
|
+
if (before)
|
|
348
|
+
return before;
|
|
349
|
+
if (opening.has(key))
|
|
350
|
+
return refusal(R.ROOM_REFUSALS.open_in_progress);
|
|
351
|
+
opening.add(key);
|
|
352
|
+
let answer;
|
|
353
|
+
try {
|
|
354
|
+
answer = await prompt.ask({ signal: call.signal, purpose });
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
answer = "unavailable";
|
|
358
|
+
}
|
|
359
|
+
finally {
|
|
360
|
+
opening.delete(key);
|
|
361
|
+
}
|
|
362
|
+
if (answer !== "yes")
|
|
363
|
+
return refusal(OPEN_ANSWER_REFUSAL[answer] ?? R.ROOM_REFUSALS.open_unverified);
|
|
364
|
+
try {
|
|
365
|
+
return writing(() => {
|
|
366
|
+
// The yes counts only if the host's prompt still qualifies and the caller is still eligible
|
|
367
|
+
// now, under the writer lock and before anything is written: evidence read between the answer
|
|
368
|
+
// and the lock (a bypass mode switched on meanwhile) cannot open a room.
|
|
369
|
+
let authorized = false;
|
|
370
|
+
try {
|
|
371
|
+
authorized = prompt.authorized();
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
authorized = false;
|
|
375
|
+
}
|
|
376
|
+
if (!authorized)
|
|
377
|
+
return refusal(R.ROOM_REFUSALS.open_unverified);
|
|
378
|
+
const at = now();
|
|
379
|
+
opportunistic(at);
|
|
380
|
+
// Rechecked under the writer lock: the person's yes does not outrank a seat taken meanwhile or a full home.
|
|
381
|
+
if (liveSeat(owner))
|
|
382
|
+
return refusal(R.ROOM_REFUSALS.open_bound);
|
|
383
|
+
const capacity = creationLimit(at);
|
|
384
|
+
if (capacity)
|
|
385
|
+
return refusal(capacity);
|
|
386
|
+
const id = insertRoom(at, "open", purpose), [first, second] = seats(id);
|
|
387
|
+
seat(inst, owner, id, first, call, at);
|
|
388
|
+
db().prepare("UPDATE rooms SET revision = revision + 1 WHERE id = ?").run(id);
|
|
389
|
+
const issued = issue(id, second, at);
|
|
390
|
+
// Member-2's prompt goes to the person's clipboard, never to the model (decided 2026-11-16). If
|
|
391
|
+
// that fails, the throw rolls back the room, seat and invite: nothing is opened.
|
|
392
|
+
if (!prompt.deliver(invitePrompt(issued, "opened", purpose)))
|
|
393
|
+
throw new ClipboardFailed();
|
|
394
|
+
const v = view(authenticate(owner), 0);
|
|
395
|
+
return {
|
|
396
|
+
...v, opened: true,
|
|
397
|
+
clipboard: `Member-2's prompt, with its one-use invite (valid until ${issued.expires_at}), is on the person's clipboard. Tell them to paste it into the conversation they choose; you were given no copy.`,
|
|
398
|
+
};
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
catch (err) {
|
|
402
|
+
if (err instanceof ClipboardFailed)
|
|
403
|
+
return refusal(R.ROOM_REFUSALS.open_clipboard);
|
|
404
|
+
throw err;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
class ClipboardFailed extends Error {
|
|
408
|
+
}
|
|
409
|
+
/** Tests only: forget prompts in progress, as a fresh server process would. */
|
|
410
|
+
export function resetRoomOpenRequestsForTests() {
|
|
411
|
+
opening.clear();
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* The join itself, under the writer lock. With `confirm`, it stops just before the first write
|
|
415
|
+
* that would seat the caller or spend the invite, and returns the question to put to the person;
|
|
416
|
+
* a replay of the caller's own spent invite needs no question and completes as before.
|
|
417
|
+
*/
|
|
418
|
+
function joinIn(inst, input, call, owner, confirm) {
|
|
419
|
+
const at = now();
|
|
420
|
+
opportunistic(at);
|
|
421
|
+
const current = authenticate(owner);
|
|
422
|
+
if (current)
|
|
423
|
+
touch(current, at);
|
|
424
|
+
if (!R.ROOM_INVITE_SHAPE.test(input.invite))
|
|
425
|
+
return unavailable();
|
|
426
|
+
const invite = db().prepare("SELECT * FROM room_invites WHERE code_hash = ?").get(hash(R.ROOM_INVITE_DOMAIN, input.invite));
|
|
427
|
+
if (!invite)
|
|
428
|
+
return unavailable();
|
|
429
|
+
const found = room(invite.room_id);
|
|
430
|
+
if (!found)
|
|
431
|
+
return unavailable();
|
|
432
|
+
const r = refresh(found, at), m = seats(r.id).find((m) => m.id === invite.member_id);
|
|
433
|
+
if (m.generation !== invite.generation)
|
|
434
|
+
return unavailable();
|
|
435
|
+
if (invite.consumed_at !== null) {
|
|
436
|
+
const a = authenticate(owner);
|
|
437
|
+
if (invite.consumed_owner_hash !== owner || !a || a.r.id !== r.id || a.m.id !== m.id || a.m.generation !== invite.generation)
|
|
438
|
+
return unavailable();
|
|
439
|
+
const rate = readRate(a, at);
|
|
440
|
+
if (rate)
|
|
441
|
+
return refusal(rate);
|
|
442
|
+
return { ...view(a, 0), joined: true, repeated: true };
|
|
443
|
+
}
|
|
444
|
+
if (r.state === "ended" || invite.expires_at <= at || m.owner_hash || seats(r.id).some((s) => s.owner_hash === owner))
|
|
445
|
+
return unavailable();
|
|
446
|
+
const previous = binding(owner);
|
|
447
|
+
if (previous) {
|
|
448
|
+
const old = room(previous.room_id);
|
|
449
|
+
if (old && refresh(old, at).state !== "ended")
|
|
450
|
+
return unavailable();
|
|
451
|
+
}
|
|
452
|
+
if (confirm) {
|
|
453
|
+
const other = seats(r.id).find((s) => s.id !== m.id);
|
|
454
|
+
return { question: { room_id: r.id, label: label(m), peer: other.owner_hash && other.joined_sender_json ? JSON.parse(other.joined_sender_json) : null, origin: r.origin, purpose: r.purpose } };
|
|
455
|
+
}
|
|
456
|
+
seat(inst, owner, r.id, m, call, at);
|
|
457
|
+
db().prepare("UPDATE room_invites SET consumed_at = ?, consumed_owner_hash = ? WHERE code_hash = ?").run(at, owner, invite.code_hash);
|
|
458
|
+
db().prepare("UPDATE rooms SET state = ?, revision = revision + 1 WHERE id = ?").run(seats(r.id).every((s) => s.owner_hash) ? "open" : "waiting", r.id);
|
|
459
|
+
return { ...view(authenticate(owner), 0), joined: true, repeated: false };
|
|
460
|
+
}
|
|
461
|
+
const JOIN_ANSWER_REFUSAL = {
|
|
462
|
+
declined: R.ROOM_REFUSALS.join_declined, cancelled: R.ROOM_REFUSALS.join_cancelled, timed_out: R.ROOM_REFUSALS.join_timed_out,
|
|
463
|
+
unverified: R.ROOM_REFUSALS.join_unverified, unavailable: R.ROOM_REFUSALS.join_unavailable,
|
|
464
|
+
};
|
|
465
|
+
/**
|
|
466
|
+
* Join with a person-pasted invite. Where the server supplies `prompt` (the host's dialog is
|
|
467
|
+
* qualified to reach the person: revision 3, option B), relay first checks the invite without
|
|
468
|
+
* spending it, then asks the person; only their explicit yes, still authorized under the writer
|
|
469
|
+
* lock, seats the caller. A no, or no answer, seats nothing and leaves the invite unspent.
|
|
470
|
+
*/
|
|
471
|
+
export async function roomJoin(inst, input, call, prompt = null) {
|
|
472
|
+
const bad = preflight(inst, input, "join", call);
|
|
473
|
+
if (bad)
|
|
474
|
+
return bad;
|
|
475
|
+
const owner = roomOwnerHash(inst.token);
|
|
476
|
+
if (!prompt)
|
|
477
|
+
return writing(() => joinIn(inst, input, call, owner, false));
|
|
478
|
+
const first = writing(() => joinIn(inst, input, call, owner, true));
|
|
479
|
+
if (!("question" in first))
|
|
480
|
+
return first;
|
|
481
|
+
const key = `${relayHome()}\0${owner}`;
|
|
482
|
+
if (opening.has(key))
|
|
483
|
+
return refusal(R.ROOM_REFUSALS.join_in_progress);
|
|
484
|
+
opening.add(key);
|
|
485
|
+
let answer;
|
|
486
|
+
try {
|
|
487
|
+
answer = await prompt.ask(first.question, { signal: call.signal });
|
|
488
|
+
}
|
|
489
|
+
catch {
|
|
490
|
+
answer = "unavailable";
|
|
491
|
+
}
|
|
492
|
+
finally {
|
|
493
|
+
opening.delete(key);
|
|
494
|
+
}
|
|
495
|
+
if (answer !== "yes")
|
|
496
|
+
return refusal(JOIN_ANSWER_REFUSAL[answer] ?? R.ROOM_REFUSALS.join_unverified);
|
|
497
|
+
return writing(() => {
|
|
498
|
+
let authorized = false;
|
|
499
|
+
try {
|
|
500
|
+
authorized = prompt.authorized();
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
authorized = false;
|
|
504
|
+
}
|
|
505
|
+
if (!authorized)
|
|
506
|
+
return refusal(R.ROOM_REFUSALS.join_unverified);
|
|
507
|
+
// Everything is checked again: the invite may have been spent, the seat taken or the room ended meanwhile.
|
|
508
|
+
return joinIn(inst, input, call, owner, false);
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
function retry(a, input, argsHash) {
|
|
512
|
+
const old = db().prepare("SELECT seq,args_hash FROM room_messages WHERE room_id = ? AND member_id = ? AND request_id = ?")
|
|
513
|
+
.get(a.r.id, a.m.id, input.request_id);
|
|
514
|
+
if (!old)
|
|
515
|
+
return;
|
|
516
|
+
// Look up the request first, but malformed cursors still disclose no transcript.
|
|
517
|
+
if (!cursorOK(a, input.cursor))
|
|
518
|
+
return refusal(R.ROOM_REFUSALS.arguments);
|
|
519
|
+
const cursor = input.cursor;
|
|
520
|
+
const rate = readRate(a, now());
|
|
521
|
+
if (rate)
|
|
522
|
+
return refusal(rate);
|
|
523
|
+
if (old.args_hash !== argsHash)
|
|
524
|
+
return refusedView(a, cursor, R.ROOM_REFUSALS.changed_retry);
|
|
525
|
+
return { ...view(a, cursor), accepted_seq: old.seq, repeated: true };
|
|
526
|
+
}
|
|
527
|
+
function rowRate(id, at) {
|
|
528
|
+
const recent = db().prepare("SELECT created_at FROM room_messages WHERE room_id = ? AND created_at > ? ORDER BY created_at").all(id, at - R.ROOM_RATE_WINDOW_MS);
|
|
529
|
+
if (recent.length >= R.ROOM_ROWS_PER_MINUTE)
|
|
530
|
+
return limit("ROOM_ROWS_PER_MINUTE", recent[0].created_at + R.ROOM_RATE_WINDOW_MS);
|
|
531
|
+
}
|
|
532
|
+
export async function roomSend(inst, input, call) {
|
|
533
|
+
const bad = preflight(inst, input, "send", call);
|
|
534
|
+
if (bad)
|
|
535
|
+
return bad;
|
|
536
|
+
const owner = roomOwnerHash(inst.token), argsHash = hash(R.ROOM_SEND_DOMAIN, JSON.stringify([input.text, input.stance]));
|
|
537
|
+
const start = writing(() => {
|
|
538
|
+
opportunistic(now());
|
|
539
|
+
const a = authenticate(owner);
|
|
540
|
+
if (!a)
|
|
541
|
+
return unavailable();
|
|
542
|
+
const repeated = retry(a, input, argsHash);
|
|
543
|
+
if (repeated) {
|
|
544
|
+
touch(a, now());
|
|
545
|
+
return repeated;
|
|
546
|
+
}
|
|
547
|
+
return stamp(a);
|
|
548
|
+
});
|
|
549
|
+
if (!("owner_hash" in start))
|
|
550
|
+
return start;
|
|
551
|
+
// Sanitize outside the lock: a re-entrant adapter cannot smuggle an old generation's write.
|
|
552
|
+
operations++;
|
|
553
|
+
try {
|
|
554
|
+
const prepared = prepareText(input.text, call.sanitizeText);
|
|
555
|
+
return writing(() => {
|
|
556
|
+
const a = authenticate(owner, start);
|
|
557
|
+
if (!a)
|
|
558
|
+
return unavailable();
|
|
559
|
+
touch(a, now());
|
|
560
|
+
const repeated = retry(a, input, argsHash);
|
|
561
|
+
if (repeated)
|
|
562
|
+
return repeated;
|
|
563
|
+
if (!cursorOK(a, input.cursor))
|
|
564
|
+
return refusal(R.ROOM_REFUSALS.arguments);
|
|
565
|
+
if ("reason" in prepared)
|
|
566
|
+
return refusal(prepared.reason);
|
|
567
|
+
const { clean } = prepared, { r, m } = a, at = now();
|
|
568
|
+
if (r.state !== "open")
|
|
569
|
+
return refusedSendView(a, input.cursor, R.ROOM_REFUSALS.not_open);
|
|
570
|
+
const rows = messages(r.id);
|
|
571
|
+
if (rows.some((row) => row.seq > input.cursor && row.sender_owner_hash !== owner))
|
|
572
|
+
return refusedSendView(a, input.cursor, R.ROOM_REFUSALS.stale);
|
|
573
|
+
if (m.ordinal !== r.next_ordinal)
|
|
574
|
+
return refusedSendView(a, input.cursor, R.ROOM_REFUSALS.turn);
|
|
575
|
+
if (r.turns >= r.max_turns)
|
|
576
|
+
return refusedSendView(a, input.cursor, limit("ROOM_MAX_TURNS"));
|
|
577
|
+
const last = rows.filter((row) => row.member_id === m.id).at(-1);
|
|
578
|
+
if (last && at - last.created_at < R.ROOM_SEND_INTERVAL_MS)
|
|
579
|
+
return refusedSendView(a, input.cursor, limit("ROOM_SEND_INTERVAL_MS", last.created_at + R.ROOM_SEND_INTERVAL_MS));
|
|
580
|
+
const rate = rowRate(r.id, at);
|
|
581
|
+
if (rate)
|
|
582
|
+
return refusedSendView(a, input.cursor, rate);
|
|
583
|
+
const seq = latest(r.id) + 1;
|
|
584
|
+
const row = { room_id: r.id, seq, member_id: m.id, sender_owner_hash: owner, sender_json: m.joined_sender_json, created_at: at, text: clean, stance: input.stance, request_id: input.request_id, args_hash: argsHash };
|
|
585
|
+
if (!fits(wire(row)))
|
|
586
|
+
return refusal(R.ROOM_REFUSALS.text);
|
|
587
|
+
db().prepare(`INSERT INTO room_messages (room_id,seq,member_id,sender_owner_hash,sender_json,created_at,text,stance,request_id,args_hash)
|
|
588
|
+
VALUES (?,?,?,?,?,?,?,?,?,?)`).run(r.id, seq, m.id, owner, row.sender_json, at, clean, input.stance, input.request_id, argsHash);
|
|
589
|
+
db().prepare("UPDATE rooms SET turns = turns + 1, next_ordinal = ?, revision = revision + 1 WHERE id = ?").run(m.ordinal === 1 ? 2 : 1, r.id);
|
|
590
|
+
const prior = rows.at(-1), previousMember = rows.filter((row) => row.member_id !== null).at(-1);
|
|
591
|
+
if (input.stance === "agree" && prior?.stance === "agree")
|
|
592
|
+
end(r, { outcome: "agree", reason: "agreement", conclusion_seq: seq, closed_by: null }, at, false);
|
|
593
|
+
else if (r.turns + 1 >= r.max_turns)
|
|
594
|
+
end(r, noAgreement("turn_limit"), at, false);
|
|
595
|
+
else if (previousMember?.stance === "crux")
|
|
596
|
+
end(r, noAgreement("crux"), at, false);
|
|
597
|
+
return { ...view(a, input.cursor), accepted_seq: seq, repeated: false };
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
finally {
|
|
601
|
+
operations--;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
function readRate(a, at) {
|
|
605
|
+
const times = JSON.parse(a.m.read_times_json).filter((t) => t > at - R.ROOM_READ_WINDOW_MS);
|
|
606
|
+
if (times.length >= R.ROOM_READS_PER_SECOND)
|
|
607
|
+
return limit("ROOM_READS_PER_SECOND", times[0] + R.ROOM_READ_WINDOW_MS);
|
|
608
|
+
db().prepare("UPDATE room_members SET read_times_json = ? WHERE room_id = ? AND id = ?").run(JSON.stringify([...times, at]), a.r.id, a.m.id);
|
|
609
|
+
}
|
|
610
|
+
function refusedSendView(a, cursor, reason) {
|
|
611
|
+
const rate = readRate(a, now());
|
|
612
|
+
return rate ? refusal(rate) : refusedView(a, cursor, reason);
|
|
613
|
+
}
|
|
614
|
+
export async function roomTranscript(inst, input, call) {
|
|
615
|
+
const bad = preflight(inst, input, "transcript", call);
|
|
616
|
+
if (bad)
|
|
617
|
+
return bad;
|
|
618
|
+
return writing(() => {
|
|
619
|
+
const at = now();
|
|
620
|
+
opportunistic(at);
|
|
621
|
+
const a = authenticate(roomOwnerHash(inst.token));
|
|
622
|
+
if (!a)
|
|
623
|
+
return unavailable();
|
|
624
|
+
touch(a, at);
|
|
625
|
+
if (!cursorOK(a, input.cursor))
|
|
626
|
+
return refusal(R.ROOM_REFUSALS.arguments);
|
|
627
|
+
const rate = readRate(a, at);
|
|
628
|
+
if (rate)
|
|
629
|
+
return refusal(rate);
|
|
630
|
+
return view(a, input.cursor, true);
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
export async function roomClose(inst, input, call) {
|
|
634
|
+
const bad = preflight(inst, input, "close", call);
|
|
635
|
+
if (bad)
|
|
636
|
+
return bad;
|
|
637
|
+
return writing(() => {
|
|
638
|
+
const at = now();
|
|
639
|
+
opportunistic(at);
|
|
640
|
+
const a = authenticate(roomOwnerHash(inst.token));
|
|
641
|
+
if (!a)
|
|
642
|
+
return unavailable();
|
|
643
|
+
touch(a, at);
|
|
644
|
+
if (!cursorOK(a, input.cursor))
|
|
645
|
+
return refusal(R.ROOM_REFUSALS.arguments);
|
|
646
|
+
const rate = readRate(a, at);
|
|
647
|
+
if (rate)
|
|
648
|
+
return refusal(rate);
|
|
649
|
+
end(a.r, noAgreement("closed", a.m.id), at);
|
|
650
|
+
return view(a, input.cursor);
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
export async function roomWait(inst, input, call) {
|
|
654
|
+
const bad = preflight(inst, input, "wait", call);
|
|
655
|
+
if (bad)
|
|
656
|
+
return bad;
|
|
657
|
+
const owner = roomOwnerHash(inst.token), nonce = hex();
|
|
658
|
+
const start = writing(() => {
|
|
659
|
+
const at = now();
|
|
660
|
+
opportunistic(at);
|
|
661
|
+
const a = authenticate(owner);
|
|
662
|
+
if (!a)
|
|
663
|
+
return unavailable();
|
|
664
|
+
if (!cursorOK(a, input.cursor))
|
|
665
|
+
return refusal(R.ROOM_REFUSALS.arguments);
|
|
666
|
+
const rate = readRate(a, at);
|
|
667
|
+
if (rate)
|
|
668
|
+
return refusal(rate);
|
|
669
|
+
const peer = seats(a.r.id).find((m) => m.id !== a.m.id);
|
|
670
|
+
// Unread text and an ending are a normal result however long the peer has been silent.
|
|
671
|
+
const v = view(a, input.cursor);
|
|
672
|
+
if (v.messages.length || v.state === "ended") {
|
|
673
|
+
touch(a, at);
|
|
674
|
+
return { ...v, wait_ended: false };
|
|
675
|
+
}
|
|
676
|
+
if (a.r.state === "open" && a.m.ordinal === a.r.next_ordinal)
|
|
677
|
+
return { ...v, refused: true, reason: R.ROOM_REFUSALS.wait_turn };
|
|
678
|
+
touch(a, at);
|
|
679
|
+
if (a.m.wait_nonce && liveness(a.m.wait_pid, a.m.wait_start) !== "dead")
|
|
680
|
+
return refusedView(a, input.cursor, R.ROOM_REFUSALS.duplicate_wait);
|
|
681
|
+
const stop = peerStop(peer, at);
|
|
682
|
+
if (stop.stopped)
|
|
683
|
+
return refusedView(a, input.cursor, R.ROOM_REFUSALS.idle_peer);
|
|
684
|
+
// A long-wait host (its call moves to the background) may wait for hours in one call, as its
|
|
685
|
+
// status waits do; elsewhere the 50 s maximum and block_s apply.
|
|
686
|
+
const ms = Math.max(0, Math.min((input.wait_s ?? R.ROOM_WAIT_DEFAULT_S) * 1000, call.long_waits ? R.ROOM_LONG_WAIT_S * 1000 : Math.min(R.ROOM_WAIT_MAX_S, call.block_s) * 1000, (call.host_wait_cap_s ?? Infinity) * 1000, (call.deadline ?? Infinity) - at, expiry(a.r) - at, stop.until - at));
|
|
687
|
+
db().prepare("UPDATE room_members SET wait_pid = ?, wait_start = ?, wait_nonce = ? WHERE room_id = ? AND id = ?")
|
|
688
|
+
.run(process.pid, procStart(process.pid), nonce, a.r.id, a.m.id);
|
|
689
|
+
return { expected: stamp(a), revision: a.r.revision, ms, peerPid: peer.owner_kind === "dedicated" ? peer.pid : null };
|
|
690
|
+
});
|
|
691
|
+
if (!("expected" in start))
|
|
692
|
+
return start;
|
|
693
|
+
operations++;
|
|
694
|
+
const began = now();
|
|
695
|
+
try {
|
|
696
|
+
const changed = await waitUntil(() => reading(() => {
|
|
697
|
+
// Wake on a room change (join, re-seat, send, terminal line, ending), never on a bare peer
|
|
698
|
+
// call: two members waiting at once would otherwise wake each other with empty results,
|
|
699
|
+
// each wake costing a model continuation, for as long as both kept polling.
|
|
700
|
+
const b = binding(owner), expected = start.expected;
|
|
701
|
+
return !b || b.room_id !== expected.room_id || b.member_id !== expected.member_id || b.generation !== expected.generation
|
|
702
|
+
|| room(expected.room_id)?.revision !== start.revision
|
|
703
|
+
// The peer's server exiting ends the wait too (a cheap signal-0 check): the view that
|
|
704
|
+
// follows detaches its seat and says it is gone, rather than waiting on for hours.
|
|
705
|
+
|| (start.peerPid !== null && !pidAlive(start.peerPid));
|
|
706
|
+
}), { ms: start.ms, lender: null, signal: call.signal, onTick: call.onTick });
|
|
707
|
+
return writing(() => {
|
|
708
|
+
const a = authenticate(owner, start.expected);
|
|
709
|
+
if (!a)
|
|
710
|
+
return unavailable();
|
|
711
|
+
const v = view(a, input.cursor);
|
|
712
|
+
// Woken by the peer's server exiting (or cut at the silence fallback) with nothing to read:
|
|
713
|
+
// the same refusal, and its stop-and-report text, that the next wait would get at once.
|
|
714
|
+
if (!v.messages.length && v.state !== "ended" && v.poll.stopped)
|
|
715
|
+
return { ...v, refused: true, reason: R.ROOM_REFUSALS.idle_peer };
|
|
716
|
+
return { ...v, wait_ended: a.r.state !== "ended" && !changed && !call.signal?.aborted && now() - began >= start.ms };
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
finally {
|
|
720
|
+
try {
|
|
721
|
+
writing(() => db().prepare("UPDATE room_members SET wait_pid = NULL, wait_start = NULL, wait_nonce = NULL WHERE room_id = ? AND id = ? AND generation = ? AND wait_nonce = ?")
|
|
722
|
+
.run(start.expected.room_id, start.expected.member_id, start.expected.generation, nonce));
|
|
723
|
+
}
|
|
724
|
+
finally {
|
|
725
|
+
operations--;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
export function roomReseat(roomId, memberId, expectedGeneration) {
|
|
730
|
+
return writing(() => {
|
|
731
|
+
const at = now();
|
|
732
|
+
opportunistic(at);
|
|
733
|
+
const found = room(roomId);
|
|
734
|
+
if (!found)
|
|
735
|
+
return unavailable();
|
|
736
|
+
const r = refresh(found, at), m = seats(roomId).find((m) => m.id === memberId);
|
|
737
|
+
if (!m || m.generation !== expectedGeneration)
|
|
738
|
+
return unavailable();
|
|
739
|
+
if (r.state === "ended")
|
|
740
|
+
return refusal(R.ROOM_REFUSALS.not_open);
|
|
741
|
+
const times = JSON.parse(m.reseat_times_json).filter((t) => t > at - R.ROOM_RATE_WINDOW_MS);
|
|
742
|
+
if (times.length >= R.ROOM_RESEATS_PER_MINUTE)
|
|
743
|
+
return refusal(limit("ROOM_RESEATS_PER_MINUTE", times[0] + R.ROOM_RATE_WINDOW_MS));
|
|
744
|
+
db().prepare("DELETE FROM room_bindings WHERE room_id = ? AND member_id = ?").run(roomId, memberId);
|
|
745
|
+
db().prepare("DELETE FROM room_invites WHERE room_id = ? AND member_id = ?").run(roomId, memberId);
|
|
746
|
+
db().prepare(`UPDATE room_members SET generation = generation + 1, owner_hash = NULL, owner_kind = NULL, pid = NULL, pid_start = NULL,
|
|
747
|
+
joined_at = NULL, joined_sender_json = NULL, last_call_at = NULL, wait_pid = NULL, wait_start = NULL, wait_nonce = NULL,
|
|
748
|
+
reseat_times_json = ? WHERE room_id = ? AND id = ?`).run(JSON.stringify([...times, at]), roomId, memberId);
|
|
749
|
+
db().prepare("UPDATE rooms SET state = 'waiting', revision = revision + 1 WHERE id = ?").run(roomId);
|
|
750
|
+
return { room_id: roomId, member_id: memberId, state: "waiting", origin: r.origin, purpose: r.purpose, invite: issue(roomId, seats(roomId).find((m) => m.id === memberId), at) };
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
export function roomList() {
|
|
754
|
+
return reading(() => db().prepare("SELECT * FROM rooms ORDER BY created_at,id").all().map((row) => {
|
|
755
|
+
const r = row;
|
|
756
|
+
return { room_id: r.id, origin: r.origin, state: r.state, created_at: iso(r.created_at), expires_at: iso(r.expires_at), seats: seats(r.id).map((m) => ({ member_id: m.id, label: label(m), host: m.joined_sender_json ? JSON.parse(m.joined_sender_json).host : null })) };
|
|
757
|
+
}));
|
|
758
|
+
}
|
|
759
|
+
/** Administrative reads never acquire the writer lock or perform opportunistic maintenance. */
|
|
760
|
+
function reading(fn) {
|
|
761
|
+
const d = db();
|
|
762
|
+
d.exec("BEGIN");
|
|
763
|
+
operations++;
|
|
764
|
+
try {
|
|
765
|
+
return fn();
|
|
766
|
+
}
|
|
767
|
+
finally {
|
|
768
|
+
try {
|
|
769
|
+
d.exec("ROLLBACK");
|
|
770
|
+
}
|
|
771
|
+
finally {
|
|
772
|
+
operations--;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
export function roomPrint(roomId) {
|
|
777
|
+
return reading(() => {
|
|
778
|
+
const r = room(roomId);
|
|
779
|
+
if (!r)
|
|
780
|
+
return unavailable();
|
|
781
|
+
const members = seats(roomId);
|
|
782
|
+
return {
|
|
783
|
+
room_id: r.id, origin: r.origin, purpose: r.purpose, state: r.state, created_at: iso(r.created_at), expires_at: iso(r.expires_at), ended_at: r.ended_at === null ? null : iso(r.ended_at),
|
|
784
|
+
revision: r.revision, turns: r.turns, max_turns: r.max_turns, next: r.state === "open" ? members.find((m) => m.ordinal === r.next_ordinal).id : null,
|
|
785
|
+
seats: members.map((m) => {
|
|
786
|
+
const s = m.joined_sender_json ? JSON.parse(m.joined_sender_json) : null;
|
|
787
|
+
return { member_id: m.id, label: label(m), host: s?.host ?? null, ordinal: m.ordinal, generation: m.generation,
|
|
788
|
+
seat: m.owner_hash ? "joined" : "unseated", client: s?.client ?? null, family: s?.family ?? "unknown", owner_fingerprint: m.owner_hash?.slice(0, 24) ?? null,
|
|
789
|
+
owner_kind: m.owner_kind, pid: m.pid, pid_start: m.pid_start, liveness: m.owner_kind === "dedicated" ? liveness(m.pid, m.pid_start, true) : "unknown" };
|
|
790
|
+
}), messages: messages(roomId).map(wire), ending: r.ending_json ? JSON.parse(r.ending_json) : null, note: R.ROOM_NOTE,
|
|
791
|
+
};
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
export function roomAddLine(roomId, text, sanitizeText) {
|
|
795
|
+
operations++;
|
|
796
|
+
try {
|
|
797
|
+
const prepared = prepareText(text, sanitizeText);
|
|
798
|
+
return writing(() => {
|
|
799
|
+
const at = now();
|
|
800
|
+
opportunistic(at);
|
|
801
|
+
const found = room(roomId);
|
|
802
|
+
if (!found)
|
|
803
|
+
return unavailable();
|
|
804
|
+
const r = refresh(found, at);
|
|
805
|
+
if (r.state !== "open")
|
|
806
|
+
return refusal(R.ROOM_REFUSALS.not_open);
|
|
807
|
+
if ("reason" in prepared)
|
|
808
|
+
return refusal(prepared.reason);
|
|
809
|
+
const { clean } = prepared;
|
|
810
|
+
const count = Number(db().prepare("SELECT COUNT(*) AS n FROM room_messages WHERE room_id = ? AND member_id IS NULL").get(roomId).n);
|
|
811
|
+
if (count >= R.ROOM_TERMINAL_ROWS)
|
|
812
|
+
return refusal(limit("ROOM_TERMINAL_ROWS"));
|
|
813
|
+
const rate = rowRate(roomId, at);
|
|
814
|
+
if (rate)
|
|
815
|
+
return refusal(rate);
|
|
816
|
+
const seq = latest(roomId) + 1;
|
|
817
|
+
if (!fits({ seq, sender: terminalSender, at: iso(at), text: clean, stance: null }))
|
|
818
|
+
return refusal(R.ROOM_REFUSALS.text);
|
|
819
|
+
db().prepare("INSERT INTO room_messages (room_id,seq,sender_json,created_at,text) VALUES (?,?,?,?,?)").run(roomId, seq, JSON.stringify(terminalSender), at, clean);
|
|
820
|
+
db().prepare("UPDATE rooms SET revision = revision + 1 WHERE id = ?").run(roomId);
|
|
821
|
+
return { injected: true, room_id: roomId, seq };
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
finally {
|
|
825
|
+
operations--;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
export function roomCloseAtTerminal(roomId) {
|
|
829
|
+
return writing(() => {
|
|
830
|
+
const at = now();
|
|
831
|
+
opportunistic(at);
|
|
832
|
+
const found = room(roomId);
|
|
833
|
+
if (!found)
|
|
834
|
+
return unavailable();
|
|
835
|
+
const r = refresh(found, at);
|
|
836
|
+
end(r, noAgreement("closed", "terminal"), at);
|
|
837
|
+
return { room_id: roomId, state: "ended", ending: JSON.parse(room(roomId).ending_json) };
|
|
838
|
+
});
|
|
839
|
+
}
|