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
fix: remove TUI agent maximum runtime stop
Adam Eivy2c594832ad12
diff --git a/.changelog/next/fixed-agent-531e640a.md b/.changelog/next/fixed-agent-531e640a.mdnew file mode 100644index 0000000000..828dae3e1f--- /dev/null+++ b/.changelog/next/fixed-agent-531e640a.md@@ -0,0 +1 @@+- CoS TUI agents no longer have a wall-clock runtime limit and remain attached until their completion sentinel, process exit, or an explicit failure.diff --git a/.changelog/next/fixed-agent-64f9d496.md b/.changelog/next/fixed-agent-64f9d496.mdindex 57b3eb3e2b..18c00cbd79 100644--- a/.changelog/next/fixed-agent-64f9d496.md+++ b/.changelog/next/fixed-agent-64f9d496.md@@ -1 +1 @@-- CoS TUI agents no longer finalize or fail solely because provider output is idle; retain the wall-clock max-runtime backstop.+- CoS TUI agents no longer finalize or fail solely because provider output is idle; they stay attached until the completion sentinel, process exit, or explicit failure.diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 56d014c50a..92524fabd4 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -445,14 +445,9 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,{!inactive && (<span className={`px-2 py-0.5 text-xs rounded animate-pulse shrink-0 ${agent.metadata?.phase === 'initializing' ? 'bg-yellow-500/20 text-yellow-400' :- // Hit its max runtime and was asked to write its sentinel — it has- // minutes left before it's reaped, so say so rather than showing a- // reassuring "Working" right up to the kill.- agent.metadata?.phase === 'wrap-up' ? 'bg-orange-500/20 text-orange-400' :'bg-port-accent/20 text-port-accent'}`}>{agent.metadata?.phase === 'initializing' ? 'Initializing'- : agent.metadata?.phase === 'wrap-up' ? 'Wrapping up': 'Working'}</span>)}diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 5653ea76a1..ac6697a7f8 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -682,7 +682,7 @@ export default function AIProviders() {)}{isTuiProvider(provider) && (<p className="text-xs break-words">- TUI: paste delay <span className="text-gray-300">{provider.tuiPromptDelayMs || 2500}ms</span>, completion by sentinel, process exit, or runtime ceiling+ TUI: paste delay <span className="text-gray-300">{provider.tuiPromptDelayMs || 2500}ms</span>, completion by sentinel, process exit, or explicit failure</p>)}{provider.fallbackProvider && (@@ -1107,7 +1107,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAllo/></FormField><p className="sm:col-span-2 text-xs text-gray-500">- TUI providers stay attached while the provider is silent; they finish on the completion sentinel, process exit, explicit failure, or the max-runtime ceiling.+ TUI providers stay attached while the provider is silent; they finish on the completion sentinel, process exit, or explicit failure.</p></div>)}diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex a54c0748c2..6246f45a0b 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -565,10 +565,7 @@ export function createProviderService(config = {}) {envVars: providerData.envVars || {},secretEnvVars: providerData.secretEnvVars || [],headlessArgs: providerData.headlessArgs || [],- tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500,- // Absolute wall-clock ceiling for long-running TUI agents (3h). The- // consumer (agentTuiSpawning) enforces this backstop.- tuiMaxRuntimeMs: providerData.tuiMaxRuntimeMs || 10800000+ tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500};data.providers[id] = provider;diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex 0aa0440d39..56b833de2f 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -108,10 +108,7 @@ export const providerSchema = z.object({envVars: z.record(z.string()).optional(),secretEnvVars: z.array(z.string()).optional(),headlessArgs: z.array(z.string()).optional(),- tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),- // Absolute wall-clock ceiling for a long-running TUI agent. Min 1min, max 12h- // to cover the longest legitimate multi-hour orchestration.- tuiMaxRuntimeMs: z.number().int().min(60000).max(43200000).optional()+ tuiPromptDelayMs: z.number().int().min(250).max(60000).optional()});// PUT /api/providers/active — set the active provider by id. Constrain to thediff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 3f1417ed85..6e4d931830 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -684,60 +684,6 @@ export function scheduleSubmitEnters(write, isFinalized) {// per-provider prompt timing values (provider.tuiPromptDelayMs).export const DEFAULT_TUI_PROMPT_DELAY_MS = 2500;-// Absolute wall-clock ceiling for a long-running TUI agent, applied from prompt-// submission. CoS agents intentionally have no output-idle completion/reap: a-// slow provider may be silent while it works. This ceiling is the remaining-// automatic backstop for a genuinely wedged provider/CLI and is configurable via-// `tuiMaxRuntimeMs`.-export const DEFAULT_TUI_MAX_RUNTIME_MS = 3 * 60 * 60 * 1000;--// Grace window opened when the max-runtime ceiling fires, BEFORE the agent is-// reaped. The ceiling above is a wall-clock deadline, so it lands wherever it-// lands — including on an agent that is seconds from writing `.agent-done`.-// Measured (2026-07-27, agent-d2ae0352): its PR merged at 01:32:29 and the-// max-runtime timer killed it at 01:32:59 — 30 SECONDS later. The run was-// complete; it just hadn't written the sentinel yet. The kill deleted the-// worktree, and CoS re-dispatched the task to a fresh agent that started the-// (already-shipped) work over from scratch.-//-// So instead of reaping on the deadline, we PROD the agent — paste a "wrap up-// and write your sentinel now" message into its live TUI (the same-// bracketed-paste channel `sendBtwToAgent` uses) — and keep polling for the-// sentinel for this long before failing. An agent that was genuinely finishing-// gets to land its summary and finalize as a SUCCESS; a truly hung one is-// unaffected and still reaped, just this much later. 5 minutes covers a-// Claude Code turn that has to finish a tool call, run its completion workflow,-// and write the file, without meaningfully loosening the ceiling.-export const MAX_RUNTIME_WRAP_UP_GRACE_MS = 5 * 60 * 1000;--/**- * The wrap-up prod pasted into a TUI agent's session when its max-runtime- * ceiling fires. Deliberately imperative and short: the agent is mid-turn on a- * provider that may itself be slow, so the message has to be actionable in one- * read. It names the sentinel path convention rather than an absolute path —- * the agent already knows its own workspace from its system prompt.- *- * Both arguments are REQUIRED, deliberately: `graceMs` is interpolated so the- * deadline the agent is told matches the one actually enforced (a drift there- * would promise it more time than it has, and it would be reaped mid-wrap-up),- * and `sentinelName` is the caller's per-agent filename (`doneSentinelName`).- * A default for either would be a silently-wrong instruction on the one message- * whose whole job is telling an about-to-be-reaped agent where to write.- */-export function buildWrapUpProdMessage(graceMs, sentinelName) {- const minutes = Math.max(1, Math.round(graceMs / 60000));- return [- `STOP — you have hit your maximum runtime and will be terminated in ${minutes} minute(s).`,- '',- 'If your work is already shipped (PR opened/merged, or changes committed and pushed),',- `write your \`${sentinelName}\` sentinel in your workspace root RIGHT NOW with a short summary`,- 'so this run is recorded as a success. Do not start anything new.',- '',- 'If the work is NOT shipped, commit whatever is worth keeping to your branch, push it,',- `and then write \`${sentinelName}\` describing exactly what is done and what is left.`,- ].join('\n');-}-// ─── Codex MCP-server boot detection ──────────────────────────────────────//diff --git a/server/lib/validation.js b/server/lib/validation.jsindex c4f34454e9..064c250c8a 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -416,10 +416,7 @@ export const providerSchema = z.object({allowCustomEndpoint: z.boolean().optional(),envVars: z.record(z.string()).optional(),headlessArgs: z.array(z.string()).optional(),- tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),- // Absolute wall-clock ceiling for long-running TUI agents (mirrors the- // aiToolkit providerSchema). Min 1min, max 12h.- tuiMaxRuntimeMs: z.number().int().min(60000).max(43200000).optional()+ tuiPromptDelayMs: z.number().int().min(250).max(60000).optional()});// Run command schemadiff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 1435ef73b3..426525fae6 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -686,16 +686,16 @@ function resolvePatternOrigin(errorDef, analysisOutput) {* Runner-resolved completion reasons → the failure they actually describe.** When the spawner's own finalize path already KNOWS why a run ended (a legacy- * idle reaper fired, max runtime elapsed, or the shell session never came up),- * that is a structural signal about the process — strictly better evidence than a regex+ * forced-stop was applied, or the shell session never came up), that is a+ * structural signal about the process — strictly better evidence than a regex* sweep over the transcript. Keyed by the `reason` each `finish()` call passes;* see `server/services/agentTuiSpawning.js`. Categories are deliberately reused* from ERROR_PATTERNS so downstream taxonomies (task-learning metrics,* layeredIntelligenceExecutionFailures) keep classifying them without a new token.*/-// Legacy idle-out reasons remain readable for archived agent records and retries;-// the current CoS TUI path completes by sentinel, process exit, explicit provider-// failure, or its wall-clock runtime ceiling.+// Legacy idle-out and forced-stop reasons remain readable for archived agent+// records and retries; the current CoS TUI path completes by sentinel, process+// exit, or explicit provider failure.export const COMPLETION_REASON_ANALYSES = {'idle-no-changes': {category: 'no-changes',@@ -760,18 +760,16 @@ export const COMPLETION_REASON_ANALYSES = {'max-runtime-timeout': {category: 'timeout',actionable: false,- message: 'Agent exceeded its maximum runtime',- suggestedFix: 'Task took longer than the configured max runtime. Break it into smaller subtasks or raise the runtime budget.'+ message: 'Agent was stopped by a retired maximum-runtime limit',+ suggestedFix: 'This result came from an older PortOS runtime guard; current CoS TUI agents have no wall-clock runtime ceiling.'},- // Distinct from the bare ceiling above: this agent was explicitly ASKED to wrap- // up and write its sentinel (see MAX_RUNTIME_WRAP_UP_GRACE_MS) and never did, so- // "raise the runtime budget" is the wrong advice — a session that can't answer a- // direct prompt in five minutes is wedged, not merely slow.+ // Historical counterpart for runs that were asked to wrap up during the+ // retired wall-clock guard and never did.'max-runtime-no-wrap-up': {category: 'timeout',actionable: false,- message: 'Agent did not wrap up when asked at its max runtime',- suggestedFix: 'The agent was asked to write its completion sentinel and did not respond within the grace window — its provider/CLI is likely wedged rather than merely slow. Check the raw transcript for a stalled request, and check for open or merged-but-uncleaned PRs it left behind.'+ message: 'Agent was stopped by a retired maximum-runtime wrap-up limit',+ suggestedFix: 'This result came from an older PortOS runtime guard; current CoS TUI agents have no wall-clock runtime ceiling.'},// The PTY was terminated by a signal rather than exiting on its own — almost// always pm2's TreeKill taking portos-server's descendants down with it on adiff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 7548a03e89..2d73f215b8 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -54,14 +54,14 @@ PortOS runs MANY apps under one shared pm2 daemon. To restart an app, use a SCOP// Also appended to every agent briefing. A CoS agent runs headless: the TUI has// no human attached, so an interactive selector or approval gate is a dead end —-// the session can sit there until its wall-clock runtime ceiling and the work is-// discarded. Nothing in the briefing used to SAY that, so a `/do:plan-task` run-// (whose skill shows its drafted issue for approval before filing) parked on a-// scope question for its whole life and was retried into the same gate three-// times, filing nothing. The rule names the escape hatch too: slash commands-// that gate on approval take a flag to skip it.+// the session can sit there indefinitely and the work may never complete.+// Nothing in the briefing used to SAY that, so a `/do:plan-task` run (whose+// skill shows its drafted issue for approval before filing) parked on a scope+// question for its whole life and was retried into the same gate three times,+// filing nothing. The rule names the escape hatch too: slash commands that gate+// on approval take a flag to skip it.export const UNATTENDED_RUN_RULE = `## ⚠️ Unattended Run (no human is present)-PortOS launched you autonomously. Nobody is watching this session and nothing can answer you — if you present an interactive choice (a multiple-choice question, an approval gate, a "which option?" selector, a confirmation), the session can sit there until its runtime ceiling and **your work may be thrown away**.+PortOS launched you autonomously. Nobody is watching this session and nothing can answer you — if you present an interactive choice (a multiple-choice question, an approval gate, a "which option?" selector, a confirmation), the session can wait indefinitely and **your work may never complete**.- **Never ask the user to choose or approve.** Make the call yourself, state the assumption in your summary, and proceed.- **Invoke commands and skills in their non-interactive form.** If one drafts something and gates on approval before acting, pass the flag that skips that gate (\`--yes\` for the slashdo commands that have one).- **Ambiguous task?** Pick the most reasonable reading, do the work, and note the alternatives you rejected in your completion summary.@@ -1324,9 +1324,9 @@ export function buildProgrammaticOutputCompletionSection(sentinelPath) {* A TUI agent still needs a `.agent-done` sentinel to signal completion — the 2s* sentinel poll in `spawnTuiAgent` is the primary finalize path and the channel* that ingests the run summary. Without it a read-only TUI run relies on shell- * exit or the runtime ceiling, so the resolution summary is not captured- * cleanly (the bug this repairs). CLI/API read-only agents complete on- * process exit and never poll a sentinel, so they get the bare notice only.+ * exit, so the resolution summary is not captured cleanly (the bug this+ * repairs). CLI/API read-only agents complete on process exit and never poll a+ * sentinel, so they get the bare notice only.*/export function buildReadOnlyCompletionSection({ isTui = false, sentinelPath = null } = {}) {const notice = '## Read-Only Task\nDo NOT commit, push, or modify any files. Read data and report findings only.';diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 79583c1009..03d6f23778 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -13,7 +13,7 @@ import * as shellService from './shell.js';import { emitLog } from './cosEvents.js';import { updateAgent } from './cosAgentLifecycle.js';import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';-import { captureWorktreeDiff, resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';+import { resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { activeAgents, userTerminatedAgents, pausedAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';@@ -34,9 +34,6 @@ import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetimport { isAntigravityCommand } from '../lib/antigravity.js';import {DEFAULT_TUI_PROMPT_DELAY_MS,- DEFAULT_TUI_MAX_RUNTIME_MS,- MAX_RUNTIME_WRAP_UP_GRACE_MS,- buildWrapUpProdMessage,READY_POLL_INTERVAL_MS,READY_IDLE_THRESHOLD_MS,PASTE_MARKER_POLL_MS,@@ -73,14 +70,14 @@ import { execFile } from '../lib/childProcess.js';const PROVIDER_SIGNAL_POLL_MS = 5000;// Output buffering/spooling (createOutputSpooler) and failure-analysis /-// worktree-inspection helpers (captureWorktreeDiff, resolveErrorAnalysis,+// worktree-inspection and failure-analysis helpers (resolveErrorAnalysis,// RAW_TAIL_ANALYSIS_BYTES) live in// ./agentTuiSpawning/ so spawnTuiAgent stays a thin orchestrator.// Sentinel-file polling. TUI agents write `.agent-done` in their workspace// when they've finished /simplify + /do:pr (or /do:push) — we poll for it// here so the agent gets cleanly finalized as soon as the work is done,-// without waiting for a runtime ceiling or a shell exit.+// without waiting for a shell exit.// The filename is per agent instance — see doneSentinelName in ../lib/agentSentinel.js.const DONE_POLL_INTERVAL_MS = 2000;@@ -221,27 +218,23 @@ export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null,command,args,commandLine: [command, ...args].map(shellQuote).join(' '),- promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS,- maxRuntimeMs: provider?.tuiMaxRuntimeMs || DEFAULT_TUI_MAX_RUNTIME_MS+ promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS};}-// Paste + submit-Enter + max-runtime retry machinery for spawnTuiAgent's+// Paste + submit-Enter retry machinery for spawnTuiAgent's// prompt delivery. Separated from spawnTuiAgent so retries don't re-run the// liveness guard or re-set the outer promptSentAt (see `sendPrompt` below) —// the cluster spawnTuiAgent's own comments already described as one cohesive// concern. Owns the paste-attempt counter, the post-paste accumulator, the-// paste-marker/verify timers, the submit-Enter backstop timer, the-// max-runtime wall-clock timer, and the wrap-up grace window it opens instead-// of reaping immediately.+// paste-marker/verify timers, and the submit-Enter backstop timer.//// `isFinalized`/`markPromptSent`/`markPromptSubmitted` are accessors into// spawnTuiAgent's own `finalized`/`promptSentAt`/`promptSubmittedAt` — those// are read by handleData and the provider-signal timer well outside this// cluster, so they stay owned by spawnTuiAgent and are threaded through rather-// than duplicated here. `finish`/`finishStartupFailure`/`appendLine`/-// `sentinelPresent` are likewise spawnTuiAgent's own closures, passed in-// rather than re-implemented.+// than duplicated here. `finishStartupFailure`/`appendLine` are likewise+// spawnTuiAgent's own closures, passed in rather than re-implemented.function createPasteRetryController({agentId,sessionId,@@ -249,15 +242,11 @@ function createPasteRetryController({useDurableRunner,prompt,tuiConfig,- cwd,- agentDir,mcpBoot,appendLine,- sentinelPresent,isFinalized,markPromptSent,markPromptSubmitted,- finish,finishStartupFailure,}) {// Markers already present in the prompt text itself (a transcript-analysis task@@ -282,14 +271,6 @@ function createPasteRetryController({let pasteEnterTimer = null;let pasteVerifyTimer = null;let submitEnterTimer = null;- // Absolute wall-clock backstop — armed once the prompt is SUBMITTED, cleared- // by cancel(). This bounds the total run so a hung provider/CLI can't run- // unbounded. See DEFAULT_TUI_MAX_RUNTIME_MS for the incident.- let maxRuntimeTimer = null;- // Deadline for the wrap-up grace window the max-runtime ceiling opens instead of- // reaping immediately (see MAX_RUNTIME_WRAP_UP_GRACE_MS). Cleared by cancel()- // alongside every other timer.- let wrapUpTimer = null;let pasteAttempt = 0;// Wall-clock of the FIRST paste attempt — the anchor for the MCP-boot-aware// retry deadline (retries are time-bounded, not attempt-count-bounded, while@@ -335,84 +316,6 @@ function createPasteRetryController({return !!handle;};- // Reap the run as a max-runtime failure. Shared by the wrap-up grace window's- // expiry and its own "session already died" branch so both produce the same- // record: uncommitted work captured for post-mortem, then a- // needs-manual-finish error (the same recovery guidance as any stalled- // orchestrator — it may have left- // PRs/worktrees behind).- const finishMaxRuntimeFailure = (detail, reason = 'max-runtime-timeout') => {- captureWorktreeDiff(cwd, agentDir).catch(() => {});- finish({- success: false,- exitCode: 124,- error: `TUI agent exceeded its max runtime of ${Math.round(tuiConfig.maxRuntimeMs / 60000)}min — ${detail} check for open or merged-but-uncleaned PRs and finish them manually.`,- reason,- }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId} at max-runtime: ${err.message}`, { agentId });- });- };-- // Max-runtime wrap-up grace: prod the agent to land its sentinel, then watch- // for it before reaping (see MAX_RUNTIME_WRAP_UP_GRACE_MS). The prod goes in- // over the same bracketed-paste + delayed-Enter channel `sendBtwToAgent` uses,- // so from the agent's side it is indistinguishable from the user typing it.- //- // Success here finalizes through the ordinary sentinel path — we do NOT call- // finish() ourselves on the happy path, because the 2s doneSentinelTimer is- // still running and owns that transition; racing it would just be a second- // caller into the same `finalized` guard. This poll exists to bound the WAIT- // and to reap when the prod doesn't work.- const startWrapUpGrace = () => {- if (isFinalized() || wrapUpTimer) return;- // A dead session can't be prodded — nothing will ever write the sentinel, so- // skip the grace window rather than waiting out the full 5min.- if (!sessionId || !shellService.getSession(sessionId)) {- finishMaxRuntimeFailure('the TUI session was already gone, so it could not be asked to wrap up;');- return;- }- const graceMin = Math.round(MAX_RUNTIME_WRAP_UP_GRACE_MS / 60000);- appendLine(`⏳ Max runtime reached — asking the agent to wrap up and write its sentinel (${graceMin}min grace)`);- emitLog('warn', `TUI agent ${agentId} hit max runtime — prodding it to wrap up with ${graceMin}min of grace before reaping`, { agentId, phase: 'wrap-up' });- updateAgent(agentId, { metadata: { phase: 'wrap-up' } }).catch(err => {- emitLog('warn', `Failed to mark TUI agent ${agentId} as wrapping up: ${err.message}`, { agentId });- });-- // Clear any prior submit-Enter interval first: hours after submission the- // prompt's own is long finished, but overwriting a live handle would leak- // it past finish().- if (submitEnterTimer) clearInterval(submitEnterTimer);- submitEnterTimer = shellService.pasteToSession(- sessionId,- // The agent's OWN sentinel name — the bare `.agent-done` is a path no- // poller is watching.- buildWrapUpProdMessage(MAX_RUNTIME_WRAP_UP_GRACE_MS, doneSentinelName(agentId)),- { label: '[cosAgents] max-runtime wrap-up' },- );-- // A single deadline, NOT a poll: the 2s doneSentinelTimer is already watching- // this exact path at this exact cadence and owns the success transition (and- // cancel() clears this handle), so polling here would just double the- // existsSync syscalls for 5 minutes to learn something the other timer acts on- // first. All this needs to do is fire once at the end of the window.- wrapUpTimer = setTimeout(() => {- try {- wrapUpTimer = null;- if (isFinalized()) return;- // The sentinel landed right at the boundary — the prod worked after all.- // Let the sentinel path finalize it as the success it is.- if (sentinelPresent()) return;- finishMaxRuntimeFailure(- `it did not wrap up within ${graceMin}min of being asked, so the provider/CLI likely hung (the wall-clock ceiling is the remaining backstop);`,- 'max-runtime-no-wrap-up',- );- } catch (err) {- // setTimeout callback: an uncaught throw here would crash the process.- console.error(`❌ wrapUpTimer callback failed: ${err.message}`);- }- }, MAX_RUNTIME_WRAP_UP_GRACE_MS);- };-const sendPrompt = async (reason) => {if (isFinalized() || sent) return;sent = true;@@ -470,38 +373,6 @@ function createPasteRetryController({() => shellService.writeToSession(sessionId, '\r'),() => isFinalized());- // Arm the absolute wall-clock backstop from submission (once — a paste- // retry re-enters submitEnter but must not stack timers). This timer is- // the ceiling regardless of how much or how little PTY output arrives.- if (!maxRuntimeTimer) {- maxRuntimeTimer = setTimeout(() => {- try {- if (isFinalized()) return;- // Salvage net: if the agent already wrote its .agent-done sentinel the- // run truly finished (the TUI just never wrote the sentinel/exited), so complete as- // success — mirrors the one-shot runner's response-file salvage. The- // 2s doneSentinelTimer normally catches this first; this covers the- // boundary where it lands right at the deadline.- if (sentinelPresent()) {- finish({ success: true, exitCode: 0, reason: 'max-runtime-sentinel' }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId} at max-runtime salvage: ${err.message}`, { agentId });- });- return;- }- // No sentinel yet — but a wall-clock deadline lands wherever it lands,- // including on an agent seconds from writing one (see- // MAX_RUNTIME_WRAP_UP_GRACE_MS for the measured 30s miss). PROD it to- // wrap up and keep watching for the sentinel through the grace window- // before reaping. Only then does this become a real failure.- startWrapUpGrace();- } catch (err) {- // setTimeout callback: an uncaught throw here (e.g. a PTY write racing- // a dead session) would crash the whole process, killing every other- // in-flight agent, not just this one.- console.error(`❌ maxRuntimeTimer callback failed: ${err.message}`);- }- }, tuiConfig.maxRuntimeMs);- }};// Confirms the TUI actually received the paste before we submit. The@@ -631,8 +502,6 @@ function createPasteRetryController({if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }if (pasteVerifyTimer) { clearInterval(pasteVerifyTimer); pasteVerifyTimer = null; }if (submitEnterTimer) { clearInterval(submitEnterTimer); submitEnterTimer = null; }- if (maxRuntimeTimer) { clearTimeout(maxRuntimeTimer); maxRuntimeTimer = null; }- if (wrapUpTimer) { clearTimeout(wrapUpTimer); wrapUpTimer = null; }postPasteBuffer = null;};@@ -671,7 +540,7 @@ export async function spawnTuiAgent({// the sentinel watcher below) and then stops — it does NOT run `/quit` (that// is a UI command the agent can't invoke). The 2s poll is the primary// finalize path; finish() also ingests the sentinel directly so the summary- // is captured even if some other path (shell exit/max-runtime) finalizes first. Computed+ // is captured even if some other path (shell exit) finalizes first. Computed// up front so both the watcher AND finish() can read it (see ingestDoneSentinel).// Resolved from the shared helper, so this is byte-identical to the path the// prompt told the agent to write (see resolveSentinelPath).@@ -744,10 +613,10 @@ export async function spawnTuiAgent({// only as a recovery path, never duplicated into raw.txt.let receivedTuiOutput = false;- // The paste-attempt / max-runtime / wrap-up-grace machinery (postPasteBuffer,- // pasteEnterTimer, pasteVerifyTimer, submitEnterTimer, maxRuntimeTimer,- // wrapUpTimer) lives in createPasteRetryController rather than this closure- // — see its own comment for why that cluster is separated out.+ // The paste-attempt / submit-Enter machinery (postPasteBuffer, pasteEnterTimer,+ // pasteVerifyTimer, submitEnterTimer) lives in createPasteRetryController+ // rather than this closure — see its own comment for why that cluster is+ // separated out.// `pasteController` is created once sessionId/pid are known (below) and torn// down from stopRunMachinery via `pasteController?.cancel()`.let pasteController = null;@@ -769,10 +638,9 @@ export async function spawnTuiAgent({// finalize chokepoint); idempotent via `sentinelIngested` so it reads at most// once. Capped at 4 KB so an agent that pasted the whole diff into the// sentinel can't blow up the record.- // Has the agent written its completion sentinel? One predicate for every path- // that asks (the 2s watcher, the max-runtime salvage, the wrap-up grace poll,- // and ingestDoneSentinel) so "the run finished" can't mean subtly different- // things in four places.+ // Has the agent written its completion sentinel? One predicate for the 2s+ // watcher and ingestDoneSentinel so "the run finished" can't mean subtly+ // different things in two places.const sentinelPresent = () => !!doneSentinelPath && existsSync(doneSentinelPath);const ingestDoneSentinel = async () => {@@ -805,17 +673,16 @@ export async function spawnTuiAgent({* Shared by the two paths that end a run — `finish()` (records an outcome) and* `abandonForHostShutdown()` (records none). Every timer here is created inside* this closure, so a teardown site that falls behind leaks an interval holding- * the closure and the PTY handle alive; this file has already grown two new- * timers since it was written (maxRuntime + wrapUp), which is exactly the drift- * a single teardown prevents.+ * the closure and the PTY handle alive, which is exactly the drift a single+ * teardown prevents.*/const stopRunMachinery = () => {const agentData = activeAgents.get(agentId);if (agentData?.providerSignalTimer) clearInterval(agentData.providerSignalTimer);if (agentData?.promptTimer) clearInterval(agentData.promptTimer);if (agentData?.doneSentinelTimer) clearInterval(agentData.doneSentinelTimer);- // Cancels the paste-attempt/max-runtime/wrap-up timers and releases the- // post-paste accumulator even when the run ends mid-paste-window — see+ // Cancels the paste-attempt timers and releases the post-paste accumulator+ // even when the run ends mid-paste-window — see// createPasteRetryController's own cancel() for why each is safe to clear// unconditionally (a run that ends from elsewhere — shell-exit,// command-not-found, user termination, a host restart — never gets a@@ -856,8 +723,8 @@ export async function spawnTuiAgent({// lands in outputBuffer/output.txt regardless of WHICH path finalized the// agent. The completion workflow writes the sentinel and stops; the 2s// doneSentinelTimer poll is what normally calls finish(). Reading it here- // (not just in the poll) keeps the resolution captured even when a- // different path (shell-exit, max-runtime) finalizes first. Idempotent+ // (not just in the poll) keeps the resolution captured even when shell exit+ // finalizes first. Idempotent// via `sentinelIngested`.await ingestDoneSentinel();@@ -1375,8 +1242,8 @@ export async function spawnTuiAgent({});};- // Owns the paste-attempt counter, the post-paste accumulator, the paste- // timers and the max-runtime/wrap-up machinery — see+ // Owns the paste-attempt counter, the post-paste accumulator, and the paste+ // timers — see// createPasteRetryController's own comment for why that cluster lives// outside this closure. `isFinalized`/`markPromptSent`/`markPromptSubmitted`// are accessors into THIS closure's `finalized`/`promptSentAt`/@@ -1389,15 +1256,11 @@ export async function spawnTuiAgent({useDurableRunner,prompt,tuiConfig,- cwd,- agentDir,mcpBoot,appendLine,- sentinelPresent,isFinalized: () => finalized,markPromptSent: () => { promptSentAt = Date.now(); },markPromptSubmitted: () => { if (promptSubmittedAt === null) promptSubmittedAt = Date.now(); },- finish,finishStartupFailure,});@@ -1518,8 +1381,8 @@ export async function spawnTuiAgent({// INTERVAL_MS of the sentinel appearing, and finish()'s own cleanup kills// the still-running TUI session. The actual sentinel READ happens in finish()// (via ingestDoneSentinel) so the resolution is captured no matter which path- // finalizes. A normal shell exit, explicit provider failure, or max-runtime- // wrap-up handles agents that do not write the sentinel.+ // finalizes. A normal shell exit or explicit provider failure handles agents+ // that do not write the sentinel.const doneSentinelTimer = doneSentinelPath ? setInterval(() => {try {if (finalized) return;@@ -1561,7 +1424,6 @@ export async function spawnTuiAgent({tuiSessionId: sessionId,tuiCommand: tuiConfig.commandLine,tuiKind,- tuiMaxRuntimeMs: tuiConfig.maxRuntimeMs}});diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex eaac65aa62..186f354992 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -209,7 +209,6 @@ import * as cosAgentLifecycle from './cosAgentLifecycle.js';import * as gitService from './git.js';import { activeAgents, userTerminatedAgents } from './agentState.js';import {- MAX_RUNTIME_WRAP_UP_GRACE_MS,SELF_CLEARING_RESUBMIT_INTERVAL_MS,} from '../lib/tuiHandshake.js';// Real module, not a mock: the flag is a plain process-local boolean, so driving@@ -317,7 +316,7 @@ describe('agent TUI spawning', () => {expect(config.args).toEqual(['--dangerously-skip-permissions']);});- it('quotes TUI arguments and carries prompt/runtime timing config', () => {+ it('quotes TUI arguments and carries prompt timing config without a runtime limit', () => {const config = buildTuiSpawnConfig({id: 'claude-code-tui',name: 'Claude TUI',@@ -337,7 +336,7 @@ describe('agent TUI spawning', () => {]);expect(config.commandLine).toBe("claude --dangerously-skip-permissions --add-dir '/tmp/with space' --model claude-sonnet");expect(config.promptDelayMs).toBe(1000);- expect(config.maxRuntimeMs).toBe(7200000);+ expect(config).not.toHaveProperty('maxRuntimeMs');expect(config).not.toHaveProperty('idleTimeoutMs');});@@ -365,10 +364,10 @@ describe('agent TUI spawning', () => {expect(claudeConfig.command).toBe('claude');});- it('applies default prompt delay and max runtime when the provider omits them', () => {+ it('applies the default prompt delay and omits a runtime limit', () => {const config = buildTuiSpawnConfig({ id: 'codex-tui', command: 'codex', type: 'tui' }, null);expect(config.promptDelayMs).toBe(2500);- expect(config.maxRuntimeMs).toBe(10800000);+ expect(config).not.toHaveProperty('maxRuntimeMs');expect(config).not.toHaveProperty('idleTimeoutMs');});@@ -480,9 +479,6 @@ describe('spawnTuiAgent runtime', () => {args: [],commandLine: 'codex',promptDelayMs: 100,- // Large so the wall-clock backstop never fires during the modest fake-timer- // advances the paste/handshake tests perform (the max-runtime test overrides it).- maxRuntimeMs: 3600000};function runSpawn(overrides = {}) {@@ -830,173 +826,53 @@ describe('spawnTuiAgent runtime', () => {);});- // ── Absolute wall-clock backstop reaps a busy-or-silent stuck agent ──────────- // The max-runtime timer fires from submission- // regardless of PTY chatter and, with no .agent-done sentinel present,- // finalizes as a needs-manual-finish FAILURE.- it('max-runtime: reaps a still-chattering agent as failure once the wall-clock ceiling elapses', async () => {+ // ── No wall-clock stop ─────────────────────────────────────────────────────+ // A provider can legitimately spend more than a day on one task. Advancing+ // well past the old three-hour ceiling must not send a wrap-up prompt or+ // finalize the agent; completion remains sentinel-, exit-, or failure-driven.+ it('keeps a submitted OpenCode agent attached beyond 24 hours', async () => {let resolveComplete;const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- runSpawn({ tuiConfig: { ...defaultTuiConfig, maxRuntimeMs: 30000 } });+ const spawnPromise = runSpawn({+ provider: { ...defaultProvider, id: 'opencode-tui', name: 'OpenCode TUI' },+ tuiConfig: { ...defaultTuiConfig, command: 'opencode', commandLine: 'opencode' },+ });await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));+ await capturedOnData(Buffer.from('OpenCode booting...\n'));await flushMicrotasks();await vi.advanceTimersByTimeAsync(2000);await flushMicrotasks();-- // Prompt echo → paste verification passes → submit-Enter fires → the- // max-runtime timer is armed.await capturedOnData(Buffer.from('do the thing\n'));await flushMicrotasks();await vi.advanceTimersByTimeAsync(3600);await flushMicrotasks();- // A busy agent that keeps chattering still reaches the same wall-clock ceiling.- await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(31000);+ await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000);await flushMicrotasks();- // The ceiling PRODS rather than reaping (#3167): it pastes a wrap-up message- // and opens a grace window, so the agent is NOT finalized yet.expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();- expect(shellService.pasteToSession).toHaveBeenCalledWith(+ expect(shellService.pasteToSession).not.toHaveBeenCalledWith(SESSION_ID,- expect.stringContaining('you have hit your maximum runtime'),+ expect.anything(),{ label: '[cosAgents] max-runtime wrap-up' },);- // No sentinel ever appears → the grace window expires → NOW it reaps.- await vi.advanceTimersByTimeAsync(MAX_RUNTIME_WRAP_UP_GRACE_MS + 2000);- await flushMicrotasks();-+ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;vi.useRealTimers();await completeDone;- // Reaped under the DISTINCT reason: it was asked to wrap up and didn't, which- // means a wedged provider — not "raise the runtime budget".expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({agentId: 'agent-1',- success: false,- completionReason: 'max-runtime-no-wrap-up',+ success: true,+ completionReason: 'shell-exit',}));});- // The whole point of the grace window: an agent that was SECONDS from writing- // its sentinel when the ceiling landed must finalize as a SUCCESS, not be- // reaped. This is the agent-d2ae0352 shape (PR merged 01:32:29, killed- // 01:32:59) that made a fresh agent redo already-shipped work.- it('max-runtime: an agent that wraps up during the grace window finalizes as success', async () => {- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- runSpawn({ tuiConfig: { ...defaultTuiConfig, maxRuntimeMs: 30000 } });- await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();-- // Ceiling fires → prod + grace window, no finalize.- await vi.advanceTimersByTimeAsync(31000);- await flushMicrotasks();- expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();-- // The prod works: the agent writes .agent-done well inside the grace window.- vi.mocked(existsSync).mockReturnValue(true);- await vi.advanceTimersByTimeAsync(4000);- await flushMicrotasks();-- vi.useRealTimers();- await completeDone;-- // Finalized as a SUCCESS via the ordinary sentinel path — never reaped.- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ agentId: 'agent-1', success: true })- );- expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalledWith(- expect.objectContaining({ completionReason: 'max-runtime-timeout' })- );- });-- // A dead session can't be prodded, so the grace window is pointless — reap- // immediately rather than idling the full window for a message nobody reads.- it('max-runtime: reaps immediately (no grace) when the TUI session is already gone', async () => {- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- runSpawn({ tuiConfig: { ...defaultTuiConfig, maxRuntimeMs: 30000 } });- await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();-- // Session died before the ceiling landed.- vi.mocked(shellService.getSession).mockReturnValue(null);- await vi.advanceTimersByTimeAsync(31000);- await flushMicrotasks();-- vi.useRealTimers();- await completeDone;-- // Never prodded, so this keeps the plain-ceiling reason (not no-wrap-up).- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: false, completionReason: 'max-runtime-timeout' })- );- });-- // ── 1d. A written .agent-done sentinel is never overridden by a FAILURE reap ─- // If the agent wrote .agent-done, the run truly finished — the max-runtime- // ceiling firing would be a false failure. The 2s sentinel poll normally- // finalizes it as success first; the max-runtime timer's own salvage branch- // (existsSync check) is the boundary backstop mirroring the one-shot runner's- // response-file salvage. Either way, with the sentinel present the run must- // finalize as SUCCESS — never as a max-runtime FAILURE.- it('max-runtime does not fail a run whose .agent-done sentinel exists', async () => {- vi.mocked(existsSync).mockReturnValue(true);-- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- runSpawn({ tuiConfig: { ...defaultTuiConfig, maxRuntimeMs: 30000 } });- await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();-- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();-- vi.useRealTimers();- await completeDone;-- const call = vi.mocked(agentLifecycle.finalizeAgent).mock.calls.at(-1)?.[0];- expect(call?.success).toBe(true);- expect(call?.completionReason).not.toBe('max-runtime-timeout');- });-// ── 1b. Command exited before the prompt → don't paste into the bare shell ───// The TUI command (claude/codex/…) runs as a CHILD of the persistent PTY// shell, so if it exits at startup the PTY stays open and onExit never fires.@@ -1043,12 +919,9 @@ describe('spawnTuiAgent runtime', () => {});// ── 1c. claude waits for bracketed-paste mode (input ready) before pasting ───- const claudeTuiConfig = { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100, maxRuntimeMs: 3600000 };+ const claudeTuiConfig = { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100 };// Antigravity (agy) gets the SAME positive input-ready gate as claude (#2705).- // maxRuntimeMs is explicit for the same reason defaultTuiConfig pins it: left- // undefined, the wall-clock backstop is a `setTimeout(…, undefined)` that fires- // on the next tick and prods every one of these runs to wrap up.- const agyTuiConfig = { command: 'agy', args: [], commandLine: 'agy', promptDelayMs: 100, maxRuntimeMs: 3600000 };+ const agyTuiConfig = { command: 'agy', args: [], commandLine: 'agy', promptDelayMs: 100 };const pasteCount = () => vi.mocked(shellService.writeToSession).mock.calls.filter(([, d]) => typeof d === 'string' && d.includes('\x1b[200~')).length;// The launch shell turns bracketed-paste OFF to run the command, then claude@@ -1567,7 +1440,7 @@ describe('spawnTuiAgent runtime', () => {const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- runSpawn({ tuiConfig: { command: 'gemini', args: [], commandLine: 'gemini', promptDelayMs: 100, maxRuntimeMs: 3600000 } });+ runSpawn({ tuiConfig: { command: 'gemini', args: [], commandLine: 'gemini', promptDelayMs: 100 } });await flushMicrotasks();// Same banner text codex prints — but this is a gemini session.await capturedOnData(Buffer.from('Starting MCP servers (0/3): a, b, c\n'));diff --git a/server/services/agentTuiSpawning/finalizeHelpers.js b/server/services/agentTuiSpawning/finalizeHelpers.jsindex edbcefb2ff..db9e0d783a 100644--- a/server/services/agentTuiSpawning/finalizeHelpers.js+++ b/server/services/agentTuiSpawning/finalizeHelpers.js@@ -76,10 +76,11 @@ export async function captureWorktreeDiff(workspacePath, agentDir) {* short-circuits the analysis entirely.** `completionReason` / `completionError` carry the finalize path's OWN verdict- * (legacy idle-reaper reason, max runtime, spawn failure). The analyzer prefers- * that structural signal over a loose keyword match in the transcript — a repaint-driven PTY- * transcript is a whole session's worth of text, and any keyword in it (including- * ones the agent itself typed) would otherwise classify the failure.+ * (legacy forced-stop reason or spawn failure). The analyzer prefers that+ * structural signal over a loose keyword match in the transcript — a+ * repaint-driven PTY transcript is a whole session's worth of text, and any+ * keyword in it (including ones the agent itself typed) would otherwise+ * classify the failure.** @returns {Promise<object|null>} The error-analysis object, or null on success.*/diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex ac839f92dc..045ce2c6b1 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -365,7 +365,8 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREAT// A run that owned its PR workflow and FAILED may still have opened the PR// before it died — the prompt has it open one at step 3 and merge at step 4,- // so a forced termination in between (max-runtime, spend limit, host shutdown)+ // so a forced termination in between (legacy runtime guard, spend limit,+ // host shutdown)// leaves a real PR with nothing watching it (#3733). The old flow could not// produce this: PortOS opened the PR only on success and spawned the follow-up// in the same breath. The retry adopts the PR ("if `gh` reports the pull