mouth-all-personas: one Matrix mouth serves every Persona; deliveries carry mentions and is_direct, refusals are typed; same-server DM invites accepted; the ring is deleted (Persona turns are the heartbeat's) (squash of eureka-body/mouth-all-personas 7b63031..5b628e2; Soul s1-s3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
18bbe6c312
commit
cc76f0f2d0
7 changed files with 634 additions and 160 deletions
|
|
@ -9,13 +9,24 @@ export const kinds = Object.freeze({
|
|||
ack: "gamecult.persona.chat_ack.v1",
|
||||
sendRequest: "gamecult.persona.chat_send_request.v1",
|
||||
sendReceipt: "gamecult.persona.chat_send_receipt.v1",
|
||||
refusal: "gamecult.persona.chat_refusal.v1",
|
||||
});
|
||||
|
||||
export const refusals = Object.freeze(["Brake", "PersonaMismatch", "UnknownRoom", "EmptyText", "SendFailed"]);
|
||||
export const refusals = Object.freeze(["Brake", "PersonaMismatch", "UnknownRoom", "EmptyText", "SendFailed", "UnknownPersona"]);
|
||||
|
||||
const maxTextBytes = 4000;
|
||||
const maxContext = 20;
|
||||
|
||||
// Per-delivery bounds, applied where the mouth reads Matrix: the body is bounded like a send,
|
||||
// a context line and a display name are smaller, and a reply is paged to a byte budget.
|
||||
export const limits = Object.freeze({ textBytes: maxTextBytes, contextBytes: 1000, displayBytes: 256, mentions: 64, replyBytes: 256 * 1024 });
|
||||
|
||||
// `value` cut to at most `maxBytes` of UTF-8 without splitting a character.
|
||||
export function clip(value, maxBytes) {
|
||||
if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
|
||||
return Buffer.from(value, "utf8").subarray(0, maxBytes).toString("utf8").replace(/<2F>$/, "");
|
||||
}
|
||||
|
||||
export function pendingRequestTuple({ persona, afterSeq }) {
|
||||
return [text(persona, "persona"), seq(afterSeq, "after_seq")];
|
||||
}
|
||||
|
|
@ -50,23 +61,38 @@ export function sendReceiptTuple({ requestId, eventId = null, refusal = null })
|
|||
export function parseSendReceipt(t) {
|
||||
const [requestId, eventId, refusal] = tuple(t, 3, "chat_send_receipt");
|
||||
if ((eventId === null) === (refusal === null)) throw new Error("a send receipt carries exactly one of event_id and refusal");
|
||||
if (refusal !== null && !refusals.includes(refusal)) throw new Error(`unknown refusal ${String(refusal)}`);
|
||||
return { requestId: text(requestId, "request_id"), eventId: eventId === null ? null : text(eventId, "event_id"), refusal };
|
||||
}
|
||||
|
||||
// A typed refusal for a request that names a Persona the mouth does not serve.
|
||||
export function refusalTuple({ persona, refusal }) {
|
||||
if (!refusals.includes(refusal)) throw new Error(`unknown refusal ${refusal}`);
|
||||
return [text(persona, "persona"), refusal];
|
||||
}
|
||||
export function parseRefusal(t) {
|
||||
const [persona, refusal] = tuple(t, 2, "chat_refusal");
|
||||
if (!refusals.includes(refusal)) throw new Error(`unknown refusal ${String(refusal)}`);
|
||||
return { persona: text(persona, "persona"), refusal };
|
||||
}
|
||||
|
||||
export function deliveryTuple(d) {
|
||||
return [
|
||||
seq(d.seq, "seq"), text(d.roomAlias, "room_alias"), text(d.roomId, "room_id"), text(d.eventId, "event_id"),
|
||||
text(d.sender, "sender"), text(d.senderDisplay, "sender_display"), String(d.text), seq(d.atUnixMs, "at_unix_ms"),
|
||||
d.context.slice(-maxContext).map(c => [text(c.sender, "sender"), String(c.text), seq(c.atUnixMs, "at_unix_ms")]),
|
||||
d.mentions.map(id => text(id, "mention")), flag(d.isDirect, "is_direct"),
|
||||
];
|
||||
}
|
||||
export function parseDelivery(t) {
|
||||
const [s, roomAlias, roomId, eventId, sender, senderDisplay, body, atUnixMs, context] = tuple(t, 9, "delivery");
|
||||
const [s, roomAlias, roomId, eventId, sender, senderDisplay, body, atUnixMs, context, mentions, isDirect] = tuple(t, 11, "delivery");
|
||||
if (!Array.isArray(context)) throw new Error("delivery context must be a list");
|
||||
if (!Array.isArray(mentions)) throw new Error("delivery mentions must be a list");
|
||||
return {
|
||||
seq: seq(s, "seq"), roomAlias: text(roomAlias, "room_alias"), roomId: text(roomId, "room_id"), eventId: text(eventId, "event_id"),
|
||||
sender: text(sender, "sender"), senderDisplay: text(senderDisplay, "sender_display"), text: String(body), atUnixMs: seq(atUnixMs, "at_unix_ms"),
|
||||
context: context.map(c => { const [cs, ct, ca] = tuple(c, 3, "context"); return { sender: text(cs, "sender"), text: String(ct), atUnixMs: seq(ca, "at_unix_ms") }; }),
|
||||
mentions: mentions.map(id => text(id, "mention")), isDirect: flag(isDirect, "is_direct"),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -108,6 +134,10 @@ function text(v, what) {
|
|||
if (typeof v !== "string" || v === "") throw new Error(`${what} must be a non-empty string`);
|
||||
return v;
|
||||
}
|
||||
function flag(v, what) {
|
||||
if (typeof v !== "boolean") throw new Error(`${what} must be a boolean`);
|
||||
return v;
|
||||
}
|
||||
function seq(v, what) {
|
||||
if (!Number.isSafeInteger(v) || v < 0) throw new Error(`${what} must be a non-negative integer`);
|
||||
return v;
|
||||
|
|
|
|||
|
|
@ -1,21 +1,23 @@
|
|||
// The Matrix ear and mouth of one Persona. One process per Persona.
|
||||
// The Matrix ear and mouth of every Persona. One process: one account (token) and
|
||||
// one /sync loop per Persona, one CultNet endpoint for all of them.
|
||||
//
|
||||
// Ear: /sync the configured rooms; every message from another sender becomes a
|
||||
// delivery kept in memory. The /sync position (next_batch) is persisted only when
|
||||
// an ack covers it, so a restart before the ack re-delivers instead of losing.
|
||||
// Ear: /sync the configured rooms (and the account's direct rooms); every message
|
||||
// from another sender becomes a delivery kept in memory, carrying its sender id,
|
||||
// its m.mentions user ids and whether the room is a DM. The /sync position
|
||||
// (next_batch) is persisted only when an ack covers it, so a restart before the
|
||||
// ack re-delivers instead of losing. Reading wakes nothing: the heartbeat polls
|
||||
// with a non-consuming chat_pending_request and decides who runs.
|
||||
// Mouth: a send request becomes one PUT with txnId = request_id (a retry is
|
||||
// idempotent) and only while the instance brake is released.
|
||||
// Ring: the first delivery of an idle window starts the Persona's one-shot unit.
|
||||
// Starting is a request; the unit's own gate decides.
|
||||
// idempotent), and a room is joined, only while that Persona's brake is released.
|
||||
//
|
||||
// The Matrix access token is read here, from a systemd credential, and nowhere
|
||||
// else. It is never put in a document, an environment passed to a child, or a log.
|
||||
// Each Matrix access token is read here, from its own systemd credential, and
|
||||
// nowhere else. It is never put in a document, an environment passed to a child,
|
||||
// or a log, and it is only ever presented in its own Persona's Authorization header.
|
||||
//
|
||||
// Everything outside this process is a port (fetch, state, brake, ring, clock), so
|
||||
// the core runs against a fake homeserver with no CultLib and no daemon.
|
||||
import { execFile } from "node:child_process";
|
||||
// Everything outside this process is a port (fetch, state, brake, clock), so the
|
||||
// core runs against a fake homeserver with no CultLib and no daemon.
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { createSocket } from "node:dgram";
|
||||
import { resolve, join } from "node:path";
|
||||
|
|
@ -25,16 +27,20 @@ import * as docs from "./persona-chat-documents.mjs";
|
|||
const API = "/_matrix/client/v3";
|
||||
const BRAKE_TYPE = "eureka.control.brake.v1";
|
||||
const CONTEXT = 20;
|
||||
const RING_WINDOW_MS = 5 * 60 * 1000;
|
||||
const MAX_PENDING = 500;
|
||||
const SLUG = /^[A-Za-z0-9_-]{1,64}$/;
|
||||
|
||||
export function createMouth({
|
||||
persona, homeserver, rooms, token, fetch: httpFetch = globalThis.fetch, state, brake, ring,
|
||||
now = Date.now, log = () => {}, syncTimeoutMs = 30000,
|
||||
persona, homeserver, serverName, rooms, token, fetch: httpFetch = globalThis.fetch, state, brake,
|
||||
now = Date.now, log = () => {}, syncTimeoutMs = 30000, maxPending = MAX_PENDING,
|
||||
}) {
|
||||
if (!persona || !homeserver || !token || !rooms?.length) throw new Error("persona, homeserver, rooms and token are required");
|
||||
const say = message => log(redact(String(message), token));
|
||||
const roomIdByAlias = new Map();
|
||||
const aliasByRoomId = new Map();
|
||||
const joinedAliases = new Set();
|
||||
const freshRooms = new Set(); // joined by this process since the last sync: their history is context, not mail
|
||||
const directRooms = new Set(); // room ids the account marks as DMs (m.direct)
|
||||
const history = new Map(); // room_id -> last CONTEXT messages, oldest first
|
||||
const displayNames = new Map();
|
||||
let selfId = null;
|
||||
|
|
@ -43,8 +49,10 @@ export function createMouth({
|
|||
let pending = []; // deliveries not yet acked
|
||||
let batches = []; // { token, maxSeq }: positions awaiting an ack
|
||||
let committed = null; // the position that is persisted
|
||||
let lastRingAt = -Infinity;
|
||||
let started = false;
|
||||
const directContent = {}; // the account's m.direct content: user id -> room ids
|
||||
const invites = new Map(); // room id -> { inviter, direct }: invitations not yet answered
|
||||
const processed = new Set(); // event ids read since the position last advanced
|
||||
|
||||
async function matrix(method, path, body) {
|
||||
let response;
|
||||
|
|
@ -61,58 +69,139 @@ export function createMouth({
|
|||
return response.json();
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const saved = await state.load();
|
||||
cursor = committed = saved?.nextBatch ?? null;
|
||||
seqCounter = saved?.seq ?? 0;
|
||||
selfId = (await matrix("GET", "/account/whoami")).user_id;
|
||||
for (const alias of rooms) {
|
||||
const { room_id: roomId } = await matrix("GET", `/directory/room/${encodeURIComponent(alias)}`);
|
||||
await matrix("POST", `/join/${encodeURIComponent(roomId)}`, {});
|
||||
roomIdByAlias.set(alias, roomId);
|
||||
aliasByRoomId.set(roomId, alias);
|
||||
const released = async () => { try { return (await brake()) === true; } catch { return false; } };
|
||||
const noteDirect = content => {
|
||||
for (const [user, ids] of Object.entries(content ?? {})) {
|
||||
if (!Array.isArray(ids)) continue;
|
||||
directContent[user] = ids.filter(id => typeof id === "string");
|
||||
directContent[user].forEach(id => directRooms.add(id));
|
||||
}
|
||||
started = true;
|
||||
};
|
||||
|
||||
function noteInvites(invited) {
|
||||
for (const [roomId, room] of Object.entries(invited ?? {})) {
|
||||
const event = (room.invite_state?.events ?? []).find(e => e.type === "m.room.member" && e.state_key === selfId && typeof e.sender === "string");
|
||||
if (event) invites.set(roomId, { inviter: event.sender, direct: event.content?.is_direct === true });
|
||||
}
|
||||
}
|
||||
|
||||
// A DM invitation from an account on our own homeserver is accepted, and only while the brake is
|
||||
// released; one received while braked waits for the release. An invitation from any other server is
|
||||
// declined. A same-server invitation to a room that is not a DM is not ours to accept and is dropped.
|
||||
async function answerInvites() {
|
||||
let free = null;
|
||||
for (const [roomId, invite] of [...invites]) {
|
||||
try {
|
||||
const room = encodeURIComponent(roomId);
|
||||
if (!serverName || invite.inviter.slice(invite.inviter.indexOf(":") + 1) !== serverName) {
|
||||
await matrix("POST", `/rooms/${room}/leave`, {});
|
||||
invites.delete(roomId);
|
||||
} else if (!invite.direct) {
|
||||
invites.delete(roomId);
|
||||
} else {
|
||||
free ??= await released();
|
||||
if (!free) continue;
|
||||
await matrix("POST", `/join/${room}`, {});
|
||||
invites.delete(roomId);
|
||||
directRooms.add(roomId);
|
||||
directContent[invite.inviter] = [...new Set([...(directContent[invite.inviter] ?? []), roomId])];
|
||||
await matrix("PUT", `/user/${encodeURIComponent(selfId)}/account_data/m.direct`, directContent).catch(error => say(`m.direct not saved: ${error.message}`));
|
||||
}
|
||||
} catch (error) {
|
||||
say(`invite to ${roomId} not answered: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const unjoined = () => joinedAliases.size < rooms.length;
|
||||
|
||||
// Join the configured rooms the account is not in, only while the brake is released.
|
||||
// One room failing is logged and retried on the next round; it never stops the others.
|
||||
async function ensureRooms() {
|
||||
const member = new Set((await matrix("GET", "/joined_rooms")).joined_rooms ?? []);
|
||||
let free = null;
|
||||
for (const alias of rooms.filter(a => !joinedAliases.has(a))) {
|
||||
try {
|
||||
let roomId = roomIdByAlias.get(alias);
|
||||
if (!roomId) ({ room_id: roomId } = await matrix("GET", `/directory/room/${encodeURIComponent(alias)}`));
|
||||
roomIdByAlias.set(alias, roomId);
|
||||
if (!member.has(roomId)) {
|
||||
free ??= await released();
|
||||
if (!free) continue;
|
||||
await matrix("POST", `/join/${encodeURIComponent(roomId)}`, {});
|
||||
freshRooms.add(roomId);
|
||||
}
|
||||
aliasByRoomId.set(roomId, alias);
|
||||
joinedAliases.add(alias);
|
||||
} catch (error) {
|
||||
say(`room ${alias} not joined: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (!started) {
|
||||
const saved = await state.load();
|
||||
cursor = committed = saved?.nextBatch ?? null;
|
||||
seqCounter = saved?.seq ?? 0;
|
||||
selfId = (await matrix("GET", "/account/whoami")).user_id;
|
||||
try { noteDirect(await matrix("GET", `/user/${encodeURIComponent(selfId)}/account_data/m.direct`)); } catch { /* no m.direct: no DMs yet */ }
|
||||
started = true;
|
||||
}
|
||||
if (unjoined()) await ensureRooms();
|
||||
}
|
||||
|
||||
// One /sync round. Returns the deliveries it made.
|
||||
async function syncOnce() {
|
||||
if (!started) await start();
|
||||
if (!started || unjoined()) await start();
|
||||
if (pending.length >= maxPending) return []; // unanswered mail is not outrun: the position stays where it is
|
||||
const filter = encodeURIComponent(JSON.stringify({ room: { timeline: { limit: CONTEXT } } }));
|
||||
const since = cursor === null ? "" : `&since=${encodeURIComponent(cursor)}`;
|
||||
const reply = await matrix("GET", `/sync?timeout=${cursor === null ? 0 : syncTimeoutMs}&filter=${filter}${since}`);
|
||||
const baseline = cursor === null; // first ever sync: history is context, not mail
|
||||
for (const event of reply.account_data?.events ?? []) if (event.type === "m.direct") noteDirect(event.content);
|
||||
noteInvites(reply.rooms?.invite);
|
||||
await answerInvites();
|
||||
const made = [];
|
||||
for (const [roomId, room] of Object.entries(reply.rooms?.join ?? {})) {
|
||||
const alias = aliasByRoomId.get(roomId);
|
||||
let truncated = false; // the pending cap was reached inside this round
|
||||
rounds: for (const [roomId, room] of Object.entries(reply.rooms?.join ?? {})) {
|
||||
const alias = aliasByRoomId.get(roomId) ?? (directRooms.has(roomId) ? roomId : undefined);
|
||||
if (!alias) continue;
|
||||
for (const event of [...(room.state?.events ?? []), ...(room.timeline?.events ?? [])]) {
|
||||
if (event.type === "m.room.member" && event.content?.displayname) displayNames.set(event.state_key, event.content.displayname);
|
||||
const shown = event.content?.displayname;
|
||||
if (event.type === "m.room.member" && typeof event.state_key === "string" && typeof shown === "string" && shown !== "") displayNames.set(event.state_key, docs.clip(shown, docs.limits.displayBytes));
|
||||
}
|
||||
for (const event of room.timeline?.events ?? []) {
|
||||
if (event.type !== "m.room.message" || typeof event.content?.body !== "string") continue;
|
||||
const entry = { sender: event.sender, text: event.content.body, atUnixMs: event.origin_server_ts ?? now() };
|
||||
if (typeof event.sender !== "string" || event.sender === "" || typeof event.event_id !== "string" || event.event_id === "") continue;
|
||||
if (processed.has(event.event_id)) continue; // read already in a round the cap kept from advancing
|
||||
const ts = event.origin_server_ts;
|
||||
const entry = { sender: event.sender, text: docs.clip(event.content.body, docs.limits.textBytes), atUnixMs: Number.isSafeInteger(ts) && ts >= 0 ? ts : now() };
|
||||
const context = (history.get(roomId) ?? []).slice(-CONTEXT);
|
||||
if (!baseline && event.sender !== selfId) {
|
||||
const deliverable = !baseline && !freshRooms.has(roomId) && event.sender !== selfId;
|
||||
if (deliverable && pending.length + made.length >= maxPending) { truncated = true; break rounds; }
|
||||
processed.add(event.event_id);
|
||||
if (deliverable) {
|
||||
const mentioned = event.content["m.mentions"]?.user_ids;
|
||||
made.push({
|
||||
seq: ++seqCounter, roomAlias: alias, roomId, eventId: event.event_id, sender: event.sender,
|
||||
senderDisplay: displayNames.get(event.sender) ?? localpart(event.sender), text: entry.text, atUnixMs: entry.atUnixMs,
|
||||
context: context.map(c => ({ ...c })),
|
||||
context: context.map(c => ({ ...c, text: docs.clip(c.text, docs.limits.contextBytes) })),
|
||||
mentions: Array.isArray(mentioned) ? mentioned.filter(id => typeof id === "string" && id !== "" && id.length <= 255).slice(0, docs.limits.mentions) : [],
|
||||
isDirect: directRooms.has(roomId),
|
||||
});
|
||||
}
|
||||
history.set(roomId, [...context, entry].slice(-CONTEXT));
|
||||
}
|
||||
}
|
||||
const wasIdle = pending.length === 0;
|
||||
pending.push(...made);
|
||||
cursor = reply.next_batch;
|
||||
batches.push({ token: reply.next_batch, maxSeq: seqCounter });
|
||||
if (!truncated) { // a truncated round leaves the position where it was: the rest stays on the server
|
||||
cursor = reply.next_batch;
|
||||
batches.push({ token: reply.next_batch, maxSeq: seqCounter });
|
||||
processed.clear();
|
||||
freshRooms.clear();
|
||||
}
|
||||
await commit();
|
||||
if (made.length > 0) await state.save({ nextBatch: committed, seq: seqCounter }); // sequence numbers never repeat across a restart
|
||||
if (made.length > 0 && (wasIdle || now() - lastRingAt >= RING_WINDOW_MS)) {
|
||||
lastRingAt = now();
|
||||
Promise.resolve().then(ring).catch(error => say(`ring failed: ${error?.message ?? error}`));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
|
|
@ -133,20 +222,18 @@ export function createMouth({
|
|||
}
|
||||
|
||||
function pendingAfter(afterSeq) {
|
||||
return pending.filter(d => d.seq > afterSeq).map(d => ({ ...d }));
|
||||
return pending.filter(d => d.seq > afterSeq).map(d => ({ ...d, context: d.context.map(c => ({ ...c })), mentions: [...d.mentions] }));
|
||||
}
|
||||
|
||||
async function send({ requestId, persona: asked, roomAlias, text }) {
|
||||
const refuse = refusal => ({ requestId, eventId: null, refusal });
|
||||
if (asked !== persona) return refuse("PersonaMismatch");
|
||||
let released = false;
|
||||
try { released = (await brake()) === true; } catch { released = false; }
|
||||
if (!released) return refuse("Brake");
|
||||
if (!(await released())) return refuse("Brake");
|
||||
if (typeof text !== "string" || text.trim() === "") return refuse("EmptyText");
|
||||
if (!started) await start();
|
||||
const roomId = roomIdByAlias.get(roomAlias);
|
||||
if (!roomId) return refuse("UnknownRoom");
|
||||
try {
|
||||
if (!started || unjoined()) await start();
|
||||
const roomId = joinedAliases.has(roomAlias) ? roomIdByAlias.get(roomAlias) : directRooms.has(roomAlias) ? roomAlias : null;
|
||||
if (!roomId) return refuse("UnknownRoom");
|
||||
const sent = await matrix("PUT", `/rooms/${encodeURIComponent(roomId)}/send/m.room.message/${encodeURIComponent(requestId)}`, { msgtype: "m.text", body: text });
|
||||
return { requestId, eventId: sent.event_id, refusal: null };
|
||||
} catch (error) {
|
||||
|
|
@ -156,10 +243,14 @@ export function createMouth({
|
|||
}
|
||||
|
||||
async function run(signal) {
|
||||
const pause = ms => new Promise(r => { const t = setTimeout(r, ms); signal?.addEventListener("abort", () => { clearTimeout(t); r(); }, { once: true }); });
|
||||
while (!signal?.aborted) {
|
||||
try { await syncOnce(); } catch (error) {
|
||||
try {
|
||||
await syncOnce();
|
||||
if (pending.length >= maxPending) await pause(1000);
|
||||
} catch (error) {
|
||||
say(`sync failed: ${error.message}`);
|
||||
await new Promise(r => { const t = setTimeout(r, 5000); signal?.addEventListener("abort", () => { clearTimeout(t); r(); }, { once: true }); });
|
||||
await pause(5000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -167,24 +258,22 @@ export function createMouth({
|
|||
return { start, syncOnce, ack, pendingAfter, send, run, get pendingCount() { return pending.length; } };
|
||||
}
|
||||
|
||||
export function redact(message, token) {
|
||||
return token ? message.split(token).join("[redacted]") : message;
|
||||
// Replace every secret in a message. `secrets` is one string or a list.
|
||||
export function redact(message, secrets) {
|
||||
let out = String(message);
|
||||
for (const secret of [secrets].flat()) if (secret) out = out.split(secret).join("[redacted]");
|
||||
return out;
|
||||
}
|
||||
|
||||
// Run `fn`; whatever it throws leaves with every secret redacted.
|
||||
export async function guarded(secrets, fn) {
|
||||
try { return await fn(); } catch (error) { throw new Error(redact(error?.message ?? String(error), secrets)); }
|
||||
}
|
||||
|
||||
function localpart(userId) {
|
||||
return userId.replace(/^@/, "").split(":")[0];
|
||||
}
|
||||
|
||||
// Ring: start the Persona's one-shot unit. No retry loop, no token in its environment.
|
||||
export function createRing({ instance, run = execFile, log = () => {} }) {
|
||||
return () => new Promise(done => {
|
||||
run("systemctl", ["start", "--no-block", `mind-persona@${instance}.service`], { env: { PATH: process.env.PATH ?? "" } }, error => {
|
||||
if (error) log(`ring failed: ${error.message}`);
|
||||
done();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Brake: released only when the instance's control store decodes to a released
|
||||
// brake. Absent, undecodable or held reads are all "not released".
|
||||
export function createBrakeReader({ controlPath, readStore, decode }) {
|
||||
|
|
@ -208,16 +297,38 @@ export function connectionIdFor(connectionKey) {
|
|||
return createHash("sha256").update(connectionKey).digest().readUInt32BE(0);
|
||||
}
|
||||
|
||||
// CultNet RUDP endpoint on loopback. Requests arrive as document_put_raw messages.
|
||||
export async function startChatEndpoint({ mouth, persona, runtime, port, connectionKey, runtimeId, socketFactory = createSocket, host = "127.0.0.1", log = () => {} }) {
|
||||
// The reply to a chat_pending_request: deliveries oldest first, each encoded on its own so one that
|
||||
// will not encode is skipped and logged without silencing the rest, up to the reply byte budget.
|
||||
// The caller acks what it has read and asks again.
|
||||
export function pageOf(persona, deliveries, msgpack, log = () => {}) {
|
||||
const page = [];
|
||||
let bytes = 0;
|
||||
for (const delivery of deliveries) {
|
||||
let tuple, size;
|
||||
try { tuple = docs.deliveryTuple(delivery); size = msgpack.encode(tuple).length; } catch (error) {
|
||||
log(`delivery ${delivery?.seq} skipped: ${error?.message ?? error}`);
|
||||
continue;
|
||||
}
|
||||
if (page.length > 0 && bytes + size > docs.limits.replyBytes) break;
|
||||
page.push(tuple);
|
||||
bytes += size;
|
||||
}
|
||||
return [persona, page];
|
||||
}
|
||||
|
||||
// CultNet RUDP endpoint on loopback, one for every Persona in `mouths` (persona -> mouth).
|
||||
// Requests arrive as document_put_raw messages. A request naming a Persona this
|
||||
// process does not serve is answered with a typed UnknownPersona refusal.
|
||||
export async function startChatEndpoint({ mouths, runtime, port, connectionKey, runtimeId, socketFactory = createSocket, host = "127.0.0.1", log = () => {} }) {
|
||||
if (!/^127\.\d+\.\d+\.\d+$/.test(host)) throw new Error("the chat endpoint listens on loopback only");
|
||||
const { msgpack, cultnet } = runtime;
|
||||
const socket = socketFactory("udp4");
|
||||
await new Promise((ok, fail) => { socket.once("error", fail); socket.once("listening", ok); socket.bind(port, host); });
|
||||
const connectionId = connectionIdFor(connectionKey);
|
||||
const connection = new cultnet.CultNetRudpSocketTransportConnection({ runtimeId, socket, mode: "server", connectionId, initialSequence: 100, resendDelayMs: 50, resendPollMs: 10, maxFragmentBytes: 1200 });
|
||||
const respond = (kind, recordKey, tuple) => connection.send("schema", msgpack.encode(cultnet.encodeCultNetMessageForWire(
|
||||
const respond = (persona, kind, recordKey, tuple) => connection.send("schema", msgpack.encode(cultnet.encodeCultNetMessageForWire(
|
||||
docs.envelope({ kind, recordKey, payload: msgpack.encode(tuple), sourceRuntimeId: runtimeId, sourceAgentId: persona, sourceRole: "bifrost-persona-matrix-mouth" }), "cultnet.schema.v0")));
|
||||
const refuseUnknown = persona => respond(persona, docs.kinds.refusal, persona, docs.refusalTuple({ persona, refusal: "UnknownPersona" }));
|
||||
let busy = Promise.resolve();
|
||||
const handle = async value => {
|
||||
try {
|
||||
|
|
@ -227,16 +338,19 @@ export async function startChatEndpoint({ mouth, persona, runtime, port, connect
|
|||
const tuple = msgpack.decode(document.payload);
|
||||
if (document.schemaId === docs.kinds.pendingRequest) {
|
||||
const request = docs.parsePendingRequest(tuple);
|
||||
if (request.persona !== persona) throw new Error("chat request names another Persona");
|
||||
respond(docs.kinds.pending, persona, docs.pendingTuple({ persona, deliveries: mouth.pendingAfter(request.afterSeq) }));
|
||||
const mouth = mouths.get(request.persona);
|
||||
if (!mouth) return refuseUnknown(request.persona);
|
||||
respond(request.persona, docs.kinds.pending, request.persona, pageOf(request.persona, mouth.pendingAfter(request.afterSeq), msgpack, log));
|
||||
} else if (document.schemaId === docs.kinds.ack) {
|
||||
const request = docs.parseAck(tuple);
|
||||
if (request.persona !== persona) throw new Error("chat ack names another Persona");
|
||||
const mouth = mouths.get(request.persona);
|
||||
if (!mouth) return refuseUnknown(request.persona);
|
||||
await mouth.ack(request.throughSeq);
|
||||
} else {
|
||||
const request = docs.parseSendRequest(tuple);
|
||||
const receipt = await mouth.send(request);
|
||||
respond(docs.kinds.sendReceipt, receipt.requestId, docs.sendReceiptTuple(receipt));
|
||||
const mouth = mouths.get(request.persona);
|
||||
const receipt = mouth ? await mouth.send(request) : { requestId: request.requestId, eventId: null, refusal: "UnknownPersona" };
|
||||
respond(request.persona, docs.kinds.sendReceipt, receipt.requestId, docs.sendReceiptTuple(receipt));
|
||||
}
|
||||
} catch (error) {
|
||||
log(`chat endpoint rejected a frame: ${error?.message ?? error}`);
|
||||
|
|
@ -275,27 +389,36 @@ function credential(env, name) {
|
|||
return readFileSync(join(required(env, "CREDENTIALS_DIRECTORY"), name), "utf8").trim();
|
||||
}
|
||||
|
||||
// PERSONAS is the comma-separated list of Persona slugs this process speaks for.
|
||||
// Each slug names its credential (matrix-token-<slug>), its cursor directory under
|
||||
// STATE_DIRECTORY and its brake at CONTROL_ROOT/<slug>/control.cc.
|
||||
export async function main(env = process.env) {
|
||||
const persona = required(env, "PERSONA");
|
||||
const instance = env.MIND_INSTANCE ?? persona; // the unit template is instanced by the Persona's mind
|
||||
if (!/^[A-Za-z0-9_-]{1,64}$/.test(instance)) throw new Error("MIND_INSTANCE is not a slug");
|
||||
const token = credential(env, "matrix-token");
|
||||
const runtime = loadRuntime(resolve(env.CULTLIB_ROOT ?? resolve(import.meta.dirname, "..", "..", "CultLib")));
|
||||
const log = line => console.error(line);
|
||||
const controlPath = join(env.CONTROL_ROOT ?? "/etc/gamecult/minds", instance, "control.cc");
|
||||
const mouth = createMouth({
|
||||
persona, token, log,
|
||||
homeserver: required(env, "MATRIX_HOMESERVER").replace(/\/$/, ""),
|
||||
rooms: required(env, "MATRIX_ROOMS").split(",").map(s => s.trim()).filter(Boolean),
|
||||
state: cultcacheState({ runtime, path: env.STATE_PATH ?? join(required(env, "STATE_DIRECTORY"), "cursor.cc") }),
|
||||
brake: createBrakeReader({ controlPath, readStore: runtime.readSingleFileStore, decode: runtime.msgpack.decode }),
|
||||
ring: createRing({ instance, log }),
|
||||
const personas = required(env, "PERSONAS").split(",").map(s => s.trim()).filter(Boolean);
|
||||
if (personas.length === 0 || new Set(personas).size !== personas.length || !personas.every(p => SLUG.test(p))) throw new Error("PERSONAS must be distinct slugs");
|
||||
const tokens = new Map(personas.map(p => [p, credential(env, `matrix-token-${p}`)]));
|
||||
const chatKey = credential(env, "chat-key");
|
||||
const secrets = [...tokens.values(), chatKey];
|
||||
return guarded(secrets, async () => {
|
||||
const runtime = loadRuntime(resolve(env.CULTLIB_ROOT ?? resolve(import.meta.dirname, "..", "..", "CultLib")));
|
||||
const log = line => console.error(redact(line, secrets));
|
||||
const homeserver = required(env, "MATRIX_HOMESERVER").replace(/\/$/, "");
|
||||
const serverName = required(env, "MATRIX_SERVER_NAME");
|
||||
const rooms = required(env, "MATRIX_ROOMS").split(",").map(s => s.trim()).filter(Boolean);
|
||||
const stateRoot = required(env, "STATE_DIRECTORY");
|
||||
const controlRoot = env.CONTROL_ROOT ?? "/etc/gamecult/minds";
|
||||
const mouths = new Map(personas.map(persona => {
|
||||
mkdirSync(join(stateRoot, persona), { recursive: true });
|
||||
return [persona, createMouth({
|
||||
persona, homeserver, serverName, rooms, token: tokens.get(persona), log: line => log(`${persona}: ${line}`),
|
||||
state: cultcacheState({ runtime, path: join(stateRoot, persona, "cursor.cc") }),
|
||||
brake: createBrakeReader({ controlPath: join(controlRoot, persona, "control.cc"), readStore: runtime.readSingleFileStore, decode: runtime.msgpack.decode }),
|
||||
})];
|
||||
}));
|
||||
const listen = required(env, "CHAT_RUDP_LISTEN"); // host:port, loopback
|
||||
const colon = listen.lastIndexOf(":");
|
||||
await startChatEndpoint({ mouths, runtime, host: listen.slice(0, colon), port: Number(listen.slice(colon + 1)), connectionKey: chatKey, runtimeId: "bifrost-persona-mouth", log });
|
||||
await Promise.all([...mouths.values()].map(mouth => mouth.run()));
|
||||
});
|
||||
await mouth.start();
|
||||
const listen = required(env, "CHAT_RUDP_LISTEN"); // host:port, loopback
|
||||
const colon = listen.lastIndexOf(":");
|
||||
await startChatEndpoint({ mouth, persona, runtime, host: listen.slice(0, colon), port: Number(listen.slice(colon + 1)), connectionKey: credential(env, "chat-key"), runtimeId: `bifrost-persona-mouth-${persona}`, log });
|
||||
await mouth.run();
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
|
|
|
|||
Loading…
Reference in a new issue