UNPKG

@code-yeongyu/senpi

Version:

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

551 lines • 26.5 kB
import { MANUAL_CONTINUE_CUSTOM_TYPE } from "../../../manual-continue.js"; import { buildDeadlineStopNotice, deadlineStopPendingSinceLastTurn, TURN_DEADLINE_ENTRY_TYPE, } from "../../../turn-deadline.js"; import { noticeEntryRenderer } from "../../notice/index.js"; import { continueGoalAfterAgentEnd } from "./agent-end-continuation.js"; import { GOAL_CACHE_WARMUP_ENTRY_TYPE } from "./cache-warm.js"; import { isSameGoalCacheWarmCard, renderGoalCacheWarmupEntry } from "./cache-warm-renderer.js"; import { registerGoalCommand } from "./command-registration.js"; import { GOAL_CONTINUATION_CAP } from "./continuation.js"; import { GoalDirectInputLifecycle } from "./direct-input-lifecycle.js"; import { GoalElapsedTicker } from "./elapsed-ticker.js"; import { formatGoalForTool, goalStatusLabel } from "./format.js"; import { goalLifecycleChanged, registerGoalLifecycleCollector } from "./lifecycle-facts.js"; import { GOAL_STALE_STOP_NOTICE, isResumeOfStoppedGoal, recoverMissingGoalContinuationStop, } from "./lifecycle-helpers.js"; import { GOAL_CONTINUATION_SCHEDULED_EVENT, MonitorAwareGoalContinuation } from "./monitor-continuation.js"; import { reengageGoalAfterReload } from "./reload-reengagement.js"; import { registerGoalFireNowRequest } from "./rpc-wait-surface.js"; import { queueGoalContinuation, readTrailingGoalContinuations } from "./session-start-continuation.js"; import { isStaleExtensionContextError } from "./stale-context.js"; import { interruptedRunHeld, markStopPaused, markStopResumed, pausedByStop, stopHoldLive } from "./stop-pause.js"; import { accountGoalUsage, migrateLegacyGoal, readGoal, updateGoal } from "./store.js"; import { GOAL_STORE_CHANGED_EVENT, isGoalStoreChangedEvent } from "./store-changed-event.js"; import { goalStoreRef as buildGoalStoreRef } from "./store-ref.js"; import { staleGoalTodoReminder, todoResultAddsOpenTasks } from "./todo-gate.js"; import { TodoOwedBackstop } from "./todo-owed-backstop.js"; import { registerGoalTools } from "./tool-registration.js"; import { collectTurnEndLivenessInput, reportTurnEndLiveness } from "./turn-end-liveness-report.js"; import { TurnUsageTracker } from "./turn-usage.js"; import { updateGoalUi } from "./ui.js"; import { GOAL_WAIT_STATUS_KEY, GoalWaitTicker } from "./wait-ticker.js"; const RESUME_GOAL_CHOICE = "Resume goal"; const LEAVE_GOAL_STOPPED_CHOICE = "Leave stopped"; export default function goalExtension(pi) { // A user Stop pauses the goal with the session; a plain interrupt keeps blocking it (senpi#3811). async function pauseOrBlockOnUserAbort(ctx, goalId) { if (stopHoldLive(ctx)) { markStopPaused(pi, goalId); return updateGoal(goalStoreRef(ctx), { status: "paused" }, "user"); } return updateGoal(goalStoreRef(ctx), { status: "blocked", reason: "user interrupted the turn" }, "model"); } let agentTurnInProgress = false; let staleGoalReminderSentThisTurn = false; let agentGoalAccounting = null; let blockedThisTurnGoalId = null; let completedThisTurnGoalId = null; let continuationPending = false; let activeContext; let lastAgentEnd; let lastTodoOutcome; let retireLifecycleCollector; const turnUsage = new TurnUsageTracker(); // No stale-ctx swallow here: GoalWaitTicker retires itself on a stale render // (a ticker that keeps ticking against a retired ctx freezes the footer // countdown forever); non-stale render errors still propagate. const goalWaitTicker = new GoalWaitTicker({ render: (renderCtx, status) => renderCtx.ui.setStatus(GOAL_WAIT_STATUS_KEY, status), }); const monitorContinuation = new MonitorAwareGoalContinuation(pi, () => continuationPending, () => { continuationPending = true; }, goalWaitTicker); registerGoalFireNowRequest(pi, () => monitorContinuation.fireNow()); const todoOwedBackstop = new TodoOwedBackstop(pi); const directInputLifecycle = new GoalDirectInputLifecycle({ monitor: monitorContinuation, goalStoreRef, beginAgentGoalAccounting, refreshGoalUi: refreshGoalUiBestEffort, resumeAfterSuppressedLoad: (resumeCtx, goal) => queueGoalContinuationForCurrentSession(pi, resumeCtx, goal), onAcceptedDirectInput: () => todoOwedBackstop.resetChain(), }); const goalTicker = new GoalElapsedTicker({ render: (renderCtx, renderGoal, live) => updateGoalUi(renderCtx, renderGoal, live), }); pi.registerEntryRenderer(GOAL_CACHE_WARMUP_ENTRY_TYPE, renderGoalCacheWarmupEntry, { replaces: isSameGoalCacheWarmCard, }); pi.registerEntryRenderer(TURN_DEADLINE_ENTRY_TYPE, noticeEntryRenderer((entry) => { const data = entry.data; if (data === undefined) return undefined; return { title: "turn stopped on a deadline", why: buildDeadlineStopNotice(data) }; })); registerGoalTools(pi, { goalStoreRef: (ctx) => buildGoalStoreRef(ctx.sessionManager, ctx.cwd), accountCurrentAgentTurn, beginAgentGoalAccounting: (goal) => { monitorContinuation.noteContinuationStarted(); beginAgentGoalAccounting(goal); }, markGoalBlockedThisTurn, markGoalCompletedThisTurn, refreshGoalUi, }); registerGoalCommand(pi, { goalStoreRef: (ctx) => buildGoalStoreRef(ctx.sessionManager, ctx.cwd), accountCurrentAgentTurn, beginAgentGoalAccounting, stopAgentGoalAccounting, clearAgentGoalAccounting, queueGoalContinuation: (extensionApi, commandCtx, goal) => { void queueGoalContinuationForCurrentSession(extensionApi, commandCtx, goal); }, refreshGoalUi, }); const unsubscribeGoalStoreChanged = pi.events?.on(GOAL_STORE_CHANGED_EVENT, async (data) => { if (!isGoalStoreChangedEvent(data)) return; const ctx = data.ctx ?? activeContext; if (ctx === undefined || ctx.sessionManager.getSessionId() !== data.threadId || !ctx.isIdle() || ctx.hasPendingMessages()) { return; } const goal = await readGoal(goalStoreRef(ctx)); if (goal?.status !== "active") return; monitorContinuation.syncGoal(goal); beginAgentGoalAccounting(goal); refreshGoalUiBestEffort(ctx, goal); pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, { goalId: goal.id, delayMs: 0, activeMonitorCount: 0, wakeSources: {}, reason: GOAL_STORE_CHANGED_EVENT, }); await queueGoalContinuationForCurrentSession(pi, ctx, goal); }) ?? (() => { }); pi.on("session_start", async (event, ctx) => { ctx.ui.setStatus("todo-waiting", undefined); activeContext = ctx; monitorContinuation.start(ctx); retireLifecycleCollector?.(); retireLifecycleCollector = registerGoalLifecycleCollector(ctx.sessionManager, async (restoredEnd, changedGoal) => { const goal = changedGoal === undefined ? await readGoal(goalStoreRef(ctx)) : changedGoal; const end = lastAgentEnd ?? restoredEnd; return { goal, ...(lastTodoOutcome === undefined ? {} : { todoOutcome: lastTodoOutcome }), ...(end ? { input: collectTurnEndLivenessInput(ctx, end, { goal, todoOutcome: lastTodoOutcome, deadlineStop: deadlineStopPendingSinceLastTurn(ctx.sessionManager.getBranch()) !== undefined, continuationPending, monitor: monitorContinuation, }), } : {}), }; }); directInputLifecycle.reset(); todoOwedBackstop.resetChain(); const ref = goalStoreRef(ctx); await migrateLegacyGoal(ref); let goal = await readGoal(goalStoreRef(ctx)); // senpi#3015: a crash between the stop claim and the session append leaves the claim // without its entries; re-append the missing ones once on reopen. if (goal) await recoverMissingGoalContinuationStop(pi, ctx, goal); // A process that died mid-turn never ran the quit-time abort that stops an active goal (senpi#5753). Stop it the // same way here, so the resume prompt below asks before any continuation runs (senpi#5755). Opening that session // at launch (`--continue`, `--session`) is the same resume, so it asks too. let stoppedInterruptedGoal = false; if ((event.reason === "resume" || event.reason === "startup") && ctx.hasUI && goal?.status === "active" && goal.continuationStoppedAt === undefined && interruptedRunHeld(ctx)) { goal = await pauseOrBlockOnUserAbort(ctx, goal.id); stoppedInterruptedGoal = true; } if (goal?.status === "active") { beginAgentGoalAccounting(goal); } else { clearAgentGoalAccounting(); } refreshGoalUi(ctx, goal); // A session reopened under a live Stop keeps its goal paused until the Stop is released. if (await pauseGoalWithHeldSession(ctx)) return; // A goal a live Stop paused (a crashed run included) resumes with the session once the Stop is released, so the // resume prompt would only restart its counter under the hold. if (goal?.status === "paused" && stopHoldLive(ctx) && pausedByStop(ctx, goal.id)) return; // Opening the session earns one reminder; renders and extension reloads do not. // Stale stops retain active status, unlike user-paused or blocking stops. if ((event.reason === "startup" || event.reason === "resume") && goal?.status === "active" && goal.continuationStoppedAt !== undefined) { if (ctx.hasUI) ctx.ui.notify(GOAL_STALE_STOP_NOTICE, "info"); return; } if (await maybePromptResumeStoppedGoal(pi, ctx, stoppedInterruptedGoal ? "resume" : event.reason, goal)) { return; } if (goal && event.reason === "reload") { // A reload retires the extension generation and every armed continuation // timer with it. Re-engage through the reload path: stopped goals stay // stopped, active goals resume the wait the reload tore down. await reengageGoalAfterReload({ ctx, goal, monitor: monitorContinuation, readTrailingContinuations: () => readTrailingGoalContinuations(ctx.sessionManager.getBranch()), queueContinuation: (limitWait) => queueGoalContinuationForCurrentSession(pi, ctx, goal, limitWait), }); } else if (goal) { // Migration-lite admission: a resumed session carrying a trailing flood of // historical continuations must not reignite on load. Skip the auto-queue, // leave the goal active (no status rewrite), and tell the user how to resume. const trailing = readTrailingGoalContinuations(ctx.sessionManager.getBranch()); // A session a host restart interrupted is not a cold resume (senpi#7020): its streak goes on. if (trailing.counted >= GOAL_CONTINUATION_CAP && event.continued !== true) { // The load-time flood suppression parks the goal without rewriting its // status, so the only resume signal left is the user's next message. // Arm the one-shot latch the direct-input lifecycle fires when that // message is accepted; without it the promise in the notice is a lie // and the resumed session sits idle until the goal is recreated. directInputLifecycle.armSuppressedLoadResume(); ctx.ui.notify(`Goal auto-continuation suppressed for this resumed session (${trailing.counted} historical continuations). Send a message to resume.`, "info"); } else { await queueGoalContinuationForCurrentSession(pi, ctx, goal, trailing.waitingOutLimit); } } }); // A Stop that lands while no turn runs emits no `session_abort`, so the goal pauses and resumes with the session here. // Edges are applied one at a time against the hold as it is now: an input that admits no turn (a slash command) // releases the Stop and takes it back within milliseconds, and handling those two edges concurrently let the resume // write land after the pause read, leaving the goal running under a live Stop (senpi#6897). let holdChange = Promise.resolve(); pi.on("session_hold_changed", (_event, ctx) => { const applied = holdChange.then(() => stopHoldLive(ctx) ? pauseGoalWithHeldSession(ctx).then(() => { }) : resumeGoalWithReleasedSession(ctx)); holdChange = applied.catch(() => { }); return applied; }); pi.on("held_wakes_released", async (event, ctx) => { if (!event.sources.goal) return; const goal = await readGoal(goalStoreRef(ctx)); if (goal?.status !== "active") return; monitorContinuation.noteContinuationStarted(); await queueGoalContinuationForCurrentSession(pi, ctx, goal); }); pi.on("session_tree", async (_event, ctx) => { ctx.ui.setStatus("todo-waiting", undefined); todoOwedBackstop.resetChain(); }); pi.on("input", async (event, ctx) => { await directInputLifecycle.onInput(event, ctx); }); pi.on("input_disposition", async (event, ctx) => { await directInputLifecycle.onDisposition(event, ctx); }); pi.on("turn_start", async () => { staleGoalReminderSentThisTurn = false; }); // When the model starts tracking new open todo work while the thread has no // goal (or only a stale, already-complete one), append a system reminder to // the todo result so the model registers the goal when the work warrants it. pi.on("tool_result", async (event, ctx) => { if (event.toolName !== "todo" || event.isError || staleGoalReminderSentThisTurn) return undefined; if (!todoResultAddsOpenTasks(event.details)) return undefined; const reminder = staleGoalTodoReminder(await readGoal(goalStoreRef(ctx))); if (reminder === undefined) return undefined; staleGoalReminderSentThisTurn = true; return { content: [...event.content, { type: "text", text: reminder }] }; }); pi.on("agent_start", async (_event, ctx) => { lastAgentEnd = undefined; lastTodoOutcome = undefined; ctx.ui.setStatus("todo-waiting", undefined); const continuationStarted = continuationPending; continuationPending = false; if (continuationStarted) monitorContinuation.noteContinuationStarted(); agentTurnInProgress = true; blockedThisTurnGoalId = null; completedThisTurnGoalId = null; turnUsage.reset(); const goal = await readGoal(goalStoreRef(ctx)); if (goal?.status === "active") { beginAgentGoalAccounting(goal); } else { agentGoalAccounting = null; } }); pi.on("message_start", async (event, ctx) => { if (event.message.role !== "custom" || event.message.customType !== MANUAL_CONTINUE_CUSTOM_TYPE) return; const ref = goalStoreRef(ctx); const goal = await readGoal(ref); if (goal?.status !== "blocked") return; syncContinuationGoal(ctx, await updateGoal(ref, { status: "active" }, "user")); }); pi.on("message_end", async (event) => { turnUsage.noteMessageEnd(event.message); }); pi.on("agent_end", async (event, ctx) => { const mode = blockedThisTurnGoalId !== null ? "activeOrBlocked" : completedThisTurnGoalId === null ? "active" : "activeOrComplete"; let goal = await accountCurrentAgentTurn(ctx, mode, event.messages); agentTurnInProgress = false; blockedThisTurnGoalId = null; completedThisTurnGoalId = null; if (goal?.status === "paused" && !stopHoldLive(ctx) && pausedByStop(ctx, goal.id)) { markStopResumed(pi, goal.id); goal = await updateGoal(goalStoreRef(ctx), { status: "active" }, "user"); } if (event.aborted === true && event.abortSource === "user" && goal?.status === "active") { goal = await pauseOrBlockOnUserAbort(ctx, goal.id); } else if (goal?.status === "active" && goal.continuationStoppedAt === undefined && stopHoldLive(ctx)) { // A Stop that joined this turn's agent_end boundary leaves the turn un-aborted; the goal still pauses with it. markStopPaused(pi, goal.id); goal = await updateGoal(goalStoreRef(ctx), { status: "paused" }, "user"); } if (goal?.status === "active") { beginAgentGoalAccounting(goal); } else { clearAgentGoalAccounting(); } refreshGoalUiBestEffort(ctx, goal); const continuationGoal = await continueGoalAfterAgentEnd(monitorContinuation, { ctx, event, goal }); if (continuationGoal !== goal) { goal = continuationGoal; syncContinuationGoal(ctx, goal); } const deadlineStop = deadlineStopPendingSinceLastTurn(ctx.sessionManager.getBranch()) !== undefined; const todoOutcome = deadlineStop ? undefined : todoOwedBackstop.afterAgentEnd({ ctx, event, goal, continuationPending, hasActiveWakeSources: monitorContinuation.hasActiveWakeSources(), wakeSourceNames: monitorContinuation.liveWakeSources(), }); lastAgentEnd = event; lastTodoOutcome = todoOutcome; reportTurnEndLiveness(pi, ctx, event, { goal, todoOutcome, deadlineStop, continuationPending, monitor: monitorContinuation, }); }); pi.on("agent_settled", async (event, ctx) => { const goal = await monitorContinuation.afterAgentSettled(event.fallbackExhausted); if (goal !== undefined) syncContinuationGoal(ctx, goal); }); pi.on("session_abort", async (_event, ctx) => { continuationPending = false; const goal = await readGoal(goalStoreRef(ctx)); if (goal?.status !== "active") return; const accounted = await accountCurrentAgentTurn(ctx, "active"); if (accounted?.status === "active") { const stopped = await pauseOrBlockOnUserAbort(ctx, accounted.id); clearAgentGoalAccounting(); refreshGoalUiBestEffort(ctx, stopped); } }); pi.on("session_shutdown", async (event, ctx) => { retireLifecycleCollector?.(); activeContext = undefined; unsubscribeGoalStoreChanged(); if (agentGoalAccounting !== null) { await accountCurrentAgentTurn(ctx, "active"); } clearAgentGoalAccounting(); // A graceful close stops the goal cleanly (oh-my-openagent#14313): it reopens paused, never mid-continuation. if (event.closed === true && (await readGoal(goalStoreRef(ctx)))?.status === "active") await updateGoal(goalStoreRef(ctx), { status: "paused" }, "user"); goalTicker.stop(); monitorContinuation.dispose(); }); async function maybePromptResumeStoppedGoal(pi, ctx, sessionStartReason, goal) { if (!isResumeOfStoppedGoal(ctx, sessionStartReason, goal)) { return false; } // RPC switch_session cannot service a nested interactive UI request until the // switch response completes. Keep the goal stopped and let the user resume it // explicitly after the new session finishes binding. if (ctx.mode === "rpc") { ctx.ui.notify(`Goal remains ${goal.status} after session resume. Resume it explicitly after the session finishes loading.`, "info"); return true; } const choice = await ctx.ui.select(`Resume ${goal.status} goal?\nGoal: ${goal.objective}`, [ RESUME_GOAL_CHOICE, LEAVE_GOAL_STOPPED_CHOICE, ]); if (choice !== RESUME_GOAL_CHOICE) return true; const resumed = await updateGoal(goalStoreRef(ctx), { status: "active" }, "user"); beginAgentGoalAccounting(resumed); refreshGoalUi(ctx, resumed); ctx.ui.notify(`Goal ${goalStatusLabel(resumed.status)}\n${formatGoalForTool(resumed)}`, "info"); await queueGoalContinuationForCurrentSession(pi, ctx, resumed); return true; } async function queueGoalContinuationForCurrentSession(extensionApi, ctx, goal, limitWait = false) { const continuedGoal = await queueGoalContinuation(extensionApi, ctx, goal, { continuationPending, markContinuationPending: () => { continuationPending = true; }, limitWait, }); if (continuedGoal === null) { clearAgentGoalAccounting(); refreshGoalUiBestEffort(ctx, null); return; } if (continuedGoal === goal) return; syncContinuationGoal(ctx, continuedGoal); } /** Close the accounting window at the Stop and pause an idle active goal; a running turn pauses at its `agent_end`. */ async function pauseGoalWithHeldSession(ctx) { if (agentTurnInProgress || !stopHoldLive(ctx)) return false; const goal = await readGoal(goalStoreRef(ctx)); if (goal?.status !== "active" || goal.continuationStoppedAt !== undefined) return false; const accounted = await accountCurrentAgentTurn(ctx, "active"); if (accounted?.status !== "active") return false; markStopPaused(pi, accounted.id); const paused = await updateGoal(goalStoreRef(ctx), { status: "paused" }, "user"); clearAgentGoalAccounting(); refreshGoalUiBestEffort(ctx, paused); return true; } async function resumeGoalWithReleasedSession(ctx) { if (stopHoldLive(ctx)) return; const goal = await readGoal(goalStoreRef(ctx)); if (goal?.status !== "paused" || !pausedByStop(ctx, goal.id)) return; markStopResumed(pi, goal.id); const resumed = await updateGoal(goalStoreRef(ctx), { status: "active" }, "user"); beginAgentGoalAccounting(resumed); refreshGoalUiBestEffort(ctx, resumed); } function beginAgentGoalAccounting(goal) { // Goal usage accrues only while its accounting window is open. A stale stop // excludes extension-driven turns, like other inactive goals, until input or resume. if (goal.status !== "active" || goal.continuationStoppedAt !== undefined) return; if (agentGoalAccounting?.goalId === goal.id) return; turnUsage.discardPending(); agentGoalAccounting = { goalId: goal.id, measuredFromMilliseconds: Date.now() }; } function markGoalBlockedThisTurn(goal) { if (agentTurnInProgress) blockedThisTurnGoalId = goal.id; } function markGoalCompletedThisTurn(goal) { if (!agentTurnInProgress) return; completedThisTurnGoalId = goal.id; agentGoalAccounting = { goalId: goal.id, measuredFromMilliseconds: Date.now() }; } function stopAgentGoalAccounting(goalId) { if (agentGoalAccounting?.goalId === goalId) { agentGoalAccounting = null; } if (blockedThisTurnGoalId === goalId) { blockedThisTurnGoalId = null; } if (completedThisTurnGoalId === goalId) { completedThisTurnGoalId = null; } } function clearAgentGoalAccounting() { agentGoalAccounting = null; blockedThisTurnGoalId = null; completedThisTurnGoalId = null; } function syncContinuationGoal(ctx, goal) { if (goal?.status === "active" && goal.continuationStoppedAt === undefined) beginAgentGoalAccounting(goal); else clearAgentGoalAccounting(); refreshGoalUiBestEffort(ctx, goal); } function refreshGoalUi(ctx, goal) { monitorContinuation.syncGoal(goal); goalLifecycleChanged(ctx.sessionManager, goal); const accounting = agentGoalAccounting; if (ctx.hasUI && goal?.status === "active" && accounting?.goalId === goal.id) { goalTicker.sync(ctx, goal, accounting.measuredFromMilliseconds); return; } goalTicker.stop(); updateGoalUi(ctx, goal); } function refreshGoalUiBestEffort(ctx, goal) { try { refreshGoalUi(ctx, goal); } catch (error) { if (isStaleExtensionContextError(error)) { return; } throw error; } } async function accountCurrentAgentTurn(ctx, mode, agentRunMessages) { const accounting = agentGoalAccounting; const ref = goalStoreRef(ctx); if (accounting === null) return readGoal(ref); const usage = agentRunMessages === undefined ? turnUsage.takePending() : turnUsage.takeRemaining(agentRunMessages); const now = Date.now(); const elapsedSeconds = Math.max(0, Math.round((now - accounting.measuredFromMilliseconds) / 1000)); const goal = await accountGoalUsage(ref, usage, elapsedSeconds, mode, accounting.goalId); if (goal?.id === accounting.goalId) { agentGoalAccounting = { goalId: accounting.goalId, measuredFromMilliseconds: now }; } else { clearAgentGoalAccounting(); } return goal; } } function goalStoreRef(ctx) { return buildGoalStoreRef(ctx.sessionManager, ctx.cwd); } //# sourceMappingURL=index.js.map