From 870d1cf64f896bc272f44cca236ae16e45a9f415 Mon Sep 17 00:00:00 2001 From: zhoushoujian Date: Wed, 25 Nov 2026 19:10:22 +0800 Subject: [PATCH] feat(profiles): add caller-specific defaults Support native Claude Sonnet profiles through the installed Claude Code login and route new runs by explicit caller without changing resume behavior.\n\nRefs MIKA-77 Co-authored-by: multica-agent --- README.md | 13 +- docs/execution-pkg-detail.md | 16 +- docs/execution-pkg.md | 4 +- docs/guide.md | 37 +- internal/agentinstall/install.go | 3 +- internal/cli/caller_default_test.go | 436 ++++++++++++++++++ internal/cli/cli.go | 58 ++- internal/cli/execution.go | 2 +- internal/cli/profile_availability.go | 2 +- internal/cli/profile_lifecycle.go | 4 + internal/cli/profiles.go | 87 ++-- internal/cli/settings.go | 6 + internal/config/caller_defaults.go | 146 ++++++ internal/config/config.go | 46 +- internal/config/native_auth_test.go | 264 +++++++++++ internal/config/profile.go | 14 +- internal/config/profile_lifecycle.go | 12 + internal/worker/environment.go | 3 + internal/worker/native_auth_test.go | 188 ++++++++ internal/worker/native_controls.go | 5 +- internal/worker/worker.go | 39 +- .../OffloadMonitor/ProfileModels.swift | 30 +- .../Sources/OffloadMonitor/SettingsView.swift | 36 +- .../OffloadMonitorTests/ControlTests.swift | 15 +- pkg/execution/execution.go | 13 +- pkg/execution/native_auth_test.go | 129 ++++++ pkg/execution/profiles.go | 4 +- skills/offload/SKILL.md | 7 +- 28 files changed, 1521 insertions(+), 98 deletions(-) create mode 100644 internal/cli/caller_default_test.go create mode 100644 internal/config/caller_defaults.go create mode 100644 internal/config/native_auth_test.go create mode 100644 internal/worker/native_auth_test.go create mode 100644 pkg/execution/native_auth_test.go diff --git a/README.md b/README.md index 3d716a9..5d346d0 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,11 @@ brief instead of spawning a native subagent. The worker starts with a clean context, so nothing leaks between it and the main conversation, and only its final report comes back. The main agent keeps design decisions and final review. -- **Default profile first:** new runs inherit `OFFLOAD_PROFILE` or the configured - default; explicit per-run overrides remain available when requested or required. -- **Two backends:** Codex CLI and Claude Code with Anthropic-compatible gateways. +- **Default profile first:** new runs inherit `OFFLOAD_PROFILE`, the default for an + explicit `--caller`, or the configured default; explicit per-run overrides remain + available when requested or required. +- **Two backends:** Codex CLI and Claude Code, through Anthropic-compatible gateways + or Claude Code's own official login (`"auth_mode": "native"`). - **Named profiles:** a model, provider or managed Codex account, with an optional hint about which tasks it suits. - **Persistent sessions:** resume related work and inspect previous reports. - **macOS dashboard:** track tasks, switch profiles and manage accounts. @@ -51,8 +53,9 @@ offload stats # usage and estimated costs ``` `-p` selects a profile for one task; `offload default ` changes the saved -default. `OFFLOAD_PROFILE` overrides that default. Resumes retain their recorded -account. Costs are estimates when available, not billing records. +default. `OFFLOAD_PROFILE` overrides that default. `offload default --caller +` sets a profile for runs that pass `--caller `, a routing convenience and +not access control. Resumes retain their recorded profile and account. Costs are estimates when available, not billing records. **Execution scope:** default-policy Codex workers bypass approvals and sandboxing. `-w` communicates write intent; it does not enforce a filesystem boundary. Give diff --git a/docs/execution-pkg-detail.md b/docs/execution-pkg-detail.md index 61de692..fa81fdb 100644 --- a/docs/execution-pkg-detail.md +++ b/docs/execution-pkg-detail.md @@ -9,7 +9,13 @@ No exported signature requires importing an `internal` package. `New` validates and snapshots the explicit profile without starting a native process. `LoadConfig` reads the given absolute config file and resolves the named profile; -it never saves config or changes global defaults. Requests use an existing +it never saves config or changes global defaults, and it copies `AuthMode`. +`Profile.AuthMode` is empty (gateway) or `native`; it is omitted from +`ProfileFingerprint` when empty, so fingerprints of existing gateway and Codex +profiles are unchanged, while a native profile hashes differently from the same +profile in gateway mode. `ListProfiles` reports `AuthMode` `native` for it. +Per-caller default profiles are a CLI selection feature; the package still takes +an explicit profile name and never reads `caller_defaults`. Requests use an existing absolute directory; native continuation is explicit, with no automatic lookup or retry on a missing native session. @@ -129,7 +135,13 @@ assembly. Caller instructions use a private temporary file, the task uses stdin, and images use native stream-JSON blocks. Normal native project discovery remains owned by Claude; extraction and restricted reads exclude ambient instructions. Credentials always come from the selected Offload profile, never an ambient -native profile's settings or caller ANTHROPIC variables. The optional stream +native profile's settings or caller ANTHROPIC variables. A Claude profile with +`AuthMode: "native"` is the one exception: it sets no gateway variables, resolves +no token and makes no gateway reachability check, passes `--model`, omits +`--bare` (which never reads the official login) and still removes every caller +`ANTHROPIC_*` variable and passes `--setting-sources ""`. It requires a `Model` +and no `BaseURL`, `Token`, `TokenCmd` or `Endpoint`, applies to Claude only, and +cannot be combined with an isolated `EnvironmentDirectory`. The optional stream environment accepts only the validated streaming-recovery switch and positive output-token limit; it is applied consistently to child environment and settings. diff --git a/docs/execution-pkg.md b/docs/execution-pkg.md index b98f229..4a1c3ac 100644 --- a/docs/execution-pkg.md +++ b/docs/execution-pkg.md @@ -15,7 +15,9 @@ events, cancellation, timeout and process cleanup. Execution completion never implies business acceptance or memory publication. Configuration is explicit: construct a client with a resolved profile, or load a -named profile from an explicit absolute configuration path. A request supplies +named profile from an explicit absolute configuration path. A Claude profile with +`AuthMode: "native"` uses the installed Claude Code's official login and needs no +`BaseURL`, `Token` or `TokenCmd`; an empty `AuthMode` is the gateway mode. A request supplies the task, working directory, internal instructions and optional native session. The caller cancels through its context; the package installs no process-wide signal handlers and does not change cwd or environment. diff --git a/docs/guide.md b/docs/guide.md index 4d9be50..2fc974e 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -55,6 +55,19 @@ Run `offload config`, select **Profile**, then **Add profile** to save a bundle Optional `endpoint` (`cc` for a Claude Code proxy, `llm` for a generic LLM gateway) applies to Claude profiles only. It is an informational label shown by `offload profiles` and in the settings wizard; it does not change requests. Unknown values and Codex profiles with an endpoint are rejected. +### Official Claude (native login) + +A Claude profile with `"auth_mode": "native"` runs the installed Claude Code with its own official login (OAuth or keychain) instead of a gateway. Sign in once with the `claude` CLI. A native profile needs a `model` (an alias such as `sonnet`, or a full model name) and must not set `base_url`, `token`, `token_cmd` or `endpoint`; an empty or absent `auth_mode` keeps the gateway behavior above. Native auth applies to Claude profiles only. + +```sh +offload profile save --json <<'JSON' +{"name":"claude-sonnet","create":true,"backend":"claude","model":"sonnet","auth_mode":"native"} +JSON +offload -p claude-sonnet -d /absolute/path/app "Summarize README.md, max 5 bullets." +``` + +For a native run, offload still drops every caller `ANTHROPIC_*` variable and keeps `--setting-sources ""`, so an ambient key, token or gateway URL cannot redirect the worker. It sets no `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` or `ANTHROPIC_MODEL`, runs no token command, makes no gateway reachability check, and passes the model as `--model` instead. It omits `--bare`, because `--bare` never reads OAuth or the keychain, and sets `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`. Permission and tool behavior match gateway runs. A native profile cannot be combined with an isolated execution environment, which replaces the home that holds the login. `offload profiles --json` reports `auth_mode: "native"` with an empty `base_url`. Switch an existing profile with `{"name":"…","auth_mode":"native"}` (this clears its gateway settings) or back with `auth_mode` `token` or `token_cmd` plus a `base_url` and `secret`. + ### How switching works Profiles select a `backend`: `claude` (the default for existing profiles) or `codex`. Claude profiles provide the three variables Claude Code reads. For each Claude run, offload drops every `ANTHROPIC_*` variable from the caller's environment and sets exactly: @@ -77,10 +90,26 @@ Interrupted Codex runs retain progress and a resume command. Automatic tool-less ### Choosing a profile -Choose per run with `-p name`, per shell with `OFFLOAD_PROFILE=name`, otherwise through `default` in the config. `offload profiles` lists profiles (name, backend, endpoint or `-`, model, base URL), with `*` marking the selected default; it never prints tokens. +Choose per run with `-p name`, per shell with `OFFLOAD_PROFILE=name`, per calling tool with a [caller default](#per-caller-default-profiles), otherwise through `default` in the config. `offload profiles` lists profiles (name, backend, endpoint or `-`, model, base URL), with `*` marking the selected default; it never prints tokens. Profiles may declare `"aliases": ["cc", "fast"]`. Each alias must match `[a-z0-9-]{1,32}`, be unique across all profiles, and differ from every profile name. Use aliases with `-p cc`, `OFFLOAD_PROFILE=cc`, or `offload default cc`; the saved default and run records use the resolved full name. JSON results and history also include `profile_alias` when an alias selected the run. Resuming a session keeps its stored profile name. `offload profiles` displays aliases, and `offload config` lets you edit a comma-separated alias list (clear it to remove all aliases). +### Per-caller default profiles + +An external main agent can have its own default profile, so Claude Code and Codex each delegate through the profile that suits them. The key is the `--caller` ID that agent passes on every call: + +```sh +offload default --caller claude claude-sonnet # saved as caller_defaults.claude +offload default --caller codex codex +offload default --caller claude # print it (the global default if none is set) +``` + +The profile may be an alias; the canonical name is saved. The caller follows the `--caller` rules (lowercase `[a-z0-9][a-z0-9._-]{0,63}`; `unspecified` is refused). There is no clearing syntax yet; point the caller at another profile, or edit `caller_defaults` in `config.json`. + +New runs choose the profile in this order: `-p`; the profile a resumed session or named thread is bound to; `OFFLOAD_PROFILE`; the default mapped to an **explicitly supplied** `--caller`; the global default. A run without `--caller`, or with a caller that has no mapping, uses the global default; `unspecified` never matches. A mapped profile that is missing or disabled fails the run instead of falling back; one that is only marked unavailable is still selected, like `-p`. Resuming (`-r`, `-thread`, `offload resume`) keeps the session's original profile after any default changes. A profile that a caller default names cannot be disabled or deleted until that caller points elsewhere. + +`--caller` is a routing convenience, not authentication or access control: any process can pass any caller ID. `offload profiles --json` adds a `caller_defaults` object (empty when none); `configured_default`, `active` and `active_source` stay global. + ```bash offload profiles offload default codex # save Codex as the default @@ -325,6 +354,8 @@ offload schedule add|list|show|update|pause|resume|delete|results|start|status offload profiles [--json] list profiles (* = the one a run would use); --json is a redacted machine-readable list offload profile save --json create or edit one profile from a JSON request on stdin offload default [profile] show or set the saved default profile +offload default --caller ID [profile] + show or set the profile new runs with --caller ID use offload mode [basic|proactive] show or set the saved delegation mode offload install-agent [flags] install skills and delegation agent instructions offload agent status [--json] user-scope skill/instruction state for Codex and Claude Code @@ -332,7 +363,7 @@ offload agent enable|disable --agent codex|claude|all [--json] offload feedback print the project homepage URL and open it in the default browser offload version - -p profile profile name (default: $OFFLOAD_PROFILE, then config default) + -p profile profile name (default: $OFFLOAD_PROFILE, then the --caller default, then config default) -m model override the profile's model -effort level override the profile's reasoning effort for this run -fast Codex only: priority (fast) tier for this run; -fast=false uses the default tier @@ -729,7 +760,7 @@ See [execution-transcript.md](execution-transcript.md). `-caller ID` (also `--caller ID`) optionally names the tool that invoked this run. It is metadata only and is separate from `-caller-run-id`, which correlates one run with one -supervisor job. It changes no execution, authentication, profile or sandbox behavior. +supervisor job. It changes no execution, authentication or sandbox behavior. Its only effect on profile selection is the optional [per-caller default](#per-caller-default-profiles), and it is a routing convenience, not authentication or access control. ```sh offload -json -caller agh -p codex -d /absolute/repo "Implement the assigned task" diff --git a/internal/agentinstall/install.go b/internal/agentinstall/install.go index d1cb3d3..8976438 100644 --- a/internal/agentinstall/install.go +++ b/internal/agentinstall/install.go @@ -44,7 +44,8 @@ const offloadAgentPolicy = offloadPolicyBegin + ` // subagentPolicy positions offload as the replacement for native subagents in both modes. const subagentPolicy = `- Use offload in place of a native subagent for any clearly specified task that does not need your conversation: research, localization, review, implementation slices, checks. The worker starts with a clean context, so nothing from your conversation leaks in or out. Parallel work means several background offload runs. Independent review starts a fresh session on the active default; use a different profile/model only when explicitly requested or concretely required for independence, and state why. Keep a native subagent only when the task needs your forked conversation, needs host-only tools the worker lacks (browser, MCP or app tools), or is the Codex result waiter. -- For new runs, normally omit -p, -m, -effort and -fast so offload inherits an explicit OFFLOAD_PROFILE or the configured default and its settings. The use_for field is descriptive metadata and must not override a usable default. Never randomly choose or proactively rotate profiles/accounts, and never silently change provider, model, effort or tier. Override only for an explicit user request, a concrete task incompatibility, or a verified default failure with a user-authorized compatible fallback; explain the reason. If the default is unavailable or disabled, report the concrete failure instead of testing, enabling, editing or replacing it automatically. Do not invent profile names.` +- Pass --caller codex on every invocation when the supervising main agent is Codex, or --caller claude when it is Claude Code, including resumes. This selects that agent's configured caller default; it is routing metadata, not authentication or access control. +- For new runs, normally omit -p, -m, -effort and -fast so offload inherits an explicit OFFLOAD_PROFILE, then the --caller default, then the configured default and its settings. The use_for field is descriptive metadata and must not override a usable default. Never randomly choose or proactively rotate profiles/accounts, and never silently change provider, model, effort or tier. Override only for an explicit user request, a concrete task incompatibility, or a verified default failure with a user-authorized compatible fallback; explain the reason. If the selected default is unavailable or disabled, report the concrete failure instead of testing, enabling, editing or replacing it automatically. Do not invent profile names.` // sessionReusePolicy is shared by both modes so the installed workflow stays identical. const sessionReusePolicy = `- Reuse one worker session for related work: investigation, implementation, and review corrections of the same task or slice should use offload -r without selection overrides (it keeps the original profile/account and directory). Each follow-up still states the current corrections and acceptance criteria, because backend compaction means history is not unlimited or verbatim. Start a new session for unrelated tasks, a different explicitly requested/required profile, or stale context; do not reuse one session for every task. Never send overlapping runs to one session. Inspect an interrupted run (offload show , git diff) before continuing, and keep its partial edits. If the session's profile no longer exists, restore it or start a user-authorized new session with -p; offload never switches providers silently. diff --git a/internal/cli/caller_default_test.go b/internal/cli/caller_default_test.go new file mode 100644 index 0000000..39fd0ae --- /dev/null +++ b/internal/cli/caller_default_test.go @@ -0,0 +1,436 @@ +package cli + +import ( + "encoding/json" + "os" + "strings" + "testing" + + "github.com/zhoushoujianwork/offload/internal/config" + "github.com/zhoushoujianwork/offload/internal/history" +) + +// callerCfg: global default "glob"; "envp", "explicit", "claude-sonnet" (native, alias "son") and +// "cx" (Codex) are the other choices a run can land on. +const callerDefaultsCfg = `{"default":"glob","profiles":{` + + `"glob":{"base_url":"https://glob.example","model":"mg","token":"t"},` + + `"envp":{"base_url":"https://env.example","model":"me","token":"t"},` + + `"explicit":{"base_url":"https://exp.example","model":"mx","token":"t"},` + + `"claude-sonnet":{"auth_mode":"native","model":"sonnet","aliases":["son"]},` + + `"off":{"disabled":true,"base_url":"https://off.example","model":"mo","token":"t"},` + + `"cx":{"backend":"codex","aliases":["codex-alias"]}}}` + +func writeCallerDefaultsCfg(t *testing.T, mutate func(string) string) { + t.Helper() + body := callerDefaultsCfg + if mutate != nil { + body = mutate(body) + } + if err := os.WriteFile(config.Path(), []byte(body), 0o600); err != nil { + t.Fatal(err) + } +} + +func ranProfile(t *testing.T) string { t.Helper(); return lastRecord(t).Profile } + +func TestCallerDefaultPrecedence(t *testing.T) { + work, _ := setup(t, okReply) + writeCallerDefaultsCfg(t, nil) + for _, args := range [][]string{{"default", "--caller", "claude", "claude-sonnet"}} { + if code, _, e := runCLI(args...); code != 0 { + t.Fatal(e) + } + } + run := func(env string, args ...string) string { + t.Helper() + t.Setenv("OFFLOAD_PROFILE", env) + if code, out, e := runCLI(append(append([]string{"-d", work}, args...), "task")...); code != 0 { + t.Fatalf("code=%d out=%q err=%q", code, out, e) + } + return ranProfile(t) + } + for _, tc := range []struct { + name string + env string + args []string + want string + }{ + {"explicit -p beats env, caller and global", "envp", []string{"-p", "explicit", "--caller", "claude"}, "explicit"}, + {"explicit alias is canonicalized", "", []string{"-p", "son", "--caller", "claude"}, "claude-sonnet"}, + {"OFFLOAD_PROFILE beats caller default", "envp", []string{"--caller", "claude"}, "envp"}, + {"caller default beats global", "", []string{"--caller", "claude"}, "claude-sonnet"}, + {"caller is normalized to lowercase", "", []string{"--caller", "CLAUDE"}, "claude-sonnet"}, + {"no caller uses the global default", "", nil, "glob"}, + {"unknown caller uses the global default", "", []string{"--caller", "other"}, "glob"}, + {"explicit unspecified never matches", "", []string{"--caller", "unspecified"}, "glob"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := run(tc.env, tc.args...); got != tc.want { + t.Fatalf("ran on %q, want %q", got, tc.want) + } + }) + } +} + +func TestCallerDefaultNativeRunUsesOfficialLoginPath(t *testing.T) { + work, record := setup(t, okReply) + writeCallerDefaultsCfg(t, nil) + if code, _, e := runCLI("default", "--caller", "claude", "son"); code != 0 { + t.Fatal(e) + } + if code, _, e := runCLI("-d", work, "--caller", "claude", "inspect"); code != 0 { + t.Fatal(e) + } + b, _ := os.ReadFile(record) + got := string(b) + if strings.Contains(got, "--bare") || !strings.Contains(got, "--model\nsonnet\n") || + !strings.Contains(got, "token= base= model= key= hdr=") { + t.Fatalf("native run reached a gateway, used --bare or sent a credential:\n%s", got) + } + if r := lastRecord(t); r.Profile != "claude-sonnet" || r.Backend != "claude" || r.Model != "sonnet" || r.Status != "ok" { + t.Fatalf("%+v", r) + } +} + +func TestCallerDefaultMissingOrDisabledProfileFailsInsteadOfFallingBack(t *testing.T) { + work, record := setup(t, okReply) + for name, mutate := range map[string]func(string) string{ + "missing": func(s string) string { + return strings.Replace(s, `"default":"glob"`, `"default":"glob","caller_defaults":{"claude":"gone"}`, 1) + }, + "disabled": func(s string) string { + return strings.Replace(s, `"default":"glob"`, `"default":"glob","caller_defaults":{"claude":"off"}`, 1) + }, + } { + t.Run(name, func(t *testing.T) { + writeCallerDefaultsCfg(t, mutate) + os.Remove(record) + code, _, e := runCLI("-d", work, "--caller", "claude", "task") + if code != 2 || !strings.Contains(e, "default profile for --caller claude") { + t.Fatalf("code=%d err=%q", code, e) + } + if _, err := os.Stat(record); err == nil { + t.Fatal("a worker started on a fallback profile") + } + // Without the caller the global default still runs. + if code, _, e := runCLI("-d", work, "task"); code != 0 { + t.Fatalf("global default broke: %d %s", code, e) + } + }) + } +} + +func TestCallerDefaultUnavailableProfileIsStillSelected(t *testing.T) { + work, _ := setup(t, okReply) + writeCallerDefaultsCfg(t, func(s string) string { + s = strings.Replace(s, `"explicit":{`, `"explicit":{"unavailable":{"reason":"quota exhausted","at":"2026-01-01T00:00:00Z"},`, 1) + return strings.Replace(s, `"default":"glob"`, `"default":"glob","caller_defaults":{"claude":"explicit"}`, 1) + }) + if code, _, e := runCLI("-d", work, "--caller", "claude", "task"); code != 0 { + t.Fatal(e) + } + if got := ranProfile(t); got != "explicit" { + t.Fatalf("an unavailable (not disabled) mapped profile is selected like -p, ran on %q", got) + } +} + +func TestResumeAndThreadRetainProfileAfterCallerDefaultChanges(t *testing.T) { + work, record := setup(t, okReply) + writeCallerDefaultsCfg(t, nil) + if code, _, e := runCLI("default", "--caller", "claude", "explicit"); code != 0 { + t.Fatal(e) + } + if code, _, e := runCLI("-d", work, "--caller", "claude", "-thread", "t1", "first"); code != 0 { + t.Fatal(e) + } + first := lastRecord(t) + if first.Profile != "explicit" { + t.Fatalf("first run: %+v", first) + } + // Change the caller default and the global default; the saved session must keep its profile. + if code, _, e := runCLI("default", "--caller", "claude", "envp"); code != 0 { + t.Fatal(e) + } + if code, _, e := runCLI("default", "cx"); code != 0 { + t.Fatal(e) + } + if code, _, e := runCLI("-d", work, "--caller", "claude", "-r", first.Session, "follow"); code != 0 { + t.Fatal(e) + } + if r := lastRecord(t); r.Profile != "explicit" { + t.Fatalf("resume moved to %q", r.Profile) + } + if b, _ := os.ReadFile(record); !strings.Contains(string(b), "base=https://exp.example") { + t.Fatalf("resume reached another gateway:\n%s", b) + } + // A thread run resumes its saved session, so it keeps that session's profile even though the + // caller default and the global default both changed. + if code, _, e := runCLI("-d", work, "--caller", "claude", "-thread", "t1", "again"); code != 0 { + t.Fatalf("thread: %s", e) + } + if r := lastRecord(t); r.Profile != "explicit" || r.ThreadStart != "resumed" || r.Thread != "t1" { + t.Fatalf("a named thread moved to %q after the defaults changed: %+v", r.Profile, r) + } + // A fresh thread key has no session to retain, so it follows the caller default. + if code, _, e := runCLI("-d", work, "--caller", "claude", "-thread", "t2", "new"); code != 0 { + t.Fatalf("new thread: %s", e) + } + if r := lastRecord(t); r.Profile != "envp" || r.ThreadStart != "fresh" { + t.Fatalf("a new thread must use the current caller default: %+v", r) + } + // offload resume (saved -p args) also keeps the profile. + if code, _, e := runCLI("resume", "--id", first.RunID, "--json", "--caller", "claude"); code != 0 { + t.Fatalf("resume: %s", e) + } + if r := lastRecord(t); r.Profile != "explicit" { + t.Fatalf("offload resume moved to %q", r.Profile) + } +} + +func TestDefaultCallerCommand(t *testing.T) { + setup(t, okReply) + writeCallerDefaultsCfg(t, func(s string) string { + return strings.Replace(s, `"default":"glob"`, `"default":"glob","future":{"keep":true}`, 1) + }) + show := func(args ...string) (int, string, string) { + code, out, e := runCLI(append([]string{"default", "--caller"}, args...)...) + return code, strings.TrimSpace(out), e + } + if code, out, _ := show("claude"); code != 0 || out != "glob" { + t.Fatalf("an unset caller prints the global default: %d %q", code, out) + } + if code, out, e := show("Claude", "son"); code != 0 || out != "claude-sonnet" { + t.Fatalf("alias must be saved and printed canonically: %d %q %s", code, out, e) + } + if code, out, _ := show("claude"); code != 0 || out != "claude-sonnet" { + t.Fatalf("show: %d %q", code, out) + } + if code, out, _ := runCLI("default"); code != 0 || strings.TrimSpace(out) != "glob" { + t.Fatalf("the global default must not change: %q", out) + } + raw, _ := os.ReadFile(config.Path()) + var f struct { + CallerDefaults map[string]string `json:"caller_defaults"` + Future json.RawMessage `json:"future"` + } + if err := json.Unmarshal(raw, &f); err != nil || f.CallerDefaults["claude"] != "claude-sonnet" || !strings.Contains(string(f.Future), "keep") { + t.Fatalf("%v %s", err, raw) + } + before, _ := os.ReadFile(config.Path()) + for _, args := range [][]string{{}, {"unspecified", "glob"}, {"bad caller", "glob"}, {"claude", "missing"}, {"claude", "off"}, {"claude", "glob", "extra"}, {""}} { + if code, _, _ := show(args...); code != 2 { + t.Errorf("%q: code %d", args, code) + } + } + if after, _ := os.ReadFile(config.Path()); string(after) != string(before) { + t.Fatal("a rejected command modified the config") + } + if code, _, _ := runCLI("default", "glob", "extra"); code != 2 { + t.Fatal("plain default keeps rejecting extra arguments") + } +} + +func TestProfileLifecycleRefusesCallerDefaultTargets(t *testing.T) { + setup(t, okReply) + writeCallerDefaultsCfg(t, nil) + if code, _, e := runCLI("default", "--caller", "claude", "claude-sonnet"); code != 0 { + t.Fatal(e) + } + before, _ := os.ReadFile(config.Path()) + for _, verb := range []string{"disable", "delete"} { + for _, ref := range []string{"claude-sonnet", "son"} { // canonical name and alias + code, _, e := runCLI("profile", verb, ref) + if code != 2 || !strings.Contains(e, "default for caller claude") { + t.Errorf("%s %s: code=%d err=%q", verb, ref, code, e) + } + } + } + // The JSON edit path refuses too. + code, _, e := runProfileCLI([]string{"profile", "save", "--json"}, `{"name":"claude-sonnet","disabled":true}`) + if code != 2 || !strings.Contains(e, "caller default") { + t.Fatalf("save disabled: code=%d err=%q", code, e) + } + if after, _ := os.ReadFile(config.Path()); string(after) != string(before) { + t.Fatal("a refused change modified the config") + } + // Unreferenced profiles are unaffected. + if code, _, e := runCLI("profile", "disable", "envp"); code != 0 { + t.Fatal(e) + } +} + +func TestProfileSaveNativeAndSnapshotReportsNative(t *testing.T) { + profileCfg(t, `{"default":"gw","profiles":{"gw":{"base_url":"https://gw","model":"m","token":"secret-token"}}}`) + code, out, e := runProfileCLI([]string{"profile", "save", "--json"}, + `{"name":"claude-sonnet","create":true,"backend":"claude","model":"sonnet","auth_mode":"native"}`) + if code != 0 || e != "" { + t.Fatalf("code=%d err=%q out=%s", code, e, out) + } + snap := decodeSnap(t, out) + var got *profileEntry + for i := range snap.Profiles { + if snap.Profiles[i].Name == "claude-sonnet" { + got = &snap.Profiles[i] + } + } + if got == nil || got.AuthMode != "native" || got.BaseURL != "" || got.Model != "sonnet" || got.Backend != "claude" || !got.Available { + t.Fatalf("%+v", got) + } + for _, p := range snap.Profiles { + if p.Name == "gw" && p.AuthMode != "token" { + t.Fatalf("gateway profile auth_mode changed: %+v", p) + } + } + if snap.CallerDefaults == nil || len(snap.CallerDefaults) != 0 { + t.Fatalf("caller_defaults must be an empty object, not null: %#v", snap.CallerDefaults) + } + noLeak(t, out, e) + raw, _ := os.ReadFile(config.Path()) + if !strings.Contains(string(raw), `"auth_mode": "native"`) || !strings.Contains(string(raw), "secret-token") { + t.Fatalf("native save must add the mode and keep other profiles:\n%s", raw) + } +} + +func TestProfileSaveNativeRejectsContradictions(t *testing.T) { + for name, body := range map[string]string{ + "codex": `{"name":"x","create":true,"backend":"codex","auth_mode":"native"}`, + "no model": `{"name":"x","create":true,"auth_mode":"native"}`, + "base url": `{"name":"x","create":true,"model":"sonnet","auth_mode":"native","base_url":"https://gw"}`, + "endpoint": `{"name":"x","create":true,"model":"sonnet","auth_mode":"native","endpoint":"cc"}`, + "secret": `{"name":"x","create":true,"model":"sonnet","auth_mode":"native","secret":"s"}`, + "unknown mode": `{"name":"x","create":true,"model":"sonnet","auth_mode":"oauth"}`, + } { + t.Run(name, func(t *testing.T) { + path := profileCfg(t, `{"default":"gw","profiles":{"gw":{"base_url":"https://gw","model":"m","token":"t"}}}`) + before, _ := os.ReadFile(path) + code, _, e := runProfileCLI([]string{"profile", "save", "--json"}, body) + if code != 2 || e == "" { + t.Fatalf("code=%d err=%q", code, e) + } + if after, _ := os.ReadFile(path); string(after) != string(before) { + t.Fatal("a rejected save modified the config") + } + }) + } +} + +func TestProfileSaveSwitchesBetweenNativeAndGateway(t *testing.T) { + path := profileCfg(t, `{"default":"gw","profiles":{"gw":{"base_url":"https://gw","model":"m","token":"secret"}}}`) + // Gateway to native drops the gateway settings. + code, _, e := runProfileCLI([]string{"profile", "save", "--json"}, `{"name":"gw","auth_mode":"native"}`) + if code != 0 { + t.Fatalf("%s", e) + } + cfg, err := config.Load(path) + if err != nil { + t.Fatal(err) + } + if p := cfg.Profiles["gw"]; !p.UsesNativeAuth() || p.BaseURL != "" || p.Token != "" || p.TokenCmd != "" || p.Endpoint != "" || p.Model != "m" { + t.Fatalf("native switch left gateway settings: %+v", p) + } + if raw, _ := os.ReadFile(path); strings.Contains(string(raw), "secret") { + t.Fatalf("the old token stayed on disk:\n%s", raw) + } + // Native back to a gateway needs a base URL and credential, then clears the native mode. + if code, _, _ := runProfileCLI([]string{"profile", "save", "--json"}, `{"name":"gw","auth_mode":"token","secret":"s2"}`); code != 2 { + t.Fatal("a credential without a base URL must be rejected") + } + code, _, e = runProfileCLI([]string{"profile", "save", "--json"}, `{"name":"gw","base_url":"https://gw2","auth_mode":"token","secret":"s2"}`) + if code != 0 { + t.Fatalf("%s", e) + } + raw, _ := os.ReadFile(path) + if strings.Contains(string(raw), "auth_mode") || !strings.Contains(string(raw), "https://gw2") { + t.Fatalf("gateway switch left native mode:\n%s", raw) + } + if cfg, err = config.Load(path); err != nil || cfg.Profiles["gw"].UsesNativeAuth() || cfg.Profiles["gw"].Token != "s2" { + t.Fatalf("%v %+v", err, cfg.Profiles["gw"]) + } +} + +// The macOS editor switches an existing gateway profile with an endpoint to native by sending only +// auth_mode and an empty endpoint; the CLI must accept exactly that. +func TestProfileSaveNativeFromMacEditorRequestShape(t *testing.T) { + path := profileCfg(t, `{"default":"gw","profiles":{"gw":{"base_url":"https://gw","model":"m","endpoint":"cc","token_cmd":"echo s"}}}`) + code, out, e := runProfileCLI([]string{"profile", "save", "--json"}, `{"name":"gw","auth_mode":"native","endpoint":""}`) + if code != 0 { + t.Fatalf("%s", e) + } + if got := decodeSnap(t, out).Profiles[0]; got.AuthMode != "native" || got.BaseURL != "" || got.Endpoint != "" { + t.Fatalf("%+v", got) + } + // A later edit that leaves the credential alone sends no auth_mode and must keep native. + if code, _, e := runProfileCLI([]string{"profile", "save", "--json"}, `{"name":"gw","use_for":"official"}`); code != 0 { + t.Fatalf("%s", e) + } + cfg, err := config.Load(path) + if err != nil || !cfg.Profiles["gw"].UsesNativeAuth() || cfg.Profiles["gw"].UseFor != "official" { + t.Fatalf("%v %+v", err, cfg.Profiles["gw"]) + } +} + +func TestProfilesJSONCallerDefaultsAreAdditiveAndGlobalFieldsStayGlobal(t *testing.T) { + setup(t, okReply) + writeCallerDefaultsCfg(t, nil) + if code, _, e := runCLI("default", "--caller", "claude", "claude-sonnet"); code != 0 { + t.Fatal(e) + } + t.Setenv("OFFLOAD_PROFILE", "") + _, out, _ := runCLI("profiles", "--json") + snap := decodeSnap(t, out) + if snap.CallerDefaults["claude"] != "claude-sonnet" || snap.ConfiguredDefault != "glob" || snap.Active != "glob" || snap.ActiveSource != "config" || snap.SchemaVersion != 1 { + t.Fatalf("%+v", snap) + } + _, plain, _ := runCLI("profiles") + if !strings.Contains(plain, "native official login") || strings.Contains(plain, "secret") { + t.Fatalf("plain listing:\n%s", plain) + } + var generic map[string]json.RawMessage + if err := json.Unmarshal([]byte(out), &generic); err != nil { + t.Fatal(err) + } + for _, k := range []string{"schema_version", "config_exists", "configured_default", "active", "active_source", "delegation_mode", "profiles", "warnings", "managed_accounts", "caller_defaults"} { + if _, ok := generic[k]; !ok { + t.Errorf("snapshot lost field %q", k) + } + } +} + +func TestHelpDocumentsCallerDefaultAndRoutingOnly(t *testing.T) { + _, out, e := runCLI("-h") + text := out + e + for _, want := range []string{"offload default --caller ID [profile]", "not authentication or access control", "--caller default"} { + if !strings.Contains(text, want) { + t.Errorf("help missing %q", want) + } + } +} + +var _ = history.CallerUnspecified + +// The interactive editor must not ask a native profile for a gateway or credential, and saving it +// must keep the native mode instead of failing on an empty base URL. +func TestSettingsWizardEditsNativeProfileWithoutGatewayPrompts(t *testing.T) { + settingsEnv(t) + writeSettingsConfig(t, `{"default":"claude-sonnet","profiles":{"claude-sonnet":{"auth_mode":"native","model":"sonnet"}}}`) + // Edit current profile, model, aliases, then back. + f := &fakePrompt{steps: []step{choose(0), choose(2), ask("opus"), ask("son"), choose(2)}} + code, out, errOut := runSettingsTest(f) + if code != 0 || errOut != "" { + t.Fatalf("%d %s %s", code, out, errOut) + } + for _, c := range f.calls { + switch c.label { + case "Base URL", "Endpoint", "Authentication", "Token command", "API token": + t.Errorf("a native profile was asked for %q", c.label) + } + } + cfg, err := config.Load(config.Path()) + if err != nil { + t.Fatal(err) + } + p := cfg.Profiles["claude-sonnet"] + if !p.UsesNativeAuth() || p.Model != "opus" || len(p.Aliases) != 1 || p.Aliases[0] != "son" || p.BaseURL != "" || p.Token != "" { + t.Fatalf("%+v", p) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 6babd25..4ad2754 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -63,6 +63,9 @@ usage: offload profiles [--json] list profiles (* = the one a run would use) offload profile save --json create or edit a profile from a JSON request on stdin offload default [profile] show or set the saved default profile + offload default --caller ID [profile] + show or set the profile new runs with --caller ID use + (a routing convenience, not authentication or access control) offload disable / enable [--json] persistently block / allow every new worker and model call (running tasks are not stopped) offload mode [basic|proactive] show or switch delegation mode and agent rules @@ -184,7 +187,7 @@ func cmdRunSaved(args []string, stdin io.Reader, stdout, stderr io.Writer, paren fs := flag.NewFlagSet("offload", flag.ContinueOnError) fs.SetOutput(stderr) fs.Usage = func() { fmt.Fprint(stderr, usage); fs.PrintDefaults() } - profile := fs.String("p", "", "profile name or alias (default: $OFFLOAD_PROFILE, then config default)") + profile := fs.String("p", "", "profile name or alias (default: $OFFLOAD_PROFILE, then the --caller default, then config default)") model := fs.String("m", "", "override the profile's model") effort := fs.String("effort", "", "override the profile's reasoning effort for this run") fast := fs.Bool("fast", false, "for this run: -fast uses the priority (fast) service tier, -fast=false the default tier; Codex profiles only") @@ -349,8 +352,20 @@ func cmdRunSaved(args []string, stdin io.Reader, stdout, stderr io.Writer, paren resumedProfile = selected } } + // Precedence for a new run: -p, then the profile a resume or thread is bound to (both set + // selected above), then OFFLOAD_PROFILE, then the default mapped to an explicit --caller, then + // the global default. The caller only routes the choice; it is not authentication. + callerMapped := "" + if selected == "" && os.Getenv("OFFLOAD_PROFILE") == "" && caller.set { + if mapped, ok := cfg.DefaultFor(caller.value); ok { + selected, callerMapped = mapped, caller.value + } + } selected = firstNonEmpty(selected, firstNonEmpty(os.Getenv("OFFLOAD_PROFILE"), cfg.EffectiveDefault())) name, prof, err := cfg.ResolveForRun(selected) + if err != nil && callerMapped != "" { + err = fmt.Errorf("default profile for --caller %s: %w", callerMapped, err) + } if resumedProfile != "" { if _, exists := cfg.Profiles[resumedProfile]; !exists { name, prof = resumedProfile, config.Profile{} @@ -807,14 +822,23 @@ func cmdProfiles(stdout, stderr io.Writer) int { if p.UseFor != "" { aliases += " — " + p.UseFor } - fmt.Fprintf(stdout, "%s %-12s %-8s %-5s %-15s %-24s %s%s\n", mark, n, p.BackendName(), firstNonEmpty(p.Endpoint, "-"), tools, p.Model, p.BaseURL, aliases) + gateway := p.BaseURL + if p.UsesNativeAuth() { + gateway = "native official login" + } + fmt.Fprintf(stdout, "%s %-12s %-8s %-5s %-15s %-24s %s%s\n", mark, n, p.BackendName(), firstNonEmpty(p.Endpoint, "-"), tools, p.Model, gateway, aliases) } return 0 } +const defaultUsage = "usage: offload default [profile] | offload default --caller [profile]" + func cmdDefault(args []string, stdout, stderr io.Writer) int { + if len(args) > 0 && (args[0] == "--caller" || args[0] == "-caller") { + return cmdCallerDefault(args[1:], stdout, stderr) + } if len(args) > 1 { - return fail(stderr, errors.New("usage: offload default [profile]")) + return fail(stderr, errors.New(defaultUsage)) } if len(args) == 1 { if err := config.SetDefault(config.Path(), args[0]); err != nil { @@ -829,6 +853,34 @@ func cmdDefault(args []string, stdout, stderr io.Writer) int { return 0 } +// cmdCallerDefault shows or sets the default profile for one explicit --caller ID. Setting stores +// the canonical profile name, resolving an alias. Showing prints the mapped profile, or the global +// default when the caller has none. +func cmdCallerDefault(args []string, stdout, stderr io.Writer) int { + if len(args) < 1 || len(args) > 2 { + return fail(stderr, errors.New(defaultUsage)) + } + caller, err := config.NormalizeCallerDefaultKey(args[0]) + if err != nil { + return fail(stderr, err) + } + if len(args) == 2 { + if err := config.SetCallerDefault(config.Path(), caller, args[1]); err != nil { + return fail(stderr, err) + } + } + cfg, err := config.Load(config.Path()) + if err != nil { + return fail(stderr, err) + } + if name, ok := cfg.CallerDefaults[caller]; ok { + fmt.Fprintln(stdout, name) + return 0 + } + fmt.Fprintln(stdout, cfg.Default) + return 0 +} + func fail(w io.Writer, err error) int { fmt.Fprintln(w, "offload:", err) return 2 diff --git a/internal/cli/execution.go b/internal/cli/execution.go index f5eaab8..a2d4448 100644 --- a/internal/cli/execution.go +++ b/internal/cli/execution.go @@ -57,6 +57,6 @@ func publicExecutionConfig(o worker.Opts) execution.Config { return execution.Config{ProfileName: o.ProfileName, Profile: execution.Profile{Backend: p.Backend, BaseURL: p.BaseURL, Model: p.Model, ReasoningEffort: p.ReasoningEffort, ServiceTier: p.ServiceTier, CodexAccount: p.CodexAccount, - IdleTimeout: p.IdleTimeout, Endpoint: p.Endpoint, TokenCmd: p.TokenCmd, Token: p.Token}, + IdleTimeout: p.IdleTimeout, Endpoint: p.Endpoint, AuthMode: p.AuthMode, TokenCmd: p.TokenCmd, Token: p.Token}, Limits: execution.Limits{MaxWorkers: limit, GoMaxProcs: o.Limits.GoMaxProcs, GoParallelism: o.Limits.GoParallelism}} } diff --git a/internal/cli/profile_availability.go b/internal/cli/profile_availability.go index 4cae4c5..6659f65 100644 --- a/internal/cli/profile_availability.go +++ b/internal/cli/profile_availability.go @@ -43,7 +43,7 @@ var probeProfile = func(ctx context.Context, path, name string) probeOutcome { cfg := execution.Config{ProfileName: canonical, Profile: execution.Profile{ Backend: p.Backend, BaseURL: p.BaseURL, Model: p.Model, ReasoningEffort: p.ReasoningEffort, ServiceTier: p.ServiceTier, CodexAccount: p.CodexAccount, IdleTimeout: p.IdleTimeout, - Endpoint: p.Endpoint, TokenCmd: p.TokenCmd, Token: p.Token}, Limits: execution.Limits{ + Endpoint: p.Endpoint, AuthMode: p.AuthMode, TokenCmd: p.TokenCmd, Token: p.Token}, Limits: execution.Limits{ MaxWorkers: saved.Limits.MaxWorkers, GoMaxProcs: saved.Limits.GoMaxProcs, GoParallelism: saved.Limits.GoParallelism}} client, err := execution.New(cfg) if err != nil { diff --git a/internal/cli/profile_lifecycle.go b/internal/cli/profile_lifecycle.go index ce580d1..c7e63a1 100644 --- a/internal/cli/profile_lifecycle.go +++ b/internal/cli/profile_lifecycle.go @@ -93,6 +93,10 @@ func cmdProfileLifecycle(args []string, stdout, stderr io.Writer) int { if err != nil { return fail(stderr, err) } + if callers := cfg.CallersUsing(name); len(callers) > 0 && (args[0] == "disable" || args[0] == "delete") { + return fail(stderr, fmt.Errorf("profile %q is the default for caller %s; set another caller default first (offload default --caller )", + name, strings.Join(callers, ", "))) + } if args[0] != "delete" { err = config.SetProfileDisabled(config.Path(), name, args[0] == "disable") } else { diff --git a/internal/cli/profiles.go b/internal/cli/profiles.go index d89d9ad..ca9fbfa 100644 --- a/internal/cli/profiles.go +++ b/internal/cli/profiles.go @@ -45,15 +45,18 @@ type profileEntry struct { // profileSnapshot is the `offload profiles --json` document (schema_version 1). type profileSnapshot struct { - ManagedAccounts []string `json:"managed_accounts"` - SchemaVersion int `json:"schema_version"` - ConfigExists bool `json:"config_exists"` - ConfiguredDefault string `json:"configured_default"` - Active string `json:"active"` - ActiveSource string `json:"active_source"` - DelegationMode string `json:"delegation_mode"` - Profiles []profileEntry `json:"profiles"` - Warnings []string `json:"warnings"` + ManagedAccounts []string `json:"managed_accounts"` + SchemaVersion int `json:"schema_version"` + ConfigExists bool `json:"config_exists"` + ConfiguredDefault string `json:"configured_default"` + Active string `json:"active"` + ActiveSource string `json:"active_source"` + DelegationMode string `json:"delegation_mode"` + // CallerDefaults maps an explicit --caller ID to its default profile. It never changes + // configured_default, active or active_source, which stay global. + CallerDefaults map[string]string `json:"caller_defaults"` + Profiles []profileEntry `json:"profiles"` + Warnings []string `json:"warnings"` } var errConfigUnreadable = errors.New("config could not be read or is invalid") @@ -74,6 +77,8 @@ func safeBaseURL(raw string) (string, bool) { func authMode(p config.Profile) string { switch { + case p.UsesNativeAuth(): + return "native" case p.TokenCmd != "": return "token_cmd" case p.Token != "": @@ -86,7 +91,7 @@ func authMode(p config.Profile) string { // run token_cmd and never copies credentials into the result. func buildProfileSnapshot(path string) (profileSnapshot, error) { snap := profileSnapshot{ManagedAccounts: config.ManagedAccountNames(), SchemaVersion: profilesSchemaVersion, ActiveSource: "none", - DelegationMode: config.ModeProactive, Profiles: []profileEntry{}, Warnings: []string{}} + DelegationMode: config.ModeProactive, CallerDefaults: map[string]string{}, Profiles: []profileEntry{}, Warnings: []string{}} if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { return snap, nil } @@ -96,6 +101,9 @@ func buildProfileSnapshot(path string) (profileSnapshot, error) { } snap.ConfigExists = true snap.ConfiguredDefault = cfg.Default + for caller, name := range cfg.CallerDefaults { + snap.CallerDefaults[caller] = name + } if cfg.DelegationMode != "" { if config.ValidMode(cfg.DelegationMode) { snap.DelegationMode = cfg.DelegationMode @@ -212,24 +220,27 @@ func readProfileRequest(stdin io.Reader) (profileSaveRequest, error) { // safeSaveErrors are the fixed config validation messages that may be shown to the caller. // Anything else is replaced so request values, paths and parser details never reach the output. var safeSaveErrors = map[string]bool{ - "set another default first": true, - "invalid Claude reasoning effort": true, - "use_for must be a single line without control characters": true, - "use_for must be at most 300 characters": true, - "profile name must not be empty": true, - "profile already exists": true, - "unknown profile": true, - "unknown backend": true, - "invalid Codex reasoning effort": true, - "invalid Codex service tier": true, - "endpoint applies only to claude profiles": true, - "base URL must be http(s) with a host": true, - "model is required": true, - "authentication is required": true, - "unknown endpoint (want cc or llm)": true, - "secret is required for token or token_cmd": true, - "secret is only allowed with token or token_cmd": true, - "unknown auth_mode (want preserve, token, token_cmd or none)": true, + "set another default first": true, + "invalid Claude reasoning effort": true, + "use_for must be a single line without control characters": true, + "use_for must be at most 300 characters": true, + "profile name must not be empty": true, + "profile already exists": true, + "unknown profile": true, + "unknown backend": true, + "invalid Codex reasoning effort": true, + "invalid Codex service tier": true, + "endpoint applies only to claude profiles": true, + "base URL must be http(s) with a host": true, + "model is required": true, + "authentication is required": true, + "unknown endpoint (want cc or llm)": true, + "secret is required for token or token_cmd": true, + "secret is only allowed with token or token_cmd": true, + "unknown auth_mode (want preserve, token, token_cmd, none or native)": true, + "auth_mode applies only to claude profiles": true, + "native auth cannot be combined with base_url, token, token_cmd or endpoint": true, + "set another caller default first": true, } func safeSaveError(err error) error { @@ -303,10 +314,28 @@ func applyProfileRequest(p config.Profile, req profileSaveRequest) (config.Profi if mode == "none" { p.Token, p.TokenCmd = "", "" } + case "native": + if req.Secret != nil { + return p, errors.New("secret is only allowed with token or token_cmd") + } + if p.BackendName() != "claude" { + return p, errors.New("auth_mode applies only to claude profiles") + } + // Switching an existing gateway profile to native drops its gateway settings. Fields the + // request sets explicitly are kept so SaveProfile rejects a contradictory request. + p.AuthMode = config.AuthModeNative + p.Token, p.TokenCmd = "", "" + if req.BaseURL == nil { + p.BaseURL = "" + } + if req.Endpoint == nil { + p.Endpoint = "" + } case "token", "token_cmd": if secret == "" { return p, errors.New("secret is required for token or token_cmd") } + p.AuthMode = "" // a credential selects the gateway path p.Token, p.TokenCmd = "", "" if mode == "token" { p.Token = secret @@ -314,7 +343,7 @@ func applyProfileRequest(p config.Profile, req profileSaveRequest) (config.Profi p.TokenCmd = secret } default: - return p, errors.New("unknown auth_mode (want preserve, token, token_cmd or none)") + return p, errors.New("unknown auth_mode (want preserve, token, token_cmd, none or native)") } return p, nil } diff --git a/internal/cli/settings.go b/internal/cli/settings.go index 7d0828f..688ea02 100644 --- a/internal/cli/settings.go +++ b/internal/cli/settings.go @@ -372,6 +372,12 @@ func settingsWizard(p settingsPrompt, cfg *config.Config, name string, add bool) if err != nil { return err } + } else if profile.UsesNativeAuth() { + // A native profile has no gateway, token or endpoint; only the model is editable here. + profile.Model, err = p.Ask("Model (required, e.g. sonnet)", profile.Model) + if err != nil { + return err + } } else { profile.BaseURL, err = p.Ask("Base URL", profile.BaseURL) if err != nil { diff --git a/internal/config/caller_defaults.go b/internal/config/caller_defaults.go new file mode 100644 index 0000000..7bb0a59 --- /dev/null +++ b/internal/config/caller_defaults.go @@ -0,0 +1,146 @@ +package config + +import ( + "encoding/json" + "errors" + "fmt" + "slices" + "sort" + "strings" + + "github.com/zhoushoujianwork/offload/internal/history" +) + +// ErrCallerDefaultInUse is returned when disabling or deleting a profile that a caller default +// still names. It is a fixed message so the profile-save JSON path may show it. +var ErrCallerDefaultInUse = errors.New("set another caller default first") + +// NormalizeCallerDefaultKey canonicalizes a caller ID for caller_defaults. The synthetic +// "unspecified" caller of an untagged run is refused, because a default for it could never apply. +func NormalizeCallerDefaultKey(caller string) (string, error) { + n, err := history.NormalizeCaller(caller) + if err != nil { + return "", err + } + if n == history.CallerUnspecified { + return "", errors.New(`caller "unspecified" cannot have a default profile`) + } + return n, nil +} + +// ValidateCallerDefaults checks the shape of caller_defaults. It does not require the named +// profiles to exist, so a hand-deleted profile fails only the runs that need it. +func (c *Config) ValidateCallerDefaults() error { + for _, caller := range sortedKeys(c.CallerDefaults) { + n, err := NormalizeCallerDefaultKey(caller) + if err != nil || n != caller { + return fmt.Errorf("caller_defaults: invalid caller %q (want canonical lowercase [a-z0-9][a-z0-9._-]{0,63})", caller) + } + if strings.TrimSpace(c.CallerDefaults[caller]) == "" { + return fmt.Errorf("caller_defaults[%q]: profile name must not be empty", caller) + } + } + return nil +} + +// DefaultFor returns the profile a new run uses when neither -p nor OFFLOAD_PROFILE chose one. +// A caller that was explicitly supplied and has a mapping wins, and mapped is then true. An empty +// caller or the synthetic "unspecified" never matches, so untagged runs keep the global default. +// The mapped name is returned as stored and is not checked here: the run resolves it like -p, so a +// missing or disabled profile fails the run instead of silently falling back. +func (c *Config) DefaultFor(caller string) (name string, mapped bool) { + if caller != "" && caller != history.CallerUnspecified { + if n := c.CallerDefaults[caller]; n != "" { + return n, true + } + } + return c.EffectiveDefault(), false +} + +// CallersUsing lists, in order, the callers whose default is the profile, by canonical name or alias. +func (c *Config) CallersUsing(profile string) []string { + var callers []string + for _, caller := range sortedKeys(c.CallerDefaults) { + if namesProfile(c.CallerDefaults[caller], profile, c.Profiles[profile].Aliases) { + callers = append(callers, caller) + } + } + return callers +} + +func namesProfile(ref, canonical string, aliases []string) bool { + return ref == canonical || slices.Contains(aliases, ref) +} + +// SetCallerDefault saves the default profile for one caller. The profile may be an alias; its +// canonical name is stored. The profile must exist and be enabled. Other fields, including unknown +// JSON, are preserved. +func SetCallerDefault(path, caller, name string) error { + key, err := NormalizeCallerDefaultKey(caller) + if err != nil { + return err + } + if strings.TrimSpace(name) == "" { + return errors.New("default profile name must not be empty") + } + c, err := Load(path) + if err != nil { + return err + } + resolved, profile, err := c.Resolve(name) + if err != nil { + return err + } + if err := profile.CheckEnabled(resolved); err != nil { + return err + } + fields, err := modeSettings(path) + if err != nil { + return err + } + defaults := map[string]string{} + if raw, ok := fields["caller_defaults"]; ok { + if err := json.Unmarshal(raw, &defaults); err != nil || defaults == nil { + return errors.New("caller_defaults must be a JSON object of profile names") + } + } + defaults[key] = resolved + if fields["caller_defaults"], err = json.Marshal(defaults); err != nil { + return err + } + return writeSettings(path, fields) +} + +// callerDefaultsUse reports whether any stored caller default names the profile, by canonical name +// or alias. +func callerDefaultsUse(fields map[string]json.RawMessage, profile string) (bool, error) { + raw, ok := fields["caller_defaults"] + if !ok { + return false, nil + } + var defaults map[string]string + if err := json.Unmarshal(raw, &defaults); err != nil { + return false, errors.New("caller_defaults must be a JSON object of profile names") + } + var profiles map[string]struct { + Aliases []string `json:"aliases"` + } + if raw, ok := fields["profiles"]; ok { + _ = json.Unmarshal(raw, &profiles) // a malformed profiles object is reported by the caller + } + for _, ref := range defaults { + if namesProfile(ref, profile, profiles[profile].Aliases) { + return true, nil + } + } + return false, nil +} + +func sortedKeys(m map[string]string) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} diff --git a/internal/config/config.go b/internal/config/config.go index 577f83e..7cfc180 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -28,6 +28,9 @@ type Profile struct { ServiceTier string `json:"service_tier,omitempty"` // Endpoint is the gateway kind: "cc" (Claude Code proxy) or "llm" (generic LLM gateway); claude backend only, informational. Endpoint string `json:"endpoint,omitempty"` + // AuthMode is empty for a gateway profile (base_url plus token or token_cmd) or "native" for a + // Claude profile that uses the installed Claude Code's own official login. Claude backend only. + AuthMode string `json:"auth_mode,omitempty"` // Unavailable is set when a run or test found an unrecoverable failure. Unavailable *Unavailable `json:"unavailable,omitempty"` // TokenCmd prints the token on stdout (e.g. `security find-generic-password -s offload-minimax -w`). @@ -44,6 +47,10 @@ type Config struct { DelegationMode string `json:"delegation_mode,omitempty"` // Limits caps concurrent workers and sets build defaults for their child processes. Limits Limits `json:"limits,omitempty"` + // CallerDefaults maps a --caller ID to the profile its new runs use when neither -p nor + // OFFLOAD_PROFILE is set. Values are canonical profile names. It selects a profile; it is not + // authentication or access control. + CallerDefaults map[string]string `json:"caller_defaults,omitempty"` } // Gateway kinds accepted in Profile.Endpoint. @@ -106,6 +113,9 @@ func Load(path string) (*Config, error) { if err := c.ValidateAliases(); err != nil { return nil, fmt.Errorf("parse %s: %w", path, err) } + if err := c.ValidateCallerDefaults(); err != nil { + return nil, fmt.Errorf("parse %s: %w", path, err) + } return &c, nil } @@ -138,7 +148,10 @@ func (c *Config) resolveNamed(name string) (string, Profile, error) { if p.BackendName() != "claude" && p.BackendName() != "codex" { return name, p, fmt.Errorf("profile %q has unknown backend %q", name, p.Backend) } - if p.BackendName() == "claude" && (p.BaseURL == "" || p.Model == "") { + if err := p.ValidateAuthMode(); err != nil { + return name, p, fmt.Errorf("profile %q: %w", name, err) + } + if p.BackendName() == "claude" && !p.UsesNativeAuth() && (p.BaseURL == "" || p.Model == "") { return name, p, fmt.Errorf("profile %q needs base_url and model", name) } if err := p.ValidateCodexSettings(); err != nil { @@ -159,6 +172,37 @@ func (p Profile) SupportsToolRestrictions() bool { return p.BackendName() != "codex" } +// AuthModeNative marks a Claude profile that uses the installed Claude Code's official login. +const AuthModeNative = "native" + +// UsesNativeAuth reports whether the profile runs Claude with its own official login instead of a +// gateway. It is true only for a Claude profile with auth_mode "native". +func (p Profile) UsesNativeAuth() bool { + return p.AuthMode == AuthModeNative && p.BackendName() == "claude" +} + +// ValidateAuthMode checks the persisted auth_mode. Native profiles are Claude-only, need a model and +// carry no gateway settings, because the worker neither sets nor reads them. +func (p Profile) ValidateAuthMode() error { + switch p.AuthMode { + case "": + return nil + case AuthModeNative: + default: + return fmt.Errorf("unknown profile auth_mode (want native or unset)") + } + if p.BackendName() != "claude" { + return fmt.Errorf("auth_mode applies only to claude profiles") + } + if strings.TrimSpace(p.Model) == "" { + return fmt.Errorf("model is required") + } + if p.BaseURL != "" || p.Token != "" || p.TokenCmd != "" || p.Endpoint != "" { + return fmt.Errorf("native auth cannot be combined with base_url, token, token_cmd or endpoint") + } + return nil +} + func (p Profile) BackendName() string { if p.Backend == "" { return "claude" diff --git a/internal/config/native_auth_test.go b/internal/config/native_auth_test.go new file mode 100644 index 0000000..409d521 --- /dev/null +++ b/internal/config/native_auth_test.go @@ -0,0 +1,264 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestNativeAuthValidation(t *testing.T) { + t.Setenv("OFFLOAD_PROFILE", "") + for _, tc := range []struct { + name string + profile Profile + want string // empty means valid + }{ + {"native sonnet", Profile{AuthMode: "native", Model: "sonnet"}, ""}, + {"explicit claude backend", Profile{Backend: "claude", AuthMode: "native", Model: "sonnet"}, ""}, + {"missing model", Profile{AuthMode: "native"}, "model is required"}, + {"blank model", Profile{AuthMode: "native", Model: " "}, "model is required"}, + {"base url", Profile{AuthMode: "native", Model: "sonnet", BaseURL: "https://gw"}, "cannot be combined"}, + {"token", Profile{AuthMode: "native", Model: "sonnet", Token: "t"}, "cannot be combined"}, + {"token cmd", Profile{AuthMode: "native", Model: "sonnet", TokenCmd: "echo t"}, "cannot be combined"}, + {"endpoint", Profile{AuthMode: "native", Model: "sonnet", Endpoint: "cc"}, "cannot be combined"}, + {"codex", Profile{Backend: "codex", AuthMode: "native", Model: "m"}, "only to claude"}, + {"unknown mode", Profile{AuthMode: "oauth", Model: "sonnet"}, "unknown profile auth_mode"}, + } { + t.Run(tc.name, func(t *testing.T) { + c := Config{Default: "p", Profiles: map[string]Profile{"p": tc.profile}} + _, _, err := c.Resolve("") + if tc.want == "" { + if err != nil { + t.Fatal(err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err=%v, want %q", err, tc.want) + } + }) + } + // Legacy gateway profiles keep their requirement for a base URL. + c := Config{Default: "g", Profiles: map[string]Profile{"g": {Model: "m"}}} + if _, _, err := c.Resolve(""); err == nil || !strings.Contains(err.Error(), "needs base_url and model") { + t.Fatalf("gateway profile without base_url: %v", err) + } +} + +func TestNativeAuthIsClaudeOnlyAndExact(t *testing.T) { + for _, p := range []Profile{{AuthMode: "native", Model: "m"}, {Backend: "claude", AuthMode: "native", Model: "m"}} { + if !p.UsesNativeAuth() { + t.Fatalf("%+v should use native auth", p) + } + } + for _, p := range []Profile{{}, {Backend: "codex", AuthMode: "native"}, {AuthMode: "", BaseURL: "https://gw", Model: "m"}} { + if p.UsesNativeAuth() { + t.Fatalf("%+v must not use native auth", p) + } + } +} + +func TestSaveNativeProfile(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + path := Path() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + original := `{"default":"gw","future":{"keep":true},"profiles":{"gw":{"base_url":"https://gateway","model":"m","token":"secret"}}}` + if err := os.WriteFile(path, []byte(original), 0o600); err != nil { + t.Fatal(err) + } + if err := SaveProfile(path, "claude-sonnet", Profile{AuthMode: "native", Model: "sonnet", UseFor: "official"}, true); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + for _, want := range []string{`"auth_mode": "native"`, `"model": "sonnet"`, `"keep": true`, `"token": "secret"`} { + if !strings.Contains(string(b), want) { + t.Errorf("saved config lost %q:\n%s", want, b) + } + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + name, p, err := c.Resolve("claude-sonnet") + if err != nil || name != "claude-sonnet" || !p.UsesNativeAuth() || p.BaseURL != "" || p.Token != "" || p.TokenCmd != "" { + t.Fatalf("%q %+v %v", name, p, err) + } + if c.Default != "claude-sonnet" { + t.Fatalf("adding selects the new profile: %q", c.Default) + } + for name, bad := range map[string]Profile{ + "base url": {AuthMode: "native", Model: "sonnet", BaseURL: "https://gw"}, + "token": {AuthMode: "native", Model: "sonnet", Token: "t"}, + "no model": {AuthMode: "native"}, + "codex": {Backend: "codex", AuthMode: "native"}, + "bad value": {AuthMode: "oauth", Model: "sonnet"}, + } { + if err := SaveProfile(path, "bad-"+strings.ReplaceAll(name, " ", "-"), bad, true); err == nil { + t.Errorf("%s: saved an invalid native profile", name) + } + } + after, _ := os.ReadFile(path) + if strings.Contains(string(after), "bad-") { + t.Fatalf("a rejected profile reached the file:\n%s", after) + } +} + +func TestSaveGatewayProfileStillRequiresGatewaySettings(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + path := Path() + for name, p := range map[string]Profile{ + "no base": {Model: "m", Token: "t"}, + "no model": {BaseURL: "https://gw", Token: "t"}, + "no auth": {BaseURL: "https://gw", Model: "m"}, + } { + if err := SaveProfile(path, "g-"+strings.ReplaceAll(name, " ", "-"), p, true); err == nil { + t.Errorf("%s: gateway profile saved without its requirements", name) + } + } +} + +const callerCfg = `{"default":"gw","future":{"keep":true},"profiles":{` + + `"gw":{"base_url":"https://gw","model":"m","token":"t"},` + + `"sonnet":{"auth_mode":"native","model":"sonnet","aliases":["son"]},` + + `"cx":{"backend":"codex","aliases":["codex-alias"]}}}` + +func writeCallerCfg(t *testing.T, body string) string { + t.Helper() + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("OFFLOAD_PROFILE", "") + path := Path() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func TestSetCallerDefaultStoresCanonicalNamePreservesFieldsAndNormalizes(t *testing.T) { + path := writeCallerCfg(t, callerCfg) + if err := SetCallerDefault(path, "Claude", "son"); err != nil { + t.Fatal(err) + } + if err := SetCallerDefault(path, "codex", "codex-alias"); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + if !strings.Contains(string(b), `"keep": true`) { + t.Fatalf("unknown fields lost:\n%s", b) + } + var stored struct { + CallerDefaults map[string]string `json:"caller_defaults"` + } + if err := json.Unmarshal(b, &stored); err != nil { + t.Fatal(err) + } + if stored.CallerDefaults["claude"] != "sonnet" || stored.CallerDefaults["codex"] != "cx" { + t.Fatalf("an alias was stored instead of the canonical name: %v", stored.CallerDefaults) + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + if c.CallerDefaults["claude"] != "sonnet" || c.CallerDefaults["codex"] != "cx" || len(c.CallerDefaults) != 2 { + t.Fatalf("aliases must be saved as canonical names with lowercase callers: %+v", c.CallerDefaults) + } + if c.Default != "gw" { + t.Fatalf("a caller default must not change the global default: %q", c.Default) + } +} + +func TestSetCallerDefaultRejectsBadInputAndLeavesConfigUntouched(t *testing.T) { + path := writeCallerCfg(t, callerCfg) + before, _ := os.ReadFile(path) + for _, tc := range []struct{ caller, profile string }{ + {"claude", "missing"}, + {"claude", ""}, + {"", "gw"}, + {"has space", "gw"}, + {"unspecified", "gw"}, + {"UNSPECIFIED", "gw"}, + } { + if err := SetCallerDefault(path, tc.caller, tc.profile); err == nil { + t.Errorf("SetCallerDefault(%q, %q) succeeded", tc.caller, tc.profile) + } + } + if after, _ := os.ReadFile(path); string(after) != string(before) { + t.Fatalf("rejected input modified the config:\n%s", after) + } + // A disabled profile cannot become a caller default. + disabled := strings.Replace(callerCfg, `"cx":{"backend":"codex"`, `"cx":{"disabled":true,"backend":"codex"`, 1) + path = writeCallerCfg(t, disabled) + if err := SetCallerDefault(path, "codex", "cx"); err == nil || !strings.Contains(err.Error(), "disabled") { + t.Fatalf("disabled profile accepted: %v", err) + } +} + +func TestDefaultForOnlyMapsAnExplicitCaller(t *testing.T) { + path := writeCallerCfg(t, callerCfg) + if err := SetCallerDefault(path, "claude", "sonnet"); err != nil { + t.Fatal(err) + } + c, _ := Load(path) + for _, tc := range []struct { + caller string + want string + mapped bool + }{ + {"claude", "sonnet", true}, + {"codex", "gw", false}, // unknown caller: global default + {"", "gw", false}, + {"unspecified", "gw", false}, // the synthetic caller never matches + } { + got, mapped := c.DefaultFor(tc.caller) + if got != tc.want || mapped != tc.mapped { + t.Errorf("DefaultFor(%q) = %q,%v want %q,%v", tc.caller, got, mapped, tc.want, tc.mapped) + } + } + // A stored unspecified key is refused at load, so it can never be hand-edited into effect. + bad := strings.Replace(callerCfg, `"future"`, `"caller_defaults":{"unspecified":"gw"},"future"`, 1) + if _, err := Load(writeCallerCfg(t, bad)); err == nil || !strings.Contains(err.Error(), "caller_defaults") { + t.Fatalf("unspecified key accepted: %v", err) + } + for _, body := range []string{`"caller_defaults":{"Claude":"gw"}`, `"caller_defaults":{"claude":""}`} { + if _, err := Load(writeCallerCfg(t, strings.Replace(callerCfg, `"future"`, body+`,"future"`, 1))); err == nil { + t.Errorf("accepted %s", body) + } + } +} + +func TestCallerDefaultBlocksDisableAndDelete(t *testing.T) { + path := writeCallerCfg(t, callerCfg) + if err := SetCallerDefault(path, "claude", "son"); err != nil { + t.Fatal(err) + } + before, _ := os.ReadFile(path) + if err := SetProfileDisabled(path, "sonnet", true); err != ErrCallerDefaultInUse { + t.Fatalf("disable: %v", err) + } + if err := DeleteProfile(path, "sonnet"); err != ErrCallerDefaultInUse { + t.Fatalf("delete: %v", err) + } + if err := SaveProfile(path, "sonnet", Profile{AuthMode: "native", Model: "sonnet", Disabled: true}, false); err != ErrCallerDefaultInUse { + t.Fatalf("save disabled: %v", err) + } + if after, _ := os.ReadFile(path); string(after) != string(before) { + t.Fatalf("a refused change modified the config:\n%s", after) + } + // Enabling and editing stay allowed, and an unreferenced profile can still be disabled. + if err := SetProfileDisabled(path, "sonnet", false); err != nil { + t.Fatal(err) + } + if err := SetProfileDisabled(path, "cx", true); err != nil { + t.Fatal(err) + } + c, _ := Load(path) + if got := c.CallersUsing("sonnet"); len(got) != 1 || got[0] != "claude" { + t.Fatalf("CallersUsing: %v", got) + } +} diff --git a/internal/config/profile.go b/internal/config/profile.go index 265227b..bae9e2a 100644 --- a/internal/config/profile.go +++ b/internal/config/profile.go @@ -126,6 +126,13 @@ func SaveProfile(path, name string, p Profile, add bool) error { if p.Disabled && (add || name == defaultName) { return fmt.Errorf("set another default first") } + if p.Disabled && !add { + if used, err := callerDefaultsUse(fields, name); err != nil { + return err + } else if used { + return ErrCallerDefaultInUse + } + } raw, exists := profiles[name] if add && exists { return fmt.Errorf("profile already exists") @@ -157,7 +164,10 @@ func SaveProfile(path, name string, p Profile, add bool) error { if p.Endpoint != "" && p.BackendName() != "claude" { return fmt.Errorf("endpoint applies only to claude profiles") } - if p.BackendName() == "claude" { + if err := p.ValidateAuthMode(); err != nil { + return err + } + if p.BackendName() == "claude" && !p.UsesNativeAuth() { u, err := url.Parse(p.BaseURL) if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") { return fmt.Errorf("base URL must be http(s) with a host") @@ -186,7 +196,7 @@ func SaveProfile(path, name string, p Profile, add bool) error { if err := json.Unmarshal(encoded, &known); err != nil { return err } - for _, key := range []string{"disabled", "use_for", "codex_account", "aliases", "backend", "base_url", "model", "token", "token_cmd", "reasoning_effort", "service_tier", "idle_timeout", "endpoint"} { + for _, key := range []string{"disabled", "use_for", "codex_account", "aliases", "backend", "base_url", "model", "token", "token_cmd", "reasoning_effort", "service_tier", "idle_timeout", "endpoint", "auth_mode"} { delete(profile, key) } for key, value := range known { diff --git a/internal/config/profile_lifecycle.go b/internal/config/profile_lifecycle.go index 58eb28b..7d2a7b6 100644 --- a/internal/config/profile_lifecycle.go +++ b/internal/config/profile_lifecycle.go @@ -22,6 +22,13 @@ func SetProfileDisabled(path, name string, disabled bool) error { if disabled && name == def { return fmt.Errorf("set another default first") } + if disabled { + if used, err := callerDefaultsUse(fields, name); err != nil { + return err + } else if used { + return ErrCallerDefaultInUse + } + } var profiles map[string]json.RawMessage if err := json.Unmarshal(fields["profiles"], &profiles); err != nil { return err @@ -55,6 +62,11 @@ func DeleteProfile(path, name string) error { if name == def { return fmt.Errorf("set another default first") } + if used, err := callerDefaultsUse(fields, name); err != nil { + return err + } else if used { + return ErrCallerDefaultInUse + } var profiles map[string]json.RawMessage if err := json.Unmarshal(fields["profiles"], &profiles); err != nil { return err diff --git a/internal/worker/environment.go b/internal/worker/environment.go index 952c0b9..14a4976 100644 --- a/internal/worker/environment.go +++ b/internal/worker/environment.go @@ -127,6 +127,9 @@ func (o *Opts) prepareEnvironment(sourceHome string) (func() error, error) { if o.EnvironmentDirectory == "" { return func() error { return nil }, nil } + if o.Profile.UsesNativeAuth() { + return nil, errors.New("a native-auth Claude profile cannot be combined with an isolated environment: the environment replaces the home that holds the official login") + } root := o.EnvironmentDirectory if err := environmentDirectory(root); err != nil { return nil, err diff --git a/internal/worker/native_auth_test.go b/internal/worker/native_auth_test.go new file mode 100644 index 0000000..ba9fab4 --- /dev/null +++ b/internal/worker/native_auth_test.go @@ -0,0 +1,188 @@ +package worker + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/zhoushoujianwork/offload/internal/config" +) + +func nativeOpts(model string) Opts { + return Opts{ProfileName: "claude-sonnet", Model: model, Task: "do it", + Profile: config.Profile{AuthMode: config.AuthModeNative, Model: model}} +} + +func TestNativeClaudeArgsOmitBareAndPassModel(t *testing.T) { + for _, resume := range []string{"", "sess"} { + o := nativeOpts("sonnet") + o.Resume, o.AddDirs = resume, []string{"/a"} + args := buildArgs(o, "/p") + if slices.Contains(args, "--bare") { + t.Fatalf("--bare never reads the official login: %q", args) + } + want := []string{"-p", "--setting-sources", "", "--output-format", "stream-json", "--verbose", "--model", "sonnet"} + if resume != "" { + want = append(want, "--resume", resume) + } + want = append(want, "--add-dir", "/a", "--dangerously-skip-permissions", "--append-system-prompt-file", "/p", "do it") + if !slices.Equal(args, want) { + t.Fatalf("%q != %q", args, want) + } + } +} + +func TestNativeClaudeKeepsPermissionAndToolBehavior(t *testing.T) { + for name, tc := range map[string]struct { + mut func(*Opts) + want []string + not []string + }{ + "allowed tools": {func(o *Opts) { o.AllowedTools = "Read,Grep" }, []string{"--permission-mode", "default", "--allowedTools", "Read Grep"}, []string{"--dangerously-skip-permissions"}}, + "disallowed tools": {func(o *Opts) { o.DisallowedTools = "Bash" }, []string{"--disallowedTools", "Bash"}, []string{"--dangerously-skip-permissions"}}, + "tools disabled": {func(o *Opts) { o.ToolsDisabled = true }, []string{"--tools", ""}, []string{"--dangerously-skip-permissions"}}, + "managed": {func(o *Opts) { o.ExecutionPolicy = "managed-development" }, []string{"--permission-mode", "acceptEdits"}, []string{"--dangerously-skip-permissions", "do it"}}, + "salvage": {func(o *Opts) { o.Salvage = true }, []string{"--tools", "", "--dangerously-skip-permissions"}, nil}, + "default": {func(*Opts) {}, []string{"--dangerously-skip-permissions"}, []string{"--permission-mode"}}, + } { + t.Run(name, func(t *testing.T) { + o := nativeOpts("sonnet") + tc.mut(&o) + args := buildArgs(o, "/p") + gateway := o + gateway.Profile = config.Profile{BaseURL: "https://gw", Model: "sonnet", Token: "t"} + // Everything after the fixed prefix must match the gateway worker exactly. + if !slices.Equal(args[8:], buildArgs(gateway, "/p")[7:]) { + t.Fatalf("native permission/tool args differ from the gateway worker:\nnative %q\ngateway %q", args, buildArgs(gateway, "/p")) + } + j := strings.Join(args, "\x00") + for _, w := range tc.want { + if !strings.Contains(j, strings.Join(strings.Split(w, " "), "\x00")) && !slices.Contains(args, w) { + t.Errorf("missing %q in %q", w, args) + } + } + for _, n := range tc.not { + if slices.Contains(args, n) { + t.Errorf("unexpected %q in %q", n, args) + } + } + if slices.Contains(args, "--bare") { + t.Errorf("--bare present: %q", args) + } + }) + } +} + +func TestGatewayClaudeArgsKeepBareAndNoModelFlag(t *testing.T) { + args := buildArgs(Opts{Model: "m", Profile: config.Profile{BaseURL: "https://gw", Model: "m", Token: "t"}, Task: "do it"}, "/p") + if !slices.Contains(args, "--bare") || slices.Contains(args, "--model") { + t.Fatalf("gateway worker changed: %q", args) + } + // An unknown auth_mode value or a Codex profile never selects the native path. + for _, p := range []config.Profile{{AuthMode: "other", BaseURL: "https://gw"}, {Backend: "codex", AuthMode: "native"}} { + if p.UsesNativeAuth() { + t.Fatalf("%+v selected native auth", p) + } + } +} + +func envValue(env []string, name string) (string, bool) { + for _, kv := range env { + if k, v, ok := strings.Cut(kv, "="); ok && k == name { + return v, true + } + } + return "", false +} + +func TestNativeChildEnvStripsAmbientAnthropicAndSetsNone(t *testing.T) { + base := []string{"PATH=/bin", "HOME=/h", "ANTHROPIC_API_KEY=ambient-key", "ANTHROPIC_AUTH_TOKEN=ambient-token", + "ANTHROPIC_BASE_URL=https://other", "ANTHROPIC_MODEL=other", "ANTHROPIC_CUSTOM_HEADERS=X: 1", "ANTHROPIC_DEFAULT_SONNET_MODEL=x"} + env := childEnv(base, nativeOpts("sonnet"), "must-not-be-used") + for _, kv := range env { + if strings.HasPrefix(kv, "ANTHROPIC_") { + t.Errorf("native worker kept %q", kv) + } + if strings.Contains(kv, "must-not-be-used") || strings.Contains(kv, "ambient") { + t.Errorf("credential reached the native worker environment: %q", kv) + } + } + for _, keep := range []string{"PATH", "HOME"} { + if _, ok := envValue(env, keep); !ok { + t.Errorf("%s was dropped", keep) + } + } + if v, _ := envValue(env, "CLAUDE_CODE_DISABLE_AUTO_MEMORY"); v != "1" { + t.Errorf("auto-memory must stay disabled without --bare: %q", env) + } + // The gateway path is unchanged. + g := nativeOpts("m") + g.Profile = config.Profile{BaseURL: "https://gw", Model: "m", Token: "t"} + genv := childEnv(base, g, "tok") + for k, want := range map[string]string{"ANTHROPIC_BASE_URL": "https://gw", "ANTHROPIC_AUTH_TOKEN": "tok", "ANTHROPIC_MODEL": "m"} { + if v, _ := envValue(genv, k); v != want { + t.Errorf("gateway %s=%q want %q", k, v, want) + } + } + if _, ok := envValue(genv, "ANTHROPIC_API_KEY"); ok { + t.Error("gateway worker kept ambient ANTHROPIC_API_KEY") + } +} + +// fakeNativeClaude records argv and the credential-bearing environment, then reports a result. +func fakeNativeClaude(t *testing.T) (bin, record string) { + t.Helper() + dir := t.TempDir() + record = filepath.Join(dir, "record") + bin = filepath.Join(dir, "claude") + script := "#!/bin/sh\n{ printf 'ARG %s\\n' \"$@\"; env | grep -E '^(ANTHROPIC_|CLAUDE_CODE_DISABLE_AUTO_MEMORY)' | sort; echo END; } > '" + record + "'\n" + + `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"NATIVE REPORT","session_id":"s-native","num_turns":1}'` + "\n" + if err := os.WriteFile(bin, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + return bin, record +} + +func TestNativeRunSkipsTokenAndPreflightAndGatewayEnv(t *testing.T) { + t.Setenv("XDG_STATE_HOME", filepath.Join(t.TempDir(), "state")) + t.Setenv("OFFLOAD_MAX_WORKERS", "-1") + t.Setenv("ANTHROPIC_API_KEY", "ambient-key") + t.Setenv("ANTHROPIC_AUTH_TOKEN", "ambient-token") + t.Setenv("ANTHROPIC_BASE_URL", "https://ambient.example") + bin, record := fakeNativeClaude(t) + t.Setenv("OFFLOAD_CLAUDE", bin) + orig := Preflight + Preflight = func(string) error { t.Fatal("native profile must not preflight a gateway"); return nil } + t.Cleanup(func() { Preflight = orig }) + + o := nativeOpts("sonnet") + o.Dir, o.Timeout = t.TempDir(), 30*time.Second + // A token command would fail the run if it were resolved. + o.Profile.TokenCmd = "" + rec, err := Run(context.Background(), o) + if err != nil || rec.Status != "ok" || rec.Result != "NATIVE REPORT" || rec.Backend != "claude" { + t.Fatalf("rec=%+v err=%v", rec, err) + } + b, _ := os.ReadFile(record) + got := string(b) + for _, want := range []string{"ARG --model\nARG sonnet\n", "ARG --setting-sources\nARG \n", "ARG --dangerously-skip-permissions\n", "CLAUDE_CODE_DISABLE_AUTO_MEMORY=1"} { + if !strings.Contains(got, want) { + t.Errorf("missing %q in:\n%s", want, got) + } + } + if strings.Contains(got, "ARG --bare") || strings.Contains(got, "ANTHROPIC_") || strings.Contains(got, "ambient") { + t.Errorf("native worker saw a gateway variable or --bare:\n%s", got) + } +} + +func TestNativeAuthRejectsIsolatedEnvironment(t *testing.T) { + o := nativeOpts("sonnet") + o.EnvironmentDirectory = t.TempDir() + if _, err := o.prepareEnvironment(""); err == nil || !strings.Contains(err.Error(), "native-auth") { + t.Fatalf("an isolated environment would hide the official login: %v", err) + } +} diff --git a/internal/worker/native_controls.go b/internal/worker/native_controls.go index 3e9b189..1951bca 100644 --- a/internal/worker/native_controls.go +++ b/internal/worker/native_controls.go @@ -206,7 +206,10 @@ func hostClaudeArgs(o Opts, promptPath string) []string { args = append(args, "--tools", "", "--disable-slash-commands", "--no-chrome") } if n.RestrictedReadOnly { - args = append(args, "--bare", "--tools", "Read,Glob,Grep", "--disallowedTools", "Bash,Edit,Write,NotebookEdit,Agent,Task", "--disable-slash-commands", "--no-chrome") + if !o.Profile.UsesNativeAuth() { // --bare never reads the official login + args = append(args, "--bare") + } + args = append(args, "--tools", "Read,Glob,Grep", "--disallowedTools", "Bash,Edit,Write,NotebookEdit,Agent,Task", "--disable-slash-commands", "--no-chrome") } if n.SkillDirectory != "" { args = append(args, "--plugin-dir", n.SkillDirectory) diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 8a0dd57..5146075 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -140,7 +140,7 @@ var SalvageTimeout = 4 * time.Minute func buildArgs(o Opts, promptPath string) []string { if o.Native != nil { args := hostClaudeArgs(o, promptPath) - if o.EnvironmentDirectory != "" { + if o.EnvironmentDirectory != "" && !o.Profile.UsesNativeAuth() { args = append(args, "--bare") } return args @@ -149,6 +149,11 @@ func buildArgs(o Opts, promptPath string) []string { // --bare still loads settings; disable user/project/local sources so their env cannot // override the selected profile's gateway, credentials or model. args := []string{"-p", "--bare", "--setting-sources", "", "--output-format", "stream-json", "--verbose"} + if o.Profile.UsesNativeAuth() { + // --bare never reads OAuth or the keychain, so a native profile omits it. Settings sources stay + // disabled, and the model travels in argv because no ANTHROPIC_MODEL is set. + args = []string{"-p", "--setting-sources", "", "--output-format", "stream-json", "--verbose", "--model", o.Model} + } if o.Resume != "" { args = append(args, "--resume", o.Resume) } @@ -260,7 +265,8 @@ func writeWorkerPrompt(o Opts) (string, error) { // childEnv makes the profile the worker's only gateway: every caller ANTHROPIC_* variable is // dropped, then exactly base URL, token and model are set. buildArgs disables settings sources -// so user/project/local settings cannot override these. +// so user/project/local settings cannot override these. A native-auth profile drops the same +// variables but sets none, so the installed Claude Code uses its own official login. func childEnv(base []string, o Opts, token string) []string { env := make([]string, 0, len(base)+3) for _, kv := range base { @@ -280,6 +286,15 @@ func childEnv(base []string, o Opts, token string) []string { env = append(env, k+"="+v) } } + if o.Profile.UsesNativeAuth() { + // Without --bare the worker would otherwise write auto-memory into the user's Claude home. + for _, kv := range env { + if kv == "CLAUDE_CODE_DISABLE_AUTO_MEMORY=1" { + return env + } + } + return append(env, "CLAUDE_CODE_DISABLE_AUTO_MEMORY=1") + } return append(env, "ANTHROPIC_BASE_URL="+o.Profile.BaseURL, "ANTHROPIC_AUTH_TOKEN="+token, "ANTHROPIC_MODEL="+o.Model) } @@ -475,12 +490,14 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { return rec, fmt.Errorf("codex CLI not found: %w", err) } } else { - token, err = o.Profile.ResolveTokenContext(ctx) - if err != nil { - return rec, err - } - if o.Transcript != nil { - o.Transcript.AddSecrets(token, o.Profile.Token) + if !o.Profile.UsesNativeAuth() { + token, err = o.Profile.ResolveTokenContext(ctx) + if err != nil { + return rec, err + } + if o.Transcript != nil { + o.Transcript.AddSecrets(token, o.Profile.Token) + } } rec.ErrorKind = "launch" if o.Native != nil && o.Native.Executable != "" { @@ -491,8 +508,10 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { if err != nil { return rec, fmt.Errorf("claude CLI not found: %w", err) } - if err := Preflight(o.Profile.BaseURL); err != nil { - return rec, err + if !o.Profile.UsesNativeAuth() { + if err := Preflight(o.Profile.BaseURL); err != nil { + return rec, err + } } } rec.ErrorKind = "launch" diff --git a/macos/Sources/OffloadMonitor/ProfileModels.swift b/macos/Sources/OffloadMonitor/ProfileModels.swift index 79334ac..e6df4c8 100644 --- a/macos/Sources/OffloadMonitor/ProfileModels.swift +++ b/macos/Sources/OffloadMonitor/ProfileModels.swift @@ -136,11 +136,12 @@ enum ProfileDraftError: LocalizedError, Equatable { struct ProfileDraft: Equatable { enum Credential: String, CaseIterable, Identifiable { - case keep, none, token, tokenCmd + case keep, native, none, token, tokenCmd var id: String { rawValue } var label: String { switch self { case .keep: return "Keep saved" + case .native: return "Claude sign-in" case .none: return "None" case .token: return "API token" case .tokenCmd: return "Token command" @@ -149,6 +150,7 @@ struct ProfileDraft: Equatable { var authMode: String { switch self { case .keep: return "preserve" + case .native: return "native" case .none: return "none" case .token: return "token" case .tokenCmd: return "token_cmd" @@ -225,7 +227,7 @@ struct ProfileDraft: Equatable { reasoning = e.reasoningEffort tier = e.serviceTier codexAccount = e.codexAccount ?? "" - credential = e.authMode == "none" ? .token : .keep + credential = e.authMode == "native" ? .native : (e.authMode == "none" ? .token : .keep) } var baseURLHidden: Bool { original?.baseUrlRedacted == true } @@ -233,8 +235,9 @@ struct ProfileDraft: Equatable { /// The credential choices the backend accepts. A Claude profile needs a token or a token command. Keeping the /// saved credential is offered only when the profile has one (a profile switched from Codex has none). var credentialChoices: [Credential] { - guard let o = original, o.authMode != "none" else { return [.token, .tokenCmd] } - return [.keep, .token, .tokenCmd] + guard let o = original, o.authMode != "none" else { return [.native, .token, .tokenCmd] } + if o.authMode == "native" { return [.native, .token, .tokenCmd] } + return [.keep, .native, .token, .tokenCmd] } static func validName(_ n: String) -> Bool { @@ -284,16 +287,21 @@ struct ProfileDraft: Equatable { guard !model.isEmpty else { throw ProfileDraftError.modelRequired } if isNew || model != (o?.model ?? "") { r.model = model } - if baseURLHidden && !replaceBaseURL { - // Withheld by the CLI: keep the stored value, send nothing. - } else { - guard !url.isEmpty else { throw ProfileDraftError.urlRequired } - guard Self.validURL(url) else { throw ProfileDraftError.urlInvalid } - if isNew || replaceBaseURL || url != (o?.baseUrl ?? "") { r.baseUrl = url } + if credential != .native && credential != .none { + if baseURLHidden && !replaceBaseURL { + // Withheld by the CLI: keep the stored value, send nothing. + } else { + guard !url.isEmpty else { throw ProfileDraftError.urlRequired } + guard Self.validURL(url) else { throw ProfileDraftError.urlInvalid } + if isNew || replaceBaseURL || url != (o?.baseUrl ?? "") { r.baseUrl = url } + } + if isNew ? !endpoint.isEmpty : endpoint != (o?.endpoint ?? "") { r.endpoint = endpoint } } - if isNew ? !endpoint.isEmpty : endpoint != (o?.endpoint ?? "") { r.endpoint = endpoint } switch credential { + case .native: + if isNew || o?.authMode != "native" { r.authMode = "native" } + if let o, !o.endpoint.isEmpty { r.endpoint = "" } case .keep: guard !isNew, o?.authMode != "none" else { throw ProfileDraftError.secretRequired("API token or token command") } r.authMode = "preserve" diff --git a/macos/Sources/OffloadMonitor/SettingsView.swift b/macos/Sources/OffloadMonitor/SettingsView.swift index 8677947..531c376 100644 --- a/macos/Sources/OffloadMonitor/SettingsView.swift +++ b/macos/Sources/OffloadMonitor/SettingsView.swift @@ -288,7 +288,8 @@ struct ProfilesSettingsView: View { if draft.isCodex { codexRows } else { claudeRows } } Text(draft.isCodex ? "Codex uses its native sign-in." - : "Tokens are saved in your local offload config file, readable only by you. They are never shown again.") + : (draft.credential == .native ? "Claude uses the official Claude Code sign-in on this Mac." + : "Tokens are saved in your local offload config file, readable only by you. They are never shown again.")) .font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(2).fixedSize(horizontal: false, vertical: true) } } @@ -298,24 +299,26 @@ struct ProfilesSettingsView: View { label("Model") TextField("required", text: $draft.model).textFieldStyle(.roundedBorder) } - GridRow { - label("Gateway URL") - VStack(alignment: .leading, spacing: 4) { - if draft.baseURLHidden && !draft.replaceBaseURL { - Text("Saved (hidden: it contains private parts)").foregroundStyle(.secondary) - Toggle("Replace gateway URL", isOn: $draft.replaceBaseURL).controlSize(.small) - } else { - TextField("https://…", text: $draft.baseURL).textFieldStyle(.roundedBorder) - if draft.baseURLHidden { Toggle("Replace gateway URL", isOn: $draft.replaceBaseURL).controlSize(.small) } + if draft.credential != .native { + GridRow { + label("Gateway URL") + VStack(alignment: .leading, spacing: 4) { + if draft.baseURLHidden && !draft.replaceBaseURL { + Text("Saved (hidden: it contains private parts)").foregroundStyle(.secondary) + Toggle("Replace gateway URL", isOn: $draft.replaceBaseURL).controlSize(.small) + } else { + TextField("https://…", text: $draft.baseURL).textFieldStyle(.roundedBorder) + if draft.baseURLHidden { Toggle("Replace gateway URL", isOn: $draft.replaceBaseURL).controlSize(.small) } + } } } - } - GridRow { - label("Endpoint") - Picker("Endpoint", selection: $draft.endpoint) { - Text("none").tag(""); Text("cc").tag("cc"); Text("llm").tag("llm") + GridRow { + label("Endpoint") + Picker("Endpoint", selection: $draft.endpoint) { + Text("none").tag(""); Text("cc").tag("cc"); Text("llm").tag("llm") + } + .pickerStyle(.segmented).labelsHidden().frame(width: 200) } - .pickerStyle(.segmented).labelsHidden().frame(width: 200) } GridRow { label("Credential") @@ -524,6 +527,7 @@ struct ProfilesSettingsView: View { switch mode { case "token": return "API token saved" case "token_cmd": return "token command saved" + case "native": return "Claude sign-in" default: return "no credential" } } diff --git a/macos/Tests/OffloadMonitorTests/ControlTests.swift b/macos/Tests/OffloadMonitorTests/ControlTests.swift index 0223cc4..405c383 100644 --- a/macos/Tests/OffloadMonitorTests/ControlTests.swift +++ b/macos/Tests/OffloadMonitorTests/ControlTests.swift @@ -147,6 +147,15 @@ final class ProfileDraftTests: XCTestCase { XCTAssertNil(j["service_tier"], "Claude omits the new Codex Fast default") } + func testNewNativeClaudeSonnetProfileRequest() throws { + var d = ProfileDraft.new() + d.name = "claude-sonnet"; d.model = "sonnet"; d.credential = .native + let j = try json(d.request(existingNames: [])) + XCTAssertEqual(j["auth_mode"] as? String, "native") + XCTAssertEqual(j["model"] as? String, "sonnet") + XCTAssertNil(j["base_url"]); XCTAssertNil(j["secret"]); XCTAssertNil(j["endpoint"]) + } + func testNewProfileValidation() { var d = ProfileDraft.new() XCTAssertThrowsError(try d.request(existingNames: [])) { XCTAssertEqual($0 as? ProfileDraftError, .nameRequired) } @@ -280,9 +289,9 @@ final class ProfileDraftTests: XCTestCase { } func testCredentialChoicesForNewAndExisting() throws { - XCTAssertEqual(ProfileDraft.new().credentialChoices, [.token, .tokenCmd], "a new Claude profile cannot choose no credential") + XCTAssertEqual(ProfileDraft.new().credentialChoices, [.native, .token, .tokenCmd]) XCTAssertEqual(ProfileDraft.new().credential, .token) - XCTAssertEqual(ProfileDraft(editing: try entry()).credentialChoices, [.keep, .token, .tokenCmd]) + XCTAssertEqual(ProfileDraft(editing: try entry()).credentialChoices, [.keep, .native, .token, .tokenCmd]) XCTAssertEqual(ProfileDraft(editing: try entry()).credential, .keep) } @@ -299,7 +308,7 @@ final class ProfileDraftTests: XCTestCase { func testClaudeEditedFromCodexMustSupplyCredential() throws { let codex = try entry(backend: "codex", auth: "none") var d = ProfileDraft(editing: codex) - XCTAssertEqual(d.credentialChoices, [.token, .tokenCmd]) + XCTAssertEqual(d.credentialChoices, [.native, .token, .tokenCmd]) XCTAssertEqual(d.credential, .token) d.backend = "claude"; d.model = "m"; d.baseURL = "https://x.example" XCTAssertThrowsError(try d.request(existingNames: ["work"])) diff --git a/pkg/execution/execution.go b/pkg/execution/execution.go index a17feec..2c1dfbf 100644 --- a/pkg/execution/execution.go +++ b/pkg/execution/execution.go @@ -29,8 +29,13 @@ type Profile struct { Disabled bool Backend, BaseURL, Model, ReasoningEffort, ServiceTier string CodexAccount, IdleTimeout, Endpoint string - TokenCmd string `json:"-"` - Token string `json:"-"` + // AuthMode is empty for a gateway Claude profile (BaseURL plus Token or TokenCmd) or "native" for a + // Claude profile that uses the installed Claude Code's own official login. A native profile has no + // BaseURL, Token, TokenCmd or Endpoint and needs a Model. Empty is omitted from ProfileFingerprint, + // so existing gateway and Codex fingerprints are unchanged. + AuthMode string `json:",omitempty"` + TokenCmd string `json:"-"` + Token string `json:"-"` } // Limits sets shared admission and child build defaults, not OS containment. @@ -182,7 +187,7 @@ var activeRuns sync.Map func internalProfile(p Profile) config.Profile { return config.Profile{Disabled: p.Disabled, Backend: p.Backend, BaseURL: p.BaseURL, Model: p.Model, ReasoningEffort: p.ReasoningEffort, ServiceTier: p.ServiceTier, CodexAccount: p.CodexAccount, - IdleTimeout: p.IdleTimeout, Endpoint: p.Endpoint, TokenCmd: p.TokenCmd, Token: p.Token} + IdleTimeout: p.IdleTimeout, Endpoint: p.Endpoint, AuthMode: p.AuthMode, TokenCmd: p.TokenCmd, Token: p.Token} } // New validates explicit configuration; it starts no process and loads no @@ -216,7 +221,7 @@ func LoadConfig(path, name string) (Config, error) { } return Config{ProfileName: canonical, Profile: Profile{Disabled: p.Disabled, Backend: p.Backend, BaseURL: p.BaseURL, Model: p.Model, ReasoningEffort: p.ReasoningEffort, ServiceTier: p.ServiceTier, - CodexAccount: p.CodexAccount, IdleTimeout: p.IdleTimeout, Endpoint: p.Endpoint, TokenCmd: p.TokenCmd, Token: p.Token}, + CodexAccount: p.CodexAccount, IdleTimeout: p.IdleTimeout, Endpoint: p.Endpoint, AuthMode: p.AuthMode, TokenCmd: p.TokenCmd, Token: p.Token}, Limits: Limits{MaxWorkers: c.Limits.MaxWorkers, GoMaxProcs: c.Limits.GoMaxProcs, GoParallelism: c.Limits.GoParallelism}}, nil } diff --git a/pkg/execution/native_auth_test.go b/pkg/execution/native_auth_test.go new file mode 100644 index 0000000..46e67e2 --- /dev/null +++ b/pkg/execution/native_auth_test.go @@ -0,0 +1,129 @@ +package execution + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// Fingerprints of profiles that predate AuthMode. A new field must not change them, or every saved +// task that stores a fingerprint would refuse to resume after an upgrade. +const ( + legacyGatewayFingerprint = "fcfb909c380c62a1ef3e485b4591c6eba9c25176de69483dac602ecde3c25a0e" + legacyCodexFingerprint = "4504328f523fc5a739cb638c839b64f31bf92305596251e88031f07383d61357" +) + +func TestProfileFingerprintIsStableForExistingProfilesAndSeparatesNative(t *testing.T) { + gateway := Config{ProfileName: "p", Profile: Profile{Backend: "claude", BaseURL: "https://gw.example", Model: "m", Token: "tok"}} + codex := Config{ProfileName: "c", Profile: Profile{Backend: "codex", Model: "m2", ServiceTier: "priority"}} + if got := ProfileFingerprint(gateway); got != legacyGatewayFingerprint { + t.Fatalf("gateway fingerprint changed: %s", got) + } + if got := ProfileFingerprint(codex); got != legacyCodexFingerprint { + t.Fatalf("codex fingerprint changed: %s", got) + } + native := Config{ProfileName: "p", Profile: Profile{Backend: "claude", Model: "m", AuthMode: "native"}} + bare := Config{ProfileName: "p", Profile: Profile{Backend: "claude", Model: "m"}} + if ProfileFingerprint(native) == ProfileFingerprint(bare) { + t.Fatal("a native profile must not share a fingerprint with the same profile in gateway mode") + } +} + +func TestNewValidatesNativeProfile(t *testing.T) { + for _, tc := range []struct { + name string + profile Profile + want string + }{ + {"valid", Profile{Backend: "claude", Model: "sonnet", AuthMode: "native"}, ""}, + {"legacy backend", Profile{Model: "sonnet", AuthMode: "native"}, ""}, + {"no model", Profile{Backend: "claude", AuthMode: "native"}, "model is required"}, + {"base url", Profile{Backend: "claude", Model: "sonnet", AuthMode: "native", BaseURL: "https://gw"}, "cannot be combined"}, + {"token", Profile{Backend: "claude", Model: "sonnet", AuthMode: "native", Token: "t"}, "cannot be combined"}, + {"codex", Profile{Backend: "codex", Model: "m", AuthMode: "native"}, "only to claude"}, + {"unknown", Profile{Backend: "claude", Model: "m", BaseURL: "https://gw", Token: "t", AuthMode: "oauth"}, "unknown profile auth_mode"}, + {"gateway still needs base url", Profile{Backend: "claude", Model: "m", Token: "t"}, "needs base_url and model"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := New(Config{ProfileName: "p", Profile: tc.profile}) + if tc.want == "" { + if err != nil { + t.Fatal(err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err=%v, want %q", err, tc.want) + } + }) + } +} + +func TestLoadConfigAndListProfilesCarryNativeAuth(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + body := `{"default":"gw","profiles":{` + + `"gw":{"base_url":"https://gw.example","model":"m","token":"SECRET-TOKEN"},` + + `"claude-sonnet":{"auth_mode":"native","model":"sonnet","aliases":["son"]}}}` + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := LoadConfig(path, "son") + if err != nil { + t.Fatal(err) + } + if cfg.ProfileName != "claude-sonnet" || cfg.Profile.AuthMode != "native" || cfg.Profile.Model != "sonnet" || cfg.Profile.BaseURL != "" { + t.Fatalf("%+v", cfg) + } + if _, err := New(cfg); err != nil { + t.Fatal(err) + } + gw, err := LoadConfig(path, "gw") + if err != nil || gw.Profile.AuthMode != "" || ProfileFingerprint(gw) == ProfileFingerprint(cfg) { + t.Fatalf("%+v %v", gw, err) + } + infos, err := ListProfiles(path) + if err != nil { + t.Fatal(err) + } + modes := map[string]string{} + for _, i := range infos { + modes[i.Name] = i.AuthMode + } + if modes["claude-sonnet"] != "native" || modes["gw"] != "token" { + t.Fatalf("%v", modes) + } +} + +func TestNativeRunStartsWithoutGatewayAndStripsAmbientCredentials(t *testing.T) { + t.Setenv("OFFLOAD_MAX_WORKERS", "-1") + t.Setenv("ANTHROPIC_API_KEY", "ambient-key") + t.Setenv("ANTHROPIC_AUTH_TOKEN", "ambient-token") + t.Setenv("ANTHROPIC_BASE_URL", "http://127.0.0.1:1") // unreachable: a preflight would fail the run + t.Setenv("ANTHROPIC_MODEL", "ambient-model") + bin := filepath.Join(t.TempDir(), "claude") + if err := os.WriteFile(bin, []byte(envDumpClaude), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("OFFLOAD_CLAUDE", bin) + dump := filepath.Join(t.TempDir(), "env") + t.Setenv("ENV_DUMP", dump) + c, err := New(Config{ProfileName: "claude-sonnet", Profile: Profile{Backend: "claude", Model: "sonnet", AuthMode: "native"}}) + if err != nil { + t.Fatal(err) + } + timeout := time.Minute + res, err := c.Run(context.Background(), Request{Directory: t.TempDir(), Task: "t", Timeout: &timeout}) + if err != nil || res.Status != "ok" || res.Backend != "claude" { + t.Fatalf("%+v %v", res, err) + } + raw, err := os.ReadFile(dump) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "ANTHROPIC_") || strings.Contains(string(raw), "ambient") { + t.Fatalf("a native run reached a provider variable:\n%s", raw) + } +} diff --git a/pkg/execution/profiles.go b/pkg/execution/profiles.go index 4be8695..4ef6b5f 100644 --- a/pkg/execution/profiles.go +++ b/pkg/execution/profiles.go @@ -21,7 +21,7 @@ type ProfileInfo struct { // fragment; BaseURLRedacted then reports that a value was withheld. BaseURL string BaseURLRedacted bool - // AuthMode is "token", "token_cmd" or "none". + // AuthMode is "token", "token_cmd", "native" (the installed Claude Code's official login) or "none". AuthMode string // ToolRestrictions reports whether the backend enforces tool restrictions. ToolRestrictions bool @@ -96,6 +96,8 @@ func SetDefaultProfile(path, name string) error { func profileAuthMode(p config.Profile) string { switch { + case p.UsesNativeAuth(): + return "native" case p.TokenCmd != "": return "token_cmd" case p.Token != "": diff --git a/skills/offload/SKILL.md b/skills/offload/SKILL.md index d6f6c3a..198e405 100644 --- a/skills/offload/SKILL.md +++ b/skills/offload/SKILL.md @@ -15,7 +15,7 @@ The CLI supports `claude` (default) and `codex` profile backends. Set `"backend" Default-policy Codex workers use `--dangerously-bypass-approvals-and-sandbox` for both read-only and `-w` tasks (offload adds no sandbox; `-w` only tells the worker it may modify files), and stdin for instructions/tasks. `OFFLOAD_CODEX` overrides the executable. Claude gateway/token fields do not apply to Codex. Codex preserves run token usage and supports the limited API baseline estimate below; `turns` counts tool calls. Interrupted Codex runs preserve progress and a resume hint, without automatic tool-less salvage. -For Claude profiles, the CLI starts an external `claude -p --bare` worker on the configured Anthropic-compatible gateway, such as MiniMax. It does not replace a native Codex subagent's model provider. Profiles live in `~/.config/offload/config.json`; select with `-p`, `OFFLOAD_PROFILE`, or config `default`. `offload profiles` lists them (`offload profiles --json` gives a redacted machine-readable list; `offload profile save --json` creates or edits one profile from a JSON request on stdin). Each run drops the caller's `ANTHROPIC_*` variables and sets the chosen `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` (Bearer), and `ANTHROPIC_MODEL` (`-m` can override). It also passes `--setting-sources ""` so user/project/local settings cannot override the profile; `--bare` alone does not isolate settings. Auth is environment-only, without `apiKeyHelper` or `--settings`. +For Claude profiles, the CLI starts an external `claude -p --bare` worker on the configured Anthropic-compatible gateway, such as MiniMax. A Claude profile with `"auth_mode": "native"` instead runs `claude -p` without `--bare`, with `--model` and no `ANTHROPIC_BASE_URL`/`ANTHROPIC_AUTH_TOKEN`/`ANTHROPIC_MODEL`, using the installed Claude Code's official login; it still drops ambient `ANTHROPIC_*` variables and passes `--setting-sources ""`. Create one with `offload profile save --json` and `{"name":"claude-sonnet","create":true,"backend":"claude","model":"sonnet","auth_mode":"native"}`. It does not replace a native Codex subagent's model provider. Profiles live in `~/.config/offload/config.json`; select with `-p`, `OFFLOAD_PROFILE`, a caller default, or config `default`. `offload profiles` lists them (`offload profiles --json` gives a redacted machine-readable list; `offload profile save --json` creates or edits one profile from a JSON request on stdin). Gateway runs drop the caller's `ANTHROPIC_*` variables and set the chosen `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` (Bearer), and `ANTHROPIC_MODEL` (`-m` can override). They also pass `--setting-sources ""` so user/project/local settings cannot override the profile; `--bare` alone does not isolate settings. Gateway auth is environment-only, without `apiKeyHelper` or `--settings`. `offload agent status --json` and `offload agent enable|disable --agent codex|claude|all --json` manage this skill and the delegation policy block at user scope. Only offload-owned files and marker blocks change; modified, symlinked or unmanaged ones are reported as blocked. Status reflects files on disk, not proof that the current agent session loaded them: a session already running keeps its previously loaded copy, so start a new session after a change. @@ -31,7 +31,7 @@ Because the worker cannot see your conversation, its brief must stand alone: abs ## Use the active default profile first -For a new run, normally omit `-p`, `-m`, `-effort`, and `-fast`. A bare `offload "task"` inherits an explicit `OFFLOAD_PROFILE` first, then the configured default and that profile's model, reasoning effort, and service tier. +For a new run, normally omit `-p`, `-m`, `-effort`, and `-fast`. A bare `offload "task"` inherits an explicit `OFFLOAD_PROFILE` first, then the default mapped to an explicitly passed `--caller` (`offload default --caller claude `), then the configured default, and that profile's model, reasoning effort, and service tier. Pass `--caller claude` or `--caller codex` to name the main agent you run under so its own default applies; `--caller` is a routing convenience, not authentication or access control. Resumes and named threads keep their original profile. Use `offload profiles --json` to inspect the active selection or diagnose a failure, not to rotate among usable profiles. Its optional `use_for` field is descriptive metadata; it must not override a usable active default. Never randomly choose or proactively rotate profiles or accounts, and never silently change provider, model, effort, or tier. @@ -221,7 +221,8 @@ Report each external worker's status/exit code, profile/model, session, turns, e ## Follow-up and setup -- `offload profiles` — list gateway profiles without tokens; `-p name` overrides `OFFLOAD_PROFILE` and config `default`. +- `offload profiles` — list gateway profiles without tokens; `-p name` overrides `OFFLOAD_PROFILE`, the `--caller` default and config `default`. +- `offload default --caller ID [profile]` — show or set the profile new runs with `--caller ID` use. - `offload profile disable|enable|delete ` and `offload accounts remove ` — user-managed profile and account lifecycle; run them only when the user asks. - `offload ls [n]` — recent runs with estimated cost, compact token usage and elapsed time; missing costs show `N/A`, with details in `offload show `. - `offload stats [--json] [--period today|week|month|all]` — aggregate runs, unique sessions, per-run tokens and estimated costs, with coverage and project/model breakdowns. Cached input is a subset of input. `--json` also has a `trend` of hourly (today) or daily (week, month, last 30 days for all) points with the same coverage fields. Legacy Claude costs and salvaged accounting are excluded from totals; missing data is not zero. The macOS Offload Monitor app consumes this JSON and shows live workers alongside history.