Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
recover a headless TUI agent from a retry ladder that never answers and from a permission dialog nobody can approve
[._.]/ Adam Eivye79909a7f73f
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 823e1fe992..755a52ea5a 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -574,6 +574,69 @@ export function createLocalRuntimeOomDetector({ maxBuffer = 512 } = {}) {};}+// Claude Code's in-TUI retry banner, painted while it re-sends a failed request:+// `API error · Retrying in 0s · attempt 1/10` (the prefix varies — `Request timed+// out`, `Overloaded` — so only the retry suffix is matched). The whitespace is+// `\s*` everywhere for the same reason TERMINAL_REQUEST_TIMEOUT_PATTERN's is: the+// ANSI-stripped screen can drop the spaces between cursor-positioned glyphs.+//+// A banner is NOT a failure by itself — Claude Code retries transient 429/5xx+// on its own and usually succeeds. It becomes one when the SAME request keeps+// failing: on 2026-09-04 a Stage 3 review whose ~100K-token prefill outlived the+// harness's stream-idle window was cancelled and re-sent every 6 minutes, so the+// session sat at this banner for the run's whole lifetime while every reaper+// saw a busy TUI (agent-e057cca7). `createRetryStallGate` in tuiHandshake.js+// owns the "keeps failing" judgement; this only reads the banner.+const TUI_RETRY_BANNER_PATTERN = /Retrying\s*in\s*(\d+)\s*s\s*[·•]\s*attempt\s*(\d+)\s*\/\s*(\d+)/gi;++/**+ * The LAST retry banner in `text`, or null. A repaint often carries two ticks+ * of the same countdown (`Retrying in 1s` then `0s`); the newest is the state.+ *+ * @returns {{ attempt: number, maxAttempts: number, retryInSeconds: number, endIndex: number }|null}+ */+export function detectTuiRetryBanner(text) {+ if (!text) return null;+ let last = null;+ for (const match of String(text).matchAll(TUI_RETRY_BANNER_PATTERN)) {+ last = {+ retryInSeconds: Number(match[1]),+ attempt: Number(match[2]),+ maxAttempts: Number(match[3]),+ endIndex: match.index + match[0].length,+ };+ }+ return last;+}++/**+ * The fail-over analysis for a request the TUI kept retrying without ever+ * getting a response — same shape as `detectImmediateFallbackSignal` returns, so+ * a consumer hands it straight to its fail-over path.+ *+ * A FIXED sentence, deliberately not the banner text: this message becomes the+ * run error, then a failure reason a CoS task body can quote, and a TUI echoes+ * a pasted prompt back through the very detector above — so it must not match+ * TUI_RETRY_BANNER_PATTERN (it carries no `Retrying in Ns · attempt`).+ */+export function describeTuiRetryStall({ attempts, spanMs }) {+ const minutes = Math.max(1, Math.round(spanMs / 60000));+ return {+ hasError: true,+ category: ERROR_CATEGORIES.TIMEOUT,+ message: `Provider kept failing the same request: the TUI retried it ${attempts} times over ${minutes} minutes without a response`,+ waitTime: null,+ requiresFallback: true,+ // Nothing a human has to fix before a retry can succeed elsewhere: the+ // request is too slow for THIS provider's harness window (a long prefill on+ // a local model server, a stalled upstream), and a fallback can serve it now.+ actionable: false,+ graceMs: 0,+ suggestedFix: 'Every retry re-sent the same request and none answered — typically a prompt whose prefill outlives the harness\'s stream-idle window on a local model server. Shrink the prompt, widen the idle window, or pin the stage to a faster provider.',+ origin: 'provider',+ };+}+export function extractWaitTime(text) {if (!text) return null;diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.jsindex c4f16c165c..dc3315bfa8 100644--- a/server/lib/aiToolkit/errorDetection.test.js+++ b/server/lib/aiToolkit/errorDetection.test.js@@ -11,6 +11,8 @@ import {detectLocalRuntimeOom,detectTerminalModelError,detectTerminalRequestTimeout,+ detectTuiRetryBanner,+ describeTuiRetryStall,extractWaitTime,isRunCanceledError,ERROR_CATEGORIES@@ -631,6 +633,48 @@ describe('Error Detection', () => {});});+ describe('detectTuiRetryBanner', () => {+ it('reads Claude Code\'s retry banner as it comes off the ANSI-stripped screen', () => {+ // Verbatim shape from agent-e057cca7's raw.txt (2026-09-04), after+ // stripping: the colour reset lands the box-drawing rule flush against it.+ expect(detectTuiRetryBanner('API error · Retrying in 0s · attempt 1/10─────'))+ .toMatchObject({ retryInSeconds: 0, attempt: 1, maxAttempts: 10 });+ // Cursor-positioned glyphs can lose their spaces on the way out.+ expect(detectTuiRetryBanner('Requesttimedout·Retryingin38s·attempt3/10'))+ .toMatchObject({ retryInSeconds: 38, attempt: 3, maxAttempts: 10 });+ });++ it('returns the newest banner when a repaint carries several ticks', () => {+ const screen = 'API error · Retrying in 1s · attempt 2/10\n…\nAPI error · Retrying in 0s · attempt 2/10\n';+ const banner = detectTuiRetryBanner(screen);+ expect(banner).toMatchObject({ retryInSeconds: 0, attempt: 2 });+ expect(screen.slice(banner.endIndex)).toBe('\n');+ });++ it('leaves prose about retries alone', () => {+ expect(detectTuiRetryBanner('retrying the fetch later; attempt 1 of 3 failed')).toBeNull();+ expect(detectTuiRetryBanner('')).toBeNull();+ expect(detectTuiRetryBanner(null)).toBeNull();+ });++ it('describes a stall in a sentence that cannot re-match the banner detector', () => {+ // The message becomes the run's error, then a task body a TUI echoes+ // back through this detector. Re-matching would fail over the agent+ // dispatched to investigate the stall.+ const analysis = describeTuiRetryStall({ attempts: 3, spanMs: 12 * 60 * 1000 });+ expect(analysis).toMatchObject({+ category: ERROR_CATEGORIES.TIMEOUT,+ requiresFallback: true,+ actionable: false,+ graceMs: 0,+ origin: 'provider',+ });+ expect(analysis.message).toContain('retried it 3 times over 12 minutes');+ expect(detectTuiRetryBanner(analysis.message)).toBeNull();+ expect(detectTuiRetryBanner(analysis.suggestedFix)).toBeNull();+ });+ });+describe('extractWaitTime', () => {it('should extract "X day X hour X minutes" format', () => {const result = extractWaitTime('try again in 1 day 2 hours 30 minutes');diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex c3b981306d..acefd1dd95 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -17,6 +17,7 @@// PROVIDER_VENDORS registry (#3618), consumed by every dispatch site that// used to duplicate its own vendor if-chain.import { inferTuiCommand, applyCommandDefaults, injectTuiModelAndEffort } from './providerVendors.js';+import { detectTuiRetryBanner, describeTuiRetryStall } from './aiToolkit/errorDetection.js';// ─── Paste handshake constants ────────────────────────────────────────────@@ -1074,3 +1075,191 @@ export function createOomNudgeGate() {},};}++// How long one request's retry sequence may span before the run is failed over.+//+// Long enough that Claude Code's own retry ladder for a transient cloud fault+// (ten attempts, seconds of backoff each) always finishes inside it — that+// ladder either recovers or ends in a terminal gutter line the idle reaper+// handles — and short enough that a request the provider can never answer is+// not left to burn a lane for the run's whole 3h ceiling. The gate also demands+// the banner ADVANCE at least twice (attempt N → N+2): a single sighting is+// often chrome that recovered a second later, and one advance can be a fault+// that cleared on the next try, but a third attempt of the same request ten+// minutes on is a request this provider is not going to answer.+export const RETRY_STALL_MS = 10 * 60 * 1000;+export const RETRY_STALL_MIN_ADVANCES = 2;+// Carry-over kept across chunks so a banner split by a PTY chunk boundary still+// matches. Spans the longest banner (`Retrying in 999s · attempt 10/10`) plus+// the cursor-positioning residue stripping leaves around it.+const RETRY_STALL_CARRY_CAP = 96;++/**+ * State machine for "the TUI keeps retrying the same request and it never+ * answers" — see TUI_RETRY_BANNER_PATTERN in aiToolkit/errorDetection.js for+ * the 2026-09-04 incident it exists for.+ *+ * Feed it every ANSI-stripped chunk after the prompt is in via+ * `observe(strippedText, nowMs)`; poll `takeStall(nowMs)` on whatever timer the+ * consumer already runs. It tracks one EPISODE at a time — the retry sequence+ * of a single request, recognised by its attempt counter climbing. A counter+ * that goes back down is the next request's ladder (Claude Code numbers each+ * request's retries from 1), and a banner more than RETRY_STALL_MS after the+ * last one is a new episode too, so a run that hit a blip, recovered, and did+ * an hour of work before the next blip is never judged across both.+ *+ * The verdict is decided AT A SIGHTING, never by the clock alone: a ladder+ * that climbed to attempt 10 in two minutes and then succeeded must not turn+ * into a stall ten quiet minutes later. Only a banner painted RETRY_STALL_MS+ * or more after the episode began — the provider failing this request yet+ * again — counts. It is handed back once (the episode is cleared with it), so+ * a consumer acting on it fails over exactly once.+ *+ * @returns {{ observe: (strippedText: string, nowMs: number) => void,+ * takeStall: (nowMs: number) => object|null }}+ */+export function createRetryStallGate() {+ let episode = null; // { firstSeenAt, lastSeenAt, firstAttempt, lastAttempt }+ let verdict = null;+ let tail = '';+ return {+ observe(strippedText, nowMs) {+ if (typeof strippedText !== 'string' || !strippedText) return;+ const window = tail + strippedText;+ const banner = detectTuiRetryBanner(window);+ // Consume through the match so the carry-over cannot re-sight the same+ // banner on the next chunk; without one, keep only the cap.+ tail = (banner ? window.slice(banner.endIndex) : window).slice(-RETRY_STALL_CARRY_CAP);+ if (!banner) return;+ const isNewEpisode = !episode+ || banner.attempt < episode.lastAttempt+ || nowMs - episode.lastSeenAt > RETRY_STALL_MS;+ if (isNewEpisode) {+ episode = { firstSeenAt: nowMs, lastSeenAt: nowMs, firstAttempt: banner.attempt, lastAttempt: banner.attempt };+ return;+ }+ episode.lastSeenAt = nowMs;+ episode.lastAttempt = banner.attempt;+ const spanMs = nowMs - episode.firstSeenAt;+ if (episode.lastAttempt - episode.firstAttempt < RETRY_STALL_MIN_ADVANCES || spanMs < RETRY_STALL_MS) return;+ verdict = describeTuiRetryStall({ attempts: episode.lastAttempt - episode.firstAttempt + 1, spanMs });+ episode = null;+ },+ // The stall analysis to fail over with, once, or null.+ takeStall() {+ const analysis = verdict;+ verdict = null;+ return analysis;+ },+ };+}++// Claude Code's tool-permission dialog, as the ANSI-stripped screen renders it+// (spaces between cursor-positioned glyphs can vanish, hence `\s*`):+//+// Read(/data.reference/providers.json)+// Do you want to proceed?+// ❯ 1. Yes+// 2. Yes, allow reading from /data.reference during this session+// 3. No+// Esc to cancel · Tab to amend+//+// It paints whenever a tool call falls outside what the launch posture+// pre-approved — under the hardened public-review recipe (`--permission-mode+// acceptEdits` + sandbox) that is any read or write outside the worktree, which+// a local model reaches for the moment it hallucinates an absolute path+// (agent-e057cca7, 2026-09-04: `Read(/data.reference/providers.json)` sat+// unanswered for 30+ minutes while the spinner kept the idle reaper happy).+// Nobody is at the keyboard, and the posture already decided the answer: an+// unattended run never widens its own scope, so the dialog is DECLINED. "No" is+// always the last numbered option, but its number varies with the tool (a+// two-option dialog for some, three for most), so it is read off the screen.+export const TUI_TOOL_PERMISSION_PROMPT_PATTERN = /do\s*you\s*want\s*to\s*proceed\?/i;+const TUI_TOOL_PERMISSION_NO_OPTION_PATTERN = /(\d+)\.\s*No\b/i;+const TUI_TOOL_PERMISSION_CALL_PATTERN = /([A-Z][A-Za-z]*\([^\n]{0,300}?\))\s*do\s*you\s*want\s*to\s*proceed\?/i;+// How much screen after the question the option list may span before it is+// judged not painted yet.+const TUI_TOOL_PERMISSION_OPTIONS_SPAN = 600;++/**+ * The tool-permission dialog on screen, or null. Null also while the question+ * has painted but the option list has not — the consumer waits for the next+ * repaint rather than guessing which key declines.+ *+ * @returns {{ noOption: number, toolCall: string|null }|null}+ */+export function detectToolPermissionPrompt(strippedText) {+ if (typeof strippedText !== 'string' || !strippedText) return null;+ const question = TUI_TOOL_PERMISSION_PROMPT_PATTERN.exec(strippedText);+ if (!question) return null;+ const options = strippedText.slice(question.index, question.index + TUI_TOOL_PERMISSION_OPTIONS_SPAN);+ const no = TUI_TOOL_PERMISSION_NO_OPTION_PATTERN.exec(options);+ if (!no) return null;+ const lead = strippedText.slice(Math.max(0, question.index - 400), question.index + question[0].length);+ const call = TUI_TOOL_PERMISSION_CALL_PATTERN.exec(lead);+ return { noOption: Number(no[1]), toolCall: call ? call[1].replace(/\s+/g, ' ') : null };+}++// A declined dialog keeps repainting for a few chunks and the keystrokes take a+// moment to land; sightings this close to a decline are the same dialog.+export const TOOL_PERMISSION_REPAINT_COOLDOWN_MS = 15000;+// Declining a tool call ends the assistant turn in current Claude Code builds+// ("What should Claude do instead?"), so the session then needs a message to+// carry on. Sent once the session has been SILENT this long after a decline —+// the same provider-agnostic silence test the OOM nudge uses — so a build that+// instead hands the model a rejection and lets it continue is left alone.+export const TOOL_PERMISSION_NUDGE_SETTLE_MS = 25000;+// A decline whose session never went quiet inside this window continued on its+// own; drop the pending nudge rather than fire it into a later quiet stretch.+export const TOOL_PERMISSION_NUDGE_ARM_WINDOW_MS = 120000;+// A model that keeps reaching outside its scope after this many declines is not+// going to finish inside it; the caller fails the run rather than looping.+export const TOOL_PERMISSION_DECLINE_MAX = 8;+export const TOOL_PERMISSION_NUDGE_TEXT = 'That tool call reached outside this run\'s allowed scope, so it was declined. Nobody is watching this session and no permission can be granted. Everything you need is inside your worktree and your prompt; continue using paths under the worktree only, and write the completion sentinel when you are done.';++/**+ * State machine for "decline every tool-permission dialog, then get the+ * session moving again". Feed it every ANSI-stripped chunk after the prompt is+ * in via `observe(strippedText, nowMs)`: it returns the dialog to decline+ * (`{ noOption, toolCall, count }`) exactly once per dialog, `'exhausted'` when+ * the decline budget is spent, or null. Poll `takeNudge(nowMs, lastOutputAtMs)`+ * on the consumer's existing timer; it returns the decline number a nudge is+ * due for, or 0.+ *+ * Carries a screen tail across chunks so a dialog split by a PTY chunk+ * boundary still matches; the tail is dropped after a decline so the same+ * dialog cannot be re-sighted from the carry-over.+ *+ * @returns {{ observe: (strippedText: string, nowMs: number) => object|'exhausted'|null,+ * takeNudge: (nowMs: number, lastOutputAtMs: number) => number }}+ */+export function createToolPermissionGate() {+ let tail = '';+ let declines = 0;+ let lastDeclineAt = null;+ let pendingNudge = null; // { declinedAt, count }+ return {+ observe(strippedText, nowMs) {+ if (typeof strippedText !== 'string' || !strippedText) return null;+ const window = (tail + strippedText).slice(-1024);+ tail = window;+ if (lastDeclineAt !== null && nowMs - lastDeclineAt < TOOL_PERMISSION_REPAINT_COOLDOWN_MS) return null;+ const dialog = detectToolPermissionPrompt(window);+ if (!dialog) return null;+ tail = '';+ lastDeclineAt = nowMs;+ if (declines >= TOOL_PERMISSION_DECLINE_MAX) return 'exhausted';+ declines += 1;+ pendingNudge = { declinedAt: nowMs, count: declines };+ return { ...dialog, count: declines };+ },+ takeNudge(nowMs, lastOutputAtMs) {+ if (!pendingNudge) return 0;+ if (nowMs - pendingNudge.declinedAt > TOOL_PERMISSION_NUDGE_ARM_WINDOW_MS) { pendingNudge = null; return 0; }+ if (nowMs - lastOutputAtMs < TOOL_PERMISSION_NUDGE_SETTLE_MS) return 0;+ const { count } = pendingNudge;+ pendingNudge = null;+ return count;+ },+ };+}diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex ad28e73c2f..f891c45fcb 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -44,6 +44,16 @@ import {isCollapsedPasteChip,createInputReadyTracker,AGY_INPUT_READY_PATTERN,+ createRetryStallGate,+ RETRY_STALL_MS,+ RETRY_STALL_MIN_ADVANCES,+ detectToolPermissionPrompt,+ createToolPermissionGate,+ TOOL_PERMISSION_REPAINT_COOLDOWN_MS,+ TOOL_PERMISSION_NUDGE_SETTLE_MS,+ TOOL_PERMISSION_NUDGE_ARM_WINDOW_MS,+ TOOL_PERMISSION_DECLINE_MAX,+ TOOL_PERMISSION_NUDGE_TEXT,} from './tuiHandshake.js';import { detectImmediateFallbackSignal } from './aiToolkit/errorDetection.js';import { CODEX_CONFIGURED_DEFAULT } from './providerModels.js';@@ -1595,6 +1605,157 @@ describe('tuiHandshake — parity with the shipped provider catalog', () => {);});+describe('createRetryStallGate', () => {+ const MIN = 60 * 1000;+ const banner = (attempt, secs = 0) => `API error · Retrying in ${secs}s · attempt ${attempt}/10`;++ it('fails over a request the provider keeps failing across the stall window (agent-e057cca7)', () => {+ // Stage 3's ~100K-token prefill was cancelled by the harness every ~6+ // minutes and re-sent verbatim: attempt 1 at t, 2 at t+6m, 3 at t+12m …+ const gate = createRetryStallGate();+ gate.observe(banner(1, 1), 0);+ gate.observe(banner(1, 0), 1000);+ expect(gate.takeStall()).toBeNull();+ gate.observe(banner(2), 6 * MIN);+ expect(gate.takeStall()).toBeNull();+ gate.observe(banner(3), 12 * MIN);++ const verdict = gate.takeStall();+ expect(verdict).toMatchObject({ category: 'timeout', requiresFallback: true, actionable: false });+ expect(verdict.message).toContain('retried it 3 times over 12 minutes');+ // Handed back once: the consumer fails over exactly once.+ expect(gate.takeStall()).toBeNull();+ });++ it('is decided at a sighting, never by the clock: a fast ladder that then succeeded is not a stall', () => {+ // A transient cloud fault: ten attempts in two minutes, the last one+ // answered, and the run did an hour of useful work afterwards.+ const gate = createRetryStallGate();+ for (let attempt = 1; attempt <= 10; attempt += 1) gate.observe(banner(attempt), attempt * 12 * 1000);+ gate.observe('⏺ Read(server/index.js)\n', 5 * MIN);+ gate.observe('⏺ Edit(server/index.js)\n', 60 * MIN);+ expect(gate.takeStall()).toBeNull();+ });++ it('needs the banner to advance RETRY_STALL_MIN_ADVANCES times inside one episode', () => {+ const gate = createRetryStallGate();+ // A single failing attempt repainted for a long time — the countdown+ // ticking and a stale screen — is one sighting, not a ladder.+ gate.observe(banner(1, 2), 0);+ gate.observe(banner(1, 1), RETRY_STALL_MS);+ gate.observe(banner(1, 0), RETRY_STALL_MS + 5000);+ expect(gate.takeStall()).toBeNull();+ gate.observe(banner(1 + RETRY_STALL_MIN_ADVANCES - 1), RETRY_STALL_MS + 6 * MIN);+ expect(gate.takeStall()).toBeNull();+ gate.observe(banner(1 + RETRY_STALL_MIN_ADVANCES), RETRY_STALL_MS + 12 * MIN);+ expect(gate.takeStall()).not.toBeNull();+ });++ it('starts a new episode when the counter restarts or the last banner is stale', () => {+ const gate = createRetryStallGate();+ // Episode A: two attempts, then the request answered.+ gate.observe(banner(1), 0);+ gate.observe(banner(2), 6 * MIN);+ // Episode B, a later request: its counter restarts at 1 …+ gate.observe(banner(1), 30 * MIN);+ gate.observe(banner(2), 36 * MIN);+ expect(gate.takeStall()).toBeNull();+ gate.observe(banner(3), 42 * MIN);+ const verdict = gate.takeStall();+ // … and is judged on its own attempts, not A's.+ expect(verdict.message).toContain('retried it 3 times over 12 minutes');++ // A banner more than the stall window after the previous one is a fresh+ // episode even when its counter happens to be higher.+ const stale = createRetryStallGate();+ stale.observe(banner(1), 0);+ stale.observe(banner(4), RETRY_STALL_MS + 1000);+ stale.observe(banner(5), RETRY_STALL_MS + 2000);+ expect(stale.takeStall()).toBeNull();+ });++ it('matches a banner split across PTY chunks, and never re-sights it from the carry-over', () => {+ const gate = createRetryStallGate();+ gate.observe('API error · Retrying in 0s · att', 0);+ gate.observe('empt 1/10\n', 10);+ // Chunks that follow carry no banner of their own; the carry-over was+ // consumed through the match, so these must not read as new sightings that+ // would keep an episode alive.+ gate.observe('\n', 6 * MIN);+ gate.observe('─────\n', 12 * MIN);+ gate.observe(banner(2), 20 * MIN);+ // If the carry-over had re-sighted attempt 1 at 6m/12m, attempt 2 at 20m+ // would still be inside the episode; being > RETRY_STALL_MS after the only+ // real sighting, it starts a new one instead.+ gate.observe(banner(3), 21 * MIN);+ gate.observe(banner(4), 22 * MIN);+ expect(gate.takeStall()).toBeNull();+ });+});++describe('tool-permission dialog (agent-e057cca7)', () => {+ // Verbatim from the stripped screen: a local model hallucinated an absolute+ // path, and acceptEdits asked a human who was not there.+ const READ_DIALOG = ' Read(/data.reference/providers.json) Doyouwanttoproceed? ❯1. Yes 2. Yes,allowreadingfrom/data.referenceduringthissession 3. No Esc to cancel · Tab to amend ';+ const TWO_OPTION_DIALOG = 'Bash(rm -rf build)\nDo you want to proceed?\n❯ 1. Yes\n 2. No\n';++ describe('detectToolPermissionPrompt', () => {+ it('reads the decline option off the screen, whatever its number', () => {+ expect(detectToolPermissionPrompt(READ_DIALOG)).toEqual({ noOption: 3, toolCall: 'Read(/data.reference/providers.json)' });+ expect(detectToolPermissionPrompt(TWO_OPTION_DIALOG)).toEqual({ noOption: 2, toolCall: 'Bash(rm -rf build)' });+ });++ it('waits for the option list rather than guessing which key declines', () => {+ expect(detectToolPermissionPrompt(' Read(/etc/hosts) Doyouwanttoproceed? ')).toBeNull();+ });++ it('ignores prose and the nudge it sends', () => {+ expect(detectToolPermissionPrompt('Ask the user whether they want to proceed with 3. No changes')).toBeNull();+ expect(detectToolPermissionPrompt(TOOL_PERMISSION_NUDGE_TEXT)).toBeNull();+ expect(detectToolPermissionPrompt('')).toBeNull();+ });+ });++ describe('createToolPermissionGate', () => {+ it('declines a dialog once, however many chunks repaint it, then nudges the quiet session', () => {+ const gate = createToolPermissionGate();+ // Split across a chunk boundary, as a PTY delivers it.+ expect(gate.observe(READ_DIALOG.slice(0, 60), 0)).toBeNull();+ expect(gate.observe(READ_DIALOG.slice(60), 50)).toEqual({ noOption: 3, toolCall: 'Read(/data.reference/providers.json)', count: 1 });+ // The declined dialog keeps repainting while the keystrokes land.+ expect(gate.observe(READ_DIALOG, 2000)).toBeNull();+ expect(gate.observe(READ_DIALOG, TOOL_PERMISSION_REPAINT_COOLDOWN_MS - 1)).toBeNull();+ // Still repainting: not quiet, so no nudge yet.+ expect(gate.takeNudge(5000, 4000)).toBe(0);+ // Quiet for the settle window: nudge, exactly once.+ const quietAt = 5000;+ expect(gate.takeNudge(quietAt + TOOL_PERMISSION_NUDGE_SETTLE_MS, quietAt)).toBe(1);+ expect(gate.takeNudge(quietAt + TOOL_PERMISSION_NUDGE_SETTLE_MS + 5000, quietAt)).toBe(0);+ });++ it('drops the nudge when the session carried on by itself', () => {+ const gate = createToolPermissionGate();+ gate.observe(READ_DIALOG, 0);+ // Output never stops for the whole arm window — the build handed the model+ // a rejection and it kept working — so a later quiet stretch gets no nudge.+ const late = TOOL_PERMISSION_NUDGE_ARM_WINDOW_MS + 1000;+ expect(gate.takeNudge(late, late - 100)).toBe(0);+ expect(gate.takeNudge(late + TOOL_PERMISSION_NUDGE_SETTLE_MS, late)).toBe(0);+ });++ it('reports exhaustion after TOOL_PERMISSION_DECLINE_MAX distinct dialogs', () => {+ const gate = createToolPermissionGate();+ let now = 0;+ for (let i = 1; i <= TOOL_PERMISSION_DECLINE_MAX; i += 1) {+ now += TOOL_PERMISSION_REPAINT_COOLDOWN_MS + 1;+ expect(gate.observe(READ_DIALOG, now)).toMatchObject({ count: i });+ }+ now += TOOL_PERMISSION_REPAINT_COOLDOWN_MS + 1;+ expect(gate.observe(TWO_OPTION_DIALOG, now)).toBe('exhausted');+ });+ });+});+describe('createOomNudgeGate', () => {const analysis = { category: 'resource-exhausted', message: 'Local inference runtime ran out of GPU memory' };diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex c3d7fb6e80..5224875a65 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -130,18 +130,25 @@ function pipelineContextLines(pipelineCtx) {`Previous stage: "${pipelineCtx.stages[pipelineCtx.currentStage - 1]?.name}"`,'',];- if (pipelineCtx.previousStageAgentId) {+ const rawPreviousOutput = typeof pipelineCtx.previousStageOutput === 'string'+ ? pipelineCtx.previousStageOutput.trim()+ : '';+ const previousOutput = rawPreviousOutput.slice(0, 12_000).replace(/~+/g, "'");+ const truncated = rawPreviousOutput.length > previousOutput.length;+ if (!pipelineCtx.previousStageAgentId) {+ lines.push('The previous stage completed as a direct preflight; its summary is included below.');+ } else if (previousOutput && !truncated) {+ // The whole output is inlined below, so the file pointer would only send+ // the agent OUTSIDE its worktree — which, under a sandboxed permission+ // posture, is a tool-permission dialog nobody is present to answer.+ lines.push("The previous stage's complete output is inlined below; there is nothing further to read from disk.");+ } else {lines.push("Read the previous stage's output from:",`\`${join(AGENTS_DIR, pipelineCtx.previousStageAgentId, 'output.txt')}\``,);- } else {- lines.push('The previous stage completed as a direct preflight; its summary is included below.');}- const previousOutput = typeof pipelineCtx.previousStageOutput === 'string'- ? pipelineCtx.previousStageOutput.trim().slice(0, 12_000).replace(/~+/g, "'")- : '';if (previousOutput) {lines.push('',diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex d21df2ddfe..3cd40239aa 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -2320,6 +2320,34 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/agent-prev-1[\\/]output\.txt/);});+ it('keeps a stage inside its worktree when the previous output is inlined in full', () => {+ // The pointer names a file under data/cos/agents — outside every agent+ // worktree. Under a sandboxed permission posture reading it is a dialog+ // nobody answers (agent-e057cca7), and the text is already in the prompt.+ const inlined = buildLightContextPrompt(makeTask({+ metadata: { pipeline: {+ previousStageAgentId: 'agent-prev-1',+ previousStageOutput: JSON.stringify({ eligibility: 'passed', eligibleNumbers: [6223] }),+ currentStage: 2,+ stages: [{ name: 'scan' }, { name: 'gate' }, { name: 'review' }],+ }}+ }), '/r', null, isTruthyMeta);+ expect(inlined).toMatch(/complete output is inlined below/);+ expect(inlined).not.toMatch(/output\.txt/);+ expect(inlined).toMatch(/"eligibleNumbers":\[6223\]/);++ // A clipped inline still needs the pointer: the rest is only on disk.+ const clipped = buildLightContextPrompt(makeTask({+ metadata: { pipeline: {+ previousStageAgentId: 'agent-prev-1',+ previousStageOutput: 'x'.repeat(12_001),+ currentStage: 2,+ stages: [{ name: 'scan' }, { name: 'gate' }, { name: 'review' }],+ }}+ }), '/r', null, isTruthyMeta);+ expect(clipped).toMatch(/agent-prev-1[\\/]output\.txt/);+ });+it('renders a direct preflight summary when the previous stage has no agent', () => {const prompt = buildLightContextPrompt(makeTask({metadata: { pipeline: {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 89dd989e4c..640becf255 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -45,6 +45,10 @@ import {countPasteMarkers,createSelfClearingSignalGate,createOomNudgeGate,+ createRetryStallGate,+ createToolPermissionGate,+ TOOL_PERMISSION_DECLINE_MAX,+ TOOL_PERMISSION_NUDGE_TEXT,OOM_NUDGE_MAX_ATTEMPTS,OOM_NUDGE_TEXT,createMcpBootTracker,@@ -739,6 +743,15 @@ export async function spawnTuiAgent({// createOomNudgeGate for why this is a separate mechanism from the gate above.const detectLocalRuntimeOom = createLocalRuntimeOomDetector();const oomNudgeGate = createOomNudgeGate();+ // A request the TUI keeps retrying and the provider never answers. Every+ // reaper reads such a session as busy (the retry ladder repaints the screen),+ // so without this the run holds its lane until the max-runtime ceiling — see+ // createRetryStallGate.+ const retryStallGate = createRetryStallGate();+ // A tool-permission dialog nobody is present to answer. Declined on sight —+ // the launch posture already decided the run's scope — then nudged along+ // once the session goes quiet. See createToolPermissionGate.+ const toolPermissionGate = createToolPermissionGate();// Guards ingestDoneSentinel to a single read. finish() is its only caller and// is itself guarded by `finalized`, so this is defensive — it pins the// read-at-most-once invariant at the helper.@@ -1417,6 +1430,29 @@ export async function spawnTuiAgent({}}+ // Same gating as the OOM nudge above: before the prompt is in there is no+ // request of ours for the provider to be retrying. Acted on by the+ // provider-signal timer, on its own poll, like the other gates.+ if (promptSubmittedAt) retryStallGate.observe(stripped, now);++ const permissionDialog = promptSubmittedAt ? toolPermissionGate.observe(stripped, now) : null;+ if (permissionDialog === 'exhausted') {+ await finish({+ success: false,+ exitCode: 1,+ error: `${tuiConfig.command} kept asking for tool permissions an unattended run cannot grant (${TOOL_PERMISSION_DECLINE_MAX} dialogs declined) — the model keeps reaching outside the run's allowed scope`,+ reason: 'permission-prompt-loop',+ });+ return;+ }+ if (permissionDialog) {+ // "No" is the last option and option 1 is highlighted: arrow down to it,+ // then Enter — lands under both of Ink's selection models, whereas a bare+ // digit is immediate-select in some builds and ignored in others.+ shellService.writeToSession(sessionId, `${'\x1b[B'.repeat(Math.max(0, permissionDialog.noOption - 1))}\r`);+ appendLine(`🚫 Declined ${tuiConfig.command} permission prompt for ${permissionDialog.toolCall || 'a tool call'} — an unattended run never widens its scope (${permissionDialog.count}/${TOOL_PERMISSION_DECLINE_MAX})`);+ }+if (!promptSentAt) {// Only the login-shell path can reach this: it is the shell PRINTING// "command not found". A direct PTY resolves the executable before it@@ -1875,6 +1911,21 @@ export async function spawnTuiAgent({resubmitAfterSignal();return;}+ const stall = retryStallGate.takeStall();+ if (stall) {+ failOverToFallback(stall).catch((err) =>+ emitLog('error', `TUI agent ${agentId} retry-stall fallback finish failed: ${err?.message || err}`, { agentId }));+ return;+ }+ // A declined permission dialog ends the turn; once the session is quiet,+ // tell it why and send it back to work.+ const declined = toolPermissionGate.takeNudge(Date.now(), lastOutputAt);+ if (declined) {+ if (pasteController?.resubmit({ text: TOOL_PERMISSION_NUDGE_TEXT, label: 'declined-permission nudge' })) {+ appendLine(`🔁 Nudged the session to continue after declined permission prompt ${declined}`);+ }+ return;+ }// Nudge a session a local-GPU OOM parked. Rides this timer rather than one// of its own so the nudge cadence and the fail-over verdict stay on the same// clock — and so there is one fewer interval to leak past finish().diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 118fcf64be..c317adadc1 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -251,6 +251,9 @@ import {OOM_NUDGE_COOLDOWN_MS,OOM_NUDGE_MAX_ATTEMPTS,OOM_NUDGE_TEXT,+ RETRY_STALL_MS,+ TOOL_PERMISSION_NUDGE_SETTLE_MS,+ TOOL_PERMISSION_NUDGE_TEXT,} from '../lib/tuiHandshake.js';// Real module, not a mock: the flag is a plain process-local boolean, so driving// it directly exercises the same code path production does.@@ -1779,6 +1782,71 @@ describe('spawnTuiAgent runtime', () => {);});+ // ── Retry stall: the provider keeps failing the same request ───────────────+ // agent-e057cca7 (2026-09-04): a Stage 3 prefill the harness cancelled every+ // ~6 minutes and re-sent verbatim. The screen repaints on every attempt, so+ // every reaper saw a busy session and the run held its lane until the+ // max-runtime ceiling.+ it('fails over a session whose retry banner keeps advancing past the stall window', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ await driveAgyToSubmittedPrompt();++ const retryCycleMs = RETRY_STALL_MS / 2 + 60_000;+ for (const attempt of [1, 2]) {+ await capturedOnData(Buffer.from(`API error · Retrying in 0s · attempt ${attempt}/10\n`));+ await flushMicrotasks();+ // The retried request is in flight: the title bar flickers, nothing else+ // paints. Two attempts alone are not a verdict, however long they span.+ await vi.advanceTimersByTimeAsync(retryCycleMs);+ await flushMicrotasks();+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();+ }++ await capturedOnData(Buffer.from('API error · Retrying in 0s · attempt 3/10\n'));+ await flushMicrotasks();+ // Acted on by the 5s provider-signal poll, like the other gates.+ await vi.advanceTimersByTimeAsync(5000);+ vi.useRealTimers();+ await completeDone;++ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ success: false,+ completionReason: 'fallback-signal',+ error: expect.stringContaining('retried it 3 times'),+ })+ );+ });++ // ── Tool-permission dialog: decline, then nudge ───────────────────────────+ // agent-e057cca7 (2026-09-04): under the sandboxed acceptEdits recipe a local+ // model asked to Read an absolute path outside the worktree, and the dialog+ // sat unanswered for the rest of the run.+ it('declines a tool-permission dialog and nudges the session once it goes quiet', async () => {+ await driveAgyToSubmittedPrompt();+ vi.mocked(shellService.writeToSession).mockClear();+ vi.mocked(shellService.pasteToSession).mockClear();++ await capturedOnData(Buffer.from(' Read(/data.reference/providers.json) Doyouwanttoproceed? ❯1. Yes 2. Yes,allowreadingfrom/data.referenceduringthissession 3. No Esc to cancel · Tab to amend '));+ await flushMicrotasks();+ // Option 1 is highlighted; "No" is option 3: down, down, Enter.+ expect(shellService.writeToSession).toHaveBeenCalledWith(SESSION_ID, '\x1b[B\x1b[B\r');++ // The decline ends the turn; once the session is quiet the nudge goes out.+ await vi.advanceTimersByTimeAsync(TOOL_PERMISSION_NUDGE_SETTLE_MS + 10000);+ await flushMicrotasks();+ expect(shellService.pasteToSession).toHaveBeenCalledWith(+ SESSION_ID,+ TOOL_PERMISSION_NUDGE_TEXT,+ expect.objectContaining({ label: expect.stringContaining('permission') }),+ );+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();+ });+// ── 1b. Submit-Enter retries ─────────────────────────────────────────────────// A single `\r` after a large bracketed paste can be swallowed mid-paste-// commit, stranding the prompt unsent (the "I had to hit Enter myself" bug,