diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d4c9962..ebd0bead 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@v7 - - uses: maxim-lobanov/setup-xcode@v1 + - uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1 with: xcode-version: ${{ env.XCODE_VERSION }} # Formatting and style, with the swift-format that comes with Xcode and diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4bd99662..fb03ac93 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,14 +70,19 @@ jobs: timeout-minutes: 45 steps: - uses: actions/checkout@v7 - - uses: maxim-lobanov/setup-xcode@v1 + - uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1 with: xcode-version: ${{ env.XCODE_VERSION }} + # What was typed is given through the environment and checked, never + # pasted into the script (#318). - name: Resolve version id: version + env: + TYPED_VERSION: ${{ inputs.version }} run: | - if [ -n "${{ inputs.version }}" ]; then v="${{ inputs.version }}"; else v="${GITHUB_REF_NAME#v}"; fi + if [ -n "$TYPED_VERSION" ]; then v="$TYPED_VERSION"; else v="${GITHUB_REF_NAME#v}"; fi + printf '%s' "$v" | grep -Eqx '[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?' || { echo "Not a version like 0.15.1 or 0.15.1-beta.1: $v" >&2; exit 1; } echo "value=$v" >> "$GITHUB_OUTPUT" case "$v" in *-*) echo "prerelease=true" >> "$GITHUB_OUTPUT" ;; *) echo "prerelease=false" >> "$GITHUB_OUTPUT" ;; esac @@ -85,9 +90,11 @@ jobs: # notes have to be written: the GitHub release and TestFlight show them. - name: Check the version and its release notes id: notes + env: + VERSION: ${{ steps.version.outputs.value }} run: | - scripts/check-version.sh "${{ steps.version.outputs.value }}" - echo "path=$(scripts/check-release-notes.sh "${{ steps.version.outputs.value }}")" >> "$GITHUB_OUTPUT" + scripts/check-version.sh "$VERSION" + echo "path=$(scripts/check-release-notes.sh "$VERSION")" >> "$GITHUB_OUTPUT" - name: Install fastlane run: command -v fastlane >/dev/null || brew install fastlane @@ -124,10 +131,17 @@ jobs: fastlane mac release cd dist && shasum -a 256 "AgentTerm-$VERSION.dmg" > "AgentTerm-$VERSION.sha256" + # Gone before publishing: nothing after this needs them (#314). + - name: Remove the signing files + run: rm -f "$RUNNER_TEMP/asc_key.p8" "$RUNNER_TEMP/developer_id.p12" "$RUNNER_TEMP/firebase.plist" + - name: Publish GitHub release - uses: softprops/action-gh-release@v3 + uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3 with: tag_name: ${{ github.ref_type == 'tag' && github.ref_name || format('v{0}', steps.version.outputs.value) }} + # A release started by hand from a branch tags the commit that was + # built, not the default branch's head (#315). + target_commitish: ${{ github.sha }} name: AgentTerm ${{ steps.version.outputs.value }} prerelease: ${{ steps.version.outputs.prerelease }} body_path: ${{ steps.notes.outputs.path }} @@ -141,9 +155,12 @@ jobs: if: env.HOMEBREW_TAP_TOKEN != '' env: HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} - run: scripts/publish-homebrew.sh "${{ steps.version.outputs.value }}" + # For the release's published checksum (#316). + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.version.outputs.value }} + run: scripts/publish-homebrew.sh "$VERSION" - - name: Remove the signing files + - name: Remove the signing files, whatever happened if: always() run: rm -f "$RUNNER_TEMP/asc_key.p8" "$RUNNER_TEMP/developer_id.p12" "$RUNNER_TEMP/firebase.plist" @@ -154,14 +171,18 @@ jobs: timeout-minutes: 45 steps: - uses: actions/checkout@v7 - - uses: maxim-lobanov/setup-xcode@v1 + - uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1 with: xcode-version: ${{ env.XCODE_VERSION }} + # What was typed is given through the environment and checked (#318). - name: Resolve version id: version + env: + TYPED_VERSION: ${{ inputs.version }} run: | - if [ -n "${{ inputs.version }}" ]; then v="${{ inputs.version }}"; else v="${GITHUB_REF_NAME#v}"; fi + if [ -n "$TYPED_VERSION" ]; then v="$TYPED_VERSION"; else v="${GITHUB_REF_NAME#v}"; fi + printf '%s' "$v" | grep -Eqx '[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?' || { echo "Not a version like 0.15.1 or 0.15.1-beta.1: $v" >&2; exit 1; } # TestFlight takes numbers only: 0.2.0-beta.1 is uploaded as 0.2.0. echo "value=${v%%-*}" >> "$GITHUB_OUTPUT" echo "release=$v" >> "$GITHUB_OUTPUT" @@ -170,9 +191,11 @@ jobs: # notes have to be written: the GitHub release and TestFlight show them. - name: Check the version and its release notes id: notes + env: + VERSION: ${{ steps.version.outputs.value }} run: | - scripts/check-version.sh "${{ steps.version.outputs.value }}" - echo "path=$(scripts/check-release-notes.sh "${{ steps.version.outputs.value }}")" >> "$GITHUB_OUTPUT" + scripts/check-version.sh "$VERSION" + echo "path=$(scripts/check-release-notes.sh "$VERSION")" >> "$GITHUB_OUTPUT" - name: Install fastlane and XcodeGen run: | @@ -233,7 +256,9 @@ jobs: - name: Post the release notes env: DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }} + TYPED_VERSION: ${{ inputs.version }} run: | if [ -z "$DISCORD_WEBHOOK_URL" ]; then echo "No DISCORD_WEBHOOK_URL secret: not announcing."; exit 0; fi - if [ -n "${{ inputs.version }}" ]; then v="${{ inputs.version }}"; else v="${GITHUB_REF_NAME#v}"; fi + if [ -n "$TYPED_VERSION" ]; then v="$TYPED_VERSION"; else v="${GITHUB_REF_NAME#v}"; fi + printf '%s' "$v" | grep -Eqx '[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?' || { echo "Not a version: $v" >&2; exit 1; } scripts/announce-discord.sh "$v" diff --git a/PRIVACY.md b/PRIVACY.md index e0b1e03a..0c60e391 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -85,8 +85,9 @@ the source yourself sends nothing at all. relay the developer runs on Cloudflare, which holds the key Apple asks for. What the notification says (the session's name, its folder, what the agent said or asks) is encrypted on your Mac with a key your iPhone made for that Mac alone, and only your iPhone can open it: the relay and Apple - see the iPhone's push token, when a notification is sent, its size, and the address your Mac - connects from. The relay keeps none of it. "Also While the App Is Closed" in the iPhone's + see the iPhone's push token, when a notification is sent, its size, the address your Mac + connects from, and the notification's name, made of a random id your iPhone gave this Mac and + the notification's number on it. The relay keeps none of it. "Also While the App Is Closed" in the iPhone's Settings turns it off, and "Tell me when an agent is done or needs me" turns off all notifications; revoking the iPhone on the Mac forgets its token and key. When a notification was handled or read on another device, the Mac asks the relay to take it back from the iPhone: that request @@ -94,8 +95,9 @@ the source yourself sends nothing at all. - **The Live Activity through Apple (iPhone, released app).** While agents work, and for 15 minutes after the last one stops, the Mac keeps the iPhone's Live Activity up to date through the same relay and Apple. Unlike a notification it cannot be encrypted for the iPhone, because iOS draws it from what the push carries: how many - agents work, wait, are done or stopped, and the names of the sessions that wait or are done, - with whether the change needs you, so that Apple shows it at once. It + agents work, wait, are done or stopped, the names of the sessions that wait or are done, and + your Mac's name as macOS gives it (often "'s MacBook"), with whether the change + needs you, so that Apple shows it at once. It never carries what an agent said. The relay keeps none of it. "Live Activity of the Mac's agents" in the iPhone's Settings turns it off. - **To the services of the coding agents you use.** To show what your account has left (the figures diff --git a/README.md b/README.md index eaec86fe..82d7a266 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,8 @@ use versions from the same row. | Mac app | iPhone app | Protocol | |---|---|---| -| 0.15.x | 0.15.x | 40 | +| 0.15.1 | 0.15.1 | 45 | +| 0.15.0 | 0.15.0 | 40 | | 0.14.x | 0.14.x | 39 | | 0.13.x | 0.13.x | 36 | | 0.12.x | 0.12.x | 32 | diff --git a/SECURITY.md b/SECURITY.md index 27d3225b..109ea749 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -25,7 +25,7 @@ forward its port to the internet or to a network you do not control.** | Pairing an iPhone | The Mac shows a code that works once, for five minutes, and only while the pairing screen is open. The phone trades it for a token of its own. | | Taking a device off | Each paired device has its own token, which the Mac can revoke under **Pair iPhone**. | | The Mac's own token | It is kept in a file only you can read (mode 0600) and is accepted only on connections that arrive on the loopback interface, so it is no use from another machine. | -| Your data | What your terminals show, your prompts, files and folders never leave your devices. The released apps can send crash reports (if you agree) and counts of which features are used (can be switched off) through Firebase; a build from source sends nothing. AgentTerm has no server of its own and no account. See [PRIVACY.md](PRIVACY.md). | +| Your data | What your terminals show, your prompts, files and folders never leave your devices. The released apps can send crash reports (if you agree) and counts of which features are used (can be switched off) through Firebase; a build from source sends nothing. AgentTerm has no account; its one server is the small relay the released apps send notifications through to Apple, which sees no content and keeps nothing. See [PRIVACY.md](PRIVACY.md). | | Files you preview | A Markdown preview runs nothing from the file: HTML in it is turned into Markdown, and scripts and styles are not interpreted. | ## What it does not protect against diff --git a/Sources/AgentTermClient/AgentTermConnection.swift b/Sources/AgentTermClient/AgentTermConnection.swift index 0166adce..4364e623 100644 --- a/Sources/AgentTermClient/AgentTermConnection.swift +++ b/Sources/AgentTermClient/AgentTermConnection.swift @@ -36,6 +36,8 @@ public final class AgentTermConnection: @unchecked Sendable { private let queue = DispatchQueue(label: "agentterm.client") /// Touched on the main queue only. private var closed = false + /// It was said on this connection that a message could not be read. + private var saidUnreadable = false /// Joins a large message sent in pieces (`MessageParts`). private var joiner = MessageParts.Joiner() @@ -45,6 +47,8 @@ public final class AgentTermConnection: @unchecked Sendable { /// these wait, and follow the greeting in the order they were sent. private var waiting: [(data: Data, opcode: NWProtocolWebSocket.Opcode)]? = [] private let waitingLock = NSLock() + /// Numbers the large messages sent in pieces; under `waitingLock`. + private var nextMessage: UInt32 = 0 /// The protocol the host said it is at, in its welcome; nil until then. /// Under `waitingLock`. private var hostProtocol: Int? @@ -148,7 +152,19 @@ public final class AgentTermConnection: @unchecked Sendable { let host = hostProtocol waitingLock.unlock() if let host, !message.isKnown(toHostAt: host) { return } - send(MessageCoding.encode(message), opcode: .text) + let data = MessageCoding.encode(message) + // Larger than a frame may be: in pieces, one after the other, as + // the host sends its own (#289); a frame over the host's 4 MB + // closed the connection without a word. + waitingLock.lock() + let id = nextMessage + nextMessage &+= 1 + waitingLock.unlock() + if let frames = MessageParts.frames(for: data, id: id) { + for frame in frames { send(frame.encoded(), opcode: .binary) } + return + } + send(data, opcode: .text) } public func sendInput(_ data: Data, to session: SessionID) { @@ -220,6 +236,15 @@ public final class AgentTermConnection: @unchecked Sendable { } /// Anything from the host is a sign of life, also a part of a message. + /// A message from the host that could not be read is said, once a + /// connection, as an error both apps show in their banner (#292): + /// before, it was dropped and nothing said so. + private func couldNotRead() { + guard !saidUnreadable else { return } + saidUnreadable = true + deliver { if !self.closed { self.onMessage?(.error(HostErrorWords.unreadableMessage)) } } + } + private func heard() { lastHeard = .now() pingSentAt = nil @@ -259,14 +284,20 @@ public final class AgentTermConnection: @unchecked Sendable { if let data, let message = MessageCoding.decode(ServerMessage.self, from: data) { self.noteProtocol(of: message) self.deliver { if !self.closed { self.onMessage?(message) } } + } else { + self.couldNotRead() } case .binary: guard let data, let frame = DataFrame(decoding: data) else { break } if frame.kind == .output { self.deliver { if !self.closed { self.onOutput?(frame.session, frame.payload) } } - } else if let whole = self.joiner.add(frame), let message = MessageCoding.decode(ServerMessage.self, from: whole) { + } else if let whole = self.joiner.add(frame) { // A large message, sent in pieces. - self.deliver { if !self.closed { self.onMessage?(message) } } + if let message = MessageCoding.decode(ServerMessage.self, from: whole) { + self.deliver { if !self.closed { self.onMessage?(message) } } + } else { + self.couldNotRead() + } } case .close: self.finish(reason: nil) diff --git a/Sources/AgentTermClient/PairingStore.swift b/Sources/AgentTermClient/PairingStore.swift new file mode 100644 index 00000000..ae33035d --- /dev/null +++ b/Sources/AgentTermClient/PairingStore.swift @@ -0,0 +1,142 @@ +import Foundation +import Security + +/// A Mac this iPhone is paired with, and the token it connects to it with. +public struct SavedHost: Codable, Equatable, Identifiable, Sendable { + public var id: String + public var host: String + public var port: UInt16 + public var name: String + /// This device's own token for that Mac, given when pairing. The Mac can + /// revoke it without affecting other devices. + public var token: String + + public init(id: String, host: String, port: UInt16, name: String, token: String) { + self.id = id + self.host = host + self.port = port + self.name = name + self.token = token + } +} + +/// The Keychain's items of this app, by account: what `PairingStore` asks +/// of it, so that a test can stand a Keychain of its own in (#287). +public protocol KeychainItems: Sendable { + func read(account: String) -> (status: OSStatus, data: Data?) + func update(account: String, data: Data) -> OSStatus + func add(account: String, data: Data) -> OSStatus + func delete(account: String) -> OSStatus +} + +/// The system's Keychain, a generic password per account, kept on this +/// device only and readable after its first unlock. +public struct SystemKeychain: KeychainItems { + public init() {} + + private func query(account: String) -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: "com.manhpham.agentterm", + kSecAttrAccount as String: account, + ] + } + + public func read(account: String) -> (status: OSStatus, data: Data?) { + var request = query(account: account) + request[kSecReturnData as String] = true + request[kSecMatchLimit as String] = kSecMatchLimitOne + var result: CFTypeRef? + let status = SecItemCopyMatching(request as CFDictionary, &result) + return (status, status == errSecSuccess ? result as? Data : nil) + } + + private func changes(_ data: Data) -> [String: Any] { + [kSecValueData as String: data, kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly] + } + + public func update(account: String, data: Data) -> OSStatus { + SecItemUpdate(query(account: account) as CFDictionary, changes(data) as CFDictionary) + } + + public func add(account: String, data: Data) -> OSStatus { + var item = query(account: account) + item.merge(changes(data)) { $1 } + return SecItemAdd(item as CFDictionary, nil) + } + + public func delete(account: String) -> OSStatus { + SecItemDelete(query(account: account) as CFDictionary) + } +} + +/// Keeps the paired Macs in the Keychain, since the tokens grant shell access. +public final class PairingStore: @unchecked Sendable { + public static let shared = PairingStore() + + private let keychain: KeychainItems + private let lock = NSLock() + private var couldNotRead = false + + public init(keychain: KeychainItems = SystemKeychain()) { + self.keychain = keychain + } + + /// The Keychain could not be read when the list was loaded (a launch + /// before the first unlock, say): the paired Macs are not known, and + /// nothing is written over them (#287). + public var unreadable: Bool { + lock.lock() + defer { lock.unlock() } + return couldNotRead + } + + private func read(account: String) -> Data? { + let (status, data) = keychain.read(account: account) + if status != errSecSuccess, status != errSecItemNotFound { + lock.lock() + couldNotRead = true + lock.unlock() + } + return data + } + + public func load() -> [SavedHost] { + lock.lock() + couldNotRead = false + lock.unlock() + if let data = read(account: "hosts"), let hosts = try? JSONDecoder().decode([SavedHost].self, from: data) { + return hosts + } + if unreadable { return [] } + // Builds that paired with a single Mac kept it under another name. + struct Single: Codable { + var host: String + var port: UInt16 + var name: String + var token: String + } + guard let data = read(account: "host"), let old = try? JSONDecoder().decode(Single.self, from: data) else { return [] } + let migrated = [SavedHost(id: UUID().uuidString, host: old.host, port: old.port, name: old.name, token: old.token)] + save(migrated) + _ = keychain.delete(account: "host") + return migrated + } + + @discardableResult + public func save(_ hosts: [SavedHost]) -> Bool { + // Never over what could not be read: it may hold every paired Mac. + guard !unreadable else { return false } + guard !hosts.isEmpty else { + let status = keychain.delete(account: "hosts") + return status == errSecSuccess || status == errSecItemNotFound + } + guard let data = try? JSONEncoder().encode(hosts) else { return false } + // Changed in place: the list is never deleted before the new one is + // there, so a failure keeps the old one (#287). + let updated = keychain.update(account: "hosts", data: data) + if updated == errSecSuccess { return true } + guard updated == errSecItemNotFound else { return false } + return keychain.add(account: "hosts", data: data) == errSecSuccess + } +} diff --git a/Sources/AgentTermHost/AccountUsageFetcher.swift b/Sources/AgentTermHost/AccountUsageFetcher.swift index 9743738d..76051d65 100644 --- a/Sources/AgentTermHost/AccountUsageFetcher.swift +++ b/Sources/AgentTermHost/AccountUsageFetcher.swift @@ -113,7 +113,7 @@ public enum AccountUsageFetcher { private static func claude(_ environment: Environment) -> AccountUsage { // The keychain on a Mac; the file where Claude Code has no keychain. - let directory = environment.variables["CLAUDE_CONFIG_DIR"].flatMap { $0.isEmpty ? nil : $0 } ?? environment.home + "/.claude" + let directory = AgentFolders.of(home: environment.home, own: environment.variables).claude let stored = environment.keychain("Claude Code-credentials", nil).map { Data($0.utf8) } ?? environment.file(directory + "/.credentials.json") guard let login = object(stored)?["claudeAiOauth"] as? [String: Any], let token = login["accessToken"] as? String, !token.isEmpty else { return failed("claude", "Claude Code is not signed in with a claude.ai account on this Mac.", environment, showsRemaining: false) @@ -211,7 +211,7 @@ public enum AccountUsageFetcher { // MARK: Codex private static func codex(_ environment: Environment) -> AccountUsage { - let directory = environment.variables["CODEX_HOME"].flatMap { $0.isEmpty ? nil : $0 } ?? environment.home + "/.codex" + let directory = AgentFolders.of(home: environment.home, own: environment.variables).codex guard let tokens = object(environment.file(directory + "/auth.json"))?["tokens"] as? [String: Any], let token = tokens["access_token"] as? String, !token.isEmpty else { return failed("codex", "Codex is not signed in with a ChatGPT account on this Mac.", environment) } diff --git a/Sources/AgentTermHost/AgentBrowserTools.swift b/Sources/AgentTermHost/AgentBrowserTools.swift index a2d2100c..0212fee2 100644 --- a/Sources/AgentTermHost/AgentBrowserTools.swift +++ b/Sources/AgentTermHost/AgentBrowserTools.swift @@ -104,6 +104,14 @@ extension AgentShellsMCP { private static func number(_ description: String) -> [String: Any] { ["type": "number", "description": description] } private static func boolean(_ description: String) -> [String: Any] { ["type": "boolean", "description": description] } + /// What each number a browser tool takes may be. + static let numberRanges: [String: ClosedRange] = [ + "x": -100_000...100_000, "y": -100_000...100_000, "seconds": 0...600, + "width": 1...10_000, "height": 1...10_000, "latitude": -90...90, "longitude": -180...180, + ] + + private static func words(_ number: Double) -> String { number == number.rounded() ? String(Int(number)) : String(number) } + /// The request a browser tool's call makes, or why it cannot be made. static func browserRequest(_ name: String, _ arguments: [String: Any]) -> Result { func text(_ key: String) -> String? { (arguments[key] as? String).flatMap { $0.isEmpty ? nil : $0 } } @@ -113,6 +121,13 @@ extension AgentShellsMCP { let tab = text("tab") ?? (arguments["tab"] as? NSNumber).map { $0.stringValue } func needs(_ key: String) -> BrowserToolError { BrowserToolError(text: "Give \(key == "tab" ? "the tab's id" : "`\(key)`") as `\(key)`.") } if !["browser_open", "browser_tabs", "browser_profiles"].contains(name), tab == nil { return .failure(needs("tab")) } + // A number out of what the browser takes, or no number ("inf", + // "nan", which JSON cannot carry), is refused at once (#249). + for (key, range) in Self.numberRanges where arguments[key] != nil { + guard let number = value(key), number.isFinite, range.contains(number) else { + return .failure(BrowserToolError(text: "`\(key)` is a number from \(Self.words(range.lowerBound)) to \(Self.words(range.upperBound)).")) + } + } let id = tab ?? "" func withRef(_ make: (String) -> BrowserRequest) -> Result { guard let ref = text("ref") else { return .failure(needs("ref")) } diff --git a/Sources/AgentTermHost/AgentFolders.swift b/Sources/AgentTermHost/AgentFolders.swift new file mode 100644 index 00000000..940b0439 --- /dev/null +++ b/Sources/AgentTermHost/AgentFolders.swift @@ -0,0 +1,50 @@ +#if os(macOS) +import Foundation + +/// Where each agent keeps its configuration and its conversations, in one +/// place for setup, schedules, history and delete alike (#264). +/// +/// Claude Code moves all of it with `CLAUDE_CONFIG_DIR`, `.claude.json` +/// too, and Codex with `CODEX_HOME`: tried with Claude Code 2.1.330 and +/// Codex 0.171.0 on 2026-11-23, in a home of the trial's own, where +/// `.claude.json`, `projects/` and `sessions/` were written into the folder +/// the variable named and nothing into the home. +public struct AgentFolders: Equatable, Sendable { + /// Claude Code's: `settings.json`, `projects/`, `.credentials.json`. + public let claude: String + /// Claude Code's `.claude.json`: what folders are trusted. + public let claudeState: String + /// Codex's: `config.toml`, `sessions/`, `history.jsonl`. + public let codex: String + /// Copilot CLI's: `config.json`, `session-state/`. + public let copilot: String + + /// The variables that move them, asked of the login shell too. + static let variables = ["CLAUDE_CONFIG_DIR", "CODEX_HOME"] + + public init(home: String, environment: [String: String]) { + func given(_ name: String) -> String? { + environment[name].flatMap { $0.isEmpty ? nil : ($0 as NSString).expandingTildeInPath } + } + let claudeFolder = given("CLAUDE_CONFIG_DIR") + claude = claudeFolder ?? home + "/.claude" + claudeState = claudeFolder.map { $0 + "/.claude.json" } ?? home + "/.claude.json" + codex = given("CODEX_HOME") ?? home + "/.codex" + copilot = home + "/.copilot" + } + + /// The user's: what the host's own environment says, and where it says + /// nothing, what their login shell does. A host started by the app or + /// at login has none of what `.zshrc` exports, while the agents, started + /// through that shell, have it. + public static func of(home: String, own: [String: String] = ProcessInfo.processInfo.environment) -> AgentFolders { + of(home: home, own: own, shell: .shared) + } + + static func of(home: String, own: [String: String], shell: LoginShellPath) -> AgentFolders { + var environment = shell.variables() + for name in variables { if let value = own[name], !value.isEmpty { environment[name] = value } } + return AgentFolders(home: home, environment: environment) + } +} +#endif diff --git a/Sources/AgentTermHost/AgentHistory.swift b/Sources/AgentTermHost/AgentHistory.swift index d5ff0b98..782f802c 100644 --- a/Sources/AgentTermHost/AgentHistory.swift +++ b/Sources/AgentTermHost/AgentHistory.swift @@ -23,12 +23,14 @@ public enum AgentHistory { in directory: String, includeSubfolders: Bool = false, home: String = NSHomeDirectory(), + folders: AgentFolders? = nil, limit: Int = 200 ) -> [Conversation] { let directory = URL(fileURLWithPath: directory).standardizedFileURL.path + let folders = folders ?? AgentFolders.of(home: home) let home = URL(fileURLWithPath: home, isDirectory: true) let scope = Scope(directory: directory, includeSubfolders: includeSubfolders) - let all = claude(scope, home) + codex(scope, home) + antigravity(scope, home) + copilot(scope, home) + let all = claude(scope, folders) + codex(scope, folders) + antigravity(scope, home) + copilot(scope, home) return Array( all.filter { isSafeIdentifier($0.sessionID) && !$0.title.isEmpty } .sorted { $0.updatedAt > $1.updatedAt } @@ -38,10 +40,11 @@ public enum AgentHistory { /// Every conversation the agents have on this machine, newest first, /// whatever folder it ran in. - public static func allConversations(home: String = NSHomeDirectory(), limit: Int = 300) -> [Conversation] { + public static func allConversations(home: String = NSHomeDirectory(), folders: AgentFolders? = nil, limit: Int = 300) -> [Conversation] { + let folders = folders ?? AgentFolders.of(home: home) let home = URL(fileURLWithPath: home, isDirectory: true) let scope = Scope(directory: nil, includeSubfolders: true) - let all = claude(scope, home) + codex(scope, home) + antigravity(scope, home) + copilot(scope, home) + let all = claude(scope, folders) + codex(scope, folders) + antigravity(scope, home) + copilot(scope, home) // What an agent was asked on the host's own behalf, a commit // message for one, is not a conversation of the user's. let own = HostEnvironment.commitWriterDirectory.standardizedFileURL.path @@ -77,8 +80,8 @@ public enum AgentHistory { // MARK: Claude Code /// `~/.claude/projects//.jsonl` - private static func claude(_ scope: Scope, _ home: URL) -> [Conversation] { - let projects = home.appendingPathComponent(".claude/projects") + private static func claude(_ scope: Scope, _ folders: AgentFolders) -> [Conversation] { + let projects = URL(fileURLWithPath: folders.claude, isDirectory: true).appendingPathComponent("projects") let own = scope.directory.map(claudeProjectName) // Subfolders of the directory have their own project folder. The name // alone cannot tell "apps/web" from a sibling "apps-web", and cannot @@ -147,8 +150,9 @@ public enum AgentHistory { /// `~/.codex/sessions////rollout-