agent: T3 Code gets magpie on Codex too, picked in T3's model picker
karissasel_ on X: T3 Code through magpie could only run Claude Code; the
harness couldn't be chosen. T3 runs a thread on the driver of the provider
instance its model is picked under, and magpie wrote only a claudeAgent
instance. It now also writes `magpie-codex` ("magpie · Codex", driver
codex) in ~/.t3/userdata/settings.json. Its config.launchArgs (T3's
CodexSettings key, passed to `codex app-server`, and its -c pairs to
`codex exec`) are Codex's own -c overrides: model_provider=magpie, the
same model_providers.magpie table codex.go writes, and model_catalog_json
pointing at magpie-codex-models.json beside settings.json. Values are
quoted for T3's tokenizeCliArgs. ~/.codex/config.toml is not written. A
binaryPath/homePath the user gave T3's own codex instance is carried over.
The user's name, on/off and unknown keys are kept; launch args and catalog
are magpie's, and Check says when they no longer reach the gateway
(the base_url read back through T3's tokenizer; a reverse proxy to magpie
the user put there counts, reachesMagpie, as for every agent). An
older Claude-only wiring gets the instance once on Sync; one the user
removed stays removed (stash t3code.codex) until magpie is turned on for
T3 again. Turning magpie off removes both instances and the catalog. The
option's note says where to pick (4 languages); reference.md and
agent-wiring.md describe it.
Run (on mote, the tree as committed):
- real end to end, sandbox HOME (~/t3e2e/home): settings written by this
code, magpie serve on 127.0.0.1:47811 with a fake Responses upstream,
T3 Code server 0.1.5 (npm t3) and @openai/codex 0.165.0.
`t3 thread start . "Reply with the word pong." --provider magpie-codex
--model fake/fake-model --wait` answered PONG-T3-CODEX; the upstream saw
POST /v1/responses, model fake-model, stream true, with the provider's
own key (sent by magpie's gateway).
- go test -tags nogui ./internal/agent -count=1 -timeout 45m: ok
- gofmt -l; go vet (darwin, GOOS=linux, GOOS=windows) ./internal/agent
- node --test internal/gui/tests/i18n-keys.test.cjs: ok
Broken by hand, each red then restored: no escaping in t3Arg
(TestT3CodeCodexInstance red); Sync without t3CodexSync (both new tests
red); no stash check (TestT3CodeCodexInstanceAddedOnce red); t3CodexOff
never reporting (TestT3CodeCodexInstance red). The first full run
was red in TestReverseProxyIsStillMagpie, Check comparing the launch
args by string; that red is the break for the proxy rule.
Not tried: T3's desktop app window (the server CLI is what it runs); the
Windows quoting on a Windows box; a real vendor upstream (fake one only);
T3's other drivers (cursor, opencode, pi, grok, ...), which are off by
default in T3 and not wired.
This commit is contained in:
+1
-1
@@ -146,7 +146,7 @@ line; agents connected to magpie lose it when it quits.
|
||||
| Kiro Crew | `~/.kiro/crew/config.json` (`$KIROCREW_HOME`; `config.local.json` over it is left alone) | provider, harness (`agent.acp_backend`, and `agent.member_acp_backend` for a harness that can dispatch: an agent connected to magpie, so its models are magpie's: the one Crew is set to is connected along with it when it isn't yet, and disconnected with it again; the user's value is put back on Disconnect) |
|
||||
| OpenPencil | `openpencil/settings.json` in the config folder: `~/Library/Application Support` (macOS), `$XDG_CONFIG_HOME` or `~/.config` (Linux), `%APPDATA%` (Windows) | provider (a `magpie` entry in its `builtin_agents`, magpie's models in its chat's model picker; the user's entries and settings kept; refused while OpenPencil runs, as it writes the file back when it quits) |
|
||||
| NewMax | `newmax.db` (SQLite, the row `app` of its `settings` table) in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` (every OS) | provider (a `magpie-gateway` entry in its `providers` and `providerOrder`, magpie's models in its model picker; the rest of the row kept byte for byte; refused while NewMax runs, as it writes its settings back whenever one changes) |
|
||||
| T3 Code | `~/.t3/userdata/settings.json` (`$T3CODE_HOME/userdata`) | provider (a `magpie` provider instance on Claude Code, magpie's models as its custom models) |
|
||||
| T3 Code | `~/.t3/userdata/settings.json` (`$T3CODE_HOME/userdata`) | provider (a `magpie` provider instance on Claude Code, magpie's models as its custom models; a `magpie-codex` instance on Codex, whose `launchArgs` are Codex's own `-c` overrides to magpie and a `magpie-codex-models.json` catalog beside the settings. The harness is picked in T3's model picker) |
|
||||
| OpenHanako | `~/.hanako/provider-catalog.json` + `agents/<id>/config.yaml` (`$HANA_HOME`; its local API while it runs) | model (the primary agent's; magpie's models as a provider) |
|
||||
| AtomCode | `~/.atomcode/config.toml` (`$ATOMCODE_HOME`) | model, effort (a `magpie` provider account, one model table per catalog model as its own sign-in writes) |
|
||||
| Snow CLI | `~/.snow/profiles/magpie.json` (`$SNOW_CONFIG_DIR`), made the active profile and copied to `config.json` | model (the user's other profiles' models too; Snow App takes the profile in with "Sync Snow CLI API config") |
|
||||
|
||||
@@ -101,6 +101,7 @@ something else shows up as drift.
|
||||
- Claude Code's provider switches (`agentenv.ClaudeProviders`: `CLAUDE_CODE_USE_BEDROCK`, `_VERTEX`, `_FOUNDRY`, `_ANTHROPIC_AWS`, `_ANTHROPIC_GOOGLE_CLOUD`, `_MANTLE`, Claude Code 2.1.300) send it to that cloud's own endpoint and pass `ANTHROPIC_BASE_URL` over, so with one on it never reaches magpie (jw1dev on X: Bedrock refused magpie's model, and magpie showed nothing). Claude Code reads 1, true, yes and on as on (`claudeSwitchOn`). One that is on in the settings magpie writes is taken out on every route that writes the wiring (`dropClouds` in `writeTiers` and `Sync`), its raw value stashed (`claude.cloud.<var>`, under the distro's id for a WSL twin), and put back as written when magpie steps out (`putClouds` in `unroute`), unless the user set it again since. The cloud's own variables (`AWS_*`, `ANTHROPIC_VERTEX_PROJECT_ID`, …) and a switch that is off stay. Where magpie doesn't write it, Check says so, naming the variable, the cloud and where (`claudeCloud`): the managed settings, which win over the user's; `~/.claude.json`'s env, under the user's settings; and, for this machine's Claude Code, the login shell's environment (`proc.LoginEnv`, read but never set in magpie's), under every settings file. A project's `.claude/settings.json` isn't read: magpie doesn't know which folders Claude Code runs in. T3 Code's Check says the same of the user's `~/.claude` settings, which are put over its magpie instance's environment, and a switch put on that instance goes at its next write; that Check first says when the instance's `ANTHROPIC_BASE_URL` no longer reaches the gateway (`t3EnvOf`), as every agent's Check does, so a port move rewrites it too. The drift's detail is shown in the row's line and its pill through `tNotice` (`claude-cloud-drift.test.cjs`). Claude Desktop's Code tab runs with `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, under which Claude Code ignores a switch in settings files, so Desktop needs neither.
|
||||
- Claude Code's sign-in (`login`) is magpie's key (`""`, the default) or claude.ai (`claudeai`). claude.ai writes `ANTHROPIC_AUTH_TOKEN` empty, which Claude Code reads as no key: it keeps its claude.ai login and sends that to magpie, which never passes it on (`claudeSignIn` in the gateway). Every later write keeps the token empty (`wiredKey`), and a caller key of the gateway's own put there by hand is taken for magpie's, by Check and a model pick alike, kept as the user left it (`keyHolds`, #2545); a key the gateway would refuse is reported by Check and wired over, and so is the sharing key magpie itself made (`access.Default`), once sharing is off — magpie's own, however well the gateway still takes it. It's offered only where the gateway takes any key (`gwKey() == gateway.Token`: loopback, a WSL distro mirrored), not from a distro under NAT while magpie is shared on the network, where only the sharing key gets in. The choice is stashed, so it survives Disconnect and a port move. An empty token counts as magpie's only beside the address magpie last wrote (`claude.wired_at` in the stash, which Rewire carries to the new port, `keyOurs`): an endpoint of the user's own with an empty token stays theirs when the model goes back to Claude Code's own.
|
||||
- Claude Code's auto mode review (`CLAUDE_CODE_AUTO_MODE_SERVER`, `claudeReviewEnv` in [`claude.go`](../../internal/agent/claude.go)) is written `"0"` while Claude Code is routed through magpie and none of the models it can reach there is one Anthropic reviews (`claudeReviewed`, by `gateway.AutoModeReviewable`: a model `AutoModeReviewed` that is asked on the Messages API; a Claude model a provider serves only on Chat or Responses, or one set to be asked on another API, is translated, carries no `safeguards` and counts for nothing, nexnull on Discord, `TestClaudeReviewedOnlyWhereMessagesReachClaude`): those it is shown (and Claude Desktop's while Desktop is on magpie), a shown group's members, those providers' fallbacks, and the models it is set to, each judged on the provider (or group, or fallback) it resolves to, as the gateway judges its requests, so a Claude model on Copilot or Kiro alone writes `"0"` and a name magpie doesn't know is judged by the name (`TestClaudeReviewedJudgesTheSetModelWhereItGoes`). Off, it classifies locally from the start, as it does anyway behind a gateway that doesn't answer, without the "isn't eligible because your requests go through 127.0.0.1:3425" notice (1EFLOPS on X). Any reviewed model leaves it unset, since `/model` can take the session there; a model hidden from Claude Code doesn't count. It is rewritten on every model set and `Sync`, so adding a Claude provider turns the review back on. magpie's value is kept apart in the stash (`claude.auto_mode_server`), a user's own is left alone, and it goes when Claude Code is taken off magpie (`desktopOnly`, `unroute`). T3 Code's magpie instance, which runs Claude Code on the gateway through its own environment, carries the same `"0"` there by the models it lists (`t3InstanceJSON` in [`t3code.go`](../../internal/agent/t3code.go)); a value in the user's `~/.claude` settings comes after it.
|
||||
- T3 Code runs a thread on the harness of the provider instance its model is picked under, so magpie writes two instances (karissasel_ on X: only Claude Code could be picked). `magpie` runs Claude Code, as above. `magpie-codex` ("magpie · Codex", `t3CodexJSON` in [`t3code.go`](../../internal/agent/t3code.go)) runs Codex: its `config.launchArgs`, which T3 hands to `codex app-server` and the `-c` pairs of to `codex exec`, are Codex's own overrides, making `magpie` its `model_provider` (the same table `codex.go` writes) and `magpie-codex-models.json`, written beside settings.json from `codexcat`, its `model_catalog_json`. Each value is quoted for T3's `tokenizeCliArgs` (`t3Arg`; `TestT3CodeCodexInstance` reads them back with a port of it). `~/.codex/config.toml` is not written, and a `binaryPath` or `homePath` the user gave T3's own `codex` instance is carried over. The name, on/off and unknown keys are the user's; the launch args and catalog are magpie's, and Check says when the launch args no longer reach the gateway (`t3CodexOff`). An older Claude-only wiring gets the Codex instance on its next Sync once; one the user removed stays removed (`t3code.codex` in the stash) until magpie is turned on for T3 again (`TestT3CodeCodexInstanceAddedOnce`).
|
||||
- Claude Code takes one window (`CLAUDE_CODE_MAX_CONTEXT_TOKENS`, `claudeContextEnv` in [`claude.go`](../../internal/agent/claude.go)) for every model it doesn't know. Claude Code alone on magpie is told its main model's (`claudeWindow`). While Claude Desktop is on magpie too, its Code tab runs Claude Code on the same `~/.claude/settings.json` with every model Desktop lists, so magpie tells it the largest window of those and of Claude Code's own models, and holds each model below it to its own with `modelSettings.<id>.autoCompactWindow` (`claudePlan` in [`claude_budget.go`](../../internal/agent/claude_budget.go), #2025: the least held a 1M model to 131K). A model handed by a `[1m]` id (Desktop's under `DesktopLongest`, or Claude Code's own) counts by its 1M too, so it still runs at 1M when Claude Code stops taking the id for 1M (the 1M beta turned away once, `CLAUDE_CODE_DISABLE_1M_CONTEXT`); left out, a 1M model beside a 272K GPT was told 272K (dumplings on Discord). Claude Code 2.1.296 matches that key by the id it was handed, lowercased and without `[1m]`; it comes before the top-level `autoCompactWindow`, which serves a model without one. `CLAUDE_CODE_AUTO_COMPACT_WINDOW` would take precedence over both, so in this mode magpie's working window goes in the top-level `autoCompactWindow` instead, and an entry is written only where a model's window or its own threshold differs from what it would run at without one. magpie's entries and top-level value are stashed (`claude.model_budgets`, `claude.compact_default`) and go when Desktop leaves magpie; the user's own entries, top-level value and variables stay, a user's entry past its model's window (or `auto`) holds the largest to that window, and with a `CLAUDE_CODE_AUTO_COMPACT_WINDOW` of the user's the least window is told as before.
|
||||
- Claude Code is told what each of magpie's models can do in `CLAUDE_CODE_MODEL_CAPABILITIES` (`claudeCapsEnv`, `claudeCapabilities` in [`claude.go`](../../internal/agent/claude.go)): `<model>=effort[,xhigh_effort][,max_effort]` for those it is shown, and, while Claude Desktop is on magpie, for Desktop's `mythos-magpie-<number>` ids its Code tab hands it. A Claude model Claude Code knows gets no more than Claude Code gives it (Opus and Sonnet 4.6: no xhigh), and one with no known levels isn't named. A model that reaches max without xhigh (GLM-5.3 at low/high/max, DeepSeek V4 at high/max) is said to have xhigh too: the gateway runs xhigh at max for it (`fitEffort`), and Claude Code 2.1.299 turns Ultracode down without `xhigh_effort` ("Ultracode isn't available on …"), which in Desktop is the Ultracode level and dynamic workflows (leesunrise2364 on Discord; `TestClaudeModelCapabilities`). A value of the user's is left alone.
|
||||
- MiniMax Code takes a model ref with one slash in the whole (a SubAgent's `model` must match `^[^/\s]+\/[^/\s]+$`, #1387), and magpie's refs there are `custom_provider:magpie/<model>`. So a model under `custom_provider.magpie` is written with `~` for each slash of its catalog id (`bb-codex~gpt-6.1-sol`, `provider.FlatID`), only when that spelling stands for one served id (`provider.Flattened`); the gateway takes it back. A config an older magpie wrote moves over on the next sync: the user's keys on a model go to its new key, `defaultModel`, `defaultLightModel` and `memory.captureModel`/`consolidationModel` follow (`mcodeRefs`), and the slashed key stays, switched off (`enabled: false`), so a session begun on it still resumes. magpie never edits the user's own `agents/<name>/agent.md`. No other agent was found with this limit ([`minimax.go`](../../internal/agent/minimax.go)).
|
||||
@@ -154,7 +155,7 @@ node --test internal/gui/tests/agy-launch.test.cjs
|
||||
go test -tags nogui ./internal/agent -run 'TestPiModelsAskedOnTheirNativeAPI|TestPiGoogle'
|
||||
go test -tags nogui ./internal/agent -run '^TestMothX'
|
||||
go test -tags nogui ./internal/agent -run '^TestPenguin'
|
||||
go test -tags nogui ./internal/agent -run 'TestClaudeAutoModeReview|TestClaudeReviewedOnlyWhereMessagesReachClaude|TestT3CodeAutoModeReview|TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress'
|
||||
go test -tags nogui ./internal/agent -run 'TestClaudeAutoModeReview|TestClaudeReviewedOnlyWhereMessagesReachClaude|TestT3CodeAutoModeReview|TestT3CodeCodexInstance|TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress'
|
||||
go test -tags nogui ./internal/agent
|
||||
go test -tags nogui ./internal/agent -run '^TestAir'
|
||||
go test -tags nogui ./internal/agent -run 'TestReverseProxy|TestClaudeManagedProxyIsStillMagpie|TestMagpieProbe|TestCodexBehindReverseProxy|TestCodexSignedInBehindReverseProxy|TestAwayPath|TestClaudeBehindLocalProxyKeepsIt|OwnEndpointNeverAsked'
|
||||
|
||||
+279
-8
@@ -25,8 +25,23 @@ package agent
|
||||
// magpie's alone: the user's own instances, their custom models and T3's
|
||||
// other keys stay as they are, and off takes only it out. A binary path or
|
||||
// Claude home the user gave T3's own Claude is carried over, so it runs the
|
||||
// same Claude Code. T3's Codex lists what Codex's model/list says, which is
|
||||
// magpie's catalog once Codex is routed through magpie, so it needs nothing.
|
||||
// same Claude Code.
|
||||
//
|
||||
// T3 Code runs each thread on the harness of the instance its model is
|
||||
// picked from, so with magpie on Claude Code alone every magpie model ran
|
||||
// there (karissasel_ on X: "can't pick the harness, it's Claude Code").
|
||||
// So magpie has a Codex instance too, "magpie-codex" (magpie · Codex): a
|
||||
// codex instance whose launchArgs, which T3 passes to `codex app-server`
|
||||
// and `codex exec` (codexLaunchArgs.ts), are Codex's own -c overrides
|
||||
// making magpie its model provider and magpie's model catalog for T3
|
||||
// (magpie-codex-models.json beside settings.json) its catalog, so T3's
|
||||
// picker lists every magpie model under it from Codex's model/list. The
|
||||
// user's ~/.codex config.toml isn't written: the overrides are this
|
||||
// instance's alone, and T3's own Codex stays as it is. It is written with
|
||||
// magpie's instance; one the user removed in T3 isn't brought back by a
|
||||
// sync (t3CodexOffered), only by turning magpie on again. Its name, whether
|
||||
// it is on, and the keys magpie doesn't write are the user's; the launch
|
||||
// arguments and the catalog are magpie's.
|
||||
//
|
||||
// The settings environment (~/.claude/settings.json's env) is applied over
|
||||
// the process', so a Claude Code routed elsewhere in its own settings
|
||||
@@ -35,6 +50,7 @@ package agent
|
||||
// takes it to that cloud, which Check says.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -44,14 +60,23 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/agentenv"
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/codexcat"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// t3Instance is the key of magpie's provider instance in T3 Code's
|
||||
// settings.json.
|
||||
const t3Instance = "providerInstances." + magpieID
|
||||
// settings.json, and t3CodexInstance that of its Codex one.
|
||||
const (
|
||||
t3Instance = "providerInstances." + magpieID
|
||||
t3CodexInstance = "providerInstances." + magpieID + "-codex"
|
||||
)
|
||||
|
||||
// t3CodexOffered is the stash key that says magpie has written its Codex
|
||||
// instance into T3 Code's settings: one gone after that the user removed in
|
||||
// T3, and a sync doesn't bring it back.
|
||||
const t3CodexOffered = "t3code.codex"
|
||||
|
||||
func t3code(home string) *Agent {
|
||||
base := appdir.Getenv("T3CODE_HOME")
|
||||
@@ -61,7 +86,13 @@ func t3code(home string) *Agent {
|
||||
base = filepath.Join(home, rest)
|
||||
}
|
||||
path := filepath.Join(base, "userdata", "settings.json")
|
||||
wired := func() bool { _, ok := edit.GetJSON(path, t3Instance); return ok }
|
||||
claudeOn := func() bool { _, ok := edit.GetJSON(path, t3Instance); return ok }
|
||||
// either of magpie's instances: one the user removed in T3 leaves
|
||||
// magpie on in the other
|
||||
wired := func() bool {
|
||||
_, ok := edit.GetJSON(path, t3CodexInstance)
|
||||
return ok || claudeOn()
|
||||
}
|
||||
return &Agent{
|
||||
ID: "t3code", Name: "T3 Code", Icon: "t3code", Aliases: []string{"t3", "t3-code"},
|
||||
Dir: base, Path: path,
|
||||
@@ -70,7 +101,10 @@ func t3code(home string) *Agent {
|
||||
detect: func() bool { return isDir(base) || t3App(home) },
|
||||
ListOnly: true,
|
||||
Sync: func() error {
|
||||
return syncJSON(path, t3Instance, func() any { return t3Merged(path, gateway.URL()) })
|
||||
if err := syncJSON(path, t3Instance, func() any { return t3Merged(path, gateway.URL()) }); err != nil {
|
||||
return err
|
||||
}
|
||||
return t3CodexSync(path, gateway.URL())
|
||||
},
|
||||
// its custom models are the models picked for it (#1508)
|
||||
ListsModels: true,
|
||||
@@ -84,6 +118,12 @@ func t3code(home string) *Agent {
|
||||
if !wired() {
|
||||
return ""
|
||||
}
|
||||
if why := t3CodexOff(path, gateway.URL()); why != "" {
|
||||
return why
|
||||
}
|
||||
if !claudeOn() {
|
||||
return ""
|
||||
}
|
||||
if why := wiringOff("T3 Code", path, func(k string) (string, bool) { return t3EnvOf(path, k) }, "ANTHROPIC_BASE_URL", gateway.URL()); why != "" {
|
||||
return why
|
||||
}
|
||||
@@ -100,12 +140,20 @@ func t3code(home string) *Agent {
|
||||
},
|
||||
Set: func(v string) error {
|
||||
if v == "" {
|
||||
if err := edit.DelJSON(path, t3CodexInstance); err != nil {
|
||||
return err
|
||||
}
|
||||
os.Remove(t3CodexCatalog(path))
|
||||
forget(t3CodexOffered)
|
||||
return edit.DelJSON(path, t3Instance)
|
||||
}
|
||||
return edit.SetJSON(path, edit.KV{Path: t3Instance, Value: t3Merged(path, gateway.URL())})
|
||||
if err := edit.SetJSON(path, edit.KV{Path: t3Instance, Value: t3Merged(path, gateway.URL())}); err != nil {
|
||||
return err
|
||||
}
|
||||
return t3CodexPut(path, gateway.URL())
|
||||
},
|
||||
Options: func(map[string]string) []Option {
|
||||
return []Option{{Value: magpieID, Label: "magpie", Icon: "magpie", Note: "every magpie model as a provider in T3 Code, on Claude Code"}}
|
||||
return []Option{{Value: magpieID, Label: "magpie", Icon: "magpie", Note: "every magpie model in T3 Code twice: magpie on Claude Code, magpie · Codex on Codex; pick one in T3's model picker"}}
|
||||
},
|
||||
}},
|
||||
}
|
||||
@@ -282,3 +330,226 @@ func t3Capabilities(id string, efforts []string) map[string]any {
|
||||
}
|
||||
return map[string]any{"optionDescriptors": descriptors}
|
||||
}
|
||||
|
||||
// t3CodexCatalog is the model catalog of magpie's Codex instance in T3
|
||||
// Code, beside its settings.json at path.
|
||||
func t3CodexCatalog(path string) string {
|
||||
return filepath.Join(filepath.Dir(path), "magpie-codex-models.json")
|
||||
}
|
||||
|
||||
// t3TOML is s as a TOML basic string: JSON's quoting, which TOML reads
|
||||
// alike, with nothing escaped for HTML.
|
||||
func t3TOML(s string) string {
|
||||
var b bytes.Buffer
|
||||
e := json.NewEncoder(&b)
|
||||
e.SetEscapeHTML(false)
|
||||
e.Encode(s)
|
||||
return strings.TrimSuffix(b.String(), "\n")
|
||||
}
|
||||
|
||||
// t3Arg is Codex's -c override of key to the TOML value v, quoted as T3
|
||||
// Code's tokenizeCliArgs reads a double-quoted argument: \ before ", \,
|
||||
// $ and `, so it comes to Codex as written.
|
||||
func t3Arg(key, v string) string {
|
||||
r := strings.NewReplacer(`\`, `\\`, `"`, `\"`, "$", `\$`, "`", "\\`")
|
||||
return `-c "` + r.Replace(key+"="+v) + `"`
|
||||
}
|
||||
|
||||
// t3CodexBase is the override of the base URL magpie's Codex instance
|
||||
// reaches the gateway at gw by.
|
||||
func t3CodexBase(gw string) string {
|
||||
return t3Arg("model_providers."+magpieID+".base_url", t3TOML(gw+"/v1"))
|
||||
}
|
||||
|
||||
// t3CodexArgs is the launch arguments of magpie's Codex instance: magpie
|
||||
// as Codex's provider, as Codex's own [model_providers.magpie] is when
|
||||
// magpie is its provider (codex.go's putProvider), and its catalog.
|
||||
func t3CodexArgs(path, gw string) string {
|
||||
p := "model_providers." + magpieID + "."
|
||||
return strings.Join([]string{
|
||||
t3Arg("model_provider", t3TOML(magpieID)),
|
||||
t3Arg(p+"name", t3TOML("magpie")),
|
||||
t3CodexBase(gw),
|
||||
t3Arg(p+"wire_api", t3TOML("responses")),
|
||||
t3Arg(p+"experimental_bearer_token", t3TOML(keyAt(gw))),
|
||||
// the image tool, as on Codex's own table (putProvider)
|
||||
t3Arg(p+"http_headers", `{"x-openai-actor-authorization"="magpie"}`),
|
||||
t3Arg("model_catalog_json", t3TOML(t3CodexCatalog(path))),
|
||||
}, " ")
|
||||
}
|
||||
|
||||
// t3CodexJSON is magpie's Codex instance in T3 Code's settings.json at
|
||||
// path, with the binary path and Codex home of T3's own Codex when the
|
||||
// user gave them one.
|
||||
func t3CodexJSON(path, gw string) map[string]any {
|
||||
config := map[string]any{"launchArgs": t3CodexArgs(path, gw)}
|
||||
for _, k := range []string{"binaryPath", "homePath"} {
|
||||
v, _ := edit.GetJSON(path, "providerInstances.codex.config."+k)
|
||||
if v == "" {
|
||||
v, _ = edit.GetJSON(path, "providers.codex."+k)
|
||||
}
|
||||
if v = strings.TrimSpace(v); v != "" {
|
||||
config[k] = v
|
||||
}
|
||||
}
|
||||
return map[string]any{"driver": "codex", "displayName": "magpie · Codex", "enabled": true, "config": config}
|
||||
}
|
||||
|
||||
// t3CodexMerged is t3CodexJSON merged into the instance at path: the
|
||||
// user's name, whether it is on, and keys magpie doesn't write stay.
|
||||
func t3CodexMerged(path, gw string) any {
|
||||
want := t3CodexJSON(path, gw)
|
||||
cur, ok := edit.GetJSON(path, t3CodexInstance)
|
||||
if !ok {
|
||||
return want
|
||||
}
|
||||
var have map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(cur), &have) != nil || have == nil {
|
||||
return want
|
||||
}
|
||||
var name string
|
||||
if json.Unmarshal(have["displayName"], &name) == nil && strings.TrimSpace(name) != "" {
|
||||
want["displayName"] = name
|
||||
}
|
||||
var on bool
|
||||
if json.Unmarshal(have["enabled"], &on) == nil {
|
||||
want["enabled"] = on
|
||||
}
|
||||
b, err := json.Marshal(want)
|
||||
var w map[string]json.RawMessage
|
||||
if err != nil || json.Unmarshal(b, &w) != nil {
|
||||
return want
|
||||
}
|
||||
return mergeTheirs(have, w, nil)
|
||||
}
|
||||
|
||||
// t3CodexPut writes magpie's Codex instance and its catalog into T3
|
||||
// Code's settings at path.
|
||||
func t3CodexPut(path, gw string) error {
|
||||
if err := t3CodexCatalogPut(path); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := edit.SetJSON(path, edit.KV{Path: t3CodexInstance, Value: t3CodexMerged(path, gw)}); err != nil {
|
||||
return err
|
||||
}
|
||||
stash(map[string]string{t3CodexOffered: "1"})
|
||||
return nil
|
||||
}
|
||||
|
||||
// t3CodexCatalogPut writes the models picked for T3 Code as Codex's
|
||||
// catalog for magpie's Codex instance, when it changed.
|
||||
func t3CodexCatalogPut(path string) error {
|
||||
cat := t3CodexCatalog(path)
|
||||
b := codexcat.CatalogAt(magpieModels("t3code"), "")
|
||||
if cur, err := os.ReadFile(cat); err == nil && bytes.Equal(cur, b) {
|
||||
return nil
|
||||
}
|
||||
return edit.WriteAtomic(cat, b)
|
||||
}
|
||||
|
||||
// t3CodexSync brings magpie's Codex instance up to the catalog and the
|
||||
// gateway, and writes it beside magpie's Claude Code instance an older
|
||||
// magpie wrote alone. One the user removed stays removed.
|
||||
func t3CodexSync(path, gw string) error {
|
||||
if _, ok := edit.GetJSON(path, t3CodexInstance); !ok {
|
||||
if _, mine := edit.GetJSON(path, t3Instance); !mine || t3Stashed(t3CodexOffered) {
|
||||
return nil
|
||||
}
|
||||
return t3CodexPut(path, gw)
|
||||
}
|
||||
if err := t3CodexCatalogPut(path); err != nil {
|
||||
return err
|
||||
}
|
||||
return syncJSON(path, t3CodexInstance, func() any { return t3CodexMerged(path, gw) })
|
||||
}
|
||||
|
||||
// t3CodexOff says when magpie's Codex instance no longer reaches the
|
||||
// gateway at gw: its launch arguments lost magpie's base URL, or name
|
||||
// another address that isn't a way to magpie (reachesMagpie: a proxy the
|
||||
// user put in front of it is kept, as for every agent).
|
||||
func t3CodexOff(path, gw string) string {
|
||||
if _, there := edit.GetJSON(path, t3CodexInstance); !there {
|
||||
return ""
|
||||
}
|
||||
args, _ := edit.GetJSON(path, t3CodexInstance+".config.launchArgs")
|
||||
want := gw + "/v1"
|
||||
if v := t3CodexBaseOf(args); v == want || v != "" && reachesMagpie(v, want) {
|
||||
return ""
|
||||
}
|
||||
return "T3 Code's magpie · Codex launch arguments (" + filepath.Base(path) + ") no longer reach magpie's gateway at " + gw
|
||||
}
|
||||
|
||||
// t3CodexBaseOf is the base URL the -c overrides in launchArgs give
|
||||
// magpie's Codex provider, as T3 tokenizes them; "" when none does.
|
||||
func t3CodexBaseOf(args string) string {
|
||||
toks := t3Tokens(args)
|
||||
base := ""
|
||||
for i := 0; i+1 < len(toks); i++ {
|
||||
if toks[i] != "-c" && toks[i] != "--config" {
|
||||
continue
|
||||
}
|
||||
k, v, ok := strings.Cut(toks[i+1], "=")
|
||||
i++
|
||||
if !ok || strings.TrimSpace(k) != "model_providers."+magpieID+".base_url" {
|
||||
continue
|
||||
}
|
||||
// a TOML basic string, as t3TOML writes it; the last one wins
|
||||
var s string
|
||||
if json.Unmarshal([]byte(strings.TrimSpace(v)), &s) == nil {
|
||||
base = s
|
||||
} else {
|
||||
base = strings.Trim(strings.TrimSpace(v), `"'`)
|
||||
}
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// t3Stashed reports whether the stash holds key.
|
||||
func t3Stashed(key string) bool {
|
||||
stashMu.Lock()
|
||||
defer stashMu.Unlock()
|
||||
return stashLoad()[key] != ""
|
||||
}
|
||||
|
||||
// t3Tokens is T3 Code's tokenizeCliArgs (packages/shared/src/cliArgs.ts),
|
||||
// which splits an instance's launchArgs into the arguments it passes to
|
||||
// `codex app-server`.
|
||||
func t3Tokens(s string) []string {
|
||||
in := []rune(strings.TrimSpace(s))
|
||||
var out []string
|
||||
cur, quote, quoted := "", rune(0), false
|
||||
space := func(r rune) bool { return strings.ContainsRune(" \t\n\r\f\v", r) }
|
||||
for i := 0; i < len(in); i++ {
|
||||
c := in[i]
|
||||
if quote != 0 {
|
||||
switch {
|
||||
case c == quote:
|
||||
quote, quoted = 0, true
|
||||
case c == '\\' && quote == '"' && i+1 < len(in) && strings.ContainsRune("\"\\$`", in[i+1]):
|
||||
cur += string(in[i+1])
|
||||
i++
|
||||
default:
|
||||
cur += string(c)
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case c == '\'' || c == '"':
|
||||
quote, quoted = c, true
|
||||
case space(c):
|
||||
if cur != "" || quoted {
|
||||
out = append(out, cur)
|
||||
cur, quoted = "", false
|
||||
}
|
||||
case c == '\\' && i+1 < len(in) && (space(in[i+1]) || in[i+1] == '\'' || in[i+1] == '"'):
|
||||
cur += string(in[i+1])
|
||||
i++
|
||||
default:
|
||||
cur += string(c)
|
||||
}
|
||||
}
|
||||
if cur != "" || quoted {
|
||||
out = append(out, cur)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// t3Overrides is the -c overrides in launchArgs, key to raw TOML value.
|
||||
func t3Overrides(t *testing.T, args string) map[string]string {
|
||||
t.Helper()
|
||||
toks := t3Tokens(args)
|
||||
out := map[string]string{}
|
||||
for i := 0; i < len(toks); i += 2 {
|
||||
if toks[i] != "-c" || i+1 >= len(toks) {
|
||||
t.Fatalf("not -c pairs: %q", toks)
|
||||
}
|
||||
k, v, ok := strings.Cut(toks[i+1], "=")
|
||||
if !ok {
|
||||
t.Fatalf("override %q", toks[i+1])
|
||||
}
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type t3CodexEnvelope struct {
|
||||
Driver string `json:"driver"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Config struct {
|
||||
BinaryPath string `json:"binaryPath"`
|
||||
HomePath string `json:"homePath"`
|
||||
LaunchArgs string `json:"launchArgs"`
|
||||
} `json:"config"`
|
||||
}
|
||||
|
||||
func t3CodexRead(t *testing.T, path string) (t3CodexEnvelope, bool) {
|
||||
t.Helper()
|
||||
raw, ok := edit.GetJSON(path, t3CodexInstance)
|
||||
if !ok {
|
||||
return t3CodexEnvelope{}, false
|
||||
}
|
||||
var e t3CodexEnvelope
|
||||
if err := json.Unmarshal([]byte(raw), &e); err != nil {
|
||||
t.Fatalf("%v\n%s", err, raw)
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
|
||||
// karissasel_ on X: T3 Code through magpie ran Claude Code only. magpie
|
||||
// gives T3 a Codex instance too, so a magpie model can be picked under
|
||||
// either harness: Codex made to use magpie as its provider by its own -c
|
||||
// overrides in the instance's launch arguments, as T3 tokenizes them, with
|
||||
// magpie's catalog for T3 as Codex's, and T3's own Codex's binary and home
|
||||
// carried over. ~/.codex is never written.
|
||||
func TestT3CodeCodexInstance(t *testing.T) {
|
||||
home := syncHome(t)
|
||||
// a home whose path a shell and TOML both need quoting for
|
||||
base := filepath.Join(home, `T3 "a" $b`)
|
||||
t.Setenv("T3CODE_HOME", base)
|
||||
if err := provider.Save(provider.Provider{ID: "resp", Name: "Resp", Key: "k", Responses: "http://127.0.0.1:1/v1", Models: []string{"gpt-5.5"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(base, "userdata", "settings.json")
|
||||
os.MkdirAll(filepath.Dir(path), 0o755)
|
||||
os.WriteFile(path, []byte(`{"providerInstances":{"codex":{"driver":"codex","config":{"binaryPath":"/opt/codex","homePath":"~/.codex-t3"}}}}`), 0o600)
|
||||
a := t3code(home)
|
||||
f := a.Field("provider")
|
||||
if err := f.Set(magpieID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e, ok := t3CodexRead(t, path)
|
||||
if !ok || e.Driver != "codex" || e.DisplayName == "" || e.Enabled == nil || !*e.Enabled {
|
||||
t.Fatalf("instance: %+v\n%s", e, readFile(path))
|
||||
}
|
||||
if e.Config.BinaryPath != "/opt/codex" || e.Config.HomePath != "~/.codex-t3" {
|
||||
t.Errorf("T3's Codex not carried over: %+v", e.Config)
|
||||
}
|
||||
cat := filepath.Join(base, "userdata", "magpie-codex-models.json")
|
||||
str := func(v string) string { return t3TOML(v) }
|
||||
want := map[string]string{
|
||||
"model_provider": str(magpieID),
|
||||
"model_providers.magpie.name": str("magpie"),
|
||||
"model_providers.magpie.base_url": str(gateway.URL() + "/v1"),
|
||||
"model_providers.magpie.wire_api": str("responses"),
|
||||
"model_providers.magpie.experimental_bearer_token": str(gateway.Token),
|
||||
"model_providers.magpie.http_headers": `{"x-openai-actor-authorization"="magpie"}`,
|
||||
"model_catalog_json": str(cat),
|
||||
}
|
||||
if got := t3Overrides(t, e.Config.LaunchArgs); !maps.Equal(got, want) {
|
||||
t.Errorf("overrides:\n got %v\nwant %v", got, want)
|
||||
}
|
||||
if !strings.Contains(str(cat), `\"a\"`) {
|
||||
t.Fatalf("the path's quotes aren't TOML-escaped: %s", str(cat))
|
||||
}
|
||||
var list struct {
|
||||
Models []struct {
|
||||
Slug string `json:"slug"`
|
||||
} `json:"models"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(readFile(cat)), &list); err != nil {
|
||||
t.Fatalf("catalog: %v", err)
|
||||
}
|
||||
if !slices.ContainsFunc(list.Models, func(m struct {
|
||||
Slug string `json:"slug"`
|
||||
}) bool {
|
||||
return m.Slug == "resp/gpt-5.5"
|
||||
}) {
|
||||
t.Errorf("catalog lacks resp/gpt-5.5: %s", readFile(cat))
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(home, ".codex")); err == nil {
|
||||
t.Error("~/.codex written")
|
||||
}
|
||||
if why := a.Check(); why != "" {
|
||||
t.Errorf("check: %s", why)
|
||||
}
|
||||
|
||||
// the base URL gone from the launch arguments is said, and a sync
|
||||
// puts it back
|
||||
if err := edit.SetJSON(path, edit.KV{Path: t3CodexInstance + ".config.launchArgs", Value: "--strict-config"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if why := a.Check(); !strings.Contains(why, "Codex") {
|
||||
t.Errorf("check after the args went: %q", why)
|
||||
}
|
||||
if err := a.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e, _ := t3CodexRead(t, path); !strings.Contains(e.Config.LaunchArgs, t3CodexBase(gateway.URL())) || a.Check() != "" {
|
||||
t.Errorf("not repaired: %s / %q", e.Config.LaunchArgs, a.Check())
|
||||
}
|
||||
|
||||
// off takes both instances and the catalog out
|
||||
if err := f.Set(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := t3CodexRead(t, path); ok || f.Get() != "" {
|
||||
t.Errorf("after off: %s", readFile(path))
|
||||
}
|
||||
if _, err := os.Stat(cat); err == nil {
|
||||
t.Error("catalog left after off")
|
||||
}
|
||||
if _, ok := edit.GetJSON(path, "providerInstances.codex"); !ok {
|
||||
t.Error("T3's own Codex removed")
|
||||
}
|
||||
}
|
||||
|
||||
// An older magpie wrote its Claude Code instance alone: the next sync adds
|
||||
// the Codex one. One the user then removed in T3 stays removed through
|
||||
// syncs, and turning magpie on again brings it back. The name and on/off
|
||||
// the user gave it stay.
|
||||
func TestT3CodeCodexInstanceAddedOnce(t *testing.T) {
|
||||
home := syncHome(t)
|
||||
t.Setenv("T3CODE_HOME", "")
|
||||
path := filepath.Join(home, ".t3", "userdata", "settings.json")
|
||||
a := t3code(home)
|
||||
os.MkdirAll(filepath.Dir(path), 0o755)
|
||||
if err := edit.SetJSON(path, edit.KV{Path: t3Instance, Value: t3Merged(path, gateway.URL())}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := t3CodexRead(t, path); !ok {
|
||||
t.Fatalf("not added by a sync: %s", readFile(path))
|
||||
}
|
||||
|
||||
if err := edit.SetJSON(path, edit.KV{Path: t3CodexInstance + ".displayName", Value: "Codex via magpie"}, edit.KV{Path: t3CodexInstance + ".enabled", Value: false}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e, _ := t3CodexRead(t, path); e.DisplayName != "Codex via magpie" || e.Enabled == nil || *e.Enabled {
|
||||
t.Errorf("the user's name or off lost: %+v", e)
|
||||
}
|
||||
|
||||
if err := edit.DelJSON(path, t3CodexInstance); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 2 {
|
||||
if err := a.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, ok := t3CodexRead(t, path); ok {
|
||||
t.Fatal("a sync brought back the instance the user removed")
|
||||
}
|
||||
if a.Field("provider").Get() != magpieID {
|
||||
t.Fatal("magpie off with its Claude Code instance there")
|
||||
}
|
||||
if err := a.Field("provider").Set(magpieID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := t3CodexRead(t, path); !ok {
|
||||
t.Fatal("turning magpie on didn't bring the Codex instance back")
|
||||
}
|
||||
|
||||
// the Claude Code instance removed in T3, the Codex one keeps magpie on
|
||||
if err := edit.DelJSON(path, t3Instance); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.Field("provider").Get() != magpieID || a.Check() != "" {
|
||||
t.Errorf("Codex instance alone: %q %q", a.Field("provider").Get(), a.Check())
|
||||
}
|
||||
}
|
||||
@@ -1386,7 +1386,7 @@ const I18N = {
|
||||
"{agent} signed out of {user}": "{agent} 已退出 {user}",
|
||||
"auth": "认证",
|
||||
"agent default": "Agent 默认值",
|
||||
"every magpie model as a provider in T3 Code, on Claude Code": "magpie 的全部模型作为 T3 Code 里的一个供应商(经 Claude Code 运行)",
|
||||
"every magpie model in T3 Code twice: magpie on Claude Code, magpie · Codex on Codex; pick one in T3's model picker": "magpie 的全部模型在 T3 Code 里出现两次:magpie 走 Claude Code,magpie · Codex 走 Codex;在 T3 的模型选择器里选一个",
|
||||
"default": "默认",
|
||||
"default ({level})": "默认({level})",
|
||||
"off": "关闭",
|
||||
@@ -5592,7 +5592,7 @@ const I18N = {
|
||||
"{agent} signed out of {user}": "{agent} 已退出 {user}",
|
||||
"auth": "認證",
|
||||
"agent default": "Agent 預設值",
|
||||
"every magpie model as a provider in T3 Code, on Claude Code": "magpie 的全部模型作為 T3 Code 裡的一個供應商(經 Claude Code 執行)",
|
||||
"every magpie model in T3 Code twice: magpie on Claude Code, magpie · Codex on Codex; pick one in T3's model picker": "magpie 的全部模型在 T3 Code 裡出現兩次:magpie 走 Claude Code,magpie · Codex 走 Codex;在 T3 的模型選擇器裡選一個",
|
||||
"default": "預設",
|
||||
"default ({level})": "預設({level})",
|
||||
"off": "關閉",
|
||||
@@ -9769,7 +9769,7 @@ const I18N = {
|
||||
"{agent} signed out of {user}": "{agent} は {user} からサインアウトしました",
|
||||
"auth": "認証",
|
||||
"agent default": "エージェントのデフォルト",
|
||||
"every magpie model as a provider in T3 Code, on Claude Code": "magpie のすべてのモデルを T3 Code のプロバイダとして(Claude Code 上で)",
|
||||
"every magpie model in T3 Code twice: magpie on Claude Code, magpie · Codex on Codex; pick one in T3's model picker": "magpie のすべてのモデルが T3 Code に 2 回並びます:magpie は Claude Code、magpie · Codex は Codex で動きます。T3 のモデルピッカーで選んでください",
|
||||
"default": "デフォルト",
|
||||
"default ({level})": "デフォルト({level})",
|
||||
"off": "オフ",
|
||||
@@ -13976,7 +13976,7 @@ const I18N = {
|
||||
"{agent} signed out of {user}": "{agent} von {user} abgemeldet",
|
||||
"auth": "Auth",
|
||||
"agent default": "Standard des Agenten",
|
||||
"every magpie model as a provider in T3 Code, on Claude Code": "alle magpie-Modelle als Anbieter in T3 Code, über Claude Code",
|
||||
"every magpie model in T3 Code twice: magpie on Claude Code, magpie · Codex on Codex; pick one in T3's model picker": "alle magpie-Modelle zweimal in T3 Code: magpie über Claude Code, magpie · Codex über Codex; wähle eins in T3s Modellauswahl",
|
||||
"default": "Standard",
|
||||
"default ({level})": "Standard ({level})",
|
||||
"off": "aus",
|
||||
|
||||
Reference in New Issue
Block a user