Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ offload stats # usage and estimated costs

`-p` selects a profile for one task; `offload default <name>` changes the saved
default. `OFFLOAD_PROFILE` overrides that default. `offload default --caller <id>
<name>` sets a profile for runs that pass `--caller <id>`, a routing convenience and
not access control. Resumes retain their recorded profile and account. Costs are estimates when available, not billing records.
<name>` sets a profile for runs that pass `--caller <id>`, and `offload default
--caller <id> --clear` removes it. This is a routing convenience, not access control.
The macOS App sets the Codex and Claude callers in Settings > Profiles > Caller defaults.
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
Expand Down
5 changes: 4 additions & 1 deletion docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,12 @@ An external main agent can have its own default profile, so Claude Code and Code
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)
offload default --caller claude --clear # remove the mapping; the caller follows the global default again
```

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`.
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). `--clear` removes only that caller's entry, keeps every other config field, and succeeds without changing the file when the caller has no mapping. It also clears a mapping to a profile that was deleted by hand. Like showing, clearing prints the profile the caller now uses.

In the macOS App, **Settings > Profiles** has a **Caller defaults** section with one picker for Codex (`--caller codex`) and one for Claude (`--caller claude`). Each lists **Follow global default** (with the configured default named) and every enabled profile. Choosing one runs the commands above at once and refreshes the list; the pickers are disabled while another profile action runs. A saved mapping to a disabled or missing profile stays selected and is labelled "(disabled)" or "(not found)" instead of being replaced. The App edits only the Codex and Claude callers; use the CLI for other caller IDs. The routing rules below apply unchanged: the run must pass the caller ID, and `-p` or `OFFLOAD_PROFILE` still override the mapping.

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.

Expand Down
73 changes: 72 additions & 1 deletion internal/cli/caller_default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,77 @@ func TestDefaultCallerCommand(t *testing.T) {
}
}

func TestDefaultCallerClearCommand(t *testing.T) {
setup(t, okReply)
writeCallerDefaultsCfg(t, func(s string) string {
return strings.Replace(s, `"default":"glob"`, `"default":"glob","future":{"keep":true}`, 1)
})
for _, args := range [][]string{{"claude", "son"}, {"codex", "cx"}} {
if code, _, e := runCLI(append([]string{"default", "--caller"}, args...)...); code != 0 {
t.Fatal(e)
}
}
code, out, e := runCLI("default", "--caller", "Claude", "--clear")
if code != 0 || strings.TrimSpace(out) != "glob" {
t.Fatalf("clear prints the global default the caller now follows: %d %q %s", code, out, e)
}
if code, out, _ := runCLI("default", "--caller", "claude"); code != 0 || strings.TrimSpace(out) != "glob" {
t.Fatalf("show after clear: %d %q", code, out)
}
if code, out, _ := runCLI("default", "--caller", "codex"); code != 0 || strings.TrimSpace(out) != "cx" {
t.Fatalf("the other caller must keep its mapping: %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 || len(f.CallerDefaults) != 1 || f.CallerDefaults["codex"] != "cx" || !strings.Contains(string(f.Future), "keep") {
t.Fatalf("%v %s", err, raw)
}
// Clearing twice, or an unmapped caller, is a successful no-op that leaves the file alone.
before, _ := os.ReadFile(config.Path())
for _, caller := range []string{"claude", "never-set"} {
if code, out, e := runCLI("default", "--caller", caller, "--clear"); code != 0 || strings.TrimSpace(out) != "glob" {
t.Fatalf("clear %s: %d %q %s", caller, code, out, e)
}
}
if after, _ := os.ReadFile(config.Path()); string(after) != string(before) {
t.Fatal("a no-op clear modified the config")
}
// Invalid callers and extra arguments are refused without changing the config.
for _, args := range [][]string{{"unspecified", "--clear"}, {"bad caller", "--clear"}, {"codex", "--clear", "extra"}, {"--clear"}} {
if code, _, _ := runCLI(append([]string{"default", "--caller"}, args...)...); code != 2 {
t.Errorf("%q: code %d", args, code)
}
}
if after, _ := os.ReadFile(config.Path()); string(after) != string(before) {
t.Fatal("a rejected clear modified the config")
}
// A cleared caller routes new runs to the global default again.
work, _ := setup(t, okReply)
writeCallerDefaultsCfg(t, nil)
if code, _, e := runCLI("default", "--caller", "claude", "claude-sonnet"); code != 0 {
t.Fatal(e)
}
if code, _, e := runCLI("default", "--caller", "claude", "--clear"); code != 0 {
t.Fatal(e)
}
if code, _, e := runCLI("-d", work, "--caller", "claude", "task"); code != 0 {
t.Fatal(e)
}
if got := ranProfile(t); got != "glob" {
t.Fatalf("a cleared caller ran on %q, want the global default", got)
}
// Clearing releases the profile for disable.
if code, _, e := runCLI("profile", "disable", "claude-sonnet"); code != 0 {
t.Fatalf("disable after clear: %s", e)
}
}

func TestProfileLifecycleRefusesCallerDefaultTargets(t *testing.T) {
setup(t, okReply)
writeCallerDefaultsCfg(t, nil)
Expand Down Expand Up @@ -399,7 +470,7 @@ func TestProfilesJSONCallerDefaultsAreAdditiveAndGlobalFieldsStayGlobal(t *testi
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"} {
for _, want := range []string{"offload default --caller ID [profile|--clear]", "not authentication or access control", "--caller default"} {
if !strings.Contains(text, want) {
t.Errorf("help missing %q", want)
}
Expand Down
20 changes: 13 additions & 7 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ 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
offload default --caller ID [profile|--clear]
show, set or clear (--clear) 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)
Expand Down Expand Up @@ -831,7 +831,7 @@ func cmdProfiles(stdout, stderr io.Writer) int {
return 0
}

const defaultUsage = "usage: offload default [profile] | offload default --caller <caller> [profile]"
const defaultUsage = "usage: offload default [profile] | offload default --caller <caller> [profile|--clear]"

func cmdDefault(args []string, stdout, stderr io.Writer) int {
if len(args) > 0 && (args[0] == "--caller" || args[0] == "-caller") {
Expand All @@ -853,9 +853,10 @@ 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.
// cmdCallerDefault shows, sets or clears the default profile for one explicit --caller ID. Setting
// stores the canonical profile name, resolving an alias. Clearing (--clear) removes the mapping so
// the caller follows the global default. Showing, and the output after setting or clearing, is 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))
Expand All @@ -865,7 +866,12 @@ func cmdCallerDefault(args []string, stdout, stderr io.Writer) int {
return fail(stderr, err)
}
if len(args) == 2 {
if err := config.SetCallerDefault(config.Path(), caller, args[1]); err != nil {
if args[1] == "--clear" || args[1] == "-clear" {
err = config.ClearCallerDefault(config.Path(), caller)
} else {
err = config.SetCallerDefault(config.Path(), caller, args[1])
}
if err != nil {
return fail(stderr, err)
}
}
Expand Down
34 changes: 34 additions & 0 deletions internal/config/caller_defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,40 @@ func SetCallerDefault(path, caller, name string) error {
return writeSettings(path, fields)
}

// ClearCallerDefault removes the saved default profile for one caller, so its runs follow the
// global default again. Clearing a caller that has no mapping succeeds without touching the file.
// The mapped profile need not exist, so a mapping to a hand-deleted profile can be cleared. Other
// fields, including unknown JSON, are preserved; the caller_defaults key is dropped when it
// becomes empty.
func ClearCallerDefault(path, caller string) error {
key, err := NormalizeCallerDefaultKey(caller)
if err != nil {
return err
}
fields, err := modeSettings(path)
if err != nil {
return err
}
raw, ok := fields["caller_defaults"]
if !ok {
return nil
}
var defaults map[string]string
if err := json.Unmarshal(raw, &defaults); err != nil || defaults == nil {
return errors.New("caller_defaults must be a JSON object of profile names")
}
if _, mapped := defaults[key]; !mapped {
return nil
}
delete(defaults, key)
if len(defaults) == 0 {
delete(fields, "caller_defaults")
} else 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) {
Expand Down
78 changes: 78 additions & 0 deletions internal/config/native_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,84 @@ func TestSetCallerDefaultRejectsBadInputAndLeavesConfigUntouched(t *testing.T) {
}
}

func TestClearCallerDefaultRemovesOneMappingAndPreservesFields(t *testing.T) {
path := writeCallerCfg(t, callerCfg)
for caller, profile := range map[string]string{"claude": "sonnet", "codex": "cx"} {
if err := SetCallerDefault(path, caller, profile); err != nil {
t.Fatal(err)
}
}
if err := ClearCallerDefault(path, "Claude"); err != nil {
t.Fatal(err)
}
c, err := Load(path)
if err != nil {
t.Fatal(err)
}
if _, ok := c.CallerDefaults["claude"]; ok || c.CallerDefaults["codex"] != "cx" || len(c.CallerDefaults) != 1 {
t.Fatalf("only the claude mapping may go: %v", c.CallerDefaults)
}
if name, mapped := c.DefaultFor("claude"); name != "gw" || mapped {
t.Fatalf("a cleared caller must follow the global default: %q %v", name, mapped)
}
if b, _ := os.ReadFile(path); !strings.Contains(string(b), `"keep": true`) || c.Default != "gw" {
t.Fatalf("unknown fields or the global default changed:\n%s", b)
}
// Clearing the last mapping drops the key; the profile is released for disable and delete.
if err := ClearCallerDefault(path, "codex"); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(path); strings.Contains(string(b), "caller_defaults") || !strings.Contains(string(b), `"keep": true`) {
t.Fatalf("an empty caller_defaults must be removed:\n%s", b)
}
if err := SetProfileDisabled(path, "cx", true); err != nil {
t.Fatalf("a cleared caller default must not block disable: %v", err)
}
}

func TestClearCallerDefaultIsIdempotentAndValidatesInput(t *testing.T) {
path := writeCallerCfg(t, callerCfg)
before, _ := os.ReadFile(path)
if err := ClearCallerDefault(path, "claude"); err != nil {
t.Fatalf("clearing a caller with no caller_defaults key must succeed: %v", err)
}
if after, _ := os.ReadFile(path); string(after) != string(before) {
t.Fatal("a no-op clear rewrote the config")
}
if err := SetCallerDefault(path, "codex", "cx"); err != nil {
t.Fatal(err)
}
mapped, _ := os.ReadFile(path)
if err := ClearCallerDefault(path, "claude"); err != nil {
t.Fatal(err)
}
if after, _ := os.ReadFile(path); string(after) != string(mapped) {
t.Fatal("clearing an unmapped caller rewrote the config")
}
for _, caller := range []string{"", "has space", "unspecified"} {
if err := ClearCallerDefault(path, caller); err == nil {
t.Errorf("ClearCallerDefault(%q) succeeded", caller)
}
}
bad := strings.Replace(callerCfg, `"future"`, `"caller_defaults":["x"],"future"`, 1)
badPath := writeCallerCfg(t, bad)
if err := ClearCallerDefault(badPath, "claude"); err == nil || !strings.Contains(err.Error(), "JSON object") {
t.Fatalf("a malformed caller_defaults must be refused: %v", err)
}
}

func TestClearCallerDefaultWorksForMissingOrDisabledTargets(t *testing.T) {
gone := strings.Replace(callerCfg, `"future"`, `"caller_defaults":{"claude":"gone","codex":"cx"},"future"`, 1)
path := writeCallerCfg(t, gone)
if err := ClearCallerDefault(path, "claude"); err != nil {
t.Fatalf("a mapping to a missing profile must be clearable: %v", err)
}
c, err := Load(path)
if err != nil || len(c.CallerDefaults) != 1 || c.CallerDefaults["codex"] != "cx" {
t.Fatalf("%v %v", err, c.CallerDefaults)
}
}

func TestDefaultForOnlyMapsAnExplicitCaller(t *testing.T) {
path := writeCallerCfg(t, callerCfg)
if err := SetCallerDefault(path, "claude", "sonnet"); err != nil {
Expand Down
15 changes: 15 additions & 0 deletions macos/Sources/OffloadMonitor/CLIServices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,21 @@ struct OffloadCLI {
_ = try await run(["default", name])
}

/// Arguments for `offload default --caller <id> <profile>` (set) or `... --clear` (follow the global default).
static func callerDefaultArguments(_ caller: CallerDefaultCaller, profile: String?) -> [String]? {
guard let profile else { return ["default", "--caller", caller.rawValue, "--clear"] }
guard validArgumentName(profile) else { return nil }
return ["default", "--caller", caller.rawValue, profile]
}

/// Sets (or, with a nil profile, clears) the default profile of one caller. The global default is untouched.
func setCallerDefault(_ caller: CallerDefaultCaller, profile: String?) async throws {
guard let args = Self.callerDefaultArguments(caller, profile: profile) else {
throw CLIError.invalidArgument("That profile name cannot be selected from here.")
}
_ = try await run(args)
}

struct ProfileTestResult {
var snapshot: ProfilesSnapshot
var succeeded: Bool
Expand Down
16 changes: 16 additions & 0 deletions macos/Sources/OffloadMonitor/ControlModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,22 @@ final class ProfilesModel: ObservableObject {
return true
}

/// Sets (nil profile: clears) the default profile of one caller, then re-reads. Serialized with every other
/// action through `busy`. A failed command changes nothing, shows its message and re-reads nothing.
@discardableResult
func setCallerDefault(_ caller: CallerDefaultCaller, profile: String?) async -> Bool {
guard let cli, !busy else { return false }
busy = true
defer { busy = false }
actionError = nil
do { try await cli.setCallerDefault(caller, profile: profile) } catch {
actionError = message(error)
return false
}
if !(await fetch(cli)) { actionError = "Saved, but the profile list could not be refreshed." }
return true
}

/// Creates or patches a profile. The reply is the refreshed redacted list.
@discardableResult
func save(_ request: ProfileSaveRequest) async -> Bool {
Expand Down
Loading
Loading