UNPKG

@code-yeongyu/senpi

Version:

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

249 lines • 11.8 kB
import { randomUUID } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { AcceptedTranscript } from "./accepted-transcript.js"; import { MessageIdentities } from "./compact-message-identity.js"; import { CompactSettledMessages } from "./compact-settled-messages.js"; import { CompactContentStore } from "./compact-content-store.js"; import { TransferStaging } from "./compact-transfer-staging.js"; import { admitRecord, correlationChange, field, SEQUENCED, } from "./session-acceptance-admission.js"; import { foldCompactRecord, foldCompactTransition } from "./session-acceptance-compact.js"; import { AcceptedRootReads } from "./session-acceptance-reads.js"; import { recoveryAgentDir, RecoveryStorageHealth } from "./compact-storage-health.js"; import { SessionGenerations } from "./compact-session-generations.js"; const RETIRED_SETTLED = Object.freeze({ base: undefined, overrides: undefined }); /** * The ordered acceptance lane of one routing session. Every record reaches it synchronously, before * `SessionEventWriter.enqueue`, in the order the session produced it; a worker's records arrive here before * the worker's credit returns. Each bootstrap starts a new `sessionEpoch` whose sequences are never compared * with another epoch's. */ export class SessionAcceptanceLane extends AcceptedRootReads { constructor(storage, diagnose = (reason) => process.stderr.write(`senpi rpc acceptance: settled transition: ${reason}\n`), agentDir = recoveryAgentDir) { super(); this.epoch = ""; this.sequence = 0; this.activeMessageId = null; this.turnId = null; this.correlation = null; this.refusedCorrelations = 0; /** RULING-120 (#5331): the settled ids of the record being delivered, read at `acceptedSequence`. */ this.identities = new MessageIdentities(); this.storageRetired = false; this.nonce = randomUUID(); this.cleanup = Promise.resolve(); this.compact = () => ({ settled: this.settled, current: this.current }); this.generations = new SessionGenerations(agentDir); this.storage = { ...storage, dir: storage?.dir ?? tmpdir(), health: storage?.health ?? new RecoveryStorageHealth(agentDir), }; this.diagnose = diagnose; const dir = join(storage?.dir ?? tmpdir(), `senpi-transcript-${randomUUID()}`); this.staging = new TransferStaging(new CompactContentStore({ ...this.storage, dir })); this.transcript = new AcceptedTranscript(this.staging); } get recoveryEpoch() { return this.nonce; } /** The sequence of the last record this epoch accepted: what a record leased right after its acceptance names (S13). */ get acceptedSequence() { return this.sequence; } /** The public epoch of this incarnation (S08-Q1): distinct from the producer nonce, which is never serialized. */ get sessionEpoch() { return this.epoch; } get retired() { return this.retiredAs !== undefined; } get retirement() { return this.retiredAs; } /** Open broadcast questions now (a hot count for status); undefined when the compact state is unavailable. */ get openBroadcastDialogs() { return this.retired ? undefined : this.current.openBroadcastDialogs; } bootstrap(input, nonce = randomUUID()) { if (this.retired) return; if (this.settled) this.retireSettled(); this.identities.reset(); this.nonce = nonce; if (input.epochSignal) Buffer.from(nonce, "ascii").copy(Buffer.from(input.epochSignal)); this.settled = new CompactSettledMessages(nonce, { ...this.storage, dir: join(this.storage?.dir ?? tmpdir(), `senpi-settled-${randomUUID()}`), }, this.diagnose); this.epoch = randomUUID(); this.current.bootstrap({ ...this.storage, dir: join(this.storage?.dir ?? tmpdir(), `senpi-current-${randomUUID()}`), epoch: nonce, sessionEpoch: this.epoch, }); this.sequence = 0; // Every root of the previous epoch was released above, so its tail content goes with it. this.transcript.release(); this.transcript = new AcceptedTranscript(this.staging); this.transcript.bootstrap(input.transcript); this.activeMessageId = null; this.turnId = null; this.correlation = null; this.refusedCorrelations = 0; } /** Transcript transitions committed before the record they arrive with; each takes its own sequence (C1.1). */ applyTranscript(transitions) { if (this.retired || this.epoch === "") return; for (const transition of transitions) { this.sequence += 1; this.transcript.apply(transition); const owner = foldCompactTransition(this.compact(), transition, this.transcript.available, this.nonce); this.identities.joined(transition, owner); } } /** * A legacy record and, when the structured lane projected one, its canonical record: one unit, one sequence. * `canonicalRefused`: the pairing refused this event's canonical record at the protocol depth limit and that refusal * was already counted; like a record the depth check refuses here, the unit then takes its place but changes no * compact state, and the event is never counted twice (RULING-59 C). */ accept(record, carrier, canonical, canonicalRefused = false, callKey) { const type = field(record, "type"); this.identities.clear(); if (this.retired || this.epoch === "" || typeof type !== "string" || !SEQUENCED.has(type)) return undefined; this.beforeAccept?.(record); const folds = !canonicalRefused && this.current.admits(record, type); // The calls component decides first, before the lane commits anything for this record, its correlation change // included (RULING-13 Q9); a correlation change takes the sequence just before its record. const correlation = folds ? correlationChange(this.correlation, this.turnId, record) : undefined; const at = { sequence: this.sequence + (correlation ? 1 : 0), turnId: this.turnId }; const place = admitRecord(this.current, record, type, at, folds, callKey); if (!place) return undefined; if (!folds && correlationChange(this.correlation, this.turnId, record)) this.refusedCorrelations += 1; if (correlation) this.correlation = Object.freeze({ sequence: place.sequence - 1, ...correlation }); const { turnId, call } = place; this.turnId = turnId; this.sequence = place.sequence; if (type === "turn_end" || type === "agent_end") this.turnId = null; const messageId = type.startsWith("message_") && this.settled.valid(carrier) ? carrier.messageId : null; if (type === "message_start") this.activeMessageId = messageId; const unit = { record, type, carrier, canonical, sequence: this.sequence, turnId, call }; // An unfolded record is still delivered, so its `entry_appended` takes its entry's join (RULING-122). this.identities.hold(type, this.sequence, record, folds ? foldCompactRecord(this.compact(), unit) : undefined); if (type === "message_end" && this.activeMessageId === messageId) this.activeMessageId = null; return { sessionEpoch: this.epoch, sequence: this.sequence, historyVersion: this.transcript.historyVersion, messageId, turnId, }; } /** A block control has no legacy record; it is a unit of its own at the next sequence. */ acceptControl(unit) { if (this.retired || this.epoch === "" || !unit) return undefined; this.beforeAccept?.({ type: "materializer_control" }); this.sequence += 1; this.current.fold(unit, this.sequence); return this.sequence; } /** * A canonical record of this epoch was lost before folding, so its compact state can no longer be complete; one refused * at the protocol depth limit is counted instead, live state or not, and a live state stays (RULING-59 C). */ compactUnavailable(cause) { if (!this.retired) this.current.fail(cause); } freeze() { const root = Object.freeze({ sessionEpoch: this.epoch, sequence: this.sequence, activeMessageId: this.activeMessageId, turnId: this.turnId, correlation: this.correlation, refusedCorrelations: this.refusedCorrelations, transcript: this.transcript.freeze(), // A retired lane's paged settled store refuses new cuts; its root is never live or readable. settled: this.retired ? RETIRED_SETTLED : this.settled.freeze(), current: this.retired ? undefined : this.current.freeze(), }); if (this.retired) return root; this.rootOwners.set(root, this.settled); this.live.add(root); // The cut keeps the tail segments it names until it is released (RULING-78 (1)). root.transcript.tail.retainCut(root.transcript.count); return root; } release(root) { if (!this.live.delete(root)) return; root.transcript.tail.releaseCut(root.transcript.count); this.rootOwners.get(root)?.release(root.settled); this.current.release(root.current); if (this.retired) this.retireStorage(); } storageStatus() { return { ...this.settled.storageStatus(), refusedRecords: this.current.refusedRecords, ...this.identities.status(), transcript: this.staging.status(), }; } async idle() { await this.generations.idle(); await this.cleanup; await this.settled.idle(); await this.current.idle(); await this.staging.idle(); } retireSettled() { for (const root of this.live) this.release(root); this.cleanup = Promise.all([this.cleanup, this.settled.retire()]).then(() => { }); void this.cleanup.catch(() => this.diagnose("retired_owner")); } /** * No record is accepted after retirement, and every root this lane published is released except those in `keep`: * a legacy view still queued at a seal reads its root to the end (RULING-51 Q2=A), and the lane's storage retires * with the last such release. A root never published by this lane is not kept. The epoch's retained transcript * (ids, kinds, parents, tail) goes with the lane; a kept root holds its own reference until released. */ retire(reason, keep = new Set()) { this.retiredAs ??= reason; this.identities.reset(); this.generations.close(); this.transcript = new AcceptedTranscript(this.staging); for (const root of this.live) if (!keep.has(root)) this.release(root); this.retireStorage(); } retireStorage() { if (this.storageRetired || this.live.size > 0) return; this.storageRetired = true; if (this.settled) this.retireSettled(); this.current.retire(); this.cleanup = Promise.all([this.cleanup, this.staging.close()]).then(() => { }); void this.cleanup.catch(() => this.diagnose("retired_owner")); } } //# sourceMappingURL=session-acceptance-lane.js.map