The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: abort reasoning-field length stops and surface close taskkill failures
brooklyn!8b17394cc650
diff --git a/agent/turn_truncation.py b/agent/turn_truncation.pyindex 61c44e56fc1..265a391cfc7 100644--- a/agent/turn_truncation.py+++ b/agent/turn_truncation.py@@ -242,21 +242,47 @@ class _Trunc(TruncationVerdict):return getattr(self.response, "id", "") == PARTIAL_STREAM_STUB_ID-def _abort_reason(agent: Any, content: Any, has_tool_calls: bool) -> Optional[tuple]:+def _abort_reason(+ agent: Any, content: Any, has_tool_calls: bool, *,+ reasoning: Any = None, reasoning_content: Any = None,+) -> Optional[tuple]:"""``(vprint, user response, error)`` when continuation must NOT be attempted:- thinking exhausted the budget (reasoning blocks with no visible text after them —- ``content=None`` from non-<think> models is normal truncation), or a repetition loop- burned the budget on one fragment (reasoning stripped first)."""+ thinking exhausted the budget (a ``<think>`` block with no visible text after+ it, or ``finish_reason=length`` with empty visible content and a non-empty+ ``reasoning`` / ``reasoning_content`` side channel), or a repetition loop+ burned the budget on one fragment (reasoning stripped first). Empty content+ with no side-channel reasoning is still a normal truncation."""if has_tool_calls:return Noneif content and _THINK_TAG_RE.search(content) and not agent._has_content_after_think_block(content):return _THINKING_EXHAUSTED+ if _visible_content_empty(agent, content) and (+ _nonempty_side_channel(reasoning) or _nonempty_side_channel(reasoning_content)+ ):+ return _THINKING_EXHAUSTEDvisible = agent._strip_think_blocks(content) if isinstance(content, str) else contentif visible and is_repetition_dominated(visible):return _REPETITION_DOMINATEDreturn None+def _nonempty_side_channel(value: Any) -> bool:+ """True when a reasoning side channel actually carried text. No model id."""+ if isinstance(value, str):+ return bool(value.strip())+ if isinstance(value, (list, tuple, dict, set)):+ return len(value) > 0+ return bool(value)+++def _visible_content_empty(agent: Any, content: Any) -> bool:+ if content is None:+ return True+ if isinstance(content, str):+ return not (agent._strip_think_blocks(content) or "").strip()+ return not content++def _content_filter_fallback(st: _Trunc, _retry: TurnRetryState) -> Optional[TruncationVerdict]:"""Content-filter stream stall → fallback. ``_content_filter_terminated`` iscontent-deterministic, so escalate before retrying the primary; without a fallback@@ -493,7 +519,11 @@ def recover_from_truncation(_trunc_content = getattr(_trunc_msg, "content", None) if _trunc_msg else None_trunc_has_tool_calls = bool(getattr(_trunc_msg, "tool_calls", None)) if _trunc_msg else False- abort = _abort_reason(agent, _trunc_content, _trunc_has_tool_calls)+ abort = _abort_reason(+ agent, _trunc_content, _trunc_has_tool_calls,+ reasoning=getattr(_trunc_msg, "reasoning", None) if _trunc_msg else None,+ reasoning_content=getattr(_trunc_msg, "reasoning_content", None) if _trunc_msg else None,+ )if abort is not None:line, user_response, error = abortagent._vprint(f"{agent.log_prefix}{line}", force=True, diagnostic=True)diff --git a/apps/desktop/electron/close-stop-kill.test.ts b/apps/desktop/electron/close-stop-kill.test.tsnew file mode 100644index 00000000000..bc27c5d1dbd--- /dev/null+++ b/apps/desktop/electron/close-stop-kill.test.ts@@ -0,0 +1,82 @@+import assert from 'node:assert/strict'+import { test } from 'vitest'++import { finishWindowsCloseStop, type RuntimeLock } from './close-stop-kill'++function killThatThrows(message: string) {+ return () => {+ throw new Error(message)+ }+}++test('close/stop surfaces a taskkill failure and does not clear a lock a live holder still owns', () => {+ const killed: number[] = []+ const cleared: string[] = []+ const locks: RuntimeLock[] = [+ { path: 'C:\\Users\\me\\.hermes\\gateway.lock', holderPids: [4242], held: true },+ { path: 'C:\\Users\\me\\.hermes\\profiles\\other\\gateway.lock', holderPids: [], held: false }+ ]++ const result = finishWindowsCloseStop([4242], locks, {+ killTree: pid => {+ killed.push(pid)+ throw new Error('Access is denied')+ },+ isPidAlive: pid => pid === 4242,+ clearLock: path => {+ cleared.push(path)+ }+ })++ assert.deepEqual(killed, [4242], 'tree-kill stays on the owned PID only')+ assert.equal(result.taskkillFailures.length, 1)+ assert.match(result.taskkillFailures[0].error, /Access is denied/)+ assert.equal(result.taskkillFailures[0].pid, 4242)+ assert.deepEqual(result.remainingPids, [4242])+ assert.equal(result.liveFailure, true)+ assert.deepEqual(cleared, ['C:\\Users\\me\\.hermes\\profiles\\other\\gateway.lock'])+ assert.deepEqual(result.retainedLocks, ['C:\\Users\\me\\.hermes\\gateway.lock'])+})++test('close/stop inventories owned PIDs after the tree kill and clears only unheld locks', () => {+ const killed: number[] = []+ const cleared: string[] = []+ const alive = new Set([9001])++ const result = finishWindowsCloseStop([4242, 9001], [+ { path: 'gone.lock', holderPids: [4242] },+ { path: 'still-held.lock', holderPids: [9001] },+ { path: 'foreign-held.lock', holderPids: [7777], held: true },+ { path: 'no-holder.lock', holderPids: [] }+ ], {+ killTree: pid => {+ killed.push(pid)+ alive.delete(pid === 4242 ? 4242 : -1)+ },+ isPidAlive: pid => alive.has(pid),+ clearLock: path => {+ cleared.push(path)+ }+ })++ assert.deepEqual(killed, [4242, 9001], 'does not widen the tree-kill to foreign holders')+ assert.deepEqual(result.remainingPids, [9001])+ assert.deepEqual(result.taskkillFailures, [])+ assert.equal(result.liveFailure, true)+ assert.deepEqual(cleared.sort(), ['gone.lock', 'no-holder.lock'].sort())+ assert.deepEqual(result.retainedLocks.sort(), ['foreign-held.lock', 'still-held.lock'].sort())+})++test('a taskkill error is not discarded when the owned PID is already gone', () => {+ const result = finishWindowsCloseStop([4242], [{ path: 'stale.lock', holderPids: [4242] }], {+ killTree: killThatThrows('The process "4242" not found'),+ isPidAlive: () => false,+ clearLock: () => {}+ })++ assert.equal(result.taskkillFailures.length, 1)+ assert.match(result.taskkillFailures[0].error, /not found/)+ assert.deepEqual(result.remainingPids, [])+ assert.equal(result.liveFailure, false)+ assert.deepEqual(result.clearedLocks, ['stale.lock'])+})diff --git a/apps/desktop/electron/close-stop-kill.ts b/apps/desktop/electron/close-stop-kill.tsnew file mode 100644index 00000000000..e8a1f2844fb--- /dev/null+++ b/apps/desktop/electron/close-stop-kill.ts@@ -0,0 +1,113 @@+/**+ * Windows Desktop close/stop after the existing tree-kill.+ *+ * taskkill /T /F is not widened: the caller passes the owned PIDs and the+ * same tree-kill. This module does not discover extra processes to signal.+ * A taskkill error is recorded, never discarded. After the kill, owned PIDs+ * are inventoried, and only locks with no live holder are cleared.+ */++export interface RuntimeLock {+ path: string+ /** PIDs named by the lock file, if any. */+ holderPids: number[]+ /**+ * Explicit hold (Restart Manager / open handle). True means a live process+ * holds the file even if we do not have its PID. Omit when unknown.+ */+ held?: boolean+}++export interface TaskkillFailure {+ pid: number+ error: string+}++export interface CloseStopKillDeps {+ /** Existing tree-kill (taskkill /PID n /T /F). Must not be widened by this module. */+ killTree: (pid: number) => void+ /** True while `pid` is still in the process table. */+ isPidAlive: (pid: number) => boolean+ clearLock: (path: string) => void+}++export interface CloseStopKillResult {+ taskkillFailures: TaskkillFailure[]+ /** Owned PIDs still enumerable after the tree kill. */+ remainingPids: number[]+ clearedLocks: string[]+ retainedLocks: string[]+ /**+ * True when a taskkill failure left an owned PID alive, or any owned PID+ * is still enumerable. An already-gone taskkill error is recorded but is+ * not itself a live failure.+ */+ liveFailure: boolean+}++function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++function lockIsHeld(lock: RuntimeLock, alive: (pid: number) => boolean): boolean {+ if (lock.held === true) {+ return true+ }++ return lock.holderPids.some(pid => Number.isInteger(pid) && pid > 0 && alive(pid))+}++/**+ * Tree-kill the owned PIDs, inventory what is still alive, and clear locks+ * that no live holder owns. Does not signal any PID that was not passed in.+ */+export function finishWindowsCloseStop(+ ownedPids: number[],+ locks: RuntimeLock[],+ deps: CloseStopKillDeps+): CloseStopKillResult {+ const pids = ownedPids.filter(pid => Number.isInteger(pid) && pid > 0)+ const taskkillFailures: TaskkillFailure[] = []++ for (const pid of pids) {+ try {+ deps.killTree(pid)+ } catch (error) {+ taskkillFailures.push({ pid, error: errorText(error) })+ }+ }++ const remainingPids = pids.filter(pid => deps.isPidAlive(pid))+ const alive = new Set(remainingPids)+ const clearedLocks: string[] = []+ const retainedLocks: string[] = []++ for (const lock of locks) {+ if (lockIsHeld(lock, pid => alive.has(pid) || deps.isPidAlive(pid))) {+ retainedLocks.push(lock.path)+ continue+ }++ deps.clearLock(lock.path)+ clearedLocks.push(lock.path)+ }++ const failedWhileAlive = new Set(taskkillFailures.map(failure => failure.pid))+ const liveFailure = remainingPids.length > 0 || pids.some(pid => failedWhileAlive.has(pid) && deps.isPidAlive(pid))++ return {+ taskkillFailures,+ remainingPids,+ clearedLocks,+ retainedLocks,+ liveFailure+ }+}++export function closeStopFailureMessage(result: CloseStopKillResult): string {+ const kills = result.taskkillFailures.map(failure => `PID ${failure.pid}: ${failure.error}`).join('; ')+ const remaining = result.remainingPids.length ? `still running: ${result.remainingPids.join(', ')}` : ''+ const retained = result.retainedLocks.length ? `locks still held: ${result.retainedLocks.join(', ')}` : ''++ return ['Windows close/stop did not finish cleanly.', kills, remaining, retained].filter(Boolean).join(' ')+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 2b051ade25d..93e8d5d8be3 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -79,6 +79,7 @@ import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyimport { waitForDashboardPortAnnouncement } from './backend-ready'import { recycleOwnedBackend } from './backend-recycle'import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'+import { closeStopFailureMessage, finishWindowsCloseStop, type RuntimeLock } from './close-stop-kill'import { createBackendServeSupportResolver } from './backend-serve-support'import {isHostKeyChangedBootFailure,@@ -3591,7 +3592,14 @@ function killHermesOwnedVenvDaemons(updateRoot) {if (Number.isInteger(pid) && pid > 0) {rememberLog(`[updates] stopping Hermes-owned venv daemon (hindsight) PID ${pid} before hand-off`)- forceKillProcessTree(pid)++ try {+ forceKillProcessTree(pid)+ } catch (error) {+ // Update hand-off only. Close/stop must not swallow this; see+ // windowsCloseStopOwnedBackends.+ rememberLog(`[updates] taskkill PID ${pid} failed: ${error instanceof Error ? error.message : String(error)}`)+ }}}}@@ -3600,9 +3608,11 @@ function killHermesOwnedVenvDaemons(updateRoot) {// only signals the direct child, so on Windows a backend `hermes.exe` that// spawned its own grandchildren (a `hermes` REPL, a pty terminal session, the// gateway) would survive and keep the venv shim locked. taskkill /T /F reaps-// the whole tree synchronously. Windows-only: this is called solely from the-// Windows shim-unlock path, and the backend is NOT spawned detached (so it's-// not a process-group leader — a POSIX negative-pgid kill would be meaningless+// the whole tree synchronously. The command is not widened: one owned PID,+// /T /F, nothing else. Failures propagate — close/stop must not discard them.+// Windows-only: this is called solely from the Windows shim-unlock and+// close/stop paths, and the backend is NOT spawned detached (so it's not a+// process-group leader — a POSIX negative-pgid kill would be meaningless// here anyway). POSIX teardown stays with the existing before-quit SIGTERM.function forceKillProcessTree(pid) {if (!IS_WINDOWS) {@@ -3613,11 +3623,113 @@ function forceKillProcessTree(pid) {return}+ execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], hiddenWindowsChildOptions({ stdio: 'ignore' }))+}++function holderPidsFromLockFile(lockPath: string): Pick<RuntimeLock, 'holderPids' | 'held'> {try {- execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], hiddenWindowsChildOptions({ stdio: 'ignore' }))+ const raw = fs.readFileSync(lockPath, 'utf8').trim()++ if (!raw) {+ return { holderPids: [] }+ }++ let pid = Number(raw)++ if (!Number.isInteger(pid)) {+ const parsed = JSON.parse(raw) as { pid?: unknown }+ pid = Number(typeof parsed === 'object' && parsed ? parsed.pid : parsed)+ }++ return Number.isInteger(pid) && pid > 0 ? { holderPids: [pid] } : { holderPids: [] }+ } catch (error) {+ const code = (error as NodeJS.ErrnoException | null)?.code++ // Can't read the file: a live holder may be why. Do not clear it.+ if (code === 'EBUSY' || code === 'EPERM' || code === 'EACCES') {+ return { holderPids: [], held: true }+ }++ return { holderPids: [] }+ }+}++function collectCloseStopLocks(): RuntimeLock[] {+ const roots = [HERMES_HOME]+ const profilesRoot = path.join(HERMES_HOME, 'profiles')++ try {+ for (const name of fs.readdirSync(profilesRoot)) {+ roots.push(path.join(profilesRoot, name))+ }} catch {- // Already gone, or no permission — best effort; the unlock wait below is- // the real gate.+ // No profiles directory — the default home lock is enough.+ }++ const locks: RuntimeLock[] = []++ for (const root of roots) {+ const lockPath = path.join(root, 'gateway.lock')++ try {+ if (!fs.statSync(lockPath).isFile()) {+ continue+ }+ } catch {+ continue+ }++ locks.push({ path: lockPath, ...holderPidsFromLockFile(lockPath) })+ }++ return locks+}++function collectOwnedBackendPids(): number[] {+ const pids: number[] = []+ const primary = backendConnectionState.getProcess()++ if (primary && Number.isInteger(primary.pid) && primary.pid > 0) {+ pids.push(primary.pid)+ }++ for (const entry of backendPool.values()) {+ const pid = entry?.process?.pid++ if (Number.isInteger(pid) && pid > 0) {+ pids.push(pid)+ }+ }++ return pids+}++// Close/stop: same tree-kill as forceKillProcessTree, then inventory the+// owned PIDs and clear only locks no live holder still owns. A taskkill+// failure is logged and, when an owned PID is still alive, thrown.+function windowsCloseStopOwnedBackends() {+ if (!IS_WINDOWS) {+ return+ }++ const result = finishWindowsCloseStop(collectOwnedBackendPids(), collectCloseStopLocks(), {+ killTree: forceKillProcessTree,+ isPidAlive: isPidAliveWindows,+ clearLock: lockPath => {+ fs.rmSync(lockPath, { force: true })+ }+ })++ for (const failure of result.taskkillFailures) {+ rememberLog(`[close-stop] taskkill PID ${failure.pid} failed: ${failure.error}`)+ }++ if (result.clearedLocks.length) {+ rememberLog(`[close-stop] cleared unheld lock(s): ${result.clearedLocks.join(', ')}`)+ }++ if (result.liveFailure) {+ throw new Error(closeStopFailureMessage(result))}}@@ -3727,7 +3839,18 @@ async function stopOwnedBackend(identity) {}if (IS_WINDOWS) {- forceKillProcessTree(identity.pid)+ try {+ forceKillProcessTree(identity.pid)+ } catch (error) {+ const detail = error instanceof Error ? error.message : String(error)+ const stillThere = await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS)++ if (stillThere !== false) {+ throw new Error(`taskkill failed for backend PID ${identity.pid}: ${detail}`)+ }++ rememberLog(`taskkill reported failure for already-gone backend PID ${identity.pid}: ${detail}`)+ }} else {try {process.kill(-identity.pid, 'SIGTERM')@@ -3972,7 +4095,13 @@ async function releaseBackendLock(updateRoot: string, tag: string): Promise<{ unreturn stragglers},- killProcessTree: forceKillProcessTree,+ killProcessTree: pid => {+ try {+ forceKillProcessTree(pid)+ } catch (error) {+ rememberLog(`[${tag}] taskkill PID ${pid} failed: ${error instanceof Error ? error.message : String(error)}`)+ }+ },sleep: (ms: number) => new Promise(r => setTimeout(r, ms)),now: () => Date.now(),log: rememberLog@@ -11963,6 +12092,10 @@ function reapInstallRootedStragglers(excludePids: number[]): void {}const backendShutdown = createBackendShutdownCoordinator(async (): Promise<void> => {+ // Before teardown drops the process handles: inventory those owned PIDs+ // after the same tree-kill, and refuse to pretend close succeeded.+ windowsCloseStopOwnedBackends()+const localShutdown = localBackendLifecycle.shutdown()const primary = backendConnectionState.getProcess()const primaryStop = teardownPrimaryBackendAndWait()diff --git a/tests/agent/test_length_continuation_thinking_exhaustion.py b/tests/agent/test_length_continuation_thinking_exhaustion.pyindex 2c987b35739..39fdc963a70 100644--- a/tests/agent/test_length_continuation_thinking_exhaustion.py+++ b/tests/agent/test_length_continuation_thinking_exhaustion.py@@ -142,6 +142,27 @@ def _thinking_only_length_response():)+def _side_channel_length_response(*, reasoning=None, reasoning_content=None, content=""):+ """finish_reason=length, empty visible content, reasoning parked off to+ the side. Model id is irrelevant — the field is the signal."""+ from tests.agent.test_run_agent import _mock_assistant_msg++ return SimpleNamespace(+ id="chatcmpl-reasoning-side-channel",+ model="test/model",+ choices=[SimpleNamespace(+ index=0,+ message=_mock_assistant_msg(+ content=content,+ reasoning=reasoning,+ reasoning_content=reasoning_content,+ ),+ finish_reason=FINISH_REASON_LENGTH,+ )],+ usage=None,+ )++def _full_response(content):from tests.agent.test_run_agent import _mock_response@@ -320,3 +341,38 @@ class TestReasoningOffReachesTheWire:calls = loop_agent.client.chat.completions.create.call_args_listfirst = (calls[0].kwargs.get("extra_body") or {}).get("reasoning")assert first == {"enabled": True, "effort": "high"}, first+++class TestReasoningSideChannelBudgetAbort:+ """finish_reason=length with nothing visible and a non-empty reasoning+ side channel is the existing thinking-budget abort, not a continuation.+ No model id is consulted."""++ @pytest.mark.parametrize("field", ["reasoning", "reasoning_content"])+ def test_empty_visible_content_aborts_on_side_channel(self, loop_agent, field):+ kwargs = {field: "the model spent the whole budget here"}+ loop_agent.client.chat.completions.create.side_effect = [+ _side_channel_length_response(**kwargs),+ _full_response("this continuation must not run"),+ ]+ result = _run(loop_agent, "write me a long report")++ assert result["completed"] is False+ assert "Thinking Budget Exhausted" in (result["final_response"] or "")+ assert loop_agent.client.chat.completions.create.call_count == 1, (+ "A length stop with empty visible content and a non-empty "+ f"{field} field must abort, not continue."+ )++ def test_visible_answer_with_reasoning_still_continues(self, loop_agent):+ loop_agent.client.chat.completions.create.side_effect = [+ _side_channel_length_response(+ content="partial answer ",+ reasoning="some leftover reasoning",+ ),+ _full_response("and the rest."),+ ]+ result = _run(loop_agent, "write me a long report")++ assert result["completed"] is True+ assert "partial answer" in (result["final_response"] or "")