Skip to content

v0.10.0

Latest

Choose a tag to compare

@github-actions github-actions released this 26 Nov 15:14

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 partial status. LLM_MAX_TOOL_ROUNDS (default 50, aligned with openab-agent's OPENAB_AGENT_MAX_TOOL_LOOPS) bounds model↔tool round-trips; on exhaustion a wrap-up call asks the model for a final answer, reported as status: "partial" + stopReason: "max_turn_requests" — never as completed. 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-ending state_update.
  • Capability tool policy. [policy] section / LLM_POLICY_{READ,WRITE,SHELL,WEB} with four actions: allow executes; audit emits a visible [policy:audit] notice then executes; confirm executes only with a deployment grant ([policy] grants / LLM_POLICY_GRANTS) and denies otherwise — it never executes unconfirmed; deny returns a structured Denied tool 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' path argument AND on every path list_dir/search_code enumerate — 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 carry exit_code, error_kind, and truncated flags.
  • Opt-in session snapshots. LLM_SESSION_DIR enables atomic per-session JSON snapshots; session/load/session/resume restore across restarts and loadSession is 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:latest only moves on clean tags.
  • session/permit — per-operation grants. A confirm-blocked tool call can be rescued by a single-use, TTL-bound (≤3600s) permit the Client issues via session/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. confirm never executes unconfirmed.
  • Context-window fitting ([context] compaction). Local backends reject prompt + max_tokens > context outright 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_tokens is 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}.done marker 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_SESSIONS now 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 flock on a permanent {id}.lock anchor held for the session's lifetime — a live session cannot be taken over by staleness heuristics, and a concurrent session/load refuses -32003 session_busy immediately. .done becomes a sha256-bound manifest committed by atomic rename; .json.prev keeps the last verified generation for rollback. {id}.turn records 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 history interrupted instead of replaying. store.lock serializes the cross-process quota check+write section; cleanup probes candidate flocks instead of trusting in-process liveness.
  • Capability-beneath file writes (R6). write_file/edit side effects resolve under a workspace Dir pinned at open time via cap-std (openat2 RESOLVE_BENEATH on Linux, per-component openat fallback 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; edit publishes by tmp+rename so a hardlink alias outside the workspace cannot be truncated.
  • Ollama native backend. When LLM_BASE_URL carries no /v1 suffix, chat runs on native /api/chat with NDJSON streaming; the backend probe reads /api/show num_ctx + capabilities (config mismatches warn, never block); each turn snapshots /api/ps into evidence.backend_models and accumulates native load/prefill/decode timings into evidence.backendTiming. The OpenAI-compatible path is unchanged; absent fields mean unmeasured, never fabricated.
  • Real streaming in the main loop. fit_and_call uses chat_streamed: answer text increments agent_message_chunk, reasoning increments agent_thought_chunk with real text; OpenAI SSE tool_calls deltas are assembled by index; a JSON-content-type response falls back to whole-body parsing; a channel that closes without a terminal Final reports 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: received notifies immediately, applied injects [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_applied counts injections; losing the slot race is an explicit error, never a silent drop.
  • Tool journal (P3). {id}.tools.jsonl is an append-only record of start/done/interrupted/turn entries — the start is 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 latest turn boundary; unclosed starts reconcile as interrupted once, with the affected calls named in history — never silently replayed or claimed complete. Compaction rewrites through tmp+rename.
  • web_fetch source records. A successful fetch persists source-<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 refused server_busy; LLM_MAX_PROMPT_CHARS (default 200K) refuses oversized payloads as prompt_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.txt and history keeps a bounded head plus a read_file pointer — the turn survives instead of dying on a protected-input context rejection. Requires LLM_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's request (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 above LLM_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-readable read_file pointer. read_file accepts absolute paths only inside the session artifact root — every other absolute path stays denied. Without LLM_SESSION_DIR outputs truncate at the same budget.
  • read_file line pagination. Optional offset (1-based) and limit parameters 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 on ACP_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_file paths under symlinked parents no longer create_dir_all into 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 so yes-style output cannot exhaust memory; search_code/list_dir can 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 a message_count completeness check plus writer_pid provenance.
  • session/cancel aborts 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/new validates cwd by canonicalizing it and requiring an existing directory; invalid paths are rejected with -32602 instead of being silently character-filtered (which mangled Windows paths like C:\tools\proj).
  • session/prompt drops image content blocks when image support is disabled (LLM_SUPPORTS_IMAGE unset/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_file publishes atomically: payload is written to a same-dir temp name inside the CANONICAL parent path and rename()d over the target — rename replaces 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 cancelled while 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 (typed LlmErrorKinds; 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 numeric prompt (N) / context (N) figures survive into diagnostics.
  • read_file pagination arithmetic saturates on hostile u64 offset/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 via Path::is_absolute instead 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 smaller max_tokens after a learned-window shrink is not mistaken for a duplicate; fallback compaction protects the working-memory summary carrying user constraints.
  • An applied steer prompt responds in the negotiated wire shape (v1 stopReason / v2 state_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_DIR disables the store — it no longer writes snapshots into the process cwd.
  • turn_registry/steer_queues lock points recover from mutex poisoning (same as the sessions RwLock) instead of cascading a poisoned .expect into 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_env and ConfigFile::into_llm_config return Result. 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_tool takes a deny_globs argument so policy applies to enumeration results and direct callers alike; shell tools cannot be path-filtered honestly (command strings are opaque) — deny shell if that matters, the limitation is documented in docs/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 turn boundary 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.