UNPKG

@code-yeongyu/senpi

Version:

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

159 lines • 8.37 kB
import { callKey, cancelledKey, decodeCallRow, decodeVariant, encodeCallRow, encodeVariant, isStoredMessage, requestChunkKey, resultChunkKey, splitUtf8, stepIndexKey, stepIndexPrefix, variantKey, variantPrefix, } from "./ledger-schema.js"; const putRow = (row) => ({ op: "put", key: callKey(row.callId), data: encodeCallRow(row) }); const deletes = (count, key) => Array.from({ length: count }, (_, index) => ({ op: "delete", key: key(index) })); /** Every stored chunk of `row`: its request and, once `ended` with a message, the assembled message. */ const chunkDeletes = (row) => [ ...deletes(row.requestChunks, (index) => requestChunkKey(row.callId, index)), ...deletes(row.result?.kind === "message" ? row.result.chunks : 0, (index) => resultChunkKey(row.callId, index)), ]; /** A cancelled row keeps its identity and an error result, never pointers to chunks W14 deleted. */ function cancelledRow(row) { const { result, ...fields } = row; return { ...fields, state: "cancelled", requestChunks: 0, ...(result?.kind === "error" ? { result } : {}) }; } /** * W14 on the step's live row. A dispatched or ended row becomes `cancelled`; a superseded row (the abort came while its * reissue waited: the pacer backoff or the user's choice) stays superseded. Either way its chunks are deleted, because a * cancelled step is never dialed again, so no later W4 retires them. */ function cancelWrites(row) { if (row.state === "closed" || row.state === "cancelled") return []; const kept = row.state === "superseded" ? { ...row, requestChunks: 0 } : cancelledRow(row); return [putRow(kept), ...chunkDeletes(row)]; } /** The W9 part the ledger owns: the step's row becomes `closed` and its request chunks are deleted (4.5 retention). */ export function closeCallWrites(row) { return [putRow({ ...row, state: "closed" }), ...chunkDeletes(row)]; } export function createEgressLedger(options) { const { store, mutate } = options; const withRequest = (row, requestJson) => { const chunks = splitUtf8(requestJson); const next = { ...row, requestChunks: chunks.length }; const writes = chunks.map((data, index) => ({ op: "put", key: requestChunkKey(row.callId, index), data, })); return { row: next, writes: [...writes, putRow(next)] }; }; const variantWrite = async (variant) => { const key = variantKey(variant.providerId, variant.deviceId); const prior = decodeVariant(await store.getDocument(key)); const sameRun = prior !== undefined && prior.headDigest === variant.headDigest && prior.stepId === variant.stepId; const mismatches = sameRun ? prior.mismatches + 1 : 1; const { headDigest, liveAtMismatch, stepId } = variant; return { op: "put", key, data: encodeVariant({ headDigest, liveAtMismatch, mismatches, stepId }) }; }; const stepOf = (row) => { if (row.call.kind !== "step") throw new Error("the device-route ledger indexes loop steps only"); return row.call; }; const readRow = async (callId) => decodeCallRow(await store.getDocument(callKey(callId))); const readChunks = async (row, what, count, key) => { const chunks = await Promise.all(Array.from({ length: count }, (_, index) => store.getDocument(key(index)))); if (!chunks.every((chunk) => typeof chunk === "string")) throw new Error(`egress_call ${row.callId}: stored ${what} is incomplete`); return chunks.join(""); }; return { async rowsForStep(stepId) { const index = await store.scanDocuments(stepIndexPrefix(stepId)); const rows = await Promise.all(index.map((entry) => (typeof entry.data === "string" ? readRow(entry.data) : undefined))); return rows.filter((row) => row !== undefined); }, readRequest: (row) => readChunks(row, "request", row.requestChunks, (index) => requestChunkKey(row.callId, index)), async readMessage(row) { if (row.result?.kind !== "message") throw new Error(`egress_call ${row.callId} has no stored message`); const key = (index) => resultChunkKey(row.callId, index); const parsed = JSON.parse(await readChunks(row, "message", row.result.chunks, key)); if (!isStoredMessage(parsed)) throw new Error(`egress_call ${row.callId}: stored message is malformed`); return parsed; }, async dispatch(next, requestJson, previous) { const { stepId, attempt } = stepOf(next); const created = withRequest({ ...next, state: "dispatched", requestChunks: 0 }, requestJson); const retire = previous ? [ putRow({ ...previous, state: previous.state === "ended" ? "closed" : previous.state }), ...chunkDeletes(previous), ] : []; const index = { op: "put", key: stepIndexKey(stepId, attempt), data: next.callId }; await mutate(async () => [...retire, ...created.writes, index]); return created.row; }, async recordHooked(row, requestJson) { const updated = withRequest({ ...row, hooksApplied: true }, requestJson); await mutate(async () => [...chunkDeletes(row), ...updated.writes]); return updated.row; }, async end(row, result) { if (result.kind === "error") { const failed = { ...row, state: "ended", result }; await mutate(async () => [putRow(failed)]); return failed; } const chunks = splitUtf8(JSON.stringify(result.message)); const { stopReason, usage } = result.message; const ended = { ...row, state: "ended", result: { kind: "message", stopReason, usage, chunks: chunks.length }, }; const writes = chunks.map((data, index) => ({ op: "put", key: resultChunkKey(row.callId, index), data, })); await mutate(async () => [...writes, putRow(ended)]); return ended; }, async replaceRefused(row, callId) { const { stepId, attempt } = stepOf(row); const requestJson = await readChunks(row, "request", row.requestChunks, (i) => requestChunkKey(row.callId, i)); const created = withRequest({ ...row, callId, state: "dispatched", requestChunks: 0 }, requestJson); const index = { op: "put", key: stepIndexKey(stepId, attempt), data: callId }; const dropped = { op: "delete", key: callKey(row.callId) }; await mutate(async () => [dropped, ...chunkDeletes(row), ...created.writes, index]); return created.row; }, async supersede(row, variant) { const superseded = { ...row, state: "superseded" }; await mutate(async () => [putRow(superseded), ...(variant ? [await variantWrite(variant)] : [])]); return superseded; }, async cancelStep(stepId, row) { const live = row ? cancelWrites(row) : []; await mutate(async () => [{ op: "put", key: cancelledKey(stepId), data: stepId }, ...live]); }, async isCancelled(stepId) { return (await store.getDocument(cancelledKey(stepId))) !== undefined; }, async recordVariant(variant) { await mutate(async () => [await variantWrite(variant)]); }, async variants(providerId) { const prefix = variantPrefix(providerId); const entries = await store.scanDocuments(prefix); const variants = new Map(); for (const entry of entries) { const stored = decodeVariant(entry.data); if (!stored) continue; const { headDigest, liveAtMismatch, mismatches } = stored; variants.set(decodeURIComponent(entry.key.slice(prefix.length)), { headDigest, liveAtMismatch, mismatches, }); } return variants; }, }; } //# sourceMappingURL=ledger.js.map