/** * Session-bus lifecycle and operations. * * No mode joins on start: a session is invisible until it names itself or takes an action that makes * it addressable (`send`, `claim`, `join`, `watch`), and reading — the board and `status` — never * joins, because a reader is not a member. The runtime owns the heartbeat, keeps no module-level * state, and uses the common git directory so worktrees of one repository share one bus. * * A wake that arrives while the agent is running is queued and raised by the extension's reporter * once the run settles; the watch itself — the poll, the queue, the reported set — is `mail-watch.ts`. */ import { join } from "node:path"; import type { ExtensionAPI, ExtensionContext, SessionStartEvent } from "@earendil-works/pi-coding-agent"; import { getAgentDir } from "@earendil-works/pi-coding-agent"; import { realPathOfNearest } from "../../lib/path.ts"; import { BUS_DIR_NAME, ensureHostIdentity, type HostIdentity } from "../../lib/session-files.ts"; import { labelKey } from "../../lib/session-label.ts"; import { messageId } from "../../lib/session-mail.ts"; import { peerRowOf, type RosterSeams, type RosterState, recordFacts, rosterStateOf, SESSION_TTL_MS, } from "../../lib/session-roster.ts"; import { isPidAlive, startTokenOf } from "../../lib/spawn.ts"; import { defaultInterval } from "../../lib/timer.ts"; import type { SessionBus, SessionBusOptions } from "./api.ts"; import type { SessionLabels } from "./labels.ts"; import { createMailWatch, recordWatch, storedWatchMode } from "./mail-watch.ts"; import type { RecordWriter } from "./record.ts"; import { lapseNotice, lapsedOwners, MAX_LIMIT, MESSAGE_TTL_MS, normalizeLabel, normalizeLimit, normalizePaths, resolveRecipients, settleSend, } from "./protocol.ts"; import { claimPathMessage, resolveClaimPaths } from "./resolve.ts"; import { type BusStore, createBusStore, releaseClaimed } from "./store.ts"; import type { InboxPeek, LapsedClaims, SessionRecord, SessionStatus } from "./types.ts"; export type { SessionBus, SessionBusOptions }; const DEFAULT_HEARTBEAT_MS = 10_000; const NO_MAIL: InboxPeek = { mail: [], unread: new Set(), unreadable: [] }; const DEFAULT_WATCH_MS = 2_000; export function createSessionBus(pi: ExtensionAPI, options: SessionBusOptions = {}): SessionBus { const now = options.now ?? Date.now; const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS; const watchMs = options.watchMs ?? DEFAULT_WATCH_MS; const interval = options.interval ?? defaultInterval; const pid = options.pid ?? process.pid; const seams: RosterSeams = { alive: options.alive ?? isPidAlive, token: options.startTokenFn ?? startTokenOf }; /** * What one record says about its session. * * The rule is the roster's, not a copy: the bus writes these records and the page * reads them, and a second copy of the heartbeat rule is how a dead session keeps its * label and its claims while the screen already says it is gone. */ function stateOf(session: SessionRecord, at = now()): RosterState { // Facts first: whether this machine may judge the pid is settled at the read. return rosterStateOf(recordFacts(session, host), at, sessionTtlMs, seams); } const sessionTtlMs = options.sessionTtlMs ?? SESSION_TTL_MS; const messageTtlMs = options.messageTtlMs ?? MESSAGE_TTL_MS; let host: string | undefined; let identity: HostIdentity | undefined; let store: BusStore | undefined; let record: SessionRecord | undefined; let labels: SessionLabels | undefined; let joined = false; let stopHeartbeat: (() => void) | undefined; let starting: Promise | undefined; /** * The record's one writer, and the rows a reader draws: both load when something needs them. * * A session that never joins pays nothing for either, and the seams below read through * getters — empty until the start has run — so the watch and the status read cannot be * handed a half-built writer. */ let writer: RecordWriter | undefined; const mailWatch = createMailWatch({ peek: async (known): Promise => store && record ? store.peek(record.id, { limit: MAX_LIMIT, known }) : NO_MAIL, told: () => writer?.ids() ?? [], onTold: (ids) => writer?.told(ids), interval, watchMs, }); /** * The bus as a reader sees it — `session status`, and the board's snapshot. * * The module loads with the read that needs it: registration pays nothing for rows nobody has * asked for, which is the rule `test/dependencies.test.ts` holds the graph to. */ async function readStatus( me: { id: string; label: string; onBus: boolean }, liveOnly: boolean, ): Promise { const { createStatusReader } = await import("./status.ts"); return createStatusReader({ store: () => store, record: () => record, stateOf, now, watching: () => mailWatch.state(), }).read(me, liveOnly); } const ensureStarted = async (context: ExtensionContext, reason?: SessionStartEvent["reason"]): Promise => { if (starting) return starting; starting = (async () => { // Canonical once, here: the root git reports is a real path, so an unresolved // cwd does not contain the paths a caller resolves against it. const cwd = realPathOfNearest(context.cwd); // Filed beside the board, under the identity two machines agree on, with a bus an older // build wrote at the flat spelling taken across once. One body for every owner: the // module is loaded here, so a session that never joins a bus pays nothing for it. const agentDir = getAgentDir(); const { repoStoreDirFor } = await import("../../lib/store-paths.ts"); const located = options.dir === undefined ? await repoStoreDirFor(pi, cwd, agentDir, BUS_DIR_NAME, (found) => join(agentDir, BUS_DIR_NAME, found.key), { repo: options.repo, }) : undefined; const dir = options.dir ?? located?.dir; // One of the two always answered: a caller supplies the directory, or the resolver did. if (dir === undefined) throw new Error("the session bus could not resolve its directory"); const repo = options.repo ?? located?.repo; // This machine's identity, made on first use: the host every record and claim names. identity = options.host ?? (options.dir === undefined ? await ensureHostIdentity(agentDir) : undefined); host = identity?.id; store = options.store ?? createBusStore(host === undefined ? { dir } : { dir, host }); await store.ensure(); const id = context.sessionManager.getSessionId(); // Asked once, when the bus starts: a reused pid is settled from the record // afterwards, so no heartbeat tick spawns `ps`, and a session that never // joins pays nothing in its factory. const processToken = (seams.token ?? startTokenOf)(pid); // The record this process serves: a `/new` keeps the row it left, so a reset costs the // transcript and nothing else. `own-record.ts` says which row, and why every guard // fails toward minting one. const { startRecord } = await import("./own-record.ts"); const started = await startRecord({ pi, store, context, id, pid, startToken: processToken, host, reason, cwd, repoRoot: repo?.root ?? cwd, fromGit: repo?.fromGit === true, now: now(), }); record = started.record; // A record that outlived its process still says what that session was told, and a resume // is that session: adopting its cursor keeps its old mail out of the count. A `/new` reads // the row it serves, which is the row the previous transcript wrote. // The name this session holds: one module for who else has it, yielding it, publishing it, // and the refusal's wording, built on the record and the store this start just resolved. The // transcript's id goes with it: a served `/new` keeps the row's older one, and the channel // names the transcript the reader is drawing. const { createLabels } = await import("./labels.ts"); labels = createLabels({ pi, store, record, sessionId: id, stateOf, now, sessionTtlMs }); const { createRecordWriter } = await import("./record.ts"); writer = createRecordWriter({ store: () => store, record: () => record, joined: () => joined }, options.stderr); await writer.adopt(); await mailWatch.restore(storedWatchMode(await store.session(record.id))); // A served row is one this process was already on the bus with, so the start joins it as a // resumed session would: the beat is what keeps a peer's prune from taking the row — and the // claims a card is worked under — ten quiet minutes later. if (started.served) { await joinBus(); // The row kept the name; the transcript Pi holds did not. A minted start names nobody, // because naming it would put a session that never joined on the bar. labels.nameTranscript(); } })(); try { await starting; } catch (error) { starting = undefined; throw error; } }; /** The start this session is running or ran; only `start` starts one. */ function ensureReady(): Promise { return starting ?? Promise.resolve(); } async function joinBus(): Promise { if (!store || !record || !labels || !writer) throw new Error("session bus is not started."); if (joined) return; // A `leave` closes the writer while keeping the start, so a join after one re-opens it // rather than writing into a closed chain. writer.open(); record.lastSeen = now(); // The row goes down before the name is settled: a rival's `settle` can only yield to a record // it can read, so writing after the settle lets two same-instant joins both keep one name. await writer.save(); if (await labels.settle()) await writer.save(); if (identity) await store.writeHost(identity, now()); labels.publish(); joined = true; armHeartbeat(); } /** * Start the heartbeat once, whoever joins: `joinBus` on the first addressable * action, and `rename`, which is a join of its own. */ function armHeartbeat(): void { if (heartbeatMs <= 0 || stopHeartbeat) return; stopHeartbeat = writer?.startBeat(heartbeatMs, interval, async () => { if (!record || !store || !labels || !writer) return; record.lastSeen = now(); // The cursor names mail the inbox may have lost since the last poll, and a session that // stopped listening polls nothing: this write is where that set is trimmed, so it cannot // grow with every message the session ever read. await writer.trim(); // A heartbeat that resumed after a long pause can find its label taken; the tick is // where a revived session notices and yields, before the one write carries both. const yielded = await labels.settle(); await writer.save(); // The machine's row beats with the session: a claim lapses on it. if (identity) await store.writeHost(identity, now()); if (yielded) labels.publish(); // The one prune that opens inbox files rides the clock the message TTL is measured in, so no // action pays for mail nobody waits on; a peer's inbox is that peer's to end. await store.pruneMail({ now: now(), messageTtlMs, own: record.id }); }); } /** * What a prune must keep, and what it must let go. * * `live` is who can still answer, and this session is active by definition. `gone` is * who cannot: their rows survive on the heartbeat's clock, but the paths they held are * nobody's, which is the half a lead waits for. */ async function pruneSets(): Promise<{ live: Set; gone: Set }> { if (!store) throw new Error("session bus is not started."); const at = now(); const live = new Set(); const gone = new Set(); for (const session of await store.sessions()) { const state = stateOf(session, at); if (state === "live") live.add(session.id); else if (state === "gone") gone.add(session.id); } if (record) live.add(record.id); return { live, gone }; } /** * Forget the sessions the TTL has taken, so a label and the row holding it leave together. * * A label is reserved for the window this keeps, so the claim and the prune are one call: * `prepare` joins first and forgets here, which is what leaves a name free and its row gone * at the same moment — and one label over one session, rather than two a `send` must refuse. * * Records and claims only: this runs before every action, and the inbox sweep is the one part * of the prune whose cost is the whole bus, so the heartbeat carries that half instead. */ async function pruneStaleRecords(): Promise { if (!store || !record || !writer) throw new Error("session bus is not started."); // The caller is active by definition; refresh it before pruning so a quiet session // that finally calls a tool does not delete its own record. record.lastSeen = now(); await writer.save(); const sets = await pruneSets(); const lapsed = await store.pruneRecords({ now: now(), activeIds: sets.live, goneIds: sets.gone, sessionTtlMs, }); await reportLapses(lapsed).catch(() => {}); } /** * Tell each owner whose claims a prune took, once, in the inbox it already reads. A notice that * fails costs the sentence, not the action: the paths have lapsed either way. */ async function reportLapses(lapsed: LapsedClaims): Promise { if (!store || !record) return; const at = now(); for (const [owner, claims] of lapsedOwners(lapsed.claims, { host, self: record.id })) { await store.writeMessage(owner, { id: messageId(at), from: record.id, fromLabel: record.label, to: owner, toLabel: claims[0].ownerLabel, kind: "message", text: lapseNotice(claims.map((claim) => claim.path)), at, }); } } async function prepare(): Promise { // A call that lands while the session's start is still settling waits for it: the channel // starts the bus without blocking the reload, so the first tool or command is the reader. await ensureReady(); await joinBus(); await pruneStaleRecords(); } async function currentRecord(): Promise { await prepare(); if (!record) throw new Error("session bus is not started."); return record; } function storedPaths(me: SessionRecord, raw: unknown): string[] { const normalized = normalizePaths(me.repoRoot, me.cwd, raw); if ("error" in normalized) throw new Error(normalized.error); const keyed = resolveClaimPaths(me.repoRoot, normalized.paths); if ("error" in keyed) throw new Error(claimPathMessage(keyed.error)); return keyed.paths; } /** The store, for a closure that cannot see the check its caller made. */ function requireStore(): BusStore { if (store === undefined) throw new Error("session bus is not started."); return store; } async function rename(label: string): Promise { if (!store || !record || !labels || !writer) throw new Error("session bus is not started."); const candidate = normalizeLabel(label, record.label); // The bus's own answer to "who has it": the session record, named by its id, because // the label it holds is the one the caller just asked for. const holder = (await labels.taken(record.id)).get(labelKey(candidate)); if (holder) throw new Error(`the label "${candidate}" is ${labels.heldBy(holder)}.`); record.label = candidate; record.lastSeen = now(); // The candidate goes down before the name is settled, for the same reason the join's row does: // a rival can only yield to a record it can read, so a settle before the write keeps both. await writer.save(); if (await labels.settle()) await writer.save(); labels.publish(); joined = true; armHeartbeat(); return record.label; } return { async start(context, event) { await ensureStarted(context, event?.reason); }, async stop(event) { stopHeartbeat?.(); stopHeartbeat = undefined; mailWatch.stop(); const wasJoined = joined; // No edge may be admitted while the row is going, and a write still queued when the // removal starts would re-create it: clearing the flag and draining `close()` are the // two halves of what keeps a quit from leaving a row behind. joined = false; await writer?.close(); if (store && record && wasJoined) { // The row's whole afterlife is `own-record.ts`'s: a `/new` and a `/reload` keep it for // the process's next start, every other reason releases its claims and removes it. const { endRecord } = await import("./own-record.ts"); await endRecord({ store, record, pid, reason: event?.reason, now: now() }); } starting = undefined; labels = undefined; writer = undefined; store = undefined; record = undefined; }, // Join, name, and listen as one act: the name is validated before a watch is armed, so a // refused label leaves the record and the watch exactly as they were. async join(input) { const me = await currentRecord(); if (!writer) throw new Error("session bus is not started."); const label = input.label === undefined ? me.label : await rename(input.label); // `listen: false` is the one way to be on the bus without mail: the record stays, // so a peer can still address this session, and only the watch is turned off. const watching = input.listen === false ? await mailWatch.watch({ stop: true }) : await mailWatch.watch({ wake: input.wake }); // Written on every join, disarmed included, so a peer reads it from disk instead of // asking: `armed: false` is the fact `team` reports as "not listening", and the // field's absence is only ever a record older than this line. recordWatch(me, watching); await writer.save(); return { label, watching }; }, inboxDepth: () => mailWatch.size(), wantsWake: () => mailWatch.wantsWake(), turnStart: () => writer?.writeTurn(now()) ?? Promise.resolve(), turnSettled: () => writer?.writeTurn(undefined) ?? Promise.resolve(), poll: () => mailWatch.poll(), pending: () => mailWatch.pending(), markReported: (ids) => mailWatch.markReported(ids), set onWake(callback: (() => void) | undefined) { mailWatch.onWake = callback; }, // Leaving is the session's own door to what `stop` does at the end of a process: the row, its // claims and the watch that would speak for it all go — while the start, its store, and the // row's id stay, so the next join re-adds the same id (a card is owned by it) rather than // minting a stranger's. async leave() { // Not `prepare()`: that joins first, which is the one thing a leave must not do. await ensureReady(); if (!store || !record) return { released: [] }; const me = record; // Whose row it is, read before anything is touched: a `/resume` in a second pane registers // one session id twice, and this pane must not strip the row and the claims of the one // still working under it — `own-record.ts` owns that rule, and `stop` asks it too. const { OTHER_PANE, ownsRow } = await import("./own-record.ts"); if (!ownsRow(await store.session(me.id).catch(() => undefined), pid)) { throw new Error(OTHER_PANE); } const wasOnBus = joined; // The heartbeat goes first because it is the one writer that would put the row back between // the two calls below; `close()` then drains what either it or the watch already queued, so a // removal cannot be undone by a write that was still in flight. stopHeartbeat?.(); stopHeartbeat = undefined; joined = false; await writer?.close(); let released: string[]; try { released = await store.releaseAll(me.id); await store.removeSession(me.id); } catch (error) { if (wasOnBus) { joined = true; writer?.open(); armHeartbeat(); } throw error; } // The watch stops only once the row is gone: across the removal the writer is closed and // `joined` is false, so a poll writes nothing — while a disarm taken before it would hand // back a session on the bus whose mail nothing polls, and a disarm drops the mode. mailWatch.stop(); labels?.withdraw(); return { ...(wasOnBus ? { label: me.label } : {}), released }; }, async status() { if (!store || !record) throw new Error("session bus is not started."); // A reader does not join: an unjoined session prunes and reads, and is not // listed by the act of looking. Only an addressable action joins. if (!joined) { const sets = await pruneSets(); await store.pruneRecords({ now: now(), activeIds: sets.live, goneIds: sets.gone, sessionTtlMs, }); return readStatus({ id: record.id, label: record.label, onBus: false }, false); } const me = await currentRecord(); return readStatus({ id: me.id, label: me.label, onBus: true }, false); }, async snapshot() { if (!store || !record) throw new Error("session bus is not started."); return readStatus({ id: record.id, label: record.label, onBus: joined }, true); }, async peek() { if (!store || !record) throw new Error("session bus is not started."); return store.peek(record.id, { limit: MAX_LIMIT }); }, /** Clear unaccounted mail — the one door `/sessions drop` opens. */ async dropUnaccounted(ids) { return requireStore().dropUnaccounted(ids); }, async forget(names) { const { forgetSessions } = await import("./forget.ts"); return forgetSessions({ store: requireStore(), stateOf }, names); }, /** * Release a claim by its stored path. * * No normalization: a claim is stored relative to the repo root of the * session that took it, and resolving it again against a cwd below that root * would rewrite the target (`src/api` becomes `src/src/api`). The path comes * from the store and `releaseOne` still refuses a claim owned by someone * else, so this cannot touch a peer's claim. */ async releaseStored(path) { if (!store || !record) throw new Error("session bus is not started."); return store.release(path, record.id); }, async send(input) { const me = await currentRecord(); if (!store) throw new Error("session bus is not started."); // The send's own words are the protocol's: settled in one place, so the refusals keep their // order and their sentences whatever door the send came through. const settled = settleSend(input); if ("error" in settled) throw new Error(settled.error); const { text, kind, key, replyTo, about } = settled.fields; // Which records mail reaches is `resolveRecipients`'s rule, over rows carrying their own // state: the gone exclusion and the sender's own record are read there, once, rather than // pre-filtered here and read again beside the wording. const at = now(); const rows = (await store.sessions()).map((session) => peerRowOf(recordFacts(session, host), at)); const resolved = resolveRecipients(rows, input.to, me.id); if ("error" in resolved) throw new Error(resolved.error); let paths: string[] | undefined; if (input.paths !== undefined) paths = storedPaths(me, input.paths); const id = messageId(now()); // One file per inbox, so the peers written before a failure keep the message: the store // answers with both lists and the caller decides what a partial delivery means. const { delivered, failed } = await store.writeTo(resolved.recipients, { id, from: me.id, fromLabel: me.label, kind, text, ...(key === undefined ? {} : { key }), ...(replyTo === undefined ? {} : { replyTo }), ...(about === undefined ? {} : { about }), ...(paths ? { paths } : {}), at: now(), }); return { delivered, failed, messageId: id }; }, async inbox(limit) { const me = await currentRecord(); if (!store) throw new Error("session bus is not started."); const { messages } = await store.inbox(me.id, normalizeLimit(limit)); // Mail read before its notice fired is never announced afterwards. mailWatch.markReported(messages.map((message) => message.id)); await mailWatch.refresh(); return messages; }, /** Clear this session's inbox of the mail older than `olderThanMs` — the door `clean` opens. */ async cleanInbox(olderThanMs) { if (!store || !record) throw new Error("session bus is not started."); const cleared = await store.cleanInbox({ now: now(), olderThanMs, own: record.id }); await mailWatch.refresh(); return cleared; }, /** * Show the mail without deleting it, and count it told. * * `inbox` is this read plus the delete, so the two differ in one fact only. A read is a * telling — the bodies reached the model — which is why the number a peer draws falls, and * why no notice repeats them; the files stay where `inbox` can still consume them. */ async read(limit) { const me = await currentRecord(); if (!store) throw new Error("session bus is not started."); const page = await store.peek(me.id, { limit: normalizeLimit(limit) }); mailWatch.markReported(page.mail.map((message) => message.id)); return page; }, async claim(rawPaths) { const me = await currentRecord(); return requireStore().claimAll(storedPaths(me, rawPaths), me.id, me.label, now()); }, async release(rawPaths, holder) { const me = await currentRecord(); const bus = requireStore(); const paths = storedPaths(me, rawPaths); if (holder === undefined) return releaseClaimed(paths, (path) => bus.release(path, me.id)); const peer = (await bus.sessions()).find((entry) => entry.label === holder && entry.id !== me.id); if (peer === undefined) throw new Error(`no live session labelled "${holder}" holds claims to take.`); const { moved: released, notHeld: notOwned } = await bus.transfer(paths, peer.id, me.id, me.label, now()); return { released, notOwned }; }, }; }