UNPKG

@code-yeongyu/senpi

Version:

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

390 lines • 17 kB
/** * Atomic, versioned, per-session sidecar store for `/loop` state. * * Persistence (temp file + rename, per-file mutation serialization, envelope * version/session checks) lives in the shared session sidecar primitive. This * module supplies the loop domain parser and keeps the historical exported * surface so callers continue to catch {@link InvalidLoopStoreError} / * {@link UnsupportedLoopStoreVersionError} by name. * * Session custom entries are deliberately NOT the authoritative store: they are branch * nodes, so a globally scanned "latest" entry can come from an abandoned branch, while * loop schedules are session-scoped. */ import { createSidecarStore, encodedSessionId as encodeSidecarSessionId, InvalidSidecarStoreError, sidecarFilePath, UnsupportedSidecarStoreVersionError, } from "../../../session-sidecar-store.js"; import { EFFECTIVE_INTERVAL_UNITS, isRecord, LOOP_END_REASONS, LOOP_PHASES, LOOP_SENTINELS, LOOP_STATE_VERSION, LOOP_WAKE_SOURCE_KINDS, REQUESTED_INTERVAL_UNITS, } from "./types.js"; export class InvalidLoopStoreError extends InvalidSidecarStoreError { constructor(message, options) { super(message, options); this.name = "InvalidLoopStoreError"; } } export class UnsupportedLoopStoreVersionError extends UnsupportedSidecarStoreVersionError { constructor(message) { super(message); this.name = "UnsupportedLoopStoreVersionError"; } } const stores = new Map(); export function encodedSessionId(ref) { return encodeSidecarSessionId(ref.sessionId); } export function loopStateFilePath(ref) { return sidecarFilePath(ref); } export function emptyLoopState(sessionId) { return { version: LOOP_STATE_VERSION, sessionId, entries: {}, activeDynamicId: null, updatedAt: 0 }; } function storeFor(ref) { const filePath = loopStateFilePath(ref); const existing = stores.get(filePath); if (existing !== undefined) return existing; const store = createSidecarStore({ baseDir: ref.baseDir, sessionId: ref.sessionId, version: LOOP_STATE_VERSION, tempPrefix: "loop", parse: parseLoopPayload, }); stores.set(filePath, store); return store; } function remapLoopStoreError(error) { if (error instanceof InvalidLoopStoreError || error instanceof UnsupportedLoopStoreVersionError) { throw error; } if (error instanceof UnsupportedSidecarStoreVersionError) { throw new UnsupportedLoopStoreVersionError(error.message.replaceAll("sidecar store", "loop store")); } if (error instanceof InvalidSidecarStoreError) { throw new InvalidLoopStoreError(error.message.replaceAll("sidecar store", "loop store"), { cause: error }); } throw error; } /** * Reads persisted state, or null when this session has never persisted any loop. * Throws {@link InvalidLoopStoreError} / {@link UnsupportedLoopStoreVersionError} on * unusable state so callers fail closed rather than resetting a user's schedule. */ export async function readLoopState(ref) { try { return await storeFor(ref).read(); } catch (error) { remapLoopStoreError(error); } } /** Like {@link readLoopState}, but returns an empty state when nothing is persisted. */ export async function loadLoopState(ref) { return (await readLoopState(ref)) ?? emptyLoopState(ref.sessionId); } /** * Last successfully loaded or written state for this ref, for synchronous consumers * (status line, tick attribution). Undefined until the store has been touched. */ export function snapshotLoopState(ref) { return storeFor(ref).snapshot(); } /** * Serializes read-modify-write cycles through a per-file promise tail so command, * timer, tool, and lifecycle writes cannot interleave and lose an update. */ export function mutateLoopState(ref, mutation) { return storeFor(ref) .mutate((current) => mutation(current ?? emptyLoopState(ref.sessionId))) .catch((error) => remapLoopStoreError(error)); } /** Persists a complete state atomically. Prefer {@link mutateLoopState} for updates. */ export async function writeLoopState(ref, state) { await storeFor(ref).write(state); } /** Drops cached snapshots; used when a session ends or tests reset global state. */ export function clearLoopStateSnapshot(ref) { storeFor(ref).clear(); } function parseLoopPayload(raw, ref) { if (!isRecord(raw)) throw new InvalidLoopStoreError("loop store must be a JSON object"); if (!isEpochMs(raw.updatedAt)) throw new InvalidLoopStoreError("loop store has an invalid updatedAt"); if (!isRecord(raw.entries)) throw new InvalidLoopStoreError("loop store entries must be an object"); const entries = {}; for (const [id, value] of Object.entries(raw.entries)) { const entry = parseEntry(id, value); entries[id] = entry; } const activeDynamicId = raw.activeDynamicId; if (activeDynamicId !== null) { if (typeof activeDynamicId !== "string") { throw new InvalidLoopStoreError("loop store activeDynamicId must be a string or null"); } const active = entries[activeDynamicId]; if (active === undefined || active.kind !== "dynamic") { throw new InvalidLoopStoreError(`loop store activeDynamicId ${activeDynamicId} does not name a dynamic loop`); } } return { version: LOOP_STATE_VERSION, sessionId: ref.sessionId, entries, activeDynamicId, updatedAt: raw.updatedAt, }; } function parseEntry(id, value) { if (!isRecord(value)) throw new InvalidLoopStoreError(`loop entry ${id} is not an object`); if (value.id !== id) throw new InvalidLoopStoreError(`loop entry ${id} carries a mismatched id`); const kind = value.kind; if (kind !== "fixed" && kind !== "dynamic") throw new InvalidLoopStoreError(`loop entry ${id} has an unknown kind`); const base = parseEntryFields(id, value); if (kind === "fixed") { const fixed = { ...base, kind: "fixed", requestedInterval: parseRequestedInterval(id, value.requestedInterval), effectiveInterval: parseEffectiveInterval(id, value.effectiveInterval), cronExpression: requireString(id, "cronExpression", value.cronExpression), nextFireAt: requireEpochMs(id, "nextFireAt", value.nextFireAt), intervalMs: requirePositiveInteger(id, "intervalMs", value.intervalMs), }; return fixed; } const keepaliveCredit = value.keepaliveCredit; if (keepaliveCredit !== 0 && keepaliveCredit !== 1) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid keepaliveCredit`); } const dynamic = { ...base, kind: "dynamic", pendingWakeup: parsePendingWakeup(id, value.pendingWakeup), keepaliveCredit, }; return dynamic; } function parseEntryFields(id, value) { const fields = { id, originalArgs: requireString(id, "originalArgs", value.originalArgs, { allowEmpty: true }), reentryPrompt: requireString(id, "reentryPrompt", value.reentryPrompt), payload: parsePayload(id, value.payload), createdAt: requireEpochMs(id, "createdAt", value.createdAt), lastFiredAt: parseNullableEpochMs(id, "lastFiredAt", value.lastFiredAt), expiresAt: requireEpochMs(id, "expiresAt", value.expiresAt), lastScheduledForAt: parseNullableEpochMs(id, "lastScheduledForAt", value.lastScheduledForAt), coalescedFirePending: requireBoolean(id, "coalescedFirePending", value.coalescedFirePending), queuedForAt: parseNullableEpochMs(id, "queuedForAt", value.queuedForAt), noopStreak: requireNonNegativeInteger(id, "noopStreak", value.noopStreak), tickCount: requireNonNegativeInteger(id, "tickCount", value.tickCount), sentinelDelivery: parseSentinelDelivery(id, value.sentinelDelivery), wakeSources: parseWakeSources(id, value.wakeSources), }; return { ...fields, ...parseLifecycle(id, value) }; } function parseLifecycle(id, value) { const phase = value.phase; if (typeof phase !== "string" || !isLoopPhase(phase)) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid phase`); } if (phase !== "ended") { if (value.endedAt !== undefined || value.endReason !== undefined || value.endDetail !== undefined) { throw new InvalidLoopStoreError(`loop entry ${id} carries terminal fields while not ended`); } return { phase }; } const endReason = value.endReason; if (typeof endReason !== "string" || !isLoopEndReason(endReason)) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid endReason`); } const endDetail = value.endDetail; if (endDetail !== undefined && typeof endDetail !== "string") { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid endDetail`); } return { phase: "ended", endedAt: requireEpochMs(id, "endedAt", value.endedAt), endReason, ...(endDetail === undefined ? {} : { endDetail }), }; } function parsePayload(id, value) { if (!isRecord(value)) throw new InvalidLoopStoreError(`loop entry ${id} has an invalid payload`); if (value.type === "prompt") { return { type: "prompt", prompt: requireString(id, "payload.prompt", value.prompt) }; } if (value.type === "sentinel") { const sentinel = value.sentinel; if (typeof sentinel !== "string" || !isLoopSentinel(sentinel)) { throw new InvalidLoopStoreError(`loop entry ${id} has an unknown payload sentinel`); } return { type: "sentinel", sentinel }; } throw new InvalidLoopStoreError(`loop entry ${id} has an unknown payload type`); } function parseSentinelDelivery(id, value) { if (!isRecord(value)) throw new InvalidLoopStoreError(`loop entry ${id} has an invalid sentinelDelivery`); return { autonomousPreambleDelivered: requireBoolean(id, "sentinelDelivery.autonomousPreambleDelivered", value.autonomousPreambleDelivered), lastLoopFileDelivered: parseFingerprint(id, value.lastLoopFileDelivered), forceFullDelivery: requireBoolean(id, "sentinelDelivery.forceFullDelivery", value.forceFullDelivery), }; } function parseFingerprint(id, value) { if (value === null) return null; if (!isRecord(value)) throw new InvalidLoopStoreError(`loop entry ${id} has an invalid loop-file fingerprint`); return { path: requireString(id, "fingerprint.path", value.path), mtimeMs: requireFiniteNumber(id, "fingerprint.mtimeMs", value.mtimeMs), size: requireNonNegativeInteger(id, "fingerprint.size", value.size), contentHash: requireString(id, "fingerprint.contentHash", value.contentHash), anchorDeliveryId: requireString(id, "fingerprint.anchorDeliveryId", value.anchorDeliveryId), }; } function parseWakeSources(id, value) { if (!Array.isArray(value)) throw new InvalidLoopStoreError(`loop entry ${id} has invalid wakeSources`); return value.map((candidate) => { if (!isRecord(candidate)) throw new InvalidLoopStoreError(`loop entry ${id} has an invalid wake source`); const source = candidate.source; if (typeof source !== "string" || !isWakeSourceKind(source)) { throw new InvalidLoopStoreError(`loop entry ${id} has an unknown wake source kind`); } const description = candidate.description; if (description !== undefined && typeof description !== "string") { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid wake source description`); } return { source, id: requireString(id, "wakeSource.id", candidate.id), createdAt: requireEpochMs(id, "wakeSource.createdAt", candidate.createdAt), ...(description === undefined ? {} : { description }), }; }); } function parsePendingWakeup(id, value) { if (value === null || value === undefined) return null; if (!isRecord(value)) throw new InvalidLoopStoreError(`loop entry ${id} has an invalid pendingWakeup`); const source = value.source; if (source !== "model" && source !== "keepalive") { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid pendingWakeup source`); } if (value.kind !== "dynamic") throw new InvalidLoopStoreError(`loop entry ${id} has an invalid pendingWakeup kind`); return { id: requireString(id, "pendingWakeup.id", value.id), loopId: requireString(id, "pendingWakeup.loopId", value.loopId), kind: "dynamic", source, requestedDelaySeconds: requireFiniteNumber(id, "pendingWakeup.requestedDelaySeconds", value.requestedDelaySeconds), delaySeconds: requirePositiveInteger(id, "pendingWakeup.delaySeconds", value.delaySeconds), dueAt: requireEpochMs(id, "pendingWakeup.dueAt", value.dueAt), reason: requireString(id, "pendingWakeup.reason", value.reason), prompt: requireString(id, "pendingWakeup.prompt", value.prompt), noop: requireBoolean(id, "pendingWakeup.noop", value.noop), createdAt: requireEpochMs(id, "pendingWakeup.createdAt", value.createdAt), }; } function parseRequestedInterval(id, value) { if (!isRecord(value)) throw new InvalidLoopStoreError(`loop entry ${id} has an invalid requestedInterval`); const unit = value.unit; if (typeof unit !== "string" || !isRequestedIntervalUnit(unit)) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid requestedInterval unit`); } return { value: requirePositiveInteger(id, "requestedInterval.value", value.value), unit, raw: requireString(id, "requestedInterval.raw", value.raw), }; } function parseEffectiveInterval(id, value) { if (!isRecord(value)) throw new InvalidLoopStoreError(`loop entry ${id} has an invalid effectiveInterval`); const unit = value.unit; if (typeof unit !== "string" || !isEffectiveIntervalUnit(unit)) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid effectiveInterval unit`); } const roundingNotice = value.roundingNotice; if (roundingNotice !== undefined && typeof roundingNotice !== "string") { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid effectiveInterval roundingNotice`); } return { value: requirePositiveInteger(id, "effectiveInterval.value", value.value), unit, human: requireString(id, "effectiveInterval.human", value.human), rounded: requireBoolean(id, "effectiveInterval.rounded", value.rounded), ...(roundingNotice === undefined ? {} : { roundingNotice }), }; } function requireString(id, field, value, options) { if (typeof value !== "string" || (options?.allowEmpty !== true && value.length === 0)) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid ${field}`); } return value; } function requireBoolean(id, field, value) { if (typeof value !== "boolean") throw new InvalidLoopStoreError(`loop entry ${id} has an invalid ${field}`); return value; } function requireFiniteNumber(id, field, value) { if (typeof value !== "number" || !Number.isFinite(value)) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid ${field}`); } return value; } function requireNonNegativeInteger(id, field, value) { if (!Number.isSafeInteger(value) || value < 0) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid ${field}`); } return value; } function requirePositiveInteger(id, field, value) { if (!Number.isSafeInteger(value) || value <= 0) { throw new InvalidLoopStoreError(`loop entry ${id} has an invalid ${field}`); } return value; } function requireEpochMs(id, field, value) { if (!isEpochMs(value)) throw new InvalidLoopStoreError(`loop entry ${id} has an invalid ${field}`); return value; } function parseNullableEpochMs(id, field, value) { if (value === null || value === undefined) return null; return requireEpochMs(id, field, value); } function isEpochMs(value) { return Number.isSafeInteger(value) && value >= 0; } function isLoopPhase(value) { return LOOP_PHASES.includes(value); } function isLoopEndReason(value) { return LOOP_END_REASONS.includes(value); } function isLoopSentinel(value) { return LOOP_SENTINELS.includes(value); } function isWakeSourceKind(value) { return LOOP_WAKE_SOURCE_KINDS.includes(value); } function isRequestedIntervalUnit(value) { return REQUESTED_INTERVAL_UNITS.includes(value); } function isEffectiveIntervalUnit(value) { return EFFECTIVE_INTERVAL_UNITS.includes(value); } //# sourceMappingURL=store.js.map