Repository navigation
feat(cmd): rename infer agent to infer headless and consolidate on RunWithStream - #1041
Conversation
…nWithStream Rename the infer agent command to infer headless (no alias), replace --output-format with --format json|ag-ui|text, and delete the 1638-line hand-rolled AgentSession loop. Headless mode now wires the container, selects a model, calls AgentService.RunWithStream, and delegates output to one of three renderers in internal/render/ that consume domain.ChatEvent directly. All tool execution, approval, hooks, reminders, and queue draining are handled by the shared state machine. Deleted cmd/agent.go, cmd/agent_agui.go, and associated tests for the deleted AgentSession/ConversationMessage types. Updated agentrunner.buildArgs to spawn infer headless instead of infer agent.
Update docs/ag-ui-output.md and docs/commands-reference.md to reflect the rename of infer agent to infer headless and the new --format flag.
|
@infer CI is failing - can you fix this? use /ponytail:ponytail /go /go-concurrency |
|
Model: Todos
Pull Request✅ Infer Result: SuccessSummaryCI was failing because the e2e tests still expected the old Two commits pushed to PR #1041:
All 10 e2e tests pass locally. CI should pass once it completes. Model: Tokens: 8,781,828 in · 28,943 out · 8,810,771 total (99 requests) Tool calls: 112 total · 62% success rate TracesStats
|
Co-authored-by: Eden Reich <[email protected]>
Co-authored-by: Eden Reich <[email protected]>
…ax-turns exit code
- Wire --require-approval: AgentRequest.ApprovalBrokerAttached feeds
ResolveApprovalDelivery, and RenderJSON answers approval_request lines
by reading approval_response from stdin onto the event's ResponseChan
- RenderText/RenderJSON/RenderAGUI drain the event channel until close;
ChatCompleteEvent is per-turn, so multi-turn runs are no longer cut off
- RenderAGUI emits exactly one RUN_STARTED and one terminal event per run
- Surface max-turns: the PostToolExecution->Completing transition marks
AgentContext.MaxTurnsExceeded, Completing publishes
ChatCompleteEvent{MaxTurnsReached}, renderers map it to
ErrMaxTurnsReached so exit code 2 works again
- Non-interactive chat reuses render.RenderText (drops the duplicate
processStreamingOutput)
- Cleanups: drop duplicate SetConversationID, dead aguiEncoder.result,
regex-for-literal replaces (strings.ReplaceAll), 11-param exported
command func (now unexported with an options struct)
- Tests: renderer unit tests (multi-turn text, single AG-UI lifecycle,
approval round-trip, max-turns) and a state machine MaxTurnsExceeded test
4eb696e to
96ed27b
Compare
The IPC approval broker was only attached to the json format, so a consumer spawning --format ag-ui --require-approval (e.g. the desktop app) would emit approval_request events but never read the response, leaving the engine to time out and reject every tool. Share the same answerApproval stdin broker across both formats.
The old batch loop blocked in BackgroundTasksWaiter.WaitAndDrain between turns so a run never exited while background bash/A2A tasks were still in flight. The state-machine consolidation dropped that: canComplete only checks the message queue, so a headless run that stopped emitting tool calls completed immediately and orphaned its background tasks. CheckingQueue now waits at the completion boundary (non-chat mode only; chat's UI ticker already handles this) via a WaitForBackgroundTasks callback backed by the registry and shared message queue, then drains any posted results so the loop continues. The now-dead BackgroundTasksWaiter is deleted.
tools.agent.mode: interactive launches subagents as live chat TUIs in tmux panes, which requires a human watching a chat session. A headless run has none, but the mode still applied whenever $TMUX was set, so a json/ag-ui run inside tmux spawned text TUI panes instead of machine-readable headless children. Headless now overrides the mode to headless before building the container; chat keeps the configured mode.
…n end RenderJSON only emitted the session info line up front and then read the entire conversation from the repo after the event channel closed, so a consumer watching stdout saw nothing until the run finished. Emit each message as its event arrives - assistant turns on ChatCompleteEvent (content, reasoning, tool calls), tool results on ToolExecutionCompletedEvent - matching the old loop's real-time output. Only session_stats still comes from the repo after close.
… in json stream json-pretty emits the same per-turn stream as json with each object indented across multiple lines for human reading. Also fixes the json stream dropping assistant text: the engine publishes ChatCompleteEvent without the message body (content flows only through ChatChunkEvent deltas), so streamed assistant lines had empty content. The renderer now accumulates deltas per turn, same as the text format.
Downstream consumers (infer-action) parse the tool line's content string
for the "Result of tool call: {...}" / "Tool execution failed: ..."
prefixes. Restore that envelope on streamed tool messages alongside the
structured tool_execution metadata.
The old json stream attached token_usage to each assistant completion; infer-action sums those per-turn (resilient to killed runs that never reach session_stats). Emit ChatCompleteEvent.Metrics.Usage under the same key.
The todo-hygiene reminder fired on a bare turn interval, injecting "your todo list is currently empty" as a hidden user message even when the list was full - the model reads the stale user-role nudge as the user asking to continue and keeps inventing work after finishing. Add an optional when: todos_empty condition on reminders (fail-closed on unknown values), thread the session todo count into ReminderQuery, and keep the state manager's todo list current from the engine's TodoWrite handling so the gate also works headless. The default todo-hygiene reminder ships with the gate on.
The old batch loop tracked consecutive no-tool-call turns, the last stream's finish_reason, and the latest todos, feeding them into the post_stream reminder query so todo-continuation (keep working the list) and truncation-continuation (finish the cut-off reply) could fire. The state-machine consolidation dropped all three, leaving both built-in reminders as dead config - an agent that stalled with incomplete todos was never nudged to continue them. Capture finish_reason from stream choice deltas, track strike counts in trackStreamOutcome at stream completion, and populate the post_stream query (todos via the state manager, which the engine now keeps current).
…ures - sessionOutcome uses errors.Is so ErrMaxTurnsReached (and wrapped cancel errors) count as RunStoppedEarly instead of RunFailed - completionErr returns context.Canceled on cancelled runs, giving JSON/Text renderers the same non-zero exit AG-UI already had - writeResultFile logs I/O failures instead of swallowing them
- approval policy no longer bypasses all approval in non-chat mode: headless enforces the same rules as chat (bash allow-list per mode, per-tool config), with delivery resolving to IPC (--require-approval) or block, restoring the default-deny posture the old cmd/agent.go loop had - blocked/approved sequential tool batches now publish ToolExecutionCompletedEvent so renderers report them (Blocked: reasons reach the JSON/AG-UI stream) - post_stream completion decision now asks the state machine guard instead of an ad-hoc predicate; hook-injected continuation reminders (hidden user-role messages) route into another streaming turn instead of deadlocking the loop - headless applies INFER_SUBAGENT_AGENT_MODE to the state manager again, so read-only subagents get read-only tool filtering - --session-id loads prior conversation history into the request again; --no-save disables auto-save instead of only skipping the ID - ToolExecutionResult carries tool_call_id; JSON lines emit it top-level and AG-UI uses it as toolCallId instead of the tool name - e2e assertions restored to main's contract (Write blocked without approver, Blocked: reasons, two continuation nudges then give up)
- Scope the gateway.timeout context to ListModels only; the run itself derives from Background so long headless runs are no longer cancelled at ~200s and reported stopped_early - Restore the WaitForAgentsReady gate before the first turn - Write the result file on every outcome with Success/Error/SessionID so the Agent-tool parent harvests partial answers and error detail again - Frame AG-UI text/reasoning deltas in START/CONTENT/END triads with a fresh per-turn message id - Match tool_call_id in the IPC approval broker so a late response to a timed-out request cannot decide the next one - Drop the legacy "Result of tool call:" / "Tool execution failed:" content envelope from tool lines (tool_execution/failed carry the structured result); infer-action adaptation tracked in inference-gateway/infer-action#302 - Emit agent_error / RUN_ERROR on stdout for failures before the event stream starts, keeping the channel manager's failure contract - Wire session rollover into headless: resolve group-key --session-id via the rollover manager, roll over at startup and between turns (rebuilding the in-flight conversation from the compacted repo), and persist the user task message so rollover summaries include it
Sweep comments, CLI hint strings, help text, docs, and examples that still referenced the old subcommand after the rename. The infer agents A2A registry command and the generated CHANGELOG are untouched.
4476560 to
8c036e9
Compare
…1043) Resolves #1042 ## Summary Since #1041 consolidated headless mode on `RunWithStream`, the state machine and tool executors run on their own goroutines — a panic there unwound as a raw Go stack trace on stderr while stdout stayed silent, so machine consumers (channel manager's `parseAgentError`, infer-action) missed the failure entirely. A `recover()` in `cmd/headless.go` alone cannot restore the pre-#1041 contract, because the command's goroutine never sees those panics. ## Changes - **`internal/agent`**: new `EventDrivenAgent.recoverPanic` helper converts a panic into the existing `failStream` path (`ChatErrorEvent` + `StateError` + loop nudge). Deferred at every goroutine root that runs task code: `processEvents`, `startStreaming`, `executeTools`, and the `ExecuteToolInternal` closure used by the approving/blocking states. - **Parallel tool workers** (`executeToolCallsParallel`): a worker panic can't be recovered by the collector's goroutine, so workers capture the first panic (logged with its original stack) and re-panic it on the collector, where `recoverPanic` surfaces it. - **`RunWithStream` setup goroutine**: recovers and publishes `ChatErrorEvent` directly, before `chatEvents` closes. - **`cmd/headless.go`**: the `EmitPreRunError` defer moves above container construction (storage init panics by design) and folds in a recover, so main-goroutine panics also produce the `agent_error` line and a non-zero exit. No renderer changes needed — all three formats already turn `ChatErrorEvent` into `agent_error` (JSON, truncated to 3500) or `RUN_ERROR` (ag-ui) and return a non-nil error, which exits 1. ## Testing - `TestProcessEvents_RecoversPanicToChatError` (counterfeiter `FakeStateHandler`, newly generated) verifies a panicking state handler surfaces as `ChatErrorEvent` instead of crashing. - Manual repro per the issue: with a `panic("boom")` injected in `executeToolInternal` and the mock gateway, `infer headless --format json` emits `{"type":"agent_error","message":"agent panic: boom"}` and exits 1; `--format ag-ui` emits `RUN_ERROR`. Injection reverted. - `go test -race ./...` and `task precommit:run` pass.
The CLI renamed the headless subcommand (agent -> headless) and its output flag (--output-format -> --format), and grew a json-pretty format that indents each streamed object for human-readable Actions logs. Spawn the new invocation with json-pretty as the default, and teach readJsonLines to frame multiline pretty objects (top-level braces at column 0) alongside compact json lines. Requires a CLI release containing inference-gateway/cli#1041. Fixes #302
|
🎉 This PR is included in version 0.166.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
Resolves #1040
Summary
Rename
infer agenttoinfer headlessand consolidate the CLI onto the single event-driven state machine loop. The old hand-rolled synchronous loop incmd/agent.go(1638 lines) is deleted; headless mode now drives throughAgentService.RunWithStream. Output formats (json, ag-ui, text) are renderers behind--format, consumingdomain.ChatEventdirectly.Changes
infer agentis renamed toinfer headlesswith no alias. Updateagentrunner.buildArgsto use"headless"subcommand.--output-formatis replaced by--format json|ag-ui|text.internal/render/: ContainsRenderJSON,RenderAGUI, andRenderTextfunctions, each consuming<-chan domain.ChatEventfromRunWithStream. The old globalvar agui *aguiEncoderand allif agui != nilbranches are eliminated.cmd/headless.goreplaces the oldcmd/agent.go+cmd/agent_agui.go. It wires the container, selects a model, builds anAgentRequest, callsRunWithStream, and delegates to the appropriate renderer. All tool execution, approval, hooks, reminders, and queue draining are handled by the shared state machine.cmd/agent.go,cmd/agent_agui.go, and their associated test files for the deletedAgentSession/ConversationMessage/aguiEncodertypes are removed.info,approval_request,agent_error, conversation messages,session_stats) parsed byagentrunner. AG-UI mode emits real-time deltas. Text mode streams plain content.This is phase 1 + 2 of the refactoring plan described in #1040. Follow-up phases will delete
Run/RunStreamingfrom the interface, de-stutterinternal/agentnaming, and update documentation.