Commit Graph

23 Commits

Author SHA1 Message Date
Teknium
55f708e4dd fix(agent): a pending redirect does not hide the restart from a shutdown stop
The round-2 guard kept any pending interrupt's cause when a gateway shutdown interrupted the
same agent. redirect() (a mid-request user correction) also sets _interrupt_requested, so a
restart after a correction dropped the correction AND recorded no cause: the turn ended
interrupted with no restart notice. The guard now keeps the cause only when the pending
interrupt is a user Stop (USER_INTERRUPT_REASONS); a pending redirect is replaced by the
restart, which is the turn's real cause.

Review round 2b (#141336); the reviewer's probe is promoted into
tests/gateway/test_restart_interrupt_notice.py.

Refs #134889 (F1)
Refs #141321
2026-10-19 00:03:16 -07:00
Teknium
027f587ea4 fix(agent): a gateway shutdown interrupt never relabels a user Stop already pending
An in-process turn the user stopped could still be unwinding (inside a tool) when stop()'s
_interrupt_running_agents hit the same agent; interrupt() overwrote the pending Stop's empty
message with "Gateway restarting", so the turn recorded the restart as its cause and the user's
Stop got the restart notice. A shutdown-tagged interrupt (tool_reason "gateway shutdown") now
keeps the cause of an interrupt already pending; it still sets the flags and the hard-stop event.
A turn only the restart stopped still records the restart and gets the notice.

Review round 2 (#141336, in-process path); repro promoted into
tests/gateway/test_restart_interrupt_notice.py.
2026-10-18 22:52:23 -07:00
unsupportedpastels
94458ebba1 fix(gateway): a late queued steer goes back to its queue, never into a follow-up
An empty steer buffer at settlement did not prove the turn read a transfer.
The turn finalizer drained a steer that arrived after the last tool batch into
result['pending_steer'], and the gateway's follow-up handling discards that
follow-up while it drains for a restart. Settlement still recorded the
transferred admission steered, so the prompt neither reached a model call nor
stayed queued for the next owner.

The finalizer now uses the agent's _drain_leftover_steer: it hands back only
ticketless steers (a /steer typed into the turn still becomes the next user
turn) and keeps each ticketed transfer buffered. The claim's settlement then
withdraws the transfer by its ticket and puts the admission back in its own
FIFO place. It runs once as its own turn, or waits queued for the next owner
when this one is draining. A transfer never rides a follow-up, so no restart
can drop one. An agent without the method keeps the old full drain.

Refs #134889 (RT-35)
Refs #140208
2026-10-17 14:25:35 -04:00
unsupportedpastels
0b5cf74487 fix(gateway): settle a queued steer by its admission, not by searching its text
Settlement withdrew a transfer by finding its text between newlines in the
agent's combined steer buffer. Those newlines also occur inside another
submission, so withdrawing a consumed 'alpha' stripped it out of a later
'alpha\nbeta': the consumed prompt was queued again and ran twice, the unread
one was recorded steered, and 'beta' leaked into a later turn. Identical text
on both sides of a drain had the same swap.

The agent's steer buffer now keeps each submission as a (ticket, text) part,
with _pending_steer still their newline join. The gateway hands a transfer
over with its admission id as the ticket. A drain records each ticket it took
as consumed, a hard stop records it as dropped unread, and a drained text put
back undelivered (_requeue_pending_steer) gets its tickets back.
withdraw_steer(ticket) settles exactly that submission: True while it is still
buffered (only its part is removed) or was dropped unread, False once a drain
consumed it.

Refs #134889 (RT-35)
Refs #140208
2026-10-17 14:25:35 -04:00
unsupportedpastels
bafd32849b fix(gateway): a queued steer no drain of the turn consumed goes back to its queue
agent.steer() only buffers the text. A prompt.steer_queued accepted after
the turn's last drain (the finalizer has already taken _pending_steer while
the handler finishes streaming and cleanup) was recorded as delivered, so
the claim settled the row `steered` although that turn never saw it, and the
text stayed on the cached agent until an unrelated later turn picked it up.

The transfer now records the accepted text. When the claim settles (its
execution has returned, so nothing can drain any more), each text the
agent still buffers is withdrawn with the new AIAgent.withdraw_steer() and
reads undelivered: its admission goes back to its own FIFO place and runs
once as its own turn. Other buffered steers (session.steer) stay where
they were. A text a drain took settles as before.

Refs #134889 (RT-35)
Refs #140208
2026-10-17 14:25:35 -04:00
alt-glitch
2c8df45ee5 Merge remote-tracking branch 'origin/main' into sid/onboarding
# Conflicts:
#	agent/conversation_loop.py
#	tui_gateway/prompt_turn.py
2026-10-07 19:29:35 +05:30
kshitijk4poor
7c493cd2a1 refactor(agent): derive user-stop skip wording from USER_INTERRUPT_REASONS
_USER_STOP_WORDING restated the three USER_INTERRUPT_REASONS keys with
their values capitalised, so a new human-stop reason had to be added in
two places or it would render as "Turn aborted — …". Drop the mirror
and capitalise the recorded reason; output is identical for all three
keys (probe-B02-5.py).

Gate rP finding 5 (reuse).
2026-10-07 18:15:29 +05:30
kshitijk4poor
17da1d75b7 fix(agent): render skip wording verbatim instead of brace-escaping it
Fold finding 3 (B02 gate): interrupt_skip_wording doubled braces on the
assumption the wording reaches str.format, but every consumer substitutes
{name} with str.replace, so a reason like "a{b}" rendered as "a{{b}}".
Drop the escape and its docstring claim, and look user-stop wording up
directly in _USER_STOP_WORDING.
2026-10-07 18:15:29 +05:30
alrcatraz
e8a478d155 fix(agent): render concurrent skip notices from the recorded reason
The sequential path was converted to interrupt_skip_wording() but the
concurrent batch kept three hardcoded user-blaming strings: the pre-batch
skip (execute_tool_calls_concurrent), the unfilled-slot notice
(_unfinished_tool_result) and emit_cancelled's hook message. A system
producer that stops a parallel batch — watchdog, lease loss, SSE
disconnect, or any segment routed through execute_tool_calls_segmented —
still told the model "skipped due to user interrupt" while
interrupt_issuer() booked the same turn as interrupted_by_system. Render
all three from the recorded reason like the sequential siblings; the
observability enums (error_type/hook_error_type) stay untouched.

Also harden the interpolation the wording rides on: _append_skipped_tool_results
substitutes {name} with str.replace instead of str.format, and
interrupt_skip_wording escapes braces in caller-supplied reasons, so a
free-form tool_reason can never raise KeyError/IndexError mid-turn.

(cherry picked from commit b785bccbca6fd997921411198d277c39d3d93261)
2026-10-07 18:15:29 +05:30
alrcatraz
b6912e1e58 fix(agent): let an explicit tool_reason label a soft interrupt
interrupt() derived the published tool-interrupt reason from whether a message
was attached, so on the soft path a system producer had no way to label itself:
passing a message booked the stop as "user sent a new message", passing none
booked it as "user interrupt". Both live in USER_INTERRUPT_REASONS, so
interrupt_issuer() returned None and the turn exit reason became
interrupted_by_user — a system abort recorded as a human stop.

An explicit tool_reason now wins on the soft path as it already did for
hard_cancel, keeping the message heuristic only as the fallback.

(cherry picked from commit 495f1a84a15a4bf88295af1e06f225e25d57715c)
2026-10-07 18:15:29 +05:30
alt-glitch
995bc1c0e7 feat(free-tier): offer sign-in after finished tasks, backing off
A free-tier user is offered sign-in 3 minutes after their first finished
task, whether or not they send another prompt. Later offers each need
another finished task after the previous one, come 3 minutes after that
task, and never sooner than 1h, 4h, then 24h after the previous offer, so
a user who keeps saying "Not now" hears it less often.

- hermes_cli/free_tier_offer.py: the policy. One install-wide record
  (<default root>/free_tier/sign_in_offer.json, file lock + atomic write);
  claim_offer() is compare-and-set so two windows never both show it.
  Nothing is due off the free tier.
- tui_gateway/free_tier_task_done.py: a "finished task" is a completed
  turn with a reply, on the free-tier agent, not a crash resume, and with
  no steer/redirect/interrupt/busy-typing while it ran. Called from
  prompt_turn after a complete turn, before message.complete goes out, so
  a status read prompted by that event already sees the record. Intervention is reported by the agent
  (result["user_intervened"], reset per turn) and marked on the session by
  the steer/redirect/interrupt RPCs and busy submits.
- Wire: free_tier.status gains nudge_due_in (seconds, 0 = now, absent when
  none is pending); new free_tier.claim_nudge -> {claimed}.
2026-10-07 12:26:42 +05:30
kshitijk4poor
429f319d45 refactor(agent): one builder for the interrupted_during_api_call exit reason
The summary-interrupt path added a second copy of the string the loop's
interrupt path builds; turn_explainers matches its prefix, so both now
share interrupted_during_api_call_reason().
2026-09-27 02:02:41 +05:30
赵桂雄
79d1c4b225 fix(agent): clear_interrupt drops an unconsumed steer only on hard cancel
The _pending_steer wipe in clear_interrupt() ran unconditionally behind a
comment claiming "a hard interrupt supersedes any pending /steer" — but
nothing gated it on an actual hard stop. Every soft caller wiped the buffer
too: the redirect rebuild (turn_api_call.handle_api_interrupt and the
response-crossing check), API-error recovery, and turn-boundary hygiene.
Production signature: a text-only follow-up lands while the agent is busy,
redirect() degrades to steer() and returns True, the gateway acknowledges
delivery, and the accepted message then evaporates during a later soft
clear — no payload, no leftover, no log.

Gate the wipe on the new hard_cancel flag and keep the steer buffered on
soft clears: the existing drains already deliver it (pre-API inject into
the newest tool result, post-batch append, or the finalizer's leftover
handoff to the next turn). abort_turn_on_interrupt is the one real hard
stop in the clear family and now passes hard_cancel=True, preserving the
documented drop-on-stop semantics.
2026-09-18 13:01:12 -04:00
teknium1
6a99766424 fix(agent): system watchdog interrupts are attributed to their issuer, not the user
Every hard interrupt reached `begin_iteration` through the same `_interrupt_requested`
flag, so the turn loop booked all of them as `interrupted_by_user` — a cron run killed
by the scheduler's inactivity watchdog, a turn aborted by the liveness watchdog, a lost
session turn lease and a gateway inactivity timeout all read as a human pressing stop,
and the investigation went to the wrong subsystem (#112647).

`interrupt()` already records a trusted category per interrupt (`_tool_interrupt_reason`,
fed by the `tool_reason` every producer can pass through `request_hard_interrupt`). The
exit reason is now derived from it: the three categories `interrupt()` itself mints for
human stops keep `interrupted_by_user` / `interrupted_during_api_call`; any other
category names its producer — `interrupted_by_system(cron_inactivity_watchdog)`,
`interrupted_during_api_call(turn_liveness_watchdog)`. The system producers that passed
no `tool_reason` (cron inactivity watchdog, turn liveness watchdog, lease loss, gateway
inactivity timeout) now name themselves, so the model-visible tool-cancellation text
says the same thing. `_publish_interrupt_state` logs ONE line naming the source so the
turn record and the log agree.

No change to WHEN anything interrupts. `interrupted_during_api_call` moves to the
prefix-matched explanation table so the parameterised form keeps its user copy.

Slim redo of #112652 by @KoNit-K, which added a parallel `issuer` attribute and
keyword; this reuses the existing `tool_reason` plumbing instead.

Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
2026-09-16 17:48:17 -07:00
kshitijk4poor
26f4a674e0 fix(agent): a /steer row is human input for every user-turn predicate
Follow-up to #106317. Typing the steer row (display_kind="steer") for the renderer and the
alternation-repair guard collided with the convention that any display_kind on a user row means
scaffolding: is_user_originated_turn / _is_actionable_user_turn / split_user_originated_turn
returned False for it (tail anchoring, auto-focus, dispatcher views, resume counts) while
_is_real_user_message returned True (anchor restoration) — the two predicate families disagreed
on the same row, and list_recent_user_messages (/undo, /rewind) skipped it in SQL. A steer
carries full user authority; the steer kind is now whitelisted in all four.

Also: the pre-API drain's requeue tail reuses _requeue_pending_steer instead of a copy; the TUI
history projection compares against STEER_DISPLAY_KIND; the steer() docstring describes the row.
2026-09-09 13:08:25 +05:30
Teknium
463292351f fix: mid-turn user message no longer waits behind a foreground terminal command
A message typed while the agent runs (CLI busy_input_mode=interrupt, gateway
priority redirect, ACP redirect) goes through AIAgent.redirect(). During tool
execution redirect() degrades to steer(), whose delivery rides the tool result
— so a long foreground command (a `sleep 285` CI poller, a build) parked the
user's message until it exited. The UI printed "Redirected current turn" while
nothing happened for minutes.

redirect() now also asks the tool workers to YIELD (tools/interrupt.request_yield).
The local terminal backend's wait loop honours it: the drain thread is stopped, the
still-running Popen is adopted by the process registry as a notify_on_complete
background session (ProcessRegistry.adopt_local — output so far seeds the buffer,
the registry reader continues from the pipe), and the tool returns immediately with
status "yielded_to_background" + session_id. The command is never killed; the
completion notification arrives as usual and process(poll/wait/log/kill) work on it.

Non-local backends and internal env.execute() consumers pass no yield_handler and
are unaffected; a stale yield bit is cleared with the interrupt bit per worker tid.
2026-09-05 13:51:06 -07:00
Teknium
6e2796b82d review-fix(locks): restore BASE fail-loud lock-slot reads and _is_openai_client_closed truth table
Adolanium review §3 (Medium/Low). BASE shape at every steer/redirect/persist/agent-cache
lock site was: lock = getattr(obj, "_x_lock", None); if lock is not None: with lock: <direct
attribute read>; else: <getattr fallback for object.__new__ test stubs>. The refactor rewrote
several of these as 'with getattr(...) or nullcontext(): getattr(slot, None)', which (a) turned a
missing slot under the lock from a loud AttributeError into silent None and (b) in the gateway
peek helper read the cache without any lock when the lock attribute was absent.

Restored BASE semantics at:
- agent/agent_runtime_helpers.py::_requeue_pending_steer
- agent/interrupt_control.py: steer, redirect, clear_interrupt, _has_pending_redirect,
  _drain_pending_redirect, _drain_pending_steer (new _ic_slot helper: direct read under lock)
- agent/session_persistence.py::_persist_lock (explicit None check + BASE rationale)
- gateway/slash_commands.py::_cached_agent_for (BASE callers read ONLY under the lock; no lock -> None)
- gateway/run_agent_cache.py::_evict_cached_agent (BASE: self._agent_cache direct under lock)
- agent/client_lifecycle.py::_is_openai_client_closed: BASE body + docstring verbatim (outer
  is_closed first; inner _client.is_closed only when _client exists; else False)
- agent/stream_delivery.py::_ensure_stream_writer_state: restore BASE rationale that the lock is
  created unconditionally in agent_init (_STREAM_STATE) and the lazy path is stub-only

A/B (/tmp/rf/rev/ab_lock_fallbacks.py, ab_client_closed.py) is byte-identical BASE vs HEAD on
the reviewer's inputs + edge cases. tests/agent/test_lock_fallback_base_semantics.py pins it
(7 of 25 cases fail on the pre-fix tree).
2026-09-03 12:29:52 -07:00
Teknium
24a0731bf0 refactor(agent/interrupt_control,deadline): compact signatures, fence lookups and log calls 2026-09-02 19:31:18 -07:00
Teknium
83f8de7eab refactor(agent): flatten interrupt() claim closures, group lazy-origin imports, reflow literals/log calls byte-identically 2026-09-02 19:05:00 -07:00
Teknium
576fd71fbc refactor(agent/interrupt_control): unify lock/codex/abort/worker-fanout branches into helpers (425 -> 321 LOC) 2026-09-02 18:27:10 -07:00
Teknium
45e88aff38 refactor(run_agent): re-wrap comment blocks left with dangling fragments 2026-09-02 13:29:40 -07:00
Teknium
1e778ae7c6 refactor(run_agent): re-wrap compacted docstrings, restore lost issue-ref rationale 2026-09-02 13:29:40 -07:00
Teknium
81abe4799a refactor(run_agent): extract InterruptControl/TurnExplainers/ActivityTracking/RateLimitCredits mixins 2026-09-02 13:29:40 -07:00