UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

229 lines • 11.1 kB
import { CompactContentIndex } from "./compact-content-index.js"; import { COMPACT_LEAF_CODE_UNITS, CompactContentStore, } from "./compact-content-store.js"; import { assertProtocolDepth } from "./compact-protocol-depth.js"; import { CompactReadError } from "./compact-read-lease.js"; import { isProjection, } from "./compact-settled-rows.js"; /** One spillable collection owns payloads, end markers and both directions of the durable join. */ export class CompactSettledMessages { constructor(epoch, options, diagnose) { /** * Resident membership: one state key per message (`end:` ended but unjoined, `owner:` -> entry id joined before its * end, `settled:` -> entry id both), `terminal:` per pending terminal row and `entry:` per joined entry. Settling a * message folds its end marker into its join and drops its terminal row, so what a settled message keeps resident is * exactly the two id-sized facts the duplicate-end and conflicting-owner checks need (carried item 9, senpi#4460): * residency is O(settled messages) per epoch, two id keys per message, payloads zero. Bounding it independently of * message count needs a paged synchronous membership filter, carried to S08/S11 (RULING-48 item 9). */ this.keys = new Map(); this.joins = 0; this.epoch = epoch; this.diagnose = diagnose; this.store = new CompactContentStore(options); this.rows = new CompactContentIndex(this.store, (row) => (row.kind === "terminal" ? [...row.payload, row.call?.owner ?? 0] : []), 128); } /** The catalog's reader of one cut: rows a page at a time, payload leaves, paged values and entry joins. */ reader(root) { return { store: this.store, values: this.rows.values, members: (valid) => this.members(root, valid), messageOf: (entryId) => this.messageOf(root, entryId), }; } valid(carrier) { return carrier !== undefined && carrier.epoch === this.epoch; } /** * Returns the accepted end (undefined when refused): whether it joined the message to its durable entry, the only end * that settles persistence, and the message's settled ids (RULING-120): its `messageId` and the end's accepted sequence as * `terminalSequence`, which a pending or failed terminal pages as `message-<terminalSequence>` and a joined message * pages only through its `join-<n>` member's `messageId` (an already-joined end writes no terminal row). `call`: * the projection of the outstanding call this toolResult settles, stored with the terminal (Q2). The terminal is * serialized from `record`, so a record over the protocol depth limit is refused typed before anything changes * (RULING-59 C); the lane runs that check, and counts the refusal, before it calls this. */ end(record, carrier, sequence, turnId, call) { assertProtocolDepth(record); if (!this.valid(carrier)) return this.reject("unknown_message"); const identity = { messageId: carrier.messageId, terminalSequence: sequence }; const id = identity.messageId; if (this.keys.has(`end:${id}`) || this.keys.has(`settled:${id}`)) return this.reject("duplicate_end"); const owned = this.keys.get(`owner:${id}`); if (carrier.durableEntryId && owned !== undefined && owned !== carrier.durableEntryId) return this.reject("conflicting_owner"); let joined = false; if (carrier.durableEntryId && owned === undefined) { if (this.keys.has(`entry:${carrier.durableEntryId}`)) return this.reject("conflicting_owner"); this.join(id, carrier.durableEntryId); joined = true; } if (this.keys.has(`owner:${id}`)) { this.settle(id); return { joined, identity }; } // The call projection is owned first: a refusal there leaves no payload leaf and no end marker behind. const projection = call ? this.rows.values.own(call) : null; this.keys.set(`end:${id}`, ""); const message = Reflect.get(record, "message"); const role = String(Reflect.get(Object(message), "role")); const payload = []; const text = JSON.stringify({ terminal: message, correlation: { clientMessageId: Reflect.get(record, "clientMessageId"), clientTurnId: Reflect.get(record, "clientTurnId"), clientMessages: Reflect.get(record, "clientMessages"), }, }); for (let offset = 0; offset < text.length; offset += COMPACT_LEAF_CODE_UNITS) payload.push(this.store.createLeaf(text.slice(offset, offset + COMPACT_LEAF_CODE_UNITS))); this.put(`terminal:${id}`, { kind: "terminal", messageId: id, turnId, terminalSequence: identity.terminalSequence, role, runtimeItemKey: call?.runtimeItemKey ?? null, ...(call?.callUnknown ? { callUnknown: true } : {}), entryId: null, status: "pending", error: null, payload, call: projection, }); for (const leaf of payload) this.store.adjust(leaf, -1, 0); if (projection) this.store.adjust(projection.owner, -1, 0); if (!["user", "assistant", "toolResult", "custom"].includes(role)) this.diagnose("unsupported_role"); return { joined: false, identity }; } reject(reason) { this.diagnose(reason); return undefined; } /** Marks the message's pending terminal failed; returns the `messageId` that row carries, undefined for none. */ fail(carrier, errorMessage) { if (!this.valid(carrier) || !this.keys.has(`terminal:${carrier.messageId}`)) return this.reject("unknown_message"); this.rows.patch(`terminal:${carrier.messageId}`, { status: "failed", error: { errorMessage } }); return { messageId: carrier.messageId }; } /** Joins an owned append to its message; returns that message's id, the `messageId` of the join member it made. */ append(transition) { const id = transition.owningMessageId; if (id === undefined) return undefined; if (transition.recoveryEpoch !== this.epoch) return this.reject("retired_owner"); if (this.keys.has(`owner:${id}`) || this.keys.has(`settled:${id}`) || this.keys.has(`entry:${transition.id}`)) return this.reject("conflicting_owner"); this.join(id, transition.id); return id; } join(messageId, entryId) { const owner = { kind: "owner", messageId, entryId, ordinal: this.joins++ }; this.put(`owner:${messageId}`, owner); this.put(`entry:${entryId}`, owner); this.rows.delete(`terminal:${messageId}`); this.keys.delete(`terminal:${messageId}`); this.keys.set(`owner:${messageId}`, entryId); if (this.keys.has(`end:${messageId}`)) this.settle(messageId); } /** Ended and joined: its rows stay paged; its end marker folds into its join, its entry stays claimed. */ settle(messageId) { this.keys.set(`settled:${messageId}`, this.keys.get(`owner:${messageId}`) ?? ""); this.keys.delete(`owner:${messageId}`); this.keys.delete(`end:${messageId}`); } put(key, row) { this.rows.set(key, row); this.keys.set(key, ""); } /** The message each entry joined in this epoch, read in order from one cut of the paged rows; undefined for none. */ async messagesOf(entryIds) { const cut = this.rows.freeze(); try { const ids = []; for (const entryId of entryIds) ids.push((await this.messageOf(cut, entryId)) ?? undefined); return ids; } finally { this.rows.release(cut); } } freeze() { return this.rows.freeze(); } release(root) { this.rows.release(root); } async read(root) { const settledMessages = []; const owners = []; for (const [key, row] of await this.rows.entries(root)) { if (row.kind === "owner" && key.startsWith("owner:")) owners.push({ kind: "owner", messageId: row.messageId, entryId: row.entryId }); if (row.kind !== "terminal") continue; const { payload, kind: _kind, call, ...fields } = row; const bytes = (await Promise.all(payload.map((leaf) => this.store.readLeaf(leaf)))).join(""); const value = JSON.parse(bytes); const projection = call ? await this.rows.values.read(call) : undefined; if (projection !== undefined && !isProjection(projection)) throw new CompactReadError("ownership"); settledMessages.push({ ...fields, ...value, ...(projection ? { call: projection } : {}) }); } return { settledMessages, owners }; } /** * The rows of one cut, a descriptor page (at most 128) at a time (S10b): each terminal row with its patched status * and the ref of its paged call, each `owner:` join once (its `entry:` twin is the same row). A reader of a terminal's * payload or call pages through `readLeaf` and `values.walk` under the same cut. */ async *members(root, valid) { let cursor; do { const page = await this.rows.page(root, cursor); for (const { row, patch } of page.rows) { valid(); const key = await this.rows.values.read(row.key); if (typeof key !== "string" || key.startsWith("entry:")) continue; const stored = JSON.parse(JSON.stringify(await this.rows.values.read(row.value))); if (stored.kind === "owner") { yield stored; continue; } const patched = patch ? JSON.parse(JSON.stringify(await this.rows.values.read(patch))) : {}; yield { kind: "terminal", row: { ...stored, ...patched } }; } cursor = page.next; } while (cursor); } /** The message an entry joined in this cut, if any (the `source` family's join). */ async messageOf(root, entryId) { const row = await this.rows.lookup(root, `entry:${entryId}`); const owner = row && (await this.rows.values.read(row.value)); const messageId = owner ? Reflect.get(Object(owner), "messageId") : null; return typeof messageId === "string" ? messageId : null; } storageStatus() { return { ...this.store.status(), ...this.rows.status(), residentSettledKeys: this.keys.size }; } idle() { return this.store.idle(); } retire() { return this.store.retire(); } } //# sourceMappingURL=compact-settled-messages.js.map