Skip to content

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

feat: recover CoS TUI agents from a local-GPU out-of-memory stall

Adam Eivy4a018eca8e7f
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index a44f44ca1e..231e147fe0 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -20,6 +20,12 @@ export const ERROR_CATEGORIES = {
// a fallback (a local model often doesn't refuse) and tell the UI what
// happened. See server/index.js#onRunFailed + autoFixer.handleAIProviderError.
CONTENT_REFUSAL: 'content-refusal',
+ // A LOCAL inference runtime ran out of accelerator memory mid-request (Metal
+ // on Apple silicon, CUDA elsewhere). Distinct from QUOTA_EXCEEDED (money) and
+ // from TIMEOUT (the request never finished): the request was ACCEPTED and then
+ // killed by the device allocator, so the same prompt can succeed once the GPU
+ // drains. See LOCAL_RUNTIME_OOM_PATTERN.
+ RESOURCE_EXHAUSTED: 'resource-exhausted',
UNKNOWN: 'unknown'
};
@@ -46,6 +52,35 @@ export const isRunCanceledError = (err) => (
!!err && (err.code === 'RUN_CANCELED' || err.canceled === true)
);
+// A LOCAL inference runtime that ran out of accelerator memory mid-request.
+//
+// Observed shape (MTPLX/MLX behind an OpenAI-compatible server, rendered inside
+// OpenCode's error box, hard-wrapped by the TUI):
+//
+// {"message":"[METAL] Command buffer execution failed: Insufficient Memory
+// (00000008: kIOGPUCommandBufferCallbackErrorOutOfMemory).","type":
+// "server_error","code":"RuntimeError","param":null}
+//
+// Every alternative below is a single unbroken token or a short phrase that a
+// TUI wraps at a space, so the pattern survives the box-drawing glyphs and
+// newlines the renderer injects INSIDE the JSON. That is also why this pattern
+// is deliberately NOT line-anchored the way the agy banners are: there is no
+// line start to anchor to once the envelope is wrapped across four rows.
+//
+// The precision comes from the strings themselves — these are vendor error
+// constants, not English an agent writes by accident. The residual
+// false-positive surface is an agent QUOTING one (working on this file, or
+// investigating this very failure), and the consumer bounds that cost: the
+// agent-TUI path only nudges a session that has ALREADY gone silent, and only
+// fails the run after three such nudges (see createOomNudgeGate).
+const LOCAL_RUNTIME_OOM_PATTERN = new RegExp([
+ 'kIOGPUCommandBufferCallbackErrorOutOfMemory',
+ '\\[METAL\\]\\s*Command buffer execution failed',
+ 'CUDA (?:error: )?out of memory',
+ 'torch\\.(?:cuda\\.)?OutOfMemoryError',
+ 'CUDA_ERROR_OUT_OF_MEMORY',
+].join('|'), 'i');
+
// Order matters — more specific patterns first.
const ERROR_PATTERNS = [
{
@@ -61,6 +96,19 @@ const ERROR_PATTERNS = [
actionable: false,
suggestedFix: 'Model declined the prompt on content/safety grounds — retrying with a fallback model.'
},
+ {
+ // A local inference server (MTPLX/MLX, vLLM, llama.cpp, Ollama) whose device
+ // allocator failed mid-request. Matched BEFORE the generic network/timeout
+ // clauses so a post-hoc scan of a failed run's output labels it for what it
+ // is instead of landing in UNKNOWN. Shares its source with
+ // LOCAL_RUNTIME_OOM_PATTERN so the streaming detector and the post-hoc scan
+ // can never drift apart.
+ pattern: LOCAL_RUNTIME_OOM_PATTERN,
+ category: ERROR_CATEGORIES.RESOURCE_EXHAUSTED,
+ requiresFallback: true,
+ actionable: false,
+ suggestedFix: 'The local inference runtime ran out of GPU memory. Retry once the device drains, shrink the context/KV cache, or run a smaller model.'
+ },
{
pattern: /billing|payment|credit|insufficient funds/i,
category: ERROR_CATEGORIES.QUOTA_EXCEEDED,
@@ -439,6 +487,65 @@ export function createTerminalRequestTimeoutDetector({ maxBuffer = 512 } = {}) {
};
}
+/**
+ * Detect a LOCAL inference runtime that ran out of accelerator memory
+ * mid-request (see LOCAL_RUNTIME_OOM_PATTERN for the observed shape).
+ *
+ * Deliberately NOT an entry in IMMEDIATE_FALLBACK_SIGNALS, for the same reason
+ * detectTerminalModelError is kept out of it: that list is consulted by every
+ * TUI/CLI spawn path, and a `graceMs` entry there would arm the self-clearing
+ * gate in the ONE-SHOT runner too — where a false "recovered" latch finalizes a
+ * run as a success that scraped the error screen. This failure needs a
+ * different remedy anyway. The provider did not REJECT the submission the way
+ * agy's eligibility banner does; it accepted the turn and the device allocator
+ * killed it, so the TUI session still holds the whole conversation and only
+ * needs to be told to carry on — which is exactly what a human typing
+ * `continue` did on 2026-08-22 (agent-011d0c27, OpenCode on
+ * `mtplx/mtplx-qwen38-27b-optimized-speed`). Re-sending the whole prompt, the
+ * one thing the self-clearing gate knows how to do, would instead restart the
+ * task on top of the work already done.
+ *
+ * Only `agentTuiSpawning` consults this, through `createOomNudgeGate`.
+ *
+ * @returns {object|null} an analysis in the same shape
+ * `detectImmediateFallbackSignal` returns, so the caller can hand it straight
+ * to its fail-over path once the nudges are spent.
+ */
+export function detectLocalRuntimeOom(text) {
+ if (!text) return null;
+ const match = String(text).match(LOCAL_RUNTIME_OOM_PATTERN);
+ if (!match) return null;
+ return {
+ hasError: true,
+ category: ERROR_CATEGORIES.RESOURCE_EXHAUSTED,
+ message: 'Local inference runtime ran out of GPU memory',
+ waitTime: null,
+ requiresFallback: true,
+ // Nothing in PortOS config is wrong and nobody has to fix anything: the
+ // device was momentarily short of memory. Marking it actionable would BLOCK
+ // the task (see agentErrorAnalysis#resolveFailedTaskDecision) over a
+ // condition a fallback provider can serve right now.
+ actionable: false,
+ graceMs: 0,
+ suggestedFix: 'The local inference runtime ran out of GPU memory. Retry once the device drains, shrink the context/KV cache, or run a smaller model.',
+ // Genuine evidence about the provider host: this endpoint's GPU is short of
+ // memory, so benching it briefly (RESOURCE_EXHAUSTED in
+ // providerCooldown.js) routes the retry somewhere that can serve it.
+ origin: 'provider',
+ };
+}
+
+export function createLocalRuntimeOomDetector({ maxBuffer = 512 } = {}) {
+ let buffer = '';
+ const cap = Number.isFinite(maxBuffer) && maxBuffer > 0 ? maxBuffer : 512;
+
+ return (chunk) => {
+ if (!chunk) return null;
+ buffer = `${buffer}${String(chunk)}`.slice(-cap);
+ return detectLocalRuntimeOom(buffer);
+ };
+}
+
export function extractWaitTime(text) {
if (!text) return null;
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index 52c6f82a17..a3c69e93e3 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -4,8 +4,10 @@ import {
analyzeHttpError,
createImmediateFallbackSignalDetector,
createTerminalModelErrorDetector,
+ createLocalRuntimeOomDetector,
createTerminalRequestTimeoutDetector,
detectImmediateFallbackSignal,
+ detectLocalRuntimeOom,
detectTerminalModelError,
detectTerminalRequestTimeout,
extractWaitTime,
@@ -529,6 +531,59 @@ describe('Error Detection', () => {
});
});
+ describe('detectLocalRuntimeOom', () => {
+ // The MLX/MTPLX error envelope exactly as OpenCode's error box renders it —
+ // hard-wrapped mid-JSON, with the box-drawing gutter between rows. Captured
+ // from agent-011d0c27 (2026-08-22).
+ const WRAPPED_OOM_BOX = [
+ '│ {"message":"[METAL] Command buffer execution failed: │',
+ '│ Insufficient Memory (00000008: │',
+ '│ kIOGPUCommandBufferCallbackErrorOutOfMemory).","type": │',
+ '│ "server_error","code":"RuntimeError","param":null} │',
+ ].join('\n');
+
+ it('detects the Metal OOM through the TUI box that wraps it mid-JSON', () => {
+ expect(detectLocalRuntimeOom(WRAPPED_OOM_BOX)).toMatchObject({
+ category: ERROR_CATEGORIES.RESOURCE_EXHAUSTED,
+ requiresFallback: true,
+ // Nobody has to fix anything — marking it actionable would block the task.
+ actionable: false,
+ // Nudge-then-fail-over is the caller's policy, not a grace window here.
+ graceMs: 0,
+ origin: 'provider',
+ });
+ });
+
+ it('detects the CUDA phrasings a non-Apple local runtime raises', () => {
+ expect(detectLocalRuntimeOom('RuntimeError: CUDA out of memory. Tried to allocate 2.00 GiB'))
+ .toMatchObject({ category: ERROR_CATEGORIES.RESOURCE_EXHAUSTED });
+ expect(detectLocalRuntimeOom('torch.cuda.OutOfMemoryError: CUDA out of memory'))
+ .toMatchObject({ category: ERROR_CATEGORIES.RESOURCE_EXHAUSTED });
+ });
+
+ it('leaves ordinary output alone', () => {
+ expect(detectLocalRuntimeOom('the build ran out of disk space')).toBeNull();
+ expect(detectLocalRuntimeOom('Insufficient Memory')).toBeNull();
+ expect(detectLocalRuntimeOom('')).toBeNull();
+ });
+
+ it('buffers the constant across stream chunks', () => {
+ const detect = createLocalRuntimeOomDetector();
+ expect(detect('...(00000008: kIOGPUCommandBuffer')).toBeNull();
+ expect(detect('CallbackErrorOutOfMemory).')).toMatchObject({
+ category: ERROR_CATEGORIES.RESOURCE_EXHAUSTED,
+ });
+ });
+
+ it('classifies the same text in a post-hoc output scan', () => {
+ expect(analyzeError(WRAPPED_OOM_BOX, 1)).toMatchObject({
+ category: ERROR_CATEGORIES.RESOURCE_EXHAUSTED,
+ requiresFallback: true,
+ actionable: false,
+ });
+ });
+ });
+
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/providerCooldown.js b/server/lib/providerCooldown.js
index 041e8ebb09..d8afb4fabc 100644
--- a/server/lib/providerCooldown.js
+++ b/server/lib/providerCooldown.js
@@ -27,6 +27,9 @@ import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';
// MODEL_NOT_FOUND — 30m: also config; longer because retry is unlikely
// QUOTA_EXCEEDED — 60m: billing/credits; retry sooner is futile
// NETWORK_ERROR — 2m: usually a transient hiccup
+// RESOURCE_EXHAUSTED — 2m: a local GPU that just OOM'd needs the in-flight
+// work to drain before it can serve the same context again;
+// the endpoint itself is healthy, so this is a short bench
// TIMEOUT/UNKNOWN — 1m: short enough to retry, long enough to skip
// while the immediate workload retries via fallback
export const COOLDOWN_MS_BY_CATEGORY = {
@@ -35,6 +38,7 @@ export const COOLDOWN_MS_BY_CATEGORY = {
[ERROR_CATEGORIES.MODEL_NOT_FOUND]: 30 * 60 * 1000,
[ERROR_CATEGORIES.QUOTA_EXCEEDED]: 60 * 60 * 1000,
[ERROR_CATEGORIES.NETWORK_ERROR]: 2 * 60 * 1000,
+ [ERROR_CATEGORIES.RESOURCE_EXHAUSTED]: 2 * 60 * 1000,
[ERROR_CATEGORIES.TIMEOUT]: 60 * 1000,
[ERROR_CATEGORIES.UNKNOWN]: 60 * 1000,
};
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index e913d8e056..d293cab334 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -907,3 +907,98 @@ export function detectMissingTuiBinary(strippedText, commandName) {
const lower = strippedText.toLowerCase();
return lower.includes('command not found') && lower.includes(commandName.toLowerCase());
}
+
+// ── Local-runtime OOM nudge ────────────────────────────────────────────────
+// Recovery policy for a LOCAL inference runtime that ran out of accelerator
+// memory mid-turn (detectLocalRuntimeOom in aiToolkit/errorDetection.js).
+//
+// This is NOT the self-clearing gate above, and the difference is what the
+// provider did with the turn. agy's eligibility banner REJECTS the submission:
+// the composer empties, nothing is in flight, and the remedy is to re-send the
+// whole prompt. A Metal/CUDA OOM kills a turn the server had already ACCEPTED:
+// the TUI session still holds the entire conversation, so the remedy is a
+// one-word nudge to carry on. Re-pasting the task prompt there would restart
+// the task on top of the work already done.
+//
+// Provenance: agent-011d0c27 (2026-08-22, OpenCode on
+// `mtplx/mtplx-qwen38-27b-optimized-speed`) died on
+// `kIOGPUCommandBufferCallbackErrorOutOfMemory` and sat at its idle footer
+// until a human typed `continue`, at which point it resumed and finished the
+// turn. Nothing in the unattended path would ever have typed it — the
+// long-running agent path has no idle watchdog by design ("a CoS TUI may remain
+// silent for as long as the provider needs").
+
+// How long the session must have been SILENT before a nudge goes out. This is
+// the whole false-positive defense, and it is deliberately a silence test
+// rather than a chrome test: the generation-activity tracker above is spelled in
+// agy/claude/codex footer text that OpenCode does not paint at all (its
+// in-flight chrome is an animated block wave plus an `esc interrupt` footer that
+// repaints only ~8 times across a 74MB transcript), so a chrome-based recovery
+// check would read a perfectly healthy OpenCode session as stuck. Silence is
+// provider-agnostic and needs no per-TUI vocabulary.
+export const OOM_NUDGE_SETTLE_MS = 25000;
+// How long an armed nudge waits for that silence before giving up. Bounds the
+// blast radius of the one case the cooldown can't dedupe — the error box being
+// repainted long after the session recovered — so a stale arm can't sit around
+// and fire into the next quiet stretch of a healthy run.
+export const OOM_NUDGE_ARM_WINDOW_MS = 120000;
+// Two matches this close together are one OOM: the detector re-tests a 512-char
+// rolling window, and a TUI repaint re-delivers the same error box for many
+// chunks after the event.
+export const OOM_NUDGE_COOLDOWN_MS = 120000;
+// After this many nudges the OOM is not transient — the conversation no longer
+// fits the device, and it only grows — so the caller fails the run over to a
+// fallback provider rather than nudging forever.
+export const OOM_NUDGE_MAX_ATTEMPTS = 3;
+// What gets pasted. The literal word a human used, for the literal reason it
+// worked: the TUI still holds the conversation and the model just needs a turn.
+export const OOM_NUDGE_TEXT = 'continue';
+
+/**
+ * State machine for "nudge a TUI session that a local-GPU OOM left parked".
+ *
+ * Feed it every OOM detection via `arm(analysis, nowMs)`, then poll
+ * `takeNudge(nowMs, lastOutputAtMs)` on whatever timer the consumer already
+ * runs. Owns the dedupe cooldown, the silence test, the arm window and the
+ * attempt budget so a consumer can't get any of them subtly wrong.
+ *
+ * `arm` returns:
+ * - `'armed'` — a fresh OOM; wait for silence, then nudge
+ * - `'exhausted'` — a fresh OOM with the budget already spent; the caller
+ * should fail the run over to a fallback provider
+ * - `null` — a repaint of an OOM already accounted for, or a window
+ * that is still open
+ *
+ * @returns {{ arm: (analysis: object, nowMs: number) => 'armed'|'exhausted'|null,
+ * takeNudge: (nowMs: number, lastOutputAtMs: number) => number }}
+ */
+export function createOomNudgeGate() {
+ let armed = null; // { analysis, armedAt }
+ let lastArmedAt = null;
+ let attempts = 0;
+ return {
+ arm(analysis, nowMs) {
+ if (!analysis || armed) return null;
+ if (lastArmedAt !== null && nowMs - lastArmedAt < OOM_NUDGE_COOLDOWN_MS) return null;
+ lastArmedAt = nowMs;
+ // Budget spent: this is a genuinely NEW OOM (it cleared the cooldown)
+ // after the nudges already bought the run more than one recovery. Hand the
+ // verdict back rather than arming a window nobody will act on.
+ if (attempts >= OOM_NUDGE_MAX_ATTEMPTS) return 'exhausted';
+ armed = { analysis, armedAt: nowMs };
+ return 'armed';
+ },
+ // Returns the 1-based attempt number when the session has been quiet long
+ // enough to nudge, or 0. Disarms either way — on a nudge because it fired,
+ // and on an expired window because the session never went quiet, which is
+ // itself evidence it recovered without help.
+ takeNudge(nowMs, lastOutputAtMs) {
+ if (!armed) return 0;
+ if (nowMs - armed.armedAt > OOM_NUDGE_ARM_WINDOW_MS) { armed = null; return 0; }
+ if (nowMs - lastOutputAtMs < OOM_NUDGE_SETTLE_MS) return 0;
+ armed = null;
+ attempts += 1;
+ return attempts;
+ },
+ };
+}
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index 4a3804680e..3f4c46a031 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -9,6 +9,11 @@ import {
countPasteMarkers,
createGenerationActivityTracker,
createSelfClearingSignalGate,
+ createOomNudgeGate,
+ OOM_NUDGE_SETTLE_MS,
+ OOM_NUDGE_ARM_WINDOW_MS,
+ OOM_NUDGE_COOLDOWN_MS,
+ OOM_NUDGE_MAX_ATTEMPTS,
SELF_CLEARING_RESUBMIT_INTERVAL_MS,
SELF_CLEARING_RESUBMIT_ECHO_MS,
MCP_BOOT_PASTE_DEADLINE_MS,
@@ -1509,3 +1514,65 @@ describe('tuiHandshake — parity with the shipped provider catalog', () => {
}
);
});
+
+describe('createOomNudgeGate', () => {
+ const analysis = { category: 'resource-exhausted', message: 'Local inference runtime ran out of GPU memory' };
+
+ it('nudges only once the session has actually gone quiet', () => {
+ const gate = createOomNudgeGate();
+ const t0 = 1_000_000;
+ expect(gate.arm(analysis, t0)).toBe('armed');
+ // The TUI is still repainting the error box — nudging here would land on
+ // top of the repaint instead of at an idle composer.
+ expect(gate.takeNudge(t0 + OOM_NUDGE_SETTLE_MS, t0 + 5_000)).toBe(0);
+ expect(gate.takeNudge(t0 + OOM_NUDGE_SETTLE_MS + 5_001, t0 + 5_000)).toBe(1);
+ // Fired once; the arm is spent until the next distinct OOM.
+ expect(gate.takeNudge(t0 + 60_000, t0 + 5_000)).toBe(0);
+ });
+
+ it('treats repaints of the same error box as one OOM', () => {
+ const gate = createOomNudgeGate();
+ const t0 = 0;
+ expect(gate.arm(analysis, t0)).toBe('armed');
+ // Same window: already armed.
+ expect(gate.arm(analysis, t0 + 100)).toBeNull();
+ expect(gate.takeNudge(t0 + OOM_NUDGE_SETTLE_MS + 1, t0)).toBe(1);
+ // Disarmed, but still inside the dedupe cooldown — a repaint must not
+ // spend a second nudge on the same event.
+ expect(gate.arm(analysis, t0 + OOM_NUDGE_COOLDOWN_MS - 1)).toBeNull();
+ expect(gate.arm(analysis, t0 + OOM_NUDGE_COOLDOWN_MS)).toBe('armed');
+ });
+
+ it('drops a stale arm the session never went quiet for', () => {
+ const gate = createOomNudgeGate();
+ const t0 = 0;
+ gate.arm(analysis, t0);
+ // Output kept flowing for the whole window: the run recovered on its own,
+ // so the arm expires rather than waiting to fire into the next quiet spell.
+ expect(gate.takeNudge(t0 + OOM_NUDGE_ARM_WINDOW_MS + 1, t0 + OOM_NUDGE_ARM_WINDOW_MS)).toBe(0);
+ // An expired window costs nothing: the next real OOM still gets attempt 1.
+ const t1 = t0 + OOM_NUDGE_COOLDOWN_MS;
+ expect(gate.arm(analysis, t1)).toBe('armed');
+ expect(gate.takeNudge(t1 + OOM_NUDGE_SETTLE_MS + 1, t1)).toBe(1);
+ });
+
+ it('hands back an exhausted verdict once the nudge budget is spent', () => {
+ const gate = createOomNudgeGate();
+ let t = 0;
+ for (let i = 1; i <= OOM_NUDGE_MAX_ATTEMPTS; i += 1) {
+ expect(gate.arm(analysis, t)).toBe('armed');
+ t += OOM_NUDGE_SETTLE_MS + 1;
+ expect(gate.takeNudge(t, t - OOM_NUDGE_SETTLE_MS - 1)).toBe(i);
+ t += OOM_NUDGE_COOLDOWN_MS;
+ }
+ // A genuinely new OOM after the budget: the context no longer fits the
+ // device, so the caller fails over instead of nudging again.
+ expect(gate.arm(analysis, t)).toBe('exhausted');
+ });
+
+ it('ignores a null analysis', () => {
+ const gate = createOomNudgeGate();
+ expect(gate.arm(null, 0)).toBeNull();
+ expect(gate.takeNudge(OOM_NUDGE_SETTLE_MS + 1, 0)).toBe(0);
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 7d8735d90c..25f0146e77 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -32,7 +32,7 @@ import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';
import { formatShellCommandLine } from '../lib/shellCd.js';
import { isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
-import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
+import { createImmediateFallbackSignalDetector, createLocalRuntimeOomDetector } from '../lib/aiToolkit/errorDetection.js';
import { isAntigravityCommand } from '../lib/antigravity.js';
import {
DEFAULT_TUI_PROMPT_DELAY_MS,
@@ -41,6 +41,9 @@ import {
PASTE_MARKER_POLL_MS,
countPasteMarkers,
createSelfClearingSignalGate,
+ createOomNudgeGate,
+ OOM_NUDGE_MAX_ATTEMPTS,
+ OOM_NUDGE_TEXT,
createMcpBootTracker,
MCP_BOOT_PASTE_DEADLINE_MS,
MCP_BOOT_PASTE_RETRY_DELAY_MS,
@@ -272,8 +275,10 @@ function createPasteRetryController({
let sent = false;
/**
- * Re-deliver the prompt while a self-clearing provider signal's grace window
- * is open (agy's account-eligibility banner).
+ * Re-deliver text into the live session: the whole prompt while a
+ * self-clearing provider signal's grace window is open (agy's
+ * account-eligibility banner), or the short `continue` nudge that recovers a
+ * turn a local-GPU OOM killed (see createOomNudgeGate).
*
* The banner is the REJECTION of the submission, not a spinner over an
* in-flight one: agy discards the prompt, empties its composer and returns to
@@ -293,15 +298,15 @@ function createPasteRetryController({
* session is gone — the caller must not claim a re-submission that didn't
* happen).
*/
- const resubmit = () => {
+ const resubmit = ({ text = prompt, label = 'provider-handshake resubmit' } = {}) => {
if (isFinalized() || !sessionId) return false;
// Overwriting a live handle would leak the previous attempt's Enter interval
// past cancel(); pasteToSession returns a fresh one, or false once the
// session is gone — which is also the "don't bother" answer, since the
// grace window's deadline still owns the fail-over.
if (submitEnterTimer) clearInterval(submitEnterTimer);
- const handle = shellService.pasteToSession(sessionId, prompt, {
- label: '[cosAgents] provider-handshake resubmit',
+ const handle = shellService.pasteToSession(sessionId, text, {
+ label: `[cosAgents] ${label}`,
});
submitEnterTimer = handle || null;
return !!handle;
@@ -548,6 +553,11 @@ export async function spawnTuiAgent({
// (agy's account-eligibility banner). The provider-signal timer below resolves
// its deadline and drives the re-submission cadence.
const selfClearingGate = createSelfClearingSignalGate();
+ // A local-GPU OOM kills the turn but leaves the TUI session holding the whole
+ // conversation, so it is nudged to carry on rather than re-prompted — see
+ // createOomNudgeGate for why this is a separate mechanism from the gate above.
+ const detectLocalRuntimeOom = createLocalRuntimeOomDetector();
+ const oomNudgeGate = createOomNudgeGate();
// 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.
@@ -1096,6 +1106,26 @@ export async function spawnTuiAgent({
return;
}
+ // A local inference runtime that ran out of GPU memory. The turn is dead
+ // but the session is intact, so this arms a nudge instead of killing the
+ // run — the provider-signal timer sends it once the session has actually
+ // gone quiet. Gated on promptSubmittedAt for the same reason
+ // resubmitAfterSignal is: before the prompt is in, there is no turn to
+ // resume and the ordinary paste path still owns first delivery.
+ const oomSignal = promptSubmittedAt ? detectLocalRuntimeOom(stripped) : null;
+ if (oomSignal) {
+ const armed = oomNudgeGate.arm(oomSignal, now);
+ if (armed === 'armed') {
+ appendLine('⏳ Local runtime out of GPU memory — will nudge the session to continue if it goes quiet');
+ } else if (armed === 'exhausted') {
+ // Nudged its way through OOM_NUDGE_MAX_ATTEMPTS and it came back
+ // again: the conversation no longer fits this device, and it only
+ // grows from here. Hand the task to a fallback provider.
+ await failOverToFallback(oomSignal);
+ return;
+ }
+ }
+
if (!promptSentAt) {
const lowerStripped = stripped.toLowerCase();
if (lowerStripped.includes('command not found') && lowerStripped.includes(commandName.toLowerCase())) {
@@ -1498,7 +1528,18 @@ export async function spawnTuiAgent({
emitLog('error', `TUI agent ${agentId} deferred fallback finish failed: ${err?.message || err}`, { agentId }));
return;
}
- if (selfClearingGate.armed) resubmitAfterSignal();
+ if (selfClearingGate.armed) {
+ resubmitAfterSignal();
+ 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().
+ const nudge = oomNudgeGate.takeNudge(Date.now(), lastOutputAt);
+ if (!nudge) return;
+ if (pasteController?.resubmit({ text: OOM_NUDGE_TEXT, label: 'local-runtime OOM nudge' })) {
+ appendLine(`🔁 Local runtime OOM — nudged the session to continue (attempt ${nudge}/${OOM_NUDGE_MAX_ATTEMPTS})`);
+ }
}, PROVIDER_SIGNAL_POLL_MS);
// Sentinel-file watcher. The agent's prompt instructs it to write
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 1916063608..82303ac7d9 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -230,6 +230,11 @@ import * as gitService from './git.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
import {
SELF_CLEARING_RESUBMIT_INTERVAL_MS,
+ OOM_NUDGE_SETTLE_MS,
+ OOM_NUDGE_ARM_WINDOW_MS,
+ OOM_NUDGE_COOLDOWN_MS,
+ OOM_NUDGE_MAX_ATTEMPTS,
+ OOM_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.
@@ -1404,6 +1409,97 @@ describe('spawnTuiAgent runtime', () => {
);
});
+ // ── Local-runtime GPU OOM: a nudge, not a verdict ──────────────────────────
+ // MLX/MTPLX kills a turn the server had already accepted, so unlike agy's
+ // banner the session still holds the whole conversation and the prompt must
+ // NOT be re-sent — a one-word `continue` resumes it, which is exactly what a
+ // human typed to rescue agent-011d0c27 on 2026-08-22.
+ const OOM_BOX = '│ {"message":"[METAL] Command buffer execution failed: Insufficient Memory\n'
+ + '│ (00000008: kIOGPUCommandBufferCallbackErrorOutOfMemory).","type":"server_error"}';
+
+ // Long enough for the arm's silence test AND the 5s provider-signal poll that
+ // acts on it.
+ const PAST_SETTLE_MS = OOM_NUDGE_SETTLE_MS + 10000;
+
+ it('nudges a session a local-GPU OOM left parked, without re-sending the prompt', async () => {
+ await driveAgyToSubmittedPrompt();
+ vi.mocked(shellService.pasteToSession).mockClear();
+
+ await capturedOnData(Buffer.from(OOM_BOX));
+ await flushMicrotasks();
+ // The error box is still repainting — nudging into that lands on chrome,
+ // not on an idle composer.
+ await vi.advanceTimersByTimeAsync(5000);
+ await flushMicrotasks();
+ expect(shellService.pasteToSession).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(PAST_SETTLE_MS);
+ await flushMicrotasks();
+ expect(shellService.pasteToSession).toHaveBeenCalledWith(
+ SESSION_ID,
+ OOM_NUDGE_TEXT,
+ expect.objectContaining({ label: expect.stringContaining('OOM') }),
+ );
+ // Exactly one nudge, and the run is left alone to carry on.
+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);
+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();
+ });
+
+ it('leaves a session that kept working after the OOM alone', async () => {
+ await driveAgyToSubmittedPrompt();
+ vi.mocked(shellService.pasteToSession).mockClear();
+
+ await capturedOnData(Buffer.from(OOM_BOX));
+ await flushMicrotasks();
+ // The TUI never goes quiet — it recovered on its own — so the arm has to
+ // expire rather than wait around to fire into the next quiet stretch.
+ for (let elapsed = 0; elapsed <= OOM_NUDGE_ARM_WINDOW_MS; elapsed += 5000) {
+ await capturedOnData(Buffer.from('still working\n'));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(5000);
+ await flushMicrotasks();
+ }
+ await vi.advanceTimersByTimeAsync(PAST_SETTLE_MS);
+ await flushMicrotasks();
+
+ expect(shellService.pasteToSession).not.toHaveBeenCalled();
+ });
+
+ it('falls back once the OOM outlasts every nudge', async () => {
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
+
+ await driveAgyToSubmittedPrompt();
+ vi.mocked(shellService.pasteToSession).mockClear();
+
+ for (let i = 0; i < OOM_NUDGE_MAX_ATTEMPTS; i += 1) {
+ await capturedOnData(Buffer.from(OOM_BOX));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(PAST_SETTLE_MS);
+ await flushMicrotasks();
+ // Clear the dedupe cooldown so the next box reads as a NEW OOM rather
+ // than a repaint of the one just nudged.
+ await vi.advanceTimersByTimeAsync(OOM_NUDGE_COOLDOWN_MS);
+ await flushMicrotasks();
+ }
+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(OOM_NUDGE_MAX_ATTEMPTS);
+
+ // The budget is spent and it OOM'd again: the conversation no longer fits
+ // this device, so the task goes to a fallback provider.
+ await capturedOnData(Buffer.from(OOM_BOX));
+ vi.useRealTimers();
+ await completeDone;
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ success: false,
+ completionReason: 'fallback-signal',
+ error: expect.stringContaining('GPU memory'),
+ })
+ );
+ });
+
// ── 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,