diff --git a/README.md b/README.md index 037b6f9..bc423ac 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,8 @@ final report comes back. The main agent keeps design decisions and final review. - **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"`). +- **Local backends:** Codex CLI, Claude Code (Anthropic-compatible gateway or native login), + and Antigravity CLI over ACP. - **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. @@ -19,8 +19,7 @@ final report comes back. The main agent keeps design decisions and final review. ## Quick start -Requires Go 1.24+ and a signed-in `codex`, or `claude` configured with a supported -gateway. Both backend CLIs run locally. +Requires Go 1.24+ and at least one configured local backend CLI. ```sh go install github.com/zhoushoujianwork/offload@latest @@ -40,6 +39,25 @@ JSON Creating a profile selects it as the default. New features may require building from the current source with `go install .`. +### Antigravity CLI + +Install `agy` on your PATH and sign in once with `agy acp --login` or an interactive +`agy` session. Offload uses the existing Antigravity credentials. +[Antigravity ACP setup](https://antigravity.google/docs/cli/acp/) + +```sh +offload profile save --json <<'JSON' +{"name":"agy","create":true,"backend":"agy"} +JSON +offload -p agy "Inspect this project and summarize its entry points." +offload -r "Continue the previous review." +``` + +Leave the model and reasoning effort empty to use Antigravity's defaults. Tool +permissions follow Antigravity's settings, and Offload denies requests that would +need interactive approval. This backend uses the default execution policy and does +not enforce Offload tool lists or report per-run token usage or cost. + ## Everyday commands ```sh diff --git a/docs/guide.md b/docs/guide.md index d9e91e7..18665d4 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -7,7 +7,7 @@ Run shell examples from the repository root. ## Install -Requires Go 1.24+ and the CLI for your selected backend: [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (`claude` on PATH or at `~/.claude/local/claude`) or [Codex](https://developers.openai.com/codex/cli/) (`codex` on PATH, already signed in). +Requires Go 1.24+ and the CLI for your selected backend. Use [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (`claude` on PATH or at `~/.claude/local/claude`), [Codex](https://developers.openai.com/codex/cli/) (`codex` on PATH, already signed in), or [Antigravity CLI](https://antigravity.google/docs/cli/acp/) (`agy` on PATH, already signed in). ```bash go install github.com/zhoushoujianwork/offload@latest @@ -53,7 +53,7 @@ Run `offload config`, select **Profile**, then **Add profile** to save a bundle `token_cmd` (preferred) prints the token on stdout, so secrets can live in the macOS Keychain, `pass`, 1Password CLI, etc. A literal `token` field also works. -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. +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. ### Official Claude (native login) @@ -70,7 +70,7 @@ For a native run, offload still drops every caller `ANTHROPIC_*` variable and ke ### 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: +Supported values for `backend` are `claude` (the default for existing profiles), `codex`, and `agy`. For each Claude gateway run, offload drops every `ANTHROPIC_*` variable from the caller's environment and sets the following values. | profile field | worker env | |---|---| @@ -88,6 +88,10 @@ By default, Codex runs with `--dangerously-bypass-approvals-and-sandbox` for bot Interrupted Codex runs retain progress and a resume command. Automatic tool-less salvage is supported only for Claude. +### Antigravity workers + +An `agy` profile launches `agy acp` with the working directory and any `--add-dir` paths. An optional `model` or `-m` selects a model ID offered by Antigravity. An optional `reasoning_effort` or `-effort` selects a thinking level available for that model. Follow-up runs use `offload -r `. See the [Antigravity CLI quick start](../README.md#antigravity-cli) for profile setup and permissions. + ### Choosing a profile 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. diff --git a/internal/cli/agy_test.go b/internal/cli/agy_test.go new file mode 100644 index 0000000..e2120ea --- /dev/null +++ b/internal/cli/agy_test.go @@ -0,0 +1,107 @@ +package cli + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/zhoushoujianwork/offload/internal/history" + "github.com/zhoushoujianwork/offload/internal/transcript" +) + +func TestAgyACPProfileRunAndResume(t *testing.T) { + work, _ := setup(t, okReply) + dir := t.TempDir() + agy := filepath.Join(dir, "agy") + const script = `#!/bin/sh +set -eu +[ "$1" = acp ] && [ "$2" = --add-dir ] && [ "$3" = "$AGY_TEST_MOUNT" ] || exit 10 +read_frame() { IFS= read -r frame; } +read_frame +case "$frame" in *'"method":"initialize"'*'"protocolVersion":1'*) ;; *) exit 11 ;; esac +echo '{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"sessionCapabilities":{"resume":{}}}}}' +read_frame +case "$frame" in + *'"method":"session/new"'*) report="new" ;; + *'"method":"session/resume"'*'"sessionId":"agy-session"'*) report="resumed" ;; + *) exit 12 ;; +esac +echo '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"agy-session","configOptions":[{"id":"model","currentValue":"default-model"}]}}' +read_frame +case "$frame" in *'"method":"session/set_config_option"'*'"configId":"model"'*'"value":"chosen-model"'*) ;; *) exit 13 ;; esac +echo '{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"id":"model","currentValue":"chosen-model"}]}}' +read_frame +case "$frame" in *'"method":"session/set_config_option"'*'"configId":"thought_level"'*'"value":"low"'*) ;; *) exit 14 ;; esac +echo '{"jsonrpc":"2.0","id":4,"result":{"configOptions":[{"id":"model","currentValue":"chosen-model"}]}}' +read_frame +case "$frame" in *'"method":"session/prompt"'*'"type":"text"'*'"sessionId":"agy-session"'*) ;; *) exit 15 ;; esac +if [ "${AGY_TEST_HANG:-}" = 1 ]; then exec sleep 60; fi +echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"agy-session","update":{"sessionUpdate":"tool_call","toolCallId":"tool","title":"Test","kind":"execute"}}}' +echo '{"jsonrpc":"2.0","id":"permission","method":"session/request_permission","params":{"sessionId":"agy-session","options":[{"kind":"allow_once","optionId":"allow"},{"kind":"reject_once","optionId":"deny"}]}}' +read_frame +case "$frame" in *'"id":"permission"'*'"optionId":"deny"'*'"outcome":"selected"'*) ;; *) exit 16 ;; esac +echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"agy-session","update":{"sessionUpdate":"tool_call_update","toolCallId":"tool","status":"failed"}}}' +echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"foreign","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ignored"}}}}' +printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"agy-session","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"%s "}}}}\n' "$report" +echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"agy-session","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"report"}}}}' +echo '{"jsonrpc":"2.0","id":5,"result":{"stopReason":"end_turn"}}' +# Some servers exit immediately instead of waiting for the client to close stdin. +` + if err := os.WriteFile(agy, []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + mount := t.TempDir() + t.Setenv("AGY_TEST_MOUNT", mount) + input := strings.NewReader(`{"name":"agy","create":true,"backend":"agy","model":"chosen-model","reasoning_effort":"low"}`) + var output, stderr strings.Builder + if code := cmdProfile([]string{"save", "--json"}, input, &output, &stderr); code != 0 { + t.Fatal(stderr.String()) + } + if code, out, err := runCLI("-p", "agy", "-d", work, "--add-dir", mount, "first task"); code != 0 || !strings.Contains(out, "new report") { + t.Fatalf("fresh code=%d stdout=%q stderr=%q", code, out, err) + } + if code, out, err := runCLI("-r", "agy-session", "next task"); code != 0 || !strings.Contains(out, "resumed report") { + t.Fatalf("resume code=%d stdout=%q stderr=%q", code, out, err) + } + records, err := history.Read(history.Path()) + if err != nil || len(records) != 2 { + t.Fatalf("history: %v %v", records, err) + } + for _, record := range records { + if record.Backend != "agy" || record.NativeProtocol != "acp" || record.ObservedModel != "chosen-model" || + record.Session != "agy-session" || record.Turns != 1 || record.Denials != 1 || + record.Usage != nil || record.CostUSD != nil || record.UsageUnavailable == "" || record.CostUnavailable == "" { + t.Fatalf("unexpected ACP history: %+v", record) + } + capture := transcript.Read(transcript.ReadOptions{RunID: record.RunID}) + found := false + for _, raw := range capture.Events { + var event transcript.Event + if err := json.Unmarshal(raw, &event); err != nil { + t.Fatal(err) + } + if event.Type == transcript.TypeMessage && event.Role == "assistant" && event.Text == record.Result { + found = true + } + } + if capture.Availability != transcript.Available || !found { + t.Fatalf("missing ACP report in transcript: %+v", capture) + } + } + + t.Setenv("AGY_TEST_HANG", "1") + if code, _, err := runCLI("-r", "agy-session", "-t", "2s", "time out"); code != 124 { + t.Fatalf("timeout code=%d stderr=%q", code, err) + } + records, err = history.Read(history.Path()) + if err != nil || len(records) != 3 { + t.Fatalf("history after timeout: %v %v", records, err) + } + last := records[2] + if last.Status != "timeout" || last.Session != "agy-session" || last.Cleanup != "" { + t.Fatalf("ACP timeout lost its session or left an owned process: %+v", last) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index e46023e..52848be 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -823,7 +823,7 @@ func cmdProfiles(stdout, stderr io.Writer) int { aliases += " — " + p.UseFor } gateway := p.BaseURL - if p.UsesNativeAuth() { + if p.UsesNativeAuth() || p.BackendName() == "agy" { 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) diff --git a/internal/cli/profiles.go b/internal/cli/profiles.go index ca9fbfa..7fb1c7c 100644 --- a/internal/cli/profiles.go +++ b/internal/cli/profiles.go @@ -77,7 +77,7 @@ func safeBaseURL(raw string) (string, bool) { func authMode(p config.Profile) string { switch { - case p.UsesNativeAuth(): + case p.UsesNativeAuth() || p.BackendName() == "agy": return "native" case p.TokenCmd != "": return "token_cmd" @@ -230,6 +230,9 @@ var safeSaveErrors = map[string]bool{ "unknown backend": true, "invalid Codex reasoning effort": true, "invalid Codex service tier": true, + "invalid agy reasoning effort": true, + "agy uses native credentials and cannot use Offload gateway settings": true, + "agy cannot use Codex account or service tier settings": true, "endpoint applies only to claude profiles": true, "base URL must be http(s) with a host": true, "model is required": true, @@ -266,6 +269,10 @@ func applyProfileRequest(p config.Profile, req profileSaveRequest) (config.Profi p.Backend = "claude" } if req.Backend != nil { + if p.BackendName() != "agy" && *req.Backend == "agy" { + p.BaseURL, p.Endpoint, p.AuthMode, p.Token, p.TokenCmd = "", "", "", "", "" + p.ServiceTier, p.ReasoningEffort = "", "" + } p.Backend = *req.Backend } if req.BaseURL != nil { @@ -318,6 +325,9 @@ func applyProfileRequest(p config.Profile, req profileSaveRequest) (config.Profi if req.Secret != nil { return p, errors.New("secret is only allowed with token or token_cmd") } + if p.BackendName() == "agy" { + break // Native credentials are inherent to the agy backend. + } if p.BackendName() != "claude" { return p, errors.New("auth_mode applies only to claude profiles") } diff --git a/internal/cli/settings.go b/internal/cli/settings.go index 688ea02..552aa65 100644 --- a/internal/cli/settings.go +++ b/internal/cli/settings.go @@ -338,11 +338,11 @@ func settingsWizard(p settingsPrompt, cfg *config.Config, name string, add bool) if _, exists := cfg.Profiles[name]; exists { return errors.New("profile already exists") } - index, err := settingsChoice(p, "Backend", []string{"Codex", "Claude gateway"}, 0) + index, err := settingsChoice(p, "Backend", []string{"Codex", "Claude gateway", "Antigravity (agy)"}, 0) if err != nil { return err } - profile.Backend = []string{"codex", "claude"}[index] + profile.Backend = []string{"codex", "claude", "agy"}[index] } if profile.BackendName() == "codex" { profile.Model, err = p.Ask("Model (empty inherits Codex default)", profile.Model) @@ -372,6 +372,11 @@ func settingsWizard(p settingsPrompt, cfg *config.Config, name string, add bool) if err != nil { return err } + } else if profile.BackendName() == "agy" { + profile.Model, err = p.Ask("Model (empty inherits Antigravity default)", profile.Model) + 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) diff --git a/internal/config/config.go b/internal/config/config.go index 7cfc180..41248f0 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -21,7 +21,7 @@ type Profile struct { CodexAccount string `json:"codex_account,omitempty"` Aliases []string `json:"aliases,omitempty"` IdleTimeout string `json:"idle_timeout,omitempty"` - Backend string `json:"backend,omitempty"` // claude (default) or codex + Backend string `json:"backend,omitempty"` // claude (default), codex, or agy BaseURL string `json:"base_url"` Model string `json:"model"` ReasoningEffort string `json:"reasoning_effort,omitempty"` @@ -145,9 +145,12 @@ func (c *Config) resolveNamed(name string) (string, Profile, error) { } name = match } - if p.BackendName() != "claude" && p.BackendName() != "codex" { + if !p.ValidBackend() { return name, p, fmt.Errorf("profile %q has unknown backend %q", name, p.Backend) } + if err := p.ValidateAgySettings(); err != nil { + return name, p, err + } if err := p.ValidateAuthMode(); err != nil { return name, p, fmt.Errorf("profile %q: %w", name, err) } @@ -167,9 +170,9 @@ func (c *Config) resolveNamed(name string) (string, Profile, error) { } // SupportsToolRestrictions reports whether the backend can enforce explicit tool allow or deny -// lists. Claude forwards them to the CLI; Codex has no equivalent control. +// lists. Claude forwards them to the CLI. func (p Profile) SupportsToolRestrictions() bool { - return p.BackendName() != "codex" + return p.BackendName() == "claude" } // AuthModeNative marks a Claude profile that uses the installed Claude Code's official login. @@ -210,6 +213,15 @@ func (p Profile) BackendName() string { return p.Backend } +func (p Profile) ValidBackend() bool { + switch p.BackendName() { + case "claude", "codex", "agy": + return true + default: + return false + } +} + // SetDefault updates only the default field, preserving other configuration fields. func SetDefault(path, name string) error { c, err := Load(path) diff --git a/internal/config/profile.go b/internal/config/profile.go index bae9e2a..d664670 100644 --- a/internal/config/profile.go +++ b/internal/config/profile.go @@ -99,6 +99,24 @@ func (p Profile) ValidateClaudeSettings() error { } } +func (p Profile) ValidateAgySettings() error { + if p.BackendName() != "agy" { + return nil + } + if p.BaseURL != "" || p.Token != "" || p.TokenCmd != "" || p.Endpoint != "" || p.AuthMode != "" { + return fmt.Errorf("agy uses native credentials and cannot use Offload gateway settings") + } + if p.CodexAccount != "" || p.ServiceTier != "" { + return fmt.Errorf("agy cannot use Codex account or service tier settings") + } + switch p.ReasoningEffort { + case "", "low", "medium", "high", "xhigh", "max": + return nil + default: + return fmt.Errorf("invalid agy reasoning effort") + } +} + // SaveProfile saves a complete bundle, preserving unknown JSON and unrelated profiles. // Adding selects the new profile; editing preserves the saved default. func SaveProfile(path, name string, p Profile, add bool) error { @@ -140,9 +158,12 @@ func SaveProfile(path, name string, p Profile, add bool) error { if !add && !exists { return fmt.Errorf("unknown profile") } - if p.BackendName() != "codex" && p.BackendName() != "claude" { + if !p.ValidBackend() { return fmt.Errorf("unknown backend") } + if err := p.ValidateAgySettings(); err != nil { + return err + } if err := p.ValidateCodexSettings(); err != nil { return err } diff --git a/internal/nativeusage/native.go b/internal/nativeusage/native.go index 59411e9..a279ca1 100644 --- a/internal/nativeusage/native.go +++ b/internal/nativeusage/native.go @@ -149,6 +149,9 @@ func SamePromptOverlap(a, b history.Record) bool { // It refuses to replace a conflicting measured value. Interrupted native records // are retained as a lower bound (partial_run), never promoted to full-run totals. func (rd *Reader) Recover(r history.Record) (history.Record, bool, string) { + if r.Backend == "agy" { + return r, false, "Antigravity ACP has no native log accounting adapter" + } if !Needed(r) { return r, false, "already covered" } diff --git a/internal/transcript/backend.go b/internal/transcript/backend.go index 0bfa916..38eb563 100644 --- a/internal/transcript/backend.go +++ b/internal/transcript/backend.go @@ -33,6 +33,10 @@ func (r *Recorder) Line(line []byte) { r.gapLocked("unparseable_backend_line", len(line)) return } + if r.id.Backend == "agy" { + r.acpLine(head.Method, line) + return + } // codex app-server speaks JSON-RPC: notifications carry "method", responses carry "id". if head.Type == "" && r.id.Backend == "codex" && (head.Method != "" || len(head.ID) > 0) { r.appServerLine(head.Method, line) @@ -56,6 +60,92 @@ func (r *Recorder) Line(line []byte) { } } +func (r *Recorder) flushACPText() { + if body := r.acpText.String(); strings.TrimSpace(body) != "" { + r.emitLocked(Event{Type: TypeMessage, Role: "assistant", Origin: "backend", Text: body}, false) + } + r.acpText.Reset() +} + +func (r *Recorder) acpLine(method string, line []byte) { + var event struct { + Params struct { + SessionID string + Update struct { + SessionUpdate, ToolCallID, Title, Kind, Status string + Content json.RawMessage + } + } + Result struct{ SessionID, StopReason string } + Error *struct{ Message string } + } + if json.Unmarshal(line, &event) != nil { + r.gapLocked("undecodable_backend_event", len(line)) + return + } + switch method { + case "": + r.setSession(event.Result.SessionID) + if event.Result.StopReason != "" || event.Error != nil { + r.flushACPText() + } + if event.Error != nil { + r.emitLocked(Event{Type: TypeBackendError, Text: event.Error.Message}, false) + } + return + case "session/update": + if !validSession(event.Params.SessionID) || r.session != "" && r.session != event.Params.SessionID { + return + } + r.setSession(event.Params.SessionID) + default: + return + } + u := event.Params.Update + switch u.SessionUpdate { + case "agent_message_chunk": + var content struct{ Type, Text string } + if json.Unmarshal(u.Content, &content) != nil || content.Type != "text" { + r.sum.SkippedBlocks++ + return + } + if r.acpText.Len()+len(content.Text) > MaxLineBytes { + r.flushACPText() + } + if len(content.Text) > MaxLineBytes { + r.gapLocked("acp_text_chunk_too_large", len(content.Text)) + return + } + r.acpText.WriteString(content.Text) + case "agent_thought_chunk", "plan": + r.sum.SkippedBlocks++ + case "tool_call": + r.flushACPText() + r.toolCallLocked(u.ToolCallID, u.Title, acpToolCategory(u.Kind), "") + fallthrough + case "tool_call_update": + if !r.open[u.ToolCallID] || (u.Status != "completed" && u.Status != "failed") { + return + } + failed := u.Status == "failed" + delete(r.open, u.ToolCallID) + r.emitLocked(Event{Type: TypeToolResult, ToolCallID: u.ToolCallID, ToolName: r.tools[u.ToolCallID], IsError: &failed}, false) + } +} + +func acpToolCategory(kind string) string { + switch kind { + case "execute": + return "shell" + case "read", "edit", "delete", "move", "search": + return "file" + case "fetch": + return "web" + default: + return "other" + } +} + // Claude Code `-p --output-format stream-json --verbose` prints one complete event per content // block group: assistant events carry text, thinking and tool_use blocks, user events carry // tool_result blocks. The worker is not started with --include-partial-messages, so no text deltas diff --git a/internal/transcript/read.go b/internal/transcript/read.go index f2d8c5e..f9fb765 100644 --- a/internal/transcript/read.go +++ b/internal/transcript/read.go @@ -98,7 +98,7 @@ func Read(o ReadOptions) Response { return base(UnsupportedVersion, fmt.Sprintf("transcript schema_version %d is not supported; this reader supports %d", head.SchemaVersion, SchemaVersion)) case head.RunID != runID: return base(Unreadable, "transcript identity does not match its file") - case head.Backend != "claude" && head.Backend != "codex": + case head.Backend != "claude" && head.Backend != "codex" && head.Backend != "agy": return base(UnsupportedBackend, "backend "+safeText(head.Backend)+" has no transcript capture") case o.CallerRunID != "" && head.CallerRunID != o.CallerRunID: return base(IdentityMismatch, "run_id and caller_run_id do not belong to the same invocation") diff --git a/internal/transcript/recorder.go b/internal/transcript/recorder.go index 3e1985d..044cb82 100644 --- a/internal/transcript/recorder.go +++ b/internal/transcript/recorder.go @@ -56,6 +56,7 @@ type Recorder struct { tools map[string]string // tool_call_id -> tool name, for results open map[string]bool // tool calls without a result yet codexSeq map[string]bool // codex item ids whose tool_call was already written + acpText strings.Builder // adjacent assistant chunks, redacted as one message } // Open creates the transcript file for a run. The file is created exclusively with mode 0600 in a @@ -162,6 +163,7 @@ func (r *Recorder) End(info EndInfo) { if info.Session != "" && validSession(info.Session) { r.session = info.Session } + r.flushACPText() r.sum.WriteFailed = r.failed e := Event{Type: TypeExecutionEnd, Status: info.Status, ExitCode: info.ExitCode, ErrorKind: info.ErrorKind, StopReason: info.StopReason, TerminationClass: info.TerminationClass} diff --git a/internal/worker/agy_acp.go b/internal/worker/agy_acp.go new file mode 100644 index 0000000..5902305 --- /dev/null +++ b/internal/worker/agy_acp.go @@ -0,0 +1,335 @@ +package worker + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "strconv" + "strings" + "sync" + + "github.com/zhoushoujianwork/offload/internal/config" + "github.com/zhoushoujianwork/offload/internal/text" +) + +const AgyProtocol = "acp" + +func agyArgs(o Opts) []string { + args := []string{"acp"} + for _, dir := range o.AddDirs { + args = append(args, "--add-dir", dir) + } + return args +} + +// ACP allows agent requests while the client is waiting for a response. The +// protocol goroutine owns all stdin writes, leaving the stdout reader free to +// drain notifications even when a request is larger than a pipe buffer. +type agyACP struct { + ctx context.Context + stdin io.WriteCloser + inbox chan jsonRPCMessage + protocolErr chan error + processDone chan struct{} + done chan error + nextID int + + mu sync.Mutex + s streamSummary + report strings.Builder +} + +func newAgyACP(ctx context.Context, stdin io.WriteCloser) *agyACP { + return &agyACP{ + ctx: ctx, stdin: stdin, inbox: make(chan jsonRPCMessage, 16), + protocolErr: make(chan error, 1), processDone: make(chan struct{}), done: make(chan error, 1), + } +} + +func (p *agyACP) start(o Opts, prompt string) { + go func() { + err := p.run(o, prompt) + _ = p.stdin.Close() + p.done <- err + }() +} + +func (p *agyACP) summary() streamSummary { + p.mu.Lock() + defer p.mu.Unlock() + return p.s.clone() +} + +func (p *agyACP) fail(err error) { + select { + case p.protocolErr <- err: + default: + } +} + +func (p *agyACP) feed(line []byte) { + var msg jsonRPCMessage + if json.Unmarshal(line, &msg) != nil || msg.JSONRPC != "2.0" { + p.fail(errors.New("Antigravity ACP emitted an invalid JSON-RPC frame")) + return + } + p.mu.Lock() + p.s.Events++ + p.mu.Unlock() + if len(msg.ID) == 0 || string(msg.ID) == "null" { + if msg.Method == "session/update" { + p.update(msg.Params) + } + return + } + select { + case p.inbox <- msg: + default: + p.fail(errors.New("Antigravity ACP sent too many pending messages")) + } +} + +func (p *agyACP) update(raw json.RawMessage) { + var params struct { + SessionID string + Update struct { + SessionUpdate, Title, Kind string + Content struct{ Type, Text string } + ConfigOptions []agyConfigOption + } + } + if json.Unmarshal(raw, ¶ms) != nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.s.Session == "" || params.SessionID != p.s.Session { + return + } + u := params.Update + switch u.SessionUpdate { + case "agent_message_chunk": + if u.Content.Type != "text" { + return + } + if len(u.Content.Text) > maxLineKept-p.report.Len() { + p.fail(errors.New("Antigravity ACP report exceeds the output limit")) + return + } + p.report.WriteString(u.Content.Text) + if s := strings.TrimSpace(u.Content.Text); s != "" { + p.s.LastText = s + } + case "tool_call": + p.s.ToolCalls++ + title := text.Truncate(text.OneLine(firstNonEmpty(u.Title, u.Kind)), 100) + p.s.LastTools = append(p.s.LastTools, title) + if len(p.s.LastTools) > lastToolsKept { + p.s.LastTools = p.s.LastTools[1:] + } + case "config_option_update": + p.setModelLocked(u.ConfigOptions, "") + } +} + +func (p *agyACP) send(message map[string]any) error { + raw, err := json.Marshal(message) + if err != nil { + return err + } + if len(raw) > maxLineKept { + return errors.New("Antigravity ACP request exceeds the frame limit") + } + _, err = p.stdin.Write(append(raw, '\n')) + return err +} + +func (p *agyACP) receive() (jsonRPCMessage, error) { + select { + case err := <-p.protocolErr: + return jsonRPCMessage{}, err + default: + } + select { + case msg := <-p.inbox: + return msg, nil + default: + } + select { + case msg := <-p.inbox: + return msg, nil + case err := <-p.protocolErr: + return jsonRPCMessage{}, err + case <-p.ctx.Done(): + return jsonRPCMessage{}, p.ctx.Err() + case <-p.processDone: + // The stdout reader may have queued a response immediately before exit. + select { + case msg := <-p.inbox: + return msg, nil + default: + return jsonRPCMessage{}, io.ErrUnexpectedEOF + } + } +} + +func (p *agyACP) request(method string, params any, result any) error { + p.nextID++ + id := p.nextID + err := p.send(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}) + if err != nil { + return fmt.Errorf("Antigravity ACP %s: %w", method, err) + } + for { + msg, err := p.receive() + if err != nil { + return fmt.Errorf("Antigravity ACP %s: %w", method, err) + } + if msg.Method != "" { + if err := p.answer(msg); err != nil { + return err + } + continue + } + if string(msg.ID) != strconv.Itoa(id) || (len(msg.Result) > 0) == (len(msg.Error) > 0) { + return fmt.Errorf("Antigravity ACP %s returned an invalid response", method) + } + if len(msg.Error) > 0 { + var rpcErr struct { + Code int + Message string + } + _ = json.Unmarshal(msg.Error, &rpcErr) + if rpcErr.Code == -32000 { + return errors.New("Antigravity ACP authentication required; please sign in with agy acp --login") + } + return fmt.Errorf("Antigravity ACP %s failed (%d): %s", method, rpcErr.Code, config.SanitizeReason(rpcErr.Message)) + } + if string(msg.Result) == "null" || json.Unmarshal(msg.Result, result) != nil { + return fmt.Errorf("Antigravity ACP %s returned an invalid result", method) + } + return nil + } +} + +func (p *agyACP) answer(msg jsonRPCMessage) error { + reply := map[string]any{"jsonrpc": "2.0", "id": msg.ID} + switch msg.Method { + case "session/request_permission": + p.mu.Lock() + p.s.Denials++ + p.mu.Unlock() + // Deny this action without modifying the user's persistent rules. + outcome := map[string]string{"outcome": "cancelled"} + var params struct { + Options []struct{ Kind, OptionID string } + } + if json.Unmarshal(msg.Params, ¶ms) == nil { + for _, option := range params.Options { + if option.Kind == "reject_once" && option.OptionID != "" { + outcome = map[string]string{"outcome": "selected", "optionId": option.OptionID} + break + } + } + } + reply["result"] = map[string]any{"outcome": outcome} + default: + reply["error"] = map[string]any{"code": -32601, "message": "Offload does not support this ACP client method"} + } + return p.send(reply) +} + +type agyConfigOption struct { + ID, Category, CurrentValue string +} + +func (p *agyACP) setModelLocked(options []agyConfigOption, fallback string) { + for _, option := range options { + if option.Category == "model" || option.ID == "model" { + fallback = firstNonEmpty(option.CurrentValue, fallback) + break + } + } + p.s.ObservedModel = firstNonEmpty(fallback, p.s.ObservedModel) +} + +func (p *agyACP) run(o Opts, prompt string) error { + var initialize struct { + ProtocolVersion int + AgentCapabilities struct { + SessionCapabilities struct{ Resume json.RawMessage } + } + } + if err := p.request("initialize", map[string]any{"protocolVersion": 1, "clientCapabilities": map[string]any{}}, &initialize); err != nil { + return err + } + if initialize.ProtocolVersion != 1 { + return fmt.Errorf("Antigravity ACP returned unsupported protocol version %d", initialize.ProtocolVersion) + } + params := map[string]any{"cwd": o.Dir, "mcpServers": []any{}} + method := "session/new" + if o.Resume != "" { + if len(initialize.AgentCapabilities.SessionCapabilities.Resume) == 0 { + return errors.New("Antigravity ACP does not support session resume; update agy") + } + method, params["sessionId"] = "session/resume", o.Resume + } + var session struct { + SessionID string + ConfigOptions []agyConfigOption + Models struct{ CurrentModelID string } + } + if err := p.request(method, params, &session); err != nil { + return err + } + if o.Resume != "" && session.SessionID != "" && session.SessionID != o.Resume { + return errors.New("Antigravity ACP returned a different session ID for resume") + } + id := firstNonEmpty(session.SessionID, o.Resume) + if strings.TrimSpace(id) == "" { + return errors.New("Antigravity ACP returned no session ID") + } + p.mu.Lock() + p.s.Session = id + p.setModelLocked(session.ConfigOptions, session.Models.CurrentModelID) + p.mu.Unlock() + + for _, setting := range []struct{ id, value string }{ + {"model", o.Model}, {"thought_level", o.Profile.ReasoningEffort}, + } { + if setting.value == "" { + continue + } + var applied struct{ ConfigOptions []agyConfigOption } + if err := p.request("session/set_config_option", map[string]string{ + "sessionId": id, "configId": setting.id, "value": setting.value, + }, &applied); err != nil { + return fmt.Errorf("set Antigravity %s: %w", setting.id, err) + } + p.mu.Lock() + p.setModelLocked(applied.ConfigOptions, "") + p.mu.Unlock() + } + + var turn struct{ StopReason string } + if err := p.request("session/prompt", map[string]any{ + "sessionId": id, "prompt": []map[string]string{{"type": "text", "text": prompt}}, + }, &turn); err != nil { + return err + } + p.mu.Lock() + defer p.mu.Unlock() + report := strings.TrimSpace(p.report.String()) + result := &claudeResult{Result: report, SessionID: id, NumTurns: p.s.ToolCalls} + if turn.StopReason != "end_turn" { + result.IsError = true + result.Errors = []string{"Antigravity ACP stopped before completing the prompt (" + firstNonEmpty(turn.StopReason, "unknown reason") + ")"} + } else if report == "" { + result.IsError = true + result.Errors = []string{"Antigravity ACP completed without a text report"} + } + p.s.Result = result + return nil +} diff --git a/internal/worker/claude_usage.go b/internal/worker/claude_usage.go index 3f97598..adeacff 100644 --- a/internal/worker/claude_usage.go +++ b/internal/worker/claude_usage.go @@ -247,7 +247,7 @@ func applyClaudeAccounting(rec *history.Record, res *claudeResult, o Opts, base // markClaudeNoResult records that a normal Claude run ended without a final result, so neither // usage nor cost is known. Codex accounting is applied separately. func markClaudeNoResult(rec *history.Record) { - if rec.Backend == "codex" { + if rec.Backend != "claude" { return } rec.UsageSource = claudeUsageSource diff --git a/internal/worker/codex_app_server.go b/internal/worker/codex_app_server.go index 6275545..f044606 100644 --- a/internal/worker/codex_app_server.go +++ b/internal/worker/codex_app_server.go @@ -21,7 +21,7 @@ const codexAppServerProtocol = "codex-app-server" const codexAppServerMaxFrame = 32 << 20 -type appServerMessage struct { +type jsonRPCMessage struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id"` Method string `json:"method"` @@ -34,7 +34,7 @@ type appServerParser struct { mu sync.Mutex w io.WriteCloser nextID int - pending map[string]chan appServerMessage + pending map[string]chan jsonRPCMessage done chan struct{} doneOnce sync.Once err error @@ -48,7 +48,7 @@ type appServerParser struct { } func newAppServerParser(w io.WriteCloser, o Opts) *appServerParser { - return &appServerParser{w: w, pending: make(map[string]chan appServerMessage), done: make(chan struct{}), o: o} + return &appServerParser{w: w, pending: make(map[string]chan jsonRPCMessage), done: make(chan struct{}), o: o} } func (p *appServerParser) summary() streamSummary { @@ -58,7 +58,7 @@ func (p *appServerParser) summary() streamSummary { } func (p *appServerParser) feed(line []byte) { - var m appServerMessage + var m jsonRPCMessage if len(line) > maxLineKept || json.Unmarshal(line, &m) != nil || m.JSONRPC != "" && m.JSONRPC != "2.0" { p.fail(errors.New("Codex app-server emitted a malformed JSON-RPC frame")) return @@ -91,7 +91,7 @@ func (p *appServerParser) feed(line []byte) { p.notification(m.Method, m.Params) } -func (p *appServerParser) rejectServerRequest(m appServerMessage) { +func (p *appServerParser) rejectServerRequest(m jsonRPCMessage) { _ = p.write(map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(m.ID), "error": map[string]any{"code": -32601, "message": "interactive server requests are not supported"}}) p.fail(fmt.Errorf("Codex app-server requested unsupported interaction %q", m.Method)) } @@ -244,7 +244,7 @@ func (p *appServerParser) request(method string, params any) (json.RawMessage, e p.mu.Lock() p.nextID++ id := strconv.Itoa(p.nextID) - ch := make(chan appServerMessage, 1) + ch := make(chan jsonRPCMessage, 1) p.pending[id] = ch requestID := p.nextID p.mu.Unlock() @@ -578,7 +578,7 @@ func (p *appServerParser) interruptAndWait(wait time.Duration) { p.nextID++ id := p.nextID key := strconv.Itoa(id) - response := make(chan appServerMessage, 1) + response := make(chan jsonRPCMessage, 1) p.pending[key] = response p.mu.Unlock() if err := p.write(map[string]any{"jsonrpc": "2.0", "id": id, "method": "turn/interrupt", "params": map[string]any{"threadId": threadID, "turnId": turnID}}); err != nil { diff --git a/internal/worker/idle.go b/internal/worker/idle.go index f9bc24e..3c31d43 100644 --- a/internal/worker/idle.go +++ b/internal/worker/idle.go @@ -118,6 +118,9 @@ type sessionActivity struct { func newSessionActivity(o Opts) *sessionActivity { home, _ := os.UserHomeDir() a := &sessionActivity{codex: o.Profile.BackendName() == "codex", sizes: map[string]int64{}} + if o.Profile.BackendName() == "agy" { + return a // ACP activity is reported on the process streams. + } if a.codex { root := os.Getenv("CODEX_HOME") if root == "" { @@ -137,7 +140,7 @@ func newSessionActivity(o Opts) *sessionActivity { func (a *sessionActivity) grew(session string) bool { // 会话标识来自子进程,禁止路径及 glob 元字符。 - if session == "" || strings.ContainsAny(session, "/\\*?[]") || session == "." || session == ".." { + if a.root == "" || session == "" || strings.ContainsAny(session, "/\\*?[]") || session == "." || session == ".." { return false } pattern := filepath.Join(a.root, "*", session+".jsonl") diff --git a/internal/worker/supervisor.go b/internal/worker/supervisor.go index f2cb847..06d6a54 100644 --- a/internal/worker/supervisor.go +++ b/internal/worker/supervisor.go @@ -104,6 +104,12 @@ func CheckToolRestrictions(o *Opts) (notEnforced bool, err error) { // Validate checks supervisor constraints before any provider is started. func Validate(o *Opts) error { + if !o.Profile.ValidBackend() { + return errors.New("unknown backend") + } + if err := o.Profile.ValidateAgySettings(); err != nil { + return err + } if err := o.Native.Validate(o.Profile.BackendName(), o.Resume, o.ToolsDisabled); err != nil { return err } @@ -112,6 +118,9 @@ func Validate(o *Opts) error { return errors.New("invalid execution-policy") } managed := o.ExecutionPolicy == "managed-development" + if o.Profile.BackendName() == "agy" && (managed || o.EnvironmentDirectory != "") { + return &configError{"configuration", errors.New("agy requires the default execution policy and the native CLI environment")} + } if managed && !o.Write { return errors.New("managed-development requires -w") } diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 5146075..344be79 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -1,4 +1,4 @@ -// Package worker runs one task through Claude Code or Codex and reports what the worker did. +// Package worker runs one task through a local backend and reports what the worker did. package worker import ( @@ -344,6 +344,11 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { if o.Native != nil && o.Native.CodexAppServer { rec.NativeProtocol = codexAppServerProtocol } + if rec.Backend == "agy" { + rec.NativeProtocol = AgyProtocol + rec.UsageUnavailable = "Antigravity ACP emitted no trusted per-run token usage" + rec.CostUnavailable = "Antigravity ACP emitted no trusted per-run cost" + } if rec.Backend == "claude" { rec.ClaudeHome = os.Getenv("CLAUDE_CONFIG_DIR") if o.Native != nil && o.Native.ProfileDirectory != "" { @@ -369,7 +374,7 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { return rec, errors.New("isolated Codex account home changed") } } - if o.EnvironmentDirectory != "" { + if o.EnvironmentDirectory != "" && rec.Backend != "agy" { _, setupErr := o.prepareEnvironment(sourceHome) if setupErr != nil { return rec, setupErr @@ -483,13 +488,23 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { } defer os.Remove(promptPath) var token, bin string - if o.Profile.BackendName() == "codex" { + switch rec.Backend { + case "codex": rec.ErrorKind = "launch" bin, err = codexBin() if err != nil { return rec, fmt.Errorf("codex CLI not found: %w", err) } - } else { + case "agy": + rec.ErrorKind = "launch" + bin, err = exec.LookPath("agy") + if err != nil { + return rec, fmt.Errorf("Antigravity CLI (agy) not found: %w", err) + } + if o.Transcript != nil { + o.Transcript.AddSecrets(os.Getenv("GEMINI_API_KEY"), os.Getenv("GOOGLE_API_KEY")) + } + default: if !o.Profile.UsesNativeAuth() { token, err = o.Profile.ResolveTokenContext(ctx) if err != nil { @@ -550,6 +565,18 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { leftover = a.leftover } s := a.s + if rec.Backend == "agy" { + rec.ObservedModel = s.ObservedModel + rec.Model = firstNonEmpty(s.ObservedModel, o.Model) + switch { + case s.ObservedModel != "": + rec.ModelSource = "native_acp" + case o.Model != "": + rec.ModelSource = "requested_fallback" + default: + rec.ModelSource, rec.ModelUnavailable = "unknown", "Antigravity ACP returned no model selection" + } + } if rec.Backend == "claude" { rec.ObservedModel = s.ObservedModel if strings.Contains(a.stderr, "unrecognized_model") { @@ -667,7 +694,7 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { rec.Session, rec.Turns, rec.DurationMs, rec.Result = firstNonEmpty(res.SessionID, s.Session), res.NumTurns, res.DurationMs, res.Result rec.StructuredOutput = res.StructuredOutput - if rec.NativeProtocol != codexAppServerProtocol { + if rec.Backend != "agy" && rec.NativeProtocol != codexAppServerProtocol { applyClaudeAccounting(&rec, &res, o, a.claudeBase) } if !res.IsError && a.runErr == nil && a.cause == nil { @@ -752,11 +779,14 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin var cmd *exec.Cmd var parser eventParser = &claudeParser{} var appServer *appServerParser + var acp *agyACP + var acpPrompt string var baseline *history.TokenUsage var baselineError string var claudeBase claudeBaseline // Not CommandContext: that kills only the worker process and never its children. - if o.Profile.BackendName() == "codex" { + switch o.Profile.BackendName() { + case "codex": if o.Native == nil || !o.Native.CodexAppServer { baseline, baselineError = codexBaseline(o.Resume, o.CodexHome) } @@ -812,7 +842,23 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin } parser = &codexParser{} } - } else { + case "agy": + prompt, err := os.ReadFile(promptPath) + if err != nil { + return attempt{runErr: err} + } + acpPrompt = string(prompt) + "\nTask:\n" + o.Task + cmd = exec.Command(bin, agyArgs(o)...) + cmd.Dir = o.Dir + cmd.Env = o.Limits.ApplyEnv(o.baseEnvironment()) + stdin, err := cmd.StdinPipe() + if err != nil { + return attempt{runErr: err} + } + defer stdin.Close() + acp = newAgyACP(ctx, stdin) + parser = acp + default: if o.Resume != "" && !o.Salvage { // Capture before the child starts: the result's cost and modelUsage are session totals. claudeBase = captureClaudeBaseline(history.Path(), o.Resume) @@ -884,6 +930,9 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin if appServer != nil { appServer.start() } + if acp != nil { + acp.start(o, acpPrompt) + } group := proc.Started(cmd) if h.started != nil { h.started(group) @@ -922,6 +971,9 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin case runErr = <-waited: case <-ctx.Done(): // Timeout, idle limit or interrupt: stop the group, then collect the worker's exit. + if acp != nil { + _ = acp.stdin.Close() + } if appServer != nil { appServer.interruptAndWait(StopGrace / 2) _ = appServer.w.Close() @@ -961,6 +1013,10 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin if err := out.finish(); err != nil { runErr = errors.Join(runErr, err) } + if acp != nil { + close(acp.processDone) + runErr = errors.Join(runErr, <-acp.done) + } var nativeExitCode *int if cmd.ProcessState != nil { code := cmd.ProcessState.ExitCode() diff --git a/macos/Sources/OffloadMonitor/ProfileModels.swift b/macos/Sources/OffloadMonitor/ProfileModels.swift index 455dec5..2b9cdea 100644 --- a/macos/Sources/OffloadMonitor/ProfileModels.swift +++ b/macos/Sources/OffloadMonitor/ProfileModels.swift @@ -301,6 +301,8 @@ struct ProfileDraft: Equatable { var baseURLHidden: Bool { original?.baseUrlRedacted == true } var isCodex: Bool { backend == "codex" } + var isAgy: Bool { backend == "agy" } + static let agyEfforts = ["", "low", "medium", "high", "xhigh", "max"] /// 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] { @@ -334,7 +336,7 @@ struct ProfileDraft: Equatable { guard Self.validName(trimmedName) else { throw ProfileDraftError.nameInvalid } guard !existingNames.contains(trimmedName) else { throw ProfileDraftError.nameTaken } } - guard Self.efforts.contains(reasoning) else { throw ProfileDraftError.badEffort } + guard (isAgy ? Self.agyEfforts : Self.efforts).contains(reasoning) else { throw ProfileDraftError.badEffort } guard Self.tiers.contains(tier) else { throw ProfileDraftError.badTier } guard Self.endpoints.contains(endpoint) else { throw ProfileDraftError.badEndpoint } @@ -343,6 +345,13 @@ struct ProfileDraft: Equatable { if isNew || backend != (o?.backend.isEmpty == false ? o!.backend : "claude") { r.backend = backend } + if isAgy { + if model != (o?.model ?? "") { r.model = model } + let savedEffort = o?.backend == "agy" ? o?.reasoningEffort ?? "" : "" + if reasoning != savedEffort { r.reasoningEffort = reasoning } + return r + } + if isCodex { if codexAccount != (o?.codexAccount ?? "") { r.codexAccount = codexAccount } if model != (o?.model ?? "") || (isNew && !model.isEmpty) { r.model = model } @@ -369,7 +378,7 @@ struct ProfileDraft: Equatable { switch credential { case .native: - if isNew || o?.authMode != "native" { r.authMode = "native" } + if isNew || o?.authMode != "native" || o?.backend == "agy" { 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") } diff --git a/macos/Sources/OffloadMonitor/SettingsView.swift b/macos/Sources/OffloadMonitor/SettingsView.swift index ee2138f..2a25a37 100644 --- a/macos/Sources/OffloadMonitor/SettingsView.swift +++ b/macos/Sources/OffloadMonitor/SettingsView.swift @@ -321,6 +321,7 @@ struct ProfilesSettingsView: View { Picker("Backend", selection: $draft.backend) { Text("Claude").tag("claude") Text("Codex").tag("codex") + Text("Antigravity").tag("agy") } .pickerStyle(.segmented).labelsHidden().frame(width: 200) } @@ -328,9 +329,27 @@ struct ProfilesSettingsView: View { label("Use for") TextField("optional: tasks this profile suits", text: $draft.useFor).textFieldStyle(.roundedBorder).lineLimit(1) } - if draft.isCodex { codexRows } else { claudeRows } + if draft.isCodex { + codexRows + } else if draft.isAgy { + GridRow { + label("Model") + TextField("optional: inherit Antigravity default", text: $draft.model).textFieldStyle(.roundedBorder) + } + GridRow { + label("Reasoning") + Picker("Reasoning", selection: $draft.reasoning) { + Text("inherit").tag("") + ForEach(ProfileDraft.agyEfforts.dropFirst(), id: \.self) { Text($0).tag($0) } + } + .labelsHidden().frame(width: 200) + } + } else { + claudeRows + } } - Text(draft.isCodex ? "Codex uses its native sign-in." + Text(draft.isAgy ? "Antigravity uses the sign-in from the local agy CLI." + : draft.isCodex ? "Codex uses its native sign-in." : (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) @@ -558,7 +577,7 @@ struct ProfilesSettingsView: View { } private var missingSecret: Bool { - !draft.isCodex && (draft.credential == .token || draft.credential == .tokenCmd) + !draft.isCodex && !draft.isAgy && (draft.credential == .token || draft.credential == .tokenCmd) && draft.secret.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } diff --git a/pkg/execution/execution.go b/pkg/execution/execution.go index 2c1dfbf..6b5b7b4 100644 --- a/pkg/execution/execution.go +++ b/pkg/execution/execution.go @@ -381,6 +381,9 @@ func (c *Client) Run(ctx context.Context, req Request) (result Result, resultErr if native != nil && native.CodexAppServer { protocol = "codex-app-server" } + if c.profile.BackendName() == "agy" { + protocol = worker.AgyProtocol + } err := req.OnEvent(RawEvent{RunID: id, CallerRunID: req.CallerRunID, Backend: c.profile.BackendName(), NativeProtocol: protocol, Data: redactEnvValues(line, envSet)}) observerErr = errors.Join(observerErr, err) if err != nil || progress == nil { diff --git a/pkg/execution/profiles.go b/pkg/execution/profiles.go index 4ef6b5f..43eddc5 100644 --- a/pkg/execution/profiles.go +++ b/pkg/execution/profiles.go @@ -96,7 +96,7 @@ func SetDefaultProfile(path, name string) error { func profileAuthMode(p config.Profile) string { switch { - case p.UsesNativeAuth(): + case p.UsesNativeAuth() || p.BackendName() == "agy": return "native" case p.TokenCmd != "": return "token_cmd"