Repository navigation
The agent-harness hardening plan, first release: the bridge grows from a
thin adapter into a bounded, observable, recoverable agent loop —
covering the P0–P1 core plus early P2 (context management) and P3
(durability, tool journal, source records) slices. ACP v1/v2 wire
compatibility is unchanged — every addition is additive.
Added
- Bounded tool loop with honest
partialstatus.LLM_MAX_TOOL_ROUNDS(default 50, aligned with openab-agent'sOPENAB_AGENT_MAX_TOOL_LOOPS) bounds model↔tool round-trips; on exhaustion a wrap-up call asks the model for a final answer, reported asstatus: "partial"+stopReason: "max_turn_requests"— never ascompleted. A second breaker,LLM_TOOL_FAILURE_STREAK(default 3), aborts the loop when the same tool+args fails identically N times and takes the same wrap-up path. - Structured turn evidence. The prompt response carries
evidence—rounds,toolCalls,toolsOk,toolsFailed,toolsDenied,toolsTimedOut,outputsTruncated,budgetHit(null|"rounds"|"failure_streak"),wallMs— so automation can branch on data instead of prose. v1 puts it on the prompt result; v2 on the turn-endingstate_update. - Capability tool policy.
[policy]section /LLM_POLICY_{READ,WRITE,SHELL,WEB}with four actions:allowexecutes;auditemits a visible[policy:audit]notice then executes;confirmexecutes only with a deployment grant ([policy] grants/LLM_POLICY_GRANTS) and denies otherwise — it never executes unconfirmed;denyreturns a structuredDeniedtool error the model can read. Defaults: read/write allow, shell/web audit. - Workspace-relative path deny globs.
deny_path_globs/LLM_POLICY_DENY_PATHS(defaults cover.env,*.pem,*.key,.ssh/**,.aws/**,.gnupg/**) are enforced on file tools'pathargument AND on every pathlist_dir/search_codeenumerate — credential-shaped files cannot leak through search results either.*does not cross/,**does; a glob without/matches basenames at any depth. - Async bounded tool execution. bash/git_*/web_fetch run under
LLM_TOOL_TIMEOUT(default 120 s) with process-group kills on Unix;LLM_TURN_TIMEOUT(default 0 = off) bounds the whole turn. Tool results carryexit_code,error_kind, andtruncatedflags. - Opt-in session snapshots.
LLM_SESSION_DIRenables atomic per-session JSON snapshots;session/load/session/resumerestore across restarts andloadSessionis advertised only when a store is configured. Restored cwd is re-validated (missing dir →-32602); store errors split into-32001 load_failed(corrupt snapshot) vs-32002 session_not_found(no snapshot). - Release channel split. Tags containing
-(e.g.v0.10.0-rc.2) produce binaries + GHCR image + a GitHub prerelease WITHOUT a crates.io publish; clean tags publish crates.ghcr.io/.../acp-bridge:latestonly moves on clean tags. session/permit— per-operation grants. Aconfirm-blocked tool call can be rescued by a single-use, TTL-bound (≤3600s) permit the Client issues viasession/permit {sessionId, capability, tool?, ttlSeconds?}. Permits are session-scoped, optionally tool-scoped, consumed on first match, and the consumption is visible as a[policy:permit]notice.confirmnever executes unconfirmed.- Context-window fitting (
[context]compaction). Local backends rejectprompt + max_tokens > contextoutright instead of truncating — every model call is now pre-fitted: oversized message contents are elided in place (head+tail kept, middle marked[…N bytes elided…]), then oldest non-anchor history drops when the estimate overflows — the system prompt and the FIRST user message (the task) are anchors that never drop, and a marker records the seam. The drop is written back into the session and announced via a[context]chunk — the loss is real, not hidden.max_tokensis clamped to what the window can emit. A still-overflowing 400 retries once; when the backend reports the real prompt size (prompt (N tokens)— llama.cpp/LM Studio family) the retry scales the char/4 estimate by the measured ratio instead of guessing. - Session snapshot durability + bounds. Saves hold a per-session writer lock (
{id}.lock), fsync the body before rename, and commit only when a{id}.donemarker is written — a snapshot without its marker loads as corrupt. Load validates the full schema (format_version, session_id match, required fields, message_count). Store caps: 2 MB per snapshot, 500 files, 64 MB total — over-limit saves are skipped.LLM_MAX_SESSIONSnow defaults to 256 (was unlimited). Final lock semantics in the R1–R5 entry below. - Session store ownership & crash protocol (R1–R5). The lock is now a real OS
flockon a permanent{id}.lockanchor held for the session's lifetime — a live session cannot be taken over by staleness heuristics, and a concurrentsession/loadrefuses-32003 session_busyimmediately..donebecomes a sha256-bound manifest committed by atomic rename;.json.prevkeeps the last verified generation for rollback.{id}.turnrecords turn intent (tmp+rename+fsync) before any tool dispatch — a turn whose marker cannot persist refuses to run, and a leftover marker marks the restored historyinterruptedinstead of replaying.store.lockserializes the cross-process quota check+write section; cleanup probes candidate flocks instead of trusting in-process liveness. - Capability-beneath file writes (R6).
write_file/editside effects resolve under a workspaceDirpinned at open time viacap-std(openat2 RESOLVE_BENEATHon Linux, per-componentopenatfallback elsewhere) — a swapped or symlinked parent directory can no longer redirect a write outside the sandbox, by mechanism rather than repeated checks. The canonicalize/prefix check remains as the explicit refusal contract;editpublishes by tmp+rename so a hardlink alias outside the workspace cannot be truncated. - Ollama native backend. When
LLM_BASE_URLcarries no/v1suffix, chat runs on native/api/chatwith NDJSON streaming; the backend probe reads/api/shownum_ctx+ capabilities (config mismatches warn, never block); each turn snapshots/api/psintoevidence.backend_modelsand accumulates native load/prefill/decode timings intoevidence.backendTiming. The OpenAI-compatible path is unchanged; absent fields mean unmeasured, never fabricated. - Real streaming in the main loop.
fit_and_calluseschat_streamed: answer text incrementsagent_message_chunk, reasoning incrementsagent_thought_chunkwith real text; OpenAI SSEtool_callsdeltas are assembled by index; a JSON-content-type response falls back to whole-body parsing; a channel that closes without a terminalFinalreports a truncated-stream error instead of silent success. - Mid-turn steer. A second prompt during a running turn joins a per-session steer queue (cap 8) instead of failing
turn_in_progress:receivednotifies immediately,appliedinjects[steer mid-turn]at the next round boundary,queued(image prompts, late arrivals) runs a full turn under the real request id when the slot frees.evidence.steers_appliedcounts injections; losing the slot race is an explicit error, never a silent drop. - Tool journal (P3).
{id}.tools.jsonlis an append-only record ofstart/done/interrupted/turnentries — thestartis fsync'd before dispatch, so a Write/Shell tool whose journal write fails refuses to run (an unjournaled mutation is unreconcilable); read/web calls proceed with an explicit unrecorded note. Same-turn redelivery dedup keys on the full-args sha256 and is scoped to records after the latestturnboundary; unclosedstarts reconcile asinterruptedonce, with the affected calls named in history — never silently replayed or claimed complete. Compaction rewrites through tmp+rename. web_fetchsource records. A successful fetch persistssource-<host>-<ts>.json(url/status/contentType/truncated/fetchedAt/reduced body) under the session artifact dir and the tool result names the path — fetched pages stay citable and re-readable after inline elision.- Per-turn tool-output budget.
LLM_TURN_TOOL_CHARS(default 16384) bounds cumulative tool output within a turn — the budget-spent tail degrades to metrics-plus-artifact pointers, the decisive bound for rounds whose current-turn tool group cannot be elided. - Image support corrections. Each image payload estimates a flat
IMAGE_CONTEXT_ESTIMATE_TOKENS(1536) instead of counting base64 as prompt text (a 1 MB image no longer reads as ~450k tokens);LLM_IMAGE_HISTORY_MAX(default 3) bounds live image payloads (not bearing messages), offloading the oldest to artifacts with explicit re-readable markers. - Turn-boundary quotas (G1a-Q2).
LLM_MAX_INFLIGHT(default 8) bounds concurrent turns globally — the excess prompt is refusedserver_busy;LLM_MAX_PROMPT_CHARS(default 200K) refuses oversized payloads asprompt_too_large. Both statuses are identifiable; cancel/completion frees the slot. - Quota-triggered store cleanup (G1a-Q3). When the cumulative store quota refuses a snapshot, the oldest non-active sessions' snapshots+artifacts are evicted and the save retried once — live sessions are never candidates.
- Inbound transport bound. ACP stdio frames are capped at 4 MiB (
frame::read_frame) — an oversized frame is dropped whole and the stream resyncs on the next newline instead of growing memory without limit. - User-input pre-trim. A single user message estimated above half the usable window is offloaded to
{LLM_SESSION_DIR}/artifacts/<session>/user-input.txtand history keeps a bounded head plus aread_filepointer — the turn survives instead of dying on a protected-input context rejection. RequiresLLM_SESSION_DIR; without a store the existing rejection remains the boundary. - Backend-reported window learning. An overflow error naming its real context (
context (N tokens), Ollama'srequest (N)/context size (N)forms included) shrinks the session's effective window for the in-flight retry AND all later calls, down to but never aboveLLM_MODEL_CONTEXT. - Tool-output artifacts. Results past
LLM_ARTIFACT_CHARS(default 8192) are written to{LLM_SESSION_DIR}/artifacts/<session>/<call>.txt(tmp+rename+fsync, inside the recursive store quota) and history keeps a head excerpt plus a re-readableread_filepointer.read_fileaccepts absolute paths only inside the session artifact root — every other absolute path stays denied. WithoutLLM_SESSION_DIRoutputs truncate at the same budget. read_fileline pagination. Optionaloffset(1-based) andlimitparameters return a[lines X-Y of N]header plus the slice — the supported way to page through artifact files and large sources instead of pulling whole files into history.- Live Ollama E2E test.
tests/live_ollama.rs(gated onACP_LIVE_BASE_URL) drives a real backend over stdio: streamed chunks,backendTiming, tool journal records, steer queueing, and image-block delivery.
Fixed
- Review round-2 hardening. Rejected
write_filepaths under symlinked parents no longercreate_dir_allinto the outside target (the deepest existing ancestor is canonical-verified first, and the new parent is re-verified after); process stdout/stderr are drained incrementally with a 1 MB retained bound per stream soyes-style output cannot exhaust memory;search_code/list_dircan no longer leak denied files (deny is checked before the hidden-file filter and counted as a policy skip); session snapshot ids reject any character outside[A-Za-z0-9_-]outright (no sanitize-collision) and snapshots carry amessage_countcompleteness check pluswriter_pidprovenance. session/cancelaborts an active ACP prompt and reports cancellation on both wire versions; concurrent prompts for one session are rejected; a cancelled turn is closed in history with a[cancelled by user]reply; an LLM response cut off mid-body is retried once.- Recovery path no longer pushes the raw assistant response into history twice, and recovered tool calls are recorded on the assistant message they belong to so
embedded_*tool results are not orphaned. session/newvalidatescwdby canonicalizing it and requiring an existing directory; invalid paths are rejected with-32602instead of being silently character-filtered (which mangled Windows paths likeC:\tools\proj).session/promptdrops image content blocks when image support is disabled (LLM_SUPPORTS_IMAGEunset/false) and emits a visible notice, instead of forwarding them and surfacing a provider HTTP 400.- Tool-timeout path kills the child before joining output readers — waiting on readers first would hang until the process exits on its own. The process group is now killed on EVERY completion path (timeout AND normal exit) before the reader join, and reader/wait joins carry grace deadlines — a
cmd &-style grandchild holding pipes open can no longer hang the tool call. write_filepublishes atomically: payload is written to a same-dir temp name inside the CANONICAL parent path andrename()d over the target —renamereplaces the dentry, so a symlink swapped in at write time can no longer redirect bytes outside the sandbox; the parent is re-canonicalized after the payload write and a leaked temp file is cleaned up on refusal.- Terminal-state race (G1a-C1): a cancel arriving after the engine's result already committed reports the completion — the turn no longer masquerades as
cancelledwhile dropping a finished result. - Dangling tool calls (G1a-C2): an aborted turn closes any tool_call ids left without results with an explicit aborted marker — the next turn can't send a malformed tool_calls group.
- Backend error classification: HTTP 413 →
payload_too_large, context-shaped 400/422 →context_overflow(typedLlmErrorKinds; both feed the bounded fit-and-retry). Error bodies are capped at 64 KiB and success bodies at 32 MiB; backend error text is no longer echoed — only the status line and numericprompt (N)/context (N)figures survive into diagnostics. read_filepagination arithmetic saturates on hostile u64offset/limit(was a potential overflow panic); artifact files up to the store's 2 MB quota stay readable through their pointer (the 1 MB workspace cap is unchanged); Windows absolute paths (C:\…, UNC) are recognized viaPath::is_absoluteinstead of a/prefix check.- Tool-output elision is idempotent, including the newest tool result; user instructions and tool arguments are not text-truncated. Dropped tool calls take their results with them and record loss markers; an unchanged overflowing request is never retried identically.
- Context diagnostics are classified and numeric (estimated/actual sizes, attempt numbers) — request content is never logged.
- The summary path respects the learned effective window (
min(config, learned)for its own budget); the identical-request dedup keys on messages AND output budget, so a retry with a smallermax_tokensafter a learned-window shrink is not mistaken for a duplicate; fallback compaction protects the working-memory summary carrying user constraints. - An
appliedsteer prompt responds in the negotiated wire shape (v1stopReason/ v2state_update+messageId) — a bespoke envelope previously left strict Clients unable to close the request. - A turn-boundary journal record that fails to persist disables dedup for that turn — the lookup window can no longer silently extend into the previous turn and replay a stale outcome.
- On non-Unix targets a timed-out tool kills the child directly (
start_kill) instead of relying on drop semantics. - An empty or whitespace-only
LLM_SESSION_DIRdisables the store — it no longer writes snapshots into the process cwd. turn_registry/steer_queueslock points recover from mutex poisoning (same as the sessions RwLock) instead of cascading a poisoned.expectinto abort.- The test suite is Windows-portable (
CARGO_MANIFEST_DIR-relative cwd,cfg(unix)on bash/process tests).
Changed
- Configuration is now strict. An unreadable or unparseable TOML config file, an unknown section/field, or a present-but-invalid
LLM_*env var is a startup error (exit code 2) instead of a silent fallback to defaults.LlmConfig::from_envandConfigFile::into_llm_configreturnResult. Old configs that only used documented fields are unaffected; configs written for future fields (e.g.[permissions]) must now be updated or the binary refuses to start. execute_tooltakes adeny_globsargument so policy applies to enumeration results and direct callers alike; shell tools cannot be path-filtered honestly (command strings are opaque) —denyshell if that matters, the limitation is documented indocs/scope.md.- Context is budgeted on serialized messages — tools, arguments, and provider-calibrated token counts (learned from successful usage and overflow reports), with output budget reserved separately; protected inputs that still overflow are refused explicitly rather than truncated.
- Older history is summarized through a bounded no-tools model call before deterministic pruning (
LLM_AUTO_SUMMARIZE,LLM_SUMMARIZE_AT): task and latest-user anchors plus recent complete tool groups are preserved; a failed summary keeps the original working history and backs off four calls. - History trimming runs on user-turn boundaries — the pre-prompt message-count trim is replaced by the summary trigger, and explicit trims never split a tool_call/result group.
Known limitations
- On Windows a timed-out tool kills the direct child only — process-tree kill remains Unix-only, and grandchildren may survive.
- Session locks are advisory
flocks: a writer bypassing the store API is unconstrained; journal fsync durability follows the filesystem's guarantees. - File reads (
read_file/list_dir/search_code) still resolve canonicalize-then-open — a racing rename within process privileges can redirect a read; the write side is beneath-pinned. - Journal dedup assumes the journal file survives intact; a failed
turnboundary record disables dedup for that turn (fail-safe direction: re-execution, never stale replay). - Vision is validated only at the transport level (image blocks reach the backend and are dropped gracefully when disabled); model-side comprehension is unverified.
- Ctrl+C console-event termination on Windows is untested (taskkill and stdin EOF paths are verified); UNC paths are unverified.