@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
71 lines • 2.98 kB
JavaScript
import { randomUUID } from "node:crypto";
import { carryExecutionCallKey } from "./session-call-keys.js";
const carriers = new WeakMap();
const producers = new WeakMap();
/** Internal bootstrap, kept off AgentSession's public SDK surface. */
export function setSessionRecoveryEpoch(session, epoch) {
producers.get(session)?.reset(epoch);
}
export function recoveryCarrier(record) {
return carriers.get(record);
}
/** Every copy of a record on its way to the host lane keeps the original's carrier. */
export function carryRecovery(from, to) {
const carrier = carriers.get(from);
if (carrier !== undefined && from !== to)
carriers.set(to, carrier);
carryExecutionCallKey(from, to);
return to;
}
/**
* Mints each message's opaque id at its start, in emission order. An assistant stream copies its message per
* event, so it owns one open slot from start to end; other roles are keyed by their message object. A terminal
* with no start mints at that terminal; an update with no start has no owner and gets no id.
*/
export class SessionRecoveryIdentity {
constructor(epoch = randomUUID(), owner) {
this.byMessage = new WeakMap();
this.epoch = epoch;
if (owner)
producers.set(owner, this);
}
reset(epoch) {
if (epoch === this.epoch)
return;
this.epoch = epoch;
this.openAssistant = undefined;
this.byMessage = new WeakMap();
}
/** A committed lifecycle delivery can predate its terminal record. */
hint(event, durableEntryId) {
const carrier = carriers.get(event);
if (carrier && durableEntryId)
carriers.set(event, { ...carrier, durableEntryId });
}
/** A block control belongs to the assistant message open at its emission; it gets that message's identity. */
own(control) {
if (this.openAssistant !== undefined)
carriers.set(control, { messageId: this.openAssistant, epoch: this.epoch });
}
observe(event) {
const message = event.message;
if (message === undefined || carriers.has(event))
return;
if (event.type !== "message_start" && event.type !== "message_update" && event.type !== "message_end")
return;
const assistant = message.role === "assistant";
const known = assistant ? this.openAssistant : this.byMessage.get(message);
const messageId = event.type === "message_start"
? randomUUID()
: (known ?? (event.type === "message_end" ? randomUUID() : undefined));
if (messageId === undefined)
return;
if (assistant)
this.openAssistant = event.type === "message_end" ? undefined : messageId;
this.byMessage.set(message, messageId);
const carrier = { messageId, epoch: this.epoch };
carriers.set(event, carrier);
carriers.set(message, carrier);
}
}
//# sourceMappingURL=session-recovery-identity.js.map