From d37b821908151b916b02c97d9b9c60e6582ae986 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 30 Sep 2026 09:31:59 +0800 Subject: [PATCH] =?UTF-8?q?toml:=20Codex's=20config.toml=20with=20a=20mult?= =?UTF-8?q?i-line=20array=20(notify=20=3D=20[=20=E2=80=A6=20])=20is=20edit?= =?UTF-8?q?ed=20right,=20and=20an=20edit=20that=20fails=20leaves=20every?= =?UTF-8?q?=20file=20as=20it=20was=20(#253=20kerwinliu00001:=20"edited=20T?= =?UTF-8?q?OML=20is=20invalid:=20line=202,=20column=201:=20incomplete=20nu?= =?UTF-8?q?mber",=20config.toml=20left=20with=20model=5Fprovider=20gone=20?= =?UTF-8?q?and=20[model=5Fproviders.magpie]=20added=20but=20no=20model)=20?= =?UTF-8?q?=E2=80=94=20the=20top-level=20key=20edits=20(GetTOMLTop,=20SetT?= =?UTF-8?q?OMLTop,=20DelTOMLTop)=20went=20line=20by=20line=20with=20regexe?= =?UTF-8?q?s:=20a=20new=20key=20went=20after=20the=20last=20line=20that=20?= =?UTF-8?q?looked=20like=20`key=20=3D=20=E2=80=A6`,=20which=20for=20`notif?= =?UTF-8?q?y=20=3D=20[`=20was=20inside=20the=20array;=20`key=20=3D=20value?= =?UTF-8?q?`=20lines=20inside=20a=20multi-line=20string=20were=20read=20as?= =?UTF-8?q?=20keys=20and=20a=20line=20starting=20with=20`[`=20as=20a=20tab?= =?UTF-8?q?le;=20replacing=20or=20deleting=20a=20multi-line=20value=20touc?= =?UTF-8?q?hed=20only=20its=20first=20line.=20They=20now=20locate=20the=20?= =?UTF-8?q?top-level=20keys=20with=20the=20TOML=20parser,=20as=20the=20tab?= =?UTF-8?q?le=20edits=20already=20did,=20each=20with=20its=20value's=20who?= =?UTF-8?q?le=20range=20however=20many=20lines=20it=20takes=20(parseTOMLFi?= =?UTF-8?q?le,=20the=20unnamed=20root=20table=20beside=20the=20tables);=20?= =?UTF-8?q?SetTOMLTop=20finds=20all=20its=20keys=20in=20the=20file=20as=20?= =?UTF-8?q?read=20and=20writes=20once.=20A=20file=20the=20parser=20refuses?= =?UTF-8?q?=20is=20still=20read=20line=20by=20line,=20so=20a=20broken=20co?= =?UTF-8?q?nfig=20keeps=20showing=20its=20model,=20and=20writes=20to=20it?= =?UTF-8?q?=20are=20refused=20untouched.=20And=20a=20pick=20is=20several?= =?UTF-8?q?=20writes=20(Codex:=20drop=20model=5Fprovider,=20add=20magpie's?= =?UTF-8?q?=20provider=20table,=20set=20openai=5Fbase=5Furl=20and=20model)?= =?UTF-8?q?,=20each=20checked,=20so=20one=20failing=20left=20the=20earlier?= =?UTF-8?q?=20ones=20on=20disk:=20edit.Atomically(fn,=20paths=E2=80=A6)=20?= =?UTF-8?q?puts=20each=20file=20back=20to=20its=20bytes=20and=20mode,=20or?= =?UTF-8?q?=20removes=20one=20it=20created,=20when=20fn=20fails,=20and=20e?= =?UTF-8?q?very=20field=20set=20and=20Sync=20of=20Codex=20(config.toml=20a?= =?UTF-8?q?nd=20magpie-models.json,=20so=20Codex=20in=20WSL=20too),=20Kimi?= =?UTF-8?q?=20and=20Grok=20goes=20through=20it,=20as=20do=20Codex's=20MCP?= =?UTF-8?q?=20server=20writes=20(putCodex,=20delCodex).=20Tested=20in=20te?= =?UTF-8?q?mp=20dirs=20and=20a=20temp=20HOME:=20the=20reporter's=20file=20?= =?UTF-8?q?read,=20set=20and=20deleted=20directly=20and=20through=20Codex'?= =?UTF-8?q?s=20model=20field=20(signed=20in,=20with=20model=5Fprovider=20a?= =?UTF-8?q?nd=20model=20above=20the=20array,=20with=20magpie=20as=20the=20?= =?UTF-8?q?provider),=20the=20array's=20text=20kept=20and=20the=20TOML=20v?= =?UTF-8?q?alid,=20and=20back=20to=20a=20Codex=20model;=20nested=20arrays,?= =?UTF-8?q?=20trailing=20commas,=20comments=20in=20arrays,=20[x]=20and=20a?= =?UTF-8?q?=20=3D=20b=20in=20strings,=20an=20inline=20table=20in=20an=20ar?= =?UTF-8?q?ray;=20"""=20and=20'''=20strings=20holding=20model=20=3D=20?= =?UTF-8?q?=E2=80=A6=20and=20[table]=20lines=20not=20read=20as=20keys,=20n?= =?UTF-8?q?ew=20keys=20after=20their=20closing=20quotes,=20one=20deleted?= =?UTF-8?q?=20whole;=20a=20forced=20failure=20of=20Codex's=20last=20write?= =?UTF-8?q?=20leaving=20config.toml=20byte-identical;=20TestAtomically.=20?= =?UTF-8?q?They=20fail=20on=20main=20(the=20Codex=20ones=20with=20the=20re?= =?UTF-8?q?porter's=20error).=20go=20vet=20./internal/...,=20go=20build=20?= =?UTF-8?q?-tags=20nogui=20(and=20GOOS=3Dlinux,=20GOOS=3Dwindows)=20and=20?= =?UTF-8?q?go=20test=20-tags=20nogui=20./...=20pass.=20Not=20tried=20again?= =?UTF-8?q?st=20a=20real=20~/.codex,=20in=20WSL=20or=20in=20the=20GUI;=20m?= =?UTF-8?q?ulti-line=20inline=20tables=20(TOML=201.1)=20are=20refused=20by?= =?UTF-8?q?=20the=20parser=20and=20so=20left=20untouched=20with=20an=20err?= =?UTF-8?q?or.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/agent/agent.go | 19 +++ internal/agent/codex.go | 4 +- internal/agent/codex_multiline_test.go | 79 ++++++++++ internal/agent/grok.go | 4 +- internal/agent/kimi.go | 4 +- internal/edit/file.go | 53 +++++++ internal/edit/text.go | 46 +----- internal/edit/toml.go | 188 +++++++++++++++++++---- internal/edit/toml_multiline_test.go | 202 +++++++++++++++++++++++++ internal/edit/toml_write_test.go | 18 ++- internal/library/mcp.go | 37 +++-- 11 files changed, 553 insertions(+), 101 deletions(-) create mode 100644 internal/agent/codex_multiline_test.go create mode 100644 internal/edit/toml_multiline_test.go diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 49442663a..e569a9739 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -13,6 +13,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" ) @@ -275,3 +276,21 @@ func (a *Agent) Spell(key, v string) (string, error) { } return v, nil } + +// atomic makes each of an agent's field sets, and its Sync, one edit of the +// files at paths: one that fails part way puts them all back as they were, +// rather than leaving, say, Codex's config.toml with magpie's provider table +// written but its model not (#253). +func atomic(a *Agent, paths ...string) *Agent { + for i := range a.Fields { + if set := a.Fields[i].Set; set != nil { + a.Fields[i].Set = func(v string) error { + return edit.Atomically(func() error { return set(v) }, paths...) + } + } + } + if sync := a.Sync; sync != nil { + a.Sync = func() error { return edit.Atomically(sync, paths...) } + } + return a +} diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 4a04dfcea..2c0a93ed1 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -246,7 +246,7 @@ func codexIn(at place) *Agent { return settle() } - return &Agent{ + return atomic(&Agent{ ID: "codex", Name: "Codex", Icon: "codex-color", Bin: "codex", Dir: dir, Path: path, UA: []string{"codex"}, Sync: func() error { @@ -413,7 +413,7 @@ func codexIn(at place) *Agent { }, }, }, - } + }, path, catalogPath) } func contains(xs []string, x string) bool { diff --git a/internal/agent/codex_multiline_test.go b/internal/agent/codex_multiline_test.go new file mode 100644 index 000000000..f90386d82 --- /dev/null +++ b/internal/agent/codex_multiline_test.go @@ -0,0 +1,79 @@ +package agent + +import ( + "reflect" + "strings" + "testing" + + "github.com/pelletier/go-toml/v2" +) + +// #253: a config.toml with a top-level array over several lines. Picking a +// model through magpie put the new top-level keys inside the array, and the +// failed write left the provider table appended but no model. +const codexNotify = `notify = [ + "/usr/local/bin/notifier", + "turn-ended", +] + +[model_providers.example] +base_url = "http://127.0.0.1:1/v1" +` + +func TestCodexMultilineArray(t *testing.T) { + for _, tc := range []struct{ name, auth, config string }{ + {"signed in", `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, codexNotify}, + {"signed in, on a provider of its own", `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, + "model = \"gpt-5.5\"\nmodel_provider = \"example\"\n" + codexNotify}, + {"as a provider", "", codexNotify}, + } { + t.Run(tc.name, func(t *testing.T) { + home, read := codexHome(t, tc.auth, tc.config) + cx := codex(home) + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + var cfg struct { + Model string + Notify []string + ModelProviders map[string]any `toml:"model_providers"` + } + if err := toml.Unmarshal([]byte(read()), &cfg); err != nil { + t.Fatalf("%v\n%s", err, read()) + } + if want := []string{"/usr/local/bin/notifier", "turn-ended"}; cfg.Model != "fake/m1" || !reflect.DeepEqual(cfg.Notify, want) || + cfg.ModelProviders["magpie"] == nil || cfg.ModelProviders["example"] == nil { + t.Fatalf("after the pick:\n%s", read()) + } + if !strings.Contains(read(), "notify = [\n \"/usr/local/bin/notifier\",\n \"turn-ended\",\n]\n") { + t.Fatalf("the array was rewritten:\n%s", read()) + } + // and back to one of Codex's own + if err := cx.Fields[0].Set("gpt-5.4"); err != nil { + t.Fatal(err) + } + if got := cx.Fields[0].Get(); got != "gpt-5.4" { + t.Fatalf("model = %q\n%s", got, read()) + } + if !strings.Contains(read(), "notify = [\n \"/usr/local/bin/notifier\",\n \"turn-ended\",\n]\n") { + t.Fatalf("the array was rewritten:\n%s", read()) + } + }) + } +} + +// A pick whose last step can't be written leaves config.toml byte for byte +// as it was, rather than with magpie's provider table added and no model: +// here a table named openai_base_url makes the key of that name a +// conflicting definition, found only once the earlier steps are written. +func TestCodexFailedPickLeavesConfig(t *testing.T) { + const config = "model = \"gpt-5.5\" # mine\nmodel_provider = \"example\"\n\n[openai_base_url]\nx = 1\n\n[model_providers.example]\nbase_url = \"http://127.0.0.1:1/v1\"\n" + home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, config) + err := codex(home).Fields[0].Set("fake/m1") + if err == nil || !strings.Contains(err.Error(), "edited TOML is invalid") { + t.Fatalf("err = %v\n%s", err, read()) + } + if got := read(); got != config { + t.Fatalf("config.toml left half-edited:\n%s", got) + } +} diff --git a/internal/agent/grok.go b/internal/agent/grok.go index 599281d82..6ae2ff4a5 100644 --- a/internal/agent/grok.go +++ b/internal/agent/grok.go @@ -98,7 +98,7 @@ func grok(home string) *Agent { } return catalog.Efforts(magpieModels("grok"), ref) } - return &Agent{ + return atomic(&Agent{ ID: "grok", Name: "Grok Build", Icon: "xai", Aliases: []string{"grok-build", "grok-cli"}, UA: []string{"grok-shell", "grok-pager", "xai-grok-build"}, // grok-pager: its terminal front end Dir: dir, Path: path, @@ -210,7 +210,7 @@ func grok(home string) *Agent { }, }, }, - } + }, path) } // grokOwnOptions are the models Grok Build offers its signed-in account, as diff --git a/internal/agent/kimi.go b/internal/agent/kimi.go index 9832e3454..f70150cf1 100644 --- a/internal/agent/kimi.go +++ b/internal/agent/kimi.go @@ -93,7 +93,7 @@ func kimi(home string) *Agent { t, err := edit.GetTOMLTable(path, "models."+strconv.Quote(k)) return err == nil && t != nil } - return &Agent{ + return atomic(&Agent{ ID: "kimi", Name: "Kimi Code", Icon: "kimi", Aliases: []string{"kimi-code", "kimi-cli"}, UA: []string{"kimicli"}, Bin: "kimi", Dir: dir, Path: path, @@ -161,7 +161,7 @@ func kimi(home string) *Agent { return append(kimiOwnOptions(path, cur["model"]), viaMagpie("kimi", magpieID+"/")...) }, }}, - } + }, path) } // kimiOwnOptions are the models of the user's own in Kimi's config: its diff --git a/internal/edit/file.go b/internal/edit/file.go index 8f4101107..8f7a9fa45 100644 --- a/internal/edit/file.go +++ b/internal/edit/file.go @@ -4,7 +4,9 @@ package edit import ( + "bytes" "errors" + "fmt" "io/fs" "os" "path/filepath" @@ -56,3 +58,54 @@ func WriteAtomic(path string, data []byte) error { } return nil } + +// Atomically runs fn, which may write the files at paths in several steps, +// and puts each of them back as it was — its bytes and mode, or its absence +// — when fn fails, so an edit that fails part way leaves no file half made. +// A file that can't be read beforehand is left to fn as it is. +func Atomically(fn func() error, paths ...string) error { + type saved struct { + path string + data []byte + mode fs.FileMode + exists bool + } + var before []saved + for _, p := range paths { + st, err := os.Stat(p) + if errors.Is(err, fs.ErrNotExist) { + before = append(before, saved{path: p}) + continue + } + if err != nil || !st.Mode().IsRegular() { + continue + } + b, err := os.ReadFile(p) + if err != nil { + continue + } + before = append(before, saved{p, b, st.Mode().Perm(), true}) + } + err := fn() + if err == nil { + return nil + } + for _, s := range before { + now, rerr := os.ReadFile(s.path) + switch { + case !s.exists: + if !errors.Is(rerr, fs.ErrNotExist) { + if e := os.Remove(s.path); e != nil && !errors.Is(e, fs.ErrNotExist) { + err = errors.Join(err, fmt.Errorf("put %s back: %w", s.path, e)) + } + } + case rerr != nil || !bytes.Equal(now, s.data): + if e := WriteAtomic(s.path, s.data); e != nil { + err = errors.Join(err, fmt.Errorf("put %s back: %w", s.path, e)) + } else if e := os.Chmod(s.path, s.mode); e != nil { + err = errors.Join(err, fmt.Errorf("put %s back: %w", s.path, e)) + } + } + } + return err +} diff --git a/internal/edit/text.go b/internal/edit/text.go index d67f1cf6e..61f5f3245 100644 --- a/internal/edit/text.go +++ b/internal/edit/text.go @@ -7,54 +7,20 @@ import ( "strings" ) -// Top-level TOML and YAML keys are edited line by line. That keeps every -// comment and every other line byte-for-byte intact, which a round trip -// through a parser would not. +// Top-level YAML keys are edited line by line. That keeps every comment and +// every other line byte-for-byte intact, which a round trip through a parser +// would not. TOML's are located by its parser (see toml.go), since a value +// there can run over several lines. var ( + // tomlTable and tomlKV only read a TOML file its parser refuses; see + // GetTOMLTop. tomlTable = regexp.MustCompile(`^\s*\[`) tomlKV = regexp.MustCompile(`^\s*([A-Za-z0-9_.-]+|"[^"]*")\s*=\s*(.*?)\s*$`) yamlKV = regexp.MustCompile(`^([A-Za-z0-9_.-]+)\s*:\s*(.*?)\s*$`) yamlPlain = regexp.MustCompile(`^[A-Za-z0-9._/-]+$`) ) -// GetTOMLTop reads a top-level (pre-table) key from a TOML file. -func GetTOMLTop(path, key string) (string, bool) { - raw, err := Read(path) - if err != nil || raw == nil { - return "", false - } - for _, line := range splitLines(string(raw)) { - if tomlTable.MatchString(line) { - break - } - if m := tomlKV.FindStringSubmatch(line); m != nil && strings.Trim(m[1], `"`) == key { - return tomlValue(m[2]), true - } - } - return "", false -} - -// SetTOMLTop sets top-level keys in a TOML file. Existing lines are replaced -// in place; new keys go right after the last existing top-level key. -func SetTOMLTop(path string, kvs ...KV) error { - raw, err := Read(path) - if err != nil { - return err - } - lines := splitLines(string(raw)) - for _, kv := range kvs { - lines = setLine(lines, kv.Path, kv.Path+" = "+strconv.Quote(toString(kv.Value)), tomlTable, func(line string) (string, bool) { - m := tomlKV.FindStringSubmatch(line) - if m == nil { - return "", false - } - return strings.Trim(m[1], `"`), true - }) - } - return writeTOML(path, lines) -} - // GetYAMLTop reads a top-level scalar key from a YAML file. func GetYAMLTop(path, key string) (string, bool) { raw, err := Read(path) diff --git a/internal/edit/toml.go b/internal/edit/toml.go index be382eb56..44a7c9741 100644 --- a/internal/edit/toml.go +++ b/internal/edit/toml.go @@ -195,29 +195,132 @@ func DelTOMLTable(path, name string) error { return writeTOML(path, out) } -// DelTOMLTop removes top-level (pre-table) keys. +// GetTOMLTop reads a top-level (pre-table) key from a TOML file. A string is +// decoded; any other value is its text as written, without a trailing +// comment, an array or inline table over several lines included. A file +// TOML's parser refuses is read line by line, as well as that goes. +func GetTOMLTop(path, key string) (string, bool) { + doc, err := tomlFileOf(path) + if err != nil { + return getTOMLTopLines(path, key) + } + for _, kv := range doc.root.keys { + if kv.name == key { + if kv.scalar { + return kv.value, true + } + return kv.text, true + } + } + return "", false +} + +// getTOMLTopLines is GetTOMLTop for a file that isn't valid TOML: the first +// line that looks like `key = value` before one that looks like a header. +func getTOMLTopLines(path, key string) (string, bool) { + raw, err := Read(path) + if err != nil || raw == nil { + return "", false + } + for _, line := range splitLines(string(raw)) { + if tomlTable.MatchString(line) { + break + } + if m := tomlKV.FindStringSubmatch(line); m != nil && strings.Trim(m[1], `"`) == key { + return tomlValue(m[2]), true + } + } + return "", false +} + +// SetTOMLTop sets top-level keys in a TOML file, as strings. An existing key +// is replaced as a whole, its value's every line with it; new keys go right +// after the last existing top-level key's value, or first in the file when +// there is none. Every key is located in the file as it was read, so the +// edit is one write that either happens entirely or not at all. +func SetTOMLTop(path string, kvs ...KV) error { + raw, err := Read(path) + if err != nil { + return err + } + lines := splitLines(string(raw)) + doc, err := parseTOMLFile(lines) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } + type span struct { + to int + line string + } + replace := map[int]span{} + var added []string + addedAt := map[string]int{} + at := 0 + if n := len(doc.root.keys); n > 0 { + at = doc.root.keys[n-1].to + } + for _, kv := range kvs { + line := kv.Path + " = " + strconv.Quote(toString(kv.Value)) + found := false + for _, k := range doc.root.keys { + if k.name == kv.Path { + replace[k.from] = span{k.to, line} + found = true + break + } + } + switch i, ok := addedAt[kv.Path]; { + case found: + case ok: + added[i] = line + default: + addedAt[kv.Path] = len(added) + added = append(added, line) + } + } + out := make([]string, 0, len(lines)+len(added)) + for i := 0; i < len(lines); { + if i == at { + out = append(out, added...) + added = nil + } + if r, ok := replace[i]; ok { + out = append(out, r.line) + i = r.to + continue + } + out = append(out, lines[i]) + i++ + } + out = append(out, added...) + return writeTOML(path, out) +} + +// DelTOMLTop removes top-level (pre-table) keys, each with every line of its +// value. func DelTOMLTop(path string, keys ...string) error { raw, err := Read(path) if err != nil || raw == nil { return err } + lines := splitLines(string(raw)) + doc, err := parseTOMLFile(lines) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } drop := map[string]bool{} for _, k := range keys { drop[k] = true } var out []string - header := true - for _, line := range splitLines(string(raw)) { - if header && tomlTable.MatchString(line) { - header = false + at := 0 + for _, kv := range doc.root.keys { + if drop[kv.name] { + out = append(out, lines[at:kv.from]...) + at = kv.to } - if header { - if m := tomlKV.FindStringSubmatch(line); m != nil && drop[strings.Trim(m[1], `"`)] { - continue - } - } - out = append(out, line) } + out = append(out, lines[at:]...) return writeTOML(path, out) } @@ -233,6 +336,7 @@ type tomlKeySpan struct { from, to int // to is -1 until the next expression or EOF bounds the value. column int // 1-based start of the key. name, value string + text string // The value as written, from prefix to suffix. prefix, suffix string // Original text before and after the complete value. comment int // Column of a trailing comment, or -1 when absent. scalar bool @@ -269,31 +373,56 @@ func tomlTableNamed(tables []tomlTableSpan, name string) (tomlTableSpan, bool) { // changes: an agent's config can be large (Codex's lists every project it // was trusted in) and is read field by field. Missing files are (nil, nil). func tomlTablesOf(path string) ([]tomlTableSpan, error) { - tables, err := filememo.Read("toml tables", path, func(b []byte) ([]tomlTableSpan, error) { - tables, err := parseTOMLTables(splitLines(string(b))) + doc, err := tomlFileOf(path) + return doc.tables, err +} + +// tomlFileOf is parseTOMLFile of a file, kept as tomlTablesOf says. A missing +// file is an empty document and no error. +func tomlFileOf(path string) (tomlFile, error) { + doc, err := filememo.Read("toml file", path, func(b []byte) (tomlFile, error) { + doc, err := parseTOMLFile(splitLines(string(b))) if err != nil { - return nil, fmt.Errorf("%s: %w", path, err) + return tomlFile{}, fmt.Errorf("%s: %w", path, err) } - return tables, nil + return doc, nil }) if errors.Is(err, fs.ErrNotExist) { - return nil, nil + return tomlFile{}, nil } - return tables, err + return doc, err } // parseTOMLTables finds both ordinary and array-table blocks in one parser pass. // Only top-level expressions delimit edits, so lines inside multiline values // cannot be mistaken for keys, comments, or table headers. func parseTOMLTables(lines []string) ([]tomlTableSpan, error) { + doc, err := parseTOMLFile(lines) + return doc.tables, err +} + +// tomlFile is a file's top-level (pre-table) keys, as the unnamed table root +// spanning [0, first header), and its table blocks in file order. +type tomlFile struct { + root tomlTableSpan + tables []tomlTableSpan +} + +// parseTOMLFile is parseTOMLTables with the top-level keys too, located the +// same way: a key's range covers its whole value, however many lines it takes. +func parseTOMLFile(lines []string) (tomlFile, error) { p := unstable.Parser{KeepComments: true} p.Reset([]byte(strings.Join(lines, "\n"))) + root := tomlTableSpan{to: len(lines)} var tables []tomlTableSpan - finishKey := func(to int) error { + current := func() *tomlTableSpan { if len(tables) == 0 { - return nil + return &root } - table := &tables[len(tables)-1] + return &tables[len(tables)-1] + } + finishKey := func(to int) error { + table := current() if len(table.keys) == 0 { return nil } @@ -319,6 +448,8 @@ func parseTOMLTables(lines []string) ([]tomlTableSpan, error) { // the value. Keep all whitespace between the closing value and comment. end = len(strings.TrimRight(last[:end], " \t\r")) kv.suffix = last[end:] + text := strings.Join(lines[kv.from:kv.to], "\n") + kv.text = text[len(kv.prefix) : len(text)-len(kv.suffix)] return nil } for p.NextExpression() { @@ -342,23 +473,18 @@ func parseTOMLTables(lines []string) ([]tomlTableSpan, error) { shape := p.Shape(keyRange) i := shape.Start.Line - 1 if err := finishKey(i); err != nil { - return nil, err + return tomlFile{}, err } switch expr.Kind { case unstable.Table, unstable.ArrayTable: - if len(tables) > 0 { - tables[len(tables)-1].to = i - } + current().to = i tables = append(tables, tomlTableSpan{ from: i, to: len(lines), name: strings.Join(rawParts, "."), column: shape.Start.Column, array: expr.Kind == unstable.ArrayTable, }) case unstable.KeyValue: - if len(tables) == 0 { - continue - } - table := &tables[len(tables)-1] + table := current() value := expr.Value() // Start after the parsed key, which may itself contain '='. _, valueText, _ := strings.Cut(lines[i][shape.End.Column-1:], "=") @@ -376,12 +502,12 @@ func parseTOMLTables(lines []string) ([]tomlTableSpan, error) { } } if err := p.Error(); err != nil { - return nil, tomlParseError(&p, err) + return tomlFile{}, tomlParseError(&p, err) } if err := finishKey(len(lines)); err != nil { - return nil, err + return tomlFile{}, err } - return tables, nil + return tomlFile{root: root, tables: tables}, nil } func tomlParseError(p *unstable.Parser, err error) error { diff --git a/internal/edit/toml_multiline_test.go b/internal/edit/toml_multiline_test.go new file mode 100644 index 000000000..c1f27343d --- /dev/null +++ b/internal/edit/toml_multiline_test.go @@ -0,0 +1,202 @@ +package edit + +import ( + "errors" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/pelletier/go-toml/v2" +) + +// The config.toml of #253: a top-level array over several lines. A new +// top-level key went in right after the array's first line, inside it +// ("edited TOML is invalid: line 2, column 1: incomplete number"). +const issue253 = `notify = [ + "/usr/local/bin/notifier", + "turn-ended", +] + +[model_providers.example] +base_url = "http://127.0.0.1:1/v1" +` + +func TestTOMLTopMultilineArray(t *testing.T) { + p := tmpFile(t, "config.toml", issue253) + if v, ok := GetTOMLTop(p, "notify"); !ok || v != "[\n \"/usr/local/bin/notifier\",\n \"turn-ended\",\n]" { + t.Fatalf("notify = %q %v", v, ok) + } + if err := SetTOMLTop(p, KV{Path: "model", Value: "gpt-6-luna"}, KV{Path: "model_provider", Value: "magpie"}); err != nil { + t.Fatal(err) + } + assertTOMLContent(t, p, `notify = [ + "/usr/local/bin/notifier", + "turn-ended", +] +model = "gpt-6-luna" +model_provider = "magpie" + +[model_providers.example] +base_url = "http://127.0.0.1:1/v1" +`) + assertNotify(t, p) + // replacing a key before the array, and the array itself + if err := SetTOMLTop(p, KV{Path: "model", Value: "gpt-5.5"}); err != nil { + t.Fatal(err) + } + assertNotify(t, p) + if err := DelTOMLTop(p, "model_provider", "notify"); err != nil { + t.Fatal(err) + } + assertTOMLContent(t, p, "model = \"gpt-5.5\"\n\n[model_providers.example]\nbase_url = \"http://127.0.0.1:1/v1\"\n") +} + +func assertNotify(t *testing.T, p string) { + t.Helper() + var doc struct{ Notify []string } + if err := toml.Unmarshal([]byte(read(t, p)), &doc); err != nil { + t.Fatal(err) + } + if want := []string{"/usr/local/bin/notifier", "turn-ended"}; !reflect.DeepEqual(doc.Notify, want) { + t.Fatalf("notify = %q", doc.Notify) + } +} + +// Nested arrays, trailing commas, comments inside an array, and brackets +// and `key = value` inside its strings: none of it is a key or a header. +func TestTOMLTopNestedArrays(t *testing.T) { + const input = `model = "old" # the model +matrix = [ + [1, 2,], + ["[x]", "a = b"], # a comment with [brackets] + # model = "not a key" + [ + 3, + ], + { name = "[t]" }, +] +[mcp] +x = 1 +` + p := tmpFile(t, "config.toml", input) + if v, ok := GetTOMLTop(p, "model"); !ok || v != "old" { + t.Fatalf("model = %q %v", v, ok) + } + if err := SetTOMLTop(p, KV{Path: "model", Value: "new"}, KV{Path: "openai_base_url", Value: "http://127.0.0.1:1"}); err != nil { + t.Fatal(err) + } + assertTOMLContent(t, p, `model = "new" +matrix = [ + [1, 2,], + ["[x]", "a = b"], # a comment with [brackets] + # model = "not a key" + [ + 3, + ], + { name = "[t]" }, +] +openai_base_url = "http://127.0.0.1:1" +[mcp] +x = 1 +`) + if err := DelTOMLTop(p, "matrix"); err != nil { + t.Fatal(err) + } + assertTOMLContent(t, p, "model = \"new\"\nopenai_base_url = \"http://127.0.0.1:1\"\n[mcp]\nx = 1\n") +} + +// Multi-line strings, basic and literal, whose lines look like keys and +// tables: they are the string's text, not the file's. +func TestTOMLTopMultilineStrings(t *testing.T) { + const input = `instructions = """ +model = "inner" +[not.a.table] +""" +raw = ''' +[another] +model_provider = x +''' + +[t] +x = 1 +` + p := tmpFile(t, "config.toml", input) + if v, ok := GetTOMLTop(p, "model"); ok { + t.Fatalf("model read from inside a string: %q", v) + } + if v, _ := GetTOMLTop(p, "raw"); v != "[another]\nmodel_provider = x\n" { + t.Fatalf("raw = %q", v) + } + if got, err := TOMLTables(p); err != nil || !reflect.DeepEqual(got, []string{"t"}) { + t.Fatalf("tables = %v, %v", got, err) + } + if err := SetTOMLTop(p, KV{Path: "model", Value: "m"}, KV{Path: "model_provider", Value: "magpie"}); err != nil { + t.Fatal(err) + } + assertTOMLContent(t, p, `instructions = """ +model = "inner" +[not.a.table] +""" +raw = ''' +[another] +model_provider = x +''' +model = "m" +model_provider = "magpie" + +[t] +x = 1 +`) + if err := DelTOMLTop(p, "instructions", "model_provider"); err != nil { + t.Fatal(err) + } + assertTOMLContent(t, p, "raw = '''\n[another]\nmodel_provider = x\n'''\nmodel = \"m\"\n\n[t]\nx = 1\n") + if err := SetTOMLKey(p, "t", "y", "z"); err != nil { + t.Fatal(err) + } + if err := SetTOMLTable(p, "u", KV{Path: "k", Value: "v"}); err != nil { + t.Fatal(err) + } + assertTOMLContent(t, p, "raw = '''\n[another]\nmodel_provider = x\n'''\nmodel = \"m\"\n\n[t]\nx = 1\ny = \"z\"\n\n[u]\nk = \"v\"\n") +} + +// Atomically puts back every file an edit in several steps touched once a +// step fails: changed bytes, mode, and a file that wasn't there. +func TestAtomically(t *testing.T) { + dir := t.TempDir() + cfg := filepath.Join(dir, "config.toml") + extra := filepath.Join(dir, "models.json") + os.WriteFile(cfg, []byte(issue253), 0o600) + fail := errors.New("step two") + err := Atomically(func() error { + if err := SetTOMLTable(cfg, "model_providers.magpie", KV{Path: "name", Value: "magpie"}); err != nil { + return err + } + if err := WriteAtomic(extra, []byte("{}")); err != nil { + return err + } + os.Chmod(cfg, 0o644) + return fail + }, cfg, extra) + if !errors.Is(err, fail) { + t.Fatalf("err = %v", err) + } + if got := read(t, cfg); got != issue253 { + t.Fatalf("config not put back:\n%s", got) + } + if st, _ := os.Stat(cfg); runtime.GOOS != "windows" && st.Mode().Perm() != 0o600 { + t.Fatalf("mode %v", st.Mode().Perm()) + } + if _, err := os.Stat(extra); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("a file made by the failed edit stays: %v", err) + } + // a successful edit is kept + if err := Atomically(func() error { return SetTOMLTop(cfg, KV{Path: "model", Value: "m"}) }, cfg); err != nil { + t.Fatal(err) + } + if v, _ := GetTOMLTop(cfg, "model"); v != "m" { + t.Fatalf("model = %q", v) + } +} diff --git a/internal/edit/toml_write_test.go b/internal/edit/toml_write_test.go index 27b0e5ba0..61f209bdc 100644 --- a/internal/edit/toml_write_test.go +++ b/internal/edit/toml_write_test.go @@ -104,21 +104,23 @@ func TestTOMLWritesRejectDefinitionConflicts(t *testing.T) { } } -func TestTOMLTopRejectsBrokenMultilineEdits(t *testing.T) { +// A top-level value over several lines is replaced or removed as a whole. +func TestTOMLTopMultilineEdits(t *testing.T) { const input = "value = [\n1,\n2\n]\n\n[a]\nkeep = true\n" for _, tc := range []struct { - name string - edit func(string) error + name, want string + edit func(string) error }{ - {"replace", func(p string) error { return SetTOMLTop(p, KV{Path: "value", Value: "new"}) }}, - {"delete", func(p string) error { return DelTOMLTop(p, "value") }}, + {"replace", "value = \"new\"\n\n[a]\nkeep = true\n", func(p string) error { return SetTOMLTop(p, KV{Path: "value", Value: "new"}) }}, + {"delete", "\n[a]\nkeep = true\n", func(p string) error { return DelTOMLTop(p, "value") }}, + {"add", "value = [\n1,\n2\n]\nother = \"x\"\n\n[a]\nkeep = true\n", func(p string) error { return SetTOMLTop(p, KV{Path: "other", Value: "x"}) }}, } { t.Run(tc.name, func(t *testing.T) { p := tmpFile(t, "config.toml", input) - if err := tc.edit(p); err == nil { - t.Fatal("expected the incomplete multiline edit to be rejected") + if err := tc.edit(p); err != nil { + t.Fatal(err) } - assertTOMLContent(t, p, input) + assertTOMLContent(t, p, tc.want) }) } } diff --git a/internal/library/mcp.go b/internal/library/mcp.go index 2ae464bff..0051ac44d 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -628,26 +628,31 @@ func (f *mcpFile) del(name string) error { // or only those under it, which putCodex writes inline instead. // Include child array tables (such as env_vars), which would otherwise // implicitly recreate the removed server. +// Each is one edit of the file: a step that fails puts it back as it was. func delCodex(path, name string, self bool) error { - table := "mcp_servers." + name - if err := edit.SetTOMLTables(path, []string{table + "."}, nil); err != nil { - return err - } - if !self { - return nil - } - return edit.DelTOMLTable(path, table) + return edit.Atomically(func() error { + table := "mcp_servers." + name + if err := edit.SetTOMLTables(path, []string{table + "."}, nil); err != nil { + return err + } + if !self { + return nil + } + return edit.DelTOMLTable(path, table) + }, path) } func putCodex(path, name string, o ordered) error { - if err := delCodex(path, name, false); err != nil { - return err - } - var kvs []edit.KV - for _, e := range o { - kvs = append(kvs, edit.KV{Path: tomlKey(e.k), Value: edit.Raw(tomlValue(e.v))}) - } - return edit.SetTOMLTable(path, "mcp_servers."+name, kvs...) + return edit.Atomically(func() error { + if err := delCodex(path, name, false); err != nil { + return err + } + var kvs []edit.KV + for _, e := range o { + kvs = append(kvs, edit.KV{Path: tomlKey(e.k), Value: edit.Raw(tomlValue(e.v))}) + } + return edit.SetTOMLTable(path, "mcp_servers."+name, kvs...) + }, path) } func tomlString(s string) string {