Skip to content

armgit / chops

Public Imported from GitHub
0

Your AI agent skills, finally organized. A macOS app to browse, edit, and manage skills across Claude Code, Cursor, Codex, Windsurf, and Amp.

Replace ACP transport with one-shot Claude/Codex CLI agents (#96)

Josh Pigford13264426c76a
diff --git a/CLAUDE.md b/CLAUDE.md
index e28cfba..9d597e0 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -52,11 +52,11 @@ SwiftData store path is explicit: `~/Library/Application Support/Chops/Chops.sto
- `SkillScanner` — probes tool directories (~/.claude/skills/, ~/.cursor/rules/, etc.), parses frontmatter, upserts into SwiftData. Deduplicates via resolved symlink paths.
- `FileWatcher` — FSEvents via `DispatchSourceFileSystemObject`, triggers re-scan on changes.
- `SkillParser` → dispatches to `FrontmatterParser` (.md) or `MDCParser` (.mdc).
-- **ACP agent hierarchy** — `BaseACPAgent` owns all transport/session logic. Vendor subclasses override three hooks:
- - `shouldFilter(JsonRpcMessage) → Bool` — drop messages before SDK decoding (e.g. Augment's `usage_update`)
- - `postProcess(String) → String` — strip vendor-specific XML tags before text is stored
- - `resolvePermission(title, options)` — present permission UI; hook for future session-wide allow-all
- - `ACPAgentFactory.make(for: ToolSource)` instantiates the right subclass; `ComposePanel` holds `BaseACPAgent?`.
+- **Agent transports** — Chops drives the user's installed `claude` and `codex` binaries directly via a one-shot, request/response pattern. No streaming protocol, no JSON-RPC, no permission gymnastics — Chops sends the system prompt + current file content + user request, the model returns "summary + fenced full file", Chops parses the fence, builds a `PendingWrite`, and the existing diff-review UI gates the disk write.
+ - `ClaudeCLIAgent` — `claude -p --output-format json --system-prompt … --model sonnet --settings '{"effortLevel":"low",…}' "<user message>"`. Reads the JSON envelope, returns `result`. See `Chops/Services/Agents/Claude/`.
+ - `CodexCLIAgent` — `codex exec --skip-git-repo-check --sandbox read-only --ephemeral --output-last-message <tmp> "<user message>"`. Reads the temp file for the final agent message. See `Chops/Services/Agents/Codex/`.
+ - Both share `OneShotResponseParser` (`Chops/Services/Agents/OneShotResponseParser.swift`) — the parser tries a structured-edits JSON envelope first and falls back to summary + fenced full-file. Either format produces a `PendingWrite`.
+ - Both conform to `AgentSession` (`Chops/Services/Agents/AgentSession.swift`); `AgentFactory.make(for:)` returns the right one. `ComposePanel` keys off the protocol so the UI doesn't care which transport is in use.
**Views:** Three-column `NavigationSplitView` (Sidebar → List → Detail). Editor uses native `NSTextView` with markdown highlighting. Cmd+S save via `FocusedValues`. Agent responses render via `MarkdownMessageView` (MarkdownUI `.gitHub` theme + syntax highlighting).
diff --git a/Chops.xcodeproj/project.pbxproj b/Chops.xcodeproj/project.pbxproj
index 4d3d45b..51302c4 100644
--- a/Chops.xcodeproj/project.pbxproj
+++ b/Chops.xcodeproj/project.pbxproj
@@ -9,34 +9,34 @@
/* Begin PBXBuildFile section */
038F5975DA97A3211EF4D448 /* ThinkingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D07C2CD05E172DB71F63033 /* ThinkingView.swift */; };
09D3F065191A83BDEE922789 /* SkillDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 168E103488DEA623E712852B /* SkillDetailView.swift */; };
- 0DC3536F86CAA3C4680958AF /* ACPModel in Frameworks */ = {isa = PBXBuildFile; productRef = 86292938A0949F325E358FA5 /* ACPModel */; };
- 1BBEBC85C24BBC4E08AA1821 /* ACPLogViewer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F236C158C893B626A51E385 /* ACPLogViewer.swift */; };
+ 0AED62EB9C82E6B7C86392A4 /* ActivityRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 125B3A8A0094D3BF9E068E75 /* ActivityRow.swift */; };
+ 0D24C25D8EF2753D3B4779F1 /* AgentLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92E8381274A1590717831053 /* AgentLogger.swift */; };
+ 0F66ACF4862BE349F3C99B03 /* AgentFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02EF85EE8B243A6EBF7BC0EA /* AgentFactory.swift */; };
2263A0A3B358FBA099D0086D /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A924245DDDA4C6A59BE15567 /* SettingsView.swift */; };
25A4FB387DB5BD96DB630C14 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 231C267216AF1BCA8628B667 /* AppState.swift */; };
+ 2958B4F28A2BA0D683550419 /* WizardTemplateType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C6B997C722E5E4F3ECE3877 /* WizardTemplateType.swift */; };
309B12E0B72A22C9772BBC99 /* ChopsApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2787064DC7DF112E70C4E4D0 /* ChopsApp.swift */; };
322C22C23073C29FC0C6098D /* MarkdownMessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 947EAED7376B7762A373EF08 /* MarkdownMessageView.swift */; };
331F55021A7E6C9F0B666514 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = 4338FC540625A275BBC9AAC9 /* Sparkle */; };
- 3BF88469DCE0B56DD15DDB09 /* ACPClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DAD83C176F3A71A5B360BFD /* ACPClient.swift */; };
+ 389CE7F49A118FD26F861011 /* OneShotResponseParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62DAB83F8E24DF7E0BB19F76 /* OneShotResponseParser.swift */; };
3F0ED402E77D8D25C600BAED /* TemplateManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12C5CD1627D4EFF58AEF4F71 /* TemplateManager.swift */; };
480681BAD19F7CAF6AE154A2 /* RemoteServersSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E684304D1723CA691F40335B /* RemoteServersSettingsView.swift */; };
53C393C13E30EC439317509F /* ToolBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7B6AE242CAD6A285DD57079 /* ToolBadge.swift */; };
- 590A98554CAF058BC006CC53 /* ACPAgentFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BBC9E32924CF525F1C96BAE /* ACPAgentFactory.swift */; };
+ 5A3580B4B7E9BCBC0801B096 /* ClaudeCLIAgent.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A790BF6E4978D4BAC6ACCF /* ClaudeCLIAgent.swift */; };
5B81DED237A60776ADB04134 /* RemoteServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3314080A44DEB895223E36D5 /* RemoteServer.swift */; };
60A6711BAB0C3B8A3ACBF985 /* SkillParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5155D141EF812A3FE9ADF59C /* SkillParser.swift */; };
- 62C6C8687D8A1E3C1EBBBC8C /* ClaudeACPAgent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E201054F47FC1E66D6E0BE2 /* ClaudeACPAgent.swift */; };
6A8E0927D95BB14C9F377F4E /* SkillScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6A5B26D335C1AFB6CDE8207 /* SkillScanner.swift */; };
6E02BA7498763274DD403CD0 /* DiffReviewPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B955C8B935BD62ED4811FCA2 /* DiffReviewPanel.swift */; };
71E92A838AB4D1D6DC6174AF /* NewSkillSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = F02A00F80E4712872205EA7B /* NewSkillSheet.swift */; };
- 72F7688C0EDA2DAF80C6512B /* ACPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 511C5A2149EFF77BDA7D4692 /* ACPLogger.swift */; };
74045816B0CF10369DB51ADD /* ComposePanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 937F83BF3496CB231C535608 /* ComposePanel.swift */; };
791AA125E9170DBA81BCBE62 /* Highlightr in Frameworks */ = {isa = PBXBuildFile; productRef = 704A14702546BFBD29BE27A8 /* Highlightr */; };
7A17C99C5EFAE3AA9E788D50 /* Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9AFE1AF02B0F8057791C2A9 /* Collection.swift */; };
7EC6156934D559226BC78859 /* CollectionListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CA102A49ACFB23BC15794F8 /* CollectionListView.swift */; };
7FD1DE6640F9339D5E97E09A /* MDCParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A4F680B33C74A38FCF5ADD5 /* MDCParser.swift */; };
801A39D725B59A2F2BAF5DF2 /* cmark in Frameworks */ = {isa = PBXBuildFile; productRef = 9F4BE66CFE1E8401894FEF1F /* cmark */; };
+ 82A3B6608A09239EE8F4C7C9 /* AgentConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32C7BFA21B0740FF884FA01F /* AgentConfiguration.swift */; };
846B58F3B105D1734DC6FA75 /* SkillRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FC9D3E83D8640CC258CF361 /* SkillRegistry.swift */; };
87A469B631CC80C89B14B1C7 /* SkillMetadataBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C812515FD8DC222B89745F2 /* SkillMetadataBar.swift */; };
- 87AEE95EAD9793D3241D4387 /* ACP in Frameworks */ = {isa = PBXBuildFile; productRef = F642568B19B420E64E62307D /* ACP */; };
91EA572FCA75A2EA848C3429 /* ChopsTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A58EBE34E8A678FC897DFCB /* ChopsTextView.swift */; };
95163AEB7980654C901EC693 /* Skill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27D6ED655F951177D2152351 /* Skill.swift */; };
98434D3DDFEEC7239F6F7B79 /* RegistrySheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FCD6C2A8BE68F553A9CA392 /* RegistrySheet.swift */; };
@@ -46,59 +46,61 @@
A99BA179E0520DCDC98E1382 /* AppLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45D5C8E8C732B2F4A867E43 /* AppLogger.swift */; };
AAC4A3CBF2A9B4DF50608948 /* SSHService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6797D4AC1970DB9ACB5ACA73 /* SSHService.swift */; };
AFDC3DAB708B352A7606F119 /* DiagnosticExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5D3C2567FBF8DBA4DE957B3 /* DiagnosticExporter.swift */; };
+ B007633F077CBD9EBA65B017 /* CodexCLIAgent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CD5E41FB46E550A2F56E881 /* CodexCLIAgent.swift */; };
B4526ECE136AC044CD3C7603 /* EditorTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = D24B049638C76AC6248FD5D2 /* EditorTheme.swift */; };
B5B95B9DA63A734F25470FF5 /* SchemaVersions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1F8AA042D5D8A9F92F35CA3 /* SchemaVersions.swift */; };
+ BAF9118D55FC713079B8F730 /* AgentSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F5183DD7FC1EAA9E46940E /* AgentSettingsView.swift */; };
BD584933CCE2B650345C4CF1 /* ToolSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5487D9027B97F7E9EE9A1F4A /* ToolSource.swift */; };
BFF9964529E6C48F4F7BCB97 /* MarkdownSyntaxHighlighter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 135976FA0E8358E099157DE1 /* MarkdownSyntaxHighlighter.swift */; };
C2A028F40A1C665D29495DB6 /* StoreBootstrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D23D43EC788E51ED1C265FE /* StoreBootstrap.swift */; };
C30BEAE03E54BD36F257A925 /* ToolFilterView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A5774429CCE83C2AFBE046C /* ToolFilterView.swift */; };
C6CFF37CC0B155E8846344A4 /* ChopsIcon.icon in Resources */ = {isa = PBXBuildFile; fileRef = 04C3C644B72DD508A7CBC403 /* ChopsIcon.icon */; };
- C983C685C6296C2EF73CE57D /* CursorACPAgent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07899C351E63B32277272A59 /* CursorACPAgent.swift */; };
CBD8FECF1C5A453C8B021665 /* FrontmatterParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C77C5B30E6C885B39444E5B /* FrontmatterParser.swift */; };
CCD92CB102DFA0965D6AFDB5 /* SidebarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CF7822031FD82A28978D9C5 /* SidebarView.swift */; };
CECE9BEEC1D933C543B66A4E /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 17F7FE50C96124BA4EE43A6F /* Assets.xcassets */; };
D4C107BE303FC07CAF9C66AF /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60E0F71982C4AF0045962380 /* ContentView.swift */; };
- E15FE0630C11B3D0BC4C25ED /* ACPConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = D946A13468984E6DEBC20B9A /* ACPConfiguration.swift */; };
+ D910229B5BE2075CB2BC1B1E /* AgentSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3116880190EF088AE3B6DC67 /* AgentSession.swift */; };
E46A2BA5FA20531A06AFB418 /* ComposeModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CAA9B98C7A69F32C6950710 /* ComposeModel.swift */; };
E6F4E1CF50F2F78F5BA9BAC9 /* SkillPreviewView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77E332B9970E6E3D00DCFBA3 /* SkillPreviewView.swift */; };
E7ED248D6F94C1B1DEF1E8BA /* MarkdownRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 372FA72F2C179B79470DF86A /* MarkdownRenderer.swift */; };
E98F7490B18A194F82ED2C0E /* SkillListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA64A368BBF950CD36C4F495 /* SkillListView.swift */; };
- F16A5D53C17EB72817E1282F /* WizardTemplate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 181FD0056E54DEB3957FB4DC /* WizardTemplate.swift */; };
- F3F5B40B2B8F6C684313097D /* ACPRegistry in Frameworks */ = {isa = PBXBuildFile; productRef = 642A52CB994BF3466A09E6A6 /* ACPRegistry */; };
- F482F0222F6C14110B01D47F /* ACPSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C052B94D025127C9823E7BC /* ACPSettingsView.swift */; };
+ F54A42D63F72E619FB051F9D /* AgentLogViewer.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8C32D91C01AA0A0D63D00ED /* AgentLogViewer.swift */; };
+ F6EBFD8F2B9E42AF8E156946 /* AgentTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = C14D7755BBA1F48D7E3F2ACE /* AgentTypes.swift */; };
F98B1E8579B139FD2A801650 /* SearchService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FFC47BDE92105F4736B379F /* SearchService.swift */; };
FB295303DD30AED03290C726 /* SkillEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31B4DB87833D5160A11E39C9 /* SkillEditorView.swift */; };
FD8D2544AE423F4AB2843C0F /* AgentTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 907E59B064AB8366B60BF611 /* AgentTarget.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
+ 02EF85EE8B243A6EBF7BC0EA /* AgentFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentFactory.swift; sourceTree = "<group>"; };
03AA4FA049E1DADB40552060 /* LibrarySettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibrarySettingsView.swift; sourceTree = "<group>"; };
04C3C644B72DD508A7CBC403 /* ChopsIcon.icon */ = {isa = PBXFileReference; lastKnownFileType = wrapper.icon; path = ChopsIcon.icon; sourceTree = "<group>"; };
- 07899C351E63B32277272A59 /* CursorACPAgent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CursorACPAgent.swift; sourceTree = "<group>"; };
+ 125B3A8A0094D3BF9E068E75 /* ActivityRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActivityRow.swift; sourceTree = "<group>"; };
12C5CD1627D4EFF58AEF4F71 /* TemplateManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManager.swift; sourceTree = "<group>"; };
135976FA0E8358E099157DE1 /* MarkdownSyntaxHighlighter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownSyntaxHighlighter.swift; sourceTree = "<group>"; };
168E103488DEA623E712852B /* SkillDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillDetailView.swift; sourceTree = "<group>"; };
17F7FE50C96124BA4EE43A6F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
- 181FD0056E54DEB3957FB4DC /* WizardTemplate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WizardTemplate.swift; sourceTree = "<group>"; };
231C267216AF1BCA8628B667 /* AppState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppState.swift; sourceTree = "<group>"; };
2787064DC7DF112E70C4E4D0 /* ChopsApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChopsApp.swift; sourceTree = "<group>"; };
27D6ED655F951177D2152351 /* Skill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Skill.swift; sourceTree = "<group>"; };
2CF7822031FD82A28978D9C5 /* SidebarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarView.swift; sourceTree = "<group>"; };
2D07C2CD05E172DB71F63033 /* ThinkingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThinkingView.swift; sourceTree = "<group>"; };
2D9B5801101BA69BB84EE28D /* ChopsSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChopsSettings.swift; sourceTree = "<group>"; };
+ 3116880190EF088AE3B6DC67 /* AgentSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentSession.swift; sourceTree = "<group>"; };
31B4DB87833D5160A11E39C9 /* SkillEditorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillEditorView.swift; sourceTree = "<group>"; };
+ 32C7BFA21B0740FF884FA01F /* AgentConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentConfiguration.swift; sourceTree = "<group>"; };
3314080A44DEB895223E36D5 /* RemoteServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteServer.swift; sourceTree = "<group>"; };
372FA72F2C179B79470DF86A /* MarkdownRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownRenderer.swift; sourceTree = "<group>"; };
3A4F680B33C74A38FCF5ADD5 /* MDCParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MDCParser.swift; sourceTree = "<group>"; };
+ 3C6B997C722E5E4F3ECE3877 /* WizardTemplateType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WizardTemplateType.swift; sourceTree = "<group>"; };
+ 3CD5E41FB46E550A2F56E881 /* CodexCLIAgent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexCLIAgent.swift; sourceTree = "<group>"; };
3D23D43EC788E51ED1C265FE /* StoreBootstrap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoreBootstrap.swift; sourceTree = "<group>"; };
4CA102A49ACFB23BC15794F8 /* CollectionListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionListView.swift; sourceTree = "<group>"; };
- 511C5A2149EFF77BDA7D4692 /* ACPLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPLogger.swift; sourceTree = "<group>"; };
5155D141EF812A3FE9ADF59C /* SkillParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillParser.swift; sourceTree = "<group>"; };
5487D9027B97F7E9EE9A1F4A /* ToolSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolSource.swift; sourceTree = "<group>"; };
5CAA9B98C7A69F32C6950710 /* ComposeModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposeModel.swift; sourceTree = "<group>"; };
- 5E201054F47FC1E66D6E0BE2 /* ClaudeACPAgent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeACPAgent.swift; sourceTree = "<group>"; };
- 5F236C158C893B626A51E385 /* ACPLogViewer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPLogViewer.swift; sourceTree = "<group>"; };
60E0F71982C4AF0045962380 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
+ 62DAB83F8E24DF7E0BB19F76 /* OneShotResponseParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OneShotResponseParser.swift; sourceTree = "<group>"; };
6797D4AC1970DB9ACB5ACA73 /* SSHService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHService.swift; sourceTree = "<group>"; };
77E332B9970E6E3D00DCFBA3 /* SkillPreviewView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillPreviewView.swift; sourceTree = "<group>"; };
7C77C5B30E6C885B39444E5B /* FrontmatterParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FrontmatterParser.swift; sourceTree = "<group>"; };
@@ -106,29 +108,30 @@
7FFC47BDE92105F4736B379F /* SearchService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SearchService.swift; sourceTree = "<group>"; };
8A58EBE34E8A678FC897DFCB /* ChopsTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChopsTextView.swift; sourceTree = "<group>"; };
8C812515FD8DC222B89745F2 /* SkillMetadataBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillMetadataBar.swift; sourceTree = "<group>"; };
- 8DAD83C176F3A71A5B360BFD /* ACPClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPClient.swift; sourceTree = "<group>"; };
907E59B064AB8366B60BF611 /* AgentTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTarget.swift; sourceTree = "<group>"; };
+ 92E8381274A1590717831053 /* AgentLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentLogger.swift; sourceTree = "<group>"; };
937F83BF3496CB231C535608 /* ComposePanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposePanel.swift; sourceTree = "<group>"; };
947EAED7376B7762A373EF08 /* MarkdownMessageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownMessageView.swift; sourceTree = "<group>"; };
9A5774429CCE83C2AFBE046C /* ToolFilterView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolFilterView.swift; sourceTree = "<group>"; };
- 9BBC9E32924CF525F1C96BAE /* ACPAgentFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPAgentFactory.swift; sourceTree = "<group>"; };
- 9C052B94D025127C9823E7BC /* ACPSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPSettingsView.swift; sourceTree = "<group>"; };
9FC9D3E83D8640CC258CF361 /* SkillRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillRegistry.swift; sourceTree = "<group>"; };
+ A5F5183DD7FC1EAA9E46940E /* AgentSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentSettingsView.swift; sourceTree = "<group>"; };
A7B6AE242CAD6A285DD57079 /* ToolBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolBadge.swift; sourceTree = "<group>"; };
A924245DDDA4C6A59BE15567 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
AA64A368BBF950CD36C4F495 /* SkillListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillListView.swift; sourceTree = "<group>"; };
B1F8AA042D5D8A9F92F35CA3 /* SchemaVersions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SchemaVersions.swift; sourceTree = "<group>"; };
B3F5CF5BB1FC8455FDDB004A /* Chops.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Chops.app; sourceTree = BUILT_PRODUCTS_DIR; };
B955C8B935BD62ED4811FCA2 /* DiffReviewPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiffReviewPanel.swift; sourceTree = "<group>"; };
+ C14D7755BBA1F48D7E3F2ACE /* AgentTypes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTypes.swift; sourceTree = "<group>"; };
+ C9A790BF6E4978D4BAC6ACCF /* ClaudeCLIAgent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeCLIAgent.swift; sourceTree = "<group>"; };
C9AFE1AF02B0F8057791C2A9 /* Collection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Collection.swift; sourceTree = "<group>"; };
CAD26AA4787A2E0CDC86AADC /* FileWatcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileWatcher.swift; sourceTree = "<group>"; };
D24B049638C76AC6248FD5D2 /* EditorTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EditorTheme.swift; sourceTree = "<group>"; };
D5D3C2567FBF8DBA4DE957B3 /* DiagnosticExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticExporter.swift; sourceTree = "<group>"; };
- D946A13468984E6DEBC20B9A /* ACPConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPConfiguration.swift; sourceTree = "<group>"; };
E684304D1723CA691F40335B /* RemoteServersSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteServersSettingsView.swift; sourceTree = "<group>"; };
E6A5B26D335C1AFB6CDE8207 /* SkillScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillScanner.swift; sourceTree = "<group>"; };
F02A00F80E4712872205EA7B /* NewSkillSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewSkillSheet.swift; sourceTree = "<group>"; };
F45D5C8E8C732B2F4A867E43 /* AppLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLogger.swift; sourceTree = "<group>"; };
+ F8C32D91C01AA0A0D63D00ED /* AgentLogViewer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentLogViewer.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -139,9 +142,6 @@
331F55021A7E6C9F0B666514 /* Sparkle in Frameworks */,
791AA125E9170DBA81BCBE62 /* Highlightr in Frameworks */,
801A39D725B59A2F2BAF5DF2 /* cmark in Frameworks */,
- 87AEE95EAD9793D3241D4387 /* ACP in Frameworks */,
- 0DC3536F86CAA3C4680958AF /* ACPModel in Frameworks */,
- F3F5B40B2B8F6C684313097D /* ACPRegistry in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -183,7 +183,8 @@
1B016A7C37052B1801FCFD6A /* Shared */ = {
isa = PBXGroup;
children = (
- 5F236C158C893B626A51E385 /* ACPLogViewer.swift */,
+ 125B3A8A0094D3BF9E068E75 /* ActivityRow.swift */,
+ F8C32D91C01AA0A0D63D00ED /* AgentLogViewer.swift */,
5CAA9B98C7A69F32C6950710 /* ComposeModel.swift */,
937F83BF3496CB231C535608 /* ComposePanel.swift */,
B955C8B935BD62ED4811FCA2 /* DiffReviewPanel.swift */,
@@ -196,21 +197,18 @@
path = Shared;
sourceTree = "<group>";
};
- 3B8985D8816557B264BF0AD8 /* ACP */ = {
+ 3C9FA8A6F7D954287FF61A43 /* Claude */ = {
isa = PBXGroup;
children = (
- 9BBC9E32924CF525F1C96BAE /* ACPAgentFactory.swift */,
- 8DAD83C176F3A71A5B360BFD /* ACPClient.swift */,
- 511C5A2149EFF77BDA7D4692 /* ACPLogger.swift */,
- 89F9D9F176DFDB3FDF02DEFC /* Agents */,
+ C9A790BF6E4978D4BAC6ACCF /* ClaudeCLIAgent.swift */,
);
- path = ACP;
+ path = Claude;
sourceTree = "<group>";
};
40FF74A5B2D0A1E16B14B7A4 /* Settings */ = {
isa = PBXGroup;
children = (
- 9C052B94D025127C9823E7BC /* ACPSettingsView.swift */,
+ A5F5183DD7FC1EAA9E46940E /* AgentSettingsView.swift */,
D5D3C2567FBF8DBA4DE957B3 /* DiagnosticExporter.swift */,
03AA4FA049E1DADB40552060 /* LibrarySettingsView.swift */,
E684304D1723CA691F40335B /* RemoteServersSettingsView.swift */,
@@ -252,7 +250,7 @@
6797D4AC1970DB9ACB5ACA73 /* SSHService.swift */,
3D23D43EC788E51ED1C265FE /* StoreBootstrap.swift */,
12C5CD1627D4EFF58AEF4F71 /* TemplateManager.swift */,
- 3B8985D8816557B264BF0AD8 /* ACP */,
+ 8F2B3324DF590761AB9BC484 /* Agents */,
);
path = Services;
sourceTree = "<group>";
@@ -260,7 +258,7 @@
75334DE5CD1545A8E1E63699 /* Models */ = {
isa = PBXGroup;
children = (
- D946A13468984E6DEBC20B9A /* ACPConfiguration.swift */,
+ 32C7BFA21B0740FF884FA01F /* AgentConfiguration.swift */,
907E59B064AB8366B60BF611 /* AgentTarget.swift */,
2D9B5801101BA69BB84EE28D /* ChopsSettings.swift */,
C9AFE1AF02B0F8057791C2A9 /* Collection.swift */,
@@ -268,16 +266,21 @@
B1F8AA042D5D8A9F92F35CA3 /* SchemaVersions.swift */,
27D6ED655F951177D2152351 /* Skill.swift */,
5487D9027B97F7E9EE9A1F4A /* ToolSource.swift */,
- 181FD0056E54DEB3957FB4DC /* WizardTemplate.swift */,
+ 3C6B997C722E5E4F3ECE3877 /* WizardTemplateType.swift */,
);
path = Models;
sourceTree = "<group>";
};
- 89F9D9F176DFDB3FDF02DEFC /* Agents */ = {
+ 8F2B3324DF590761AB9BC484 /* Agents */ = {
isa = PBXGroup;
children = (
- 5E201054F47FC1E66D6E0BE2 /* ClaudeACPAgent.swift */,
- 07899C351E63B32277272A59 /* CursorACPAgent.swift */,
+ 02EF85EE8B243A6EBF7BC0EA /* AgentFactory.swift */,
+ 92E8381274A1590717831053 /* AgentLogger.swift */,
+ 3116880190EF088AE3B6DC67 /* AgentSession.swift */,
+ C14D7755BBA1F48D7E3F2ACE /* AgentTypes.swift */,
+ 62DAB83F8E24DF7E0BB19F76 /* OneShotResponseParser.swift */,
+ 3C9FA8A6F7D954287FF61A43 /* Claude */,
+ FB0A84BBF3FACBCFC6428AC5 /* Codex */,
);
path = Agents;
sourceTree = "<group>";
@@ -323,6 +326,14 @@
name = Products;
sourceTree = "<group>";
};
+ FB0A84BBF3FACBCFC6428AC5 /* Codex */ = {
+ isa = PBXGroup;
+ children = (
+ 3CD5E41FB46E550A2F56E881 /* CodexCLIAgent.swift */,
+ );
+ path = Codex;
+ sourceTree = "<group>";
+ };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -343,9 +354,6 @@
4338FC540625A275BBC9AAC9 /* Sparkle */,
704A14702546BFBD29BE27A8 /* Highlightr */,
9F4BE66CFE1E8401894FEF1F /* cmark */,
- F642568B19B420E64E62307D /* ACP */,
- 86292938A0949F325E358FA5 /* ACPModel */,
- 642A52CB994BF3466A09E6A6 /* ACPRegistry */,
);
productName = Chops;
productReference = B3F5CF5BB1FC8455FDDB004A /* Chops.app */;
@@ -372,7 +380,6 @@
mainGroup = 08ECEAD013847D8F110E61B4;
minimizedProjectReferenceProxies = 1;
packageReferences = (
- EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */,
7FA62842E4E9A8FD27AE24AF /* XCRemoteSwiftPackageReference "Highlightr" */,
FD1D69AB767CC40E2CE9FED9 /* XCRemoteSwiftPackageReference "Sparkle" */,
05A6F59368DE6489DCD607F1 /* XCRemoteSwiftPackageReference "cmark-gfm" */,
@@ -404,25 +411,27 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- 590A98554CAF058BC006CC53 /* ACPAgentFactory.swift in Sources */,
- 3BF88469DCE0B56DD15DDB09 /* ACPClient.swift in Sources */,
- E15FE0630C11B3D0BC4C25ED /* ACPConfiguration.swift in Sources */,
- 1BBEBC85C24BBC4E08AA1821 /* ACPLogViewer.swift in Sources */,
- 72F7688C0EDA2DAF80C6512B /* ACPLogger.swift in Sources */,
- F482F0222F6C14110B01D47F /* ACPSettingsView.swift in Sources */,
+ 0AED62EB9C82E6B7C86392A4 /* ActivityRow.swift in Sources */,
+ 82A3B6608A09239EE8F4C7C9 /* AgentConfiguration.swift in Sources */,
+ 0F66ACF4862BE349F3C99B03 /* AgentFactory.swift in Sources */,
+ F54A42D63F72E619FB051F9D /* AgentLogViewer.swift in Sources */,
+ 0D24C25D8EF2753D3B4779F1 /* AgentLogger.swift in Sources */,
+ D910229B5BE2075CB2BC1B1E /* AgentSession.swift in Sources */,
+ BAF9118D55FC713079B8F730 /* AgentSettingsView.swift in Sources */,
FD8D2544AE423F4AB2843C0F /* AgentTarget.swift in Sources */,
+ F6EBFD8F2B9E42AF8E156946 /* AgentTypes.swift in Sources */,
A99BA179E0520DCDC98E1382 /* AppLogger.swift in Sources */,
25A4FB387DB5BD96DB630C14 /* AppState.swift in Sources */,
309B12E0B72A22C9772BBC99 /* ChopsApp.swift in Sources */,
A500A6E37C3F2BF5B4428959 /* ChopsSettings.swift in Sources */,
91EA572FCA75A2EA848C3429 /* ChopsTextView.swift in Sources */,
- 62C6C8687D8A1E3C1EBBBC8C /* ClaudeACPAgent.swift in Sources */,
+ 5A3580B4B7E9BCBC0801B096 /* ClaudeCLIAgent.swift in Sources */,
+ B007633F077CBD9EBA65B017 /* CodexCLIAgent.swift in Sources */,
7A17C99C5EFAE3AA9E788D50 /* Collection.swift in Sources */,
7EC6156934D559226BC78859 /* CollectionListView.swift in Sources */,
E46A2BA5FA20531A06AFB418 /* ComposeModel.swift in Sources */,
74045816B0CF10369DB51ADD /* ComposePanel.swift in Sources */,
D4C107BE303FC07CAF9C66AF /* ContentView.swift in Sources */,
- C983C685C6296C2EF73CE57D /* CursorACPAgent.swift in Sources */,
AFDC3DAB708B352A7606F119 /* DiagnosticExporter.swift in Sources */,
6E02BA7498763274DD403CD0 /* DiffReviewPanel.swift in Sources */,
B4526ECE136AC044CD3C7603 /* EditorTheme.swift in Sources */,
@@ -434,6 +443,7 @@
E7ED248D6F94C1B1DEF1E8BA /* MarkdownRenderer.swift in Sources */,
BFF9964529E6C48F4F7BCB97 /* MarkdownSyntaxHighlighter.swift in Sources */,
71E92A838AB4D1D6DC6174AF /* NewSkillSheet.swift in Sources */,
+ 389CE7F49A118FD26F861011 /* OneShotResponseParser.swift in Sources */,
98434D3DDFEEC7239F6F7B79 /* RegistrySheet.swift in Sources */,
5B81DED237A60776ADB04134 /* RemoteServer.swift in Sources */,
480681BAD19F7CAF6AE154A2 /* RemoteServersSettingsView.swift in Sources */,
@@ -457,7 +467,7 @@
53C393C13E30EC439317509F /* ToolBadge.swift in Sources */,
C30BEAE03E54BD36F257A925 /* ToolFilterView.swift in Sources */,
BD584933CCE2B650345C4CF1 /* ToolSource.swift in Sources */,
- F16A5D53C17EB72817E1282F /* WizardTemplate.swift in Sources */,
+ 2958B4F28A2BA0D683550419 /* WizardTemplateType.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -748,14 +758,6 @@
minimumVersion = 2.2.1;
};
};
- EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */ = {
- isa = XCRemoteSwiftPackageReference;
- repositoryURL = "https://github.com/wiedymi/swift-acp";
- requirement = {
- branch = main;
- kind = branch;
- };
- };
FD1D69AB767CC40E2CE9FED9 /* XCRemoteSwiftPackageReference "Sparkle" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/sparkle-project/Sparkle";
@@ -772,31 +774,16 @@
package = FD1D69AB767CC40E2CE9FED9 /* XCRemoteSwiftPackageReference "Sparkle" */;
productName = Sparkle;
};
- 642A52CB994BF3466A09E6A6 /* ACPRegistry */ = {
- isa = XCSwiftPackageProductDependency;
- package = EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */;
- productName = ACPRegistry;
- };
704A14702546BFBD29BE27A8 /* Highlightr */ = {
isa = XCSwiftPackageProductDependency;
package = 7FA62842E4E9A8FD27AE24AF /* XCRemoteSwiftPackageReference "Highlightr" */;
productName = Highlightr;
};
- 86292938A0949F325E358FA5 /* ACPModel */ = {
- isa = XCSwiftPackageProductDependency;
- package = EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */;
- productName = ACPModel;
- };
9F4BE66CFE1E8401894FEF1F /* cmark */ = {
isa = XCSwiftPackageProductDependency;
package = 05A6F59368DE6489DCD607F1 /* XCRemoteSwiftPackageReference "cmark-gfm" */;
productName = cmark;
};
- F642568B19B420E64E62307D /* ACP */ = {
- isa = XCSwiftPackageProductDependency;
- package = EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */;
- productName = ACP;
- };
/* End XCSwiftPackageProductDependency section */
};
rootObject = 0BF6016099FDE9BFD3432654 /* Project object */;
diff --git a/Chops.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Chops.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index e56d94b..5e4a5a4 100644
--- a/Chops.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/Chops.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "e0ac615d8e4bebcfc18f6c3a73bc868431f4021df8a008148a52f6b4be44d7d4",
+ "originHash" : "cced8d2c7e8017967b1fbc19bce1489634e299f796e5c0826981d26ef3f07509",
"pins" : [
{
"identity" : "cmark-gfm",
@@ -27,15 +27,6 @@
"revision" : "21d8df80440b1ca3b65fa82e40782f1e5a9e6ba2",
"version" : "2.9.0"
}
- },
- {
- "identity" : "swift-acp",
- "kind" : "remoteSourceControl",
- "location" : "https://github.com/wiedymi/swift-acp",
- "state" : {
- "branch" : "main",
- "revision" : "c22dc706b8b985f7d140f245ba5de36a7a2a7493"
- }
}
],
"version" : 3
diff --git a/Chops/App/ChopsApp.swift b/Chops/App/ChopsApp.swift
index 4e58128..554c239 100644
--- a/Chops/App/ChopsApp.swift
+++ b/Chops/App/ChopsApp.swift
@@ -5,7 +5,7 @@ import Sparkle
@main
struct ChopsApp: App {
@State private var appState = AppState()
- @AppStorage("ACPDebugLogging") private var debugLoggingEnabled = false
+ @AppStorage("AgentDebugLogging") private var debugLoggingEnabled = false
private let updaterController: SPUStandardUpdaterController
init() {
diff --git a/Chops/Models/ACPConfiguration.swift b/Chops/Models/ACPConfiguration.swift
deleted file mode 100644
index 8a655aa..0000000
--- a/Chops/Models/ACPConfiguration.swift
+++ /dev/null
@@ -1,95 +0,0 @@
-import Foundation
-import ACPRegistry
-
-// MARK: - ACP Configuration Manager
-
-/// Manages registry-based ACP agent discovery, selection, and installation.
-@Observable
-@MainActor
-final class ACPConfiguration {
- static let shared = ACPConfiguration()
-
- private static let enabledIdsKey = "acpEnabledAgentIds"
-
- /// Allowlist of registry agent IDs surfaced in the UI.
- /// Extend this set to support additional agents.
- static let supportedAgentIds: Set<String> = [
- "claude-acp",
- "auggie",
- "codex-acp",
- "cursor"
- ]
-
- private let registryClient = RegistryClient()
- private let installer = AgentInstaller()
-
- // MARK: - Observable State
-
- /// Registry agents filtered to `supportedAgentIds`, in allowlist order.
- private(set) var registryAgents: [RegistryAgent] = []
- private(set) var isLoadingRegistry = false
- private(set) var registryError: String?
-
- private var enabledIds: Set<String> {
- didSet {
- UserDefaults.standard.set(Array(enabledIds), forKey: Self.enabledIdsKey)
- }
- }
-
- // MARK: - Derived
-
- var enabledAgents: [RegistryAgent] {
- registryAgents.filter { enabledIds.contains($0.id) }
- }
-
- var hasEnabledACP: Bool { !enabledAgents.isEmpty }
-
- // MARK: - Init
-
- private init() {
- let stored = UserDefaults.standard.stringArray(forKey: Self.enabledIdsKey) ?? []
- enabledIds = Set(stored)
- }
-
- // MARK: - Enable / Disable
-
- func isEnabled(_ agentId: String) -> Bool { enabledIds.contains(agentId) }
-
- func setEnabled(_ agentId: String, _ on: Bool) {
- if on { enabledIds.insert(agentId) } else { enabledIds.remove(agentId) }
- }
-
- // MARK: - Registry
-
- func loadRegistryIfNeeded() async {
- guard registryAgents.isEmpty, !isLoadingRegistry else { return }
- await refreshRegistry()
- }
-
- func refreshRegistry() async {
- isLoadingRegistry = true
- registryError = nil
- do {
- let registry = try await registryClient.fetch(forceRefresh: true)
- let allowed = Self.supportedAgentIds
- let order: [String] = ["claude-acp", "auggie", "codex-acp", "cursor"]
- registryAgents = order.compactMap { id in
- registry.agents.first { $0.id == id && allowed.contains($0.id) }
- }
- } catch {
- registryError = error.localizedDescription
- }
- isLoadingRegistry = false
- }
-
- // MARK: - Resolve
-
- /// Returns a ready-to-launch `InstalledAgent` for the given registry agent.
- /// For npx/uvx agents this is instant; for binary agents it downloads on first use.
- func resolve(_ agent: RegistryAgent) async throws -> InstalledAgent {
- if let existing = await installer.installedAgent(agent.id) {
- return existing
- }
- return try await installer.install(agent)
- }
-}
diff --git a/Chops/Models/AgentConfiguration.swift b/Chops/Models/AgentConfiguration.swift
new file mode 100644
index 0000000..a8b7c63
--- /dev/null
+++ b/Chops/Models/AgentConfiguration.swift
@@ -0,0 +1,97 @@
+import Foundation
+
+/// Stable identifier for the supported coding agents. Currently just Claude Code and
+/// Codex — both driven directly by spawning the user's installed binary.
+enum AgentID: String, Codable, CaseIterable, Identifiable, Sendable {
+ case claude
+ case codex
+
+ var id: String { rawValue }
+
+ var displayName: String {
+ switch self {
+ case .claude: "Claude Code"
+ case .codex: "Codex"
+ }
+ }
+
+ var description: String {
+ switch self {
+ case .claude: "Anthropic's Claude Code, driven via a one-shot `claude --print` invocation."
+ case .codex: "OpenAI Codex, driven via a one-shot `codex exec` invocation."
+ }
+ }
+
+ /// Where the user can install the binary if it isn't already on disk.
+ var installURL: URL {
+ switch self {
+ case .claude: URL(string: "https://claude.ai/download")!
+ case .codex: URL(string: "https://github.com/openai/codex/releases")!
+ }
+ }
+
+ /// `ToolSource` we look at to detect the binary on disk.
+ var toolSource: ToolSource {
+ switch self {
+ case .claude: .claude
+ case .codex: .codex
+ }
+ }
+}
+
+/// Tracks which agents the user has enabled. The list of *supported* agents is fixed.
+@Observable
+@MainActor
+final class AgentConfiguration {
+ static let shared = AgentConfiguration()
+
+ private static let enabledIdsKey = "agentEnabledIds"
+
+ /// Currently-supported agents, in display order.
+ let supported: [AgentID] = AgentID.allCases
+
+ private(set) var enabledIds: Set<AgentID> {
+ didSet {
+ UserDefaults.standard.set(enabledIds.map(\.rawValue), forKey: Self.enabledIdsKey)
+ }
+ }
+
+ var enabledAgents: [AgentID] { supported.filter { enabledIds.contains($0) } }
+ var hasAnyEnabled: Bool { !enabledIds.isEmpty }
+
+ private init() {
+ let defaults = UserDefaults.standard
+ // Treat "key has never been written" as first run. We do NOT use empty-array as a
+ // signal, since the user might explicitly disable everything.
+ let hasStoredValue = defaults.object(forKey: Self.enabledIdsKey) != nil
+ let stored = defaults.stringArray(forKey: Self.enabledIdsKey) ?? []
+ let migrated = Set(stored.compactMap { raw -> AgentID? in
+ // Migrate legacy values from the previous registry-driven scheme.
+ switch raw {
+ case "claude-acp", "claude": return .claude
+ case "codex-acp", "codex": return .codex
+ default: return nil
+ }
+ })
+
+ if hasStoredValue {
+ self.enabledIds = migrated
+ } else {
+ // First run: auto-enable every supported agent whose binary we can detect on disk.
+ // Saves the user from a no-op trip to Settings just to flip toggles for tools they
+ // already have installed.
+ var initial = Set<AgentID>()
+ for id in AgentID.allCases where id.toolSource.cliBinaryURL != nil {
+ initial.insert(id)
+ }
+ self.enabledIds = initial
+ defaults.set(initial.map(\.rawValue), forKey: Self.enabledIdsKey)
+ }
+ }
+
+ func isEnabled(_ id: AgentID) -> Bool { enabledIds.contains(id) }
+
+ func setEnabled(_ id: AgentID, _ on: Bool) {
+ if on { enabledIds.insert(id) } else { enabledIds.remove(id) }
+ }
+}
diff --git a/Chops/Models/ToolSource.swift b/Chops/Models/ToolSource.swift
index 3f65ddb..c2f2e76 100644
--- a/Chops/Models/ToolSource.swift
+++ b/Chops/Models/ToolSource.swift
@@ -270,22 +270,78 @@ enum ToolSource: String, Codable, CaseIterable, Identifiable {
}
private static func cliBinaryExists(_ name: String) -> Bool {
+ cliBinaryURL(name) != nil
+ }
+
+ /// Resolves an executable name to an absolute file URL by probing standard install locations
+ /// and active nvm node versions. Returns nil if not found.
+ static func cliBinaryURL(_ name: String, extraPaths: [String] = []) -> URL? {
let fm = FileManager.default
let home = fm.homeDirectoryForCurrentUser.path
- let paths = [
- "/usr/local/bin/\(name)",
- "/opt/homebrew/bin/\(name)",
+ var paths = extraPaths
+ paths.append(contentsOf: [
"\(home)/.local/bin/\(name)",
- ]
- for path in paths where fm.fileExists(atPath: path) {
- return true
+ "/opt/homebrew/bin/\(name)",
+ "/usr/local/bin/\(name)",
+ ])
+ for path in paths where fm.isExecutableFile(atPath: path) {
+ return URL(fileURLWithPath: path)
}
let nvmDir = "\(home)/.nvm/versions/node"
if let nodeDirs = try? fm.contentsOfDirectory(atPath: nvmDir) {
- for nodeDir in nodeDirs {
- if fm.fileExists(atPath: "\(nvmDir)/\(nodeDir)/bin/\(name)") { return true }
+ for nodeDir in nodeDirs.sorted().reversed() {
+ let candidate = "\(nvmDir)/\(nodeDir)/bin/\(name)"
+ if fm.isExecutableFile(atPath: candidate) {
+ return URL(fileURLWithPath: candidate)
+ }
}
}
- return false
+ return nil
+ }
+
+ /// Resolved binary URL for tools that can be driven directly via subprocess.
+ /// Currently used by Claude and Codex transports.
+ var cliBinaryURL: URL? {
+ let home = FileManager.default.homeDirectoryForCurrentUser.path
+ switch self {
+ case .claude:
+ return Self.cliBinaryURL("claude")
+ case .codex:
+ return Self.cliBinaryURL("codex", extraPaths: ["\(home)/.codex/bin/codex"])
+ default:
+ return nil
+ }
+ }
+
+ /// Runs `<bin> --version` and parses semver. Returns nil if the binary is missing
+ /// or the output doesn't match an expected pattern.
+ func cliVersion() async -> (major: Int, minor: Int, patch: Int)? {
+ guard let url = cliBinaryURL else { return nil }
+ return await Task.detached(priority: .userInitiated) { () -> (Int, Int, Int)? in
+ let proc = Process()
+ proc.executableURL = url
+ proc.arguments = ["--version"]
+ let pipe = Pipe()
+ proc.standardOutput = pipe
+ proc.standardError = FileHandle.nullDevice
+ do {
+ try proc.run()
+ proc.waitUntilExit()
+ } catch {
+ return nil
+ }
+ guard proc.terminationStatus == 0 else { return nil }
+ let data = (try? pipe.fileHandleForReading.readToEnd()) ?? Data()
+ try? pipe.fileHandleForReading.close()
+ guard let raw = String(data: data, encoding: .utf8) else { return nil }
+ let pattern = #/(\d+)\.(\d+)\.(\d+)/#
+ guard let match = raw.firstMatch(of: pattern),
+ let major = Int(match.output.1),
+ let minor = Int(match.output.2),
+ let patch = Int(match.output.3) else {
+ return nil
+ }
+ return (major, minor, patch)
+ }.value
}
}
diff --git a/Chops/Models/WizardTemplate.swift b/Chops/Models/WizardTemplate.swift
deleted file mode 100644
index 663a0dc..0000000
--- a/Chops/Models/WizardTemplate.swift
+++ /dev/null
@@ -1,49 +0,0 @@
-import Foundation
-
-// MARK: - Wizard Template Type
-
-/// Types of wizard templates for AI-assisted composition
-enum WizardTemplateType: String, CaseIterable, Codable, Identifiable {
- case skill = "skill"
- case agent = "agent"
- case rule = "rule"
-
- var id: String { rawValue }
-
- var displayName: String {
- switch self {
- case .skill: "Skills"
- case .agent: "Agents"
- case .rule: "Rules"
- }
- }
-
- var fileName: String {
- "\(rawValue)-composer.md"
- }
-
- var icon: String {
- switch self {
- case .skill: "doc.text"
- case .agent: "person.crop.rectangle"
- case .rule: "list.bullet.rectangle"
- }
- }
-}
-
-// MARK: - Wizard Template
-
-/// A wizard template with content and metadata
-struct WizardTemplate: Identifiable, Equatable {
- var id: String { type.rawValue }
- let type: WizardTemplateType
- var content: String
- var lastModified: Date
-
- /// Render template with placeholders replaced
- func render(fileContent: String, userInstructions: String) -> String {
- content
- .replacingOccurrences(of: "{{file_content}}", with: fileContent)
- .replacingOccurrences(of: "{{user_instructions}}", with: userInstructions)
- }
-}
diff --git a/Chops/Models/WizardTemplateType.swift b/Chops/Models/WizardTemplateType.swift
new file mode 100644
index 0000000..fa0d4f9
--- /dev/null
+++ b/Chops/Models/WizardTemplateType.swift
@@ -0,0 +1,7 @@
+import Foundation
+
+enum WizardTemplateType: String {
+ case skill
+ case agent
+ case rule
+}
diff --git a/Chops/Services/ACP/ACPAgentFactory.swift b/Chops/Services/ACP/ACPAgentFactory.swift
deleted file mode 100644
index 0599942..0000000
--- a/Chops/Services/ACP/ACPAgentFactory.swift
+++ /dev/null
@@ -1,15 +0,0 @@
-import Foundation
-
-/// Returns the vendor-specific agent for a given registry agent ID.
-/// Maps known agent IDs to their subclass; unknown agents use the base class.
-@MainActor
-enum ACPAgentFactory {
- static func make(for agentId: String) -> BaseACPAgent {
- switch agentId {
- case "claude-acp": return ClaudeACPAgent()
- case "cursor": return CursorACPAgent()
- case "auggie": return BaseACPAgent()
- default: return BaseACPAgent()
- }
- }
-}
diff --git a/Chops/Services/ACP/ACPClient.swift b/Chops/Services/ACP/ACPClient.swift
deleted file mode 100644
index 27f9a63..0000000
--- a/Chops/Services/ACP/ACPClient.swift
+++ /dev/null
@@ -1,471 +0,0 @@
-import ACP
-import ACPModel
-import ACPRegistry
-import Foundation
-
-// MARK: - Permission Request
-
-struct PermissionRequest: Identifiable, @unchecked Sendable {
- let id: UUID = UUID()
- let title: String
- let options: [PermissionOption]
- let continuation: CheckedContinuation<RequestPermissionResponse, Error>
-}
-
-struct PendingWrite: Sendable {
- let path: String
- let content: String
- let originalText: String?
- let originalData: Data?
- let existedBefore: Bool
-}
-
-/// Base class for ACP agent interaction. Owns an `ACP.Client` actor and conforms to `ClientDelegate`.
-/// Subclass to override vendor-specific hooks: additionalFlags, postProcess, conversationalText,
-/// resolvePermission, and the onXxx stream callbacks.
-@Observable
-@MainActor
-open class BaseACPAgent: ClientDelegate {
-
- // MARK: - Observable State
-
- var responseText: String = ""
- var thoughtText: String = ""
- var currentActivity: String?
- var pendingWrites: [PendingWrite] = []
- /// Maps resolved file paths to proposed content not yet accepted by the user.
- /// Lets handleFileReadRequest return the "virtual" state during the same turn.
- var deferredContent: [String: String] = [:]
- private(set) var sessionConfigOptions: [SessionConfigOption] = []
-
- /// True when the agent's permission mode is set to bypass — writes should be
- /// auto-accepted without user review.
- var isBypassMode: Bool {
- sessionConfigOptions.contains { option in
- if case .select(let select) = option.kind {
- return select.currentValue.value.lowercased().contains("bypass")
- }
- return false
- }
- }
- private(set) var pendingPermissionRequest: PermissionRequest?
- private(set) var isConnected: Bool = false
- private(set) var isConnecting: Bool = false
- private(set) var isProcessing: Bool = false
- private(set) var lastError: String?
- private(set) var currentAgentId: String?
-
- // MARK: - Private Handles
-
- private var acpClient: ACP.Client?
- private var sessionId: SessionId?
- private var connectTask: Task<Void, Never>?
- private var notificationTask: Task<Void, Never>?
- private var pendingSystemPrompt: String?
-
- // MARK: - Connect / Disconnect
-
- /// Starts connecting non-blocking. Observe isConnecting / isConnected / lastError for state.
- func startConnect(agent: RegistryAgent, workingDirectory: URL, systemPrompt: String?) {
- connectTask?.cancel()
- lastError = nil
- connectTask = Task {
- defer { connectTask = nil }
- do {
- try await connect(agent: agent, workingDirectory: workingDirectory, systemPrompt: systemPrompt)
- } catch is CancellationError {
- // user-initiated — no error shown
- } catch {
- acpLog.error("Connection failed: \(error.localizedDescription)")
- lastError = error.localizedDescription
- }
- }
- }
-
- private func connect(agent: RegistryAgent, workingDirectory: URL, systemPrompt: String?) async throws {
- guard ACPConfiguration.shared.isEnabled(agent.id) else {
- throw ACPClientError.agentNotConfigured(agent.id)
- }
- currentAgentId = agent.id
- acpLog.debug("Resolving agent: \(agent.id) v\(agent.version)")
- let installed = try await ACPConfiguration.shared.resolve(agent)
- acpLog.debug("Resolved: \(installed.executablePath) args=[\(installed.arguments.joined(separator: " "))]")
- try await attemptConnect(installed: installed, workingDirectory: workingDirectory, systemPrompt: systemPrompt)
- }
-
- private func attemptConnect(installed: InstalledAgent, workingDirectory: URL, systemPrompt: String?) async throws {
- pendingSystemPrompt = systemPrompt
- isConnecting = true
- defer { isConnecting = false }
-
- let arguments = installed.arguments + additionalFlags()
- let environment = installed.environment.isEmpty ? nil : installed.environment
-
- let execPath = await resolveExecutable(installed.executablePath)
- acpLog.debug("launch: \(execPath) | args: \(arguments.joined(separator: " "))")
-
- let client = ACP.Client()
- await client.setDelegate(self)
-
- // SDK's ProcessManager loads the full login-shell environment internally.
- // Custom env from the registry (e.g. API keys) is merged on top by the SDK.
- try await client.launch(
- agentPath: execPath,
- arguments: arguments,
- workingDirectory: workingDirectory.path,
- environment: environment
- )
- guard !Task.isCancelled else { await client.terminate(); return }
-
- let initResp = try await client.initialize(
- capabilities: ClientCapabilities(
- fs: FileSystemCapabilities(readTextFile: true, writeTextFile: true),
- terminal: false
- ),
- clientInfo: ClientInfo(name: "Chops", version: "1.0")
- )
- guard !Task.isCancelled else { await client.terminate(); return }
- acpLog.debug("Connected: \(initResp.agentInfo?.name ?? "?") (protocol v\(initResp.protocolVersion))")
-
- let cwd = sessionCwd(for: workingDirectory)
- let sessionResp = try await client.newSession(workingDirectory: cwd.path)
- guard !Task.isCancelled else { await client.terminate(); return }
- sessionId = sessionResp.sessionId
- sessionConfigOptions = processConfigOptions(sessionResp.configOptions ?? [])
- acpLog.debug("Session created: \(sessionResp.sessionId) (\(sessionConfigOptions.count) config options)")
-
- acpClient = client
- isConnected = true
- startNotificationMonitor(client: client)
- }
-
- func disconnect() async {
- connectTask?.cancel()
- connectTask = nil
- notificationTask?.cancel()
- notificationTask = nil
- // Resume any parked permission continuation before tearing down —
- // CheckedContinuation will crash if it is never resumed.
- if let req = pendingPermissionRequest {
- pendingPermissionRequest = nil
- req.continuation.resume(returning: RequestPermissionResponse(outcome: PermissionOutcome(cancelled: true)))
- }
- let client = acpClient
- acpClient = nil
- sessionId = nil
- isConnected = false
- currentAgentId = nil
- lastError = nil
- sessionConfigOptions = []
- pendingSystemPrompt = nil
- await client?.terminate()
- acpLog.debug("Disconnected")
- }
-
- // MARK: - Notification Monitor
-
- private func startNotificationMonitor(client: ACP.Client) {
- notificationTask?.cancel()
- notificationTask = Task.detached { [weak self] in
- let stream = await client.notifications
- for await notification in stream {
- guard !Task.isCancelled else { break }
- guard notification.method == "session/update" else { continue }
- await self?.handleRawNotification(notification)
- }
- // Stream ended — agent process likely exited
- await self?.onAgentDisconnected()
- }
- }
-
- private func onAgentDisconnected() {
- if isConnected {
- isConnected = false
- // Resume any parked permission continuation so it doesn't leak.
- if let req = pendingPermissionRequest {
- pendingPermissionRequest = nil
- req.continuation.resume(returning: RequestPermissionResponse(outcome: PermissionOutcome(cancelled: true)))
- }
- acpLog.debug("Agent process ended")
- }
- }
-
- private func handleRawNotification(_ notification: JSONRPCNotification) {
- guard let params = notification.params else { return }
- do {
- let data = try JSONEncoder().encode(params)
- struct SessionUpdateParams: Codable {
- let sessionId: String
- let update: SessionUpdate
- }
- let decoded = try JSONDecoder().decode(SessionUpdateParams.self, from: data)
- handleUpdate(decoded.update)
- } catch {
- acpLog.debug("Failed to decode session update: \(error)")
- }
- }
-
- // MARK: - Session
-
- func setConfigOption(id: SessionConfigId, value: SessionConfigValueId) async throws {
- guard let client = acpClient, let sid = sessionId else { return }
- let resp = try await client.setConfigOption(sessionId: sid, configId: id, value: value)
- sessionConfigOptions = processConfigOptions(resp.configOptions)
- }
-
- // MARK: - Prompt
-
- func prompt(_ text: String) async throws {
- guard let client = acpClient, let sid = sessionId else { throw ACPClientError.noSession }
- responseText = ""; thoughtText = ""; pendingWrites = []; currentActivity = nil
- isProcessing = true
- defer { isProcessing = false }
-
- // Prepend system prompt context to the first message of the session.
- let fullText: String
- if let sp = pendingSystemPrompt {
- pendingSystemPrompt = nil
- fullText = sp.isEmpty ? text : "\(sp)\n\n---\n\n\(text)"
- } else {
- fullText = text
- }
-
- let resp = try await client.sendPrompt(
- sessionId: sid,
- content: [.text(TextContent(text: fullText))]
- )
- currentActivity = nil
- acpLog.debug("Prompt done: \(resp.stopReason)")
- }
-
- func clearPendingWrites() { pendingWrites = []; deferredContent = [:] }
-
- /// Seed the virtual file map so same-turn reads see the editor state rather than stale disk.
- func primeDeferredContent(for path: String, content: String) {
- let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
- deferredContent[resolved] = content
- }
-
- /// Sends a session/cancel notification to the agent to interrupt the current turn.
- func cancelPrompt() {
- guard let client = acpClient, let sid = sessionId else { return }
- Task {
- do {
- try await client.cancelSession(sessionId: sid)
- } catch {
- acpLog.error("Cancel failed: \(error.localizedDescription)")
- }
- }
- }
-
- // MARK: - Permission
-
- func parkPermissionRequest(title: String, options: [PermissionOption]) async throws -> RequestPermissionResponse {
- try await withCheckedThrowingContinuation { cont in
- pendingPermissionRequest = PermissionRequest(title: title, options: options, continuation: cont)
- }
- }
-
- func respondToPermission(optionId: String?) {
- guard let req = pendingPermissionRequest else { return }
- pendingPermissionRequest = nil
- if let id = optionId {
- req.continuation.resume(returning: RequestPermissionResponse(outcome: PermissionOutcome(optionId: id)))
- } else {
- req.continuation.resume(returning: RequestPermissionResponse(outcome: PermissionOutcome(cancelled: true)))
- }
- }
-
- // MARK: - ClientDelegate
-
- public func handleFileReadRequest(_ path: String, sessionId: String, line: Int?, limit: Int?) async throws -> ReadTextFileResponse {
- acpLog.debug("readTextFile: \(path)")
- let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
- if let deferred = deferredContent[resolved] {
- acpLog.debug("Returning deferred content for: \(path)")
- return ReadTextFileResponse(content: deferred)
- }
- let content = try await Task.detached { try String(contentsOfFile: path, encoding: .utf8) }.value
- return ReadTextFileResponse(content: content)
- }
-
- public func handleFileWriteRequest(_ path: String, content: String, sessionId: String) async throws -> WriteTextFileResponse {
- acpLog.debug("Write via ACP: \(path)")
- // Read original snapshot so the diff panel can show before/after.
- // Skip if a diff block already captured this path (e.g. ClaudeACPAgent.captureDiffs).
- // Resolve symlinks on both sides so that e.g. a symlink path and its target compare equal.
- let resolvedIncoming = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
- let alreadyCaptured = pendingWrites.contains {
- URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == resolvedIncoming
- }
- if !alreadyCaptured {
- let snapshot = await Task.detached {
- let existedBefore = FileManager.default.fileExists(atPath: path)
- let originalData: Data?
- if existedBefore {
- do {
- originalData = try Data(contentsOf: URL(fileURLWithPath: path))
- } catch {
- acpLog.error("Failed to read original for diff (\(path)): \(error.localizedDescription)")
- originalData = nil
- }
- } else {
- originalData = nil
- }
- return (existedBefore, originalData, Self.decodeText(from: originalData))
- }.value
- pendingWrites.append(
- PendingWrite(
- path: path,
- content: content,
- originalText: snapshot.2,
- originalData: snapshot.1,
- existedBefore: snapshot.0
- )
- )
- } else if let idx = pendingWrites.firstIndex(where: {
- URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == resolvedIncoming
- }) {
- // captureDiffs may have set content to a partial diff fragment.
- // Replace with the full file content from write_text_file.
- let existing = pendingWrites[idx]
- pendingWrites[idx] = PendingWrite(
- path: existing.path,
- content: content,
- originalText: existing.originalText,
- originalData: existing.originalData,
- existedBefore: existing.existedBefore
- )
- }
- // Store proposed content so subsequent agent reads return it.
- deferredContent[resolvedIncoming] = content
- if isBypassMode {
- // Bypass mode: write to disk immediately — user opted out of review.
- try await Task.detached {
- let url = URL(fileURLWithPath: path)
- let parent = url.deletingLastPathComponent()
- if !FileManager.default.fileExists(atPath: parent.path) {
- try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
- }
- try content.write(to: url, atomically: true, encoding: .utf8)
- }.value
- }
- // Non-bypass: do NOT write to disk — deferred until user accepts the diff.
- return WriteTextFileResponse()
- }
-
- public func handleTerminalCreate(command: String, sessionId: String, args: [String]?, cwd: String?, env: [EnvVariable]?, outputByteLimit: Int?) async throws -> CreateTerminalResponse {
- throw ACPClientError.terminalNotSupported
- }
-
- public func handleTerminalOutput(terminalId: TerminalId, sessionId: String) async throws -> TerminalOutputResponse {
- throw ACPClientError.terminalNotSupported
- }
-
- public func handleTerminalWaitForExit(terminalId: TerminalId, sessionId: String) async throws -> WaitForExitResponse {
- throw ACPClientError.terminalNotSupported
- }
-
- public func handleTerminalKill(terminalId: TerminalId, sessionId: String) async throws -> KillTerminalResponse {
- throw ACPClientError.terminalNotSupported
- }
-
- public func handleTerminalRelease(terminalId: TerminalId, sessionId: String) async throws -> ReleaseTerminalResponse {
- throw ACPClientError.terminalNotSupported
- }
-
- public func handlePermissionRequest(request: RequestPermissionRequest) async throws -> RequestPermissionResponse {
- let title = request.message ?? "Permission Required"
- let options = request.options ?? []
- acpLog.debug("Permission: \(title)")
- return try await resolvePermission(title: title, options: options)
- }
-
- // MARK: - Session Update Dispatch
-
- func handleUpdate(_ update: SessionUpdate) {
- switch update {
- case .agentMessageChunk(let c): onMessageChunk(c)
- case .agentThoughtChunk(let c): onThoughtChunk(c)
- case .toolCall(let t): onToolCall(t)
- case .toolCallUpdate(let d): onToolCallUpdate(d)
- case .configOptionUpdate(let u): sessionConfigOptions = processConfigOptions(u)
- case .sessionInfoUpdate(let i): if let t = i.title { acpLog.debug("Session: \(t)") }
- default: break
- }
- }
-
- // MARK: - Vendor Hooks (override in subclass)
-
- func onThoughtChunk(_ content: ContentBlock) {
- if case .text(let t) = content { currentActivity = String(t.text.prefix(80)) }
- }
-
- func onMessageChunk(_ content: ContentBlock) {
- if case .text(let t) = content { responseText += t.text }
- }
-
- func onToolCall(_ update: ToolCallUpdate) {
- currentActivity = (update.status == .completed || update.status == .failed) ? nil : update.title
- }
-
- func onToolCallUpdate(_ update: ToolCallUpdateDetails) {
- if let status = update.status, status == .completed || status == .failed {
- currentActivity = nil
- } else if let title = update.title {
- currentActivity = title
- }
- }
-
- func additionalFlags() -> [String] { [] }
- func sessionCwd(for workingDirectory: URL) -> URL { workingDirectory }
- func processConfigOptions(_ options: [SessionConfigOption]) -> [SessionConfigOption] { options }
- func postProcess(_ text: String) -> String { text }
- func conversationalText(from text: String) -> String { postProcess(text) }
-
- func resolvePermission(title: String, options: [PermissionOption]) async throws -> RequestPermissionResponse {
- try await parkPermissionRequest(title: title, options: options)
- }
-
- // MARK: - Helpers
-
- /// Resolves a bare executable name (e.g. "npx") to its absolute path via the user's shell PATH.
- /// Returns the original name unchanged if it is already absolute or not found in PATH.
- private func resolveExecutable(_ name: String) async -> String {
- guard !name.hasPrefix("/") else { return name }
- let env = await ShellEnvironment.loadUserShellEnvironmentAsync()
- let dirs = (env["PATH"] ?? "").split(separator: ":").map(String.init)
- for dir in dirs {
- let full = (dir as NSString).appendingPathComponent(name)
- if FileManager.default.isExecutableFile(atPath: full) {
- acpLog.debug("Resolved '\(name)' to \(full)")
- return full
- }
- }
- acpLog.error("'\(name)' not found in PATH — launch will likely fail")
- return name
- }
-
- nonisolated static func decodeText(from data: Data?) -> String? {
- guard let data else { return nil }
- return String(data: data, encoding: .utf8)
- ?? String(data: data, encoding: .utf16)
- }
-}
-
-// MARK: - Errors
-
-/// Chops-specific errors not covered by the SDK's errors.
-enum ACPClientError: Error, LocalizedError {
- case agentNotConfigured(String)
- case noSession
- case terminalNotSupported
-
- var errorDescription: String? {
- switch self {
- case .agentNotConfigured(let id): "Agent '\(id)' not enabled. Go to Settings → ACP."
- case .noSession: "No active ACP session."
- case .terminalNotSupported: "Terminal operations are not supported."
- }
- }
-}
diff --git a/Chops/Services/ACP/Agents/ClaudeACPAgent.swift b/Chops/Services/ACP/Agents/ClaudeACPAgent.swift
deleted file mode 100644
index 79d8828..0000000
--- a/Chops/Services/ACP/Agents/ClaudeACPAgent.swift
+++ /dev/null
@@ -1,210 +0,0 @@
-import Foundation
-import ACPModel
-
-/// ACP agent for Claude Code.
-///
-/// Claude-specific stream classification:
-/// - `agentThoughtChunk` → accumulates into `thoughtText`; shown in collapsible Thinking section.
-/// - `agentMessageChunk` → accumulates raw into `responseText`; tag stripping applied at read time.
-/// - `toolCall` → activity label only; Claude does not embed diffs here.
-/// - `toolCallUpdate` → diffs captured from status-less updates; completed/failed clears activity.
-@Observable
-@MainActor
-final class ClaudeACPAgent: BaseACPAgent {
-
- // MARK: - Tag Stripping
-
- /// Claude uses both bare and `antml:` namespaced variants of these tags.
- private static let tagsToStrip = [
- "function_calls", "invoke", "parameter", "thinking",
- "antml:function_calls", "antml:invoke", "antml:parameter"
- ]
-
- // MARK: - Content Hooks
-
- /// Thought chunks are Claude's extended-thinking / reasoning stream.
- /// Accumulated in full into `thoughtText` for display in a collapsible "Thinking" section.
- /// `currentActivity` is set to a short label so the activity row shows "Thinking…"
- /// rather than truncated reasoning mid-sentence.
- override func onThoughtChunk(_ content: ContentBlock) {
- currentActivity = "Thinking…"
- if case .text(let t) = content, !t.text.isEmpty {
- thoughtText += t.text
- }
- }
-
- /// Message chunks are Claude's conversational reply.
- /// Accumulated raw into `responseText` — postProcess (tag stripping) is applied at
- /// read time by `conversationalText()`, not per-chunk, to avoid splitting tags across chunks.
- override func onMessageChunk(_ content: ContentBlock) {
- if case .text(let t) = content {
- responseText += t.text
- acpLog.debug("onMessageChunk: +\(t.text.count) chars, total=\(responseText.count)")
- }
- }
-
- /// `toolCall` notifications from Claude carry no diff content — update activity label only.
- override func onToolCall(_ toolCall: ToolCallUpdate) {
- switch toolCall.status {
- case .completed, .failed:
- currentActivity = nil
- default:
- currentActivity = toolCall.title
- }
- }
-
- /// `toolCallUpdate` is Claude's primary diff delivery channel.
- ///
- /// Claude emits two distinct `tool_call_update` shapes for the `Write` tool:
- ///
- /// 1. **Status-less** — carries `content[{type:"diff", path, newText, oldText}]`.
- /// This is the pre-write preview delivered before the file is touched on disk.
- /// Diffs are captured here so `oldText` (or a disk read) is reliable.
- ///
- /// 2. **Status: completed/failed** — carries `rawOutput` but no diff content.
- /// Used only to clear the activity label.
- ///
- /// `inProgress` updates carry a `title` to display while the tool is running.
- override func onToolCallUpdate(_ update: ToolCallUpdateDetails) {
- captureDiffs(from: update.content)
-
- guard let status = update.status else { return }
- switch status {
- case .completed, .failed:
- currentActivity = nil
- logToolResultContent(update.content)
- case .inProgress:
- if let title = update.title { currentActivity = title }
- default:
- break
- }
- }
-
- // MARK: - Diff Capture
-
- /// Extracts `ToolCallContent.diff` blocks and appends them to `pendingWrites`.
- /// Reading `oldText` here is safe — the diff block is delivered before Claude's
- /// write tool has touched the file on disk.
- private func captureDiffs(from content: [ToolCallContent]?) {
- guard let content else { return }
- for item in content {
- guard case .diff(let d) = item else { continue }
- let existedBefore = FileManager.default.fileExists(atPath: d.path)
- let oldData: Data? = if let oldText = d.oldText {
- oldText.data(using: .utf8)
- } else if existedBefore {
- try? Data(contentsOf: URL(fileURLWithPath: d.path))
- } else {
- nil
- }
- let oldText = d.oldText ?? BaseACPAgent.decodeText(from: oldData)
- // Replace any existing entry for this path — Claude may emit multiple diff blocks
- // for the same file (preview then final). The last one is the most current.
- let resolvedPath = URL(fileURLWithPath: d.path).resolvingSymlinksInPath().path
- if let existing = pendingWrites.firstIndex(where: {
- URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == resolvedPath
- }) {
- // Preserve the existing content — handleFileWriteRequest may have
- // already set it to the full file. d.newText can be a partial fragment.
- let prev = pendingWrites[existing]
- pendingWrites[existing] = PendingWrite(
- path: prev.path,
- content: prev.content,
- originalText: prev.originalText ?? oldText,
- originalData: prev.originalData ?? oldData,
- existedBefore: prev.existedBefore
- )
- } else {
- pendingWrites.append(
- PendingWrite(
- path: d.path,
- content: d.newText,
- originalText: oldText,
- originalData: oldData,
- existedBefore: existedBefore
- )
- )
- }
- acpLog.info("diff intercepted: \(d.path) original=\(oldText?.count ?? -1) chars (\(pendingWrites.count) total)")
- }
- }
-
- // MARK: - Config Option Enrichment
-
- /// Claude Code's ACP adapter omits Opus from the model picker due to an upstream SDK bug
- /// (anthropics/claude-agent-sdk-typescript#117). Inject it client-side so users can select it.
- /// Self-healing: if the upstream fix ships, hasOpus detects it and skips injection.
- override func processConfigOptions(_ options: [SessionConfigOption]) -> [SessionConfigOption] {
- options.map { option in
- guard option.name == "Model", case .select(let select) = option.kind else { return option }
-
- let existingOptions: [SessionConfigSelectOption]
- switch select.options {
- case .ungrouped(let opts): existingOptions = opts
- case .grouped(let groups): existingOptions = groups.flatMap(\.options)
- }
-
- let hasOpus = existingOptions.contains { $0.value.value == "opus" }
- guard !hasOpus else { return option }
-
- var newOptions = existingOptions
- let insertIndex = newOptions.lastIndex(where: { $0.value.value.contains("sonnet") })
- .map { newOptions.index(after: $0) } ?? newOptions.endIndex
-
- newOptions.insert(contentsOf: [
- SessionConfigSelectOption(value: SessionConfigValueId("opus"), name: "Opus"),
- SessionConfigSelectOption(value: SessionConfigValueId("opus[1m]"), name: "Opus (1M context)"),
- ], at: insertIndex)
-
- return SessionConfigOption(
- id: option.id,
- name: option.name,
- description: option.description,
- category: option.category,
- kind: .select(SessionConfigSelect(
- currentValue: select.currentValue,
- options: .ungrouped(newOptions)
- ))
- )
- }
- }
-
- // MARK: - Response Post-Processing
-
- override func postProcess(_ text: String) -> String {
- Self.stripXMLTags(text, tags: Self.tagsToStrip)
- }
-
- // MARK: - Private Helpers
-
- private static func stripXMLTags(_ text: String, tags: [String]) -> String {
- var result = text
- for tag in tags {
- for prefix in ["</\(tag)", "<\(tag)"] {
- var i = result.startIndex
- while i < result.endIndex,
- let open = result.range(of: prefix, range: i ..< result.endIndex) {
- // Search for closing '>' starting after the tag prefix, not from its start.
- guard let close = result.range(of: ">", range: open.upperBound ..< result.endIndex) else {
- // No closing '>' — malformed tag, advance past prefix to avoid infinite loop.
- i = open.upperBound
- continue
- }
- result.removeSubrange(open.lowerBound ... close.lowerBound)
- i = open.lowerBound
- }
- }
- }
- // Collapse runs of 3+ consecutive newlines down to 2.
- result = result.replacingOccurrences(of: "\n{3,}", with: "\n\n", options: .regularExpression)
- return result.trimmingCharacters(in: .whitespacesAndNewlines)
- }
-
- private func logToolResultContent(_ content: [ToolCallContent]?) {
- content?.forEach {
- if case .content(let cc) = $0, case .text(let t) = cc {
- acpLog.debug("Tool result: \(String(t.text.prefix(200)))")
- }
- }
- }
-}
diff --git a/Chops/Services/ACP/Agents/CursorACPAgent.swift b/Chops/Services/ACP/Agents/CursorACPAgent.swift
deleted file mode 100644
index 768fd4f..0000000
--- a/Chops/Services/ACP/Agents/CursorACPAgent.swift
+++ /dev/null
@@ -1,17 +0,0 @@
-import Foundation
-import ACPModel
-
-/// ACP agent for Cursor.
-///
-/// Cursor delivers conversational replies via `agentMessageChunk` with no XML wrapping.
-/// Diffs arrive through `handleFileWriteRequest` in the base class.
-@Observable
-@MainActor
-final class CursorACPAgent: BaseACPAgent {
-
- override func onThoughtChunk(_ content: ContentBlock) {}
-
- override func postProcess(_ text: String) -> String {
- return text.trimmingCharacters(in: .newlines)
- }
-}
diff --git a/Chops/Services/Agents/AgentFactory.swift b/Chops/Services/Agents/AgentFactory.swift
new file mode 100644
index 0000000..bfeb421
--- /dev/null
+++ b/Chops/Services/Agents/AgentFactory.swift
@@ -0,0 +1,13 @@
+import Foundation
+
+/// Returns the right transport for a given agent ID. Both supported agents are driven
+/// directly via the user's installed CLI.
+@MainActor
+enum AgentFactory {
+ static func make(for agentId: AgentID) -> any AgentSession {
+ switch agentId {
+ case .claude: return ClaudeCLIAgent()
+ case .codex: return CodexCLIAgent()
+ }
+ }
+}
diff --git a/Chops/Services/ACP/ACPLogger.swift b/Chops/Services/Agents/AgentLogger.swift
similarity index 76%
rename from Chops/Services/ACP/ACPLogger.swift
rename to Chops/Services/Agents/AgentLogger.swift
index 6c79c8d..d488431 100644
--- a/Chops/Services/ACP/ACPLogger.swift
+++ b/Chops/Services/Agents/AgentLogger.swift
@@ -1,21 +1,21 @@
import Foundation
import os.log
-/// Centralized ACP logging with optional debug mode and file storage
-final class ACPLogger: @unchecked Sendable {
- static let shared = ACPLogger()
+/// Centralized agent logging with optional debug mode and file storage.
+final class AgentLogger: @unchecked Sendable {
+ static let shared = AgentLogger()
- private let osLog = Logger(subsystem: "md.chops", category: "ACP")
+ private let osLog = Logger(subsystem: "md.chops", category: "Agent")
private let logFileURL: URL
- private let queue = DispatchQueue(label: "md.chops.acplogger", qos: .utility)
+ private let queue = DispatchQueue(label: "md.chops.agentlogger", qos: .utility)
private static let isoFormatter = ISO8601DateFormatter()
private var fileHandle: FileHandle?
- /// Enable verbose debug logging (send/receive payloads)
+ /// Enable verbose debug logging (send/receive payloads).
var debugEnabled: Bool {
- get { UserDefaults.standard.bool(forKey: "ACPDebugLogging") }
+ get { UserDefaults.standard.bool(forKey: "AgentDebugLogging") }
set {
- UserDefaults.standard.set(newValue, forKey: "ACPDebugLogging")
+ UserDefaults.standard.set(newValue, forKey: "AgentDebugLogging")
if newValue {
info("Debug logging enabled")
}
@@ -30,7 +30,7 @@ final class ACPLogger: @unchecked Sendable {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
- let filename = "acp-\(dateFormatter.string(from: Date())).log"
+ let filename = "agent-\(dateFormatter.string(from: Date())).log"
logFileURL = logsDir.appendingPathComponent(filename)
if !FileManager.default.fileExists(atPath: logFileURL.path) {
@@ -44,20 +44,12 @@ final class ACPLogger: @unchecked Sendable {
try? fileHandle?.close()
}
- // MARK: - Public API
-
- func info(_ message: String) {
- log(level: .info, message: message)
- }
-
+ func info(_ message: String) { log(level: .info, message: message) }
func debug(_ message: String) {
guard debugEnabled else { return }
log(level: .debug, message: message)
}
-
- func error(_ message: String) {
- log(level: .error, message: message)
- }
+ func error(_ message: String) { log(level: .error, message: message) }
enum Direction { case send, receive }
@@ -72,10 +64,9 @@ final class ACPLogger: @unchecked Sendable {
}
}
- /// Get the log file URL for viewing
var logURL: URL { logFileURL }
- /// Get recent log content — runs on the logger's background queue, never blocks the caller.
+ /// Returns the most recent `lines` from the log. Reads off the main thread.
func recentLogs(lines: Int = 200) async -> String {
await withCheckedContinuation { continuation in
queue.async { [self] in
@@ -91,13 +82,11 @@ final class ACPLogger: @unchecked Sendable {
}
}
- /// Clear logs — truncates the file and writes a single marker entry.
func clearLogs() {
queue.async { [weak self] in
guard let self else { return }
try? self.fileHandle?.truncate(atOffset: 0)
self.fileHandle?.seek(toFileOffset: 0)
- // Call log() directly on the queue to avoid an extra async hop.
let timestamp = Self.isoFormatter.string(from: Date())
let line = "[\(timestamp)] [INFO] Logs cleared\n"
if let data = line.data(using: .utf8) {
@@ -107,8 +96,6 @@ final class ACPLogger: @unchecked Sendable {
}
}
- // MARK: - Private
-
private enum Level: String {
case info = "INFO"
case debug = "DEBUG"
@@ -120,7 +107,7 @@ final class ACPLogger: @unchecked Sendable {
let line = "[\(timestamp)] [\(level.rawValue)] \(message)\n"
switch level {
- case .info: osLog.info("\(message)")
+ case .info: osLog.info("\(message)")
case .debug: osLog.debug("\(message)")
case .error: osLog.error("\(message)")
}
@@ -133,6 +120,5 @@ final class ACPLogger: @unchecked Sendable {
}
}
-// MARK: - Global convenience
-
-let acpLog = ACPLogger.shared
+/// Global convenience handle. Used by transports and views.
+let agentLog = AgentLogger.shared
diff --git a/Chops/Services/Agents/AgentSession.swift b/Chops/Services/Agents/AgentSession.swift
new file mode 100644
index 0000000..bedf879
--- /dev/null
+++ b/Chops/Services/Agents/AgentSession.swift
@@ -0,0 +1,41 @@
+import Foundation
+import Observation
+
+/// Transport-agnostic surface that `ComposePanel` observes. Implemented by:
+/// - `ClaudeCLIAgent` — one-shot `claude --print` against the user's installed binary
+/// - `CodexCLIAgent` — one-shot `codex exec` against the user's installed binary
+///
+/// All conformers must be `@Observable` so SwiftUI tracks property reads through the existential.
+@MainActor
+protocol AgentSession: AnyObject, Observable {
+ var responseText: String { get }
+ var thoughtText: String { get }
+ var currentActivity: String? { get }
+ var pendingWrites: [PendingWrite] { get }
+ var deferredContent: [String: String] { get }
+ var pendingPermissionRequest: PermissionRequest? { get }
+ var isConnected: Bool { get }
+ var isConnecting: Bool { get }
+ var isProcessing: Bool { get }
+ /// When non-nil, the timestamp at which the in-flight turn started. UIs use it to
+ /// render an elapsed-time hint so the user can tell long thinks from hangs.
+ var turnStartedAt: Date? { get }
+ /// Chronological feed of what the agent has done during the current turn. Reset on
+ /// each new prompt. Drives the live activity panel in the chat UI.
+ var activities: [AgentActivity] { get }
+ var lastError: String? { get }
+ var isBypassMode: Bool { get }
+
+ func startConnect(workingDirectory: URL, systemPrompt: String?)
+ func disconnect() async
+
+ func prompt(_ text: String) async throws
+ func cancelPrompt()
+
+ func respondToPermission(optionId: String?)
+ func clearPendingWrites()
+ func primeDeferredContent(for path: String, content: String)
+
+ /// Strip vendor-specific tags / formatting before display. Default returns text unchanged.
+ func conversationalText(from text: String) -> String
+}
diff --git a/Chops/Services/Agents/AgentTypes.swift b/Chops/Services/Agents/AgentTypes.swift
new file mode 100644
index 0000000..cddce18
--- /dev/null
+++ b/Chops/Services/Agents/AgentTypes.swift
@@ -0,0 +1,177 @@
+import Foundation
+
+// MARK: - Permission flow
+
+/// One option presented to the user when an agent asks to use a tool.
+/// `kind` is a stable string used by the UI to color the button (e.g. `allow_once`,
+/// `allow_always`, `reject_once`, `reject_always`).
+struct PermissionOption: Codable, Sendable, Identifiable {
+ let kind: String
+ let name: String
+ let optionId: String
+
+ var id: String { optionId }
+}
+
+/// Optional diff payload attached to a permission ask. When present the UI shows the
+/// before/after content side-by-side so the user can review the proposed change before
+/// clicking Allow. Required for any tool that mutates disk (Write / Edit / MultiEdit).
+struct PermissionDiffPreview: Sendable {
+ let path: String
+ let originalText: String?
+ let proposedText: String
+ let existedBefore: Bool
+}
+
+/// Wraps a parked permission ask so the UI can resume it once the user clicks.
+struct PermissionRequest: Identifiable, @unchecked Sendable {
+ let id: UUID = UUID()
+ let title: String
+ let options: [PermissionOption]
+ let diffPreview: PermissionDiffPreview?
+ let continuation: CheckedContinuation<PermissionResponse, Error>
+}
+
+/// Result of a permission ask. `cancelled == true` means the user dismissed without choosing
+/// a specific option; otherwise `optionId` identifies the chosen option.
+struct PermissionResponse: Sendable {
+ let optionId: String?
+ let cancelled: Bool
+
+ static func choice(_ optionId: String) -> PermissionResponse {
+ PermissionResponse(optionId: optionId, cancelled: false)
+ }
+ static var cancelled: PermissionResponse {
+ PermissionResponse(optionId: nil, cancelled: true)
+ }
+}
+
+// MARK: - Activity feed
+
+/// One step in the agent's chronological activity feed for a turn. The UI shows these
+/// to give the user real-time visibility into what the agent is doing — Claude
+/// generating long tool inputs can take minutes; without an activity feed it looks like
+/// the app is frozen.
+struct AgentActivity: Identifiable, Sendable, Equatable {
+ enum Kind: Sendable, Equatable {
+ case thinking
+ case toolCall(name: String)
+ case toolInputDraft(name: String, charCount: Int)
+ case toolResult(name: String)
+ case info
+ }
+ enum Status: Sendable, Equatable {
+ case running
+ case done // tool ran successfully (read-only / non-mutating)
+ case applied // mutating tool (Write/Edit/MultiEdit) successfully changed disk
+ case failed
+ }
+
+ /// Optional rich payload so the UI can show what each step actually did when
+ /// expanded. For Write/Edit this carries the diff; for Read/Bash the raw input/output.
+ struct Payload: Sendable, Equatable {
+ var filePath: String?
+ var originalText: String?
+ var proposedText: String?
+ var existedBefore: Bool?
+ var rawInput: String? // pretty-printed JSON of tool input
+ var resultText: String? // tool_result content (truncated)
+ }
+
+ let id: UUID
+ var kind: Kind
+ var title: String
+ var detail: String?
+ var startedAt: Date
+ var status: Status
+ var payload: Payload
+
+ init(
+ id: UUID = UUID(),
+ kind: Kind,
+ title: String,
+ detail: String? = nil,
+ startedAt: Date = Date(),
+ status: Status = .running,
+ payload: Payload = Payload()
+ ) {
+ self.id = id
+ self.kind = kind
+ self.title = title
+ self.detail = detail
+ self.startedAt = startedAt
+ self.status = status
+ self.payload = payload
+ }
+}
+
+// MARK: - Pending writes
+
+/// A file write proposed by the agent. Surfaced in the chat as a diff for the user to
+/// accept or reject. Both Claude (`Write` / `Edit` / `MultiEdit`) and Codex
+/// (`item/fileChange/*`) populate this.
+struct PendingWrite: Sendable {
+ let path: String
+ let content: String
+ let originalText: String?
+ let originalData: Data?
+ let existedBefore: Bool
+ /// True when the agent itself performed the disk write (the case for direct CLI
+ /// agents). On reject the UI restores from the captured snapshot.
+ let agentDidWrite: Bool
+
+ init(
+ path: String,
+ content: String,
+ originalText: String?,
+ originalData: Data?,
+ existedBefore: Bool,
+ agentDidWrite: Bool = false
+ ) {
+ self.path = path
+ self.content = content
+ self.originalText = originalText
+ self.originalData = originalData
+ self.existedBefore = existedBefore
+ self.agentDidWrite = agentDidWrite
+ }
+}
+
+// MARK: - Errors
+
+enum AgentError: Error, LocalizedError {
+ case noSession
+ case binaryNotInstalled(toolName: String, installURL: URL)
+ case agentTooOld(toolName: String, found: String, minimum: String)
+ case launchFailed(String)
+ case processExitedDuringConnect(String)
+ case connectTimedOut(stage: String)
+
+ var errorDescription: String? {
+ switch self {
+ case .noSession:
+ "No active agent session."
+ case .binaryNotInstalled(let name, _):
+ "\(name) isn't installed."
+ case .agentTooOld(let name, let found, let minimum):
+ "\(name) v\(found) is too old. Update to v\(minimum) or newer."
+ case .launchFailed(let detail):
+ "Failed to launch agent: \(detail)"
+ case .processExitedDuringConnect(let detail):
+ "Agent exited before initializing.\n\n\(detail)"
+ case .connectTimedOut(let stage):
+ "Connection timed out (\(stage))."
+ }
+ }
+}
+
+// MARK: - Helpers
+
+enum AgentDataDecoding {
+ /// Best-effort decode of bytes to a Swift String. Tries UTF-8 then UTF-16.
+ static func text(from data: Data?) -> String? {
+ guard let data else { return nil }
+ return String(data: data, encoding: .utf8)
+ ?? String(data: data, encoding: .utf16)
+ }
+}
diff --git a/Chops/Services/Agents/Claude/ClaudeCLIAgent.swift b/Chops/Services/Agents/Claude/ClaudeCLIAgent.swift
new file mode 100644
index 0000000..1093a8d
--- /dev/null
+++ b/Chops/Services/Agents/Claude/ClaudeCLIAgent.swift
@@ -0,0 +1,315 @@
+import Foundation
+import Observation
+
+/// One-shot transport for Claude Code. Each `prompt()` is a single `claude --print
+/// --output-format json` invocation: send the system prompt + current file content +
+/// user request, wait for the response, parse out a fenced code block as the proposed
+/// new file content, build a `PendingWrite` for the existing diff-review UI to gate.
+///
+/// Chops owns the disk write — Claude never touches the file. That's the simple,
+/// reliable contract: ask Claude what the file should look like; show the diff; if
+/// the user approves, *we* write it.
+@Observable
+@MainActor
+final class ClaudeCLIAgent: AgentSession {
+
+ // MARK: - AgentSession state
+
+ var responseText: String = ""
+ var thoughtText: String = ""
+ var currentActivity: String? = nil
+ var pendingWrites: [PendingWrite] = []
+ var deferredContent: [String: String] = [:]
+ private(set) var pendingPermissionRequest: PermissionRequest? = nil
+ private(set) var isConnected: Bool = false
+ private(set) var isConnecting: Bool = false
+ private(set) var isProcessing: Bool = false
+ private(set) var turnStartedAt: Date? = nil
+ private(set) var activities: [AgentActivity] = []
+ private(set) var lastError: String? = nil
+ var isBypassMode: Bool = false // unused in one-shot mode
+
+ // MARK: - Private
+
+ private var workingDirectory: URL?
+ private var sessionSystemPrompt: String?
+ private var currentProcess: Process?
+ private var currentTurnTask: Task<Void, Never>?
+ private var promptWasCancelled = false
+
+ // MARK: - Lifecycle
+
+ func startConnect(workingDirectory: URL, systemPrompt: String?) {
+ self.workingDirectory = workingDirectory
+ self.sessionSystemPrompt = systemPrompt
+ self.lastError = nil
+ guard ToolSource.claude.cliBinaryURL != nil else {
+ lastError = AgentError.binaryNotInstalled(
+ toolName: "Claude Code",
+ installURL: URL(string: "https://claude.ai/download")!
+ ).localizedDescription
+ return
+ }
+ isConnected = true
+ }
+
+ func disconnect() async {
+ currentTurnTask?.cancel()
+ currentProcess?.terminate()
+ currentTurnTask = nil
+ currentProcess = nil
+ if let req = pendingPermissionRequest {
+ pendingPermissionRequest = nil
+ req.continuation.resume(returning: .cancelled)
+ }
+ isConnected = false
+ isProcessing = false
+ turnStartedAt = nil
+ responseText = ""
+ thoughtText = ""
+ currentActivity = nil
+ activities = []
+ pendingWrites = []
+ deferredContent = [:]
+ lastError = nil
+ workingDirectory = nil
+ sessionSystemPrompt = nil
+ }
+
+ // MARK: - Per-turn
+
+ func prompt(_ text: String) async throws {
+ guard let bin = ToolSource.claude.cliBinaryURL,
+ let wd = workingDirectory else {
+ throw AgentError.noSession
+ }
+
+ responseText = ""
+ thoughtText = ""
+ pendingWrites = []
+ currentActivity = nil
+ activities = []
+ turnStartedAt = Date()
+ isProcessing = true
+ promptWasCancelled = false
+
+ let activityId = UUID()
+ activities.append(AgentActivity(
+ id: activityId,
+ kind: .thinking,
+ title: "Thinking with Claude…",
+ status: .running
+ ))
+ currentActivity = "Thinking with Claude…"
+
+ defer {
+ isProcessing = false
+ turnStartedAt = nil
+ currentActivity = nil
+ }
+
+ let (filePath, fileContent) = primaryFile()
+ let userMessage = OneShotPrompts.userMessage(
+ userRequest: text,
+ filePath: filePath,
+ fileContent: fileContent
+ )
+ let systemPrompt = sessionSystemPrompt ?? OneShotPrompts.defaultSystemPrompt(filePath: filePath)
+
+ do {
+ let result = try await runClaudeOneshot(
+ bin: bin,
+ workingDir: wd,
+ systemPrompt: systemPrompt,
+ userMessage: userMessage
+ )
+
+ let parsed = OneShotResponseParser.parse(result, originalContent: fileContent)
+ responseText = parsed.summary
+
+ guard let newContent = parsed.newContent,
+ let filePath, let fileContent,
+ newContent != fileContent else {
+ if responseText.isEmpty {
+ responseText = result.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+ if let i = activities.firstIndex(where: { $0.id == activityId }) {
+ activities[i].status = .done
+ activities[i].title = "Replied"
+ }
+ return
+ }
+
+ let resolvedPath = URL(fileURLWithPath: filePath).resolvingSymlinksInPath().path
+ pendingWrites.append(PendingWrite(
+ path: filePath,
+ content: newContent,
+ originalText: fileContent,
+ originalData: fileContent.data(using: .utf8),
+ existedBefore: FileManager.default.fileExists(atPath: resolvedPath),
+ agentDidWrite: false
+ ))
+
+ if let i = activities.firstIndex(where: { $0.id == activityId }) {
+ activities[i].status = .done
+ activities[i].title = "Proposed edit ready"
+ }
+ } catch is CancellationError {
+ if let i = activities.firstIndex(where: { $0.id == activityId }) {
+ activities[i].status = .failed
+ activities[i].title = "Cancelled"
+ }
+ throw CancellationError()
+ } catch {
+ if let i = activities.firstIndex(where: { $0.id == activityId }) {
+ activities[i].status = .failed
+ activities[i].title = "Failed"
+ activities[i].detail = error.localizedDescription
+ }
+ throw error
+ }
+ }
+
+ func cancelPrompt() {
+ promptWasCancelled = true
+ currentProcess?.terminate()
+ currentTurnTask?.cancel()
+ }
+
+ // MARK: - Permissions / writes (mostly no-ops in one-shot mode)
+
+ func respondToPermission(optionId: String?) {
+ guard let req = pendingPermissionRequest else { return }
+ pendingPermissionRequest = nil
+ if let id = optionId {
+ req.continuation.resume(returning: .choice(id))
+ } else {
+ req.continuation.resume(returning: .cancelled)
+ }
+ }
+
+ func clearPendingWrites() {
+ pendingWrites = []
+ deferredContent = [:]
+ }
+
+ func primeDeferredContent(for path: String, content: String) {
+ // Single-file flows store both the literal and resolved-symlink path so callers
+ // can look up by either. ComposePanel only ever primes the file currently in
+ // the editor, so primaryFile() picks it up reliably.
+ deferredContent[path] = content
+ let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
+ if resolved != path { deferredContent[resolved] = content }
+ }
+
+ func conversationalText(from text: String) -> String { text }
+
+ // MARK: - Internals
+
+ private func primaryFile() -> (path: String?, content: String?) {
+ if let entry = deferredContent.first {
+ return (entry.key, entry.value)
+ }
+ return (nil, nil)
+ }
+
+ private func runClaudeOneshot(
+ bin: URL,
+ workingDir: URL,
+ systemPrompt: String,
+ userMessage: String
+ ) async throws -> String {
+ let proc = Process()
+ proc.executableURL = bin
+ // `--settings` overrides ~/.claude/settings.json for THIS session only. We
+ // force effortLevel="low" so the user's global "high" doesn't make every Chops
+ // turn burn 5+ minutes on extended thinking for trivial markdown edits. We
+ // skip merging the user's hooks/plugins because they'd add overhead for short
+ // edit-style turns (the user's terminal claude is unaffected).
+ let sessionSettings = #"{"effortLevel":"low","permissions":{"dangerouslySkipPermissions":false},"includeCoAuthoredBy":false}"#
+ // Do NOT pass `--add-dir` — it's variadic and silently consumes the positional
+ // prompt arg that follows. `--tools ""` disables tool use so Claude cannot write
+ // behind Chops' diff review; `--` keeps the prompt out of that variadic option.
+ proc.arguments = [
+ "-p",
+ "--output-format", "json",
+ "--system-prompt", systemPrompt,
+ "--model", "sonnet",
+ "--settings", sessionSettings,
+ "--tools", "",
+ "--",
+ userMessage,
+ ]
+
+ var env = ProcessInfo.processInfo.environment
+ env.removeValue(forKey: "CLAUDECODE")
+ env["CLAUDE_CODE_ENTRYPOINT"] = "sdk-swift"
+ env["CLAUDE_AGENT_SDK_VERSION"] = "0.2.121"
+ proc.environment = env
+ proc.currentDirectoryURL = workingDir
+
+ let stdoutPipe = Pipe()
+ let stderrPipe = Pipe()
+ proc.standardOutput = stdoutPipe
+ proc.standardError = stderrPipe
+
+ do {
+ try proc.run()
+ } catch {
+ throw AgentError.launchFailed(error.localizedDescription)
+ }
+ currentProcess = proc
+ defer { currentProcess = nil }
+
+ // Read pipes off the main actor and concurrently. A verbose stderr stream can
+ // otherwise fill its pipe and block the child before stdout closes.
+ async let stdoutRead: Data = Task.detached(priority: .userInitiated) {
+ stdoutPipe.fileHandleForReading.readDataToEndOfFile()
+ }.value
+ async let stderrRead: Data = Task.detached(priority: .utility) {
+ stderrPipe.fileHandleForReading.readDataToEndOfFile()
+ }.value
+
+ await Task.detached(priority: .utility) {
+ proc.waitUntilExit()
+ }.value
+
+ let (stdoutData, errData) = await (stdoutRead, stderrRead)
+
+ if Task.isCancelled || promptWasCancelled { throw CancellationError() }
+
+ if let s = String(data: stdoutData, encoding: .utf8) {
+ agentLog.info("Claude stdout (\(stdoutData.count)B): \(s.prefix(2000))")
+ }
+ if let s = String(data: errData, encoding: .utf8), !s.isEmpty {
+ agentLog.info("Claude stderr: \(s.prefix(2000))")
+ }
+ agentLog.info("Claude exit=\(proc.terminationStatus)")
+
+ if proc.terminationStatus != 0 {
+ let errText = String(data: errData, encoding: .utf8) ?? ""
+ let trimmed = errText.trimmingCharacters(in: .whitespacesAndNewlines)
+ throw AgentError.launchFailed(
+ "Claude exited with code \(proc.terminationStatus)" +
+ (trimmed.isEmpty ? "" : ":\n\(trimmed.suffix(800))")
+ )
+ }
+
+ struct PrintResult: Decodable {
+ let result: String?
+ let is_error: Bool?
+ let total_cost_usd: Double?
+ }
+
+ do {
+ let envelope = try JSONDecoder().decode(PrintResult.self, from: stdoutData)
+ if envelope.is_error == true {
+ throw AgentError.launchFailed(envelope.result ?? "Claude reported an error")
+ }
+ return envelope.result ?? ""
+ } catch {
+ let preview = String(data: stdoutData.prefix(400), encoding: .utf8) ?? "<non-utf8>"
+ throw AgentError.launchFailed("Couldn't parse Claude's reply. First 400 bytes:\n\(preview)")
+ }
+ }
+}
diff --git a/Chops/Services/Agents/Codex/CodexCLIAgent.swift b/Chops/Services/Agents/Codex/CodexCLIAgent.swift
new file mode 100644
index 0000000..55656e3
--- /dev/null
+++ b/Chops/Services/Agents/Codex/CodexCLIAgent.swift
@@ -0,0 +1,288 @@
+import Foundation
+import Observation
+
+/// One-shot transport for OpenAI Codex. Each `prompt()` is a single
+/// `codex exec --output-last-message <tmp> --sandbox read-only --skip-git-repo-check
+/// --ephemeral <user-message>` invocation. Codex never touches the filesystem; Chops
+/// owns the disk write the same way the Claude transport does.
+@Observable
+@MainActor
+final class CodexCLIAgent: AgentSession {
+
+ // MARK: - AgentSession state
+
+ var responseText: String = ""
+ var thoughtText: String = ""
+ var currentActivity: String? = nil
+ var pendingWrites: [PendingWrite] = []
+ var deferredContent: [String: String] = [:]
+ private(set) var pendingPermissionRequest: PermissionRequest? = nil
+ private(set) var isConnected: Bool = false
+ private(set) var isConnecting: Bool = false
+ private(set) var isProcessing: Bool = false
+ private(set) var turnStartedAt: Date? = nil
+ private(set) var activities: [AgentActivity] = []
+ private(set) var lastError: String? = nil
+ var isBypassMode: Bool = false // unused in one-shot mode
+
+ // MARK: - Private
+
+ private var workingDirectory: URL?
+ private var sessionSystemPrompt: String?
+ private var currentProcess: Process?
+ private var promptWasCancelled = false
+
+ // MARK: - Lifecycle
+
+ func startConnect(workingDirectory: URL, systemPrompt: String?) {
+ self.workingDirectory = workingDirectory
+ self.sessionSystemPrompt = systemPrompt
+ self.lastError = nil
+ guard ToolSource.codex.cliBinaryURL != nil else {
+ lastError = AgentError.binaryNotInstalled(
+ toolName: "Codex",
+ installURL: URL(string: "https://github.com/openai/codex/releases")!
+ ).localizedDescription
+ return
+ }
+ isConnected = true
+ }
+
+ func disconnect() async {
+ currentProcess?.terminate()
+ currentProcess = nil
+ if let req = pendingPermissionRequest {
+ pendingPermissionRequest = nil
+ req.continuation.resume(returning: .cancelled)
+ }
+ isConnected = false
+ isProcessing = false
+ turnStartedAt = nil
+ responseText = ""
+ thoughtText = ""
+ currentActivity = nil
+ activities = []
+ pendingWrites = []
+ deferredContent = [:]
+ lastError = nil
+ workingDirectory = nil
+ sessionSystemPrompt = nil
+ }
+
+ // MARK: - Per-turn
+
+ func prompt(_ text: String) async throws {
+ guard let bin = ToolSource.codex.cliBinaryURL,
+ let wd = workingDirectory else {
+ throw AgentError.noSession
+ }
+
+ responseText = ""
+ thoughtText = ""
+ pendingWrites = []
+ currentActivity = nil
+ activities = []
+ turnStartedAt = Date()
+ isProcessing = true
+ promptWasCancelled = false
+
+ let activityId = UUID()
+ activities.append(AgentActivity(
+ id: activityId,
+ kind: .thinking,
+ title: "Thinking with Codex…",
+ status: .running
+ ))
+ currentActivity = "Thinking with Codex…"
+
+ defer {
+ isProcessing = false
+ turnStartedAt = nil
+ currentActivity = nil
+ }
+
+ let (filePath, fileContent) = primaryFile()
+ // Codex doesn't accept a separate system prompt flag, so we splice it into the
+ // user message — same shape that worked end-to-end in CLI smoke tests.
+ let systemPrompt = sessionSystemPrompt ?? OneShotPrompts.defaultSystemPrompt(filePath: filePath)
+ let userBody = OneShotPrompts.userMessage(
+ userRequest: text,
+ filePath: filePath,
+ fileContent: fileContent
+ )
+ let combined = "\(systemPrompt)\n\n---\n\n\(userBody)"
+
+ do {
+ let result = try await runCodexOneshot(
+ bin: bin,
+ workingDir: wd,
+ userMessage: combined
+ )
+
+ let parsed = OneShotResponseParser.parse(result, originalContent: fileContent)
+ responseText = parsed.summary
+
+ guard let newContent = parsed.newContent,
+ let filePath, let fileContent,
+ newContent != fileContent else {
+ if responseText.isEmpty {
+ responseText = result.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+ if let i = activities.firstIndex(where: { $0.id == activityId }) {
+ activities[i].status = .done
+ activities[i].title = "Replied"
+ }
+ return
+ }
+
+ let resolvedPath = URL(fileURLWithPath: filePath).resolvingSymlinksInPath().path
+ pendingWrites.append(PendingWrite(
+ path: filePath,
+ content: newContent,
+ originalText: fileContent,
+ originalData: fileContent.data(using: .utf8),
+ existedBefore: FileManager.default.fileExists(atPath: resolvedPath),
+ agentDidWrite: false
+ ))
+
+ if let i = activities.firstIndex(where: { $0.id == activityId }) {
+ activities[i].status = .done
+ activities[i].title = "Proposed edit ready"
+ }
+ } catch is CancellationError {
+ if let i = activities.firstIndex(where: { $0.id == activityId }) {
+ activities[i].status = .failed
+ activities[i].title = "Cancelled"
+ }
+ throw CancellationError()
+ } catch {
+ if let i = activities.firstIndex(where: { $0.id == activityId }) {
+ activities[i].status = .failed
+ activities[i].title = "Failed"
+ activities[i].detail = error.localizedDescription
+ }
+ throw error
+ }
+ }
+
+ func cancelPrompt() {
+ promptWasCancelled = true
+ currentProcess?.terminate()
+ }
+
+ // MARK: - Permissions / writes (no-op in one-shot mode — we own disk writes)
+
+ func respondToPermission(optionId: String?) {
+ guard let req = pendingPermissionRequest else { return }
+ pendingPermissionRequest = nil
+ if let id = optionId {
+ req.continuation.resume(returning: .choice(id))
+ } else {
+ req.continuation.resume(returning: .cancelled)
+ }
+ }
+
+ func clearPendingWrites() {
+ pendingWrites = []
+ deferredContent = [:]
+ }
+
+ func primeDeferredContent(for path: String, content: String) {
+ deferredContent[path] = content
+ let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
+ if resolved != path { deferredContent[resolved] = content }
+ }
+
+ func conversationalText(from text: String) -> String { text }
+
+ // MARK: - Internals
+
+ private func primaryFile() -> (path: String?, content: String?) {
+ if let entry = deferredContent.first {
+ return (entry.key, entry.value)
+ }
+ return (nil, nil)
+ }
+
+ private func runCodexOneshot(
+ bin: URL,
+ workingDir: URL,
+ userMessage: String
+ ) async throws -> String {
+ // `--output-last-message` is the cleanest way to get just the final agent reply.
+ // Stdout interleaves status lines, "tokens used", colorised banners, etc.; the
+ // file gets exactly the last assistant message and nothing else.
+ let lastMsgURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("chops-codex-\(UUID().uuidString).txt")
+ defer { try? FileManager.default.removeItem(at: lastMsgURL) }
+
+ let proc = Process()
+ proc.executableURL = bin
+ proc.arguments = [
+ "exec",
+ "--skip-git-repo-check",
+ "--sandbox", "read-only",
+ "--ephemeral",
+ "--color", "never",
+ "--output-last-message", lastMsgURL.path,
+ userMessage,
+ ]
+
+ proc.environment = ProcessInfo.processInfo.environment
+ proc.currentDirectoryURL = workingDir
+
+ let stdoutPipe = Pipe()
+ let stderrPipe = Pipe()
+ proc.standardOutput = stdoutPipe
+ proc.standardError = stderrPipe
+
+ do {
+ try proc.run()
+ } catch {
+ throw AgentError.launchFailed(error.localizedDescription)
+ }
+ currentProcess = proc
+ defer { currentProcess = nil }
+
+ // Read pipes concurrently. If stderr fills while stdout is still open, waiting on
+ // stdout first can deadlock the turn.
+ async let stdoutRead: Data = Task.detached(priority: .userInitiated) {
+ stdoutPipe.fileHandleForReading.readDataToEndOfFile()
+ }.value
+ async let stderrRead: Data = Task.detached(priority: .utility) {
+ stderrPipe.fileHandleForReading.readDataToEndOfFile()
+ }.value
+
+ await Task.detached(priority: .utility) {
+ proc.waitUntilExit()
+ }.value
+
+ let (stdoutData, errData) = await (stdoutRead, stderrRead)
+
+ if Task.isCancelled || promptWasCancelled { throw CancellationError() }
+
+ if let s = String(data: stdoutData, encoding: .utf8) {
+ agentLog.info("Codex stdout (\(stdoutData.count)B): \(s.prefix(2000))")
+ }
+ if let s = String(data: errData, encoding: .utf8), !s.isEmpty {
+ agentLog.info("Codex stderr: \(s.prefix(2000))")
+ }
+ agentLog.info("Codex exit=\(proc.terminationStatus)")
+
+ if proc.terminationStatus != 0 {
+ let errText = String(data: errData, encoding: .utf8) ?? ""
+ let trimmed = errText.trimmingCharacters(in: .whitespacesAndNewlines)
+ throw AgentError.launchFailed(
+ "Codex exited with code \(proc.terminationStatus)" +
+ (trimmed.isEmpty ? "" : ":\n\(trimmed.suffix(800))")
+ )
+ }
+
+ guard let lastMsg = try? String(contentsOf: lastMsgURL, encoding: .utf8),
+ !lastMsg.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
+ let preview = String(data: stdoutData.prefix(400), encoding: .utf8) ?? "<non-utf8>"
+ throw AgentError.launchFailed("Codex returned no final message. First 400 bytes of stdout:\n\(preview)")
+ }
+ return lastMsg
+ }
+}
diff --git a/Chops/Services/Agents/OneShotResponseParser.swift b/Chops/Services/Agents/OneShotResponseParser.swift
new file mode 100644
index 0000000..41ca074
--- /dev/null
+++ b/Chops/Services/Agents/OneShotResponseParser.swift
@@ -0,0 +1,163 @@
+import Foundation
+
+/// Shared parser for one-shot agent replies. Both Claude (`claude -p --output-format json`)
+/// and Codex (`codex exec --output-last-message`) ask the model for "summary + fenced full
+/// file" or a structured edits JSON envelope; this turns either into `(summary, newContent)`.
+enum OneShotResponseParser {
+
+ /// `summary` is plain text the user sees in chat. `newContent` is the proposed file
+ /// body — `nil` means the agent replied conversationally with no edit to apply.
+ struct Result {
+ let summary: String
+ let newContent: String?
+ }
+
+ /// Decoded shape of the structured-edits JSON format.
+ private struct EditsResponse: Decodable {
+ let summary: String
+ let edits: [EditOp]
+
+ struct EditOp: Decodable {
+ let find: String
+ let replace: String
+ }
+ }
+
+ static func parse(_ text: String, originalContent: String?) -> Result {
+ // 1. Try structured-edits JSON first.
+ let stripped = stripCodeFences(text).trimmingCharacters(in: .whitespacesAndNewlines)
+ if let data = stripped.data(using: .utf8),
+ let parsed = try? JSONDecoder().decode(EditsResponse.self, from: data) {
+ if parsed.edits.isEmpty {
+ return Result(summary: parsed.summary, newContent: nil)
+ }
+ if let original = originalContent,
+ let applied = try? applyEdits(parsed.edits, to: original) {
+ return Result(summary: parsed.summary, newContent: applied)
+ }
+ return Result(summary: parsed.summary, newContent: nil)
+ }
+
+ // 2. Fall back to summary + fenced full-file block.
+ guard let openingRange = openingFenceRange(in: text) else {
+ return Result(
+ summary: text.trimmingCharacters(in: .whitespacesAndNewlines),
+ newContent: nil
+ )
+ }
+ let summary = String(text[..<openingRange.lowerBound])
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let afterOpening = String(text[openingRange.upperBound...])
+ if let closingRange = lastClosingFenceRange(in: afterOpening) {
+ return Result(
+ summary: summary,
+ newContent: String(afterOpening[..<closingRange.lowerBound])
+ )
+ }
+ return Result(summary: summary, newContent: String(afterOpening))
+ }
+
+ // MARK: - Internals
+
+ private static func openingFenceRange(in text: String) -> Range<String.Index>? {
+ // ``` at start-of-string or after a newline, optional language hint, then newline.
+ let pattern = #"(?m)^```[a-zA-Z0-9_-]*\n"#
+ guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }
+ let ns = text as NSString
+ let match = regex.rangeOfFirstMatch(in: text, range: NSRange(location: 0, length: ns.length))
+ guard match.location != NSNotFound,
+ let r = Range(match, in: text) else { return nil }
+ return r
+ }
+
+ private static func lastClosingFenceRange(in text: String) -> Range<String.Index>? {
+ // Use the last fence line as the wrapper close so Markdown files containing their
+ // own fenced examples do not get truncated at the first inner code block.
+ let pattern = #"(?m)^```\s*$"#
+ guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }
+ let ns = text as NSString
+ let matches = regex.matches(in: text, range: NSRange(location: 0, length: ns.length))
+ guard let last = matches.last,
+ let r = Range(last.range, in: text) else { return nil }
+ return r
+ }
+
+ private static func stripCodeFences(_ text: String) -> String {
+ var s = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ let prefixes = ["```json\n", "```JSON\n", "```\n"]
+ for prefix in prefixes where s.hasPrefix(prefix) {
+ s.removeFirst(prefix.count)
+ break
+ }
+ if s.hasSuffix("\n```") { s.removeLast(4) }
+ else if s.hasSuffix("```") { s.removeLast(3) }
+ return s
+ }
+
+ private static func applyEdits(_ edits: [EditsResponse.EditOp], to original: String) throws -> String {
+ var content = original
+ for (i, edit) in edits.enumerated() {
+ var occurrences = 0
+ var searchStart = content.startIndex
+ while let r = content.range(of: edit.find, range: searchStart..<content.endIndex) {
+ occurrences += 1
+ searchStart = r.upperBound
+ if occurrences > 1 { break }
+ }
+ switch occurrences {
+ case 0:
+ throw AgentError.launchFailed(
+ "Edit #\(i + 1): the `find` text doesn't appear in the file. Proposed:\n\n\(edit.find.prefix(300))"
+ )
+ case 1:
+ if let r = content.range(of: edit.find) {
+ content.replaceSubrange(r, with: edit.replace)
+ }
+ default:
+ throw AgentError.launchFailed(
+ "Edit #\(i + 1): the `find` text appears more than once — needs more surrounding context to be unique."
+ )
+ }
+ }
+ return content
+ }
+}
+
+/// Small helpers shared by one-shot agents for assembling the system + user prompts.
+enum OneShotPrompts {
+ /// System prompt sent to the agent when the host hasn't supplied one. Identical for
+ /// Claude and Codex so the parser can rely on a consistent reply format.
+ static func defaultSystemPrompt(filePath: String?) -> String {
+ let name = filePath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? "the file"
+ return """
+ You are helping the user edit \(name) — a Markdown file used to instruct an AI coding assistant.
+
+ Apply the user's request **minimally**. Preserve every unchanged line exactly — same whitespace, same blank lines, same wording. Do not refactor or "improve" anything the user didn't ask about.
+
+ ## Reply format
+
+ Reply with two things in this exact order:
+ 1. ONE OR TWO SENTENCES summarizing what changed (plain text, no preamble).
+ 2. The COMPLETE updated file content inside a single fenced code block. Open with ``` on its own line, then the full file (including YAML frontmatter), then ``` on its own line.
+
+ If the user is asking a question rather than requesting an edit, omit the code fence and just answer in prose.
+ """
+ }
+
+ /// Wraps the user's request with the current file content so the agent has full context
+ /// without needing tool access.
+ static func userMessage(userRequest: String, filePath: String?, fileContent: String?) -> String {
+ var parts: [String] = []
+ if let filePath, let fileContent {
+ let name = URL(fileURLWithPath: filePath).lastPathComponent
+ parts.append("Current contents of \(name):")
+ parts.append("```")
+ parts.append(fileContent.isEmpty ? "(empty file)" : fileContent)
+ parts.append("```")
+ parts.append("")
+ }
+ parts.append("User's request:")
+ parts.append(userRequest)
+ return parts.joined(separator: "\n")
+ }
+}
diff --git a/Chops/Services/TemplateManager.swift b/Chops/Services/TemplateManager.swift
index a109d56..425cafb 100644
--- a/Chops/Services/TemplateManager.swift
+++ b/Chops/Services/TemplateManager.swift
@@ -1,34 +1,10 @@
import Foundation
-// MARK: - Template Manager
-
-/// Manages wizard templates for AI-assisted composition
-@Observable
@MainActor
final class TemplateManager {
static let shared = TemplateManager()
- private(set) var templates: [WizardTemplate] = []
-
- private let fileManager = FileManager.default
-
- private var templatesDirectory: URL {
- let appSupport = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
- ?? fileManager.temporaryDirectory
- return appSupport.appendingPathComponent("Chops/templates", isDirectory: true)
- }
-
- private init() {
- ensureTemplatesExist()
- loadTemplates()
- }
-
- // MARK: - Public API
-
- /// Get template for a specific type
- func template(for type: WizardTemplateType) -> WizardTemplate? {
- templates.first { $0.type == type }
- }
+ private init() {}
/// Build a context-aware system prompt for a given template type.
/// Substitutes `{{skill_name}}`, `{{skill_description}}`, `{{file_path}}`,
@@ -57,260 +33,64 @@ final class TemplateManager {
switch type {
case .skill: Self.defaultSkillSystemPrompt
case .agent: Self.defaultAgentSystemPrompt
- case .rule: Self.defaultRuleSystemPrompt
- }
- }
-
- /// Save updated template content
- func save(_ template: WizardTemplate, preserveVersionMarker: Bool = false) {
- let url = templatesDirectory.appendingPathComponent(template.type.fileName)
- let persistedContent = preserveVersionMarker ? template.content : stripVersionMarker(from: template.content)
- do {
- try persistedContent.write(to: url, atomically: true, encoding: .utf8)
- if let index = templates.firstIndex(where: { $0.type == template.type }) {
- templates[index] = WizardTemplate(
- type: template.type,
- content: persistedContent,
- lastModified: Date()
- )
- }
- } catch {
- AppLogger.fileIO.error("Failed to save template: \(error.localizedDescription)")
- }
- }
-
- /// Reset a template to bundled default
- func resetToDefault(_ type: WizardTemplateType) {
- guard let bundledContent = loadBundledTemplate(type) else { return }
- let template = WizardTemplate(type: type, content: bundledContent, lastModified: Date())
- save(template, preserveVersionMarker: true)
- }
-
- /// Reset all templates to defaults
- func resetAllToDefaults() {
- for type in WizardTemplateType.allCases {
- resetToDefault(type)
- }
- }
-
- // MARK: - Private
-
- private func ensureTemplatesExist() {
- do {
- try fileManager.createDirectory(at: templatesDirectory, withIntermediateDirectories: true)
- } catch {
- AppLogger.fileIO.error("Failed to create templates dir: \(error.localizedDescription)")
- }
-
- // Write bundled templates on first run; overwrite outdated stored versions.
- for type in WizardTemplateType.allCases {
- let destURL = templatesDirectory.appendingPathComponent(type.fileName)
- guard let bundled = loadBundledTemplate(type) else { continue }
-
- let needsWrite: Bool
- if !fileManager.fileExists(atPath: destURL.path) {
- needsWrite = true
- } else if let stored = try? String(contentsOf: destURL, encoding: .utf8) {
- needsWrite = templateNeedsUpdate(stored: stored, bundled: bundled)
- } else {
- needsWrite = false
- }
-
- if needsWrite {
- do {
- try bundled.write(to: destURL, atomically: true, encoding: .utf8)
- } catch {
- AppLogger.fileIO.error("Failed to write template \(type.rawValue): \(error.localizedDescription)")
- }
- }
- }
- }
-
- /// Returns true when a stored template's version marker is older than the bundled version.
- /// Only auto-updates templates that still carry the default version header — user-customized
- /// templates that omit the marker are left untouched.
- private func templateNeedsUpdate(stored: String, bundled: String) -> Bool {
- guard let storedVersion = extractVersion(from: stored),
- let bundledVersion = extractVersion(from: bundled) else {
- return false
- }
- return storedVersion < bundledVersion
- }
-
- private func extractVersion(from content: String) -> Int? {
- let prefix = "<!-- chops-template-version: "
- guard let start = content.range(of: prefix),
- let end = content.range(of: " -->", range: start.upperBound ..< content.endIndex) else {
- return nil
- }
- return Int(content[start.upperBound ..< end.lowerBound])
- }
-
- private func stripVersionMarker(from content: String) -> String {
- content.replacingOccurrences(
- of: #"^<!-- chops-template-version: \d+ -->\n?"#,
- with: "",
- options: .regularExpression
- )
- }
-
- private func loadTemplates() {
- templates = WizardTemplateType.allCases.compactMap { type in
- let url = templatesDirectory.appendingPathComponent(type.fileName)
- guard let content = try? String(contentsOf: url, encoding: .utf8) else {
- return nil
- }
- let attrs = try? fileManager.attributesOfItem(atPath: url.path)
- let modified = attrs?[.modificationDate] as? Date ?? Date()
- return WizardTemplate(type: type, content: content, lastModified: modified)
- }
- }
-
- private func loadBundledTemplate(_ type: WizardTemplateType) -> String? {
- guard let url = Bundle.main.url(
- forResource: type.rawValue + "-composer",
- withExtension: "md",
- subdirectory: "Templates"
- ) else {
- return defaultTemplateContent(for: type)
- }
- return try? String(contentsOf: url, encoding: .utf8)
- }
-
- private func defaultTemplateContent(for type: WizardTemplateType) -> String {
- switch type {
- case .skill: Self.defaultSkillTemplate
- case .agent: Self.defaultAgentTemplate
- case .rule: Self.defaultRuleTemplate
+ case .rule: Self.defaultRuleSystemPrompt
}
}
- // MARK: - Default Templates
-
- private static let defaultSkillTemplate = """
- <!-- chops-template-version: 2 -->
- # Skill Composer
-
- You are helping create or improve a skill definition.
-
- ## Context
- - File type: Skill
- - Skills are reusable knowledge/instructions for AI assistants
-
- ## Current Content
- {{file_content}}
-
- ## User Instructions
- {{user_instructions}}
-
- ## Guidelines
- 1. Use YAML frontmatter for metadata (name, description)
- 2. Write clear, actionable instructions
- 3. Include examples where helpful
- 4. Keep scope focused and composable
- """
-
-
- // MARK: - Default Agent / Rule Templates
-
- private static let defaultAgentTemplate = """
- <!-- chops-template-version: 1 -->
- # Agent Composer
-
- You are helping create or improve an agent definition.
-
- ## Context
- - File type: Agent
- - Agents are specialized AI assistants with a defined role, tools, and behavior
-
- ## Current Content
- {{file_content}}
-
- ## User Instructions
- {{user_instructions}}
-
- ## Guidelines
- 1. Use YAML frontmatter for metadata (name, description)
- 2. Define a clear, focused role for the agent
- 3. Specify which tools and capabilities the agent should use
- 4. Keep instructions concise and unambiguous
- """
-
- private static let defaultRuleTemplate = """
- <!-- chops-template-version: 1 -->
- # Rule Composer
-
- You are helping create or improve a rule definition.
-
- ## Context
- - File type: Rule
- - Rules are persistent instructions applied across all interactions in a tool
-
- ## Current Content
- {{file_content}}
-
- ## User Instructions
- {{user_instructions}}
-
- ## Guidelines
- 1. Use YAML frontmatter for metadata (name, description)
- 2. Write rules as clear, imperative directives
- 3. Keep scope narrow — one concern per rule
- 4. Avoid contradictions with other rules
- """
-
- // MARK: - Default System Prompts
-
private static let defaultSkillSystemPrompt = """
- You are an expert in writing skills for AI coding assistants that use the Model Context Protocol (MCP).
+ You are an expert in writing skills for AI coding assistants.
- ## Current skill context
+ ## File you're editing
- Name: {{skill_name}}
- Description: {{skill_description}}
- - File: {{file_path}}
- - Frontmatter:
- {{frontmatter}}
+ - Path: {{file_path}}
+
+ ## Your task
+ The user will give you their request along with the current file contents. Apply the request **minimally** — preserve every unchanged line exactly, including whitespace, blank lines, and wording. Do not refactor or "improve" anything the user didn't ask about.
+
+ ## Reply format (STRICT)
+ Reply with two things in this exact order:
+ 1. ONE OR TWO SENTENCES summarizing what changed (plain text, no preamble like "I'll update…").
+ 2. The COMPLETE updated file content inside a single fenced code block. Open with ``` on its own line, then the full file (including YAML frontmatter), then ``` on its own line.
- ## Your role
- When the user asks you to create or update this skill, use the ACP `write_text_file` tool to write the complete updated file content directly to the file path shown above.
- Do not show the content in a code block or ask for confirmation — write it directly via `write_text_file`.
- Write the complete file including YAML frontmatter. Preserve all unchanged lines exactly as they appear — do not reformat, reindent, or alter any content you are not intentionally changing.
- Important: Your file writes are proposals that the user must review and accept before they take effect. Frame your responses accordingly — say "I've proposed the changes" or "Here are the changes for your review", not "Done" or "I've updated the file".
+ If the user is asking a question rather than requesting an edit, omit the code fence and just answer in prose.
"""
private static let defaultAgentSystemPrompt = """
You are an expert in writing agent definitions for AI coding assistants.
- ## Current agent context
+ ## File you're editing
- Name: {{skill_name}}
- Description: {{skill_description}}
- - File: {{file_path}}
- - Frontmatter:
- {{frontmatter}}
+ - Path: {{file_path}}
+
+ ## Your task
+ The user will give you their request along with the current file contents. Apply the request **minimally** — preserve every unchanged line exactly, including whitespace, blank lines, and wording. Do not refactor or "improve" anything the user didn't ask about.
+
+ ## Reply format (STRICT)
+ Reply with two things in this exact order:
+ 1. ONE OR TWO SENTENCES summarizing what changed (plain text, no preamble).
+ 2. The COMPLETE updated file content inside a single fenced code block. Open with ``` on its own line, then the full file (including YAML frontmatter), then ``` on its own line.
- ## Your role
- When the user asks you to create or update this agent, use the ACP `write_text_file` tool to write the complete updated file content directly to the file path shown above.
- Do not show the content in a code block or ask for confirmation — write it directly via `write_text_file`.
- Write the complete file including YAML frontmatter. Preserve all unchanged lines exactly as they appear — do not reformat, reindent, or alter any content you are not intentionally changing.
- Important: Your file writes are proposals that the user must review and accept before they take effect. Frame your responses accordingly — say "I've proposed the changes" or "Here are the changes for your review", not "Done" or "I've updated the file".
+ If the user is asking a question rather than requesting an edit, omit the code fence and just answer in prose.
"""
private static let defaultRuleSystemPrompt = """
You are an expert in writing rules for AI coding assistants.
- ## Current rule context
+ ## File you're editing
- Name: {{skill_name}}
- Description: {{skill_description}}
- - File: {{file_path}}
- - Frontmatter:
- {{frontmatter}}
+ - Path: {{file_path}}
- ## Your role
- When the user asks you to create or update this rule, use the ACP `write_text_file` tool to write the complete updated file content directly to the file path shown above.
- Do not show the content in a code block or ask for confirmation — write it directly via `write_text_file`.
- Write the complete file including YAML frontmatter. Preserve all unchanged lines exactly as they appear — do not reformat, reindent, or alter any content you are not intentionally changing.
- Important: Your file writes are proposals that the user must review and accept before they take effect. Frame your responses accordingly — say "I've proposed the changes" or "Here are the changes for your review", not "Done" or "I've updated the file".
- """
+ ## Your task
+ The user will give you their request along with the current file contents. Apply the request **minimally** — preserve every unchanged line exactly, including whitespace, blank lines, and wording. Do not refactor or "improve" anything the user didn't ask about.
-}
+ ## Reply format (STRICT)
+ Reply with two things in this exact order:
+ 1. ONE OR TWO SENTENCES summarizing what changed (plain text, no preamble).
+ 2. The COMPLETE updated file content inside a single fenced code block. Open with ``` on its own line, then the full file (including YAML frontmatter), then ``` on its own line.
+ If the user is asking a question rather than requesting an edit, omit the code fence and just answer in prose.
+ """
+}
diff --git a/Chops/Views/Settings/ACPSettingsView.swift b/Chops/Views/Settings/ACPSettingsView.swift
deleted file mode 100644
index 5397a54..0000000
--- a/Chops/Views/Settings/ACPSettingsView.swift
+++ /dev/null
@@ -1,254 +0,0 @@
-import ACPRegistry
-import SwiftUI
-
-struct ACPSettingsView: View {
- @State private var configuration = ACPConfiguration.shared
- @State private var templateManager = TemplateManager.shared
- @State private var templateContents: [WizardTemplateType: String] = [:]
- @State private var templateChanges: Set<WizardTemplateType> = []
- @State private var showingResetConfirm: WizardTemplateType?
- @State private var expandedTemplates: Set<WizardTemplateType> = []
-
- var body: some View {
- ScrollView {
- VStack(alignment: .leading, spacing: 16) {
- Text("Enable AI assistants to help compose and improve skills, agents, and rules.")
- .font(.callout)
- .foregroundStyle(.secondary)
-
- agentListSection
-
- HStack {
- Button("Refresh Registry") {
- Task { await configuration.refreshRegistry() }
- }
- .disabled(configuration.isLoadingRegistry)
- }
-
- Divider()
-
- templateSection
- }
- .padding()
- }
- .frame(maxHeight: 550)
- .task { await configuration.loadRegistryIfNeeded() }
- .onAppear { loadAllTemplates() }
- }
-
- // MARK: - Agent List
-
- @ViewBuilder
- private var agentListSection: some View {
- VStack(alignment: .leading, spacing: 8) {
- Text("Agents")
- .font(.headline)
-
- if configuration.isLoadingRegistry {
- HStack {
- ProgressView()
- .controlSize(.small)
- Text("Loading registry…")
- .foregroundStyle(.secondary)
- }
- } else if let error = configuration.registryError {
- HStack(spacing: 6) {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundStyle(.orange)
- Text(error)
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- } else if configuration.registryAgents.isEmpty {
- Text("No agents found.")
- .foregroundStyle(.secondary)
- } else {
- VStack(spacing: 0) {
- ForEach(configuration.registryAgents) { agent in
- AgentRow(agent: agent, configuration: configuration)
- if agent.id != configuration.registryAgents.last?.id {
- Divider()
- }
- }
- }
- .padding(8)
- .background(Color(NSColor.controlBackgroundColor))
- .clipShape(RoundedRectangle(cornerRadius: 6))
- }
- }
- }
-
- // MARK: - Wizard Templates
-
- private var templateSection: some View {
- VStack(alignment: .leading, spacing: 8) {
- Text("Chat Rules")
- .font(.headline)
-
- VStack(spacing: 0) {
- ForEach(WizardTemplateType.allCases) { type in
- VStack(spacing: 0) {
- Button {
- withAnimation(.easeInOut(duration: 0.15)) {
- if expandedTemplates.contains(type) {
- expandedTemplates.remove(type)
- } else {
- expandedTemplates.insert(type)
- }
- }
- } label: {
- HStack {
- Image(systemName: "chevron.right")
- .font(.caption2)
- .rotationEffect(expandedTemplates.contains(type) ? .degrees(90) : .zero)
- Label(type.displayName, systemImage: type.icon)
- Spacer()
- }
- .padding(.horizontal, 8)
- .padding(.vertical, 8)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
-
- if expandedTemplates.contains(type) {
- templateEditor(for: type)
- .padding(.horizontal, 8)
- .padding(.bottom, 8)
- }
- }
-
- if type != WizardTemplateType.allCases.last {
- Divider()
- }
- }
- }
- .padding(4)
- .background(Color(NSColor.controlBackgroundColor))
- .clipShape(RoundedRectangle(cornerRadius: 6))
- }
- }
-
- @ViewBuilder
- private func templateEditor(for type: WizardTemplateType) -> some View {
- let binding = Binding<String>(
- get: { templateContents[type] ?? "" },
- set: {
- templateContents[type] = $0
- templateChanges.insert(type)
- }
- )
-
- VStack(alignment: .leading, spacing: 8) {
- TextEditor(text: binding)
- .font(.system(.caption, design: .monospaced))
- .scrollContentBackground(.hidden)
- .frame(height: 200)
- .padding(6)
- .background(Color(NSColor.textBackgroundColor))
- .clipShape(RoundedRectangle(cornerRadius: 4))
-
- HStack {
- if templateChanges.contains(type) {
- Text("Unsaved changes")
- .font(.caption)
- .foregroundStyle(.orange)
- }
-
- Spacer()
-
- Button("Reset to Default") {
- showingResetConfirm = type
- }
- .buttonStyle(.plain)
- .foregroundStyle(.red)
- .font(.caption)
-
- Button("Save") {
- saveTemplate(type)
- }
- .buttonStyle(.borderedProminent)
- .controlSize(.small)
- .disabled(!templateChanges.contains(type))
- }
- }
- .confirmationDialog(
- "Reset Template?",
- isPresented: Binding(
- get: { showingResetConfirm == type },
- set: { if !$0 { showingResetConfirm = nil } }
- ),
- titleVisibility: .visible
- ) {
- Button("Reset to Default", role: .destructive) {
- templateManager.resetToDefault(type)
- loadTemplate(type)
- }
- Button("Cancel", role: .cancel) {}
- } message: {
- Text("This will replace your custom template with the default version.")
- }
- }
-
- // MARK: - Template Helpers
-
- private func loadAllTemplates() {
- for type in WizardTemplateType.allCases {
- loadTemplate(type)
- }
- }
-
- private func loadTemplate(_ type: WizardTemplateType) {
- if let template = templateManager.template(for: type) {
- templateContents[type] = template.content
- }
- templateChanges.remove(type)
- }
-
- private func saveTemplate(_ type: WizardTemplateType) {
- guard let content = templateContents[type] else { return }
- let template = WizardTemplate(
- type: type,
- content: content,
- lastModified: Date()
- )
- templateManager.save(template)
- templateChanges.remove(type)
- }
-}
-
-// MARK: - Agent Row
-
-private struct AgentRow: View {
- let agent: RegistryAgent
- @Bindable var configuration: ACPConfiguration
-
- var body: some View {
- HStack(spacing: 12) {
- VStack(alignment: .leading, spacing: 2) {
- Text(agent.name)
- .fontWeight(.medium)
- Text(agent.description)
- .font(.caption)
- .foregroundStyle(.secondary)
- .lineLimit(2)
- Text("v\(agent.version)")
- .font(.caption2)
- .foregroundStyle(.tertiary)
- }
- Spacer()
- Toggle("", isOn: Binding(
- get: { configuration.isEnabled(agent.id) },
- set: { configuration.setEnabled(agent.id, $0) }
- ))
- .labelsHidden()
- }
- .padding(.vertical, 4)
- }
-}
-
-// MARK: - Preview
-
-#Preview {
- ACPSettingsView()
- .frame(width: 480)
-}
diff --git a/Chops/Views/Settings/AgentSettingsView.swift b/Chops/Views/Settings/AgentSettingsView.swift
new file mode 100644
index 0000000..3c7fafc
--- /dev/null
+++ b/Chops/Views/Settings/AgentSettingsView.swift
@@ -0,0 +1,107 @@
+import SwiftUI
+
+struct AgentSettingsView: View {
+ @State private var configuration = AgentConfiguration.shared
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 16) {
+ Text("Enable AI assistants to help compose and improve skills, agents, and rules.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+
+ agentListSection
+ }
+ .padding()
+ }
+ .frame(maxHeight: 550)
+ }
+
+ @ViewBuilder
+ private var agentListSection: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Agents")
+ .font(.headline)
+
+ VStack(spacing: 0) {
+ ForEach(configuration.supported) { id in
+ AgentRow(agentId: id, configuration: configuration)
+ if id != configuration.supported.last {
+ Divider()
+ }
+ }
+ }
+ .padding(8)
+ .background(Color(NSColor.controlBackgroundColor))
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ }
+ }
+}
+
+// MARK: - Agent Row
+
+private struct AgentRow: View {
+ let agentId: AgentID
+ @Bindable var configuration: AgentConfiguration
+ @State private var localBinaryPath: String?
+ @State private var localVersion: String?
+
+ var body: some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(agentId.displayName)
+ .fontWeight(.medium)
+ if localBinaryPath != nil {
+ let v = localVersion.map { " v\($0)" } ?? ""
+ Text("Uses your installed \(agentId.displayName)\(v)")
+ .font(.caption)
+ .foregroundStyle(Color.secondary)
+ .lineLimit(2)
+ if let path = localBinaryPath {
+ Text(path)
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ } else {
+ Text("\(agentId.displayName) isn't installed.")
+ .font(.caption)
+ .foregroundStyle(Color.orange)
+ .lineLimit(2)
+ Link("Install \(agentId.displayName) →", destination: agentId.installURL)
+ .font(.caption2)
+ }
+ }
+ Spacer()
+ Toggle("", isOn: Binding(
+ get: { configuration.isEnabled(agentId) },
+ set: { configuration.setEnabled(agentId, $0) }
+ ))
+ .labelsHidden()
+ .disabled(localBinaryPath == nil)
+ }
+ .padding(.vertical, 4)
+ .task(id: agentId.id) {
+ await refreshLocalBinaryStatus()
+ }
+ }
+
+ private func refreshLocalBinaryStatus() async {
+ let source = agentId.toolSource
+ if let url = source.cliBinaryURL {
+ localBinaryPath = url.path
+ if let v = await source.cliVersion() {
+ localVersion = "\(v.major).\(v.minor).\(v.patch)"
+ }
+ } else {
+ localBinaryPath = nil
+ localVersion = nil
+ }
+ }
+}
+
+#Preview {
+ AgentSettingsView()
+ .frame(width: 480)
+}
diff --git a/Chops/Views/Settings/SettingsView.swift b/Chops/Views/Settings/SettingsView.swift
index ae19559..45e12f7 100644
--- a/Chops/Views/Settings/SettingsView.swift
+++ b/Chops/Views/Settings/SettingsView.swift
@@ -80,7 +80,7 @@ struct SettingsView: View {
case .library:
LibrarySettingsView()
case .aiAssist:
- ACPSettingsView()
+ AgentSettingsView()
case .scanDirs:
scanSettings
case .servers:
diff --git a/Chops/Views/Shared/ActivityRow.swift b/Chops/Views/Shared/ActivityRow.swift
new file mode 100644
index 0000000..8a6139e
--- /dev/null
+++ b/Chops/Views/Shared/ActivityRow.swift
@@ -0,0 +1,124 @@
+import SwiftUI
+
+/// One row in the agent activity feed. Tap to expand and see what the step actually did
+/// — a diff for Write/Edit/MultiEdit, or the raw input/output for everything else.
+struct ActivityRow: View {
+ let activity: AgentActivity
+ @State private var expanded = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Button {
+ if hasExpandableDetail { expanded.toggle() }
+ } label: {
+ HStack(spacing: 8) {
+ statusIcon
+ .frame(width: 14, alignment: .center)
+ Text(activity.title)
+ .font(.callout)
+ .foregroundStyle(textColor)
+ if let detail = activity.detail {
+ Text(detail)
+ .font(.caption.monospacedDigit())
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ if hasExpandableDetail {
+ Image(systemName: expanded ? "chevron.down" : "chevron.right")
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ }
+ }
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .disabled(!hasExpandableDetail)
+
+ if expanded {
+ expandedDetail
+ .padding(.leading, 22)
+ .padding(.top, 4)
+ }
+ }
+ }
+
+ private var hasExpandableDetail: Bool {
+ let p = activity.payload
+ return p.proposedText != nil || p.rawInput != nil || p.resultText != nil
+ }
+
+ private var textColor: Color {
+ switch activity.status {
+ case .failed: return .red
+ case .applied: return .primary
+ default: return .primary
+ }
+ }
+
+ @ViewBuilder
+ private var statusIcon: some View {
+ switch activity.status {
+ case .running:
+ ProgressView().controlSize(.mini)
+ case .done:
+ Image(systemName: "checkmark.circle.fill")
+ .foregroundStyle(.green)
+ .font(.caption)
+ case .applied:
+ // Distinct icon so the user can see at a glance "this changed disk".
+ Image(systemName: "checkmark.seal.fill")
+ .foregroundStyle(.blue)
+ .font(.caption)
+ case .failed:
+ Image(systemName: "xmark.circle.fill")
+ .foregroundStyle(.red)
+ .font(.caption)
+ }
+ }
+
+ @ViewBuilder
+ private var expandedDetail: some View {
+ let p = activity.payload
+ if let proposed = p.proposedText {
+ // Diff view for Write / Edit / MultiEdit.
+ DiffReviewPanel(
+ original: p.originalText ?? "",
+ proposed: proposed,
+ onAccept: nil,
+ onReject: nil,
+ isApplying: false
+ )
+ .frame(minHeight: 200, idealHeight: 280, maxHeight: 360)
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.2)))
+ } else if let result = p.resultText {
+ // Read / Bash / Grep / etc. — surface the tool result.
+ ScrollView {
+ Text(result)
+ .font(.system(.caption, design: .monospaced))
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(8)
+ }
+ .frame(maxHeight: 240)
+ .background(Color(.textBackgroundColor).opacity(0.5))
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.2)))
+ } else if let raw = p.rawInput {
+ // Fallback: show the raw input JSON.
+ ScrollView {
+ Text(raw)
+ .font(.system(.caption, design: .monospaced))
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(8)
+ }
+ .frame(maxHeight: 200)
+ .background(Color(.textBackgroundColor).opacity(0.5))
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.2)))
+ }
+ }
+}
diff --git a/Chops/Views/Shared/ACPLogViewer.swift b/Chops/Views/Shared/AgentLogViewer.swift
similarity index 81%
rename from Chops/Views/Shared/ACPLogViewer.swift
rename to Chops/Views/Shared/AgentLogViewer.swift
index e65b4fc..10ac19b 100644
--- a/Chops/Views/Shared/ACPLogViewer.swift
+++ b/Chops/Views/Shared/AgentLogViewer.swift
@@ -1,17 +1,16 @@
import SwiftUI
-/// Viewer for ACP debug logs
-struct ACPLogViewer: View {
+/// Viewer for the agent debug log file written by `AgentLogger`.
+struct AgentLogViewer: View {
@State private var logContent = ""
- @State private var debugEnabled = acpLog.debugEnabled
+ @State private var debugEnabled = agentLog.debugEnabled
@State private var autoRefresh = true
@State private var refreshTask: Task<Void, Never>?
var body: some View {
VStack(spacing: 0) {
- // Toolbar
HStack {
- Text("ACP Logs")
+ Text("Agent Logs")
.font(.headline)
Spacer()
@@ -20,7 +19,7 @@ struct ACPLogViewer: View {
.toggleStyle(.switch)
.controlSize(.small)
.onChange(of: debugEnabled) { _, newValue in
- acpLog.debugEnabled = newValue
+ agentLog.debugEnabled = newValue
}
Toggle("Auto-refresh", isOn: $autoRefresh)
@@ -36,7 +35,7 @@ struct ACPLogViewer: View {
.help("Refresh")
Button {
- acpLog.clearLogs()
+ agentLog.clearLogs()
refreshLogs()
} label: {
Image(systemName: "trash")
@@ -45,7 +44,7 @@ struct ACPLogViewer: View {
.help("Clear Logs")
Button {
- NSWorkspace.shared.selectFile(acpLog.logURL.path, inFileViewerRootedAtPath: "")
+ NSWorkspace.shared.selectFile(agentLog.logURL.path, inFileViewerRootedAtPath: "")
} label: {
Image(systemName: "folder")
}
@@ -58,7 +57,6 @@ struct ACPLogViewer: View {
Divider()
- // Log content
ScrollViewReader { proxy in
ScrollView {
Text(logContent)
@@ -87,8 +85,7 @@ struct ACPLogViewer: View {
private func refreshLogs() {
Task {
- let content = await acpLog.recentLogs(lines: 500)
- logContent = content
+ logContent = await agentLog.recentLogs(lines: 500)
}
}
@@ -97,14 +94,13 @@ struct ACPLogViewer: View {
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(1))
guard autoRefresh else { continue }
- let content = await acpLog.recentLogs(lines: 500)
- logContent = content
+ logContent = await agentLog.recentLogs(lines: 500)
}
}
}
}
#Preview {
- ACPLogViewer()
+ AgentLogViewer()
.frame(width: 600, height: 400)
}
diff --git a/Chops/Views/Shared/ComposeModel.swift b/Chops/Views/Shared/ComposeModel.swift
index 39a9c49..7ec0cf4 100644
--- a/Chops/Views/Shared/ComposeModel.swift
+++ b/Chops/Views/Shared/ComposeModel.swift
@@ -13,7 +13,28 @@ struct ChatDiff: Sendable {
let originalData: Data?
let existedBefore: Bool
let proposed: String
+ /// True when the agent already performed the disk write (e.g. Claude direct CLI). On
+ /// reject we must restore from `originalData`.
+ let agentDidWrite: Bool
var status: DiffStatus = .pending
+
+ init(
+ path: String,
+ original: String?,
+ originalData: Data?,
+ existedBefore: Bool,
+ proposed: String,
+ agentDidWrite: Bool = false,
+ status: DiffStatus = .pending
+ ) {
+ self.path = path
+ self.original = original
+ self.originalData = originalData
+ self.existedBefore = existedBefore
+ self.proposed = proposed
+ self.agentDidWrite = agentDidWrite
+ self.status = status
+ }
}
struct ChatMessage: Identifiable {
diff --git a/Chops/Views/Shared/ComposePanel.swift b/Chops/Views/Shared/ComposePanel.swift
index f0e6094..cb7f1e2 100644
--- a/Chops/Views/Shared/ComposePanel.swift
+++ b/Chops/Views/Shared/ComposePanel.swift
@@ -1,8 +1,6 @@
-import ACPModel
-import ACPRegistry
import SwiftUI
-/// Inline panel for composing/editing skill content with ACP
+/// Inline panel for composing/editing skill content via the user's installed Claude or Codex.
struct ComposePanel: View {
private struct DiffApplyError: Identifiable {
let id = UUID()
@@ -22,16 +20,16 @@ struct ComposePanel: View {
@State private var selectedTemplateType: WizardTemplateType
@State private var inputText = ""
- @AppStorage("ACPSelectedAgentId") private var selectedAgentId: String?
- @State private var acpClient: BaseACPAgent?
+ @AppStorage("AgentSelectedId") private var selectedAgentId: String?
+ @State private var agent: (any AgentSession)?
@State private var showingDebugLogs = false
- /// Completed conversation history. Never holds in-flight messages — the SDK drives live state.
+ /// Completed conversation history. Never holds in-flight messages — the agent drives live state.
@State private var messages: [ChatMessage] = []
/// True until the first successful prompt in this session.
@State private var isFirstTurn = true
- @AppStorage("ACPDebugLogging") private var debugLoggingEnabled = false
+ @AppStorage("AgentDebugLogging") private var debugLoggingEnabled = false
@State private var panelHeight: CGFloat = ComposeConstants.defaultPanelHeight
@State private var isDragging = false
@State private var dragStartHeight: CGFloat?
@@ -63,12 +61,12 @@ struct ComposePanel: View {
self._selectedTemplateType = State(initialValue: templateType)
}
- private var configuredAgents: [RegistryAgent] { ACPConfiguration.shared.enabledAgents }
- private var selectedAgent: RegistryAgent? { configuredAgents.first { $0.id == selectedAgentId } }
+ private var configuredAgents: [AgentID] { AgentConfiguration.shared.enabledAgents }
+ private var selectedAgent: AgentID? { selectedAgentId.flatMap(AgentID.init(rawValue:)) }
- private var isConnected: Bool { acpClient?.isConnected ?? false }
- private var isConnecting: Bool { acpClient?.isConnecting ?? false }
- private var isProcessing: Bool { acpClient?.isProcessing ?? false }
+ private var isConnected: Bool { agent?.isConnected ?? false }
+ private var isConnecting: Bool { agent?.isConnecting ?? false }
+ private var isProcessing: Bool { agent?.isProcessing ?? false }
private var hasPendingDiffs: Bool { messages.contains { $0.diffs.contains { $0.status == .pending } } }
var body: some View {
@@ -93,7 +91,7 @@ struct ComposePanel: View {
.background(Color(.windowBackgroundColor))
.onAppear {
if selectedAgentId == nil {
- selectedAgentId = configuredAgents.first?.id
+ selectedAgentId = configuredAgents.first?.rawValue
}
}
.onDisappear {
@@ -102,17 +100,16 @@ struct ComposePanel: View {
.onChange(of: selectedAgentId) { _, _ in
forceDisconnect()
}
- .onChange(of: configuredAgents.map(\.id)) { _, newIds in
+ .onChange(of: configuredAgents.map(\.rawValue)) { _, newIds in
if selectedAgentId == nil || !newIds.contains(selectedAgentId ?? "") {
selectedAgentId = newIds.first
}
}
- .task { await ACPConfiguration.shared.loadRegistryIfNeeded() }
.sheet(isPresented: Binding(
- get: { acpClient?.pendingPermissionRequest != nil },
- set: { if !$0 { acpClient?.respondToPermission(optionId: nil) } }
+ get: { agent?.pendingPermissionRequest != nil },
+ set: { if !$0 { agent?.respondToPermission(optionId: nil) } }
)) {
- if let request = acpClient?.pendingPermissionRequest {
+ if let request = agent?.pendingPermissionRequest {
permissionSheet(request: request)
}
}
@@ -127,6 +124,17 @@ struct ComposePanel: View {
@ViewBuilder
private func permissionSheet(request: PermissionRequest) -> some View {
+ if let diff = request.diffPreview {
+ // Pre-flight diff approval. The agent has NOT touched the file yet — clicking
+ // Approve writes it, clicking Reject leaves disk untouched.
+ diffPermissionSheet(request: request, diff: diff)
+ } else {
+ simplePermissionSheet(request: request)
+ }
+ }
+
+ @ViewBuilder
+ private func simplePermissionSheet(request: PermissionRequest) -> some View {
VStack(alignment: .leading, spacing: 16) {
Label("Permission Required", systemImage: "hand.raised.fill")
.font(.headline)
@@ -136,7 +144,7 @@ struct ComposePanel: View {
VStack(alignment: .leading, spacing: 8) {
ForEach(request.options, id: \.optionId) { option in
Button(option.name) {
- acpClient?.respondToPermission(optionId: option.optionId)
+ agent?.respondToPermission(optionId: option.optionId)
}
.buttonStyle(.bordered)
.tint(permissionOptionTint(for: option.kind))
@@ -144,7 +152,7 @@ struct ComposePanel: View {
}
Divider()
Button("Cancel") {
- acpClient?.respondToPermission(optionId: nil)
+ agent?.respondToPermission(optionId: nil)
}
.foregroundStyle(.secondary)
}
@@ -152,6 +160,56 @@ struct ComposePanel: View {
.frame(minWidth: 320, maxWidth: 440)
}
+ @ViewBuilder
+ private func diffPermissionSheet(request: PermissionRequest, diff: PermissionDiffPreview) -> some View {
+ let fileName = URL(fileURLWithPath: diff.path).lastPathComponent
+ let approveOption = request.options.first { $0.kind.hasPrefix("allow") }
+ let rejectOption = request.options.first { $0.kind.hasPrefix("reject") }
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 8) {
+ Image(systemName: diff.existedBefore ? "pencil.line" : "doc.badge.plus")
+ .foregroundStyle(.tint)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(request.title)
+ .font(.headline)
+ Text(diff.path)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ Spacer()
+ }
+
+ DiffReviewPanel(
+ original: diff.originalText ?? "",
+ proposed: diff.proposedText,
+ onAccept: {
+ agent?.respondToPermission(optionId: approveOption?.optionId)
+ },
+ onReject: {
+ agent?.respondToPermission(optionId: rejectOption?.optionId)
+ },
+ isApplying: false
+ )
+ .frame(minHeight: 320, idealHeight: 420, maxHeight: 540)
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.secondary.opacity(0.2)))
+
+ HStack {
+ Spacer()
+ Button("Cancel") {
+ agent?.respondToPermission(optionId: nil)
+ }
+ .keyboardShortcut(.cancelAction)
+ .foregroundStyle(.secondary)
+ }
+ }
+ .padding(20)
+ .frame(minWidth: 640, idealWidth: 820, maxWidth: 1100)
+ .accessibilityLabel("Approve change to \(fileName)")
+ }
+
private func permissionOptionTint(for kind: String) -> Color {
switch kind {
case "allow_once", "allow_always": return .green
@@ -175,30 +233,13 @@ struct ComposePanel: View {
.foregroundStyle(.secondary)
Picker("", selection: $selectedAgentId) {
Text("Select agent…").tag(nil as String?)
- ForEach(configuredAgents) { agent in
- Text(agent.name).tag(Optional(agent.id))
+ ForEach(configuredAgents) { agentId in
+ Text(agentId.displayName).tag(Optional(agentId.rawValue))
}
}
.labelsHidden()
.fixedSize()
- if selectedAgentId != nil {
- if isConnecting {
- HStack(spacing: 6) {
- ProgressView().controlSize(.small)
- Text("Connecting…")
- .foregroundStyle(.secondary)
- }
- .font(.callout)
- } else {
- Button {
- connect()
- } label: {
- Label("Connect", systemImage: "link")
- }
- .buttonStyle(.borderedProminent)
- .controlSize(.regular)
- }
- }
+ connectControlsForSelectedAgent
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
@@ -207,7 +248,55 @@ struct ComposePanel: View {
}
}
- private let configuration = ACPConfiguration.shared
+ /// Connect / Connecting / Install controls for the currently-selected agent.
+ @ViewBuilder
+ private var connectControlsForSelectedAgent: some View {
+ if let agentId = selectedAgent {
+ if isConnecting {
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.small)
+ Text("Connecting…")
+ .foregroundStyle(.secondary)
+ }
+ .font(.callout)
+ } else if agentId.toolSource.cliBinaryURL == nil {
+ VStack(spacing: 8) {
+ Text("\(agentId.displayName) isn't installed.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ Link(destination: agentId.installURL) {
+ Label("Install \(agentId.displayName)", systemImage: "arrow.down.circle")
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.regular)
+ }
+ } else if let error = agent?.lastError {
+ VStack(spacing: 8) {
+ Text(error)
+ .font(.callout)
+ .foregroundStyle(.red)
+ .multilineTextAlignment(.center)
+ .lineLimit(4)
+ Button {
+ connect()
+ } label: {
+ Label("Retry", systemImage: "arrow.clockwise")
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.regular)
+ }
+ .frame(maxWidth: 360)
+ } else {
+ Button {
+ connect()
+ } label: {
+ Label("Connect", systemImage: "link")
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.regular)
+ }
+ }
+ }
private var noToolsConfiguredView: some View {
ZStack(alignment: .topTrailing) {
@@ -220,33 +309,26 @@ struct ComposePanel: View {
.foregroundStyle(.secondary)
VStack(spacing: 0) {
- if configuration.isLoadingRegistry {
- HStack(spacing: 6) {
- ProgressView().controlSize(.small)
- Text("Loading agents…").foregroundStyle(.secondary)
- }
- .padding(.vertical, 12)
- } else {
- ForEach(configuration.registryAgents) { agent in
- HStack(spacing: 10) {
- VStack(alignment: .leading, spacing: 1) {
- Text(agent.name)
- .font(.callout.weight(.medium))
- Text(agent.description)
- .font(.caption)
- .foregroundStyle(.secondary)
- .lineLimit(1)
- }
- Spacer()
- Toggle("", isOn: Binding(
- get: { configuration.isEnabled(agent.id) },
- set: { configuration.setEnabled(agent.id, $0) }
- ))
- .labelsHidden()
+ ForEach(AgentConfiguration.shared.supported) { agentId in
+ HStack(spacing: 10) {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(agentId.displayName)
+ .font(.callout.weight(.medium))
+ Text(agentId.description)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
}
- .padding(.horizontal, 12)
- .padding(.vertical, 8)
+ Spacer()
+ Toggle("", isOn: Binding(
+ get: { AgentConfiguration.shared.isEnabled(agentId) },
+ set: { AgentConfiguration.shared.setEnabled(agentId, $0) }
+ ))
+ .labelsHidden()
+ .disabled(agentId.toolSource.cliBinaryURL == nil)
}
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
}
}
.background(Color.primary.opacity(0.05))
@@ -258,7 +340,6 @@ struct ComposePanel: View {
closeButton
.padding(12)
}
- .task { await configuration.loadRegistryIfNeeded() }
}
private var topBar: some View {
@@ -267,8 +348,8 @@ struct ComposePanel: View {
HStack(spacing: 8) {
Picker("", selection: $selectedAgentId) {
Text("Select...").tag(nil as String?)
- ForEach(configuredAgents) { agent in
- Text(agent.name).tag(Optional(agent.id))
+ ForEach(configuredAgents) { agentId in
+ Text(agentId.displayName).tag(Optional(agentId.rawValue))
}
}
.labelsHidden()
@@ -281,7 +362,7 @@ struct ComposePanel: View {
Spacer()
// Error indicator — connection errors reported by the agent.
- if let error = acpClient?.lastError {
+ if let error = agent?.lastError {
HStack(spacing: 4) {
Image(systemName: "exclamationmark.circle.fill")
.foregroundStyle(.red)
@@ -293,54 +374,13 @@ struct ComposePanel: View {
.frame(maxWidth: 200)
}
- // RIGHT: config options (when connected) + close
- HStack(spacing: 8) {
- inlineConfigOptions
- closeButton
- }
+ closeButton
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(Color(.controlBackgroundColor))
}
- // MARK: - Config Options Bar
-
- /// Inline config option pickers shown in the top bar when connected.
- @ViewBuilder
- private var inlineConfigOptions: some View {
- let options = acpClient?.sessionConfigOptions ?? []
- if isConnected && !options.isEmpty {
- ForEach(options, id: \.id) { option in
- if case .select(let select) = option.kind {
- configOptionPicker(option: option, select: select)
- }
- }
- }
- }
-
- @ViewBuilder
- private func configOptionPicker(option: SessionConfigOption, select: SessionConfigSelect) -> some View {
- let flatOptions: [SessionConfigSelectOption] = {
- switch select.options {
- case .ungrouped(let opts): return opts
- case .grouped(let groups): return groups.flatMap(\.options)
- }
- }()
- Picker(option.name, selection: Binding(
- get: { select.currentValue },
- set: { newValue in
- Task { try? await acpClient?.setConfigOption(id: option.id, value: newValue) }
- }
- )) {
- ForEach(flatOptions, id: \.value) { opt in
- Text(opt.name.replacingOccurrences(of: " (recommended)", with: "")).tag(opt.value)
- }
- }
- .fixedSize()
- .help(option.description ?? option.name)
- }
-
// MARK: - Chat Area
/// Completed messages worth showing — assistant turns with no text and no diffs are omitted.
@@ -389,7 +429,7 @@ struct ComposePanel: View {
withAnimation { proxy.scrollTo(last.id, anchor: .bottom) }
}
}
- .onChange(of: acpClient?.currentActivity) { _, _ in
+ .onChange(of: agent?.currentActivity) { _, _ in
if isProcessing {
withAnimation { proxy.scrollTo("live-assistant", anchor: .bottom) }
}
@@ -433,10 +473,11 @@ struct ComposePanel: View {
@ViewBuilder
private func liveAssistantRow(bubbleWidth: CGFloat) -> some View {
- let thoughtText = acpClient?.thoughtText ?? ""
- let responseText = acpClient?.responseText ?? ""
- let displayText = acpClient?.conversationalText(from: responseText) ?? responseText
- let activity = acpClient?.currentActivity
+ let thoughtText = agent?.thoughtText ?? ""
+ let responseText = agent?.responseText ?? ""
+ let displayText = agent?.conversationalText(from: responseText) ?? responseText
+ let waitingOnUser = agent?.pendingPermissionRequest != nil
+ let activities = agent?.activities ?? []
VStack(alignment: .leading, spacing: 6) {
if !thoughtText.isEmpty {
@@ -448,6 +489,8 @@ struct ComposePanel: View {
Image(systemName: "sparkles").foregroundStyle(.secondary)
Text("Agent").foregroundStyle(.secondary)
Spacer()
+ elapsedTurnLabel
+ inlineStopButton
}
.font(.caption)
.padding(.horizontal, 10).padding(.top, 8).padding(.bottom, 4)
@@ -460,17 +503,16 @@ struct ComposePanel: View {
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 10).padding(.vertical, 8)
- } else if let activity {
- HStack(spacing: 6) {
- ProgressView().controlSize(.mini)
- Text(activity).foregroundStyle(.secondary)
- }
- .font(.callout)
- .padding(.horizontal, 10).padding(.vertical, 8)
- } else {
+ }
+
+ if !activities.isEmpty {
+ activityFeed(activities, waitingOnUser: waitingOnUser)
+ .padding(.horizontal, 10).padding(.vertical, 8)
+ } else if displayText.isEmpty {
HStack(spacing: 6) {
ProgressView().controlSize(.mini)
- Text("Working…").foregroundStyle(.secondary)
+ Text(waitingOnUser ? "Waiting for your approval" : "Working…")
+ .foregroundStyle(.secondary)
}
.font(.callout)
.padding(.horizontal, 10).padding(.vertical, 8)
@@ -483,6 +525,70 @@ struct ComposePanel: View {
}
}
+ @ViewBuilder
+ private func activityFeed(_ activities: [AgentActivity], waitingOnUser: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 4) {
+ ForEach(activities) { activity in
+ ActivityRow(activity: activity)
+ }
+ if waitingOnUser {
+ HStack(spacing: 8) {
+ Image(systemName: "hand.raised.fill")
+ .foregroundStyle(.orange)
+ .frame(width: 14, alignment: .center)
+ Text("Waiting for your approval")
+ .font(.callout)
+ .foregroundStyle(.orange)
+ Spacer()
+ }
+ }
+ }
+ }
+
+ private func liveStatusText(activity: String?, waitingOnUser: Bool) -> String {
+ if waitingOnUser {
+ return "Waiting for your approval"
+ }
+ return activity ?? "Working…"
+ }
+
+ /// Ticks every second while a turn is in flight so the elapsed-time label updates.
+ @ViewBuilder
+ private var elapsedTurnLabel: some View {
+ if let started = agent?.turnStartedAt {
+ TimelineView(.periodic(from: started, by: 1.0)) { ctx in
+ Text(formatElapsed(from: started, to: ctx.date))
+ .font(.caption.monospacedDigit())
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var inlineStopButton: some View {
+ if isProcessing {
+ Button {
+ agent?.cancelPrompt()
+ } label: {
+ Label("Stop", systemImage: "stop.fill")
+ .labelStyle(.titleAndIcon)
+ .font(.caption)
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ .tint(.red)
+ .help("Stop this turn (⌘.)")
+ }
+ }
+
+ private func formatElapsed(from start: Date, to now: Date) -> String {
+ let s = Int(now.timeIntervalSince(start))
+ if s < 60 { return "\(s)s" }
+ let m = s / 60
+ let r = s % 60
+ return "\(m)m \(r)s"
+ }
+
// MARK: - Completed Message Rows
@ViewBuilder
@@ -622,7 +728,7 @@ struct ComposePanel: View {
if isProcessing {
Button {
- acpClient?.cancelPrompt()
+ agent?.cancelPrompt()
} label: {
Image(systemName: "stop.fill")
.font(.body)
@@ -713,7 +819,7 @@ struct ComposePanel: View {
.frame(width: 20, height: 20)
}
.buttonStyle(.plain)
- .help(isConnected ? "Disconnect" : isConnecting ? "Cancel connection" : "Connect to \(selectedAgent?.name ?? "agent")")
+ .help(isConnected ? "Disconnect" : isConnecting ? "Cancel connection" : "Connect to \(selectedAgent?.displayName ?? "agent")")
.disabled(selectedAgentId == nil)
}
@@ -740,9 +846,9 @@ struct ComposePanel: View {
.foregroundStyle(.orange)
}
.buttonStyle(.plain)
- .help("View ACP Logs")
+ .help("View Agent Logs")
.popover(isPresented: $showingDebugLogs) {
- ACPLogViewer()
+ AgentLogViewer()
.frame(width: 600, height: 400)
}
}
@@ -751,9 +857,9 @@ struct ComposePanel: View {
// MARK: - Actions
private func connect() {
- guard let agent = selectedAgent, !isConnected, !isConnecting else { return }
- let client = ACPAgentFactory.make(for: agent.id)
- acpClient = client // agent's @Observable state drives the UI from this point
+ guard let agentId = selectedAgent, !isConnected, !isConnecting else { return }
+ let client = AgentFactory.make(for: agentId)
+ agent = client // agent's @Observable state drives the UI from this point
let systemPrompt = TemplateManager.shared.systemPrompt(
for: selectedTemplateType,
skillName: skillName,
@@ -761,11 +867,11 @@ struct ComposePanel: View {
filePath: filePath,
frontmatter: frontmatter
)
- client.startConnect(agent: agent, workingDirectory: workingDirectory, systemPrompt: systemPrompt)
+ client.startConnect(workingDirectory: workingDirectory, systemPrompt: systemPrompt)
}
private func sendMessage() {
- guard let client = acpClient else { return }
+ guard let client = agent else { return }
let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else { return }
@@ -781,17 +887,21 @@ struct ComposePanel: View {
// readFile(at:) reads disk, which may be stale (auto-save debounce).
let original = content
client.primeDeferredContent(for: fp, content: original)
- let prompt = buildPrompt(text: text, originalContent: original)
- try await client.prompt(prompt)
+ // The agent owns prompt construction (system prompt + file content +
+ // user request). We just hand it the raw user text.
+ try await client.prompt(text)
isFirstTurn = false
let raw = client.responseText
let processed = client.conversationalText(from: raw)
let finalText = processed.isEmpty ? raw : processed
- acpLog.info("Compose: turn done — raw=\(raw.count) chars, thought=\(client.thoughtText.count) chars")
+ agentLog.info("Compose: turn done — raw=\(raw.count) chars, thought=\(client.thoughtText.count) chars")
messages.append(ChatMessage(id: assistantId, role: .assistant, text: finalText, thoughtText: client.thoughtText))
await handleWrites(client: client, messageId: assistantId, filePath: fp, originalContent: original)
+ } catch is CancellationError {
+ client.clearPendingWrites()
+ messages.append(ChatMessage(id: assistantId, role: .assistant, text: "Stopped."))
} catch {
client.clearPendingWrites()
messages.append(ChatMessage(id: assistantId, role: .assistant, text: error.localizedDescription, isError: true))
@@ -807,22 +917,12 @@ struct ComposePanel: View {
}.value
}
- /// Expands the template on the first turn; returns plain text on subsequent turns.
- private func buildPrompt(text: String, originalContent: String) -> String {
- guard isFirstTurn, let template = TemplateManager.shared.template(for: selectedTemplateType) else {
- return text
- }
- return template.content
- .replacingOccurrences(of: "{{file_content}}", with: originalContent.isEmpty ? "(empty)" : originalContent)
- .replacingOccurrences(of: "{{user_instructions}}", with: text)
- }
-
/// Attaches diffs from pending writes or disk changes; logs text-only turns.
- private func handleWrites(client: BaseACPAgent, messageId: UUID, filePath: String, originalContent: String) async {
+ private func handleWrites(client: any AgentSession, messageId: UUID, filePath: String, originalContent: String) async {
let autoAccept = client.isBypassMode
- acpLog.info("Compose: handleWrites — filePath=\(filePath) originalContent.count=\(originalContent.count) autoAccept=\(autoAccept)")
+ agentLog.info("Compose: handleWrites — filePath=\(filePath) originalContent.count=\(originalContent.count) autoAccept=\(autoAccept)")
if !client.pendingWrites.isEmpty {
- acpLog.info("Compose: attaching \(client.pendingWrites.count) diff(s) from write_text_file")
+ agentLog.info("Compose: attaching \(client.pendingWrites.count) diff(s) from write_text_file")
await attachDiffs(messageId: messageId, writes: client.pendingWrites, fallbackOriginal: originalContent, autoAccept: autoAccept)
client.clearPendingWrites()
return
@@ -848,7 +948,7 @@ struct ComposePanel: View {
}
/// Converts pending writes into ChatDiff entries and attaches them to the message.
- /// Uses the pre-write snapshot captured by the ACP layer; do not reread disk here because
+ /// Uses the pre-write snapshot captured by the agent transport; do not reread disk here because
/// the agent may already have mutated the file.
/// Resolves `path` through symlinks so that e.g. a `.cursor/rules/foo.md` symlink
/// and its target `~/.aidevtools/rules/foo.md` compare as equal.
@@ -864,7 +964,7 @@ struct ComposePanel: View {
) async {
guard let idx = messages.firstIndex(where: { $0.id == messageId }) else { return }
let resolvedFilePath = resolvedPath(filePath)
- acpLog.debug("Compose: attachDiffs — filePath=\(filePath) resolved=\(resolvedFilePath) fallback.count=\(fallbackOriginal.count)")
+ agentLog.debug("Compose: attachDiffs — filePath=\(filePath) resolved=\(resolvedFilePath) fallback.count=\(fallbackOriginal.count)")
var diffs: [ChatDiff] = []
for write in writes {
let writtenResolved = resolvedPath(write.path)
@@ -886,14 +986,21 @@ struct ComposePanel: View {
originalData = write.originalData
existedBefore = write.existedBefore
}
- acpLog.debug("Compose: diff \(write.path) original=\(original?.count ?? -1) chars")
+ agentLog.debug("Compose: diff \(write.path) original=\(original?.count ?? -1) chars")
+ // For direct-CLI agents the user has already approved this write via the
+ // pre-flight permission sheet (which renders the diff). Mark it accepted so
+ // the chat shows a record without prompting again. ACP-style writes (none today)
+ // would still arrive as .pending.
+ let initialStatus: DiffStatus = write.agentDidWrite ? .accepted : .pending
diffs.append(
ChatDiff(
path: write.path,
original: original,
originalData: originalData,
existedBefore: existedBefore,
- proposed: write.content
+ proposed: write.content,
+ agentDidWrite: write.agentDidWrite,
+ status: initialStatus
)
)
}
@@ -920,8 +1027,14 @@ struct ComposePanel: View {
if resolvedPath(diff.path) == resolvedPath(filePath) {
messages[msgIdx].diffs[diffIndex].status = .accepted
// Currently-open file: update editor binding, onAccept() persists to disk.
+ // Direct-CLI agents already wrote to disk; skip re-persist to avoid a redundant write.
content = diff.proposed
- onAccept()
+ if !diff.agentDidWrite {
+ onAccept()
+ }
+ } else if diff.agentDidWrite {
+ // Direct-CLI: file is already at proposed content on disk. Just mark accepted.
+ messages[msgIdx].diffs[diffIndex].status = .accepted
} else {
let actionID = diffActionID(messageId: messageId, diffIndex: diffIndex)
guard applyingDiffID != actionID else { return }
@@ -950,8 +1063,46 @@ struct ComposePanel: View {
private func rejectDiff(messageId: UUID, diffIndex: Int) {
guard let msgIdx = messages.firstIndex(where: { $0.id == messageId }),
diffIndex < messages[msgIdx].diffs.count else { return }
+ let diff = messages[msgIdx].diffs[diffIndex]
messages[msgIdx].diffs[diffIndex].status = .rejected
- // No disk revert needed — file was never written.
+
+ // Direct-CLI agents (Claude, Codex) already wrote to disk by the time the user sees
+ // the diff. Revert from the snapshot we captured pre-write.
+ guard diff.agentDidWrite else { return }
+ let resolvedDiffPath = resolvedPath(diff.path)
+ let editorIsThisFile = resolvedDiffPath == resolvedPath(filePath)
+ Task {
+ do {
+ try await Self.revertWrittenDiff(diff)
+ if editorIsThisFile, let original = diff.original {
+ content = original
+ }
+ } catch {
+ let fileName = URL(fileURLWithPath: diff.path).lastPathComponent
+ AppLogger.fileIO.error("Revert failed for \(diff.path): \(error.localizedDescription)")
+ diffApplyError = DiffApplyError(
+ message: "Couldn't revert \(fileName): \(error.localizedDescription)"
+ )
+ }
+ }
+ }
+
+ /// Restores a file to its pre-write state. If the file didn't exist before, removes it.
+ nonisolated private static func revertWrittenDiff(_ diff: ChatDiff) async throws {
+ try await Task.detached(priority: .userInitiated) {
+ let url = URL(fileURLWithPath: diff.path)
+ if diff.existedBefore {
+ if let originalData = diff.originalData {
+ try originalData.write(to: url, options: .atomic)
+ } else if let original = diff.original {
+ try original.write(to: url, atomically: true, encoding: .utf8)
+ }
+ } else {
+ if FileManager.default.fileExists(atPath: url.path) {
+ try FileManager.default.removeItem(at: url)
+ }
+ }
+ }.value
}
private func diffActionID(messageId: UUID, diffIndex: Int) -> String {
@@ -970,8 +1121,8 @@ struct ComposePanel: View {
}
private func forceDisconnect() {
- let client = acpClient
- acpClient = nil
+ let client = agent
+ agent = nil
isFirstTurn = true
messages = []
applyingDiffID = nil
diff --git a/Chops/Views/Shared/DiffReviewPanel.swift b/Chops/Views/Shared/DiffReviewPanel.swift
index c328925..e1f6538 100644
--- a/Chops/Views/Shared/DiffReviewPanel.swift
+++ b/Chops/Views/Shared/DiffReviewPanel.swift
@@ -98,8 +98,9 @@ func computeDiff(from original: String, to proposed: String) -> [DiffLine] {
struct DiffReviewPanel: View {
let original: String
let proposed: String
- let onAccept: () -> Void
- let onReject: () -> Void
+ /// When nil, the Accept/Reject footer is hidden — the panel becomes read-only.
+ let onAccept: (() -> Void)?
+ let onReject: (() -> Void)?
var isApplying = false
@State private var lines: [DiffLine] = []
@@ -144,17 +145,21 @@ struct DiffReviewPanel: View {
Spacer()
- Button("Reject", action: onReject)
- .buttonStyle(.bordered)
- .controlSize(.small)
- .disabled(isApplying)
-
- Button(isApplying ? "Applying..." : "Accept", action: onAccept)
- .buttonStyle(.borderedProminent)
- .controlSize(.small)
- .tint(.green)
- .keyboardShortcut(.return, modifiers: .command)
- .disabled(isApplying)
+ if let onReject {
+ Button("Reject", action: onReject)
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ .disabled(isApplying)
+ }
+
+ if let onAccept {
+ Button(isApplying ? "Applying..." : "Accept", action: onAccept)
+ .buttonStyle(.borderedProminent)
+ .controlSize(.small)
+ .tint(.green)
+ .keyboardShortcut(.return, modifiers: .command)
+ .disabled(isApplying)
+ }
}
.padding(.horizontal, 12)
.padding(.vertical, 6)
diff --git a/project.yml b/project.yml
index 79d01a7..2bdf8e2 100644
--- a/project.yml
+++ b/project.yml
@@ -15,9 +15,6 @@ packages:
Sparkle:
url: https://github.com/sparkle-project/Sparkle
from: "2.6.0"
- ACP:
- url: https://github.com/wiedymi/swift-acp
- branch: main
Highlightr:
url: https://github.com/raspu/Highlightr
from: "2.2.1"
@@ -39,12 +36,6 @@ targets:
- package: Highlightr
- package: cmark-gfm
product: cmark
- - package: ACP
- product: ACP
- - package: ACP
- product: ACPModel
- - package: ACP
- product: ACPRegistry
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: com.joshpigford.Chops