@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
257 lines • 11.6 kB
JavaScript
import { randomUUID } from "node:crypto";
import { appendFile, mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { GoalAlreadyExistsError, GoalNotFoundError } from "./errors.js";
import { withGoalFileLock } from "./goal-file-lock.js";
import { encodedThreadId, goalFilePath, migrateLegacyGoalFile, readGoalFile } from "./persistence.js";
import { transitionGoalStatus } from "./transitions.js";
import { resolveTokenBudget, validateObjective, validateTokenBudget } from "./validation.js";
export { goalFilePath };
export function goalHistoryFilePath(ref) {
return join(ref.baseDir, `${encodedThreadId(ref)}.history.jsonl`);
}
export function objectiveFullTextFileName(ref) {
return `${encodedThreadId(ref)}.objective-full.txt`;
}
export function objectiveFullTextFilePath(ref) {
return join(ref.baseDir, objectiveFullTextFileName(ref));
}
export async function readGoal(ref) {
return readGoalFile(ref);
}
/** Imports a legacy pi-goal store under the goal lock, so a concurrent mutation cannot overwrite the import. */
export async function migrateLegacyGoal(ref) {
return withGoalFileLock(ref, () => migrateLegacyGoalFile(ref));
}
export async function writeGoal(ref, goal) {
await withGoalFileLock(ref, (held) => held.write(goal));
}
export async function createGoal(ref, objective, tokenBudget) {
return withGoalFileLock(ref, async (held) => {
const validatedObjective = validateObjective(objective, objectiveFullTextFileName(ref));
const current = await readGoalFile(ref);
if (current !== null && current.status !== "complete") {
throw new GoalAlreadyExistsError("cannot create a new goal because this thread already has a goal");
}
if (validatedObjective.truncated) {
held.assertHeld();
await writeFullObjectiveText(ref, objective);
}
if (current?.status === "complete") {
held.assertHeld();
await archiveGoal(ref, current);
}
const now = nowSeconds();
const goal = {
id: randomUUID(),
threadId: ref.threadId,
objective: validatedObjective.objective,
status: "active",
tokensUsed: 0,
timeUsedSeconds: 0,
consecutiveContinuations: 0,
unattendedContinuations: 0,
noProgressContinuations: 0,
createdAt: now,
updatedAt: now,
lastStartedAt: now,
...(tokenBudget === undefined ? {} : { tokenBudget: validateTokenBudget(tokenBudget) }),
};
await held.write(goal);
return goal;
});
}
export async function updateGoal(ref, update, source = "model") {
return withGoalFileLock(ref, async (held) => {
const current = await readGoalFile(ref);
if (!current)
throw new GoalNotFoundError("cannot update goal: no goal exists");
const validatedObjective = update.objective === undefined
? undefined
: validateObjective(update.objective, objectiveFullTextFileName(ref));
const objective = validatedObjective?.objective ?? current.objective;
const tokenBudget = resolveTokenBudget(current.tokenBudget, update.tokenBudget);
const now = nextUpdatedAt(current.updatedAt);
const hasObjectiveUpdate = update.objective !== undefined;
const replacesGoal = hasObjectiveUpdate && (objective !== current.objective || current.status === "complete");
const requestedStatus = update.status ?? (hasObjectiveUpdate ? "active" : undefined);
if (replacesGoal) {
const status = requestedStatus ?? "active";
if (status === "blocked")
throw new Error("objective replacement cannot create a blocked goal");
const next = {
id: randomUUID(),
threadId: ref.threadId,
objective,
status,
tokensUsed: 0,
timeUsedSeconds: 0,
consecutiveContinuations: 0,
unattendedContinuations: 0,
noProgressContinuations: 0,
createdAt: now,
updatedAt: now,
...(tokenBudget === undefined ? {} : { tokenBudget }),
};
if (status === "active")
next.lastStartedAt = now;
if (status === "complete")
next.completedAt = now;
if (validatedObjective?.truncated) {
held.assertHeld();
await writeFullObjectiveText(ref, update.objective ?? "");
}
await held.write(next);
return next;
}
const next = transitionGoalStatus({ ...current, objective }, requestedStatus ?? current.status, source, update.reason, now);
if (next.status !== current.status) {
next.consecutiveContinuations = 0;
next.unattendedContinuations = 0;
next.noProgressContinuations = 0;
delete next.lastContinuationSignature;
delete next.continuationStoppedAt;
delete next.continuationStoppedDetail;
}
if (source === "user" && requestedStatus === "active") {
next.consecutiveContinuations = 0;
next.unattendedContinuations = 0;
next.noProgressContinuations = 0;
delete next.lastContinuationSignature;
delete next.continuationStoppedAt;
delete next.continuationStoppedDetail;
next.lastStartedAt ??= nowSeconds();
}
if (tokenBudget === undefined)
delete next.tokenBudget;
else
next.tokenBudget = tokenBudget;
if (validatedObjective?.truncated) {
held.assertHeld();
await writeFullObjectiveText(ref, update.objective ?? "");
}
await held.write(next);
return next;
});
}
export async function archiveGoal(ref, goal) {
const filePath = goalHistoryFilePath(ref);
await mkdir(dirname(filePath), { recursive: true });
await appendFile(filePath, `${JSON.stringify(goal)}\n`, "utf8");
}
async function writeFullObjectiveText(ref, objective) {
const filePath = objectiveFullTextFilePath(ref);
await mkdir(dirname(filePath), { recursive: true });
await writeFile(filePath, objective, "utf8");
}
export async function clearGoal(ref) {
return withGoalFileLock(ref, async (held) => {
const hadGoal = (await readGoalFile(ref)) !== null;
await held.write(null);
return hadGoal;
});
}
export async function accountGoalUsage(ref, usage, elapsedSeconds, mode = "active", expectedGoalId) {
return withGoalFileLock(ref, async (held) => {
const goal = await readGoalFile(ref);
if (!goal || (expectedGoalId !== undefined && goal.id !== expectedGoalId) || !canAccountGoalUsage(goal, mode)) {
return goal;
}
const next = {
...goal,
tokensUsed: goal.tokensUsed + Math.max(0, usage.input) + Math.max(0, usage.output),
timeUsedSeconds: goal.timeUsedSeconds + Math.max(0, Math.trunc(elapsedSeconds)),
updatedAt: nextUpdatedAt(goal.updatedAt),
};
if (goal.status === "active" && goal.lastStartedAt !== undefined)
next.lastStartedAt = nowSeconds();
await held.write(next);
return next;
});
}
export async function recordContinuationDelivered(ref, signature, expectedGoalId, options = {}) {
return withGoalFileLock(ref, async (held) => {
const goal = await readGoalFile(ref);
if (!goal || (expectedGoalId !== undefined && goal.id !== expectedGoalId))
return null;
const counted = options.countUnattended === false ? 0 : 1;
const next = {
...goal,
consecutiveContinuations: (goal.consecutiveContinuations ?? 0) + (options.countStreak === false ? 0 : 1),
unattendedContinuations: (goal.unattendedContinuations ?? 0) + counted,
noProgressContinuations: (goal.noProgressContinuations ?? 0) + counted,
lastContinuationSignature: signature,
};
delete next.continuationStoppedAt;
delete next.continuationStoppedDetail;
if (next.status === "active")
next.lastStartedAt ??= nowSeconds();
await held.write(next);
return next;
});
}
export async function resetContinuationStreak(ref, options = {}) {
return withGoalFileLock(ref, async (held) => {
const goal = await readGoalFile(ref);
if (!goal)
return goal;
const next = { ...goal, consecutiveContinuations: 0 };
if (options.unattended === true)
next.unattendedContinuations = 0;
if (options.unattended === true || options.progress === true)
next.noProgressContinuations = 0;
delete next.lastContinuationSignature;
delete next.continuationStoppedAt;
delete next.continuationStoppedDetail;
if (options.unattended === true && next.status === "active")
next.lastStartedAt ??= nowSeconds();
await held.write(next);
return next;
});
}
/** Claims one denial under the same lock as input/reset, so evaluation retries cannot append another stop. */
export async function recordGoalContinuationStopped(ref, expected, at, blockedReason, detail) {
return withGoalFileLock(ref, async (held) => {
const current = await readGoalFile(ref);
if (current?.id !== expected.id ||
current.status !== "active" ||
(blockedReason === undefined && current.continuationStoppedAt !== undefined) ||
current.lastContinuationSignature !== expected.lastContinuationSignature ||
current.consecutiveContinuations !== expected.consecutiveContinuations) {
return { goal: current, recorded: false };
}
const next = blockedReason === undefined
? { ...current, updatedAt: nextUpdatedAt(current.updatedAt) }
: transitionGoalStatus(current, "blocked", "model", blockedReason, nextUpdatedAt(current.updatedAt));
if (blockedReason === undefined && current.lastStartedAt !== undefined) {
next.timeUsedSeconds += Math.max(0, Math.trunc(at / 1000) - current.lastStartedAt);
}
if (blockedReason !== undefined) {
next.consecutiveContinuations = 0;
next.unattendedContinuations = 0;
next.noProgressContinuations = 0;
delete next.lastContinuationSignature;
}
delete next.lastStartedAt;
next.continuationStoppedAt = at;
// The claim alone cannot rebuild the session entries; keep the denied payload with it so a later
// session start can re-append exactly the entries a crash swallowed (senpi#3015).
next.continuationStoppedDetail = detail;
await held.write(next);
return { goal: next, recorded: true };
});
}
function canAccountGoalUsage(goal, mode) {
if (mode === "active")
return goal.status === "active";
if (mode === "activeOrBlocked")
return goal.status === "active" || goal.status === "blocked";
return goal.status === "active" || goal.status === "complete";
}
function nextUpdatedAt(previousUpdatedAt) {
return Math.max(nowSeconds(), previousUpdatedAt + 1);
}
function nowSeconds() {
return Math.trunc(Date.now() / 1000);
}
//# sourceMappingURL=store.js.map