mirror of
https://github.com/Twigpine/zero.git
synced 2026-11-11 23:40:28 -10:00
* feat: agent quality, caching, retry, and tooling upgrades Ten self-contained improvements to the core agent engine and tools: - edit_file: fuzzy fallback matching (7-strategy cascade with uniqueness protection and a disproportion guard) when old_string does not match byte-for-byte; exact match remains the fast path - edit_file/write_file: inline error-severity LSP diagnostics in tool output so the model sees a break it introduced in the same turn - lsp: expand server registry from 4 to 28 languages; doctor grades only tier-1 servers and lists the long tail informationally - agent: consecutive read-only tool calls execute concurrently (bounded at 8), consumed in original order, never spanning a mutating call - anthropic: cache_control breakpoints on the last two conversation messages so the transcript prefix stays a prompt-cache hit - providerio: retry schedule raised to 6 attempts with exponential 2s-30s backoff when the server sends no Retry-After - tools: truncated exec/bash output spills to a redacted temp file referenced in the truncation notice; bash output (previously unbounded) now shares exec_command's token budget - web_fetch: dependency-free HTML-to-markdown conversion (format: auto|raw|markdown) and larger limits (256KiB default, 2MiB max, 30s) - modelregistry: live models.dev overlay refreshes context limits and base pricing from a TTL-cached fetch; opt-in at the CLI entrypoint - tools: opt-in format-on-write (ZERO_FORMAT_ON_WRITE=1) runs standard formatters across 27 extensions, ordered before the file-tracker re-baseline so conflict detection is preserved * fix: address PR review feedback on fuzzy edits, diagnostics, spill - edit_file: adapt the replacement to the fuzzy-resolved span — when the span is a uniformly deeper-indented copy of old_string (line-trimmed / indentation-flexible matches), the same indentation delta is applied to new_string, and a span ending in a bare CR keeps its CR so CRLF files never gain a mixed line ending; block-anchor matches with drifted interiors are deliberately left untouched - diagnostics: render workspace-relative paths in inline post-edit diagnostics (base name outside the workspace) so absolute paths never leak the local username or directory layout into the model prompt or session transcript - spill: harden the spill directory for shared temp dirs — per-uid name, reject symlinked or non-directory paths (MkdirAll follows symlinks), and on Unix require current-user ownership - bash: the branch's output cap and truncation-flag threading are superseded by main's capture-time bounding (boundedBuffer + budgetBashCapture), which already sets Result.Truncated; this rebase adopts that design and keeps spill-to-disk on exec_command, where the full output is still buffered and a spill is genuinely complete * fix: address review round 2 — permission-event race, fuzzy ambiguity, spill reachability - agent: serialize OnPermission behind the same mutex as OnPermissionRequest in the parallel read batch. buildPermissionEvent fires for batched reads with a non-trivial sandbox decision (e.g. a grant-matched extra root), and front-end handlers append to shared session-recording state without their own locking — two batched reads emitting concurrently was a data race the pre-batch serial loop never allowed. - edit_file: reject two or more DISTINCT candidate spans from one fuzzy strategy as ambiguous instead of silently editing the first. Duplicate blocks at different indentation each resolve to a unique literal, so the previous occurrence-uniqueness check passed and wrote the wrong span. A single candidate occurring at multiple positions still cascades to stricter strategies as before. - tools: make spill files actually reachable by the recovery path the truncation notice advertises — resolveScopedReadPath now recognizes files inside the per-uid spill dir (containment verified after symlink resolution, so a planted link cannot smuggle an out-of-scope file through the gate); read_file/grep can follow the notice instead of re-running the command. * fix: surface competing block-anchor spans; make write-barrier test observe cross-probe order - edit_file: blockAnchorReplacer now returns every span clearing the similarity threshold (best first) instead of silently picking the single most-similar block. Hiding competitors from the cascade's distinct-candidate check could edit the wrong block when two blocks share anchors and both interiors are plausible; one clear winner still resolves, two plausible blocks now report ambiguity (covered by a two-block test that asserts the file is untouched). - agent tests: the parallel write-barrier test now records both probes into one mutex-guarded shared log and asserts the cross-probe ordering it always claimed to (write starts after the first read batch ends; second read batch starts after the write ends). The previous version only compared indices within the read probe's own log, which a regression letting the write overlap a batch could still pass; the stray no-op mutex assignment is gone.
229 lines
7.1 KiB
Go
229 lines
7.1 KiB
Go
package modelregistry
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
const sampleModelsDev = `{
|
|
"anthropic": {
|
|
"id": "anthropic",
|
|
"models": {
|
|
"claude-sonnet-4-5-20250929": {
|
|
"limit": {"context": 1000000, "output": 64000},
|
|
"cost": {"input": 3.5, "output": 17.5, "cache_read": 0.35, "cache_write": 4.4}
|
|
}
|
|
}
|
|
},
|
|
"google": {
|
|
"id": "google",
|
|
"models": {
|
|
"gemini-2.5-pro": {
|
|
"limit": {"context": 2097152, "output": 65536},
|
|
"cost": {"input": 9.99, "output": 9.99}
|
|
}
|
|
}
|
|
}
|
|
}`
|
|
|
|
func TestParseModelsDev(t *testing.T) {
|
|
providers, err := parseModelsDev([]byte(sampleModelsDev))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
record, ok := providers["anthropic"]["claude-sonnet-4-5-20250929"]
|
|
if !ok {
|
|
t.Fatal("expected anthropic sonnet record")
|
|
}
|
|
if record.Limit.Context != 1_000_000 || record.Cost.Input != 3.5 {
|
|
t.Fatalf("unexpected record: %+v", record)
|
|
}
|
|
if _, err := parseModelsDev([]byte(`{}`)); err == nil {
|
|
t.Fatal("empty document must be rejected")
|
|
}
|
|
if _, err := parseModelsDev([]byte(`not json`)); err == nil {
|
|
t.Fatal("malformed document must be rejected")
|
|
}
|
|
}
|
|
|
|
func TestApplyModelsDevOverrides(t *testing.T) {
|
|
// Point the cache at a non-existent file so DefaultModelEntries returns the
|
|
// pure curated catalog, then apply the sample snapshot explicitly.
|
|
t.Setenv("ZERO_MODELS_CACHE_PATH", filepath.Join(t.TempDir(), "absent.json"))
|
|
resetModelsDevCacheForTest()
|
|
t.Cleanup(resetModelsDevCacheForTest)
|
|
|
|
providers, err := parseModelsDev([]byte(sampleModelsDev))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
entries := applyModelsDevOverrides(DefaultModelEntries(), providers)
|
|
|
|
var sonnet, geminiPro, opus ModelEntry
|
|
for _, entry := range entries {
|
|
switch entry.ID {
|
|
case "claude-sonnet-4.5":
|
|
sonnet = entry
|
|
case "gemini-2.5-pro":
|
|
geminiPro = entry
|
|
case "claude-opus-4.1":
|
|
opus = entry
|
|
}
|
|
}
|
|
|
|
// Known model: limits and base pricing refreshed from the snapshot.
|
|
if sonnet.ContextLimits.ContextWindow != 1_000_000 || sonnet.ContextLimits.MaxOutputTokens != 64_000 {
|
|
t.Fatalf("sonnet limits not overridden: %+v", sonnet.ContextLimits)
|
|
}
|
|
if sonnet.Cost.InputPerMillion != 3.5 || sonnet.Cost.OutputPerMillion != 17.5 || sonnet.Cost.CacheWritePerMillion != 4.4 {
|
|
t.Fatalf("sonnet cost not overridden: %+v", sonnet.Cost)
|
|
}
|
|
if sonnet.Cost.Source != "models.dev/api.json (cached)" {
|
|
t.Fatalf("sonnet cost source not marked: %q", sonnet.Cost.Source)
|
|
}
|
|
|
|
// Tiered pricing is curated: limits refresh, cost must NOT (gemini-2.5-pro
|
|
// has curated tiers and the snapshot's flat 9.99 would misprice them).
|
|
if geminiPro.ContextLimits.ContextWindow != 2_097_152 {
|
|
t.Fatalf("gemini limits not overridden: %+v", geminiPro.ContextLimits)
|
|
}
|
|
if geminiPro.Cost.InputPerMillion == 9.99 || len(geminiPro.Cost.Tiers) == 0 {
|
|
t.Fatalf("tiered cost must stay curated: %+v", geminiPro.Cost)
|
|
}
|
|
|
|
// Model absent from the snapshot: untouched.
|
|
if opus.ContextLimits.ContextWindow != 200_000 || opus.Cost.InputPerMillion != 15 {
|
|
t.Fatalf("opus must be untouched: %+v %+v", opus.ContextLimits, opus.Cost)
|
|
}
|
|
}
|
|
|
|
func TestRefreshModelsDevCacheFetchesAndCaches(t *testing.T) {
|
|
hits := 0
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
hits++
|
|
_, _ = w.Write([]byte(sampleModelsDev))
|
|
}))
|
|
defer server.Close()
|
|
|
|
cachePath := filepath.Join(t.TempDir(), "modelsdev.json")
|
|
t.Setenv("ZERO_MODELS_CACHE_PATH", cachePath)
|
|
t.Setenv("ZERO_MODELS_URL", server.URL)
|
|
t.Setenv("ZERO_DISABLE_MODELS_FETCH", "")
|
|
|
|
if err := RefreshModelsDevCache(t.Context()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if hits != 1 {
|
|
t.Fatalf("expected 1 fetch, got %d", hits)
|
|
}
|
|
if _, err := os.Stat(cachePath); err != nil {
|
|
t.Fatalf("cache file missing: %v", err)
|
|
}
|
|
// Fresh cache: second call must not re-fetch.
|
|
if err := RefreshModelsDevCache(t.Context()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if hits != 1 {
|
|
t.Fatalf("fresh cache must skip the fetch, got %d hits", hits)
|
|
}
|
|
}
|
|
|
|
func TestRefreshModelsDevCacheRejectsBadBodyWithoutClobbering(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_, _ = w.Write([]byte("not json"))
|
|
}))
|
|
defer server.Close()
|
|
|
|
cachePath := filepath.Join(t.TempDir(), "modelsdev.json")
|
|
if err := os.WriteFile(cachePath, []byte(sampleModelsDev), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
stale := time.Now().Add(-48 * time.Hour)
|
|
if err := os.Chtimes(cachePath, stale, stale); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("ZERO_MODELS_CACHE_PATH", cachePath)
|
|
t.Setenv("ZERO_MODELS_URL", server.URL)
|
|
|
|
if err := RefreshModelsDevCache(t.Context()); err == nil {
|
|
t.Fatal("bad body must return an error")
|
|
}
|
|
content, err := os.ReadFile(cachePath)
|
|
if err != nil || string(content) != sampleModelsDev {
|
|
t.Fatal("bad fetch must not clobber the existing cache")
|
|
}
|
|
}
|
|
|
|
func TestRefreshModelsDevCacheDisabledByEnv(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
t.Fatal("fetch must not happen when disabled")
|
|
}))
|
|
defer server.Close()
|
|
t.Setenv("ZERO_MODELS_CACHE_PATH", filepath.Join(t.TempDir(), "modelsdev.json"))
|
|
t.Setenv("ZERO_MODELS_URL", server.URL)
|
|
t.Setenv("ZERO_DISABLE_MODELS_FETCH", "1")
|
|
if err := RefreshModelsDevCache(t.Context()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func TestCachedModelsDevProvidersIgnoresStaleCache(t *testing.T) {
|
|
cachePath := filepath.Join(t.TempDir(), "modelsdev.json")
|
|
if err := os.WriteFile(cachePath, []byte(sampleModelsDev), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
stale := time.Now().Add(-modelsDevMaxAge - time.Hour)
|
|
if err := os.Chtimes(cachePath, stale, stale); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("ZERO_MODELS_CACHE_PATH", cachePath)
|
|
resetModelsDevCacheForTest()
|
|
t.Cleanup(resetModelsDevCacheForTest)
|
|
EnableModelsDevOverlay()
|
|
|
|
if providers := cachedModelsDevProviders(); providers != nil {
|
|
t.Fatal("stale cache must be ignored")
|
|
}
|
|
}
|
|
|
|
func TestCachedModelsDevProvidersRequiresOptIn(t *testing.T) {
|
|
cachePath := filepath.Join(t.TempDir(), "modelsdev.json")
|
|
if err := os.WriteFile(cachePath, []byte(sampleModelsDev), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("ZERO_MODELS_CACHE_PATH", cachePath)
|
|
resetModelsDevCacheForTest()
|
|
t.Cleanup(resetModelsDevCacheForTest)
|
|
|
|
// Without EnableModelsDevOverlay a fresh, valid cache must still be ignored:
|
|
// library consumers and hermetic tests get the pure curated catalog.
|
|
if providers := cachedModelsDevProviders(); providers != nil {
|
|
t.Fatal("overlay must be opt-in")
|
|
}
|
|
}
|
|
|
|
func TestDefaultModelEntriesAppliesFreshCache(t *testing.T) {
|
|
cachePath := filepath.Join(t.TempDir(), "modelsdev.json")
|
|
if err := os.WriteFile(cachePath, []byte(sampleModelsDev), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("ZERO_MODELS_CACHE_PATH", cachePath)
|
|
resetModelsDevCacheForTest()
|
|
t.Cleanup(resetModelsDevCacheForTest)
|
|
EnableModelsDevOverlay()
|
|
|
|
for _, entry := range DefaultModelEntries() {
|
|
if entry.ID == "claude-sonnet-4.5" {
|
|
if entry.ContextLimits.ContextWindow != 1_000_000 {
|
|
t.Fatalf("fresh cache must overlay the registry: %+v", entry.ContextLimits)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
t.Fatal("claude-sonnet-4.5 not found")
|
|
}
|