diff --git a/README.md b/README.md index cb6c842c..978b1c0b 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ **Morph Code** is a fast, local-first native macOS coding agent studio powered by a single-binary pure-Go daemon (`morphcode`). -No Electron. No Node.js runtime required. Instant SQLite startup, native SwiftUI rendering, built-in Live Web Preview, Git diff & worktree workflows, interactive PTY terminal, and first-class support for **Claude Code**, **OpenAI Codex**, **DeepSeek**, and any **OpenAI / Anthropic-compatible custom provider** (OpenRouter, Ollama, Groq, xAI, LM Studio, and more). +No Electron. No Node.js runtime required. Instant SQLite startup, native SwiftUI rendering, built-in Live Web Preview, Git diff & worktree workflows, interactive PTY terminal, and first-class support for **Antigravity (`agy`)**, **Claude Code**, **OpenAI Codex**, **DeepSeek**, and any **OpenAI / Anthropic-compatible custom provider** (OpenRouter, Ollama, Groq, xAI, LM Studio, and more). --- @@ -19,8 +19,8 @@ Morph Code is built natively from the ground up in **SwiftUI + AppKit** and **pu | **UI Stack** | Native macOS SwiftUI + AppKit (120Hz ProMotion) | Electron / Chromium renderer | | **Backend Daemon** | Single zero-CGO pure-Go binary (`~22 MB` RSS) | Node.js runtime & dependency tree | | **Live Web Preview** | Built-in native `WKWebView` + viewports + Element Picker + Console/Network | Chromium WebView / external browser | -| **Execution Engine** | Built-in pure-Go **Morph Harness** + official `claude` / `codex` CLIs | External CLI wrapper | -| **Model Providers** | Claude, Codex, DeepSeek, OpenRouter, Ollama, Groq, xAI, any custom endpoint | CLI-bound providers | +| **Execution Engine** | Built-in pure-Go **Morph Harness** + official `agy` / `claude` / `codex` CLIs | External CLI wrapper | +| **Model Providers** | Antigravity (`agy`), Claude, Codex, DeepSeek, OpenRouter, Ollama, Groq, xAI, any custom endpoint | CLI-bound providers | | **Local Storage & Search** | Embedded SQLite WAL + FTS5 instant rendering | Web / Node state layer | | **Parallel Orchestration** | Configurable Orchestrator + per-provider Worker harnesses & worktrees | Thread-level CLI execution | @@ -29,7 +29,7 @@ Morph Code is built natively from the ground up in **SwiftUI + AppKit** and **pu ## Highlights - **Bring Your Own CLI or API Keys** - - Works out of the box with your locally installed **`claude`** (Claude Code) and **`codex`** (`codex app-server`) CLIs using your own local authentication. + - Works out of the box with your locally installed **`agy`** (Antigravity ACP), **`claude`** (Claude Code), and **`codex`** (`codex app-server`) CLIs using your own local authentication. - Or run directly through Morph Code's built-in pure-Go agent harness (**Morph Harness**) using `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `DEEPSEEK_API_KEY`, or custom OpenAI/Anthropic-compatible endpoints (OpenRouter, Ollama, Groq, xAI, etc.). - **Parallel Multi-Thread & Worktree Workspace** - Run independent coding threads across multiple local repositories and isolated Git worktrees in parallel. @@ -63,7 +63,7 @@ morph-code/ ├─ agent/ # Built-in pure-Go coding agent loop, tools, compaction, MCP client ├─ checkpoint/ # Automatic per-turn workspace checkpoints and revert ├─ gitops/ # Git status, diff, worktrees, commits, GitHub PR ops - ├─ harness/ # Official Claude CLI, Codex app-server, and built-in Morph Harness adapters + ├─ harness/ # Official Agy ACP, Claude CLI, Codex app-server, and built-in Morph Harness adapters ├─ model/ # Shared workspace & streaming event schema ├─ router/ # Single-user local API key & custom provider configuration ├─ schedule/ # Persistent RRULE scheduler @@ -80,7 +80,7 @@ morph-code/ - **macOS 15.0+** and **Xcode 16.4+** - **Go 1.25+** - **XcodeGen** (`brew install xcodegen`) -- Optional: official [`claude`](https://docs.anthropic.com/en/docs/claude-code) and/or [`codex`](https://github.com/openai/codex) CLI installed locally, or API keys configured in **Settings → Providers & Models**. +- Optional: official `agy` (Antigravity CLI), [`claude`](https://docs.anthropic.com/en/docs/claude-code), and/or [`codex`](https://github.com/openai/codex) CLI installed locally, or API keys configured in **Settings → Providers & Models**. ### 1. Run `morphcode` Daemon Tests & Build diff --git a/apple/Apps/Shared/MorphAppState+Accounts.swift b/apple/Apps/Shared/MorphAppState+Accounts.swift index fa508ed8..e2e23107 100644 --- a/apple/Apps/Shared/MorphAppState+Accounts.swift +++ b/apple/Apps/Shared/MorphAppState+Accounts.swift @@ -84,7 +84,7 @@ extension MorphAppState { if let map = cfg.providerHarnesses, !map.isEmpty { providerHarnesses = map } else { - providerHarnesses = ["claude": "morphcode", "codex": "morphcode"] + providerHarnesses = ["claude": "morphcode", "codex": "morphcode", "agy": "native"] } if let orchModel = cfg.orchestratorModel?.trimmingCharacters(in: .whitespacesAndNewlines), !orchModel.isEmpty { orchestratorModel = orchModel @@ -96,7 +96,7 @@ extension MorphAppState { if let workers = cfg.workerHarnesses, !workers.isEmpty { workerHarnesses = workers } else { - workerHarnesses = ["claude": "morphcode", "codex": "morphcode"] + workerHarnesses = ["claude": "morphcode", "codex": "morphcode", "agy": "native"] } nativeCliAvailable = cfg.nativeCliAvailable ?? [:] } catch { diff --git a/apple/Apps/Shared/MorphCustomProvidersSection.swift b/apple/Apps/Shared/MorphCustomProvidersSection.swift index b214b185..7ce3948e 100644 --- a/apple/Apps/Shared/MorphCustomProvidersSection.swift +++ b/apple/Apps/Shared/MorphCustomProvidersSection.swift @@ -10,11 +10,13 @@ struct MorphProviderHarnessesSection: View { let title: String let cliName: String let brand: MorphBrand + let nativeOnly: Bool } private let providers: [ProviderSpec] = [ - ProviderSpec(id: "claude", title: "Claude", cliName: "claude", brand: .claude), - ProviderSpec(id: "codex", title: "Codex", cliName: "codex", brand: .openai), + ProviderSpec(id: "claude", title: "Claude", cliName: "claude", brand: .claude, nativeOnly: false), + ProviderSpec(id: "codex", title: "Codex", cliName: "codex", brand: .openai, nativeOnly: false), + ProviderSpec(id: "agy", title: "Antigravity (Agy)", cliName: "agy", brand: .gemini, nativeOnly: true), ] private func concreteModelSections(selection: String) -> CodeModelMenu.Sections { @@ -39,9 +41,12 @@ struct MorphProviderHarnessesSection: View { "Orchestrator", footnote: "When you pick Orchestrator in the model menu, the selected model decomposes and verifies tasks and dispatches worker subagents." ) { + let isAgyOrch = state.orchestratorModel.lowercased().hasPrefix("agy/") MorphSettingsRow( "Orchestrator Model", - detail: "\(providerDisplayName(for: state.orchestratorModel)) · morphcode Go harness" + detail: isAgyOrch + ? "\(providerDisplayName(for: state.orchestratorModel)) · Official agy CLI (ACP)" + : "\(providerDisplayName(for: state.orchestratorModel)) · morphcode Go harness" ) { EmptyView() } trailing: { @@ -157,9 +162,11 @@ struct MorphProviderHarnessesSection: View { } ForEach(providers) { spec in - let workerMode = CodeProviderHarnessMode( - rawValue: (state.workerHarnesses[spec.id] ?? "morphcode").lowercased() - ) ?? .morphcode + let workerMode: CodeProviderHarnessMode = spec.nativeOnly + ? .native + : (CodeProviderHarnessMode( + rawValue: (state.workerHarnesses[spec.id] ?? "morphcode").lowercased() + ) ?? .morphcode) let cliInstalled = state.nativeCliAvailable[spec.id] let cliLabel: String = { if let installed = cliInstalled { @@ -167,39 +174,47 @@ struct MorphProviderHarnessesSection: View { } return "Checking \(spec.cliName) CLI" }() - let detail = workerMode == .morphcode - ? "Worker: built-in morphcode Go harness · \(cliLabel)" - : "Worker: official \(spec.cliName) CLI · \(cliLabel)" + let detail = spec.nativeOnly + ? "Worker: official \(spec.cliName) CLI (ACP) · \(cliLabel)" + : (workerMode == .morphcode + ? "Worker: built-in morphcode Go harness · \(cliLabel)" + : "Worker: official \(spec.cliName) CLI · \(cliLabel)") MorphSettingsRow("\(spec.title) Worker", detail: detail) { MorphServiceIcon(brand: spec.brand) } trailing: { - AnymorphSegmentControl( - items: CodeProviderHarnessMode.allCases, - selection: Binding( - get: { workerMode }, - set: { newMode in - guard newMode != workerMode else { return } - Task { - await state.setWorkerHarness(provider: spec.id, mode: newMode) + if spec.nativeOnly { + AnymorphBadge("Native CLI") + } else { + AnymorphSegmentControl( + items: CodeProviderHarnessMode.allCases, + selection: Binding( + get: { workerMode }, + set: { newMode in + guard newMode != workerMode else { return } + Task { + await state.setWorkerHarness(provider: spec.id, mode: newMode) + } } - } - ), - label: { $0.label } - ) - .disabled(state.isSavingProviderHarnesses) + ), + label: { $0.label } + ) + .disabled(state.isSavingProviderHarnesses) + } } } } MorphSettingsGroup( "Default Provider Harness", - footnote: "Choose whether Claude and Codex run through morphcode's built-in Go harness (zero external CLI dependency) or proxy through their official local CLI." + footnote: "Choose whether Claude and Codex run through morphcode's built-in Go harness (zero external CLI dependency) or their official local CLI. Antigravity (Agy) runs exclusively via the official local agy CLI (ACP)." ) { ForEach(providers) { spec in - let currentMode = CodeProviderHarnessMode( - rawValue: (state.providerHarnesses[spec.id] ?? "morphcode").lowercased() - ) ?? .morphcode + let currentMode: CodeProviderHarnessMode = spec.nativeOnly + ? .native + : (CodeProviderHarnessMode( + rawValue: (state.providerHarnesses[spec.id] ?? "morphcode").lowercased() + ) ?? .morphcode) let cliInstalled = state.nativeCliAvailable[spec.id] let cliState: String = { if let installed = cliInstalled { @@ -207,27 +222,33 @@ struct MorphProviderHarnessesSection: View { } return "Checking \(spec.cliName) CLI" }() - let statusDetail = currentMode == .morphcode - ? "Built-in morphcode Go harness · \(cliState)" - : "Official \(spec.cliName) CLI proxy · \(cliState)" + let statusDetail = spec.nativeOnly + ? "Official \(spec.cliName) CLI (ACP) · \(cliState)" + : (currentMode == .morphcode + ? "Built-in morphcode Go harness · \(cliState)" + : "Official \(spec.cliName) CLI · \(cliState)") MorphSettingsRow(spec.title, detail: statusDetail) { MorphServiceIcon(brand: spec.brand) } trailing: { - AnymorphSegmentControl( - items: CodeProviderHarnessMode.allCases, - selection: Binding( - get: { currentMode }, - set: { newMode in - guard newMode != currentMode else { return } - Task { - await state.setProviderHarness(provider: spec.id, mode: newMode) + if spec.nativeOnly { + AnymorphBadge("Native CLI") + } else { + AnymorphSegmentControl( + items: CodeProviderHarnessMode.allCases, + selection: Binding( + get: { currentMode }, + set: { newMode in + guard newMode != currentMode else { return } + Task { + await state.setProviderHarness(provider: spec.id, mode: newMode) + } } - } - ), - label: { $0.label } - ) - .disabled(state.isSavingProviderHarnesses) + ), + label: { $0.label } + ) + .disabled(state.isSavingProviderHarnesses) + } } } } diff --git a/apple/Apps/Shared/SettingsView.swift b/apple/Apps/Shared/SettingsView.swift index 83e2af00..22fc0ab4 100644 --- a/apple/Apps/Shared/SettingsView.swift +++ b/apple/Apps/Shared/SettingsView.swift @@ -254,7 +254,7 @@ public struct SettingsView: View { VStack(alignment: .leading, spacing: 24) { MorphSettingsGroup( "Built-In Providers & Local CLIs", - footnote: "Morph Code automatically uses your locally installed Claude Code or Codex CLI authentication. You can also configure API keys stored locally in ~/.morph-code/providers.json (0600) or via standard environment variables." + footnote: "Morph Code automatically uses your locally installed Antigravity (agy), Claude Code, or Codex CLI authentication. You can also configure API keys stored locally in ~/.morph-code/providers.json (0600) or via standard environment variables." ) { Button { Task { @@ -287,13 +287,17 @@ public struct SettingsView: View { private func builtinProviderRow(_ choice: LocalProviderChoice) -> some View { let hasCLI = choice.supportsLocalCLI && (state.nativeCliAvailable[choice.rawValue] == true) - let hasKey = state.providerKeyStatus[choice.rawValue] == true + let hasKey = choice.supportsAPIKey && (state.providerKeyStatus[choice.rawValue] == true) let detail: String = { var parts: [String] = [] if choice.supportsLocalCLI { parts.append(hasCLI ? "Local \(choice.cliBinaryName) CLI detected" : "\(choice.cliBinaryName) CLI not found") } - parts.append(hasKey ? "API key configured" : "Env: \(choice.envKeyName)") + if choice.supportsAPIKey { + parts.append(hasKey ? "API key configured" : "Env: \(choice.envKeyName)") + } else { + parts.append("Official \(choice.cliBinaryName) CLI (ACP)") + } return parts.joined(separator: " · ") }() @@ -304,18 +308,22 @@ public struct SettingsView: View { if hasCLI || hasKey { AnymorphBadge(hasKey ? "API Key" : "Local CLI") } - Button(hasKey ? "Update Key" : "Set API Key") { - editingProviderKey = choice - } - .anymorphButton(size: .inline, appearance: .secondary) - if hasKey { - Button { - Task { await state.clearProviderKey(provider: choice.rawValue) } - } label: { - Image(systemName: "trash") + if choice.supportsAPIKey { + Button(hasKey ? "Update Key" : "Set API Key") { + editingProviderKey = choice + } + .anymorphButton(size: .inline, appearance: .secondary) + if hasKey { + Button { + Task { await state.clearProviderKey(provider: choice.rawValue) } + } label: { + Image(systemName: "trash") + } + .morphRound(diameter: 24) + .help("Clear saved API key") } - .morphRound(diameter: 24) - .help("Clear saved API key") + } else if !hasCLI { + AnymorphBadge("Not Installed") } } } @@ -364,6 +372,7 @@ private struct SettingsNavRow: View { // MARK: - Add Local Provider Account / Key Sheet private enum LocalProviderChoice: String, CaseIterable, Identifiable { + case agy case claude case codex case deepseek @@ -372,6 +381,7 @@ private enum LocalProviderChoice: String, CaseIterable, Identifiable { var title: String { switch self { + case .agy: return "Antigravity (Agy)" case .claude: return "Claude" case .codex: return "Codex" case .deepseek: return "DeepSeek" @@ -379,11 +389,16 @@ private enum LocalProviderChoice: String, CaseIterable, Identifiable { } var supportsLocalCLI: Bool { - self == .claude || self == .codex + self == .agy || self == .claude || self == .codex + } + + var supportsAPIKey: Bool { + self != .agy } var cliBinaryName: String { switch self { + case .agy: return "agy" case .claude: return "claude" case .codex: return "codex" case .deepseek: return "" @@ -392,6 +407,7 @@ private enum LocalProviderChoice: String, CaseIterable, Identifiable { var envKeyName: String { switch self { + case .agy: return "" case .claude: return "ANTHROPIC_API_KEY" case .codex: return "OPENAI_API_KEY" case .deepseek: return "DEEPSEEK_API_KEY" @@ -400,6 +416,7 @@ private enum LocalProviderChoice: String, CaseIterable, Identifiable { var brand: MorphBrand { switch self { + case .agy: return .gemini case .claude: return .claude case .codex: return .openai case .deepseek: return .deepseek diff --git a/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeModelMenu.swift b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeModelMenu.swift index d6055709..674c45da 100644 --- a/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeModelMenu.swift +++ b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeModelMenu.swift @@ -34,6 +34,7 @@ public enum CodeModelMenu { private static let bestOrder: [String] = [ "orchestrator", + "agy/gemini-4-neon", "claude/claude-opus-5-5", "codex/gpt-6.2-astra", ] @@ -41,6 +42,7 @@ public enum CodeModelMenu { private static let standardOrder: [String] = [ "claude/claude-sonnet-5-5", "codex/gpt-6.2-sol", + "agy/gemini-3.8-flash", "deepseek/deepseek-v4.1-flash-eco", ] @@ -48,6 +50,9 @@ public enum CodeModelMenu { private static let purposes: [String: String] = [ "auto": "Automatically picks an available configured engine", "orchestrator": "Decomposes tasks and delegates to parallel workers", + "agy/gemini-4-neon": "Balanced flagship via official agy CLI (ACP)", + "agy/gemini-pro-orchestrator-neon": "Antigravity orchestrator via official agy CLI", + "agy/gemini-3.8-flash": "Fast everyday iterations via official agy CLI", "claude/claude-opus-5-5": "Complex debugging and deep reasoning", "claude/claude-sonnet-5-5": "Fast everyday coding and reviews", "claude/claude-fable-5-2": "Architecture and long autonomous runs", @@ -58,10 +63,14 @@ public enum CodeModelMenu { /// Explicit clean display names for curated models. private static let displayNames: [String: String] = [ + "agy/gemini-4-neon": "Gemini 4 Neon", + "agy/gemini-pro-orchestrator-neon": "Gemini Pro Orchestrator Neon", + "agy/gemini-3.8-flash": "Gemini 3.8 Flash", "deepseek/deepseek-v4.1-flash-eco": "DeepSeek 4.1 Flash Eco", ] - private static let builtinProviders: Set = ["auto", "orchestrator", "claude", "codex", "deepseek"] + private static let builtinProviders: Set = ["auto", "orchestrator", "agy", "antigravity", "claude", "codex", "deepseek"] + private static let agyTiers: [String] = ["xhigh", "high", "medium", "low"] /// Splits a model list into Auto, tiered main groups (`Best`, `Standard`, plus user custom providers), /// and all remaining built-in models under `more`. @@ -115,8 +124,13 @@ public enum CodeModelMenu { ) } + /// Strips effort tier suffixes from `agy/` model ids so `agy/gemini-4-neon-high` and `-medium` group as one family. public static func family(_ id: String) -> String { - id + guard id.hasPrefix("agy/") else { return id } + for tier in agyTiers where id.hasSuffix("-" + tier) { + return String(id.dropLast(tier.count + 1)) + } + return id } public static func isSameModel(_ a: String, _ b: String) -> Bool { diff --git a/assets/hero.png b/assets/hero.png index e20e5791..8e2c9b86 100644 Binary files a/assets/hero.png and b/assets/hero.png differ diff --git a/morphcode/cmd/morphcode/main.go b/morphcode/cmd/morphcode/main.go index 12473187..275a899d 100644 --- a/morphcode/cmd/morphcode/main.go +++ b/morphcode/cmd/morphcode/main.go @@ -264,6 +264,7 @@ func runDoctor() { name string driver string }{ + {"agy", "Antigravity official CLI (ACP)"}, {"claude", "Claude Code official CLI"}, {"codex", "OpenAI Codex official CLI (app-server)"}, {"git", "Git worktrees, diffs, and checkpoints"}, diff --git a/morphcode/internal/harness/adapters.go b/morphcode/internal/harness/adapters.go index e94de154..74cb41a8 100644 --- a/morphcode/internal/harness/adapters.go +++ b/morphcode/internal/harness/adapters.go @@ -2627,10 +2627,11 @@ func RunWorkspaceCommandWithEnv(ctx context.Context, cwd string, command string, return outB.String(), errB.String(), code, runErr } -// DetectNativeCLIAvailability checks whether official claude and codex CLIs exist on disk +// DetectNativeCLIAvailability checks whether official agy, claude, and codex CLIs exist on disk // without spawning any process. func DetectNativeCLIAvailability() map[string]bool { return map[string]bool{ + string(model.ProviderAgy): findOfficialCLI("agy") != "", string(model.ProviderClaude): findOfficialCLI("claude") != "", string(model.ProviderCodex): findOfficialCLI("codex") != "", } @@ -2727,6 +2728,18 @@ func (o *Orchestrator) resolveOrchestratorRequest(req TurnRequest) TurnRequest { // selectAdapter resolves whether provider runs on the built-in Go morphcode harness // or the provider's official local CLI adapter. func (o *Orchestrator) selectAdapter(provider model.Provider, req TurnRequest) (Adapter, bool) { + // Antigravity (agy) always runs through the official local `agy acp` CLI adapter. + if provider == model.ProviderAgy { + if a, ok := o.NativeCLIAdapters[model.ProviderAgy]; ok && a != nil { + return a, true + } + if a, ok := o.Adapters[model.ProviderAgy]; ok && a != nil { + if _, isNative := a.(*NativeAdapter); !isNative { + return a, true + } + } + return nil, false + } if req.IsOrchestrator || provider == model.ProviderOrchestrator { if na := o.findNativeAdapter(); na != nil { return na, true diff --git a/morphcode/internal/harness/agy_acp.go b/morphcode/internal/harness/agy_acp.go new file mode 100644 index 00000000..c1342ee7 --- /dev/null +++ b/morphcode/internal/harness/agy_acp.go @@ -0,0 +1,1483 @@ +package harness + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "path/filepath" + "slices" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/anymorph-ai/morph-code/morphcode/internal/model" +) + +// AgyMode maps Morph Code's access mode to Antigravity CLI's ACP mode id. +func AgyMode(mode model.AccessMode) string { + switch mode { + case model.AccessPlan: + return "plan" + case model.AccessFullAccess: + return "auto" + default: + return "default" + } +} + +// AgyACPAdapter drives the user's locally installed official `agy acp` CLI over bidirectional +// JSON-RPC stdio using their own local `agy` authentication. It supports session reuse/resume, +// live thinking/text/tool streaming, interactive permission & elicitation dialogs, clean +// cancellation (`session/cancel`), native `/compact`, and dynamic model discovery. +type AgyACPAdapter struct { + BinaryPath string + mu sync.Mutex + warm *warmAgyWorker + starting chan struct{} + models []string +} + +type agySessionMeta struct { + sessionID string + cwd string + currentModelID string + availableModels []string + currentModeID string + availableModes []string + plugins pluginBinding + feedback string +} + +const ( + agyCancelGrace = 2 * time.Second + agyResumeTimeout = 15 * time.Second +) + +type warmAgyWorker struct { + client *JSONRPCClient + compactOverride string + mu sync.Mutex + sessions map[string]*agySessionState // sessionID -> active turn state + sessionMap map[string]*agySessionMeta // morphThreadID -> reusable ACP session + lastUsed time.Time +} + +type agySessionState struct { + ctx context.Context + req TurnRequest + emit EmitFunc + threadID string + text strings.Builder + title string + toolBlocks map[string]*model.TurnBlock + meta *agySessionMeta + contextUsed int64 + contextSize int64 + compactions int + inCompactCall bool +} + +func NewAgyACPAdapter(binaryPath string) *AgyACPAdapter { + if strings.TrimSpace(binaryPath) == "" { + if found := findOfficialCLI("agy"); found != "" { + binaryPath = found + } else { + binaryPath = "agy" + } + } + return &AgyACPAdapter{BinaryPath: binaryPath} +} + +// AvailableModels returns the cached list of model IDs discovered from the local `agy acp` worker. +func (a *AgyACPAdapter) AvailableModels() []string { + a.mu.Lock() + defer a.mu.Unlock() + if len(a.models) == 0 { + return nil + } + out := make([]string, len(a.models)) + copy(out, a.models) + return out +} + +// WarmUp pre-starts a warm `agy acp` worker and discovers available models in the background. +func (a *AgyACPAdapter) WarmUp(ctx context.Context, dataRoot string) { + ws := filepath.Join(dataRoot, "workspaces") + _ = os.MkdirAll(ws, 0o700) + req := TurnRequest{ + DataRoot: dataRoot, + WorkspacePath: ws, + } + w, err := a.getOrStartWorker(req) + if err != nil { + return + } + probeCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + sessRaw, err := w.client.Call(probeCtx, "session/new", map[string]any{ + "cwd": ws, + "mcpServers": []any{}, + }) + if err != nil { + return + } + meta := parseAgySessionNew(sessRaw, ws) + if len(meta.availableModels) > 0 { + a.mu.Lock() + a.models = meta.availableModels + a.mu.Unlock() + } +} + +func (a *AgyACPAdapter) getOrStartWorker(req TurnRequest) (*warmAgyWorker, error) { + for { + a.mu.Lock() + if existing := a.warm; existing != nil { + select { + case <-existing.client.closed: + a.warm = nil + default: + existing.mu.Lock() + busy := len(existing.sessions) > 0 + stale := existing.compactOverride != agyCompactOverride(req) + if !stale || busy { + existing.lastUsed = time.Now() + existing.mu.Unlock() + a.mu.Unlock() + return existing, nil + } + existing.mu.Unlock() + _ = existing.client.Close() + a.warm = nil + } + } + if waitCh := a.starting; waitCh != nil { + a.mu.Unlock() + <-waitCh + continue + } + done := make(chan struct{}) + a.starting = done + a.mu.Unlock() + + w, err := a.startWorker(req) + + a.mu.Lock() + a.starting = nil + if err == nil { + w.mu.Lock() + w.lastUsed = time.Now() + w.mu.Unlock() + a.warm = w + } + close(done) + a.mu.Unlock() + return w, err + } +} + +func (a *AgyACPAdapter) startWorker(req TurnRequest) (*warmAgyWorker, error) { + env := AugmentMemberToolchainEnv(MergeProjectEnv(os.Environ(), req.currentProjectEnv()), "") + compactOverride := agyCompactOverride(req) + env = filterEnv(env, map[string]bool{agyCompactOverrideEnv: true}) + if compactOverride != "" { + env = append(env, agyCompactOverrideEnv+"="+compactOverride) + } + + w := &warmAgyWorker{ + compactOverride: compactOverride, + sessions: make(map[string]*agySessionState), + sessionMap: make(map[string]*agySessionMeta), + lastUsed: time.Now(), + } + + bin := a.BinaryPath + if bin == "" || bin == "agy" { + if found := findOfficialCLI("agy"); found != "" { + bin = found + } else { + bin = "agy" + } + } + + var client *JSONRPCClient + var err error + client, err = StartBidirectionalJSONRPCProcess( + context.Background(), + bin, + []string{"acp"}, + req.WorkspacePath, + env, + func(method string, params json.RawMessage) { + a.handleAgyNotification(w, method, params) + }, + func(id json.RawMessage, method string, params json.RawMessage) { + a.handleAgyRequest(w, client, id, method, params) + }, + ) + if err != nil { + return nil, fmt.Errorf("start agy acp: %w", err) + } + w.client = client + + initCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if _, err := client.Call(initCtx, "initialize", map[string]any{ + "protocolVersion": 1, + "clientInfo": map[string]any{"name": "morphcode", "version": "4.0.0"}, + "clientCapabilities": map[string]any{ + "elicitation": map[string]any{"form": map[string]any{}}, + }, + }); err != nil { + _ = client.Close() + return nil, fmt.Errorf("agy acp initialize: %w", err) + } + + return w, nil +} + +func agyToolKind(rawKind, name, title string) string { + switch strings.ToLower(strings.TrimSpace(rawKind)) { + case "read": + return model.ToolKindRead + case "edit", "write": + return model.ToolKindEdit + case "search", "grep", "find": + return model.ToolKindSearch + case "execute", "command", "bash", "shell": + return model.ToolKindExecute + case "fetch", "web": + return model.ToolKindWeb + } + if isBrowserTool(name, title) { + return model.ToolKindBrowser + } + if isAgentTool(name, title) { + return model.ToolKindAgent + } + lowName := strings.ToLower(strings.TrimSpace(name)) + switch { + case strings.Contains(lowName, "read") || strings.Contains(lowName, "view_file"): + return model.ToolKindRead + case strings.Contains(lowName, "write") || strings.Contains(lowName, "edit") || strings.Contains(lowName, "replace"): + return model.ToolKindEdit + case strings.Contains(lowName, "grep") || strings.Contains(lowName, "search") || strings.Contains(lowName, "find") || strings.Contains(lowName, "list_dir"): + return model.ToolKindSearch + case strings.Contains(lowName, "command") || strings.Contains(lowName, "exec") || strings.Contains(lowName, "bash"): + return model.ToolKindExecute + } + return model.ToolKindOther +} + +func humanizeAgyTitle(kind, name, title string, input map[string]any) string { + if t := strings.TrimSpace(title); t != "" { + return t + } + if cmd := firstStringField(input, "CommandLine", "command"); cmd != "" { + return truncateStr(cmd, 80) + } + if p := firstStringField(input, "AbsolutePath", "TargetFile", "FilePath", "Path", "path", "file_path"); p != "" { + base := filepath.Base(p) + switch kind { + case model.ToolKindRead: + return "Read " + base + case model.ToolKindEdit: + return "Edit " + base + default: + return base + } + } + if n := strings.TrimSpace(name); n != "" { + return n + } + return "Tool call" +} + +func (a *AgyACPAdapter) handleAgyNotification(w *warmAgyWorker, method string, params json.RawMessage) { + if method != "session/update" { + return + } + var envelope struct { + SessionID string `json:"sessionId"` + Update json.RawMessage `json:"update"` + } + if err := json.Unmarshal(params, &envelope); err != nil { + return + } + var update struct { + SessionUpdate string `json:"sessionUpdate"` + Title string `json:"title"` + ToolCallID string `json:"toolCallId"` + Name string `json:"name"` + Status string `json:"status"` + Kind string `json:"kind"` + Content json.RawMessage `json:"content"` + RawInput map[string]any `json:"rawInput"` + Args map[string]any `json:"args"` + RawOutput any `json:"rawOutput"` + Used int64 `json:"used"` + Size int64 `json:"size"` + } + if err := json.Unmarshal(envelope.Update, &update); err != nil { + return + } + + w.mu.Lock() + state := w.sessions[envelope.SessionID] + if state == nil && envelope.SessionID == "" && len(w.sessions) == 1 { + for _, only := range w.sessions { + state = only + } + } + if state == nil { + w.mu.Unlock() + return + } + emit := state.emit + tid := state.threadID + nowTS := time.Now().UTC().Format(time.RFC3339) + + var emitEvs []model.StreamEvent + + switch update.SessionUpdate { + case "usage_update": + if update.Used > 0 { + prevUsed := state.contextUsed + state.contextUsed = update.Used + if update.Size > 0 { + state.contextSize = update.Size + } + window := state.contextSize + if window == 0 { + window = ContextWindowForModel(turnModelID(state.req)) + } + if !state.inCompactCall && prevUsed > 0 && prevUsed-update.Used >= 20_000 && update.Used*100 <= prevUsed*65 { + state.compactions++ + blk := model.TurnBlock{ + ID: fmt.Sprintf("blk-agy-compact-%d", state.compactions), + Kind: model.BlockCompaction, + Title: "Context compacted", + Status: "ok", + Compaction: &model.CompactionMeta{ + Trigger: "auto", + Native: true, + PreTokens: prevUsed, + PostTokens: update.Used, + }, + } + emitEvs = append(emitEvs, model.StreamEvent{Type: "compaction", ThreadID: tid, Block: &blk, Timestamp: nowTS}) + } + usage := &model.TokenUsage{ContextTokens: state.contextUsed, ContextWindow: window} + fillUsageEstimates(usage, turnModelID(state.req), 0, len(state.toolBlocks)) + emitEvs = append(emitEvs, tokenUsageEvent(tid, usage, nowTS)) + } + case "compaction", "context_compaction", "checkpoint": + status := normalizeToolStatus(update.Status) + if status == "" { + status = "ok" + } + title := "Context compacted" + if status == "running" { + title = "Compacting context" + } + id := strings.TrimSpace(update.ToolCallID) + if id == "" { + if status == "running" || state.compactions == 0 { + state.compactions++ + } + id = fmt.Sprintf("blk-agy-compact-%d", state.compactions) + } else { + id = "blk-agy-compact-" + sanitizeIdentifier(id) + } + blk := model.TurnBlock{ + ID: id, + Kind: model.BlockCompaction, + Title: title, + Status: status, + Compaction: &model.CompactionMeta{ + Trigger: "auto", + Native: true, + PreTokens: state.contextUsed, + PostTokens: update.Used, + }, + } + emitEvs = append(emitEvs, model.StreamEvent{Type: "compaction", ThreadID: tid, Block: &blk, Timestamp: nowTS}) + case "agent_message_chunk": + var c struct { + Type string `json:"type"` + Text string `json:"text"` + } + if json.Unmarshal(update.Content, &c) == nil && c.Text != "" { + state.text.WriteString(c.Text) + emitEvs = append(emitEvs, model.StreamEvent{ + Type: "delta", + ThreadID: tid, + Delta: c.Text, + Timestamp: nowTS, + }) + } + case "agent_thought_chunk": + var c struct { + Type string `json:"type"` + Text string `json:"text"` + } + if json.Unmarshal(update.Content, &c) == nil && c.Text != "" { + emitEvs = append(emitEvs, model.StreamEvent{ + Type: "thinking", + ThreadID: tid, + Delta: c.Text, + Timestamp: nowTS, + }) + } + case "session_info_update": + if t := strings.TrimSpace(update.Title); t != "" { + state.title = t + emitEvs = append(emitEvs, model.StreamEvent{ + Type: "session_title", + ThreadID: tid, + Title: t, + Timestamp: nowTS, + }) + } + case "tool_call", "tool_call_update": + callID := strings.TrimSpace(update.ToolCallID) + if callID == "" { + callID = fmt.Sprintf("agy-tool-%d", len(state.toolBlocks)+1) + } + inputMap := update.RawInput + if len(inputMap) == 0 { + inputMap = update.Args + } + blk, exists := state.toolBlocks[callID] + if !exists { + kind := model.BlockToolCall + if strings.EqualFold(update.Kind, "execute") || strings.EqualFold(update.Name, "run_command") { + kind = model.BlockTerminal + } + tKind := agyToolKind(update.Kind, update.Name, update.Title) + tProvider := webToolProvider(update.Name, update.Title) + title := humanizeAgyTitle(tKind, update.Name, update.Title, inputMap) + blk = &model.TurnBlock{ + ID: "blk-" + sanitizeIdentifier(callID), + Kind: kind, + ToolCallID: callID, + ToolName: update.Name, + ToolKind: tKind, + ToolProvider: tProvider, + Title: title, + Status: normalizeToolStatus(update.Status), + } + state.toolBlocks[callID] = blk + } + if update.Name != "" { + blk.ToolName = update.Name + } + if update.Kind != "" || update.Name != "" || update.Title != "" || len(inputMap) > 0 { + blk.ToolKind = agyToolKind(update.Kind, blk.ToolName, update.Title) + blk.ToolProvider = webToolProvider(blk.ToolName, update.Title) + } + if update.Title != "" || len(inputMap) > 0 { + rawTitle := update.Title + if rawTitle == "" { + rawTitle = blk.Title + } + if cleaned := humanizeAgyTitle(blk.ToolKind, blk.ToolName, rawTitle, inputMap); cleaned != "" || update.Title != "" { + blk.Title = cleaned + } + } + if update.Status != "" { + blk.Status = normalizeToolStatus(update.Status) + } + if cmdStr, ok := inputMap["CommandLine"].(string); ok && cmdStr != "" { + blk.Kind = model.BlockTerminal + blk.ToolKind = model.ToolKindExecute + blk.Command = cmdStr + } else if cmdStr, ok := inputMap["command"].(string); ok && cmdStr != "" { + blk.Kind = model.BlockTerminal + blk.ToolKind = model.ToolKindExecute + blk.Command = cmdStr + } + if p := firstStringField(inputMap, "AbsolutePath", "TargetFile", "FilePath", "Path", "path", "file_path"); p != "" { + blk.FilePath = p + } + if outText := extractToolOutputText(update.RawOutput, update.Content); outText != "" { + if blk.Kind == model.BlockTerminal { + blk.Stdout = truncateStr(outText, 12000) + } else { + blk.Content = truncateStr(outText, 4000) + } + } + blkCopy := *blk + evType := "tool_call" + if blk.Kind == model.BlockTerminal { + evType = "terminal" + } + emitEvs = append(emitEvs, model.StreamEvent{ + Type: evType, + ThreadID: tid, + Block: &blkCopy, + Timestamp: nowTS, + }) + } + w.mu.Unlock() + + if emit != nil { + for _, ev := range emitEvs { + emit(ev) + } + } +} + +func (a *AgyACPAdapter) handleAgyRequest(w *warmAgyWorker, client *JSONRPCClient, id json.RawMessage, method string, params json.RawMessage) { + if method == "elicitation/create" { + a.handleAgyElicitation(w, client, id, params) + return + } + if method != "session/request_permission" { + _ = client.RespondError(id, -32601, "unsupported client request: "+method) + return + } + var req struct { + SessionID string `json:"sessionId"` + ToolCall struct { + Title string `json:"title"` + Kind string `json:"kind"` + ToolCall string `json:"toolCallId"` + RawInput map[string]any `json:"rawInput"` + } `json:"toolCall"` + Options []struct { + OptionID string `json:"optionId"` + Name string `json:"name"` + Kind string `json:"kind"` + } `json:"options"` + } + _ = json.Unmarshal(params, &req) + + pickOption := func(preferKinds ...string) string { + for _, want := range preferKinds { + for _, opt := range req.Options { + if strings.EqualFold(opt.Kind, want) { + return opt.OptionID + } + } + } + if len(req.Options) > 0 { + return req.Options[0].OptionID + } + return "allow_once" + } + + w.mu.Lock() + state := w.sessions[req.SessionID] + if state == nil && len(w.sessions) == 1 { + for _, only := range w.sessions { + state = only + } + } + w.mu.Unlock() + + decision := model.ApprovalAllowOnce + reason := "" + if state != nil { + switch state.req.AccessMode { + case model.AccessFullAccess: + decision = model.ApprovalAllowThread + case model.AccessPlan: + if strings.EqualFold(req.ToolCall.Kind, "read") || strings.EqualFold(req.ToolCall.Kind, "search") { + decision = model.ApprovalAllowOnce + } else { + decision = model.ApprovalDenied + } + default: + if state.req.hasApprovalHandler() { + actionKind := "tool_execution" + if strings.EqualFold(req.ToolCall.Kind, "execute") { + actionKind = "tool_command" + } else if strings.EqualFold(req.ToolCall.Kind, "edit") { + actionKind = "tool_file_change" + } + title := strings.TrimSpace(req.ToolCall.Title) + if title == "" { + title = "Tool execution approval" + } + payloadBytes, _ := json.Marshal(req.ToolCall.RawInput) + tar := ToolApprovalRequest{ + ThreadID: state.req.ThreadID, + ProjectID: state.req.ProjectID, + MemberID: state.req.MemberID, + Target: state.req.ExecutionTarget, + ActionKind: actionKind, + Title: title, + Summary: fmt.Sprintf("Antigravity wants to run %s.", title), + Payload: string(payloadBytes), + } + if cmd := firstStringField(req.ToolCall.RawInput, "CommandLine", "command"); cmd != "" { + tar.CommandPreview = NormalizeCommandPreview(cmd) + tar.CommandPrefix = CommandPrefixOf(cmd) + } + if actionKind == "tool_file_change" { + path := firstStringField(req.ToolCall.RawInput, "TargetFile", "AbsolutePath", "FilePath", "path", "file_path") + tar.DiffPreview = diffPreviewFromInput(path, req.ToolCall.RawInput) + } + outcome, err := state.req.requestApproval(state.ctx, tar) + if err != nil { + decision = model.ApprovalDenied + } else { + decision = outcome.Decision + reason = strings.TrimSpace(outcome.Reason) + } + } + } + } + + var optionID string + switch decision { + case model.ApprovalAllowThread: + optionID = pickOption("allow_always", "allow_once") + case model.ApprovalAllowOnce, model.ApprovalAllowPrefix: + optionID = pickOption("allow_once", "allow_always") + default: + optionID = pickOption("reject_once", "reject_always") + if reason != "" && state != nil { + w.mu.Lock() + if state.meta != nil { + state.meta.feedback = reason + } + w.mu.Unlock() + } + } + + response := map[string]any{ + "outcome": map[string]any{ + "outcome": "selected", + "optionId": optionID, + }, + } + if reason != "" { + response["_meta"] = map[string]any{"morph/rejectionReason": denialMessage(reason)} + } + _ = client.Respond(id, response) +} + +func (a *AgyACPAdapter) handleAgyElicitation(w *warmAgyWorker, client *JSONRPCClient, id json.RawMessage, params json.RawMessage) { + var req struct { + SessionID string `json:"sessionId"` + Message string `json:"message"` + Mode string `json:"mode"` + RequestedSchema struct { + Properties map[string]json.RawMessage `json:"properties"` + Required []string `json:"required"` + } `json:"requestedSchema"` + } + _ = json.Unmarshal(params, &req) + + w.mu.Lock() + state := w.sessions[req.SessionID] + if state == nil && len(w.sessions) == 1 { + for _, only := range w.sessions { + state = only + } + } + w.mu.Unlock() + + questions, otherFields := parseAgyElicitationSchema(req.RequestedSchema.Properties) + if state == nil || state.req.QuestionHandler == nil || len(questions) == 0 { + _ = client.Respond(id, map[string]any{"action": "decline"}) + return + } + + resp, err := state.req.QuestionHandler(state.ctx, UserQuestionRequest{ + ThreadID: state.req.ThreadID, + ProjectID: state.req.ProjectID, + MemberID: state.req.MemberID, + Title: "Input required", + Message: strings.TrimSpace(req.Message), + Questions: questions, + }) + if err != nil || !strings.EqualFold(resp.Action, "accept") { + _ = client.Respond(id, map[string]any{"action": "decline"}) + return + } + + content := encodeAgyElicitationAnswers(questions, otherFields, resp.Answers) + _ = client.Respond(id, map[string]any{ + "action": "accept", + "content": content, + }) +} + +func parseAgyElicitationSchema(props map[string]json.RawMessage) ([]model.QuestionItem, map[string]string) { + if len(props) == 0 { + return nil, nil + } + type propSchema struct { + Type string `json:"type"` + Title string `json:"title"` + Description string `json:"description"` + Format string `json:"format"` + IsSecret bool `json:"isSecret"` + Secret bool `json:"secret"` + WriteOnly bool `json:"writeOnly"` + Enum []string `json:"enum"` + OneOf []struct { + Const string `json:"const"` + Title string `json:"title"` + Description string `json:"description"` + } `json:"oneOf"` + Items *struct { + Type string `json:"type"` + Enum []string `json:"enum"` + AnyOf []struct { + Const string `json:"const"` + Title string `json:"title"` + Description string `json:"description"` + } `json:"anyOf"` + OneOf []struct { + Const string `json:"const"` + Title string `json:"title"` + Description string `json:"description"` + } `json:"oneOf"` + } `json:"items"` + } + + otherFields := make(map[string]string) + keys := make([]string, 0, len(props)) + for k := range props { + if strings.HasSuffix(k, "_other") { + base := strings.TrimSuffix(k, "_other") + if _, hasBase := props[base]; hasBase { + otherFields[base] = k + continue + } + } + keys = append(keys, k) + } + sort.Slice(keys, func(i, j int) bool { + ni, ei := strconv.Atoi(strings.TrimPrefix(keys[i], "q")) + nj, ej := strconv.Atoi(strings.TrimPrefix(keys[j], "q")) + if ei == nil && ej == nil && strings.HasPrefix(keys[i], "q") && strings.HasPrefix(keys[j], "q") { + return ni < nj + } + return keys[i] < keys[j] + }) + + questions := make([]model.QuestionItem, 0, len(keys)) + for _, k := range keys { + var ps propSchema + if json.Unmarshal(props[k], &ps) != nil { + continue + } + q := model.QuestionItem{ + ID: k, + Question: strings.TrimSpace(ps.Title), + AllowOther: otherFields[k] != "", + IsSecret: ps.IsSecret || ps.Secret || ps.WriteOnly || strings.EqualFold(strings.TrimSpace(ps.Format), "password"), + } + if q.Question == "" { + q.Question = strings.TrimSpace(ps.Description) + } + if q.Question == "" { + q.Question = k + } + if ps.Type == "array" { + q.MultiSelect = true + if ps.Items != nil { + for _, opt := range ps.Items.AnyOf { + label := strings.TrimSpace(opt.Title) + if label == "" { + label = opt.Const + } + q.Options = append(q.Options, model.QuestionOption{ + Value: opt.Const, + Label: label, + Description: strings.TrimSpace(opt.Description), + }) + } + if len(q.Options) == 0 { + for _, opt := range ps.Items.OneOf { + label := strings.TrimSpace(opt.Title) + if label == "" { + label = opt.Const + } + q.Options = append(q.Options, model.QuestionOption{ + Value: opt.Const, + Label: label, + Description: strings.TrimSpace(opt.Description), + }) + } + } + if len(q.Options) == 0 { + for _, v := range ps.Items.Enum { + q.Options = append(q.Options, model.QuestionOption{Value: v, Label: v}) + } + } + } + } else { + for _, opt := range ps.OneOf { + label := strings.TrimSpace(opt.Title) + if label == "" { + label = opt.Const + } + q.Options = append(q.Options, model.QuestionOption{ + Value: opt.Const, + Label: label, + Description: strings.TrimSpace(opt.Description), + }) + } + if len(q.Options) == 0 { + for _, v := range ps.Enum { + q.Options = append(q.Options, model.QuestionOption{Value: v, Label: v}) + } + } + } + if len(q.Options) == 0 { + q.AllowOther = true + } + questions = append(questions, q) + } + return questions, otherFields +} + +func encodeAgyElicitationAnswers(questions []model.QuestionItem, otherFields map[string]string, answers map[string][]string) map[string]any { + content := make(map[string]any) + for _, q := range questions { + vals := answers[q.ID] + if len(vals) == 0 { + continue + } + optVals := make(map[string]bool, len(q.Options)) + for _, opt := range q.Options { + optVals[opt.Value] = true + } + var selected []string + var custom []string + for _, raw := range vals { + v := strings.TrimSpace(raw) + if v == "" { + continue + } + if strings.HasPrefix(v, "other:") { + if txt := strings.TrimSpace(strings.TrimPrefix(v, "other:")); txt != "" { + custom = append(custom, txt) + } + continue + } + if len(optVals) == 0 || !optVals[v] { + custom = append(custom, v) + } else { + selected = append(selected, v) + } + } + if q.MultiSelect { + if len(selected) > 0 { + content[q.ID] = selected + } + } else if len(q.Options) > 0 { + if len(selected) > 0 { + content[q.ID] = selected[0] + } + } else if len(custom) > 0 { + content[q.ID] = strings.Join(custom, ", ") + } + if otherKey := otherFields[q.ID]; otherKey != "" && len(custom) > 0 { + content[otherKey] = strings.Join(custom, ", ") + } + } + return content +} + +func parseAgySessionNew(sessRaw json.RawMessage, cwd string) *agySessionMeta { + var sess struct { + SessionID string `json:"sessionId"` + Models struct { + CurrentModelID string `json:"currentModelId"` + AvailableModels []struct { + ModelID string `json:"modelId"` + } `json:"availableModels"` + } `json:"models"` + Modes struct { + CurrentModeID string `json:"currentModeId"` + AvailableModes []struct { + ID string `json:"id"` + } `json:"availableModes"` + } `json:"modes"` + } + _ = json.Unmarshal(sessRaw, &sess) + models := make([]string, 0, len(sess.Models.AvailableModels)) + for _, m := range sess.Models.AvailableModels { + if m.ModelID != "" { + models = append(models, m.ModelID) + } + } + modes := make([]string, 0, len(sess.Modes.AvailableModes)) + for _, m := range sess.Modes.AvailableModes { + if m.ID != "" { + modes = append(modes, m.ID) + } + } + return &agySessionMeta{ + sessionID: sess.SessionID, + cwd: cwd, + currentModelID: sess.Models.CurrentModelID, + availableModels: models, + currentModeID: sess.Modes.CurrentModeID, + availableModes: modes, + } +} + +var agyTiers = []model.ReasoningEffort{model.EffortLow, model.EffortMedium, model.EffortHigh, model.EffortXHigh} + +func agyBase(id string) string { + for _, tier := range agyTiers { + if base, ok := strings.CutSuffix(id, "-"+string(tier)); ok { + return base + } + } + return id +} + +// AgyEfforts returns the effort tiers supported by an agy model id given the available list. +func AgyEfforts(id string, available []string) []model.ReasoningEffort { + efforts := []model.ReasoningEffort{} + base := agyBase(id) + if base == id { + return efforts + } + for _, tier := range agyTiers { + if slices.Contains(available, base+"-"+string(tier)) { + efforts = append(efforts, tier) + } + } + return efforts +} + +func extractEffortSuffix(modelID string, fallback model.ReasoningEffort) string { + for _, suf := range []string{"-xhigh", "-high", "-medium", "-low"} { + if strings.HasSuffix(strings.ToLower(modelID), suf) { + return strings.TrimPrefix(suf, "-") + } + } + if fallback != "" { + return string(fallback) + } + return "high" +} + +func resolveAgyModelID(wireModel string, effort model.ReasoningEffort, available []string, current string) string { + target := strings.TrimSpace(wireModel) + if len(available) == 0 { + return target + } + if target == "" { + return current + } + has := func(id string) bool { + return slices.Contains(available, id) + } + base := agyBase(target) + if tiers := AgyEfforts(target, available); effort.Valid() && len(tiers) > 0 { + return base + "-" + string(effort.Nearest(tiers)) + } + if has(target) { + return target + } + eff := extractEffortSuffix(target, effort) + for _, candidateEff := range []string{eff, "high", "medium", "low"} { + if has(base + "-" + candidateEff) { + return base + "-" + candidateEff + } + } + if current != "" && has(current) { + return current + } + return available[0] +} + +func (a *AgyACPAdapter) RunTurn(ctx context.Context, req TurnRequest, emit EmitFunc) (*TurnResult, error) { + w, err := a.getOrStartWorker(req) + if err != nil { + return nil, err + } + + createNewSession := func() (*agySessionMeta, error) { + mcpServers := loadACPMCPServers(req) + sessRaw, sErr := w.client.Call(ctx, "session/new", map[string]any{ + "cwd": req.WorkspacePath, + "mcpServers": mcpServers, + }) + if sErr != nil { + return nil, sErr + } + meta := parseAgySessionNew(sessRaw, req.WorkspacePath) + if meta.sessionID == "" { + return nil, errors.New("agy acp session/new returned empty sessionId") + } + meta.plugins = pluginBindingOf(req) + if len(meta.availableModels) > 0 { + a.mu.Lock() + a.models = meta.availableModels + a.mu.Unlock() + } + if req.ThreadID != "" { + w.mu.Lock() + w.sessionMap[req.ThreadID] = meta + w.mu.Unlock() + } + sessionProvider := model.ProviderAgy + if req.IsOrchestrator { + sessionProvider = model.ProviderOrchestrator + } + req.reportSession(sessionProvider, meta.sessionID, "") + return meta, nil + } + + var meta *agySessionMeta + reused := false + if req.ThreadID != "" { + w.mu.Lock() + existing := w.sessionMap[req.ThreadID] + w.mu.Unlock() + if existing != nil && existing.sessionID != "" && existing.cwd == req.WorkspacePath { + meta = existing + reused = true + } + } + if meta == nil && req.ThreadID != "" && strings.TrimSpace(req.ResumeSessionID) != "" { + if resumed, rErr := a.resumeSession(ctx, w, req); rErr == nil { + meta = resumed + reused = true + } else { + log.Printf("agy: thread %s starts a new session, resuming %s failed: %v", req.ThreadID, req.ResumeSessionID, rErr) + } + } + if reused && pluginsStale(meta.plugins, req) { + if _, err := w.client.Call(ctx, "session/resume", map[string]any{ + "sessionId": meta.sessionID, + "cwd": req.WorkspacePath, + "mcpServers": loadACPMCPServers(req), + }); err != nil { + log.Printf("agy: thread %s keeps previous plugin binding, session/resume failed: %v", req.ThreadID, err) + } else { + meta.plugins = pluginBindingOf(req) + } + } + if meta == nil { + var sErr error + meta, sErr = createNewSession() + if sErr != nil { + return &TurnResult{RateLimited: isRateLimitError(sErr)}, sErr + } + } + + applyModelAndMode := func(m *agySessionMeta) error { + targetModel := resolveAgyModelID(req.WireModel, req.ReasoningEffort, m.availableModels, m.currentModelID) + if targetModel != "" && targetModel != m.currentModelID { + if _, err := w.client.Call(ctx, "session/set_model", map[string]any{ + "sessionId": m.sessionID, + "modelId": targetModel, + }); err != nil { + return fmt.Errorf("agy acp set_model %s: %w", targetModel, err) + } + m.currentModelID = targetModel + } + if req.AccessMode != "" { + targetMode := AgyMode(req.AccessMode) + if targetMode != m.currentModeID { + if _, err := w.client.Call(ctx, "session/set_mode", map[string]any{ + "sessionId": m.sessionID, + "modeId": targetMode, + }); err != nil { + if req.AccessMode == model.AccessFullAccess && targetMode == "auto" { + if m.currentModeID != "accept-edits" { + if _, fbErr := w.client.Call(ctx, "session/set_mode", map[string]any{ + "sessionId": m.sessionID, + "modeId": "accept-edits", + }); fbErr == nil { + m.currentModeID = "accept-edits" + } + } + } else { + return fmt.Errorf("agy acp set_mode %s: %w", targetMode, err) + } + } else { + m.currentModeID = targetMode + } + } + } + return nil + } + + if err := applyModelAndMode(meta); err != nil { + if reused { + if fresh, fErr := createNewSession(); fErr == nil { + meta = fresh + reused = false + if err2 := applyModelAndMode(meta); err2 != nil { + return &TurnResult{RateLimited: isRateLimitError(err2)}, err2 + } + } else { + return &TurnResult{RateLimited: isRateLimitError(err)}, err + } + } else { + return &TurnResult{RateLimited: isRateLimitError(err)}, err + } + } + + state := &agySessionState{ + ctx: ctx, + req: req, + emit: emit, + threadID: req.ThreadID, + toolBlocks: make(map[string]*model.TurnBlock), + meta: meta, + } + w.mu.Lock() + w.sessions[meta.sessionID] = state + feedback := meta.feedback + meta.feedback = "" + w.mu.Unlock() + defer func() { + w.mu.Lock() + delete(w.sessions, meta.sessionID) + w.mu.Unlock() + }() + + promptText := req.Prompt + if !reused { + promptText = PromptWithHistory(req.HistorySummary, req.Prompt) + } + if feedback != "" { + promptText = "[Previous denial feedback] " + feedback + "\n\n" + promptText + } + promptParts := []map[string]any{{"type": "text", "text": promptText}} + for _, img := range req.Images { + if b64, mimeType, ok := encodeImageBase64(img); ok { + promptParts = append(promptParts, map[string]any{ + "type": "image", + "data": b64, + "mimeType": mimeType, + }) + } + } + + promptParams := map[string]any{ + "sessionId": meta.sessionID, + "prompt": promptParts, + } + + promptCtx, abandonPrompt := context.WithCancel(context.Background()) + defer abandonPrompt() + promptDone := make(chan struct{}) + go func(sessID string) { + select { + case <-ctx.Done(): + _ = w.client.Notify("session/cancel", map[string]any{"sessionId": sessID}) + select { + case <-promptDone: + case <-time.After(agyCancelGrace): + if req.ThreadID != "" { + w.mu.Lock() + if cur := w.sessionMap[req.ThreadID]; cur != nil && cur.sessionID == sessID { + delete(w.sessionMap, req.ThreadID) + } + w.mu.Unlock() + } + abandonPrompt() + } + case <-promptDone: + } + }(meta.sessionID) + promptRaw, err := w.client.Call(promptCtx, "session/prompt", promptParams) + close(promptDone) + if ctx.Err() != nil { + return nil, ctx.Err() + } + if err != nil { + if reused && strings.Contains(strings.ToLower(err.Error()), "session") { + w.mu.Lock() + delete(w.sessionMap, req.ThreadID) + w.mu.Unlock() + } + return &TurnResult{RateLimited: isRateLimitError(err)}, err + } + + w.mu.Lock() + text := strings.TrimSpace(state.text.String()) + title := strings.TrimSpace(state.title) + contextUsed, contextSize := state.contextUsed, state.contextSize + toolSteps := len(state.toolBlocks) + w.mu.Unlock() + + var promptRes struct { + Usage *struct { + TotalTokens int64 `json:"totalTokens"` + InputTokens int64 `json:"inputTokens"` + OutputTokens int64 `json:"outputTokens"` + CachedReadTokens int64 `json:"cachedReadTokens"` + ThoughtTokens int64 `json:"thoughtTokens"` + ThinkingTokens int64 `json:"thinkingTokens"` + } `json:"usage"` + TokenUsage *struct { + TotalTokens int64 `json:"totalTokens"` + InputTokens int64 `json:"inputTokens"` + OutputTokens int64 `json:"outputTokens"` + ThoughtTokens int64 `json:"thoughtTokens"` + ThinkingTokens int64 `json:"thinkingTokens"` + } `json:"tokenUsage"` + } + _ = json.Unmarshal(promptRaw, &promptRes) + + estTokens := int64(len(promptText)+len(text)) / 3 + var usage *model.TokenUsage + if u := promptRes.Usage; u != nil { + if u.TotalTokens > 0 { + estTokens = u.TotalTokens + } + reasoning := max(u.ThoughtTokens, u.ThinkingTokens) + usage = &model.TokenUsage{ + InputTokens: u.InputTokens, + OutputTokens: u.OutputTokens, + ReasoningTokens: reasoning, + CacheReadTokens: u.CachedReadTokens, + } + if usage.InputTokens == 0 && usage.OutputTokens == 0 { + usage.InputTokens = u.TotalTokens + } + } else if u := promptRes.TokenUsage; u != nil { + if u.TotalTokens > 0 { + estTokens = u.TotalTokens + } + reasoning := max(u.ThoughtTokens, u.ThinkingTokens) + usage = &model.TokenUsage{ + InputTokens: u.InputTokens, + OutputTokens: u.OutputTokens, + ReasoningTokens: reasoning, + } + } + if usage == nil && contextUsed > 0 { + usage = &model.TokenUsage{} + } + if usage != nil { + usage.ContextTokens = contextUsed + if usage.ContextTokens == 0 { + visibleOut := max(usage.OutputTokens-usage.ReasoningTokens, 0) + usage.ContextTokens = usage.InputTokens + usage.CacheReadTokens + visibleOut + } + usage.ContextWindow = contextSize + if usage.ContextWindow == 0 { + usage.ContextWindow = ContextWindowForModel("agy/" + meta.currentModelID) + } + costModel := "agy/" + meta.currentModelID + if meta.currentModelID == "" && turnModelID(req) != "" { + costModel = turnModelID(req) + } + fillUsageEstimates(usage, costModel, usage.CacheReadTokens, toolSteps) + if emit != nil { + emit(tokenUsageEvent(req.ThreadID, usage, time.Now().UTC().Format(time.RFC3339))) + } + } + actualModel := "" + if meta.currentModelID != "" { + actualModel = "agy/" + meta.currentModelID + } + return &TurnResult{ + ResponseText: text, + EstimatedTokens: estTokens, + ActualModelID: actualModel, + SessionTitle: title, + SessionID: meta.sessionID, + Usage: usage, + }, nil +} + +func (a *AgyACPAdapter) resumeSession(ctx context.Context, w *warmAgyWorker, req TurnRequest) (*agySessionMeta, error) { + sessionID := strings.TrimSpace(req.ResumeSessionID) + params := map[string]any{ + "sessionId": sessionID, + "cwd": req.WorkspacePath, + "mcpServers": loadACPMCPServers(req), + } + var lastErr error + for _, method := range []string{"session/resume", "session/load"} { + callCtx, cancel := context.WithTimeout(ctx, agyResumeTimeout) + raw, err := w.client.Call(callCtx, method, params) + cancel() + if err != nil { + lastErr = err + if ctx.Err() != nil { + return nil, ctx.Err() + } + continue + } + meta := parseAgySessionNew(raw, req.WorkspacePath) + meta.sessionID = sessionID + meta.plugins = pluginBindingOf(req) + if len(meta.availableModels) > 0 { + a.mu.Lock() + a.models = meta.availableModels + a.mu.Unlock() + } + w.mu.Lock() + w.sessionMap[req.ThreadID] = meta + w.mu.Unlock() + return meta, nil + } + return nil, lastErr +} + +func (a *AgyACPAdapter) Close() error { + a.mu.Lock() + defer a.mu.Unlock() + if a.warm != nil { + _ = a.warm.client.Close() + a.warm = nil + } + return nil +} + +func (a *AgyACPAdapter) EvictIdle(maxIdle time.Duration) int { + if maxIdle <= 0 { + return 0 + } + now := time.Now() + a.mu.Lock() + defer a.mu.Unlock() + w := a.warm + if w == nil { + return 0 + } + w.mu.Lock() + busy := len(w.sessions) > 0 + idle := !w.lastUsed.IsZero() && now.Sub(w.lastUsed) >= maxIdle + w.mu.Unlock() + if !busy && idle { + _ = w.client.Close() + a.warm = nil + return 1 + } + return 0 +} + +const agyCompactOverrideEnv = "AGY_CLI_AUTO_COMPACT_OVERRIDE" + +func agyCompactOverride(req TurnRequest) string { + if req.AutoCompactEnabled != nil && !*req.AutoCompactEnabled { + return "" + } + if req.AutoCompactTokens <= 0 { + return "" + } + return strconv.FormatInt(req.AutoCompactTokens, 10) +} + +func (a *AgyACPAdapter) HasNativeAutoCompact() bool { return true } + +func (a *AgyACPAdapter) Compact(ctx context.Context, req TurnRequest) (*CompactResult, error) { + w, err := a.getOrStartWorker(req) + if err != nil { + return nil, err + } + w.mu.Lock() + meta := w.sessionMap[req.ThreadID] + w.mu.Unlock() + if meta == nil && strings.TrimSpace(req.ResumeSessionID) != "" { + resumed, rErr := a.resumeSession(ctx, w, req) + if rErr != nil { + return nil, fmt.Errorf("%w: %v", ErrCompactUnsupported, rErr) + } + meta = resumed + } + if meta == nil || strings.TrimSpace(meta.sessionID) == "" { + return nil, ErrCompactUnsupported + } + state := &agySessionState{ + ctx: ctx, + req: req, + threadID: req.ThreadID, + toolBlocks: make(map[string]*model.TurnBlock), + meta: meta, + inCompactCall: true, + } + w.mu.Lock() + w.sessions[meta.sessionID] = state + w.mu.Unlock() + defer func() { + w.mu.Lock() + delete(w.sessions, meta.sessionID) + w.mu.Unlock() + }() + + compactPrompt := "/compact" + if focus := strings.TrimSpace(req.Prompt); focus != "" { + if strings.HasPrefix(focus, "/compact") { + compactPrompt = focus + } else { + compactPrompt = "/compact " + focus + } + } + promptRaw, err := w.client.Call(ctx, "session/prompt", map[string]any{ + "sessionId": meta.sessionID, + "prompt": []map[string]any{{"type": "text", "text": compactPrompt}}, + }) + if err != nil { + return nil, err + } + w.mu.Lock() + contextUsed, contextSize := state.contextUsed, state.contextSize + w.mu.Unlock() + + var promptRes struct { + Usage *struct { + TotalTokens int64 `json:"totalTokens"` + InputTokens int64 `json:"inputTokens"` + OutputTokens int64 `json:"outputTokens"` + CachedReadTokens int64 `json:"cachedReadTokens"` + ThoughtTokens int64 `json:"thoughtTokens"` + ThinkingTokens int64 `json:"thinkingTokens"` + } `json:"usage"` + } + _ = json.Unmarshal(promptRaw, &promptRes) + + var usage *model.TokenUsage + if u := promptRes.Usage; u != nil { + reasoning := max(u.ThoughtTokens, u.ThinkingTokens) + usage = &model.TokenUsage{ + InputTokens: u.InputTokens, + OutputTokens: u.OutputTokens, + ReasoningTokens: reasoning, + CacheReadTokens: u.CachedReadTokens, + } + } + if usage == nil && contextUsed > 0 { + usage = &model.TokenUsage{} + } + var postTokens int64 + if usage != nil { + usage.ContextTokens = contextUsed + if usage.ContextTokens == 0 { + usage.ContextTokens = usage.InputTokens + usage.CacheReadTokens + max(usage.OutputTokens-usage.ReasoningTokens, 0) + } + usage.ContextWindow = contextSize + if usage.ContextWindow == 0 { + usage.ContextWindow = ContextWindowForModel(turnModelID(req)) + } + fillUsageEstimates(usage, turnModelID(req), usage.CacheReadTokens, 0) + postTokens = usage.ContextTokens + } + return &CompactResult{PostTokens: postTokens, Usage: usage}, nil +} + +func (a *AgyACPAdapter) ResetThread(threadID string) { + a.mu.Lock() + defer a.mu.Unlock() + if a.warm != nil { + a.warm.mu.Lock() + delete(a.warm.sessionMap, threadID) + a.warm.mu.Unlock() + } +} diff --git a/morphcode/internal/harness/agy_acp_test.go b/morphcode/internal/harness/agy_acp_test.go new file mode 100644 index 00000000..99322f71 --- /dev/null +++ b/morphcode/internal/harness/agy_acp_test.go @@ -0,0 +1,94 @@ +package harness + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/anymorph-ai/morph-code/morphcode/internal/model" +) + +func TestAgyACPAdapterTurnAndModelDiscovery(t *testing.T) { + tmp := t.TempDir() + fakeBin := filepath.Join(tmp, "fake-agy") + script := `#!/bin/sh +while IFS= read -r line; do + id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) + printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1}}\n' "$id" + ;; + *'"method":"session/new"'*) + printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"agy-sess-1","models":{"currentModelId":"gemini-4-neon-medium","availableModels":[{"modelId":"gemini-4-neon-low"},{"modelId":"gemini-4-neon-medium"},{"modelId":"gemini-4-neon-high"}]},"modes":{"currentModeId":"default","availableModes":[{"id":"default"},{"id":"plan"},{"id":"auto"}]}}}\n' "$id" + ;; + *'"method":"session/set_model"'*) + printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" + ;; + *'"method":"session/set_mode"'*) + printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" + ;; + *'"method":"session/prompt"'*) + printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"agy-sess-1","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Inspecting repo"}}}}\n' + printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"agy-sess-1","update":{"sessionUpdate":"tool_call","toolCallId":"tc-1","name":"read_file","kind":"read","title":"Read main.go","status":"completed"}}}\n' + printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"agy-sess-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello from official agy ACP."}}}}\n' + printf '{"jsonrpc":"2.0","id":%s,"result":{"usage":{"inputTokens":120,"outputTokens":40,"totalTokens":160}}}\n' "$id" + ;; + esac +done +` + if err := os.WriteFile(fakeBin, []byte(script), 0o755); err != nil { + t.Fatalf("write fake agy: %v", err) + } + + adapter := NewAgyACPAdapter(fakeBin) + defer adapter.Close() + + var events []model.StreamEvent + res, err := adapter.RunTurn(context.Background(), TurnRequest{ + ThreadID: "th-agy-1", + WorkspacePath: tmp, + DataRoot: tmp, + WireModel: "gemini-4-neon-medium", + ReasoningEffort: model.EffortHigh, + AccessMode: model.AccessFullAccess, + Prompt: "Say hello", + }, func(ev model.StreamEvent) { + events = append(events, ev) + }) + if err != nil { + t.Fatalf("RunTurn failed: %v", err) + } + if res.ResponseText != "Hello from official agy ACP." { + t.Fatalf("unexpected response text: %q", res.ResponseText) + } + if res.ActualModelID != "agy/gemini-4-neon-high" { + t.Fatalf("expected effort-resolved model agy/gemini-4-neon-high, got %q", res.ActualModelID) + } + if res.SessionID != "agy-sess-1" { + t.Fatalf("unexpected session id: %q", res.SessionID) + } + avail := adapter.AvailableModels() + if len(avail) != 3 { + t.Fatalf("expected 3 discovered models, got %v", avail) + } + var sawThinking, sawTool, sawDelta bool + for _, ev := range events { + switch ev.Type { + case "thinking": + if strings.Contains(ev.Delta, "Inspecting") { + sawThinking = true + } + case "tool_call": + sawTool = true + case "delta": + if strings.Contains(ev.Delta, "Hello from official agy ACP") { + sawDelta = true + } + } + } + if !sawThinking || !sawTool || !sawDelta { + t.Fatalf("missing streamed events: thinking=%v tool=%v delta=%v", sawThinking, sawTool, sawDelta) + } +} diff --git a/morphcode/internal/model/types.go b/morphcode/internal/model/types.go index 976daee4..1563dedb 100644 --- a/morphcode/internal/model/types.go +++ b/morphcode/internal/model/types.go @@ -9,6 +9,7 @@ import ( type Provider string const ( + ProviderAgy Provider = "agy" ProviderClaude Provider = "claude" ProviderCodex Provider = "codex" ProviderDeepSeek Provider = "deepseek" diff --git a/morphcode/internal/router/providers.go b/morphcode/internal/router/providers.go index 66b8dace..6b6e6429 100644 --- a/morphcode/internal/router/providers.go +++ b/morphcode/internal/router/providers.go @@ -222,6 +222,10 @@ func ResolveModelProvider(modelID string, prompt string) (model.Provider, string return model.ProviderOrchestrator, "" } switch { + case strings.HasPrefix(id, "agy/"): + return model.ProviderAgy, raw[len("agy/"):] + case strings.HasPrefix(id, "antigravity/"): + return model.ProviderAgy, raw[len("antigravity/"):] case strings.HasPrefix(id, "claude/"): return model.ProviderClaude, raw[len("claude/"):] case strings.HasPrefix(id, "claude-"): diff --git a/morphcode/internal/server/server.go b/morphcode/internal/server/server.go index 2a5cb832..c7466039 100644 --- a/morphcode/internal/server/server.go +++ b/morphcode/internal/server/server.go @@ -138,6 +138,7 @@ func New(st *store.Store, providers *router.ProviderStore, opts Options) *Server model.ProviderDeepSeek: native, }, NativeCLIAdapters: map[model.Provider]harness.Adapter{ + model.ProviderAgy: harness.NewAgyACPAdapter(""), model.ProviderClaude: harness.NewClaudeCLIAdapter(""), model.ProviderCodex: harness.NewCodexAppServerAdapter(""), }, diff --git a/morphcode/internal/server/workspace_config.go b/morphcode/internal/server/workspace_config.go index 53379a1c..75de88e9 100644 --- a/morphcode/internal/server/workspace_config.go +++ b/morphcode/internal/server/workspace_config.go @@ -836,6 +836,7 @@ func defaultProviderHarnesses() map[string]string { return map[string]string{ string(model.ProviderClaude): model.HarnessEngineMorphcode, string(model.ProviderCodex): model.HarnessEngineMorphcode, + string(model.ProviderAgy): model.HarnessEngineNative, } } @@ -843,12 +844,17 @@ func normalizeProviderHarnesses(in map[string]string) (map[string]string, error) allowedProviders := map[string]bool{ string(model.ProviderClaude): true, string(model.ProviderCodex): true, + string(model.ProviderAgy): true, } out := defaultProviderHarnesses() for rawKey, rawVal := range in { k := strings.ToLower(strings.TrimSpace(rawKey)) if !allowedProviders[k] { - return nil, fmt.Errorf("invalid harness provider %q (expected claude or codex)", rawKey) + return nil, fmt.Errorf("invalid harness provider %q (expected claude, codex, or agy)", rawKey) + } + if k == string(model.ProviderAgy) { + out[k] = model.HarnessEngineNative + continue } v := strings.ToLower(strings.TrimSpace(rawVal)) switch v { @@ -961,11 +967,19 @@ func (s *Server) harnessSettings(memberID, projectID string) (model.HarnessConfi cfg.WorkerEffort = normalizedEffort } for k, v := range global.ProviderHarnesses { + if k == string(model.ProviderAgy) { + cfg.ProviderHarnesses[k] = model.HarnessEngineNative + continue + } if v == model.HarnessEngineMorphcode || v == model.HarnessEngineNative { cfg.ProviderHarnesses[k] = v } } for k, v := range global.WorkerHarnesses { + if k == string(model.ProviderAgy) { + cfg.WorkerHarnesses[k] = model.HarnessEngineNative + continue + } if v == model.HarnessEngineMorphcode || v == model.HarnessEngineNative { cfg.WorkerHarnesses[k] = v } @@ -1005,11 +1019,19 @@ func (s *Server) harnessSettings(memberID, projectID string) (model.HarnessConfi } } for k, v := range project.ProviderHarnesses { + if k == string(model.ProviderAgy) { + cfg.ProviderHarnesses[k] = model.HarnessEngineNative + continue + } if v == model.HarnessEngineMorphcode || v == model.HarnessEngineNative { cfg.ProviderHarnesses[k] = v } } for k, v := range project.WorkerHarnesses { + if k == string(model.ProviderAgy) { + cfg.WorkerHarnesses[k] = model.HarnessEngineNative + continue + } if v == model.HarnessEngineMorphcode || v == model.HarnessEngineNative { cfg.WorkerHarnesses[k] = v } diff --git a/morphcode/internal/server/workspace_media.go b/morphcode/internal/server/workspace_media.go index da42b72a..4fa2ebce 100644 --- a/morphcode/internal/server/workspace_media.go +++ b/morphcode/internal/server/workspace_media.go @@ -217,11 +217,12 @@ func (s *Server) buildAvailableModels(memberID string) []model.ModelOption { cliAvail := harness.DetectNativeCLIAvailability() keyAvail := s.providers.BuiltinKeyStatus() healthy := map[model.Provider]bool{ + model.ProviderAgy: cliAvail[string(model.ProviderAgy)], model.ProviderClaude: cliAvail[string(model.ProviderClaude)] || keyAvail[string(model.ProviderClaude)], model.ProviderCodex: cliAvail[string(model.ProviderCodex)] || keyAvail[string(model.ProviderCodex)], model.ProviderDeepSeek: keyAvail[string(model.ProviderDeepSeek)], } - anyHealthy := healthy[model.ProviderClaude] || healthy[model.ProviderCodex] || healthy[model.ProviderDeepSeek] + anyHealthy := healthy[model.ProviderAgy] || healthy[model.ProviderClaude] || healthy[model.ProviderCodex] || healthy[model.ProviderDeepSeek] for _, cp := range s.providers.List() { if cp.Enabled && len(cp.Models) > 0 { anyHealthy = true @@ -233,6 +234,8 @@ func (s *Server) buildAvailableModels(memberID string) []model.ModelOption { return "" } switch p { + case model.ProviderAgy: + return "Install official agy CLI and sign in locally" case model.ProviderClaude: return "Install claude CLI or set ANTHROPIC_API_KEY" case model.ProviderCodex: @@ -250,7 +253,7 @@ func (s *Server) buildAvailableModels(memberID string) []model.ModelOption { {ID: "auto", Name: "Auto", Provider: "auto", Detail: "Route to best available model", Available: anyHealthy, Efforts: allEfforts}, } if !anyHealthy { - out[0].UnavailableReason = "Install Claude/Codex CLI or configure an API key in Settings" + out[0].UnavailableReason = "Install Antigravity/Claude/Codex CLI or configure an API key in Settings" } seen := map[string]bool{"auto": true, model.ModelOrchestrator: true} @@ -270,6 +273,26 @@ func (s *Server) buildAvailableModels(memberID string) []model.ModelOption { Efforts: allEfforts, }) + agyEfforts := []model.ReasoningEffort{model.EffortLow, model.EffortMedium, model.EffortHigh, model.EffortXHigh} + if agyAd, ok := s.orch.NativeCLIAdapters[model.ProviderAgy].(*harness.AgyACPAdapter); ok { + if discovered := agyAd.AvailableModels(); len(discovered) > 0 { + for _, mid := range discovered { + effs := harness.AgyEfforts(mid, discovered) + addOpt(model.ModelOption{ + ID: "agy/" + mid, + Name: mid, + Provider: "antigravity", + Detail: "Official agy CLI (ACP)", + Available: healthy[model.ProviderAgy], + UnavailableReason: reasonFor(model.ProviderAgy), + Efforts: effs, + }) + } + } + } + addOpt(model.ModelOption{ID: "agy/gemini-4-neon-medium", Name: "Gemini 4 Neon", Provider: "antigravity", Detail: "Balanced default · Official agy CLI", Available: healthy[model.ProviderAgy], UnavailableReason: reasonFor(model.ProviderAgy), Efforts: agyEfforts}) + addOpt(model.ModelOption{ID: "agy/gemini-pro-orchestrator-neon", Name: "Gemini Pro Orchestrator Neon", Provider: "antigravity", Detail: "Antigravity orchestrator · Official agy CLI", Available: healthy[model.ProviderAgy], UnavailableReason: reasonFor(model.ProviderAgy), Efforts: agyEfforts}) + addOpt(model.ModelOption{ID: "agy/gemini-3.8-flash-medium", Name: "Gemini 3.8 Flash", Provider: "antigravity", Detail: "Fast iterations · Official agy CLI", Available: healthy[model.ProviderAgy], UnavailableReason: reasonFor(model.ProviderAgy), Efforts: agyEfforts}) addOpt(model.ModelOption{ID: "claude/claude-opus-5-5", Name: "Claude Opus 5.5", Provider: "claude", Detail: "Deep debugging and architecture", Available: healthy[model.ProviderClaude], UnavailableReason: reasonFor(model.ProviderClaude), Efforts: allEfforts}) addOpt(model.ModelOption{ID: "claude/claude-sonnet-5-5", Name: "Claude Sonnet 5.5", Provider: "claude", Detail: "Fast everyday coding", Available: healthy[model.ProviderClaude], UnavailableReason: reasonFor(model.ProviderClaude), Efforts: allEfforts}) addOpt(model.ModelOption{ID: "claude/claude-fable-5-2", Name: "Claude Fable 5.2", Provider: "claude", Detail: "Long-horizon autonomous work", Available: healthy[model.ProviderClaude], UnavailableReason: reasonFor(model.ProviderClaude), Efforts: allEfforts}) @@ -1035,13 +1058,19 @@ func (s *Server) requestInteractiveQuestion(ctx context.Context, req harness.Use } } -// WarmUp pre-warms a local Codex worker on daemon startup when the official codex CLI is installed. -func (s *Server) WarmUp(_ context.Context) { +// WarmUp pre-warms local Codex and Antigravity CLI workers on daemon startup when installed. +func (s *Server) WarmUp(ctx context.Context) { + avail := harness.DetectNativeCLIAvailability() if codexAd, ok := s.orch.NativeCLIAdapters[model.ProviderCodex].(*harness.CodexAppServerAdapter); ok { - if harness.DetectNativeCLIAvailability()[string(model.ProviderCodex)] { + if avail[string(model.ProviderCodex)] { go codexAd.WarmUp("local", s.opts.DataRoot) } } + if agyAd, ok := s.orch.NativeCLIAdapters[model.ProviderAgy].(*harness.AgyACPAdapter); ok { + if avail[string(model.ProviderAgy)] { + go agyAd.WarmUp(ctx, s.opts.DataRoot) + } + } } func (s *Server) warmupMembers(limit int) []string {