UNPKG

@code-yeongyu/senpi

Version:

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

857 lines • 40.3 kB
import { deadlineStopPendingSinceLastTurn } from "../../../turn-deadline.js"; import { subscribeProviderAccountEvents } from "../anthropic-subscription/account-events.js"; import { isHumanInputMonitorNotification } from "../monitor-state-event.js"; import { createGoalCacheWarmScheduleData, estimateCacheWarmMetrics, GOAL_CACHE_WARMUP_ENTRY_TYPE, GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS, resolveGoalBackstopMaxSecondsForCache, resolveGoalMonitorContinuationDelayMs, resolveGoalPromptCacheLifetime, } from "./cache-warm.js"; import { subscribeGoalChannelState } from "./channel-state-subscriptions.js"; import { publishGoalContinuationEvent } from "./rpc-wait-surface.js"; export { GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS, GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS, } from "./cache-warm.js"; import { continuationTurnUsedTools, evaluateGoalContinuation, GOAL_TOOL_EFFECT_WINDOW, GOAL_USER_GRACE_DELAY_MS, hasGoalContinuationProgress, hasGoalTodoProgress, hashAssistantText, isMalformedToolUseTurn, normalizeAssistantText, toolEffectFingerprint, } from "./continuation.js"; import { lastAssistantMessage } from "./last-assistant-message.js"; import { admitAndQueueGoalContinuation, buildCurrentGoalContinuationSignature, isLastTurnStuckOnContextOverflow, lastAssistantText, } from "./lifecycle-helpers.js"; import { findParkedGoalWait } from "./parked-wait.js"; import { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from "./prompt.js"; import { exhaustedLadderResumeDelayMs, GOAL_LIMIT_WAIT_WAKE_LIMIT, isLimitRefusal, limitWaitFloorMs, PROVIDER_RETRY_BASE_MS, providerRetryAt, providerRetryDelayMs, } from "./provider-retry.js"; import { isStaleExtensionContextError } from "./stale-context.js"; import { resetContinuationStreak } from "./store.js"; import { goalStoreRef } from "./store-ref.js"; import { collectAssistantUsage } from "./turn-usage.js"; /** Wake source the ask-user extension publishes while an async question is pending. */ const ASK_USER_WAKE_SOURCE = "ask-user"; /** `askUser.timeoutMinutes` default (settings-manager.ts), used when the session exposes no ask-user settings. */ const ASK_USER_DEFAULT_TIMEOUT_MINUTES = 30; export const GOAL_CONTINUATION_SCHEDULED_EVENT = "goal_continuation_scheduled"; export const GOAL_CONTINUATION_RESUMED_EVENT = "goal_continuation_resumed"; export const GOAL_CONTINUATION_TIMER_STATE_EVENT = "goal_continuation_timer_state"; export const GOAL_MONITOR_STALL_EVENT = "goal_monitor_continuation_stall"; /** A limit outlasted GOAL_LIMIT_WAIT_WAKE_LIMIT re-checks: the goal waits for a sign-in, a block reset or input. */ const GOAL_LIMIT_WAIT_PARKED_EVENT = "goal_limit_wait_parked"; /** The one notice a provider-limit park shows: when the goal resumes, in local time and as the exact instant. */ function providerPauseNotice(retryAt) { const local = new Date(retryAt).toLocaleString("en-US", { year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short", }); return `Goal paused until ${local} (${new Date(retryAt).toISOString()}): the provider cannot serve before then. It resumes once at that time.`; } export class MonitorAwareGoalContinuation { #pi; #isContinuationPending; #markContinuationPending; #waitTicker; #wakeSources = new Map(); #hasStarted = false; #ctx; #goal = null; #timer; #scheduledContinuationKind; #armedDrainFire = false; #channelStateUnsubscribers = []; #lastAgentEndMessages = []; #consecutiveLengthRecoveries = new Map(); #recentNormalizedOutputHashes = []; #toollessContinuationStreak = 0; #recentToolEffects = []; #toollessStreakGoalId = null; #endedTurnWasUserInitiated = false; #lastTurnUsage; #scheduledAtMs; #scheduledDueAtMs; #scheduledCache; #scheduledDelayMs; #askUserDeadlineAtMs; #cacheWarmIteration = 0; #scheduledCacheWarmIteration; #heldTimer; #directInputHolds = new Set(); #pendingSystemRecovery; #pendingProviderRecovery; #providerRetryAttempts = 0; #providerRetryDelayMs; /** The armed provider retry waits out a usage or rate limit, so its wake spends no continuation budget (senpi#4085). */ #limitWait = false; #limitWakes = 0; #limitParked = false; constructor(pi, isContinuationPending = () => false, markContinuationPending = () => { }, waitTicker) { this.#pi = pi; this.#isContinuationPending = isContinuationPending; this.#markContinuationPending = markContinuationPending; this.#waitTicker = waitTicker; this.#subscribeToChannelState(); // A login or an explicit block reset can end the wait early: re-check the provider now (senpi#4085). this.#channelStateUnsubscribers.push(subscribeProviderAccountEvents((event) => { if (event.type === "accounts_changed" && event.remedy !== undefined) this.#wakeLimitWait(); })); } #wakeLimitWait() { const goal = this.#goal; const waiting = this.#scheduledContinuationKind === "providerRetry" || this.#limitParked; if (!this.#limitWait || !waiting || goal === null) return; this.#limitWakes = 0; this.#limitParked = false; this.#cancelTimer(); this.#providerRetryDelayMs = 0; this.#schedule(goal, "providerRetry"); } /** * Arms the next re-check of a limit wait, never sooner than the provider backoff. A limit that outlasts * GOAL_LIMIT_WAIT_WAKE_LIMIT re-checks parks the goal, still active, until a sign-in, a block reset or input. */ #armLimitWait(goal, delayMs) { this.#limitWait = true; this.#limitWakes += 1; if (this.#limitWakes > GOAL_LIMIT_WAIT_WAKE_LIMIT) { this.#limitParked = true; this.#publish(GOAL_LIMIT_WAIT_PARKED_EVENT, { goalId: goal.id, wakes: GOAL_LIMIT_WAIT_WAKE_LIMIT }); if (this.#ctxHasUI()) { this.#ctx?.ui.notify(`Goal paused: the provider kept refusing for a usage limit through ${GOAL_LIMIT_WAIT_WAKE_LIMIT} re-checks. It resumes after a sign-in, an account block reset, or your next message.`, "warning"); } return false; } this.#providerRetryDelayMs = Math.max(delayMs, limitWaitFloorMs(this.#providerRetryAttempts)); this.#schedule(goal, "providerRetry"); return true; } start(ctx) { this.#cancelTimer(); this.#ctx = ctx; if (this.#hasStarted) this.#clearWakeSources(); else this.#hasStarted = true; this.#goal = null; this.#lastAgentEndMessages = []; this.#directInputHolds.clear(); this.#resetContinuationState(); } async afterAgentEnd(options) { if (options.goal?.id !== this.#goal?.id) this.#resetContinuationState(); this.#providerRetryAttempts = 0; this.#limitWait = false; this.#limitWakes = 0; this.#limitParked = false; this.#ctx = options.ctx; this.#goal = options.goal; this.#lastAgentEndMessages = options.messages; this.#lastTurnUsage = collectAssistantUsage([...options.messages]); this.#resetLengthRecoveryAfterCleanStop(options.goal, options.messages); const turnUsedTools = continuationTurnUsedTools(options.messages); // A person's words delivered by a human-input monitor are new input, exactly like a typed message. const humanInput = options.messages.some(isHumanInputMonitorNotification); this.#recordAssistantOutput(options.messages, turnUsedTools || humanInput); if (options.goal?.status !== "active") { this.#cancelTimer(); this.#resetContinuationState(); return options.goal; } // A turn the provider refused (a blocked pool, an outage) was not the model choosing to skip tools: // it neither counts toward nor clears the stall streak (senpi#3975). if (lastAssistantMessage(options.messages)?.stopReason !== "error") { this.#recordToollessContinuationTurn(options.goal, turnUsedTools || humanInput); } const immediateInput = this.#buildVerdictInput(options.ctx, options.goal, "immediate", options.messages); const madeProgress = this.#recordToolEffect(options.messages) || humanInput || hasGoalTodoProgress(immediateInput); const goal = !this.#endedTurnWasUserInitiated && (madeProgress || hasGoalContinuationProgress(immediateInput)) ? ((await resetContinuationStreak(goalStoreRef(options.ctx.sessionManager, options.ctx.cwd), { progress: madeProgress, unattended: humanInput, })) ?? options.goal) : options.goal; this.#goal = goal; const immediateVerdict = evaluateGoalContinuation({ goal, ...this.#buildVerdictInput(options.ctx, goal, "immediate", options.messages), }); if (this.#endedTurnWasUserInitiated) { this.#endedTurnWasUserInitiated = false; this.#cancelTimer(); if (immediateVerdict.kind === "continue") { this.#schedule(goal, "userGrace"); return goal; } switch (immediateVerdict.reason) { case "not-eligible": case "single-flight": return goal; case "stale": case "context-overflow": case "cap": case "repetition": case "length-exhausted": case "no-progress": { const admission = await this.#admitAndQueue(options.ctx, goal, "immediate", options.messages); return admission.goal; } } } if (immediateVerdict.kind === "deny" && immediateVerdict.reason === "not-eligible") return goal; if (this.#activeWakeSourceCount() === 0) { this.#cancelTimer(); const admission = await this.#admitAndQueue(options.ctx, goal, "immediate", options.messages); return admission.goal; } this.#schedule(goal, "monitor"); return goal; } async afterSystemAbort(options) { this.noteContinuationStarted(); if (options.goal?.id !== this.#goal?.id) this.#resetContinuationState(); this.#pendingSystemRecovery = undefined; this.#ctx = options.ctx; this.#goal = options.goal; this.#lastAgentEndMessages = options.messages; this.#lastTurnUsage = collectAssistantUsage([...options.messages]); if (options.goal?.status !== "active") { this.#resetContinuationState(); return options.goal; } if (options.willRetry) return options.goal; // A deadline stop is never auto-continued; the hold releases on admitted user input. if (deadlineStopPendingSinceLastTurn(options.ctx.sessionManager.getBranch()) !== undefined) { return options.goal; } if (this.#activeWakeSourceCount() > 0) this.#schedule(options.goal, "monitor"); else if (lastAssistantMessage(options.messages)?.stopReason === "error") { this.#pendingSystemRecovery = options; } return options.goal; } async afterProviderFailure(options) { this.noteContinuationStarted(); if (options.goal?.id !== this.#goal?.id) this.#resetContinuationState(); this.#pendingProviderRecovery = undefined; this.#ctx = options.ctx; this.#goal = options.goal; this.#lastAgentEndMessages = options.messages; this.#lastTurnUsage = collectAssistantUsage([...options.messages]); if (options.goal?.status !== "active") { this.#resetContinuationState(); return options.goal; } if (!options.willRetry) this.#pendingProviderRecovery = options; return options.goal; } async afterAgentSettled(fallbackExhausted) { const pendingSystem = this.#pendingSystemRecovery; const pendingProvider = this.#pendingProviderRecovery; this.#pendingSystemRecovery = undefined; this.#pendingProviderRecovery = undefined; if (fallbackExhausted !== undefined) return this.#parkUntilLadderReset(fallbackExhausted.resumeAt); if (pendingSystem !== undefined && pendingSystem.goal !== null && pendingSystem.event.abortSource !== "user") { return (await this.#admitAndQueue(pendingSystem.ctx, pendingSystem.goal, "systemRecovery", pendingSystem.messages)).goal; } if (pendingProvider === undefined || pendingProvider.goal === null || pendingProvider.event.abortSource === "user") { return undefined; } this.#providerRetryAttempts += 1; this.#limitWait = isLimitRefusal(pendingProvider.messages); const now = Date.now(); const retryAt = providerRetryAt(pendingProvider.messages, now); const delayMs = providerRetryDelayMs(this.#providerRetryAttempts, retryAt, now); if (this.#limitWait) { this.#cancelTimer(); const armed = this.#armLimitWait(pendingProvider.goal, delayMs); if (armed && retryAt !== undefined && this.#ctxHasUI(pendingProvider.ctx)) { pendingProvider.ctx.ui.notify(providerPauseNotice(retryAt), "info"); } return pendingProvider.goal; } if (delayMs > 0) { this.#cancelTimer(); this.#providerRetryDelayMs = delayMs; this.#schedule(pendingProvider.goal, "providerRetry"); if (retryAt !== undefined && this.#ctxHasUI(pendingProvider.ctx)) { pendingProvider.ctx.ui.notify(providerPauseNotice(retryAt), "info"); } return pendingProvider.goal; } return (await this.#admitAndQueue(pendingProvider.ctx, pendingProvider.goal, "providerRecovery", pendingProvider.messages)).goal; } /** * senpi#3709: every fallback rung failed, so a continuation now would hit the same limits. Park on * the soonest reset the run named; with no known reset, re-check on the provider backoff (senpi#4085). */ #parkUntilLadderReset(resumeAt) { const goal = this.#goal; if (goal?.status !== "active") return undefined; this.#cancelTimer(); this.#providerRetryAttempts += 1; // No failure named a reset: re-check on the provider backoff (15 s doubling to 30 min) rather than wait for input. this.#armLimitWait(goal, resumeAt === undefined ? 0 : exhaustedLadderResumeDelayMs(resumeAt, Date.now())); return goal; } syncGoal(goal) { if (goal?.id !== this.#goal?.id) this.#resetContinuationState(); this.#goal = goal; if (goal?.status !== "active") { this.#cancelTimer(); this.#resetContinuationState(); } } /** The continuation timer armed right now, if any (monitor backstop, user grace, provider retry). */ scheduledContinuation() { return this.#scheduledContinuationKind; } /** A system or provider recovery staged for `agent_settled`. */ hasStagedRecovery() { return this.#pendingSystemRecovery !== undefined || this.#pendingProviderRecovery !== undefined; } /** Live resumption channels known to this generation (e.g. terminal snapshots replayed on reload). */ hasActiveWakeSources() { return this.#activeWakeSourceCount() > 0; } /** * Re-arms the monitor-delayed backstop a reload tore down with the retired * generation, so a later wake-source drain can still deliver the goal * continuation. No-op unless the goal is active, a wake source is live, and * no continuation is already scheduled. A wait the branch still records as * parked is restored as-is (iteration, cache snapshot, original due time) so * a reload never appends a second card or pushes the wake past the cache TTL. */ rearmMonitorBackstop(goal) { if (goal.status !== "active" || this.#activeWakeSourceCount() === 0) return; this.#goal = goal; this.#schedule(goal, "monitor", false, this.#parkedWait(goal.id)); } /** A retired ctx throws from its getters (see `#ctxHasUI`); it has no branch to restore from. */ #parkedWait(goalId) { try { return findParkedGoalWait(this.#ctx?.sessionManager?.getBranch() ?? [], goalId); } catch (error) { if (isStaleExtensionContextError(error)) return undefined; throw error; } } /** Temporarily prevents a scheduled continuation from racing unresolved direct-input admission. */ holdDirectInput(inputId) { if (this.#directInputHolds.has(inputId)) return; this.#directInputHolds.add(inputId); if (this.#directInputHolds.size !== 1 || this.#timer === undefined || this.#scheduledContinuationKind === undefined) { return; } const heldAtMs = Date.now(); this.#heldTimer = { kind: this.#scheduledContinuationKind, remainingMs: Math.max(0, (this.#scheduledDueAtMs ?? heldAtMs) - heldAtMs), heldAtMs, totalMs: this.#scheduledDelayMs ?? GOAL_USER_GRACE_DELAY_MS, drainFire: false, }; clearTimeout(this.#timer); this.#timer = undefined; this.#scheduledDueAtMs = undefined; this.#waitTicker?.stop(); } /** Resolves one admission hold without allowing overlapping inputs to consume each other. */ resolveDirectInput(inputId, accepted) { if (!this.#directInputHolds.delete(inputId)) return; if (accepted) { this.#heldTimer = undefined; this.noteUserPrompt(); return; } if (this.#directInputHolds.size > 0 || this.#heldTimer === undefined) return; const held = this.#heldTimer; this.#heldTimer = undefined; const elapsedWhileHeldMs = Math.max(0, Date.now() - held.heldAtMs); this.#armTimer(held.kind, Math.max(0, held.remainingMs - elapsedWhileHeldMs), held.totalMs, held.drainFire); } /** An accepted real user prompt starts a grace-governed user turn. */ noteUserPrompt() { this.#cancelTimer(); this.#pendingProviderRecovery = undefined; this.#endedTurnWasUserInitiated = true; this.#resetContinuationState(); } /** A hidden continuation or system recovery has started, so the next end is not user-initiated. */ noteContinuationStarted() { this.#endedTurnWasUserInitiated = false; } dispose() { this.#cancelTimer(); for (const unsubscribe of this.#channelStateUnsubscribers) unsubscribe(); this.#channelStateUnsubscribers = []; this.#ctx = undefined; this.#goal = null; this.#clearWakeSources(); this.#lastAgentEndMessages = []; this.#directInputHolds.clear(); this.#resetContinuationState(); } #schedule(goal, kind, repark = false, parked) { if (this.#scheduledContinuationKind !== undefined) return; // A live wake source arms the periodic backstop only: the normal resumption // is the drain fire in #setWakeSourceCount, and the backstop re-checks the // goal every `promptCache.goalBackstopMaxSeconds` in case the source never // delivers. A pending ask-user question is the exception: re-prompting the // model every backstop while the user is deciding is noise it cannot act // on, so the wait is parked on the question's own deadline instead. // A best-effort prompt cache has no TTL to land inside, so an unconfigured // backstop there is the long liveness re-check (senpi#831). const askUserWaitMs = kind === "monitor" ? this.#askUserWaitMs() : undefined; const delayMs = kind === "monitor" ? (parked?.delayMs ?? askUserWaitMs ?? resolveGoalMonitorContinuationDelayMs(resolveGoalBackstopMaxSecondsForCache(this.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.(), resolveGoalPromptCacheLifetime(this.#ctx?.model, process.env)))) : kind === "providerRetry" ? (this.#providerRetryDelayMs ?? PROVIDER_RETRY_BASE_MS) : GOAL_USER_GRACE_DELAY_MS; this.#scheduledDelayMs = delayMs; let remainingMs = delayMs; if (kind === "monitor") { if (parked !== undefined) this.#cacheWarmIteration = parked.iteration; else if (!repark) this.#cacheWarmIteration += 1; this.#scheduledCacheWarmIteration = this.#cacheWarmIteration; const iteration = this.#scheduledCacheWarmIteration; const cache = parked !== undefined ? parked.cache : estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage); const wakeSources = this.#wakeSourceSnapshot(); this.#scheduledCache = cache; this.#scheduledAtMs = parked !== undefined ? parked.dueAtMs - delayMs : Date.now(); if (parked !== undefined) remainingMs = Math.max(0, parked.dueAtMs - Date.now()); const scheduleData = createGoalCacheWarmScheduleData({ goalId: goal.id, delayMs, scheduledAtMs: this.#scheduledAtMs, iteration, activeMonitorCount: this.#activeWakeSourceCount(), wakeSources, ...(cache !== undefined ? { cache } : {}), }); this.#publish(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData); // Progress adjusts this wait; it is not another cache-warm iteration // or transcript entry for every keystroke in the answer composer. if (!repark && parked === undefined) this.#appendWarmupEntry({ phase: "scheduled", ...scheduleData, }); } else { this.#scheduledAtMs = undefined; this.#scheduledCache = undefined; this.#scheduledCacheWarmIteration = undefined; } this.#scheduledContinuationKind = kind; this.#publish(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: true, kind, dueAtMs: Date.now() + remainingMs }); if (this.#directInputHolds.size > 0) { this.#heldTimer = { kind, remainingMs, heldAtMs: Date.now(), totalMs: delayMs, drainFire: false }; return; } this.#armTimer(kind, remainingMs, delayMs); } /** * `hasUI` is an `assertActive()`-guarded getter, so a ctx retired by session * replacement or reload THROWS instead of reporting false. Optional chaining * only guards an undefined ctx (what `dispose()` leaves behind), never a stale * object left by a replacement that never disposed this monitor. Callers reach * this from timer and event callbacks where a throw is fatal, so a retired ctx * reports "no UI" and any other failure keeps its current behavior. */ #ctxHasUI(ctx = this.#ctx) { try { return ctx?.hasUI === true; } catch (error) { if (isStaleExtensionContextError(error)) return false; throw error; } } #armTimer(kind, delayMs, totalMs, drainFire = false) { this.#scheduledDueAtMs = Date.now() + delayMs; this.#armedDrainFire = drainFire; const ctx = this.#ctx; if (ctx !== undefined && this.#ctxHasUI(ctx)) { this.#waitTicker?.sync(ctx, { kind, remainingMs: delayMs, totalMs, channelCounts: this.#wakeSourceSnapshot(), }); } this.#timer = setTimeout(() => { void this.#continueIfEligible(kind, drainFire).catch((error) => { // Runs from a bare setTimeout: anything thrown here escapes as an // uncaughtException and kills the session. A retired ctx cannot be // notified, and its own staleness is the expected cause of this // rejection after a session replacement, so drop it quietly. if (isStaleExtensionContextError(error) || !this.#ctxHasUI()) return; const message = error instanceof Error ? error.message : String(error); this.#ctx?.ui.notify(`Goal continuation delivery failed: ${message}`, "error"); }); }, delayMs); } async #continueIfEligible(kind, drainFire = false) { this.#timer = undefined; this.#scheduledDueAtMs = undefined; this.#scheduledContinuationKind = undefined; this.#publish(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind }); this.#waitTicker?.stop(); const delayMs = this.#scheduledDelayMs ?? (kind === "monitor" ? GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS : kind === "providerRetry" ? PROVIDER_RETRY_BASE_MS : GOAL_USER_GRACE_DELAY_MS); const waitedMs = this.#scheduledAtMs === undefined ? delayMs : Math.max(0, Date.now() - this.#scheduledAtMs); const dueAtMs = this.#scheduledAtMs === undefined ? undefined : this.#scheduledAtMs + delayMs; const wakeCause = drainFire ? "sources-drained" : "timer"; const cache = this.#scheduledCache; const iteration = this.#scheduledCacheWarmIteration; this.#scheduledAtMs = undefined; this.#scheduledCache = undefined; this.#scheduledDelayMs = undefined; this.#scheduledCacheWarmIteration = undefined; const ctx = this.#ctx; const goal = this.#goal; if (ctx === undefined || goal?.status !== "active" || !ctx.isIdle() || ctx.hasPendingMessages()) return; if (deadlineStopPendingSinceLastTurn(ctx.sessionManager.getBranch()) !== undefined) return; if (kind === "monitor" && this.#activeWakeSourceCount() === 0 && !drainFire) return; const admission = await this.#admitAndQueue(ctx, goal, kind === "monitor" ? "monitorDelayed" : kind === "providerRetry" ? "providerRecovery" : "userGrace", this.#lastAgentEndMessages); if (kind !== "monitor" || !admission.admitted || iteration === undefined) return; const wakeSources = this.#wakeSourceSnapshot(); this.#publish(GOAL_CONTINUATION_RESUMED_EVENT, { goalId: goal.id, delayMs, dueAtMs, waitedMs, wakeCause, iteration, activeMonitorCount: this.#activeWakeSourceCount(), wakeSources, cache, }); this.#appendWarmupEntry({ phase: "resumed", goalId: goal.id, delayMs, dueAtMs, waitedMs, wakeCause, iteration, activeMonitorCount: this.#activeWakeSourceCount(), wakeSources, ...(cache !== undefined ? { cache } : {}), }); if (drainFire || admission.goal.status !== "active") this.#resetCacheWarmIteration(); } async #admitAndQueue(ctx, goal, path, messages) { const input = { ...this.#buildVerdictInput(ctx, goal, path, messages), ...(path === "providerRecovery" && this.#limitWait ? { limitWait: true } : {}), }; const verdict = evaluateGoalContinuation({ goal, ...input }); const admittedGoal = await admitAndQueueGoalContinuation(this.#pi, ctx, goal, { input, content: (continuationVerdict) => this.#buildContinuationContent(ctx, goal, continuationVerdict), markContinuationPending: this.#markContinuationPending, }); if (admittedGoal === null) { this.#goal = null; this.#cancelTimer(); this.#resetToollessContinuationStreak(); return { goal, admitted: false }; } if (verdict.kind === "continue" && input.lastStopReason === "length") { this.#consecutiveLengthRecoveries.set(goal.id, input.consecutiveLengthRecoveries + 1); } this.#goal = admittedGoal; if (admittedGoal.status !== "active") { this.#cancelTimer(); this.#resetToollessContinuationStreak(); } return { goal: admittedGoal, admitted: verdict.kind === "continue" }; } #appendWarmupEntry(data) { this.#pi.appendEntry?.(GOAL_CACHE_WARMUP_ENTRY_TYPE, data); } #buildVerdictInput(ctx, goal, path, messages) { const lastAssistant = lastAssistantMessage(messages); return { isIdle: ctx.isIdle(), hasPendingMessages: ctx.hasPendingMessages(), path, lastStopReason: lastAssistant?.stopReason, lastTurnWasMalformedToolUse: lastAssistant?.role === "assistant" && isMalformedToolUseTurn(lastAssistant), consecutiveContinuations: goal.consecutiveContinuations ?? 0, lastContinuationSignature: goal.lastContinuationSignature, currentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)), consecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0, recentNormalizedOutputHashes: this.#recentNormalizedOutputHashes, toollessContinuationStreak: this.#toollessContinuationStreak, continuationPending: this.#isContinuationPending(), lastTurnStuckOnContextOverflow: isLastTurnStuckOnContextOverflow(ctx, lastAssistant), }; } #buildContinuationContent(ctx, goal, verdict) { let content = verdict.prompt === "minimal" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal, { modelId: ctx.model?.id }); if (!verdict.stallNotice) return content; const liveSources = this.liveWakeSources(); this.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, { goalId: goal.id, consecutiveContinuations: this.#toollessContinuationStreak, toolless: true, }); if (this.#ctxHasUI(ctx)) { const context = liveSources.length > 0 ? `while ${liveSources.join(", ")} channels stayed active` : "without tool use"; ctx.ui.notify(`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`, "info"); } content = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\n\n${content}`; return content; } /** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */ #recordAssistantOutput(messages, turnUsedTools) { if (turnUsedTools) { this.#recentNormalizedOutputHashes = []; return; } const text = lastAssistantText(messages); if (normalizeAssistantText(text).length === 0) return; this.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3); } /** * A tool turn is progress only when its calls and outcomes differ from every recent tool turn. With no history * (first turn, or after a reload or input reset) there is nothing to prove change against, so it only seeds. */ #recordToolEffect(messages) { const fingerprint = toolEffectFingerprint(messages); if (fingerprint === undefined) return false; const repeated = this.#recentToolEffects.length === 0 || this.#recentToolEffects.includes(fingerprint); this.#recentToolEffects = [...this.#recentToolEffects, fingerprint].slice(-GOAL_TOOL_EFFECT_WINDOW); return !repeated; } #recordToollessContinuationTurn(goal, turnUsedTools) { if (goal.id !== this.#toollessStreakGoalId) { this.#toollessStreakGoalId = goal.id; this.#toollessContinuationStreak = 0; } if (this.#endedTurnWasUserInitiated) return; if (turnUsedTools) { this.#toollessContinuationStreak = 0; return; } this.#toollessContinuationStreak += 1; } #resetLengthRecoveryAfterCleanStop(goal, messages) { if (goal === null || lastAssistantMessage(messages)?.stopReason !== "stop") return; this.#consecutiveLengthRecoveries.delete(goal.id); } #subscribeToChannelState() { const events = this.#pi.events; if (events === undefined) return; this.#channelStateUnsubscribers.push(...subscribeGoalChannelState(events, { onWakeSource: (source, activeCount, event) => this.#setWakeSourceCount(source, activeCount, event?.items), onContinuationHold: (source, active) => { const inputId = `external:${source}`; if (active) this.holdDirectInput(inputId); else this.resolveDirectInput(inputId, false); }, })); } /** * Remaining wait on a pending async ask-user question, or `undefined` when no * question is live. A deadline already in the past means the question outlived * its first idle window - the extension restarts that timer whenever the user * interacts - so the goal parks for one more window instead of falling back to * the periodic backstop. Clamped through the shared monitor bounds so a * misconfigured `askUser.timeoutMinutes` cannot park the goal past the * monitor's own ceiling. */ #askUserWaitMs() { if ((this.#wakeSources.get(ASK_USER_WAKE_SOURCE) ?? 0) <= 0) return undefined; const remainingMs = (this.#askUserDeadlineAtMs ?? 0) - Date.now(); const waitMs = remainingMs > 0 ? remainingMs : this.#askUserIdleTimeoutMs(); return resolveGoalMonitorContinuationDelayMs(waitMs / 1000); } #askUserIdleTimeoutMs() { const minutes = this.#ctx?.getAskUserSettings?.().timeoutMinutes; const resolved = typeof minutes === "number" && Number.isFinite(minutes) && minutes > 0 ? minutes : ASK_USER_DEFAULT_TIMEOUT_MINUTES; return resolved * 60_000; } /** * Prefer the earliest authoritative request deadline. Legacy count-only * emitters retain the settings-window heuristic; zero clears the deadline. */ #noteAskUserWait(activeCount, items) { if (activeCount <= 0) { this.#askUserDeadlineAtMs = undefined; return; } const deadlines = items?.flatMap((item) => (item.deadlineAtMs === undefined ? [] : [item.deadlineAtMs])) ?? []; if (deadlines.length > 0) { this.#askUserDeadlineAtMs = Math.min(...deadlines); return; } const previousCount = this.#wakeSources.get(ASK_USER_WAKE_SOURCE) ?? 0; if (activeCount > previousCount || this.#askUserDeadlineAtMs === undefined) { this.#askUserDeadlineAtMs = Date.now() + this.#askUserIdleTimeoutMs(); } } #clearWakeSources() { this.#wakeSources.clear(); this.#askUserDeadlineAtMs = undefined; } #setWakeSourceCount(source, activeCount, items) { const previousTotal = this.#activeWakeSourceCount(); const previousDeadline = this.#askUserDeadlineAtMs; if (source === ASK_USER_WAKE_SOURCE) this.#noteAskUserWait(activeCount, items); this.#wakeSources.set(source, activeCount); const nextTotal = this.#activeWakeSourceCount(); if (previousTotal > 0 && nextTotal === 0) { if (this.#scheduledContinuationKind === "monitor") this.#armDrainFire(); else this.#resetCacheWarmIteration(); this.#resetToollessContinuationStreak(); return; } if (this.#scheduledContinuationKind === "monitor") { if (previousDeadline !== this.#askUserDeadlineAtMs && this.#goal !== null) { this.#cancelTimer(); this.#schedule(this.#goal, "monitor", true); return; } this.#waitTicker?.setChannelCounts(this.#wakeSourceSnapshot()); } } #armDrainFire() { if (this.#directInputHolds.size > 0) { this.#heldTimer = { kind: "monitor", remainingMs: 1_000, heldAtMs: Date.now(), totalMs: 1_000, drainFire: true, }; return; } if (this.#timer !== undefined) clearTimeout(this.#timer); this.#timer = undefined; this.#scheduledDueAtMs = undefined; this.#waitTicker?.stop(); this.#armTimer("monitor", 1_000, 1_000, true); } #activeWakeSourceCount() { let total = 0; for (const count of this.#wakeSources.values()) total += count; return total; } #wakeSourceSnapshot() { return Object.fromEntries([...this.#wakeSources.entries()].sort(([left], [right]) => left.localeCompare(right))); } liveWakeSources() { return [...this.#wakeSources.entries()] .filter(([, count]) => count > 0) .map(([source]) => source) .sort(); } #resetContinuationState() { this.#pendingSystemRecovery = undefined; this.#pendingProviderRecovery = undefined; this.#providerRetryAttempts = 0; this.#limitWait = false; this.#limitWakes = 0; this.#limitParked = false; this.#consecutiveLengthRecoveries.clear(); this.#recentNormalizedOutputHashes = []; this.#recentToolEffects = []; this.#resetToollessContinuationStreak(); this.#resetCacheWarmIteration(); } #resetCacheWarmIteration() { this.#cacheWarmIteration = 0; this.#scheduledCacheWarmIteration = undefined; } #resetToollessContinuationStreak() { this.#toollessContinuationStreak = 0; this.#toollessStreakGoalId = null; } /** * Runs the armed continuation now, through the same eligibility checks as its timer (the * desktop's "Check now"). A held timer (the user is typing) stays held. */ async fireNow() { if (this.#heldTimer !== undefined) return { fired: false, reason: "held" }; const kind = this.#scheduledContinuationKind; if (this.#timer === undefined || kind === undefined) return { fired: false, reason: "not_armed" }; clearTimeout(this.#timer); await this.#continueIfEligible(kind, this.#armedDrainFire); return { fired: true, kind }; } #publish(name, data) { publishGoalContinuationEvent(this.#pi, name, data); } #cancelTimer() { const kind = this.#scheduledContinuationKind; this.#scheduledAtMs = undefined; this.#scheduledDueAtMs = undefined; this.#scheduledCache = undefined; this.#scheduledDelayMs = undefined; this.#scheduledCacheWarmIteration = undefined; this.#heldTimer = undefined; if (this.#timer !== undefined) clearTimeout(this.#timer); this.#timer = undefined; this.#scheduledContinuationKind = undefined; if (kind !== undefined) this.#publish(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind }); this.#waitTicker?.stop(); } } //# sourceMappingURL=monitor-continuation.js.map